diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d09ded006d75bbd0c6d5cd7eac384071fbe84f6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Base44 CLI" + short_description: "Initialize, configure, deploy, and manage Base44 projects" + default_prompt: "Use Base44 CLI guidance to initialize, configure, authenticate, and deploy this Base44 app." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/agents-push.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/agents-push.md new file mode 100644 index 0000000000000000000000000000000000000000..fa2795b4b6aed0b9a5f3d56fd8eabb09bfe072df --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/agents-push.md @@ -0,0 +1,156 @@ +# base44 agents push + +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. + +## Syntax + +```bash +npx base44 agents push +``` + +## Authentication + +**Required**: Yes. If not authenticated, you'll be prompted to login first. + +## What It Does + +1. Reads all agent files from the `base44/agents/` directory +2. Validates agent configurations +3. Displays the count of agents to be pushed +4. Uploads agents to the Base44 backend +5. Reports the results: created, updated, and deleted agents + +## Prerequisites + +- Must be run from a Base44 project directory +- Project must have agent definitions in the `base44/agents/` folder + +## Output + +```bash +$ npx base44 agents push + +Found 2 agents to push +Pushing agents to Base44... + +Created: support_agent +Updated: order_bot +Deleted: old_agent + +✓ Agents pushed to Base44 +``` + +## Agent Synchronization + +The push operation synchronizes your local agents with Base44: + +- **Created**: New agents that didn't exist in Base44 +- **Updated**: Existing agents with modified configuration +- **Deleted**: Agents that were removed from your local configuration + +**Warning**: This is a full sync operation. Agents removed locally will be deleted from Base44. + +## Error Handling + +If no agents are found in your project: +```bash +$ npx base44 agents push +No local agents found - this will delete all remote agents +``` + +If an agent has an invalid name: +```bash +$ npx base44 agents push +Error: Agent name must be lowercase alphanumeric with underscores +``` + +## Agent Configuration Schema + +Each agent file should be a `.jsonc` file in `base44/agents/` with this structure: + +```jsonc +{ + "name": "agent_name", // Required: lowercase alphanumeric with underscores, 1-100 chars + "description": "Brief description of what this agent does", // Required: min 1 char + "instructions": "Detailed instructions for the agent's behavior", // Required: min 1 char + "tool_configs": [ // Optional: defaults to [] + // Entity tool - gives agent access to entity operations + { "entity_name": "Task", "allowed_operations": ["read", "create", "update", "delete"] }, + // Backend function tool - gives agent access to a function + { "function_name": "send_email", "description": "Send an email notification" } + ], + "whatsapp_greeting": "Hello! How can I help you today?" // Optional +} +``` + +**Naming rules:** +- **Agent names** must match pattern: `/^[a-z0-9_]+$/` (lowercase alphanumeric with underscores only, 1-100 characters) + - Valid: `support_agent`, `order_bot`, `task_helper` + - Invalid: `Support-Agent`, `OrderBot`, `task helper` +- **Agent file names** must use underscores (matching the agent name) + - Valid: `support_agent.jsonc`, `order_bot.jsonc` + - Invalid: `support-agent.jsonc` (hyphens not allowed) +- **Entity names in `tool_configs`** must use PascalCase (matching the entity's `name` field) + - Valid: `"entity_name": "Task"`, `"entity_name": "TeamMember"` + - Invalid: `"entity_name": "task"`, `"entity_name": "team_member"` + +**Required fields:** +- `name`: Required, must follow naming rules above +- `description`: Required, minimum 1 character +- `instructions`: Required, minimum 1 character +- `tool_configs`: Optional, defaults to empty array +- `whatsapp_greeting`: Optional + +### Common Mistake: Wrong tool_configs Format + +**WRONG** - Do NOT use `tools` with `type` and `entity`: +```jsonc +{ + "name": "my_agent", + "tools": [ // ❌ WRONG + { "type": "entity_query", "entity": "Task" } + ] +} +``` + +**CORRECT** - Use `tool_configs` with `entity_name` and `allowed_operations`: +```jsonc +{ + "name": "my_agent", + "tool_configs": [ // ✅ CORRECT + { "entity_name": "Task", "allowed_operations": ["read"] } + ] +} +``` + +### Best Practices for Agent Instructions + +When giving agents access to entities, be explicit in the instructions about using the tools: + +```jsonc +{ + "name": "support_agent", + "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.", + "tool_configs": [ + { "entity_name": "Order", "allowed_operations": ["read"] }, + { "entity_name": "Customer", "allowed_operations": ["read"] } + ] +} +``` + +Without explicit instructions to use the entity tools, the agent may not proactively query user data when asked. + +## Use Cases + +- After defining new agents in your project +- When modifying existing agent configurations +- To sync agent changes before testing +- As part of your development workflow when agent behavior changes + +## Notes + +- This command syncs the agent configuration, not conversation data +- Changes are applied to your Base44 project immediately +- Make sure to test agent changes in a development environment first +- Agent definitions are located in the `base44/agents/` directory +- Use `base44 agents pull` to download agents from Base44 diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/auth-login.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/auth-login.md new file mode 100644 index 0000000000000000000000000000000000000000..adebd275c98ddba776e4004c6eb89ce953c1ade0 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/auth-login.md @@ -0,0 +1,54 @@ +# base44 login + +Authenticate with Base44 using device code flow. + +## Syntax + +```bash +npx base44 login +``` + +## Authentication + +**Required**: No (this is the login command itself) + +## How It Works + +The login command uses OAuth 2.0 device code flow for authentication: + +1. Generates a device code for authentication +2. Displays a verification code and verification URI +3. Directs you to visit the URI and enter the code +4. Polls for authentication completion (up to device code expiration) +5. Retrieves access and refresh tokens upon successful authentication +6. Fetches and displays your user information +7. Saves authentication data locally with expiration timestamp + +## Interactive Flow + +```bash +$ npx base44 login + +Please visit: https://auth.base44.com/device +Enter code: ABCD-EFGH + +Waiting for authentication... +✓ Successfully authenticated! + +Logged in as: user@example.com +``` + +## Session Management + +- Authentication tokens are stored locally on your device +- Tokens include expiration timestamps +- The session persists across CLI sessions +- Other commands will automatically use your stored credentials +- Use `npx base44 logout` to clear your session +- Use `npx base44 whoami` to check your current authentication status + +## Notes + +- You only need to login once per device +- If your session expires, you'll be prompted to login again when running authenticated commands +- The CLI automatically prompts for login when you run commands that require authentication diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-create.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-create.md new file mode 100644 index 0000000000000000000000000000000000000000..64a55a2db51173731efc4b9670f0b97fd98183bd --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-create.md @@ -0,0 +1,126 @@ +# Creating Connectors + +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. + +## Key Concepts + +- **Direct API Access**: Connectors provide raw OAuth access tokens - you call the external APIs directly from backend functions +- **App Builder's Account**: Connects your account (the app builder), not your end users' accounts +- **Backend Functions Only**: Tokens are only accessible server-side for security + +## File Location + +Create connector files in the `base44/connectors/` directory (or the directory specified by `connectorsDir` in your config.jsonc). + +**File naming:** `{type}.jsonc` or `{type}.json` + +Examples: +- `base44/connectors/googlecalendar.jsonc` +- `base44/connectors/slack.jsonc` +- `base44/connectors/notion.json` + +## Schema + +Each connector file must specify a `type` and optionally a list of `scopes`: + +```jsonc +{ + "type": "googlecalendar", + "scopes": [ + "https://www.googleapis.com/auth/calendar.readonly", + "https://www.googleapis.com/auth/calendar.events" + ] +} +``` + +### Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `type` | string | Yes | The integration type (run `npx base44 connectors list-available` to see options) | +| `scopes` | string[] | No | OAuth scopes to request (defaults to `[]`) | + +## Discovering Available Connector Types + +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). + +```bash +npx base44 connectors list-available +``` + +This returns a JSON object with all available integrations, their display names, descriptions, and any required connection config fields. Example output (trimmed): + +```json +{ + "integrations": [ + { + "integration_type": "googlecalendar", + "display_name": "Google Calendar", + "description": "Access and manage Google Calendar events", + "connection_config_fields": [] + }, + { + "integration_type": "slack", + "display_name": "Slack User", + "description": "Send messages and interact with Slack as yourself (user integration)", + "connection_config_fields": [] + }, + { + "integration_type": "share_point", + "display_name": "SharePoint", + "description": "Manage documents, lists, sites, and collaboration content in SharePoint", + "connection_config_fields": [ + { + "name": "subdomain", + "display_name": "SharePoint Site", + "description": "The name of your SharePoint site (e.g., sites/mysite)", + "placeholder": "sites/mysite", + "required": true, + "validation_pattern": "^[a-zA-Z0-9/_-]+$", + "validation_error": "Please enter a valid SharePoint site path" + } + ] + } + ] +} +``` + +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. + +### Stripe (Sandbox) + +```jsonc +// base44/connectors/stripe.jsonc +{ + "type": "stripe", + "scopes": [] +} +``` + +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. + +## Rules and Constraints + +1. **One connector per type**: You cannot have multiple connectors of the same type (e.g., two `googlecalendar` connectors) + +2. **Type must be valid**: The `type` field must be a valid integration type (run `npx base44 connectors list-available` to see available types) + +3. **Scopes are provider-specific**: Each service has its own scope format - refer to the provider's documentation + +## Next Steps + +After creating connector files, push them to Base44: + +```bash +npx base44 connectors push +``` + +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. + +To pull existing connectors from Base44 to local files: + +```bash +npx base44 connectors pull +``` + +See [connectors-pull.md](connectors-pull.md) for details. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-list-available.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-list-available.md new file mode 100644 index 0000000000000000000000000000000000000000..9e89acaa21eede39e7e49a256584a62322a428be --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-list-available.md @@ -0,0 +1,56 @@ +# base44 connectors list-available + +List all integration types available in the Base44 connector catalog. + +## Syntax + +```bash +npx base44 connectors list-available +``` + +## Authentication + +**Required**: Yes. If not authenticated, you'll be prompted to login first. + +## What It Does + +Fetches the catalog of available integration types from Base44 and displays each one with its display name, description, and any required configuration fields. + +## Output + +```bash +$ npx base44 connectors list-available + +✓ Available integrations fetched successfully + +Google Calendar + integrationType: googlecalendar + description: Access Google Calendar events and schedules + connectionConfigFields: [] + +Slack + integrationType: slack + description: Send messages and interact with Slack workspaces + connectionConfigFields: [] + +Stripe + integrationType: stripe + description: Process payments and manage Stripe accounts + connectionConfigFields: [] + +Found 14 available integrations. +``` + +Each integration is displayed in YAML format showing the integration type, description, and any connection configuration fields required for setup. + +## Use Cases + +- Discover all supported connector types before creating connector files +- Check if a specific integration is available in your Base44 plan +- See what configuration fields (if any) a connector requires + +## Related Commands + +- [connectors-create.md](connectors-create.md) - How to create connector configuration files +- [connectors-push.md](connectors-push.md) - Push local connectors to Base44 +- [connectors-pull.md](connectors-pull.md) - Pull connectors from Base44 to local files diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-push.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-push.md new file mode 100644 index 0000000000000000000000000000000000000000..b509512ff6401204ae6460d33da5fb99e403bfd2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-push.md @@ -0,0 +1,137 @@ +# base44 connectors push + +Push local connector configurations to Base44, synchronizing scopes and handling OAuth authorization. + +## Usage + +```bash +npx base44 connectors push +``` + +## What It Does + +1. **Reads local connectors** from your `base44/connectors/` directory +2. **Syncs with Base44** - updates scopes for existing connectors +3. **Adds new connectors** - new OAuth connector types trigger authorization; Stripe is provisioned automatically +4. **Removes unlisted connectors** - connectors not in your local files are removed from Base44 + +## OAuth Authorization Flow + +When you add a new connector, it needs to be authorized: + +1. The CLI detects which connectors need authorization +2. You're prompted: "Open browser to authorize now?" +3. If you accept, the browser opens to the OAuth provider (Google, Slack, etc.) +4. You log into your account and approve the requested permissions +5. The browser closes and the CLI confirms authorization + +**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. + +## Example Output + +### Pushing connectors (no new authorization needed) + +``` +Found 2 connectors to push: googlecalendar, slack +✓ Connectors pushed + +Summary: + Synced: googlecalendar, slack +``` + +### Pushing new connectors (authorization required) + +``` +Found 3 connectors to push: googlecalendar, slack, notion +✓ Connectors pushed + +2 connector(s) require authorization in your browser: + slack: https://auth.base44.io/oauth/... + notion: https://auth.base44.io/oauth/... + +? Open browser to authorize now? › Yes + +Opening browser for slack... +✓ slack authorization complete + +Opening browser for notion... +✓ notion authorization complete + +Summary: + Synced: googlecalendar + Added: slack, notion +``` + +### Pushing Stripe (no OAuth required) + +Stripe is provisioned automatically — no browser flow is needed: + +``` +Found 2 connectors to push: googlecalendar, stripe +✓ Connectors pushed + +Summary: + ✓ Stripe sandbox provisioned + Claim your Stripe sandbox: https://dashboard.stripe.com/... + Connectors dashboard: https://app.base44.com/... + Synced: googlecalendar +``` + +### Removing connectors + +If you delete a connector file locally and push, it will be removed: + +``` +Found 1 connectors to push: googlecalendar +✓ Connectors pushed + +Summary: + Synced: googlecalendar + Removed: slack +``` + +## CI/CD Environments + +In non-interactive environments (no TTY, such as CI/CD pipelines), the OAuth flow is skipped automatically: + +``` +Skipped OAuth in non-interactive mode. Run 'base44 connectors push' locally or open the links above to authorize. +``` + +You must run `npx base44 connectors push` locally to complete authorization for new connectors. + +## Skipping Authorization + +If you choose not to authorize immediately, the connectors remain in a pending state: + +``` +? Open browser to authorize now? › No + +Authorization skipped. Pending: slack, notion. Run 'base44 connectors push' again to complete. +``` + +Run the command again when you're ready to authorize. + +## Summary Status Meanings + +| Status | Meaning | +|--------|---------| +| Provisioned | Stripe sandbox was created automatically (no OAuth needed) | +| Synced | Connector already existed, scopes updated if needed | +| Added | New connector successfully authorized via OAuth | +| Removed | Connector was deleted from Base44 (not in local files) | +| Failed | Authorization timed out, failed, or was skipped | + +## Troubleshooting + +| Problem | Solution | +|---------|----------| +| Authorization timed out | Re-run `npx base44 connectors push` and complete OAuth faster | +| Authorization failed | Check that you approved all requested permissions | +| Wrong account connected | Remove the connector file, push to delete it, then add it back and authorize with the correct account | +| Browser didn't open | Copy the URL shown in the terminal and open it manually | + +## Related Commands + +- [connectors-create.md](connectors-create.md) - How to create connector configuration files +- [connectors-pull.md](connectors-pull.md) - Pull connectors from Base44 to local files diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/exec.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/exec.md new file mode 100644 index 0000000000000000000000000000000000000000..68b477f0a031c4dc1358fc665b3ed2f9f80894b1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/exec.md @@ -0,0 +1,47 @@ +# base44 exec + +Run a script with the Base44 SDK pre-authenticated as the current user. Reads the script from stdin. + +## Syntax + +```bash +cat ./script.ts | npx base44 exec +echo "" | npx base44 exec +``` + +## How It Works + +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. + +## Available Globals + +> **`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. + +Use it to interact with your app's resources: + +- `base44.entities.` — CRUD operations on entities (`.list()`, `.get(id)`, `.create(data)`, `.update(id, data)`, `.delete(id)`) +- `base44.functions.invoke(name, data?)` — call a backend function +- `base44.agents.` — invoke AI agents +- For more available resources and methods, see the [Base44 SDK reference](../../base44-sdk/SKILL.md) + +## Examples + +```bash +# Run a script file +cat ./script.ts | npx base44 exec + +# Inline script +echo "const users = await base44.entities.User.list(); console.log(users)" | npx base44 exec +``` + +## Requirements + +- Must be authenticated (`npx base44 login`) +- Must be run from a linked Base44 project directory +- Script must be piped via stdin (non-interactive mode) + +## Notes + +- The script runs with the Base44 SDK pre-authenticated — you can use `base44.entities`, `base44.functions`, etc. directly +- Exit code from the script is forwarded as the CLI process exit code +- This command requires stdin to be piped (it does not accept input in interactive TTY mode) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/functions-pull.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/functions-pull.md new file mode 100644 index 0000000000000000000000000000000000000000..88ad7379bd78fb5a8338aaf3269ee9e448a80104 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/functions-pull.md @@ -0,0 +1,80 @@ +# base44 functions pull + +Pull deployed functions from Base44 to local files. + +## Syntax + +```bash +npx base44 functions pull [name] +``` + +## Arguments + +| Argument | Description | Required | +|----------|-------------|----------| +| `[name]` | Function name to pull (pulls all if omitted) | No | + +## Authentication + +**Required**: Yes. If not authenticated, you'll be prompted to login first. + +## What It Does + +1. Fetches deployed functions from Base44 +2. Filters to the specified function if `[name]` is provided +3. Writes function files to the local `functions/` directory (configured in `base44/config.jsonc`) +4. Reports each file as `written` (new/updated) or `unchanged` + +## Examples + +```bash +# Pull all deployed functions +npx base44 functions pull + +# Pull a specific function +npx base44 functions pull process-order +``` + +## Output + +```bash +$ npx base44 functions pull +✓ Functions fetched successfully +✓ Function files written successfully +✓ process-order written +◆ send-notification unchanged + +✓ Pulled 2 functions to base44/functions +``` + +Single function: +```bash +$ npx base44 functions pull process-order +✓ Functions fetched successfully +✓ Function files written successfully +✓ process-order written + +✓ Pulled 1 function to base44/functions +``` + +## Error Handling + +If the specified function is not found on remote: +```bash +$ npx base44 functions pull nonexistent +✓ Function "nonexistent" not found on remote +``` + +If no functions exist on remote: +```bash +$ npx base44 functions pull +✓ No functions found on remote +``` + +## Notes + +- Files are written to the `functionsDir` configured in `base44/config.jsonc` (defaults to `functions/`) +- Files already matching remote content are skipped (reported as `unchanged`) +- This overwrites existing local function files with remote versions — commit local changes first +- Use `npx base44 functions deploy` to push local changes back to Base44 +- Use `npx base44 functions list` to see what functions are deployed on remote diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/secrets-list.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/secrets-list.md new file mode 100644 index 0000000000000000000000000000000000000000..f17fc1bd888f0b4314ec62ef2d4bd73c914cc2e1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/secrets-list.md @@ -0,0 +1,25 @@ +# base44 secrets list + +List the names of all secrets configured for the current project. + +## Syntax + +```bash +npx base44 secrets list +``` + +## Options + +No options. The command takes no arguments or flags. + +## Examples + +```bash +npx base44 secrets list +``` + +## Notes + +- Only secret **names** are listed (values are never displayed) +- Returns "No secrets configured." if there are none +- Requires authentication diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..898aa4541fb2a9c690bbff7c6027568f40368c43 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Base44 SDK" + short_description: "Build features with the Base44 JavaScript and TypeScript SDK" + default_prompt: "Use Base44 SDK guidance to implement this feature against entities, functions, auth, and integrations." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/QUICK_REFERENCE.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/QUICK_REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..0d2271a49e22155c80ea57af3b8edb16103b87cb --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/QUICK_REFERENCE.md @@ -0,0 +1,178 @@ +# Base44 SDK Quick Reference + +Compact method signatures for all SDK modules. **Verify against this before writing code.** + +--- + +## Auth (`base44.auth.*`) + +``` +loginViaEmailPassword(email, password, turnstileToken?) → Promise<{access_token, user}> +loginWithProvider('google' | 'microsoft' | 'facebook', fromUrl?) → void +me() → Promise +updateMe(data) → Promise +isAuthenticated() → Promise +logout(redirectUrl?) → void +redirectToLogin(nextUrl) → void # ⚠️ Avoid - prefer custom login UI +register({email, password, turnstile_token?, referral_code?}) → Promise +verifyOtp({email, otpCode}) → Promise +resendOtp(email) → Promise +inviteUser(userEmail, role) → Promise +resetPasswordRequest(email) → Promise +resetPassword({resetToken, newPassword}) → Promise +changePassword({userId, currentPassword, newPassword}) → Promise +setToken(token, saveToStorage?) → void +``` + +--- + +## Entities (`base44.entities.EntityName.*`) + +``` +create(data) → Promise +bulkCreate(dataArray) → Promise +list(sort?, limit?, skip?, fields?) → Promise[]> +filter(query, sort?, limit?, skip?, fields?) → Promise[]> +get(id) → Promise +update(id, data) → Promise +updateMany(query, mongoUpdateOp) → Promise // e.g. { $set: { field: val } } +bulkUpdate(dataArray) → Promise // each item must have id +delete(id) → Promise +deleteMany(query) → Promise +importEntities(file) → Promise> // frontend only +subscribe(callback) → () => void // returns unsubscribe fn +``` + +**Sort:** Use `SortField`: `-fieldName` for descending (e.g., `-created_date`). Max 5,000 per request for list/filter. + +--- + +## Functions (`base44.functions.*`) + +``` +invoke(functionName, data?) → Promise +fetch(path, init?) → Promise // low-level, for streaming/custom methods +``` + +**Backend:** Use `base44.asServiceRole.functions.invoke()` for admin access. + +--- + +## Integrations (`base44.integrations.Core.*`) + +``` +InvokeLLM({prompt, add_context_from_internet?, response_json_schema?, file_urls?}) → Promise +GenerateImage({prompt}) → Promise<{url}> +SendEmail({to, subject, body, from_name?}) → Promise +UploadFile({file}) → Promise<{file_url}> +UploadPrivateFile({file}) → Promise<{file_uri}> +CreateFileSignedUrl({file_uri, expires_in?}) → Promise<{signed_url}> +ExtractDataFromUploadedFile({file_url, json_schema}) → Promise +``` + +### Custom Integrations (`base44.integrations.custom.*`) + +``` +call(slug, operationId, {payload?, pathParams?, queryParams?}?) → Promise<{success, status_code, data}> +``` + +**operationId format:** `"method:/path"` (e.g., `"get:/contacts"`, `"post:/users/{id}"`) + +--- + +## Analytics (`base44.analytics.*`) + +``` +track({eventName, properties?}) → void +``` + +--- + +## App Logs (`base44.appLogs.*`) + +``` +logUserInApp(pageName) → Promise +fetchLogs(params?) → Promise +getStats(params?) → Promise +``` + +--- + +## Users (`base44.users.*`) + +``` +inviteUser(userEmail, role) → Promise // role: 'user' | 'admin' +``` + +--- + +## Service Role Connectors (`base44.asServiceRole.connectors.*`) + +**Backend only, service role required.** App-scoped (shared account). + +``` +getConnection(integrationType) → Promise<{accessToken, connectionConfig}> // recommended +getAccessToken(integrationType) → Promise // deprecated +``` + +**Types:** Run `npx base44 connectors list-available` to see all available integration types. + +--- + +## SSO (`base44.asServiceRole.sso.*`) + +**Backend only, service role required.** + +``` +getAccessToken(userId) → Promise<{access_token}> +``` + +--- + +## Service Role Access + +**Backend functions only.** Prefix any module with `asServiceRole` for admin access: + +```javascript +base44.asServiceRole.entities.Task.list() +base44.asServiceRole.functions.invoke('name', data) +base44.asServiceRole.connectors.getConnection('slack') +base44.asServiceRole.sso.getAccessToken(userId) +``` + +--- + +## Backend Function Template + +```javascript +import { createClientFromRequest } from "@base44/sdk"; + +Deno.serve(async (req) => { + const base44 = createClientFromRequest(req); + const data = await req.json(); + + // User context + const user = await base44.auth.me(); + + // Service role for admin operations + const allRecords = await base44.asServiceRole.entities.Task.list(); + + return Response.json({ success: true }); +}); +``` + +--- + +## Client Initialization (External Apps) + +```javascript +import { createClient } from "@base44/sdk"; + +const base44 = createClient({ appId: "your-app-id" }); // MUST use 'appId' +``` + +--- + +## TypeScript type registries + +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. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/analytics.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/analytics.md new file mode 100644 index 0000000000000000000000000000000000000000..d1b2c697dd2ca3f6597cd47d0f2d031e56fc830a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/analytics.md @@ -0,0 +1,113 @@ +# Analytics Module + +Track custom events and user activity via `base44.analytics`. + +## Contents +- [Methods](#methods) +- [Examples](#examples) +- [Automatic Tracking](#automatic-tracking) +- [Best Practices](#best-practices) + +## Methods + +| Method | Signature | Description | +|--------|-----------|-------------| +| `track(params)` | `void` | Track a custom event | + +## Examples + +### Track Custom Event + +```javascript +// Track a simple event +base44.analytics.track({ + eventName: "button_clicked" +}); + +// Track event with properties +base44.analytics.track({ + eventName: "purchase_completed", + properties: { + product_id: "prod-123", + amount: 99.99, + currency: "USD" + } +}); +``` + +### Track User Actions + +```javascript +// Track page view +base44.analytics.track({ + eventName: "page_view", + properties: { + page: "/dashboard", + referrer: document.referrer + } +}); + +// Track feature usage +base44.analytics.track({ + eventName: "feature_used", + properties: { + feature: "export_data", + format: "csv" + } +}); +``` + +## Automatic Tracking + +The analytics module automatically tracks: +- **Initialization events**: When the app loads +- **Heartbeat events**: Periodic activity signals +- **Session duration**: Time spent in the app + +These internal events help measure user engagement without manual instrumentation. + +## Best Practices + +1. **Use descriptive event names**: `order_completed` instead of `click` +2. **Include relevant properties**: Add context that helps analyze the event +3. **Be consistent**: Use the same event names and property keys across your app +4. **Don't track sensitive data**: Avoid PII in event properties + +```javascript +// Good: Descriptive with relevant properties +base44.analytics.track({ + eventName: "subscription_started", + properties: { + plan: "pro", + billing_cycle: "annual" + } +}); + +// Avoid: Vague event name, no context +base44.analytics.track({ + eventName: "click" +}); +``` + +## Type Definitions + +```typescript +/** Properties that can be attached to a tracked event. */ +type TrackEventProperties = { + [key: string]: string | number | boolean | null | undefined; +}; + +/** Parameters for the track() method. */ +interface TrackEventParams { + /** The name of the event to track. */ + eventName: string; + /** Optional properties to attach to the event. */ + properties?: TrackEventProperties; +} + +/** The analytics module interface. */ +interface AnalyticsModule { + /** Track a custom event with optional properties. */ + track(params: TrackEventParams): void; +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/app-logs.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/app-logs.md new file mode 100644 index 0000000000000000000000000000000000000000..9865bb060b67871d752fad593c03d0afb807fcfc --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/app-logs.md @@ -0,0 +1,120 @@ +# App Logs Module + +Log user activity in your app via `base44.appLogs`. + +## Contents +- [Methods](#methods) +- [Examples](#examples) +- [Use Cases](#use-cases) + +## Methods + +| Method | Signature | Description | +|--------|-----------|-------------| +| `logUserInApp(pageName)` | `Promise` | Log user activity on a page | +| `fetchLogs(params?)` | `Promise` | Fetch app logs with optional filter parameters | +| `getStats(params?)` | `Promise` | Get app usage statistics | + +## Examples + +### Log User Activity + +```javascript +// Log when user visits a page +await base44.appLogs.logUserInApp("dashboard"); + +// Log specific page visits +await base44.appLogs.logUserInApp("settings"); +await base44.appLogs.logUserInApp("profile"); + +// Log feature usage +await base44.appLogs.logUserInApp("export-button-click"); +``` + +The page name doesn't have to be an actual page - it can be any string you want to track. + +## Use Cases + +### Track Page Views in React + +```javascript +// Log page views on route change +useEffect(() => { + base44.appLogs.logUserInApp(window.location.pathname); +}, [location.pathname]); +``` + +### Track Feature Usage + +```javascript +// Log when user uses specific features +function handleExport() { + base44.appLogs.logUserInApp("export-data"); + // ... export logic +} + +function handleSettingsChange() { + base44.appLogs.logUserInApp("settings-updated"); + // ... save settings +} +``` + +### Fetch Logs + +```javascript +// Fetch all logs +const logs = await base44.appLogs.fetchLogs(); + +// Fetch logs with filters +const recentLogs = await base44.appLogs.fetchLogs({ + limit: 50, + page: "/dashboard" +}); +``` + +### Get Stats + +```javascript +// Get usage statistics for the app +const stats = await base44.appLogs.getStats(); + +// Get stats with date range params +const weekStats = await base44.appLogs.getStats({ + from: "2024-01-01", + to: "2024-01-07" +}); +``` + +## Notes + +- Logs appear in the Analytics page of your app dashboard +- App logs track page-level and feature-level activity +- Use `analytics.track()` for custom events with properties, `appLogs.logUserInApp()` for simple page/feature tracking + +## Type Definitions + +```typescript +/** App Logs module for tracking and analyzing app usage. */ +interface AppLogsModule { + /** + * Log user activity in the app. + * @param pageName - Name of the page or section being visited. + * @returns Promise that resolves when the log is recorded. + */ + logUserInApp(pageName: string): Promise; + + /** + * Fetch app logs with optional filter parameters. + * @param params - Optional filter parameters (e.g., limit, page name, date range). + * @returns Promise resolving to the logs data. + */ + fetchLogs(params?: Record): Promise; + + /** + * Get app usage statistics. + * @param params - Optional filter parameters (e.g., date range). + * @returns Promise resolving to the statistics data. + */ + getStats(params?: Record): Promise; +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/auth.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/auth.md new file mode 100644 index 0000000000000000000000000000000000000000..ad3c43d1b72fc89ea012b657016c97e834855482 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/auth.md @@ -0,0 +1,770 @@ +# Auth Module + +User authentication, registration, and session management via `base44.auth`. + +## Contents +- [TypeScript Types](#typescript-types) +- [Methods](#methods) +- [Examples](#examples) +- [Error Handling](#error-handling) +- [Auth Providers](#auth-providers) +- [Environment Availability](#environment-availability) +- [App Visibility](#app-visibility) +- [Limitations](#limitations) + +--- + +## TypeScript Types + +### User Interface +```typescript +interface User { + id: string; + created_date: string; + updated_date: string; + email: string; + full_name: string | null; + disabled: boolean | null; + is_verified: boolean; + app_id: string; + is_service: boolean; + role: string; + [key: string]: any; // Custom schema fields +} +``` + +### LoginResponse Interface +```typescript +interface LoginResponse { + access_token: string; // JWT token + user: User; // Complete user object +} +``` + +### Parameter Interfaces + +#### RegisterParams +```typescript +interface RegisterParams { + email: string; // Required + password: string; // Required + turnstile_token?: string | null; // Optional: Cloudflare Turnstile for bot protection + referral_code?: string | null; // Optional: Referral code +} +``` + +#### VerifyOtpParams +```typescript +interface VerifyOtpParams { + email: string; // User's email + otpCode: string; // OTP code from email +} +``` + +#### ResetPasswordParams +```typescript +interface ResetPasswordParams { + resetToken: string; // Token from password reset email + newPassword: string; // New password to set +} +``` + +#### ChangePasswordParams +```typescript +interface ChangePasswordParams { + userId: string; // User ID + currentPassword: string; // Current password for verification + newPassword: string; // New password to set +} +``` + +### Provider Type +```typescript +type Provider = 'google' | 'microsoft' | 'facebook'; +``` + +--- + +## Methods + +### Module Interface +```typescript +interface AuthModule { + // User Info + me(): Promise; + updateMe(data: Partial>): Promise; + isAuthenticated(): Promise; + + // Login/Logout + loginViaEmailPassword(email: string, password: string, turnstileToken?: string): Promise; + loginWithProvider(provider: Provider, fromUrl?: string): void; + logout(redirectUrl?: string): void; + redirectToLogin(nextUrl: string): void; + + // Token Management + setToken(token: string, saveToStorage?: boolean): void; + + // Registration + register(params: RegisterParams): Promise; + verifyOtp(params: VerifyOtpParams): Promise; + resendOtp(email: string): Promise; + + // User Management + inviteUser(userEmail: string, role: string): Promise; + + // Password Management + resetPasswordRequest(email: string): Promise; + resetPassword(params: ResetPasswordParams): Promise; + changePassword(params: ChangePasswordParams): Promise; +} +``` + +### Method Reference Table + +| Method | Parameters | Return Type | Description | +|--------|-----------|-------------|-------------| +| `register()` | `params: RegisterParams` | `Promise` | Create new user account | +| `loginViaEmailPassword()` | `email: string, password: string, turnstileToken?: string` | `Promise` | Authenticate with email/password | +| `loginWithProvider()` | `provider: Provider, fromUrl?: string` | `void` | Initiate OAuth login flow. Providers: `'google'` (default), `'microsoft'`, `'facebook'` (enable in app settings) | +| `me()` | None | `Promise` | Get current authenticated user | +| `updateMe()` | `data: Partial` | `Promise` | Update current user's profile | +| `logout()` | `redirectUrl?: string` | `void` | Redirect to server-side logout (clears HTTP-only cookies and session), then to redirectUrl or current URL | +| `redirectToLogin()` | `nextUrl: string` | `void` | ⚠️ **Avoid** - Prefer custom login UI with `loginViaEmailPassword()` or `loginWithProvider()` | +| `isAuthenticated()` | None | `Promise` | Check if user is logged in | +| `setToken()` | `token: string, saveToStorage?: boolean` | `void` | Manually set auth token | +| `inviteUser()` | `userEmail: string, role: string` | `Promise` | Send invitation email | +| `verifyOtp()` | `params: VerifyOtpParams` | `Promise` | Verify OTP code | +| `resendOtp()` | `email: string` | `Promise` | Resend OTP code | +| `resetPasswordRequest()` | `email: string` | `Promise` | Request password reset | +| `resetPassword()` | `params: ResetPasswordParams` | `Promise` | Reset password with token | +| `changePassword()` | `params: ChangePasswordParams` | `Promise` | Change user password | + +--- + +## Examples + +### Register New User (Complete Flow) + +Registration requires email verification before login. Complete flow: + +1. **Register** - Create the user account +2. **Verification email sent** - User receives an OTP code +3. **Verify OTP** - User enters code to verify email +4. **Login** - User can now log in + +```javascript +try { + // Step 1: Register the user + await base44.auth.register({ + email: "user@example.com", + password: "securePassword123", + referral_code: "OPTIONAL_CODE", // optional + turnstile_token: "CAPTCHA_TOKEN" // optional, for bot protection + }); + console.log('Registration successful. Check email for OTP code.'); + + // Step 2: User receives email with OTP code (e.g., "123456") + + // Step 3: Verify the OTP code + await base44.auth.verifyOtp({ + email: "user@example.com", + otpCode: "123456" // code from verification email + }); + console.log('Email verified successfully.'); + + // Step 4: Now the user can log in + const loginResponse = await base44.auth.loginViaEmailPassword( + "user@example.com", + "securePassword123" + ); + console.log('Login successful:', loginResponse.user); + +} catch (error) { + console.error('Registration flow failed:', error.message); + // Handle specific errors (see Error Handling section) +} +``` + +> **Important**: Users cannot log in until they complete OTP verification. Attempting to call `loginViaEmailPassword` before verification will fail. + +### Login with Email/Password + +```javascript +try { + const response = await base44.auth.loginViaEmailPassword( + "user@example.com", + "password123", + turnstileToken // optional: for bot protection + ); + + console.log('Login successful'); + console.log('User:', response.user); + console.log('Token:', response.access_token); + + // JWT is automatically stored for subsequent requests + +} catch (error) { + console.error('Login failed:', error.message); + if (error.status === 401) { + console.error('Invalid credentials'); + } else if (error.status === 403) { + console.error('Email not verified. Please check your email for OTP.'); + } +} +``` + +### Login with OAuth Provider + +Supported providers: `'google'` (enabled by default), `'microsoft'`, and `'facebook'`. Enable Microsoft or Facebook in your app's authentication settings before using them. + +```javascript +// Redirect to Google OAuth +base44.auth.loginWithProvider('google'); + +// Redirect to Google OAuth and return to current page after +base44.auth.loginWithProvider('google', window.location.href); + +// Microsoft or Facebook (enable in app settings first) +base44.auth.loginWithProvider('microsoft'); +base44.auth.loginWithProvider('facebook', '/dashboard'); +``` + +### Get Current User + +```javascript +try { + const user = await base44.auth.me(); + + if (user) { + console.log('User ID:', user.id); + console.log('Email:', user.email); + console.log('Name:', user.full_name); + console.log('Role:', user.role); + console.log('Verified:', user.is_verified); + } else { + console.log('User not authenticated'); + } + +} catch (error) { + console.error('Failed to fetch user:', error.message); + if (error.status === 401) { + // Token expired or invalid - navigate to your custom login page + navigate('/login'); + } +} +``` + +### Update User Profile + +```javascript +try { + const updatedUser = await base44.auth.updateMe({ + full_name: "John Doe", + // Custom schema fields can be updated here + phone: "+1234567890", + preferences: { theme: "dark" } + }); + + console.log('Profile updated:', updatedUser); + +} catch (error) { + console.error('Profile update failed:', error.message); + if (error.status === 400) { + console.error('Invalid data provided'); + } else if (error.status === 401) { + console.error('Authentication required'); + navigate('/login'); + } +} +``` + +### Check Authentication Status + +```javascript +try { + const isLoggedIn = await base44.auth.isAuthenticated(); + + if (isLoggedIn) { + // Show authenticated UI + console.log('User is authenticated'); + } else { + // Show login button + console.log('User is not authenticated'); + } + +} catch (error) { + console.error('Failed to check authentication:', error.message); + // On error, treat as not authenticated +} +``` + +### Logout + +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. + +```javascript +// Logout: clears session via server, then redirects to current page +base44.auth.logout(); + +// Logout and redirect to goodbye page after +base44.auth.logout("/goodbye"); + +// Logout and redirect to homepage +base44.auth.logout("/"); +``` + +### Protected Route Pattern + +```javascript +// Using a navigation function (e.g., React Router's useNavigate, Next.js router) +async function requireAuth(navigate) { + try { + const user = await base44.auth.me(); + + if (!user) { + // Navigate to your custom login page + navigate('/login', { state: { returnTo: window.location.pathname } }); + return null; + } + + return user; + + } catch (error) { + console.error('Authentication check failed:', error.message); + navigate('/login', { state: { returnTo: window.location.pathname } }); + return null; + } +} + +// Usage in your app +async function loadProtectedPage(navigate) { + const user = await requireAuth(navigate); + if (!user) { + // Will navigate to login + return; + } + + // Continue with authenticated logic + console.log('Welcome,', user.full_name); +} +``` + +### Set Authentication Token + +```javascript +// SECURITY WARNING: Never hardcode tokens or expose them in client code +// Tokens should only be received from secure authentication flows + +// Set token and save to localStorage (default) +base44.auth.setToken(receivedToken); + +// Set token without saving to localStorage (temporary session) +base44.auth.setToken(receivedToken, false); + +// Verify token was set +try { + const isAuthenticated = await base44.auth.isAuthenticated(); + if (!isAuthenticated) { + console.error('Token validation failed'); + } +} catch (error) { + console.error('Failed to set token:', error.message); +} +``` + +### Invite User to Application + +```javascript +try { + // Note: Typically requires admin privileges + const response = await base44.auth.inviteUser( + "newuser@example.com", + "user" // or "admin" + ); + + console.log('Invitation sent successfully'); + +} catch (error) { + console.error('Failed to invite user:', error.message); + if (error.status === 403) { + console.error('Insufficient permissions to invite users'); + } else if (error.status === 400) { + console.error('Invalid email or role'); + } +} +``` + +### OTP Verification + +```javascript +try { + // Verify OTP code sent to user's email + await base44.auth.verifyOtp({ + email: "user@example.com", + otpCode: "123456" + }); + + console.log('OTP verified successfully'); + +} catch (error) { + console.error('OTP verification failed:', error.message); + if (error.status === 400) { + console.error('Invalid or expired OTP code'); + } else if (error.status === 429) { + console.error('Too many attempts. Please try again later.'); + } +} + +// Resend OTP if needed +try { + await base44.auth.resendOtp("user@example.com"); + console.log('OTP resent successfully'); + +} catch (error) { + console.error('Failed to resend OTP:', error.message); + if (error.status === 429) { + console.error('Too many requests. Please wait before trying again.'); + } +} +``` + +### Password Reset Flow + +```javascript +// Step 1: Request password reset +try { + await base44.auth.resetPasswordRequest("user@example.com"); + console.log('Password reset email sent. Check your inbox.'); + +} catch (error) { + console.error('Password reset request failed:', error.message); + if (error.status === 429) { + console.error('Too many requests. Please try again later.'); + } + // Note: For security, don't reveal if email exists +} + +// Step 2: Reset password with token from email +try { + await base44.auth.resetPassword({ + resetToken: "token-from-email", + newPassword: "newSecurePassword123" + }); + + console.log('Password reset successfully. You can now log in.'); + +} catch (error) { + console.error('Password reset failed:', error.message); + if (error.status === 400) { + console.error('Invalid or expired reset token'); + } else if (error.status === 422) { + console.error('Password does not meet requirements'); + } +} +``` + +### Change Password + +```javascript +try { + const currentUser = await base44.auth.me(); + + if (!currentUser) { + throw new Error('User must be authenticated to change password'); + } + + await base44.auth.changePassword({ + userId: currentUser.id, + currentPassword: "oldPassword123", + newPassword: "newSecurePassword456" + }); + + console.log('Password changed successfully'); + +} catch (error) { + console.error('Password change failed:', error.message); + if (error.status === 401) { + console.error('Current password is incorrect'); + } else if (error.status === 422) { + console.error('New password does not meet requirements'); + } else if (error.status === 403) { + console.error('Not authorized to change this password'); + } +} +``` + +--- + +## Error Handling + +### Common Error Scenarios + +The auth module can throw various errors. Here are common scenarios and how to handle them: + +#### Authentication Errors (401/403) +```javascript +try { + const user = await base44.auth.me(); +} catch (error) { + if (error.status === 401) { + // Token expired or invalid - navigate to your custom login page + navigate('/login'); + } else if (error.status === 403) { + // Email not verified or insufficient permissions + console.error('Access denied:', error.message); + } +} +``` + +#### Validation Errors (400/422) +```javascript +try { + await base44.auth.register({ + email: "invalid-email", + password: "weak" + }); +} catch (error) { + if (error.status === 400) { + console.error('Invalid input:', error.message); + // Handle validation errors + } else if (error.status === 422) { + console.error('Data validation failed:', error.details); + } +} +``` + +#### Rate Limiting (429) +```javascript +try { + await base44.auth.resendOtp("user@example.com"); +} catch (error) { + if (error.status === 429) { + console.error('Too many requests. Please wait before trying again.'); + // Show countdown or disable button temporarily + } +} +``` + +#### Generic Error Handler +```javascript +function handleAuthError(error) { + switch (error.status) { + case 400: + return 'Invalid input. Please check your data.'; + case 401: + return 'Authentication required. Redirecting to login...'; + case 403: + return 'Access denied. You may need to verify your email.'; + case 404: + return 'Resource not found.'; + case 422: + return 'Validation failed. Please check your input.'; + case 429: + return 'Too many requests. Please try again later.'; + case 500: + return 'Server error. Please try again.'; + default: + return 'An unexpected error occurred.'; + } +} + +// Usage +try { + await base44.auth.loginViaEmailPassword(email, password); +} catch (error) { + console.error(handleAuthError(error)); +} +``` + +--- + +## Auth Providers + +Configure authentication providers in your app dashboard: + +### Available Providers + +**Built-in (All Plans):** +- **Email/Password** - Default, always enabled +- **Google** - OAuth authentication +- **Microsoft** - OAuth authentication +- **Facebook** - OAuth authentication + +**SSO Providers (Elite Plan):** +- **Okta** +- **Azure AD** +- **GitHub** + +### Using OAuth Providers + +- **Google** – enabled by default. +- **Microsoft** – enable in your app's authentication settings before use. +- **Facebook** – enable in your app's authentication settings before use. + +```javascript +// Initiate OAuth login flow +base44.auth.loginWithProvider('google'); + +// Return to specific page after authentication +base44.auth.loginWithProvider('microsoft', '/dashboard'); + +// Supported values: 'google', 'microsoft', 'facebook' +``` + +--- + +## Environment Availability + +| Environment | Availability | Notes | +|------------|--------------|-------| +| **Frontend** | ✅ Yes | All methods available | +| **Backend Functions** | ✅ Yes | Use `createClientFromRequest(req)` for authenticated client | +| **Service Role** | ❌ No | Auth methods not available in service role context | + +### Frontend Usage +```javascript +// Standard browser usage +const user = await base44.auth.me(); +``` + +### Backend Functions Usage +```javascript +import { createClientFromRequest } from "@base44/sdk"; + +Deno.serve(async (req) => { + const base44 = createClientFromRequest(req); + + // Get user from request context + const user = await base44.auth.me(); + + // User operations here... + return Response.json({ user }); +}); +``` + +--- + +## App Visibility + +Control who can access your app in the app settings: + +### Public Apps +- No login required for basic access +- Users can view public content without authentication +- Authenticated users get additional features/data + +### Private Apps +- Login required to access any content +- Unauthenticated users are automatically redirected to login +- All content is protected by default + +--- + +## Limitations + +### Authentication UI Options +- **Recommended:** Build custom login/signup UI using `loginViaEmailPassword()` and `loginWithProvider()` for full control over user experience and branding +- **Alternative:** `redirectToLogin()` uses Base44's hosted authentication pages with limited customization + +### Hosted Login (via redirectToLogin) +- `redirectToLogin()` shows both login and signup options on the same page +- No separate `redirectToSignup()` method +- Users can switch between login/signup on the hosted page +- ⚠️ **Note:** Prefer building custom login UI for better user experience + +### Password Requirements +- Minimum length and complexity requirements enforced +- Requirements not exposed via API +- Validation errors returned when requirements not met + +### Rate Limiting +- OTP requests are rate-limited to prevent abuse +- Password reset requests are rate-limited +- Login attempts may be rate-limited with Turnstile protection + +### Token Management +- JWTs are automatically stored in localStorage by default +- Token expiration and refresh not exposed in API +- Call `me()` or `isAuthenticated()` to verify token validity + +--- + +## Best Practices + +### 1. Always Handle Errors +```javascript +try { + await base44.auth.loginViaEmailPassword(email, password); +} catch (error) { + // Always handle authentication errors + console.error('Login failed:', error.message); +} +``` + +### 2. Verify Authentication Before Protected Actions +```javascript +const user = await requireAuth(); +if (!user) return; // Will redirect to login +// Proceed with authenticated action +``` + +### 3. Use Type Safety with TypeScript +```typescript +import type { User, LoginResponse } from '@base44/sdk'; + +const user: User = await base44.auth.me(); +const response: LoginResponse = await base44.auth.loginViaEmailPassword(email, password); +``` + +### 4. Don't Hardcode Credentials +```javascript +// ❌ BAD +base44.auth.setToken("hardcoded-token-here"); + +// ✅ GOOD +const token = await secureAuthFlow(); +base44.auth.setToken(token); +``` + +### 5. Provide User Feedback +```javascript +try { + await base44.auth.register(params); + showSuccessMessage('Registration successful! Check your email for verification code.'); +} catch (error) { + showErrorMessage('Registration failed: ' + error.message); +} +``` + +### 6. Handle Token Expiration Gracefully +```javascript +try { + const user = await base44.auth.me(); +} catch (error) { + if (error.status === 401) { + // Clear local state and navigate to login + localStorage.clear(); + navigate('/login'); + } +} +``` + +### 7. Build Custom Login UI (Recommended) +```javascript +// ✅ RECOMMENDED - Custom login form with direct methods +const handleLogin = async (email, password) => { + try { + const { user } = await base44.auth.loginViaEmailPassword(email, password); + navigate('/dashboard'); + } catch (error) { + setError(error.message); + } +}; + +const handleGoogleLogin = () => { + base44.auth.loginWithProvider('google', '/dashboard'); +}; + +// ❌ AVOID - Redirecting to hosted login page +// base44.auth.redirectToLogin(window.location.href); +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/base44-agents.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/base44-agents.md new file mode 100644 index 0000000000000000000000000000000000000000..b919bbf9940a828eeccf418f1ad8da46e49c5a15 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/base44-agents.md @@ -0,0 +1,386 @@ +# Agents Module + +AI agent conversations and messages via `base44.agents`. + +> **Note:** This module requires a logged-in user. All agent methods work in the context of the authenticated user. + +## Contents +- [Concepts](#concepts) +- [Methods](#methods) +- [Examples](#examples) (Create, Get Conversations, List, Subscribe, Send Message, WhatsApp) +- [Message Structure](#message-structure) +- [Conversation Structure](#conversation-structure) +- [Common Patterns](#common-patterns) + +## Concepts + +- **Conversation**: A dialogue between user and an AI agent. Has unique ID, agent name, user reference, and metadata. +- **Message**: Single message in a conversation. Has role (`user`, `assistant`, `system`), content, timestamps, and optional metadata. + +## Methods + +| Method | Signature | Description | +|--------|-----------|-------------| +| `createConversation(params)` | `Promise` | Create a new conversation with an agent | +| `getConversations()` | `Promise` | Get all user's conversations | +| `getConversation(id)` | `Promise` | Get conversation with messages (includes full tool call results) | +| `listConversations(filterParams)` | `Promise` | Filter/sort/paginate conversations | +| `subscribeToConversation(id, onUpdate?)` | `() => void` | Realtime updates via WebSocket; tool call data truncated (returns unsubscribe function) | +| `addMessage(conversation, message)` | `Promise` | Send a message | +| `getWhatsAppConnectURL(agentName)` | `string` | Get WhatsApp connection URL for agent | + +## Examples + +### Create Conversation + +```javascript +const conversation = await base44.agents.createConversation({ + agent_name: "support-agent", + metadata: { + order_id: "ORD-123", + category: "billing" + } +}); + +console.log(conversation.id); +``` + +### Get All Conversations + +```javascript +const conversations = await base44.agents.getConversations(); + +conversations.forEach(conv => { + console.log(conv.id, conv.agent_name, conv.created_date); +}); +``` + +### Get Single Conversation (with messages) + +Returns the complete stored conversation including full tool call results (unlike the realtime subscription, which truncates tool call data). + +```javascript +const conversation = await base44.agents.getConversation("conv-id-123"); + +console.log(conversation.messages); +``` + +### List with Filters + +```javascript +// Using filterParams object with q, sort, limit, skip, fields +const recent = await base44.agents.listConversations({ + q: { agent_name: "support-agent" }, + sort: "-created_date", + limit: 10, + skip: 0 +}); + +// Filter by metadata +const highPriority = await base44.agents.listConversations({ + q: { + agent_name: "support-agent", + "metadata.priority": "high" + }, + sort: "-updated_date", + limit: 20 +}); +``` + +### Subscribe to Updates (Realtime) + +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. + +```javascript +const unsubscribe = base44.agents.subscribeToConversation( + "conv-id-123", + (updatedConversation) => { + // Called when new messages arrive + console.log("New messages:", updatedConversation.messages); + } +); + +// Later: unsubscribe +unsubscribe(); +``` + +### Send a Message + +```javascript +const conversation = await base44.agents.getConversation("conv-id-123"); + +await base44.agents.addMessage(conversation, { + role: "user", + content: "What's the weather like today?" +}); +``` + +### Get WhatsApp Connection URL + +```javascript +const whatsappUrl = base44.agents.getWhatsAppConnectURL("support-agent"); +// Returns URL for users to connect with agent via WhatsApp +console.log(whatsappUrl); +``` + +## Message Structure + +```javascript +{ + role: "user" | "assistant" | "system", + content: "Message text or structured object", + created_date: "2024-01-15T10:30:00Z", + updated_date: "2024-01-15T10:30:00Z", + + // Optional fields + reasoning: { + content: "Agent's reasoning process", + timing: 1500 + }, + tool_calls: [{ + name: "search", + arguments: { query: "weather" }, + result: { ... }, + status: "success" + }], + file_urls: ["https://..."], + usage: { + prompt_tokens: 150, + completion_tokens: 50 + }, + metadata: { ... }, + custom_context: { ... } +} +``` + +## Conversation Structure + +```javascript +{ + id: "conv-id-123", + app_id: "app-id", + agent_name: "support-agent", + created_by_id: "user-id", + created_date: "2024-01-15T10:00:00Z", + updated_date: "2024-01-15T10:30:00Z", + messages: [ ... ], + metadata: { ... } +} +``` + +## Common Patterns + +### Chat Interface + +```javascript +// Load conversation +const conv = await base44.agents.getConversation(conversationId); +setMessages(conv.messages); + +// Subscribe to updates +const unsubscribe = base44.agents.subscribeToConversation(conversationId, (updated) => { + setMessages(updated.messages); +}); + +// Send message +async function sendMessage(text) { + await base44.agents.addMessage(conv, { role: "user", content: text }); +} + +// Cleanup on unmount +return () => unsubscribe(); +``` + +## Type Definitions + +### AgentNameRegistry and AgentName + +**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. + +```typescript +/** + * Registry of agent names. + * Augment this interface to enable autocomplete for agent names. + * Typically populated by the Base44 CLI type generator. + */ +interface AgentNameRegistry {} + +/** + * Agent name type - uses registry keys if augmented, otherwise string. + */ +type AgentName = keyof AgentNameRegistry extends never ? string : keyof AgentNameRegistry; +``` + +### AgentConversation + +```typescript +/** An agent conversation containing messages exchanged with an AI agent. */ +interface AgentConversation { + /** Unique identifier for the conversation. */ + id: string; + /** Application ID. */ + app_id: string; + /** Name of the agent in this conversation. */ + agent_name: string; + /** ID of the user who created the conversation. */ + created_by_id: string; + /** When the conversation was created. */ + created_date: string; + /** When the conversation was last updated. */ + updated_date: string; + /** Array of messages in the conversation. */ + messages: AgentMessage[]; + /** Optional metadata associated with the conversation. */ + metadata?: Record; +} +``` + +### AgentMessage + +```typescript +/** A message in an agent conversation. */ +interface AgentMessage { + /** Unique identifier for the message. */ + id: string; + /** Role of the message sender. */ + role: "user" | "assistant" | "system"; + /** When the message was created. */ + created_date: string; + /** When the message was last updated. */ + updated_date: string; + /** Message content. */ + content?: string | Record; + /** Optional reasoning information for the message. */ + reasoning?: AgentMessageReasoning | null; + /** URLs to files attached to the message. */ + file_urls?: string[]; + /** Tool calls made by the agent. */ + tool_calls?: AgentMessageToolCall[]; + /** Token usage statistics. */ + usage?: AgentMessageUsage; + /** Whether the message is hidden from the user. */ + hidden?: boolean; + /** Custom context provided with the message. */ + custom_context?: AgentMessageCustomContext[]; + /** Model used to generate the message. */ + model?: string; + /** Checkpoint ID for the message. */ + checkpoint_id?: string; + /** Metadata about when and by whom the message was created. */ + metadata?: AgentMessageMetadata; +} +``` + +### Supporting Types + +```typescript +/** Reasoning information for an agent message. */ +interface AgentMessageReasoning { + /** When reasoning started. */ + start_date: string; + /** When reasoning ended. */ + end_date?: string; + /** Reasoning content. */ + content: string; +} + +/** A tool call made by the agent. */ +interface AgentMessageToolCall { + /** Tool call ID. */ + id: string; + /** Name of the tool called. */ + name: string; + /** Arguments passed to the tool as JSON string. */ + arguments_string: string; + /** Status of the tool call. */ + status: "running" | "success" | "error" | "stopped"; + /** Results from the tool call. */ + results?: string; +} + +/** Token usage statistics for an agent message. */ +interface AgentMessageUsage { + /** Number of tokens in the prompt. */ + prompt_tokens?: number; + /** Number of tokens in the completion. */ + completion_tokens?: number; +} + +/** Custom context provided with an agent message. */ +interface AgentMessageCustomContext { + /** Context message. */ + message: string; + /** Associated data for the context. */ + data: Record; + /** Type of context. */ + type: string; +} + +/** Metadata about when and by whom a message was created. */ +interface AgentMessageMetadata { + /** When the message was created. */ + created_date: string; + /** Email of the user who created the message. */ + created_by_email: string; + /** Full name of the user who created the message. */ + created_by_full_name: string; +} +``` + +### CreateConversationParams + +```typescript +/** Parameters for creating a new conversation. */ +interface CreateConversationParams { + /** The name of the agent to create a conversation with. */ + agent_name: AgentName; + /** Optional metadata to attach to the conversation. */ + metadata?: Record; +} +``` + +### ModelFilterParams + +```typescript +/** Parameters for filtering, sorting, and paginating conversations. */ +interface ModelFilterParams { + /** Query object with field-value pairs for filtering. */ + q?: Record; + /** Sort parameter (e.g., "-created_date" for descending). */ + sort?: string | null; + /** Maximum number of results to return. */ + limit?: number | null; + /** Number of results to skip for pagination. */ + skip?: number | null; + /** Array of field names to include in the response. */ + fields?: string[] | null; +} +``` + +### AgentsModule + +```typescript +/** Agents module for managing AI agent conversations. */ +interface AgentsModule { + /** Gets all conversations from all agents in the app. */ + getConversations(): Promise; + + /** Gets a specific conversation by ID. Returns complete stored conversation including full tool call results. */ + getConversation(conversationId: string): Promise; + + /** Lists conversations with filtering, sorting, and pagination. */ + listConversations(filterParams: ModelFilterParams): Promise; + + /** Creates a new conversation with an agent. */ + createConversation(conversation: CreateConversationParams): Promise; + + /** Adds a message to a conversation. */ + addMessage(conversation: AgentConversation, message: Partial): Promise; + + /** Subscribes to realtime updates for a conversation. Returns unsubscribe function. */ + subscribeToConversation(conversationId: string, onUpdate?: (conversation: AgentConversation) => void): () => void; + + /** Gets WhatsApp connection URL for an agent. */ + getWhatsAppConnectURL(agentName: AgentName): string; +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/client.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/client.md new file mode 100644 index 0000000000000000000000000000000000000000..27cd6239270fde474d5beb28001c077d376b453c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/client.md @@ -0,0 +1,265 @@ +# Client Setup + +How to create and configure the Base44 client. + +## Contents +- [In Base44-Generated Apps](#in-base44-generated-apps) +- [In External Apps](#in-external-apps) +- [In Backend Functions](#in-backend-functions) +- [Authentication Modes](#authentication-modes) (Anonymous, User, Service Role) +- [Available Modules](#available-modules) +- [Client Methods](#client-methods) +- [Client Configuration Options](#client-configuration-options) + +## In Base44-Generated Apps + +Inside a Base44 app, the client is automatically created and configured. Import it from `@/api/base44Client` and use it as `base44`: + +```javascript +const tasks = await base44.entities.Task.list(); +``` + +## In External Apps + +When using Base44 as a backend from an external app, install the SDK and create a client by calling `createClient()` directly: + +```bash +npm install @base44/sdk +``` + +```javascript +import { createClient } from "@base44/sdk"; + +// IMPORTANT: The parameter name is 'appId' (NOT 'clientId', NOT 'id') +// IMPORTANT: onError must be nested inside 'options' object +const base44 = createClient({ + appId: "your-app-id", // Required: Use 'appId' parameter + token: "optional-user-token", // Optional: for pre-authenticated requests + options: { // Optional: configuration options + onError: (error) => { // Optional: error handler (must be in options) + console.error("Base44 error:", error); + } + } +}); +``` + +**Common Mistakes:** +- ❌ `createClient({ clientId: "..." })` - WRONG parameter name +- ❌ `createClient({ id: "..." })` - WRONG parameter name +- ❌ `createClient({ appId: "...", onError: ... })` - WRONG: onError must be in options +- ✅ `createClient({ appId: "..." })` - CORRECT parameter name +- ✅ `createClient({ appId: "...", options: { onError: ... } })` - CORRECT: onError in options + +## In Backend Functions + +`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. + +```javascript +import { createClientFromRequest } from "@base44/sdk"; + +Deno.serve(async (req) => { + const base44 = createClientFromRequest(req); + + // Client inherits authentication from the request + const user = await base44.auth.me(); + + return Response.json({ user }); +}); +``` + +## Authentication Modes + +| Mode | How to Get | Permissions | +|------|-----------|-------------| +| **Anonymous** | `createClient({ appId })` without token | Public data only | +| **User** | After `loginViaEmailPassword()` or via `createClientFromRequest` | User's own data | +| **Service Role** | `base44.asServiceRole.*` in backend | Full admin access | + +## Anonymous Mode + +No authentication. Can only access public resources. + +```javascript +const base44 = createClient({ appId: "your-app-id" }); + +// Only works if Task entity allows anonymous read +const publicTasks = await base44.entities.Task.list(); +``` + +## User Mode + +After user logs in, the client automatically includes their token. + +```javascript +const base44 = createClient({ appId: "your-app-id" }); + +// Login sets the token +await base44.auth.loginViaEmailPassword("user@example.com", "password"); + +// Subsequent requests are authenticated +const user = await base44.auth.me(); +const myTasks = await base44.entities.Task.list(); // filtered by permissions +``` + +## Service Role Mode + +Admin-level access. **Backend only.** + +```javascript +// Inside a backend function +Deno.serve(async (req) => { + const base44 = createClientFromRequest(req); + + // User mode - respects permissions + const myTasks = await base44.entities.Task.list(); + + // Service role - bypasses permissions + const allTasks = await base44.asServiceRole.entities.Task.list(); + const allUsers = await base44.asServiceRole.entities.User.list(); + const oauthToken = await base44.asServiceRole.connectors.getAccessToken("slack"); + + return Response.json({ myTasks, allTasks }); +}); +``` + +## Available Modules + +The client exposes these modules: + +```javascript +base44.agents // AI conversations +base44.analytics // Event tracking +base44.appLogs // App usage logging +base44.auth // Authentication +base44.connectors // Per-user OAuth flows (UserConnectorsModule) +base44.entities // CRUD operations +base44.functions // Backend function invocation +base44.integrations // Third-party services +base44.users // User invitations + +// Service role only (backend) +base44.asServiceRole.agents +base44.asServiceRole.appLogs +base44.asServiceRole.connectors // App-scoped OAuth tokens (ConnectorsModule) +base44.asServiceRole.entities +base44.asServiceRole.functions +base44.asServiceRole.integrations +base44.asServiceRole.sso // SSO token generation +``` + +## Client Methods + +The client provides these methods: + +```javascript +// Set authentication token for all subsequent requests +base44.setToken(newToken); + +// Cleanup WebSocket connections (call when done with client) +base44.cleanup(); +``` + +### setToken + +Updates the authentication token for all subsequent API requests and WebSocket connections. + +```javascript +// After receiving a token (e.g., from external auth) +base44.setToken("new-jwt-token"); +``` + +### cleanup + +Disconnects WebSocket connections. Call when you're done with the client or when the component unmounts. + +```javascript +// Cleanup on component unmount (React example) +useEffect(() => { + return () => base44.cleanup(); +}, []); +``` + +## Client Configuration Options + +```javascript +createClient({ + appId: "your-app-id", // Required: MUST use 'appId' (not 'clientId' or 'id') + token: "jwt-token", // Optional: pre-set auth token + options: { // Optional: configuration options + onError: (error) => {} // Optional: global error handler (must be in options) + } +}); +``` + +**⚠️ Critical:** +- The parameter name is `appId`, not `clientId` or `id`. Using the wrong parameter name will cause errors. +- The `onError` handler must be nested inside the `options` object, not at the top level. + +## Type Definitions + +### CreateClientConfig + +```typescript +/** Configuration for creating a Base44 client. */ +interface CreateClientConfig { + /** The Base44 app ID (required). */ + appId: string; + /** User authentication token. Used to authenticate as a specific user. */ + token?: string; + /** @internal Service role token; only set automatically in Base44-hosted backend functions. */ + serviceToken?: string; + /** Additional client options. */ + options?: CreateClientOptions; +} + +/** Options for creating a Base44 client. */ +interface CreateClientOptions { + /** Optional error handler called whenever an API error occurs. */ + onError?: (error: Error) => void; +} +``` + +### Base44Client + +```typescript +/** The Base44 client instance. */ +interface Base44Client { + /** Agents module for managing AI agent conversations. */ + agents: AgentsModule; + /** Analytics module for tracking custom events. */ + analytics: AnalyticsModule; + /** App logs module for tracking app usage. */ + appLogs: AppLogsModule; + /** Auth module for user authentication and management. */ + auth: AuthModule; + /** Entities module for CRUD operations on your data models. */ + entities: EntitiesModule; + /** Functions module for invoking custom backend functions. */ + functions: FunctionsModule; + /** Integrations module for calling pre-built integration methods. */ + integrations: IntegrationsModule; + + /** Cleanup function to disconnect WebSocket connections. */ + cleanup(): void; + + /** Sets a new authentication token for all subsequent requests. */ + setToken(newToken: string): void; + + /** Per-user OAuth flows. Each end user has their own connection. */ + connectors: UserConnectorsModule; + + /** Provides access to modules with elevated service role permissions (backend only). */ + readonly asServiceRole: { + agents: AgentsModule; + appLogs: AppLogsModule; + /** App-scoped OAuth tokens. All users share the same connected account. */ + connectors: ConnectorsModule; + entities: EntitiesModule; + functions: FunctionsModule; + integrations: IntegrationsModule; + /** SSO token generation for users. */ + sso: SsoModule; + cleanup(): void; + }; +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/connectors.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/connectors.md new file mode 100644 index 0000000000000000000000000000000000000000..ca906645fcfc70e45bfadaac3cb96d7b24140484 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/connectors.md @@ -0,0 +1,157 @@ +# Connectors Module + +OAuth token management for external services. + +- **`base44.asServiceRole.connectors`** — App-scoped OAuth tokens (backend/service role only). All users share the same connected account. + +## Contents +- [Service Role Connectors (`base44.asServiceRole.connectors`)](#service-role-connectors-base44asserviceroleconnectors) +- [Available Services](#available-services) +- [Type Definitions](#type-definitions) + +--- + +## Service Role Connectors (`base44.asServiceRole.connectors`) + +App-scoped OAuth tokens. The app builder connects the account once; all users share it. **Backend/service role only.** + +### Methods + +| Method | Signature | Description | +|--------|-----------|-------------| +| `getConnection(integrationType)` | `Promise` | Get access token and optional connection config | +| `getAccessToken(integrationType)` | `Promise` | ⚠️ **Deprecated** — use `getConnection()` instead | + +### Examples + +```javascript +// Backend function only +Deno.serve(async (req) => { + const base44 = createClientFromRequest(req); + + // Recommended: use getConnection() for token + optional config + const { accessToken, connectionConfig } = await base44.asServiceRole.connectors.getConnection("slack"); + + const response = await fetch("https://slack.com/api/chat.postMessage", { + method: "POST", + headers: { + "Authorization": `Bearer ${accessToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ channel: "#general", text: "Hello from Base44!" }) + }); + + return Response.json(await response.json()); +}); +``` + +```javascript +// Using connectionConfig (for services that need extra params, e.g. a subdomain) +const { accessToken, connectionConfig } = await base44.asServiceRole.connectors.getConnection("myservice"); +const subdomain = connectionConfig?.subdomain; +const response = await fetch(`https://${subdomain}.example.com/api/v1/data`, { + headers: { "Authorization": `Bearer ${accessToken}` } +}); +``` + +```javascript +// Google Calendar example +const { accessToken } = await base44.asServiceRole.connectors.getConnection("googlecalendar"); + +const events = await fetch( + "https://www.googleapis.com/calendar/v3/calendars/primary/events?" + + new URLSearchParams({ maxResults: "10", orderBy: "startTime", singleEvents: "true", timeMin: new Date().toISOString() }), + { headers: { "Authorization": `Bearer ${accessToken}` } } +).then(r => r.json()); +``` + +--- + +## Available Services + +| Service | Type identifier | +|---------|----------------| +| Airtable | `airtable` | +| Box | `box` | +| ClickUp | `clickup` | +| Discord | `discord` | +| Dropbox | `dropbox` | +| GitHub | `github` | +| Gmail | `gmail` | +| Google Analytics | `google_analytics` | +| Google BigQuery | `googlebigquery` | +| Google Calendar | `googlecalendar` | +| Google Classroom | `google_classroom` | +| Google Docs | `googledocs` | +| Google Drive | `googledrive` | +| Google Search Console | `google_search_console` | +| Google Sheets | `googlesheets` | +| Google Slides | `googleslides` | +| HubSpot | `hubspot` | +| Linear | `linear` | +| LinkedIn | `linkedin` | +| Microsoft Teams | `microsoft_teams` | +| Microsoft OneDrive | `one_drive` | +| Notion | `notion` | +| Outlook | `outlook` | +| Salesforce | `salesforce` | +| SharePoint | `share_point` | +| Slack User | `slack` | +| Slack Bot | `slackbot` | +| Splitwise | `splitwise` | +| TikTok | `tiktok` | +| Typeform | `typeform` | +| Wix | `wix` | +| Wrike | `wrike` | + +Run `npx base44 connectors list-available` from the CLI to see all available types. + +--- + +## Setup Requirements + +1. **Builder plan** or higher +2. **Backend functions** enabled (for service role connectors) +3. **Connector configured** in Base44 dashboard (OAuth flow completed) + +## Important Notes + +- **Service role connectors**: One account per connector per app — all users share the same connected account +- **You handle the API calls**: Base44 provides the token; you make the actual API requests +- **Token refresh**: Base44 handles token refresh automatically + +--- + +## Type Definitions + +```typescript +/** + * The type of external integration/connector (for service role connectors). + * Examples: 'googlecalendar', 'slack', 'github', 'notion', etc. + */ +type ConnectorIntegrationType = string; + +/** Connection details returned by getConnection(). */ +interface ConnectorConnectionResponse { + /** The OAuth access token for the external service. */ + accessToken: string; + /** Key-value configuration for the connection, or null if not needed. */ + connectionConfig: Record | null; +} + +/** Service role connectors module (app-scoped OAuth). Backend only. */ +interface ConnectorsModule { + /** + * Retrieves the OAuth access token and optional connection config. + * @param integrationType - e.g., 'googlecalendar', 'slack', 'github'. + */ + getConnection(integrationType: ConnectorIntegrationType): Promise; + + /** + * @deprecated Use getConnection() instead. + * Retrieves only the OAuth access token string. + */ + getAccessToken(integrationType: ConnectorIntegrationType): Promise; +} + +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/entities.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/entities.md new file mode 100644 index 0000000000000000000000000000000000000000..8a2f51c93407be54ec0629a390146aed79dd16d7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/entities.md @@ -0,0 +1,399 @@ +# Entities Module + +CRUD operations on data models. Access via `base44.entities.EntityName.method()`. + +## Contents +- [Methods](#methods) +- [Examples](#examples) (Create, Bulk Create, List, Filter, Get, Update, Delete, Subscribe) +- [User Entity](#user-entity) +- [Service Role Access](#service-role-access) +- [Permissions](#permissions) + +## Methods + +**Note:** The maximum limit for `list()` and `filter()` is 5,000 items per request. + +| Method | Signature | Description | +|--------|-----------|-------------| +| `create(data)` | `Promise` | Create one record | +| `bulkCreate(dataArray)` | `Promise` | Create multiple records | +| `list(sort?, limit?, skip?, fields?)` | `Promise[]>` | Get all records (paginated) | +| `filter(query, sort?, limit?, skip?, fields?)` | `Promise[]>` | Get records matching conditions | +| `get(id)` | `Promise` | Get single record by ID | +| `update(id, data)` | `Promise` | Update record (partial update) | +| `updateMany(query, data)` | `Promise` | Update all matching records using MongoDB update operators | +| `bulkUpdate(dataArray)` | `Promise` | Update multiple records by ID, each with its own data | +| `delete(id)` | `Promise` | Delete record by ID | +| `deleteMany(query)` | `Promise` | Delete all matching records | +| `importEntities(file)` | `Promise>` | Import from CSV (frontend only) | +| `subscribe(callback)` | `() => void` | Subscribe to realtime updates (returns unsubscribe function) | + +## Examples + +### Create + +```javascript +const task = await base44.entities.Task.create({ + title: "Complete documentation", + status: "pending", + dueDate: "2024-12-31" +}); +``` + +### Bulk Create + +```javascript +const tasks = await base44.entities.Task.bulkCreate([ + { title: "Task 1", status: "pending" }, + { title: "Task 2", status: "pending" } +]); +``` + +### List with Pagination + +```javascript +// Get first 10 records, sorted by created_date descending (max 5,000 per request) +const tasks = await base44.entities.Task.list( + "-created_date", // sort (SortField: prefix with - for descending) + 10, // limit + 0 // skip +); + +// Get next page +const page2 = await base44.entities.Task.list("-created_date", 10, 10); +``` + +### Filter + +```javascript +// Simple filter +const pending = await base44.entities.Task.filter({ status: "pending" }); + +// Multiple conditions +const myPending = await base44.entities.Task.filter({ + status: "pending", + assignedTo: userId +}); + +// With sort, limit, skip (max 5,000 per request) +const recent = await base44.entities.Task.filter( + { status: "pending" }, + "-created_date", // sort (SortField: prefix with - for descending) + 5, + 0 +); + +// Select specific fields +const titles = await base44.entities.Task.filter( + { status: "pending" }, + null, + null, + null, + ["id", "title"] +); +``` + +### Get by ID + +```javascript +const task = await base44.entities.Task.get("task-id-123"); +``` + +### Update + +```javascript +// Partial update - only specified fields change +await base44.entities.Task.update("task-id-123", { + status: "completed", + completedAt: new Date().toISOString() +}); +``` + +### Delete + +```javascript +// Single record +const result = await base44.entities.Task.delete("task-id-123"); +console.log("Deleted:", result.success); + +// Multiple records matching query +const manyResult = await base44.entities.Task.deleteMany({ status: "archived" }); +console.log("Deleted:", manyResult.deleted); +``` + +### Update Many (MongoDB-style) + +```javascript +// Update all pending tasks to status "in-progress" +const result = await base44.entities.Task.updateMany( + { status: "pending" }, // query: which records to update + { $set: { status: "in-progress" } } // MongoDB update operator +); +console.log("Updated:", result.updated); + +// Increment a counter field +await base44.entities.Task.updateMany( + { category: "bugs" }, + { $inc: { priority: 1 } } +); +``` + +### Bulk Update (by ID) + +```javascript +// Update multiple records, each with different data +const updated = await base44.entities.Task.bulkUpdate([ + { id: "task-1", status: "done", completedAt: new Date().toISOString() }, + { id: "task-2", status: "in-progress", assignedTo: userId }, + { id: "task-3", priority: 5 } +]); +``` + +### Import from File + +```javascript +// Frontend only: import from CSV/file +const result = await base44.entities.Task.importEntities(file); +if (result.status === "success" && result.output) { + console.log(`Imported ${result.output.length} records`); +} else { + console.error(result.details); +} +``` + +### Subscribe to Realtime Updates + +```javascript +// Subscribe to all changes on Task entity +const unsubscribe = base44.entities.Task.subscribe((event) => { + console.log(`Task ${event.id} was ${event.type}:`, event.data); + // event.type is "create", "update", or "delete" +}); + +// Later: unsubscribe to stop receiving updates +unsubscribe(); +``` + +**Event structure:** +```javascript +{ + type: "create" | "update" | "delete", + data: { ... }, // the entity data + id: "entity-id", // the affected entity's ID + timestamp: "2024-01-15T10:30:00Z" +} +``` + +## User Entity + +Every app has a built-in `User` entity with special rules: + +- Regular users can only read/update **their own** record +- Cannot create users via `entities.create()` - use `auth.register()` instead +- Service role has full access to all user records + +```javascript +// Get current user's record +const me = await base44.entities.User.get(currentUserId); + +// Service role: get any user +const anyUser = await base44.asServiceRole.entities.User.get(userId); +``` + +## Service Role Access + +For admin-level operations (bypass user permissions): + +```javascript +// Backend only +const allTasks = await base44.asServiceRole.entities.Task.list(); +const allUsers = await base44.asServiceRole.entities.User.list(); +``` + +## Permissions (RLS & FLS) + +Data access is controlled by **Row Level Security (RLS)** and **Field Level Security (FLS)** rules defined in entity schemas. + +1. **Authentication level**: anonymous, authenticated, or service role +2. **RLS rules**: Control which records (rows) users can create/read/update/delete +3. **FLS rules**: Control which fields users can read/write within accessible records + +Operations succeed or fail based on these rules - no partial results. + +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. + +**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. + +## Type Definitions + +### RealtimeEvent + +```typescript +/** Event types for realtime entity updates. */ +type RealtimeEventType = "create" | "update" | "delete"; + +/** Payload received when a realtime event occurs. */ +interface RealtimeEvent { + /** The type of change that occurred. */ + type: RealtimeEventType; + /** The entity data. */ + data: T; + /** The unique identifier of the affected entity. */ + id: string; + /** ISO 8601 timestamp of when the event occurred. */ + timestamp: string; +} + +/** Callback function invoked when a realtime event occurs. */ +type RealtimeCallback = (event: RealtimeEvent) => void; +``` + +### Result Types + +```typescript +/** Result returned when updating multiple entities. */ +interface UpdateManyResult { + /** Whether the update was successful. */ + success: boolean; + /** Number of entities that were updated. */ + updated: number; +} + +/** Result returned when deleting a single entity. */ +interface DeleteResult { + /** Whether the deletion was successful. */ + success: boolean; +} + +/** Result returned when deleting multiple entities. */ +interface DeleteManyResult { + /** Whether the deletion was successful. */ + success: boolean; + /** Number of entities that were deleted. */ + deleted: number; +} + +/** Result returned when importing entities from a file. */ +interface ImportResult { + /** Status of the import operation. */ + status: "success" | "error"; + /** Details message, e.g., "Successfully imported 3 entities with RLS enforcement". */ + details: string | null; + /** Array of created entity objects when successful, or null on error. */ + output: T[] | null; +} +``` + +### SortField and Server Fields + +```typescript +/** + * Sort field type for entity queries. + * Supports ascending (no prefix or '+') and descending ('-') sorting. + * Example: 'created_date', '+created_date', '-created_date' + */ +type SortField = (keyof T & string) | `+${keyof T & string}` | `-${keyof T & string}`; + +/** Fields added by the server to every entity record. */ +interface ServerEntityFields { + id: string; + created_date: string; + updated_date: string; + created_by?: string | null; + created_by_id?: string | null; + is_sample?: boolean; +} +``` + +### Type Registry (for typed entities) + +**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. + +```typescript +/** + * Registry mapping entity names to their TypeScript types. + * Augment this interface with your entity schema (user-defined fields only). + * Typically populated by the Base44 CLI type generator. + */ +interface EntityTypeRegistry {} + +/** + * Full record type for each entity: schema fields + server-injected fields. + */ +type EntityRecord = { + [K in keyof EntityTypeRegistry]: EntityTypeRegistry[K] & ServerEntityFields; +}; +``` + +### EntityHandler + +```typescript +/** Entity handler providing CRUD operations for a specific entity type. */ +interface EntityHandler { + /** Lists records with optional pagination and sorting. Max 5,000 per request. */ + list( + sort?: SortField, + limit?: number, + skip?: number, + fields?: K[] + ): Promise[]>; + + /** Filters records based on a query. Max 5,000 per request. */ + filter( + query: Partial, + sort?: SortField, + limit?: number, + skip?: number, + fields?: K[] + ): Promise[]>; + + /** Gets a single record by ID. */ + get(id: string): Promise; + + /** Creates a new record. */ + create(data: Partial): Promise; + + /** Updates an existing record. */ + update(id: string, data: Partial): Promise; + + /** Deletes a single record by ID. */ + delete(id: string): Promise; + + /** Deletes multiple records matching a query. */ + deleteMany(query: Partial): Promise; + + /** Creates multiple records in a single request. */ + bulkCreate(data: Partial[]): Promise; + + /** + * Updates multiple records matching a query using MongoDB update operators. + * @param query - Filter to select which records to update. + * @param data - MongoDB update operator object (e.g., `{ $set: { field: value } }`). + */ + updateMany(query: Partial, data: Record>): Promise; + + /** Updates multiple records by ID, each with its own update data. */ + bulkUpdate(data: (Partial & { id: string })[]): Promise; + + /** Imports records from a file (frontend only). */ + importEntities(file: File): Promise>; + + /** Subscribes to realtime updates. Returns unsubscribe function. */ + subscribe(callback: RealtimeCallback): () => void; +} +``` + +### EntitiesModule + +```typescript +/** Entities module: typed registry keys get typed handlers; dynamic access remains untyped. */ +type EntitiesModule = TypedEntitiesModule & DynamicEntitiesModule; + +type TypedEntitiesModule = { + [K in keyof EntityTypeRegistry]: EntityHandler; +}; + +type DynamicEntitiesModule = { + [entityName: string]: EntityHandler; +}; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/functions.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/functions.md new file mode 100644 index 0000000000000000000000000000000000000000..54ac09dbfebfa478aed6c74e002ad8b8a1b31b4d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/functions.md @@ -0,0 +1,291 @@ +# Functions Module + +Invoke custom backend functions via `base44.functions`. + +## Contents +- [Method](#method) +- [Invoking Functions](#invoking-functions) (Frontend, File Upload, Service Role, REST API) +- [Writing Backend Functions](#writing-backend-functions) (Basic, Service Role, Secrets, Errors) +- [Setup Requirements](#setup-requirements) +- [Authentication Modes](#authentication-modes) + +## Methods + +### `invoke` + +```javascript +base44.functions.invoke(functionName, data?): Promise +``` + +- `functionName`: Name of the backend function +- `data`: Optional object of parameters (sent as JSON, or multipart if contains File objects) +- Returns: Whatever the function returns + +### `fetch` + +```javascript +base44.functions.fetch(path, init?): Promise +``` + +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. + +- `path`: Function path (e.g., `/streaming_demo` or `/my-function/endpoint`) +- `init`: Optional native fetch options (`RequestInit`) +- Returns: Native `Response` object + +## Invoking Functions + +### From Frontend + +```javascript +const result = await base44.functions.invoke("processOrder", { + orderId: "order-123", + action: "ship" +}); + +console.log(result); +``` + +### Streaming Response (using fetch) + +```javascript +// Use fetch() for streaming responses (SSE, chunked text, etc.) +const response = await base44.functions.fetch("/stream-data", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ prompt: "Tell me a story" }) +}); + +// Read as a stream +const reader = response.body.getReader(); +const decoder = new TextDecoder(); +while (true) { + const { done, value } = await reader.read(); + if (done) break; + console.log(decoder.decode(value)); +} +``` + +### Custom HTTP Methods (using fetch) + +```javascript +// PUT, PATCH, DELETE, or other methods +const response = await base44.functions.fetch("/my-resource/123", { + method: "DELETE" +}); +console.log(response.status); // 204 +``` + +### With File Upload + +```javascript +const fileInput = document.querySelector('input[type="file"]'); +const file = fileInput.files[0]; + +// Automatically uses multipart/form-data when File objects present +const result = await base44.functions.invoke("uploadDocument", { + file: file, + category: "invoices" +}); +``` + +### With Service Role (Backend) + +```javascript +// Inside another backend function +const result = await base44.asServiceRole.functions.invoke("adminTask", { + userId: "user-123" +}); +``` + +### Via REST API (curl) + +Functions can be called via HTTP POST to your app domain: + +```bash +curl -X POST "https:///functions/" \ + -H "Content-Type: application/json" \ + -d '{"key": "value"}' +``` + +## Writing Backend Functions + +Backend functions run on Deno. Must export using `Deno.serve()`. + +### Required Directory Structure + +Each function must be in its own subdirectory under `base44/functions/` with a configuration file: + +``` +base44/ + functions/ + process-order/ # kebab-case directory name + function.jsonc # required configuration + index.ts # entry point +``` + +**function.jsonc:** +```jsonc +{ + "name": "process-order", + "entry": "index.ts" +} +``` + +For complete setup and deployment instructions, see [functions-create.md](../../base44-cli/references/functions-create.md) in base44-cli. + +### Basic Structure + +```javascript +// base44/functions/process-order/index.ts +import { createClientFromRequest } from "npm:@base44/sdk"; + +Deno.serve(async (req) => { + // Get authenticated client from request + const base44 = createClientFromRequest(req); + + // Parse input + const { orderId, action } = await req.json(); + + // Your logic here + const order = await base44.entities.Orders.get(orderId); + + // Return response + return Response.json({ + success: true, + order: order + }); +}); +``` + +### With Service Role Access + +```javascript +import { createClientFromRequest } from "npm:@base44/sdk"; + +Deno.serve(async (req) => { + const base44 = createClientFromRequest(req); + + // Check user is authenticated + const user = await base44.auth.me(); + if (!user) { + return Response.json({ error: "Unauthorized" }, { status: 401 }); + } + + // Use service role for admin operations + const allOrders = await base44.asServiceRole.entities.Orders.list(); + + return Response.json({ orders: allOrders }); +}); +``` + +### Using Secrets + +```javascript +Deno.serve(async (req) => { + // Access environment variables (configured in app settings) + const apiKey = Deno.env.get("STRIPE_API_KEY"); + + const response = await fetch("https://api.stripe.com/v1/charges", { + headers: { + "Authorization": `Bearer ${apiKey}` + } + }); + + return Response.json(await response.json()); +}); +``` + +### Error Handling + +```javascript +import { createClientFromRequest } from "npm:@base44/sdk"; + +Deno.serve(async (req) => { + try { + const base44 = createClientFromRequest(req); + const { orderId } = await req.json(); + + const order = await base44.entities.Orders.get(orderId); + if (!order) { + return Response.json( + { error: "Order not found" }, + { status: 404 } + ); + } + + return Response.json({ order }); + + } catch (error) { + return Response.json( + { error: error.message }, + { status: 500 } + ); + } +}); +``` + +## Setup Requirements + +1. Enable Backend Functions in app settings (requires appropriate plan) +2. Create function files in `/functions` folder +3. Configure secrets via app dashboard for API keys + +## Authentication Modes + +| Mode | Context | Permissions | +|------|---------|-------------| +| User | `base44.functions.invoke()` | Runs under calling user's permissions | +| Service Role | `base44.asServiceRole.functions.invoke()` | Admin-level access | + +Inside the function, use `createClientFromRequest(req)` to get a client that inherits the caller's auth context. + +## Type Definitions + +**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. + +```typescript +/** + * Registry of function names. + * Augment this interface to enable autocomplete for function names. + * Typically populated by the Base44 CLI type generator. + */ +interface FunctionNameRegistry {} + +/** + * Function name type - uses registry keys if augmented, otherwise string. + */ +type FunctionName = keyof FunctionNameRegistry extends never ? string : keyof FunctionNameRegistry; + +/** + * Options for functions.fetch(). Uses native fetch options directly. + */ +type FunctionsFetchInit = RequestInit; + +/** Functions module for invoking custom backend functions. */ +interface FunctionsModule { + /** + * Invokes a custom backend function by name. + * + * If any parameter is a File object, the request will automatically be + * sent as multipart/form-data. Otherwise, it will be sent as JSON. + * + * @param functionName - The name of the function to invoke. + * @param data - Optional object containing named parameters for the function. + * @returns Promise resolving to the function's response. + */ + invoke(functionName: FunctionName, data?: Record): Promise; + + /** + * Performs a direct HTTP request to a backend function path and returns the native Response. + * + * Use for streaming responses (SSE, chunked text), custom HTTP methods, + * or when you need raw access to the response. + * + * @param path - Function path, e.g. `/streaming_demo` or `/my-function/endpoint` + * @param init - Optional native fetch options. + * @returns Promise resolving to a native fetch Response. + */ + fetch(path: string, init?: FunctionsFetchInit): Promise; +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/integrations.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/integrations.md new file mode 100644 index 0000000000000000000000000000000000000000..9a9d5526920247df51e909639e054c109cc5fb7f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/integrations.md @@ -0,0 +1,375 @@ +# Integrations Module + +Access third-party services via `base44.integrations`. + +## Types of Integrations + +1. **Core/Built-in**: AI, email, file uploads (available by default) +2. **Catalog integrations**: Pre-built connectors from Base44 catalog +3. **Custom integrations**: Your own OpenAPI-based integrations + +## Accessing Integrations + +```javascript +// Core integrations +base44.integrations.Core.FunctionName(params) + +// Custom integrations +base44.integrations.custom.call(slug, operationId, params) +``` + +## Core Integrations + +### InvokeLLM (AI Text Generation) + +Generate text or structured JSON data using AI models. + +```javascript +// Basic prompt - returns string +const response = await base44.integrations.Core.InvokeLLM({ + prompt: "Summarize this text: ..." +}); + +// With internet context (uses Google Search, Maps, News) +const response = await base44.integrations.Core.InvokeLLM({ + prompt: "What's the current weather in NYC?", + add_context_from_internet: true +}); + +// Structured JSON response - returns object +const response = await base44.integrations.Core.InvokeLLM({ + prompt: "Analyze the sentiment of: 'Great product but slow shipping'", + response_json_schema: { + type: "object", + properties: { + sentiment: { type: "string", enum: ["positive", "negative", "mixed"] }, + score: { type: "number", description: "Score from 1-10" }, + key_points: { type: "array", items: { type: "string" } } + } + } +}); +// Returns: { sentiment: "mixed", score: 7, key_points: ["great product", "slow shipping"] } + +// With file attachments (uploaded via UploadFile) +const response = await base44.integrations.Core.InvokeLLM({ + prompt: "Describe what's in this image", + file_urls: ["https://...uploaded_image.png"] +}); +``` + +**Parameters:** +- `prompt` (string, required): The prompt text to send to the model +- `add_context_from_internet` (boolean, optional): If true, uses Google Search/Maps/News for real-time context +- `response_json_schema` (object, optional): JSON schema for structured output +- `file_urls` (string[], optional): URLs of uploaded files for context + +### GenerateImage + +Create AI-generated images from text prompts. + +```javascript +const { url } = await base44.integrations.Core.GenerateImage({ + prompt: "A serene mountain landscape with a lake" +}); +console.log(url); // https://...generated_image.png +``` + +### SendEmail + +Send emails to registered users. Every app gets this integration (no plan upgrade required). + +```javascript +await base44.integrations.Core.SendEmail({ + to: "user@example.com", + subject: "Welcome!", + body: "

Hello

Welcome to our app.

", + from_name: "My App" // optional, defaults to app name +}); +``` + +**Parameters:** +- `to` (string, required): Recipient email address +- `subject` (string, required): Email subject line +- `body` (string, required): Plain text or HTML email body +- `from_name` (string, optional): Sender name displayed to recipient + +**Limitations:** +- 1 credit per email (2 credits with custom domain) + +### UploadFile (Public) + +Upload files to public storage. + +```javascript +const fileInput = document.querySelector('input[type="file"]'); +const { file_url } = await base44.integrations.Core.UploadFile({ + file: fileInput.files[0] +}); +console.log(file_url); // https://...uploaded_file.pdf +``` + +### UploadPrivateFile + +Upload files to private storage that requires a signed URL to access. + +```javascript +const { file_uri } = await base44.integrations.Core.UploadPrivateFile({ + file: fileInput.files[0] +}); +console.log(file_uri); // "private/user123/document.pdf" + +// Create a signed URL to access the file +const { signed_url } = await base44.integrations.Core.CreateFileSignedUrl({ + file_uri, + expires_in: 3600 // URL expires in 1 hour (default: 300 seconds) +}); +console.log(signed_url); // Temporary URL to access the private file +``` + +### CreateFileSignedUrl + +Generate temporary access links for private files. + +```javascript +const { signed_url } = await base44.integrations.Core.CreateFileSignedUrl({ + file_uri: "private/user123/document.pdf", + expires_in: 7200 // 2 hours +}); +``` + +**Parameters:** +- `file_uri` (string, required): URI from UploadPrivateFile +- `expires_in` (number, optional): Expiration time in seconds (default: 300) + +### ExtractDataFromUploadedFile + +Extract structured data from uploaded files using AI. + +```javascript +// First upload the file +const { file_url } = await base44.integrations.Core.UploadFile({ file }); + +// Then extract structured data +const result = await base44.integrations.Core.ExtractDataFromUploadedFile({ + file_url, + json_schema: { + type: "object", + properties: { + invoice_number: { type: "string" }, + total_amount: { type: "number" }, + date: { type: "string" }, + vendor_name: { type: "string" } + } + } +}); +console.log(result); // { invoice_number: "INV-12345", total_amount: 1250.00, ... } +``` + +## Custom Integrations + +Custom integrations allow workspace administrators to connect any external API by importing an OpenAPI specification. Use `base44.integrations.custom.call()` to invoke them. + +### Syntax + +```javascript +const response = await base44.integrations.custom.call( + slug, // Integration identifier (set by admin) + operationId, // Endpoint in "method:path" format (e.g. "get:/contacts", "post:/repos/{owner}/{repo}/issues") + params // Optional: payload, pathParams, queryParams +); +``` + +### Examples + +```javascript +// GET request with query params +const response = await base44.integrations.custom.call( + "my-crm", + "get:/contacts", + { queryParams: { limit: 10, status: "active" } } +); + +// POST request with body +const response = await base44.integrations.custom.call( + "my-crm", + "post:/contacts", + { payload: { name: "John Doe", email: "john@example.com" } } +); + +// Request with path parameters +const response = await base44.integrations.custom.call( + "github", + "post:/repos/{owner}/{repo}/issues", + { + pathParams: { owner: "myorg", repo: "myrepo" }, + payload: { title: "Bug report", body: "Something is broken" } + } +); +``` + +### Response Structure + +```javascript +{ + success: true, // Whether external API returned 2xx + status_code: 200, // HTTP status code + data: { ... } // Response from external API +} +``` + +## Requirements + +- **Core integrations**: Available on all plans +- **Catalog/Custom integrations**: Require Builder plan or higher + +## Type Definitions + +### Core Integration Parameters + +```typescript +/** Parameters for the InvokeLLM function. */ +interface InvokeLLMParams { + /** The prompt text to send to the model. */ + prompt: string; + /** If true, uses Google Search/Maps/News for real-time context. */ + add_context_from_internet?: boolean; + /** JSON schema for structured output. If provided, returns object instead of string. */ + response_json_schema?: object; + /** File URLs (from UploadFile) to provide as context. */ + file_urls?: string[]; +} + +/** Parameters for the GenerateImage function. */ +interface GenerateImageParams { + /** Description of the image to generate. */ + prompt: string; +} + +/** Result from GenerateImage. */ +interface GenerateImageResult { + /** URL of the generated image. */ + url: string; +} + +/** Parameters for the UploadFile function. */ +interface UploadFileParams { + /** The file object to upload. */ + file: File; +} + +/** Result from UploadFile. */ +interface UploadFileResult { + /** URL of the uploaded file. */ + file_url: string; +} + +/** Parameters for the SendEmail function. */ +interface SendEmailParams { + /** Recipient email address. */ + to: string; + /** Email subject line. */ + subject: string; + /** Plain text or HTML email body. */ + body: string; + /** Sender name (defaults to app name). */ + from_name?: string; +} + +/** Parameters for ExtractDataFromUploadedFile. */ +interface ExtractDataFromUploadedFileParams { + /** URL of the uploaded file. */ + file_url: string; + /** JSON schema defining fields to extract. */ + json_schema: object; +} + +/** Parameters for UploadPrivateFile. */ +interface UploadPrivateFileParams { + /** The file object to upload. */ + file: File; +} + +/** Result from UploadPrivateFile. */ +interface UploadPrivateFileResult { + /** URI of the private file (used for signed URLs). */ + file_uri: string; +} + +/** Parameters for CreateFileSignedUrl. */ +interface CreateFileSignedUrlParams { + /** URI from UploadPrivateFile. */ + file_uri: string; + /** Expiration time in seconds (default: 300). */ + expires_in?: number; +} + +/** Result from CreateFileSignedUrl. */ +interface CreateFileSignedUrlResult { + /** Temporary signed URL to access the file. */ + signed_url: string; +} +``` + +### CoreIntegrations + +```typescript +/** Core package containing built-in Base44 integration functions. */ +interface CoreIntegrations { + InvokeLLM(params: InvokeLLMParams): Promise; + GenerateImage(params: GenerateImageParams): Promise; + UploadFile(params: UploadFileParams): Promise; + SendEmail(params: SendEmailParams): Promise; + ExtractDataFromUploadedFile(params: ExtractDataFromUploadedFileParams): Promise; + UploadPrivateFile(params: UploadPrivateFileParams): Promise; + CreateFileSignedUrl(params: CreateFileSignedUrlParams): Promise; +} +``` + +### Custom Integrations + +```typescript +/** Parameters for calling a custom integration method. */ +interface CustomIntegrationCallParams { + /** Request body payload. */ + payload?: Record; + /** Path parameters to substitute in the URL. For example, { owner: "user", repo: "repo" }. */ + pathParams?: Record; + /** Query string parameters. */ + queryParams?: Record; +} + +/** Response from a custom integration call. */ +interface CustomIntegrationCallResponse { + /** Whether the external API returned a 2xx status code. */ + success: boolean; + /** The HTTP status code from the external API. */ + status_code: number; + /** The response data from the external API. */ + data: any; +} + +/** Module for calling custom pre-configured API integrations. */ +interface CustomIntegrationsModule { + /** + * Call a custom integration method. + * @param slug - The integration's unique identifier (set by workspace admin). + * @param operationId - The endpoint in "method:path" format (e.g. "get:/contacts", "post:/users/{id}"). + * @param params - Optional payload, pathParams, queryParams. + */ + call(slug: string, operationId: string, params?: CustomIntegrationCallParams): Promise; +} +``` + +### IntegrationsModule + +```typescript +/** Integrations module for calling integration methods. */ +type IntegrationsModule = { + /** Core package with built-in integrations. */ + Core: CoreIntegrations; + /** Custom integrations module. */ + custom: CustomIntegrationsModule; + /** Additional integration packages (dynamic). */ + [packageName: string]: any; +}; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/sso.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/sso.md new file mode 100644 index 0000000000000000000000000000000000000000..c7a5d70f53c19c079c6e61aee1f42ea100011d60 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/sso.md @@ -0,0 +1,75 @@ +# SSO Module + +Single Sign-On (SSO) support for authenticating Base44 users with external systems. Available via `base44.asServiceRole.sso`. + +> **Backend only**: This module requires service role access and can only be used in Base44-hosted backend functions. + +## Methods + +| Method | Signature | Description | +|--------|-----------|-------------| +| `getAccessToken(userId)` | `Promise` | Get an SSO access token for a specific user | + +## Examples + +### Get SSO Access Token + +```javascript +import { createClientFromRequest } from "npm:@base44/sdk"; + +Deno.serve(async (req) => { + const base44 = createClientFromRequest(req); + + // Get the current user + const user = await base44.auth.me(); + if (!user) { + return Response.json({ error: "Unauthorized" }, { status: 401 }); + } + + // Get SSO access token for this user + const { access_token } = await base44.asServiceRole.sso.getAccessToken(user.id); + + // Use the token to authenticate with an external system + return Response.json({ ssoToken: access_token }); +}); +``` + +### Get Token for a Specific User (Service Role) + +```javascript +Deno.serve(async (req) => { + const base44 = createClientFromRequest(req); + const { userId } = await req.json(); + + // Get SSO token for any user (service role has access to all users) + const { access_token } = await base44.asServiceRole.sso.getAccessToken(userId); + + return Response.json({ token: access_token }); +}); +``` + +## Use Cases + +- Authenticating Base44 users with external SaaS tools (e.g., Okta, Azure AD) +- Building SSO bridges between Base44 and third-party systems +- Generating tokens for backend-to-backend authenticated calls + +## Type Definitions + +```typescript +/** Response from the SSO access token endpoint. */ +interface SsoAccessTokenResponse { + /** The SSO access token for the specified user. */ + access_token: string; +} + +/** SSO module for managing SSO authentication (service role only). */ +interface SsoModule { + /** + * Gets an SSO access token for a specific user. + * @param userid - The Base44 user ID to get the SSO token for. + * @returns Promise resolving to the SSO access token response. + */ + getAccessToken(userid: string): Promise; +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/users.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/users.md new file mode 100644 index 0000000000000000000000000000000000000000..4205b0672d34ee09783b432d6447e1e38053187a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/users.md @@ -0,0 +1,82 @@ +# Users Module + +Invite users to the app via `base44.users`. + +## Contents +- [Methods](#methods) +- [Examples](#examples) (Invite User) +- [Roles](#roles) +- [Notes](#notes) + +## Methods + +| Method | Signature | Description | +|--------|-----------|-------------| +| `inviteUser(user_email, role)` | `Promise` | Invite a user to the app | + +## Examples + +### Invite User + +```javascript +// Invite a user with "user" role +await base44.users.inviteUser("newuser@example.com", "user"); + +// Invite an admin +await base44.users.inviteUser("admin@example.com", "admin"); +``` + +### Invite Multiple Users + +```javascript +const usersToInvite = [ + { email: "user1@example.com", role: "user" }, + { email: "user2@example.com", role: "user" }, + { email: "manager@example.com", role: "admin" } +]; + +for (const user of usersToInvite) { + await base44.users.inviteUser(user.email, user.role); + console.log(`Invited ${user.email} as ${user.role}`); +} +``` + +## Roles + +The `role` parameter must be one of: + +| Role | Description | +|------|-------------| +| `"user"` | Standard user with default permissions | +| `"admin"` | Administrator with elevated permissions | + +**Note:** Only `"user"` and `"admin"` are valid role values. An error will be thrown if you pass any other value. + +## Notes + +- **Email invitation**: The invited user receives an email with a link to join the app +- **Duplicate handling**: Inviting an existing user will re-send the invitation +- **Also available in auth**: `base44.auth.inviteUser()` provides the same functionality +- **Role validation**: Only `"user"` or `"admin"` are accepted + +```javascript +// These are equivalent: +await base44.users.inviteUser("newuser@example.com", "user"); +await base44.auth.inviteUser("newuser@example.com", "user"); +``` + +## Type Definitions + +```typescript +/** Users module for inviting users to the app. */ +interface UsersModule { + /** + * Invite a user to the application. + * @param user_email - User's email address. + * @param role - User's role ('user' or 'admin'). + * @returns Promise resolving when the invitation is sent. + * @throws Error if role is not 'user' or 'admin'. + */ + inviteUser(user_email: string, role: "user" | "admin"): Promise; +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..497ca7bdd264af9c95cc74731b5de30f65ecf491 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Base44 Troubleshooter" + short_description: "Debug Base44 production issues with function logs" + default_prompt: "Use Base44 troubleshooting guidance to inspect logs and diagnose this production issue." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/references/project-logs.md b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/references/project-logs.md new file mode 100644 index 0000000000000000000000000000000000000000..b58fa2ada862f188d482442d98ef20b9affaa19c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/references/project-logs.md @@ -0,0 +1,57 @@ +# base44 logs + +Fetch function logs for this app. + +## Syntax + +```bash +npx base44 logs [options] +``` + +## Options + +| Option | Description | Required | +|--------|-------------|----------| +| `--function ` | Filter by function name(s), comma-separated. If omitted, fetches logs for all project functions | No | +| `--since ` | Show logs from this time (ISO format) | No | +| `--until ` | Show logs until this time (ISO format) | No | +| `--level ` | Filter by log level: `log`, `info`, `warn`, `error`, `debug` | No | +| `-n, --limit ` | Number of results to return (1-1000, default: 50) | No | +| `--order ` | Sort order: `asc` or `desc` (default: `desc`) | No | + +## Examples + +```bash +# Fetch logs for all project functions (last 50 entries) +npx base44 logs + +# Fetch only errors +npx base44 logs --level error + +# Fetch logs for a specific function +npx base44 logs --function my-function + +# Fetch logs for multiple functions +npx base44 logs --function send-email,process-payment + +# Fetch logs since a specific time +npx base44 logs --since 2024-01-15T10:00:00 + +# Fetch logs within a time range +npx base44 logs --since 2024-01-15T10:00:00 --until 2024-01-15T12:00:00 + +# Fetch last 100 log entries in ascending order +npx base44 logs -n 100 --order asc + +# Last 10 errors for a specific function +npx base44 logs --function myFunction --level error --limit 10 +``` + +## Notes + +- **Authentication required.** You must be logged in before fetching logs. +- **Project context required.** Must be run from the project directory (where `base44/.app.jsonc` exists). +- When multiple functions are specified, logs are merged and sorted by timestamp. +- If `--function` is omitted, logs are fetched for **all functions** defined in `base44/config.jsonc`. +- The `--limit` applies after merging logs from all specified functions. +- The `--since` and `--until` values are normalized to UTC if no timezone is provided (appends `Z`). diff --git a/data/.codex/.codex/.tmp/plugins/plugins/carta-crm/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/carta-crm/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..18c70df3a44210d842e572e35a548b29c9f8f20a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/carta-crm/.codex-plugin/plugin.json @@ -0,0 +1,32 @@ +{ + "name": "carta-crm", + "version": "1.0.3", + "description": "Carta CRM helps investment teams stay on top of deal flow by keeping deals, companies, and relationships in...", + "author": { + "name": "Carta Inc.", + "url": "https://carta.com" + }, + "repository": "https://github.com/openai/plugins", + "license": "MIT", + "keywords": [], + "apps": "./.app.json", + "interface": { + "displayName": "Carta CRM", + "shortDescription": "Carta CRM helps investment teams stay on top of deal flow by keeping deals, companies, and relationships in...", + "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.", + "developerName": "Carta Inc.", + "category": "Business & Operations", + "capabilities": [], + "defaultPrompt": [ + "Find the latest relationship context in Carta CRM" + ], + "screenshots": [], + "websiteURL": "https://carta.com", + "privacyPolicyURL": "https://carta.com/legal/privacy/privacy-policy/", + "termsOfServiceURL": "https://carta.com/legal/terms-agreements/terms-service/", + "composerIcon": "./assets/logo.png", + "logo": "./assets/logo.png", + "logoDark": "./assets/logo-dark.png" + }, + "homepage": "https://carta.com" +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..bd6458b16d83a29231f5ef7b3f405ce090611982 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/.codex-plugin/plugin.json @@ -0,0 +1,47 @@ +{ + "name": "cloudflare", + "version": "0.1.2", + "description": "Cloudflare platform plugin with curated skills for Workers, Wrangler, and Agents SDK plus the official Cloudflare API MCP server.", + "author": { + "name": "Cloudflare", + "url": "https://workers.cloudflare.com/" + }, + "homepage": "https://workers.cloudflare.com/", + "repository": "https://github.com/openai/plugins", + "license": "MIT", + "keywords": [ + "cloudflare", + "workflow", + "deployment", + "edge-functions", + "edge", + "analytics", + "wrangler", + "agents-sdk", + "serverless", + "ai-gateway" + ], + "skills": "./skills/", + "mcpServers": "./.mcp.json", + "interface": { + "displayName": "Cloudflare", + "shortDescription": "Cloudflare platform guidance with official MCP", + "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.", + "developerName": "Cloudflare", + "category": "Developer Tools", + "capabilities": [ + "Interactive", + "Write" + ], + "websiteURL": "https://workers.cloudflare.com/", + "privacyPolicyURL": "https://www.cloudflare.com/privacypolicy/", + "termsOfServiceURL": "https://www.cloudflare.com/website-terms/", + "defaultPrompt": [ + "Help me choose the right Cloudflare product, configure Wrangler, and use Cloudflare MCP to inspect or deploy this project" + ], + "composerIcon": "./assets/cloudflare-small.svg", + "logo": "./assets/cloudflare.png", + "screenshots": [], + "brandColor": "#F48120" + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/assets/cloudflare-small.svg b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/assets/cloudflare-small.svg new file mode 100644 index 0000000000000000000000000000000000000000..7feedbc2b37ff9f28f81d30aff52e605090bee86 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/assets/cloudflare-small.svg @@ -0,0 +1,3 @@ + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-agent.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-agent.md new file mode 100644 index 0000000000000000000000000000000000000000..08e07cf0adffd1664f4ab4f4dd48b709ed8fe144 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-agent.md @@ -0,0 +1,40 @@ +--- +description: Build an AI agent on Cloudflare using the Agents SDK +argument-hint: [agent-description] +allowed-tools: [Read, Glob, Grep, Bash, Write, Edit, WebFetch] +--- + +# Build AI Agent on Cloudflare + +This command helps you build AI agents using the Cloudflare Agents SDK with state management, real-time WebSockets, scheduled tasks, and tool integration. + +## Arguments + +The user invoked this command with: $ARGUMENTS + +## Instructions + +When this command is invoked: + +1. Read the skill file at `skills/building-ai-agent-on-cloudflare/SKILL.md` for core guidance +2. Reference `skills/building-ai-agent-on-cloudflare/references/examples.md` for templates +3. Use `skills/building-ai-agent-on-cloudflare/references/agent-patterns.md` for tool calling and patterns +4. Use `skills/building-ai-agent-on-cloudflare/references/state-patterns.md` for state management +5. Consult `skills/building-ai-agent-on-cloudflare/references/troubleshooting.md` for common issues + +## Capabilities + +- Stateful AI agents with persistent memory +- Real-time WebSocket communication +- Scheduled tasks and cron jobs +- Tool integration and function calling +- Multi-agent orchestration +- RAG (Retrieval Augmented Generation) patterns + +## Example Usage + +``` +/cloudflare:build-agent a customer support chatbot +/cloudflare:build-agent real-time coding assistant with WebSocket +/cloudflare:build-agent multi-agent workflow orchestrator +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-mcp.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-mcp.md new file mode 100644 index 0000000000000000000000000000000000000000..afd2273e03dee8c27874db16a9c12bbe7ab0172b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-mcp.md @@ -0,0 +1,38 @@ +--- +description: Build a remote MCP server on Cloudflare with tools and OAuth +argument-hint: [mcp-description] +allowed-tools: [Read, Glob, Grep, Bash, Write, Edit, WebFetch] +--- + +# Build MCP Server on Cloudflare + +This command helps you build remote Model Context Protocol (MCP) servers on Cloudflare with tools, OAuth authentication, and production deployment. + +## Arguments + +The user invoked this command with: $ARGUMENTS + +## Instructions + +When this command is invoked: + +1. Read the skill file at `skills/building-mcp-server-on-cloudflare/SKILL.md` for core guidance +2. Reference `skills/building-mcp-server-on-cloudflare/references/examples.md` for official templates +3. Use `skills/building-mcp-server-on-cloudflare/references/oauth-setup.md` for security and OAuth +4. Consult `skills/building-mcp-server-on-cloudflare/references/troubleshooting.md` for common issues + +## Capabilities + +- Remote MCP server deployment on Cloudflare Workers +- OAuth 2.0 authentication setup +- Tool definition and implementation +- Production-ready deployment patterns +- Integration with Codex and other MCP clients + +## Example Usage + +``` +/cloudflare:build-mcp a GitHub integration server +/cloudflare:build-mcp database query tool with OAuth +/cloudflare:build-mcp file management MCP server +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/LICENSE.txt b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..13e25df86ce06eb6488e6a6bc5c5847f5dedc352 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/LICENSE.txt @@ -0,0 +1,201 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf of + any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don\'t include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..846e882e387e7e7d7d1e05bdf12783ee71ac996d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/SKILL.md @@ -0,0 +1,155 @@ +--- +name: agents-sdk +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. +--- + +# Cloudflare Agents SDK + +Your knowledge of the Agents SDK may be outdated. **Prefer retrieval over pre-training** for any Agents SDK task. + +## Retrieval Sources + +Fetch current docs from `https://github.com/cloudflare/agents/tree/main/docs` before implementing. + +| Topic | Doc | Use for | +|-------|-----|---------| +| Getting started | `docs/getting-started.md` | First agent, project setup | +| State | `docs/state.md` | `setState`, `validateStateChange`, persistence | +| Routing | `docs/routing.md` | URL patterns, `routeAgentRequest`, `basePath` | +| Callable methods | `docs/callable-methods.md` | `@callable`, RPC, streaming, timeouts | +| Scheduling | `docs/scheduling.md` | `schedule()`, `scheduleEvery()`, cron | +| Workflows | `docs/workflows.md` | `AgentWorkflow`, durable multi-step tasks | +| HTTP/WebSockets | `docs/http-websockets.md` | Lifecycle hooks, hibernation | +| Email | `docs/email.md` | Email routing, secure reply resolver | +| MCP client | `docs/mcp-client.md` | Connecting to MCP servers | +| MCP server | `docs/mcp-servers.md` | Building MCP servers with `McpAgent` | +| Client SDK | `docs/client-sdk.md` | `useAgent`, `useAgentChat`, React hooks | +| Human-in-the-loop | `docs/human-in-the-loop.md` | Approval flows, pausing workflows | +| Resumable streaming | `docs/resumable-streaming.md` | Stream recovery on disconnect | + +Cloudflare docs: https://developers.cloudflare.com/agents/ + +## Capabilities + +The Agents SDK provides: + +- **Persistent state** - SQLite-backed, auto-synced to clients +- **Callable RPC** - `@callable()` methods invoked over WebSocket +- **Scheduling** - One-time, recurring (`scheduleEvery`), and cron tasks +- **Workflows** - Durable multi-step background processing via `AgentWorkflow` +- **MCP integration** - Connect to MCP servers or build your own with `McpAgent` +- **Email handling** - Receive and reply to emails with secure routing +- **Streaming chat** - `AIChatAgent` with resumable streams +- **React hooks** - `useAgent`, `useAgentChat` for client apps + +## FIRST: Verify Installation + +```bash +npm ls agents # Should show agents package +``` + +If not installed: +```bash +npm install agents +``` + +## Wrangler Configuration + +```jsonc +{ + "durable_objects": { + "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }] +} +``` + +## Agent Class + +```typescript +import { Agent, routeAgentRequest, callable } from "agents"; + +type State = { count: number }; + +export class Counter extends Agent { + initialState = { count: 0 }; + + // Validation hook - runs before state persists (sync, throwing rejects the update) + validateStateChange(nextState: State, source: Connection | "server") { + if (nextState.count < 0) throw new Error("Count cannot be negative"); + } + + // Notification hook - runs after state persists (async, non-blocking) + onStateUpdate(state: State, source: Connection | "server") { + console.log("State updated:", state); + } + + @callable() + increment() { + this.setState({ count: this.state.count + 1 }); + return this.state.count; + } +} + +export default { + fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 }) +}; +``` + +## Routing + +Requests route to `/agents/{agent-name}/{instance-name}`: + +| Class | URL | +|-------|-----| +| `Counter` | `/agents/counter/user-123` | +| `ChatRoom` | `/agents/chat-room/lobby` | + +Client: `useAgent({ agent: "Counter", name: "user-123" })` + +## Core APIs + +| Task | API | +|------|-----| +| Read state | `this.state.count` | +| Write state | `this.setState({ count: 1 })` | +| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` | +| Schedule (delay) | `await this.schedule(60, "task", payload)` | +| Schedule (cron) | `await this.schedule("0 * * * *", "task", payload)` | +| Schedule (interval) | `await this.scheduleEvery(30, "poll")` | +| RPC method | `@callable() myMethod() { ... }` | +| Streaming RPC | `@callable({ streaming: true }) stream(res) { ... }` | +| Start workflow | `await this.runWorkflow("ProcessingWorkflow", params)` | + +## React Client + +```tsx +import { useAgent } from "agents/react"; + +function App() { + const [state, setLocalState] = useState({ count: 0 }); + + const agent = useAgent({ + agent: "Counter", + name: "my-instance", + onStateUpdate: (newState) => setLocalState(newState), + onIdentity: (name, agentType) => console.log(`Connected to ${name}`) + }); + + return ( + + ); +} +``` + +## References + +- **[references/workflows.md](references/workflows.md)** - Durable Workflows integration +- **[references/callable.md](references/callable.md)** - RPC methods, streaming, timeouts +- **[references/state-scheduling.md](references/state-scheduling.md)** - State persistence, scheduling +- **[references/streaming-chat.md](references/streaming-chat.md)** - AIChatAgent, resumable streams +- **[references/mcp.md](references/mcp.md)** - MCP server integration +- **[references/email.md](references/email.md)** - Email routing and handling +- **[references/codemode.md](references/codemode.md)** - Code Mode (experimental) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4d15459e460fbf008b6c4c6848e7cdc0e8b9fb1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/agents/openai.yaml @@ -0,0 +1,6 @@ +interface: + display_name: "Agents SDK" + short_description: "Build stateful agents on Cloudflare Workers" + icon_small: "./assets/cloudflare-small.svg" + icon_large: "./assets/cloudflare.png" + default_prompt: "Use the Cloudflare Agents SDK to design or implement this agent on Workers with the right state, routing, and workflow patterns." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/assets/cloudflare-small.svg b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/assets/cloudflare-small.svg new file mode 100644 index 0000000000000000000000000000000000000000..7feedbc2b37ff9f28f81d30aff52e605090bee86 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/assets/cloudflare-small.svg @@ -0,0 +1,3 @@ + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/callable.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/callable.md new file mode 100644 index 0000000000000000000000000000000000000000..241d30cf93740b96d879486c477fd4c166792f3a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/callable.md @@ -0,0 +1,92 @@ +# Callable Methods + +Fetch `docs/callable-methods.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation. + +## Overview + +`@callable()` exposes agent methods to clients via WebSocket RPC. + +```typescript +import { Agent, callable } from "agents"; + +export class MyAgent extends Agent { + @callable() + async greet(name: string): Promise { + return `Hello, ${name}!`; + } + + @callable() + async processData(data: unknown): Promise { + // Long-running work + return result; + } +} +``` + +## Client Usage + +```typescript +// Basic call +const greeting = await agent.call("greet", ["World"]); + +// With timeout +const result = await agent.call("processData", [data], { + timeout: 5000 // 5 second timeout +}); +``` + +## Streaming Responses + +```typescript +import { Agent, callable, StreamingResponse } from "agents"; + +export class MyAgent extends Agent { + @callable({ streaming: true }) + async streamResults(stream: StreamingResponse, query: string) { + for await (const item of fetchResults(query)) { + stream.send(JSON.stringify(item)); + } + stream.close(); + } + + @callable({ streaming: true }) + async streamWithError(stream: StreamingResponse) { + try { + // ... work + } catch (error) { + stream.error(error.message); // Signal error to client + return; + } + stream.close(); + } +} +``` + +Client with streaming: + +```typescript +await agent.call("streamResults", ["search term"], { + stream: { + onChunk: (data) => console.log("Chunk:", data), + onDone: () => console.log("Complete"), + onError: (error) => console.error("Error:", error) + } +}); +``` + +## Introspection + +```typescript +// Get list of callable methods on an agent +const methods = await agent.call("getCallableMethods", []); +// Returns: ["greet", "processData", "streamResults", ...] +``` + +## When to Use + +| Scenario | Use | +|----------|-----| +| Browser/mobile calling agent | `@callable()` | +| External service calling agent | `@callable()` | +| Worker calling agent (same codebase) | DO RPC directly | +| Agent calling another agent | `getAgentByName()` + DO RPC | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/codemode.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/codemode.md new file mode 100644 index 0000000000000000000000000000000000000000..447ceef53a254b3bf55bbabd08878548b8045e95 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/codemode.md @@ -0,0 +1,207 @@ +# Code Mode (Experimental) + +Code Mode generates executable JavaScript instead of making individual tool calls. This significantly reduces token usage and enables complex multi-tool workflows. + +## Why Code Mode? + +Traditional tool calling: +- One tool call per LLM request +- Multiple round-trips for chained operations +- High token usage for complex workflows + +Code Mode: +- LLM generates code that orchestrates multiple tools +- Single execution for complex workflows +- Self-debugging and error recovery +- Ideal for MCP server orchestration + +## Setup + +### 1. Wrangler Config + +```jsonc +{ + "name": "my-agent-worker", + "compatibility_flags": ["experimental", "enable_ctx_exports"], + "durable_objects": { + // "class_name" must match your Agent class name exactly + "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }] + }, + "migrations": [ + // Required: list all Agent classes for SQLite storage + { "tag": "v1", "new_sqlite_classes": ["MyAgent"] } + ], + "services": [ + { + "binding": "globalOutbound", + // "service" must match "name" above + "service": "my-agent-worker", + "entrypoint": "globalOutbound" + }, + { + "binding": "CodeModeProxy", + "service": "my-agent-worker", + "entrypoint": "CodeModeProxy" + } + ], + "worker_loaders": [{ "binding": "LOADER" }] +} +``` + +### 2. Export Required Classes + +```typescript +// Export the proxy for tool execution (required for codemode) +export { CodeModeProxy } from "@cloudflare/codemode/ai"; + +// Define outbound fetch handler for security filtering +export const globalOutbound = { + fetch: async (input: string | URL | RequestInfo, init?: RequestInit) => { + const url = new URL( + typeof input === "string" + ? input + : typeof input === "object" && "url" in input + ? input.url + : input.toString() + ); + // Block certain domains if needed + if (url.hostname === "blocked.example.com") { + return new Response("Not allowed", { status: 403 }); + } + return fetch(input, init); + } +}; +``` + +### 3. Install Dependencies + +```bash +npm install @cloudflare/codemode ai @ai-sdk/openai zod +``` + +### 4. Use Code Mode in Agent + +```typescript +import { Agent } from "agents"; +import { experimental_codemode as codemode } from "@cloudflare/codemode/ai"; +import { streamText, tool, convertToModelMessages } from "ai"; +import { openai } from "@ai-sdk/openai"; +import { env } from "cloudflare:workers"; +import { z } from "zod"; + +const tools = { + getWeather: tool({ + description: "Get weather for a location", + parameters: z.object({ location: z.string() }), + execute: async ({ location }) => `Weather: ${location} 72°F` + }), + sendEmail: tool({ + description: "Send an email", + parameters: z.object({ to: z.string(), subject: z.string(), body: z.string() }), + execute: async ({ to, subject, body }) => `Email sent to ${to}` + }) +}; + +export class MyAgent extends Agent { + tools = {}; + + // Method called by codemode proxy + callTool(functionName: string, args: unknown[]) { + return this.tools[functionName]?.execute?.(args, { + abortSignal: new AbortController().signal, + toolCallId: "codemode", + messages: [] + }); + } + + async onChatMessage() { + this.tools = { ...tools, ...this.mcp.getAITools() }; + + const { prompt, tools: wrappedTools } = await codemode({ + prompt: "You are a helpful assistant...", + tools: this.tools, + globalOutbound: env.globalOutbound, + loader: env.LOADER, + proxy: this.ctx.exports.CodeModeProxy({ + props: { + binding: "MyAgent", // Class name + name: this.name, // Instance name + callback: "callTool" // Method to call + } + }) + }); + + const result = streamText({ + system: prompt, + model: openai("gpt-4o"), + messages: await convertToModelMessages(this.state.messages), + tools: wrappedTools // Use wrapped tools, not original + }); + + // ... handle stream + } +} +``` + +## Generated Code Example + +When user asks "Check the weather in NYC and email me the forecast", codemode generates: + +```javascript +async function executeTask() { + const weather = await codemode.getWeather({ location: "NYC" }); + + await codemode.sendEmail({ + to: "user@example.com", + subject: "NYC Weather Forecast", + body: `Current weather: ${weather}` + }); + + return { success: true, weather }; +} +``` + +## MCP Server Orchestration + +Code Mode excels at orchestrating multiple MCP servers: + +```javascript +async function executeTask() { + // Query file system MCP + const files = await codemode.listFiles({ path: "/projects" }); + + // Query database MCP + const status = await codemode.queryDatabase({ + query: "SELECT * FROM projects WHERE name = ?", + params: [files[0].name] + }); + + // Conditional logic based on results + if (status.length === 0) { + await codemode.createTask({ + title: `Review: ${files[0].name}`, + priority: "high" + }); + } + + return { files, status }; +} +``` + +## When to Use + +| Scenario | Use Code Mode? | +|----------|---------------| +| Single tool call | No | +| Chained tool calls | Yes | +| Conditional logic across tools | Yes | +| MCP multi-server workflows | Yes | +| Token budget constrained | Yes | +| Simple Q&A chat | No | + +## Limitations + +- Experimental - API may change +- Requires Cloudflare Workers +- JavaScript execution only (Python planned) +- Requires additional wrangler config diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/email.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/email.md new file mode 100644 index 0000000000000000000000000000000000000000..0cf2b83a6d0ed1e38b2f9cbe9945091e1bf6f354 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/email.md @@ -0,0 +1,146 @@ +# Email Handling + +Fetch `docs/email.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation. + +## Overview + +Agents receive and reply to emails via Cloudflare Email Routing. + +## Wrangler Configuration + +```jsonc +{ + "durable_objects": { + "bindings": [{ "name": "EmailAgent", "class_name": "EmailAgent" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["EmailAgent"] }], + "send_email": [ + { "name": "SEB", "destination_address": "reply@yourdomain.com" } + ] +} +``` + +## Basic Email Handler + +```typescript +import { Agent } from "agents"; +import { type AgentEmail } from "agents/email"; +import PostalMime from "postal-mime"; + +export class EmailAgent extends Agent { + async onEmail(email: AgentEmail) { + const raw = await email.getRaw(); + const parsed = await PostalMime.parse(raw); + + console.log("From:", email.from); + console.log("Subject:", parsed.subject); + + await this.replyToEmail(email, { + fromName: "My Agent", + subject: `Re: ${parsed.subject}`, + body: "Thanks for your email!" + }); + } +} +``` + +## Routing Emails + +```typescript +import { routeAgentRequest, routeAgentEmail } from "agents"; +import { createAddressBasedEmailResolver } from "agents/email"; + +export default { + async email(message, env) { + await routeAgentEmail(message, env, { + resolver: createAddressBasedEmailResolver("EmailAgent") + }); + }, + + async fetch(request, env) { + return routeAgentRequest(request, env) ?? new Response("Not found", { status: 404 }); + } +}; +``` + +## Resolvers + +### Address-Based (Inbound Mail) + +Routes based on recipient address: + +```typescript +import { createAddressBasedEmailResolver } from "agents/email"; + +const resolver = createAddressBasedEmailResolver("EmailAgent"); +// support@example.com → EmailAgent, instance "support" +// NotificationAgent+user123@example.com → NotificationAgent, instance "user123" +``` + +### Secure Reply (Reply Flows) + +Verifies replies are authentic using HMAC-SHA256 signatures: + +```typescript +import { createSecureReplyEmailResolver } from "agents/email"; + +const resolver = createSecureReplyEmailResolver(env.EMAIL_SECRET, { + maxAge: 7 * 24 * 60 * 60, // 7 days (default: 30 days) + onInvalidSignature: (email, reason) => { + console.warn(`Invalid signature from ${email.from}: ${reason}`); + } +}); +``` + +Sign outbound emails to enable secure reply routing: + +```typescript +await this.replyToEmail(email, { + fromName: "My Agent", + body: "Thanks!", + secret: this.env.EMAIL_SECRET // Signs headers for secure reply routing +}); +``` + +### Catch-All (Single Instance) + +Routes all emails to one agent instance: + +```typescript +import { createCatchAllEmailResolver } from "agents/email"; + +const resolver = createCatchAllEmailResolver("EmailAgent", "default"); +``` + +### Combining Resolvers + +```typescript +async email(message, env) { + const secureReply = createSecureReplyEmailResolver(env.EMAIL_SECRET); + const addressBased = createAddressBasedEmailResolver("EmailAgent"); + + await routeAgentEmail(message, env, { + resolver: async (email, env) => { + // Try secure reply first + const result = await secureReply(email, env); + if (result) return result; + // Fall back to address-based + return addressBased(email, env); + } + }); +} +``` + +## Utilities + +```typescript +import { isAutoReplyEmail } from "agents/email"; + +async onEmail(email: AgentEmail) { + if (isAutoReplyEmail(email.headers)) { + // Skip auto-replies (vacation, out-of-office, etc.) + return; + } + // Process email... +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/mcp.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/mcp.md new file mode 100644 index 0000000000000000000000000000000000000000..127212181c8b5550ad8f82210dcbe3d62e815a16 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/mcp.md @@ -0,0 +1,154 @@ +# MCP Server Integration + +Fetch `docs/mcp-client.md` and `docs/mcp-servers.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation. + +Agents include a multi-server MCP client for connecting to external MCP servers. + +## Add an MCP Server + +```typescript +import { Agent, callable } from "agents"; + +export class MyAgent extends Agent { + @callable() + async addServer(name: string, url: string) { + // Options-based API (recommended) + const result = await this.addMcpServer(name, url, { + callbackHost: "https://my-worker.workers.dev", + transport: { headers: { Authorization: "Bearer ..." } } + }); + + if (result.state === "authenticating") { + // OAuth required - redirect user to result.authUrl + return { needsAuth: true, authUrl: result.authUrl }; + } + + return { ready: true, id: result.id }; + } +} +``` + +## Use MCP Tools + +```typescript +async onChatMessage() { + // Get AI-compatible tools from all connected MCP servers + const mcpTools = this.mcp.getAITools(); + + const allTools = { + ...localTools, + ...mcpTools + }; + + const result = streamText({ + model: openai("gpt-4o"), + messages: await convertToModelMessages(this.messages), + tools: allTools + }); + + return result.toUIMessageStreamResponse(); +} +``` + +## List MCP Resources + +```typescript +// List all registered servers +const servers = this.mcp.listServers(); + +// List tools from all servers +const tools = this.mcp.listTools(); + +// List resources +const resources = this.mcp.listResources(); + +// List prompts +const prompts = this.mcp.listPrompts(); +``` + +## Remove Server + +```typescript +await this.removeMcpServer(serverId); +``` + +## Building an MCP Server + +Use `McpAgent` from the SDK to create an MCP server. + +**Install dependencies:** +```bash +npm install @modelcontextprotocol/sdk zod +``` + +**Wrangler config:** +```jsonc +{ + "durable_objects": { + "bindings": [{ "name": "MyMCP", "class_name": "MyMCP" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyMCP"] }] +} +``` + +**Server implementation:** +```typescript +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { McpAgent } from "agents/mcp"; +import { z } from "zod"; + +type State = { counter: number }; + +export class MyMCP extends McpAgent { + server = new McpServer({ + name: "MyMCPServer", + version: "1.0.0" + }); + + initialState = { counter: 0 }; + + async init() { + // Register a resource + this.server.resource("counter", "mcp://resource/counter", (uri) => ({ + contents: [{ text: String(this.state.counter), uri: uri.href }] + })); + + // Register a tool + this.server.registerTool( + "increment", + { + description: "Increment the counter", + inputSchema: { amount: z.number().default(1) } + }, + async ({ amount }) => { + this.setState({ counter: this.state.counter + amount }); + return { + content: [{ text: `Counter: ${this.state.counter}`, type: "text" }] + }; + } + ); + } +} +``` + +## Serve MCP Server + +```typescript +export default { + fetch(request: Request, env: Env, ctx: ExecutionContext) { + const url = new URL(request.url); + + // SSE transport (legacy) + if (url.pathname.startsWith("/sse")) { + return MyMCP.serveSSE("/sse", { binding: "MyMCP" }).fetch(request, env, ctx); + } + + // Streamable HTTP transport (recommended) + if (url.pathname.startsWith("/mcp")) { + return MyMCP.serve("/mcp", { binding: "MyMCP" }).fetch(request, env, ctx); + } + + return new Response("Not found", { status: 404 }); + } +}; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/state-scheduling.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/state-scheduling.md new file mode 100644 index 0000000000000000000000000000000000000000..86e617cb4c540f198a272ff2fa759274fc2ff5b6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/state-scheduling.md @@ -0,0 +1,164 @@ +# State & Scheduling + +Fetch `docs/state.md` and `docs/scheduling.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation. + +## State Management + +State persists to SQLite and broadcasts to connected clients automatically. + +### Define Typed State + +```typescript +type State = { + count: number; + items: string[]; +}; + +export class MyAgent extends Agent { + initialState: State = { count: 0, items: [] }; +} +``` + +### Read and Update + +```typescript +// Read (lazy-loaded from SQLite) +const count = this.state.count; + +// Write (sync, persists, broadcasts) +this.setState({ count: this.state.count + 1 }); +``` + +### Validation Hook + +`validateStateChange()` runs synchronously before state persists. Throw to reject the update. + +```typescript +validateStateChange(nextState: State, source: Connection | "server") { + if (nextState.count < 0) { + throw new Error("Count cannot be negative"); + } +} +``` + +### Execution Order + +1. `validateStateChange(nextState, source)` - sync, gating +2. State persisted to SQLite +3. State broadcast to connected clients +4. `onStateUpdate(nextState, source)` - async via `ctx.waitUntil`, non-gating + +### Client-Side Sync (React) + +```tsx +import { useAgent } from "agents/react"; + +function App() { + const [state, setLocalState] = useState({ count: 0 }); + + const agent = useAgent({ + agent: "MyAgent", + name: "instance-1", + onStateUpdate: (newState) => setLocalState(newState) + }); + + return ; +} +``` + +## SQL API + +Direct SQLite access for custom queries: + +```typescript +// Create table +this.sql` + CREATE TABLE IF NOT EXISTS items ( + id TEXT PRIMARY KEY, + name TEXT, + created_at INTEGER DEFAULT (unixepoch()) + ) +`; + +// Insert +this.sql`INSERT INTO items (id, name) VALUES (${id}, ${name})`; + +// Query with types +const items = this.sql<{ id: string; name: string }>` + SELECT * FROM items WHERE name LIKE ${`%${search}%`} +`; +``` + +## Scheduling + +### Schedule Types + +| Mode | Syntax | Use Case | +|------|--------|----------| +| Delay | `this.schedule(60, ...)` | Run in 60 seconds | +| Date | `this.schedule(new Date(...), ...)` | Run at specific time | +| Cron | `this.schedule("0 8 * * *", ...)` | Recurring schedule | +| Interval | `this.scheduleEvery(30, ...)` | Fixed interval (every 30s) | + +### Examples + +```typescript +// Delay (seconds) +await this.schedule(60, "checkStatus", { id: "abc123" }); + +// Specific date +await this.schedule(new Date("2025-12-25T00:00:00Z"), "sendGreeting", { to: "user" }); + +// Cron (recurring) +await this.schedule("0 9 * * 1-5", "weekdayReport", {}); + +// Fixed interval (every 30 seconds, overlap prevention built-in) +await this.scheduleEvery(30, "pollUpdates"); +await this.scheduleEvery(300, "syncData", { source: "api" }); +``` + +### Handler + +```typescript +async sendGreeting(payload: { to: string }, schedule: Schedule) { + console.log(`Sending greeting to ${payload.to}`); + // Cron schedules auto-reschedule; one-time schedules are deleted +} +``` + +### Manage Schedules + +```typescript +const schedules = this.getSchedules(); +const crons = this.getSchedules({ type: "cron" }); +await this.cancelSchedule(schedule.id); +``` + +## Lifecycle Callbacks + +```typescript +export class MyAgent extends Agent { + async onStart() { + // Agent started or woke from hibernation + } + + onConnect(conn: Connection, ctx: ConnectionContext) { + // WebSocket connected + } + + onMessage(conn: Connection, message: WSMessage) { + // WebSocket message (non-RPC) + } + + onStateUpdate(state: State, source: Connection | "server") { + // State changed (async, non-blocking) + } + + onError(error: unknown) { + // Error handler + throw error; // Re-throw to propagate + } +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/streaming-chat.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/streaming-chat.md new file mode 100644 index 0000000000000000000000000000000000000000..cce68170ba8b453ed5463f97e4b9504b2adc5388 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/streaming-chat.md @@ -0,0 +1,178 @@ +# Streaming Chat with AIChatAgent + +Fetch `docs/resumable-streaming.md` and `docs/client-sdk.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation. + +`AIChatAgent` provides streaming chat with automatic message persistence and resumable streams. + +## Basic Chat Agent + +```typescript +import { AIChatAgent } from "@cloudflare/ai-chat"; +import { streamText, convertToModelMessages } from "ai"; +import { openai } from "@ai-sdk/openai"; + +export class Chat extends AIChatAgent { + async onChatMessage(onFinish) { + const result = streamText({ + model: openai("gpt-4o"), + messages: await convertToModelMessages(this.messages), + onFinish + }); + return result.toUIMessageStreamResponse(); + } +} +``` + +## With Custom System Prompt + +```typescript +export class Chat extends AIChatAgent { + async onChatMessage(onFinish) { + const result = streamText({ + model: openai("gpt-4o"), + system: "You are a helpful assistant specializing in...", + messages: await convertToModelMessages(this.messages), + onFinish + }); + return result.toUIMessageStreamResponse(); + } +} +``` + +## With Tools + +```typescript +import { tool } from "ai"; +import { z } from "zod"; + +const tools = { + getWeather: tool({ + description: "Get weather for a location", + parameters: z.object({ location: z.string() }), + execute: async ({ location }) => `Weather in ${location}: 72°F, sunny` + }) +}; + +export class Chat extends AIChatAgent { + async onChatMessage(onFinish) { + const result = streamText({ + model: openai("gpt-4o"), + messages: await convertToModelMessages(this.messages), + tools, + onFinish + }); + return result.toUIMessageStreamResponse(); + } +} +``` + +## Custom UI Message Stream + +For more control, use `createUIMessageStream`: + +```typescript +import { createUIMessageStream, createUIMessageStreamResponse } from "ai"; + +export class Chat extends AIChatAgent { + async onChatMessage(onFinish) { + const stream = createUIMessageStream({ + execute: async ({ writer }) => { + const result = streamText({ + model: openai("gpt-4o"), + messages: await convertToModelMessages(this.messages), + onFinish + }); + writer.merge(result.toUIMessageStream()); + } + }); + return createUIMessageStreamResponse({ stream }); + } +} +``` + +## Resumable Streaming + +Streams automatically resume if client disconnects and reconnects: + +1. Chunks buffered to SQLite during streaming +2. On reconnect, buffered chunks sent immediately +3. Live streaming continues from where it left off + +**Enabled by default.** To disable: + +```tsx +const { messages } = useAgentChat({ agent, resume: false }); +``` + +## React Client + +```tsx +import { useAgent } from "agents/react"; +import { useAgentChat } from "@cloudflare/ai-chat/react"; + +function ChatUI() { + const agent = useAgent({ + agent: "Chat", + name: "my-chat-session" + }); + + const { + messages, + input, + handleInputChange, + handleSubmit, + status + } = useAgentChat({ agent }); + + return ( +
+ {messages.map((m) => ( +
+ {m.role}: {m.content} +
+ ))} + +
+ + +
+
+ ); +} +``` + +## Streaming RPC Methods + +For non-chat streaming, use `@callable({ streaming: true })`: + +```typescript +import { Agent, callable, StreamingResponse } from "agents"; + +export class MyAgent extends Agent { + @callable({ streaming: true }) + async streamData(stream: StreamingResponse, query: string) { + for (let i = 0; i < 10; i++) { + stream.send(`Result ${i}: ${query}`); + await sleep(100); + } + stream.close(); + } +} +``` + +Client receives streamed messages via WebSocket RPC. + +## Status Values + +`useAgentChat` status: + +| Status | Meaning | +|--------|---------| +| `ready` | Idle, ready for input | +| `streaming` | Response streaming | +| `submitted` | Request sent, waiting | +| `error` | Error occurred | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/workflows.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/workflows.md new file mode 100644 index 0000000000000000000000000000000000000000..791cfa9a938f0f9ed6bd2433e455790eb7647d20 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/workflows.md @@ -0,0 +1,132 @@ +# Workflows Integration + +Fetch `docs/workflows.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation. + +## Overview + +Agents handle real-time communication; Workflows handle durable execution. Together they enable: + +- Long-running background tasks with automatic retries +- Human-in-the-loop approval flows +- Multi-step pipelines that survive failures + +| Use Case | Recommendation | +|----------|----------------| +| Chat/messaging | Agent only | +| Quick API calls (<30s) | Agent only | +| Background processing (<30s) | Agent `queue()` | +| Long-running tasks (>30s) | Agent + Workflow | +| Human approval flows | Agent + Workflow | + +## AgentWorkflow Base Class + +```typescript +import { AgentWorkflow } from "agents/workflows"; +import type { AgentWorkflowEvent, AgentWorkflowStep } from "agents/workflows"; + +type TaskParams = { taskId: string; data: string }; + +export class ProcessingWorkflow extends AgentWorkflow { + async run(event: AgentWorkflowEvent, step: AgentWorkflowStep) { + const params = event.payload; + + // Durable step - retries on failure + const result = await step.do("process", async () => { + return processData(params.data); + }); + + // Non-durable: progress reporting + await this.reportProgress({ step: "process", percent: 0.5 }); + + // Non-durable: broadcast to connected clients + this.broadcastToClients({ type: "update", taskId: params.taskId }); + + // Durable: merge state via step + await step.mergeAgentState({ lastProcessed: params.taskId }); + + // Durable: report completion + await step.reportComplete(result); + + return result; + } +} +``` + +## Wrangler Configuration + +```jsonc +{ + "workflows": [ + { "name": "processing-workflow", "binding": "PROCESSING_WORKFLOW", "class_name": "ProcessingWorkflow" } + ], + "durable_objects": { + "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }] +} +``` + +## Agent Methods for Workflows + +```typescript +// Start a workflow +const instance = await this.runWorkflow("ProcessingWorkflow", { taskId: "123", data: "..." }); + +// Send event to waiting workflow +await this.sendWorkflowEvent("ProcessingWorkflow", workflowId, { type: "approve" }); + +// Query workflows +const workflow = await this.getWorkflow(workflowId); +const workflows = await this.getWorkflows({ status: "running" }); + +// Control workflows +await this.approveWorkflow(workflowId); +await this.rejectWorkflow(workflowId); +await this.terminateWorkflow(workflowId); +await this.pauseWorkflow(workflowId); +await this.resumeWorkflow(workflowId); + +// Delete workflows +await this.deleteWorkflow(workflowId); +await this.deleteWorkflows({ status: "complete", before: new Date(...) }); +``` + +## Lifecycle Callbacks + +```typescript +export class MyAgent extends Agent { + async onWorkflowProgress(workflowName: string, workflowId: string, progress: unknown) { + // Workflow reported progress via this.reportProgress() + this.broadcast({ type: "progress", workflowId, progress }); + } + + async onWorkflowComplete(workflowName: string, workflowId: string, result?: unknown) { + // Workflow finished successfully + } + + async onWorkflowError(workflowName: string, workflowId: string, error: Error) { + // Workflow failed + } + + async onWorkflowEvent(workflowName: string, workflowId: string, event: unknown) { + // Workflow received an event via sendWorkflowEvent() + } +} +``` + +## Human-in-the-Loop + +```typescript +// In workflow: wait for approval +const approved = await step.waitForEvent<{ approved: boolean }>("approval", { + timeout: "7d" +}); + +if (!approved.approved) { + throw new Error("Rejected"); +} + +// From agent: approve or reject +await this.approveWorkflow(workflowId); // Sends { approved: true } +await this.rejectWorkflow(workflowId); // Sends { approved: false } +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ff4279dc071264ebdaf231da1aa1738554cf80cc --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/SKILL.md @@ -0,0 +1,400 @@ +--- +name: building-ai-agent-on-cloudflare +description: | + Builds AI agents on Cloudflare using the Agents SDK with state management, + real-time WebSockets, scheduled tasks, tool integration, and chat capabilities. + Generates production-ready agent code deployed to Workers. + + Use when: user wants to "build an agent", "AI agent", "chat agent", "stateful + agent", mentions "Agents SDK", needs "real-time AI", "WebSocket AI", or asks + about agent "state management", "scheduled tasks", or "tool calling". + Biases towards retrieval from Cloudflare docs over pre-trained knowledge. +--- + +# Building Cloudflare Agents + +Your knowledge of the Agents SDK may be outdated. **Prefer retrieval over pre-training** for any agent-building task. + +## Retrieval Sources + +| Source | How to retrieve | Use for | +|--------|----------------|---------| +| Agents SDK docs | `https://github.com/cloudflare/agents/tree/main/docs` | SDK API, state, routing, scheduling | +| Cloudflare Agents docs | `https://developers.cloudflare.com/agents/` | Platform integration, deployment | +| Workers docs | Search tool or `https://developers.cloudflare.com/workers/` | Runtime APIs, bindings, config | + +## When to Use + +- User wants to build an AI agent or chatbot +- User needs stateful, real-time AI interactions +- User asks about the Cloudflare Agents SDK +- User wants scheduled tasks or background AI work +- User needs WebSocket-based AI communication + +## Prerequisites + +- Cloudflare account with Workers enabled +- Node.js 18+ and npm/pnpm/yarn +- Wrangler CLI (`npm install -g wrangler`) + +## Quick Start + +```bash +npm create cloudflare@latest -- my-agent --template=cloudflare/agents-starter +cd my-agent +npm start +``` + +Agent runs at `http://localhost:8787` + +## Core Concepts + +### What is an Agent? + +An Agent is a stateful, persistent AI service that: +- Maintains state across requests and reconnections +- Communicates via WebSockets or HTTP +- Runs on Cloudflare's edge via Durable Objects +- Can schedule tasks and call tools +- Scales horizontally (each user/session gets own instance) + +### Agent Lifecycle + +``` +Client connects → Agent.onConnect() → Agent processes messages + → Agent.onMessage() + → Agent.setState() (persists + syncs) +Client disconnects → State persists → Client reconnects → State restored +``` + +## Basic Agent Structure + +```typescript +import { Agent, Connection } from "agents"; + +interface Env { + AI: Ai; // Workers AI binding +} + +interface State { + messages: Array<{ role: string; content: string }>; + preferences: Record; +} + +export class MyAgent extends Agent { + // Initial state for new instances + initialState: State = { + messages: [], + preferences: {}, + }; + + // Called when agent starts or resumes + async onStart() { + console.log("Agent started with state:", this.state); + } + + // Handle WebSocket connections + async onConnect(connection: Connection) { + connection.send(JSON.stringify({ + type: "welcome", + history: this.state.messages, + })); + } + + // Handle incoming messages + async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "chat") { + await this.handleChat(connection, data.content); + } + } + + // Handle disconnections + async onClose(connection: Connection) { + console.log("Client disconnected"); + } + + // React to state changes + onStateUpdate(state: State, source: string) { + console.log("State updated by:", source); + } + + private async handleChat(connection: Connection, userMessage: string) { + // Add user message to history + const messages = [ + ...this.state.messages, + { role: "user", content: userMessage }, + ]; + + // Call AI + const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", { + messages, + }); + + // Update state (persists and syncs to all clients) + this.setState({ + ...this.state, + messages: [ + ...messages, + { role: "assistant", content: response.response }, + ], + }); + + // Send response + connection.send(JSON.stringify({ + type: "response", + content: response.response, + })); + } +} +``` + +## Entry Point Configuration + +```typescript +// src/index.ts +import { routeAgentRequest } from "agents"; +import { MyAgent } from "./agent"; + +export default { + async fetch(request: Request, env: Env) { + // routeAgentRequest handles routing to /agents/:class/:name + return ( + (await routeAgentRequest(request, env)) || + new Response("Not found", { status: 404 }) + ); + }, +}; + +export { MyAgent }; +``` + +Clients connect via: `wss://my-agent.workers.dev/agents/MyAgent/session-id` + +## Wrangler Configuration + +```toml +name = "my-agent" +main = "src/index.ts" +compatibility_date = "2024-12-01" + +[ai] +binding = "AI" + +[durable_objects] +bindings = [{ name = "AGENT", class_name = "MyAgent" }] + +[[migrations]] +tag = "v1" +new_classes = ["MyAgent"] +``` + +## State Management + +### Reading State + +```typescript +// Current state is always available +const currentMessages = this.state.messages; +const userPrefs = this.state.preferences; +``` + +### Updating State + +```typescript +// setState persists AND syncs to all connected clients +this.setState({ + ...this.state, + messages: [...this.state.messages, newMessage], +}); + +// Partial updates work too +this.setState({ + preferences: { ...this.state.preferences, theme: "dark" }, +}); +``` + +### SQL Storage + +For complex queries, use the embedded SQLite database: + +```typescript +// Create tables +await this.sql` + CREATE TABLE IF NOT EXISTS documents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + content TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + ) +`; + +// Insert +await this.sql` + INSERT INTO documents (title, content) + VALUES (${title}, ${content}) +`; + +// Query +const docs = await this.sql` + SELECT * FROM documents WHERE title LIKE ${`%${search}%`} +`; +``` + +## Scheduled Tasks + +Agents can schedule future work: + +```typescript +async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "schedule_reminder") { + // Schedule task for 1 hour from now + const { id } = await this.schedule(3600, "sendReminder", { + message: data.reminderText, + userId: data.userId, + }); + + connection.send(JSON.stringify({ type: "scheduled", taskId: id })); + } +} + +// Called when scheduled task fires +async sendReminder(data: { message: string; userId: string }) { + // Send notification, email, etc. + console.log(`Reminder for ${data.userId}: ${data.message}`); + + // Can also update state + this.setState({ + ...this.state, + lastReminder: new Date().toISOString(), + }); +} +``` + +### Schedule Options + +```typescript +// Delay in seconds +await this.schedule(60, "taskMethod", { data }); + +// Specific date +await this.schedule(new Date("2025-01-01T00:00:00Z"), "taskMethod", { data }); + +// Cron expression (recurring) +await this.schedule("0 9 * * *", "dailyTask", {}); // 9 AM daily +await this.schedule("*/5 * * * *", "everyFiveMinutes", {}); // Every 5 min + +// Manage schedules +const schedules = await this.getSchedules(); +await this.cancelSchedule(taskId); +``` + +## Chat Agent (AI-Powered) + +For chat-focused agents, extend `AIChatAgent`: + +```typescript +import { AIChatAgent } from "agents/ai-chat-agent"; + +export class ChatBot extends AIChatAgent { + // Called for each user message + async onChatMessage(message: string) { + const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", { + messages: [ + { role: "system", content: "You are a helpful assistant." }, + ...this.messages, // Automatic history management + { role: "user", content: message }, + ], + stream: true, + }); + + // Stream response back to client + return response; + } +} +``` + +Features included: +- Automatic message history +- Resumable streaming (survives disconnects) +- Built-in `saveMessages()` for persistence + +## Client Integration + +### React Hook + +```tsx +import { useAgent } from "agents/react"; + +function Chat() { + const { state, send, connected } = useAgent({ + agent: "my-agent", + name: userId, // Agent instance ID + }); + + const sendMessage = (text: string) => { + send(JSON.stringify({ type: "chat", content: text })); + }; + + return ( +
+ {state.messages.map((msg, i) => ( +
{msg.role}: {msg.content}
+ ))} + e.key === "Enter" && sendMessage(e.target.value)} /> +
+ ); +} +``` + +### Vanilla JavaScript + +```javascript +const ws = new WebSocket("wss://my-agent.workers.dev/agents/MyAgent/user123"); + +ws.onopen = () => { + console.log("Connected to agent"); +}; + +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + console.log("Received:", data); +}; + +ws.send(JSON.stringify({ type: "chat", content: "Hello!" })); +``` + +## Common Patterns + +See [references/agent-patterns.md](references/agent-patterns.md) for: +- Tool calling and function execution +- Multi-agent orchestration +- RAG (Retrieval Augmented Generation) +- Human-in-the-loop workflows + +## Deployment + +```bash +# Deploy +npx wrangler deploy + +# View logs +wrangler tail + +# Test endpoint +curl https://my-agent.workers.dev/agents/MyAgent/test-user +``` + +## Troubleshooting + +See [references/troubleshooting.md](references/troubleshooting.md) for common issues. + +## References + +- [references/examples.md](references/examples.md) — Official templates and production examples +- [references/agent-patterns.md](references/agent-patterns.md) — Advanced patterns +- [references/state-patterns.md](references/state-patterns.md) — State management strategies +- [references/troubleshooting.md](references/troubleshooting.md) — Error solutions diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d9484b27ce3c21bc59ec2ec26d4d4178cf285c91 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Building AI Agents on Cloudflare" + short_description: "Build stateful AI agents on Cloudflare Workers" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/agent-patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/agent-patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..219e82530473220117879a212698d2aa9d32b0a4 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/agent-patterns.md @@ -0,0 +1,461 @@ +# Agent Patterns + +Advanced patterns for building sophisticated agents. + +## Tool Calling + +Agents can expose tools that AI models can call: + +```typescript +import { Agent, Connection } from "agents"; +import { z } from "zod"; + +interface Tool { + name: string; + description: string; + parameters: z.ZodSchema; + handler: (params: any) => Promise; +} + +export class ToolAgent extends Agent { + private tools: Map = new Map(); + + async onStart() { + // Register tools + this.registerTool({ + name: "get_weather", + description: "Get current weather for a city", + parameters: z.object({ city: z.string() }), + handler: async ({ city }) => { + const res = await fetch(`https://api.weather.com/${city}`); + return JSON.stringify(await res.json()); + }, + }); + + this.registerTool({ + name: "search_database", + description: "Search the document database", + parameters: z.object({ query: z.string(), limit: z.number().default(10) }), + handler: async ({ query, limit }) => { + const results = await this.sql` + SELECT * FROM documents + WHERE content LIKE ${`%${query}%`} + LIMIT ${limit} + `; + return JSON.stringify(results); + }, + }); + } + + private registerTool(tool: Tool) { + this.tools.set(tool.name, tool); + } + + async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "chat") { + await this.handleChatWithTools(connection, data.content); + } + } + + private async handleChatWithTools(connection: Connection, userMessage: string) { + // Build tool descriptions for the AI + const toolDescriptions = Array.from(this.tools.values()).map((t) => ({ + type: "function", + function: { + name: t.name, + description: t.description, + parameters: JSON.parse(JSON.stringify(t.parameters)), + }, + })); + + // First AI call - may request tool use + const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", { + messages: [ + { role: "system", content: "You are a helpful assistant with access to tools." }, + ...this.state.messages, + { role: "user", content: userMessage }, + ], + tools: toolDescriptions, + }); + + // Check if AI wants to use a tool + if (response.tool_calls) { + for (const toolCall of response.tool_calls) { + const tool = this.tools.get(toolCall.function.name); + if (tool) { + const params = JSON.parse(toolCall.function.arguments); + const result = await tool.handler(params); + + // Send tool result back to AI + const finalResponse = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", { + messages: [ + ...this.state.messages, + { role: "user", content: userMessage }, + { role: "assistant", tool_calls: response.tool_calls }, + { role: "tool", tool_call_id: toolCall.id, content: result }, + ], + }); + + connection.send(JSON.stringify({ + type: "response", + content: finalResponse.response, + toolUsed: toolCall.function.name, + })); + } + } + } else { + connection.send(JSON.stringify({ + type: "response", + content: response.response, + })); + } + } +} +``` + +## RAG (Retrieval Augmented Generation) + +Combine Vectorize with Agents for knowledge-grounded responses: + +```typescript +interface Env { + AI: Ai; + VECTORIZE: VectorizeIndex; +} + +export class RAGAgent extends Agent { + async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "chat") { + // 1. Generate embedding for query + const embedding = await this.env.AI.run("@cf/baai/bge-base-en-v1.5", { + text: data.content, + }); + + // 2. Search vector database + const results = await this.env.VECTORIZE.query(embedding.data[0], { + topK: 5, + returnMetadata: true, + }); + + // 3. Build context from results + const context = results.matches + .map((m) => m.metadata?.text || "") + .join("\n\n"); + + // 4. Generate response with context + const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", { + messages: [ + { + role: "system", + content: `Answer based on this context:\n\n${context}\n\nIf the context doesn't contain relevant information, say so.`, + }, + { role: "user", content: data.content }, + ], + }); + + // 5. Update state and respond + this.setState({ + messages: [ + ...this.state.messages, + { role: "user", content: data.content }, + { role: "assistant", content: response.response }, + ], + }); + + connection.send(JSON.stringify({ + type: "response", + content: response.response, + sources: results.matches.map((m) => m.metadata?.source), + })); + } + } + + // Ingest documents into vector store + async ingestDocument(doc: { id: string; text: string; source: string }) { + const embedding = await this.env.AI.run("@cf/baai/bge-base-en-v1.5", { + text: doc.text, + }); + + await this.env.VECTORIZE.upsert([{ + id: doc.id, + values: embedding.data[0], + metadata: { text: doc.text, source: doc.source }, + }]); + } +} +``` + +## Multi-Agent Orchestration + +Coordinate multiple specialized agents: + +```typescript +interface Env { + RESEARCHER: DurableObjectNamespace; + WRITER: DurableObjectNamespace; + REVIEWER: DurableObjectNamespace; +} + +export class OrchestratorAgent extends Agent { + async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "create_article") { + connection.send(JSON.stringify({ type: "status", step: "researching" })); + + // Step 1: Research agent gathers information + const researchResult = await this.callAgent( + this.env.RESEARCHER, + data.topic, + { action: "research", topic: data.topic } + ); + + connection.send(JSON.stringify({ type: "status", step: "writing" })); + + // Step 2: Writer agent creates draft + const draftResult = await this.callAgent( + this.env.WRITER, + data.topic, + { action: "write", research: researchResult, topic: data.topic } + ); + + connection.send(JSON.stringify({ type: "status", step: "reviewing" })); + + // Step 3: Reviewer agent improves draft + const finalResult = await this.callAgent( + this.env.REVIEWER, + data.topic, + { action: "review", draft: draftResult } + ); + + connection.send(JSON.stringify({ + type: "complete", + article: finalResult, + })); + } + } + + private async callAgent( + namespace: DurableObjectNamespace, + id: string, + payload: any + ): Promise { + const agentId = namespace.idFromName(id); + const agent = namespace.get(agentId); + + const response = await agent.fetch("http://agent/task", { + method: "POST", + body: JSON.stringify(payload), + }); + + return response.text(); + } +} +``` + +## Human-in-the-Loop + +Pause agent execution for human approval: + +```typescript +interface State { + pendingApprovals: Array<{ + id: string; + action: string; + data: any; + requestedAt: string; + }>; +} + +export class ApprovalAgent extends Agent { + initialState: State = { pendingApprovals: [] }; + + async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "request_action") { + // Action requires approval + if (this.requiresApproval(data.action)) { + const approvalId = crypto.randomUUID(); + + this.setState({ + pendingApprovals: [ + ...this.state.pendingApprovals, + { + id: approvalId, + action: data.action, + data: data.payload, + requestedAt: new Date().toISOString(), + }, + ], + }); + + connection.send(JSON.stringify({ + type: "approval_required", + approvalId, + action: data.action, + description: this.describeAction(data.action, data.payload), + })); + + return; + } + + // Execute immediately if no approval needed + await this.executeAction(connection, data.action, data.payload); + } + + if (data.type === "approve") { + const approval = this.state.pendingApprovals.find( + (a) => a.id === data.approvalId + ); + + if (approval) { + // Remove from pending + this.setState({ + pendingApprovals: this.state.pendingApprovals.filter( + (a) => a.id !== data.approvalId + ), + }); + + // Execute the approved action + await this.executeAction(connection, approval.action, approval.data); + } + } + + if (data.type === "reject") { + this.setState({ + pendingApprovals: this.state.pendingApprovals.filter( + (a) => a.id !== data.approvalId + ), + }); + + connection.send(JSON.stringify({ + type: "action_rejected", + approvalId: data.approvalId, + })); + } + } + + private requiresApproval(action: string): boolean { + const sensitiveActions = ["delete", "send_email", "make_payment", "publish"]; + return sensitiveActions.includes(action); + } + + private describeAction(action: string, data: any): string { + // Generate human-readable description + return `${action}: ${JSON.stringify(data)}`; + } + + private async executeAction(connection: Connection, action: string, data: any) { + // Execute the action + const result = await this.performAction(action, data); + + connection.send(JSON.stringify({ + type: "action_completed", + action, + result, + })); + } +} +``` + +## Streaming Responses + +Stream AI responses in real-time: + +```typescript +export class StreamingAgent extends Agent { + async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "chat") { + // Start streaming response + const stream = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", { + messages: [ + { role: "system", content: "You are a helpful assistant." }, + ...this.state.messages, + { role: "user", content: data.content }, + ], + stream: true, + }); + + let fullResponse = ""; + + // Stream chunks to client + for await (const chunk of stream) { + if (chunk.response) { + fullResponse += chunk.response; + connection.send(JSON.stringify({ + type: "stream", + content: chunk.response, + done: false, + })); + } + } + + // Update state with complete response + this.setState({ + messages: [ + ...this.state.messages, + { role: "user", content: data.content }, + { role: "assistant", content: fullResponse }, + ], + }); + + // Signal completion + connection.send(JSON.stringify({ + type: "stream", + content: "", + done: true, + })); + } + } +} +``` + +## Connecting to MCP Servers + +Agents can connect to MCP servers as clients: + +```typescript +export class MCPClientAgent extends Agent { + async onStart() { + // Connect to external MCP server + await this.addMcpServer( + "github", + "https://github-mcp.example.com/sse", + { headers: { Authorization: `Bearer ${this.env.GITHUB_TOKEN}` } } + ); + + await this.addMcpServer( + "database", + "https://db-mcp.example.com/sse" + ); + } + + async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "use_tool") { + // Call tool on connected MCP server + const servers = await this.getMcpServers(); + const server = servers.find((s) => s.name === data.server); + + if (server) { + const result = await server.callTool(data.tool, data.params); + connection.send(JSON.stringify({ type: "tool_result", result })); + } + } + } + + async onClose() { + // Cleanup MCP connections + await this.removeMcpServer("github"); + await this.removeMcpServer("database"); + } +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/examples.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/examples.md new file mode 100644 index 0000000000000000000000000000000000000000..7efc0f8af681f04a243326170ec838b78f761d19 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/examples.md @@ -0,0 +1,188 @@ +# Project Bootstrapping + +Instructions for creating new agent projects. + +--- + +## Create Command + +Execute in terminal to generate a new project: + +```bash +npm create cloudflare@latest -- my-agent \ + --template=cloudflare/agents-starter +``` + +Or use npx directly: + +```bash +npx create-cloudflare@latest --template cloudflare/agents-starter +``` + +Includes: +- Persistent data via `this.setState` and `this.sql` +- WebSocket real-time connections +- Workers AI bindings ready +- React chat interface example + +--- + +## Project Layout + +Generated structure: + +``` +my-agent/ +├── src/ +│ ├── app.tsx # React chat interface +│ ├── server.ts # Agent implementation +│ ├── tools.ts # Tool definitions +│ └── utils.ts # Helpers +├── wrangler.toml # Platform configuration +└── package.json +``` + +--- + +## Agent Variations + +**Chat-focused:** + +Inherit from base `Agent` class, implement `onMessage` handler: +- Manual conversation tracking +- Full control over responses +- Integrates with any AI provider + +**Persistent data:** + +Use `this.setState()` for automatic persistence: +- JSON-serializable data +- Auto-syncs to connected clients +- Survives instance eviction + +**Per-session isolation:** + +Route by unique identifier in URL path: +- Each identifier gets dedicated instance +- Isolated data storage +- Horizontal scaling automatic + +--- + +## Platform Documentation + +- developers.cloudflare.com/agents/ +- developers.cloudflare.com/agents/getting-started/ +- developers.cloudflare.com/agents/api-reference/ + +**Source repositories:** +- `github.com/cloudflare/agents-starter` (starter template) +- `github.com/cloudflare/agents/tree/main/examples` (reference implementations) + +**Related services:** + +- developers.cloudflare.com/workers-ai/ (AI models) +- developers.cloudflare.com/vectorize/ (vector search) +- developers.cloudflare.com/d1/ (SQL database) + +--- + +## Reference Implementations + +Located at `github.com/cloudflare/agents/tree/main/examples`: + +| Example | Description | +|---------|-------------| +| `resumable-stream-chat` | Chat with reconnection-safe streaming | +| `email-agent` | Handle incoming emails via Email Routing | +| `mcp-client` | Connect agents to external MCP servers | +| `mcp-worker` | Expose agent capabilities via MCP protocol | +| `cross-domain` | Multi-domain authentication patterns | +| `tictactoe` | Multiplayer game with shared state | +| `a2a` | Agent-to-agent communication | +| `codemode` | Code transformation workflows | +| `playground` | Interactive testing sandbox | + +Browse each folder for complete implementation code and wrangler configuration. + +--- + +## Selection Matrix + +| Goal | Approach | +|------|----------| +| Conversational bot | Agent + onMessage handler | +| Custom data schema | Agent + setState() | +| Knowledge retrieval | Agent + Vectorize | +| Background jobs | Agent + schedule() | +| External integrations | Agent + tool definitions | + +--- + +## Commands Reference + +**Local execution:** + +```bash +cd my-agent +npm install +npm start +# Accessible at http://localhost:8787 +``` + +**Production push:** + +```bash +npx wrangler deploy +# Accessible at https://[name].[subdomain].workers.dev +``` + +**WebSocket connection:** + +```javascript +// URL pattern: /agents/:className/:instanceName +const socket = new WebSocket("wss://my-agent.workers.dev/agents/MyAgent/session-123"); + +socket.onmessage = (e) => { + console.log("Received:", JSON.parse(e.data)); +}; + +socket.send(JSON.stringify({ type: "chat", content: "Hello" })); +``` + +**React integration:** + +```tsx +import { useAgent } from "agents/react"; + +function Chat() { + const { state, send } = useAgent({ + agent: "my-agent", + name: "session-123", + }); + + // state auto-updates, send() dispatches messages +} +``` + +--- + +## Key Methods (from Agent class) + +| Method | Purpose | +|--------|---------| +| `onStart()` | Runs on instance startup | +| `onConnect()` | Handles new WebSocket connections | +| `onMessage()` | Processes incoming messages | +| `onClose()` | Cleanup on disconnect | +| `setState()` | Persist and broadcast data | +| `this.sql` | Query embedded SQLite | +| `schedule()` | Delayed/recurring tasks | +| `broadcast()` | Message all connections | + +--- + +## Help Channels + +- Cloudflare Discord +- GitHub discussions on cloudflare/agents repository diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/state-patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/state-patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..889f755e855256b3776d278e2be8567045602f5b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/state-patterns.md @@ -0,0 +1,360 @@ +# State Management Patterns + +Strategies for managing state in Cloudflare Agents. + +## How State Works + +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. + +```typescript +class MyAgent extends Agent { + initialState = { count: 0 }; + + increment() { + this.setState({ count: this.state.count + 1 }); + } + + onStateUpdate(state: State, source: string) { + console.log("State updated by:", source); + } +} +``` + +## State vs SQL: When to Use Which + +### Use `this.state` + `setState()` When: + +- Data is small (< 1MB recommended) +- Needs real-time sync to all connected clients +- Simple key-value or object structure +- Frequently read, occasionally updated + +```typescript +interface State { + currentUser: { id: string; name: string }; + preferences: Record; + recentMessages: Message[]; // Keep limited, e.g., last 50 + isTyping: boolean; +} +``` + +### Use `this.sql` When: + +- Large datasets (many records) +- Complex queries (JOINs, aggregations, filtering) +- Historical data / audit logs +- Data that doesn't need real-time sync + +```typescript +// Good for SQL +// - Full message history +// - User documents +// - Analytics events +// - Search indexes +``` + +## Hybrid Pattern + +Combine both for optimal performance: + +```typescript +interface State { + recentMessages: Message[]; + onlineUsers: string[]; + currentDocument: Document | null; +} + +export class HybridAgent extends Agent { + initialState: State = { + recentMessages: [], + onlineUsers: [], + currentDocument: null, + }; + + async onStart() { + await this.sql` + CREATE TABLE IF NOT EXISTS messages ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + content TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `; + + const recent = await this.sql` + SELECT * FROM messages + ORDER BY created_at DESC + LIMIT 50 + `; + + this.setState({ + ...this.state, + recentMessages: recent.reverse(), + }); + } + + async addMessage(message: Message) { + await this.sql` + INSERT INTO messages (id, user_id, content) + VALUES (${message.id}, ${message.userId}, ${message.content}) + `; + + const recentMessages = [...this.state.recentMessages, message].slice(-50); + this.setState({ ...this.state, recentMessages }); + } +} +``` + +--- + +## Queue System + +The SDK includes a built-in queue for background task processing. Tasks are stored in SQLite and processed in FIFO order. + +### Queue Methods + +| Method | Purpose | +|--------|---------| +| `queue(callback, payload)` | Add task, returns task ID | +| `dequeue(id)` | Remove specific task | +| `dequeueAll()` | Clear entire queue | +| `dequeueAllByCallback(name)` | Remove tasks by callback name | +| `getQueue(id)` | Get single task | +| `getQueues(key, value)` | Find tasks by payload field | + +### Queue Example + +```typescript +export class TaskAgent extends Agent { + async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "process_later") { + const taskId = await this.queue("processItem", { + itemId: data.itemId, + priority: data.priority, + }); + + connection.send(JSON.stringify({ queued: true, taskId })); + } + } + + // Callback receives payload and QueueItem metadata + async processItem(payload: { itemId: string }, item: QueueItem) { + console.log(`Processing ${payload.itemId}, queued at ${item.createdAt}`); + // Successfully executed tasks are auto-removed + } +} +``` + +**Queue characteristics:** +- Sequential processing (no parallelization) +- Persists across agent restarts +- No built-in retry mechanism +- Payloads must be JSON-serializable + +--- + +## Context Management + +Custom methods automatically have full agent context. Use `getCurrentAgent()` to access context from external functions. + +```typescript +import { getCurrentAgent } from "agents"; + +// External utility function +async function logActivity(action: string) { + const { agent } = getCurrentAgent(); + await agent.sql` + INSERT INTO activity_log (action, timestamp) + VALUES (${action}, ${Date.now()}) + `; +} + +export class MyAgent extends Agent { + async performAction() { + // Context automatically available + await logActivity("action_performed"); + } +} +``` + +`getCurrentAgent()` returns: +- `agent` - The current agent instance +- `connection` - Connection object (if applicable) +- `request` - Request object (if applicable) + +--- + +## State Synchronization + +### Optimistic Updates + +Update UI immediately, then persist: + +```typescript +async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "update_preference") { + this.setState({ + ...this.state, + preferences: { + ...this.state.preferences, + [data.key]: data.value, + }, + }); + + await this.sql` + INSERT OR REPLACE INTO preferences (key, value) + VALUES (${data.key}, ${data.value}) + `; + } +} +``` + +### Conflict Resolution + +Handle concurrent updates with versioning: + +```typescript +interface State { + document: { + content: string; + version: number; + lastModifiedBy: string; + }; +} + +async updateDocument(userId: string, newContent: string, expectedVersion: number) { + if (this.state.document.version !== expectedVersion) { + throw new Error("Conflict: document was modified by another user"); + } + + this.setState({ + ...this.state, + document: { + content: newContent, + version: expectedVersion + 1, + lastModifiedBy: userId, + }, + }); +} +``` + +### Per-Connection State + +Track ephemeral state for each connected client: + +```typescript +export class MultiUserAgent extends Agent { + private connectionState = new Map(); + + async onConnect(connection: Connection) { + this.connectionState.set(connection.id, { + userId: "", + cursor: { x: 0, y: 0 }, + lastActivity: Date.now(), + }); + } + + async onClose(connection: Connection) { + this.connectionState.delete(connection.id); + } +} +``` + +--- + +## State Migration + +When state schema changes: + +```typescript +interface StateV2 { + messages: Array<{ id: string; content: string; timestamp: string }>; + version: 2; +} + +export class MigratingAgent extends Agent { + initialState: StateV2 = { + messages: [], + version: 2, + }; + + async onStart() { + const rawState = this.state as any; + + if (!rawState.version || rawState.version < 2) { + const migratedMessages = (rawState.messages || []).map( + (content: string, i: number) => ({ + id: `migrated-${i}`, + content, + timestamp: new Date().toISOString(), + }) + ); + + this.setState({ + messages: migratedMessages, + version: 2, + }); + } + } +} +``` + +--- + +## State Size Management + +Keep state lean for performance: + +```typescript +export class LeanStateAgent extends Agent { + private readonly MAX_RECENT_MESSAGES = 100; + + async addMessage(message: Message) { + await this.sql`INSERT INTO messages (id, content) VALUES (${message.id}, ${message.content})`; + + let recentMessages = [...this.state.recentMessages, message]; + if (recentMessages.length > this.MAX_RECENT_MESSAGES) { + recentMessages = recentMessages.slice(-this.MAX_RECENT_MESSAGES); + } + + this.setState({ + ...this.state, + recentMessages, + stats: { + ...this.state.stats, + totalMessages: this.state.stats.totalMessages + 1, + lastActivity: new Date().toISOString(), + }, + }); + } +} +``` + +--- + +## Debugging State + +```typescript +async onMessage(connection: Connection, message: string) { + const data = JSON.parse(message); + + if (data.type === "debug_state") { + connection.send(JSON.stringify({ + type: "debug_response", + state: this.state, + stateSize: JSON.stringify(this.state).length, + sqlTables: await this.sql` + SELECT name FROM sqlite_master WHERE type='table' + `, + })); + } +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/troubleshooting.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..97008a5a32193aa8def24827a97b53a886628648 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/troubleshooting.md @@ -0,0 +1,362 @@ +# Agent Troubleshooting + +Common issues and solutions for Cloudflare Agents. + +## Connection Issues + +### "WebSocket connection failed" + +**Symptoms:** Client cannot connect to agent. + +**Causes & Solutions:** + +1. **Worker not deployed** + ```bash + wrangler deployments list + wrangler deploy # If not deployed + ``` + +2. **Wrong URL path** + ```javascript + // Ensure your routing handles the agent path + // Client: + new WebSocket("wss://my-worker.workers.dev/agent/user123"); + + // Worker must route to agent: + if (url.pathname.startsWith("/agent/")) { + const id = url.pathname.split("/")[2]; + return env.AGENT.get(env.AGENT.idFromName(id)).fetch(request); + } + ``` + +3. **CORS issues (browser clients)** + Agents handle WebSocket upgrades automatically, but ensure your entry worker doesn't block the request. + +### "Connection closed unexpectedly" + +1. **Agent threw an error** + ```bash + wrangler tail # Check for exceptions + ``` + +2. **Message handler crashed** + ```typescript + async onMessage(connection: Connection, message: string) { + try { + // Your logic + } catch (error) { + console.error("Message handling error:", error); + connection.send(JSON.stringify({ type: "error", message: error.message })); + } + } + ``` + +3. **Hibernation woke agent with stale connection** + Ensure you handle reconnection gracefully in client code. + +## State Issues + +### "State not persisting" + +**Causes:** + +1. **Didn't call `setState()`** + ```typescript + // Wrong - direct mutation doesn't persist + this.state.messages.push(newMessage); + + // Correct - use setState + this.setState({ + ...this.state, + messages: [...this.state.messages, newMessage], + }); + ``` + +2. **Agent crashed before state saved** + `setState()` is durable, but if agent crashes during processing before `setState()`, changes are lost. + +3. **Wrong agent instance** + Each unique ID gets a separate agent. Ensure clients connect to the same ID. + +### "State out of sync between clients" + +`setState()` automatically syncs to all connected clients via `onStateUpdate()`. If sync isn't working: + +1. **Check `onStateUpdate` is implemented** + ```typescript + onStateUpdate(state: State, source: string) { + // This fires when state changes from any source + console.log("State updated:", state, "from:", source); + } + ``` + +2. **Client not listening for state updates** + ```typescript + // React hook handles this automatically + const { state } = useAgent({ agent: "my-agent", name: id }); + + // Manual WebSocket - listen for state messages + ws.onmessage = (event) => { + const data = JSON.parse(event.data); + if (data.type === "state_update") { + updateLocalState(data.state); + } + }; + ``` + +### "State too large" / Performance issues + +State is serialized as JSON. Keep it small: + +```typescript +// Bad - storing everything in state +interface State { + allMessages: Message[]; // Could be thousands + allDocuments: Document[]; +} + +// Good - state for hot data, SQL for cold +interface State { + recentMessages: Message[]; // Last 50 only + currentDocument: Document | null; +} + +// Store full history in SQL +await this.sql`INSERT INTO messages ...`; +``` + +## SQL Issues + +### "no such table" + +Table not created. Create in `onStart()`: + +```typescript +async onStart() { + await this.sql` + CREATE TABLE IF NOT EXISTS messages ( + id TEXT PRIMARY KEY, + content TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `; +} +``` + +### "SQL logic error" + +Check your query syntax. Use tagged templates correctly: + +```typescript +// Wrong - string interpolation (SQL injection risk!) +await this.sql`SELECT * FROM users WHERE id = '${userId}'`; + +// Correct - parameterized query +await this.sql`SELECT * FROM users WHERE id = ${userId}`; +``` + +### SQL query returns empty + +1. **Wrong table name** +2. **Data in different agent instance** (each agent ID has isolated storage) +3. **Query conditions don't match** + +Debug: +```typescript +const tables = await this.sql` + SELECT name FROM sqlite_master WHERE type='table' +`; +console.log("Tables:", tables); + +const count = await this.sql`SELECT COUNT(*) as count FROM messages`; +console.log("Message count:", count); +``` + +## Scheduled Task Issues + +### "Task never fires" + +1. **Method name mismatch** + ```typescript + // Schedule references method that must exist + await this.schedule(60, "sendReminder", { ... }); + + // Method must be defined on the class + async sendReminder(data: any) { + // This method MUST exist + } + ``` + +2. **Cron syntax error** + ```typescript + // Invalid cron + await this.schedule("every 5 minutes", "task", {}); // Wrong + + // Valid cron + await this.schedule("*/5 * * * *", "task", {}); // Every 5 minutes + ``` + +3. **Task was cancelled** + ```typescript + const schedules = await this.getSchedules(); + console.log("Active schedules:", schedules); + ``` + +### "Task fires multiple times" + +If you schedule in `onStart()` without checking: + +```typescript +async onStart() { + // Bad - schedules new task every time agent wakes + await this.schedule("0 9 * * *", "dailyTask", {}); + + // Good - check first + const schedules = await this.getSchedules(); + const hasDaily = schedules.some(s => s.callback === "dailyTask"); + if (!hasDaily) { + await this.schedule("0 9 * * *", "dailyTask", {}); + } +} +``` + +## Deployment Issues + +### "Class MyAgent is not exported" + +```typescript +// src/index.ts - Must export the class +export { MyAgent } from "./agent"; + +// Or if defined in same file +export class MyAgent extends Agent { ... } +``` + +### "Durable Object not found" + +Check `wrangler.toml`: + +```toml +[durable_objects] +bindings = [{ name = "AGENT", class_name = "MyAgent" }] + +[[migrations]] +tag = "v1" +new_classes = ["MyAgent"] +``` + +### "Migration required" + +When adding new Durable Object classes: + +```toml +[[migrations]] +tag = "v2" # Increment from previous +new_classes = ["NewAgentClass"] + +# Or for renames +# renamed_classes = [{ from = "OldName", to = "NewName" }] +``` + +## AI Integration Issues + +### "AI binding not found" + +Add to `wrangler.toml`: + +```toml +[ai] +binding = "AI" +``` + +### "Model not found" / "Rate limited" + +```typescript +// Check model name is correct +const response = await this.env.AI.run( + "@cf/meta/llama-3-8b-instruct", // Exact model name + { messages: [...] } +); + +// Handle rate limits +try { + const response = await this.env.AI.run(...); +} catch (error) { + if (error.message.includes("rate limit")) { + // Retry with backoff or use queue + } +} +``` + +### "Streaming not working" + +```typescript +// Enable streaming +const stream = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", { + messages: [...], + stream: true, // Must be true +}); + +// Iterate over stream +for await (const chunk of stream) { + connection.send(JSON.stringify({ type: "chunk", content: chunk.response })); +} +``` + +## Debugging Tips + +### Enable Verbose Logging + +```typescript +export class MyAgent extends Agent { + async onStart() { + console.log("Agent starting, state:", JSON.stringify(this.state)); + } + + async onConnect(connection: Connection) { + console.log("Client connected:", connection.id); + } + + async onMessage(connection: Connection, message: string) { + console.log("Received message:", message); + // ... handle + console.log("State after:", JSON.stringify(this.state)); + } + + async onClose(connection: Connection) { + console.log("Client disconnected:", connection.id); + } +} +``` + +View logs: +```bash +wrangler tail --format pretty +``` + +### Test Locally First + +```bash +npm start +# Connect with test client or use browser console: +# new WebSocket("ws://localhost:8787/agent/test") +``` + +### Inspect State + +Add a debug endpoint: + +```typescript +async onRequest(request: Request) { + const url = new URL(request.url); + + if (url.pathname === "/debug") { + return Response.json({ + state: this.state, + schedules: await this.getSchedules(), + }); + } + + return new Response("Not found", { status: 404 }); +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..168a82879a62bfde7e69d7380b9e30a522dffcf6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/SKILL.md @@ -0,0 +1,266 @@ +--- +name: building-mcp-server-on-cloudflare +description: | + Builds remote MCP (Model Context Protocol) servers on Cloudflare Workers + with tools, OAuth authentication, and production deployment. Generates + server code, configures auth providers, and deploys to Workers. + + Use when: user wants to "build MCP server", "create MCP tools", "remote + MCP", "deploy MCP", add "OAuth to MCP", or mentions Model Context Protocol + on Cloudflare. Also triggers on "MCP authentication" or "MCP deployment". + Biases towards retrieval from Cloudflare docs over pre-trained knowledge. +--- + +# Building MCP Servers on Cloudflare + +Your knowledge of the MCP SDK and Cloudflare Workers integration may be outdated. **Prefer retrieval over pre-training** for any MCP server task. + +## Retrieval Sources + +| Source | How to retrieve | Use for | +|--------|----------------|---------| +| MCP docs | `https://developers.cloudflare.com/agents/mcp/` | Server setup, auth, deployment | +| MCP spec | `https://modelcontextprotocol.io/` | Protocol spec, tool/resource definitions | +| Workers docs | Search tool or `https://developers.cloudflare.com/workers/` | Runtime APIs, bindings, config | + +## When to Use + +- User wants to build a remote MCP server +- User needs to expose tools via MCP +- User asks about MCP authentication or OAuth +- User wants to deploy MCP to Cloudflare Workers + +## Prerequisites + +- Cloudflare account with Workers enabled +- Node.js 18+ and npm/pnpm/yarn +- Wrangler CLI (`npm install -g wrangler`) + +## Quick Start + +### Option 1: Public Server (No Auth) + +```bash +npm create cloudflare@latest -- my-mcp-server \ + --template=cloudflare/ai/demos/remote-mcp-authless +cd my-mcp-server +npm start +``` + +Server runs at `http://localhost:8788/mcp` + +### Option 2: Authenticated Server (OAuth) + +```bash +npm create cloudflare@latest -- my-mcp-server \ + --template=cloudflare/ai/demos/remote-mcp-github-oauth +cd my-mcp-server +``` + +Requires OAuth app setup. See [references/oauth-setup.md](references/oauth-setup.md). + +## Core Workflow + +### Step 1: Define Tools + +Tools are functions MCP clients can call. Define them using `server.tool()`: + +```typescript +import { McpAgent } from "agents/mcp"; +import { z } from "zod"; + +export class MyMCP extends McpAgent { + server = new Server({ name: "my-mcp", version: "1.0.0" }); + + async init() { + // Simple tool with parameters + this.server.tool( + "add", + { a: z.number(), b: z.number() }, + async ({ a, b }) => ({ + content: [{ type: "text", text: String(a + b) }], + }) + ); + + // Tool that calls external API + this.server.tool( + "get_weather", + { city: z.string() }, + async ({ city }) => { + const response = await fetch(`https://api.weather.com/${city}`); + const data = await response.json(); + return { + content: [{ type: "text", text: JSON.stringify(data) }], + }; + } + ); + } +} +``` + +### Step 2: Configure Entry Point + +**Public server** (`src/index.ts`): + +```typescript +import { MyMCP } from "./mcp"; + +export default { + fetch(request: Request, env: Env, ctx: ExecutionContext) { + const url = new URL(request.url); + if (url.pathname === "/mcp") { + return MyMCP.serveSSE("/mcp").fetch(request, env, ctx); + } + return new Response("MCP Server", { status: 200 }); + }, +}; + +export { MyMCP }; +``` + +**Authenticated server** — See [references/oauth-setup.md](references/oauth-setup.md). + +### Step 3: Test Locally + +```bash +# Start server +npm start + +# In another terminal, test with MCP Inspector +npx @modelcontextprotocol/inspector@latest +# Open http://localhost:5173, enter http://localhost:8788/mcp +``` + +### Step 4: Deploy + +```bash +npx wrangler deploy +``` + +Server accessible at `https://[worker-name].[account].workers.dev/mcp` + +### Step 5: Connect Clients + +**Codex MCP client setup:** + +```bash +codex mcp add my-server -- npx mcp-remote https://my-mcp.workers.dev/mcp +``` + +Restart Codex after updating the MCP configuration. + +## Tool Patterns + +### Return Types + +```typescript +// Text response +return { content: [{ type: "text", text: "result" }] }; + +// Multiple content items +return { + content: [ + { type: "text", text: "Here's the data:" }, + { type: "text", text: JSON.stringify(data, null, 2) }, + ], +}; +``` + +### Input Validation with Zod + +```typescript +this.server.tool( + "create_user", + { + email: z.string().email(), + name: z.string().min(1).max(100), + role: z.enum(["admin", "user", "guest"]), + age: z.number().int().min(0).optional(), + }, + async (params) => { + // params are fully typed and validated + } +); +``` + +### Accessing Environment/Bindings + +```typescript +export class MyMCP extends McpAgent { + async init() { + this.server.tool("query_db", { sql: z.string() }, async ({ sql }) => { + // Access D1 binding + const result = await this.env.DB.prepare(sql).all(); + return { content: [{ type: "text", text: JSON.stringify(result) }] }; + }); + } +} +``` + +## Authentication + +For OAuth-protected servers, see [references/oauth-setup.md](references/oauth-setup.md). + +Supported providers: +- GitHub +- Google +- Auth0 +- Stytch +- WorkOS +- Any OAuth 2.0 compliant provider + +## Wrangler Configuration + +Minimal `wrangler.toml`: + +```toml +name = "my-mcp-server" +main = "src/index.ts" +compatibility_date = "2024-12-01" + +[durable_objects] +bindings = [{ name = "MCP", class_name = "MyMCP" }] + +[[migrations]] +tag = "v1" +new_classes = ["MyMCP"] +``` + +With bindings (D1, KV, etc.): + +```toml +[[d1_databases]] +binding = "DB" +database_name = "my-db" +database_id = "xxx" + +[[kv_namespaces]] +binding = "KV" +id = "xxx" +``` + +## Common Issues + +### "Tool not found" in Client + +1. Verify tool name matches exactly (case-sensitive) +2. Ensure `init()` registers tools before connections +3. Check server logs: `wrangler tail` + +### Connection Fails + +1. Confirm endpoint path is `/mcp` +2. Check CORS if browser-based client +3. Verify Worker is deployed: `wrangler deployments list` + +### OAuth Redirect Errors + +1. Callback URL must match OAuth app config exactly +2. Check `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` are set +3. For local dev, use `http://localhost:8788/callback` + +## References + +- [references/examples.md](references/examples.md) — Official templates and production examples +- [references/oauth-setup.md](references/oauth-setup.md) — OAuth provider configuration +- [references/troubleshooting.md](references/troubleshooting.md) — Error codes and fixes diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c725600d7a363e6e5b4293d90a4829a6b8a2f78 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Building MCP Servers on Cloudflare" + short_description: "Build remote MCP servers on Cloudflare Workers" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/examples.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/examples.md new file mode 100644 index 0000000000000000000000000000000000000000..57b213830a07024a12e442aaf6442f8b410f9af2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/examples.md @@ -0,0 +1,108 @@ +# Project Bootstrapping + +Instructions for creating new MCP server projects. + +--- + +## Create Commands + +Execute in terminal to generate a new project: + +**Without authentication:** + +```bash +npm create cloudflare@latest -- my-mcp-server \ + --template=cloudflare/ai/demos/remote-mcp-authless +``` + +**With GitHub login:** + +```bash +npm create cloudflare@latest -- my-mcp-server \ + --template=cloudflare/ai/demos/remote-mcp-github-oauth +``` + +**With Google login:** + +```bash +npm create cloudflare@latest -- my-mcp-server \ + --template=cloudflare/ai/demos/remote-mcp-google-oauth +``` + +--- + +## Additional Boilerplate Locations + +**Main repository:** `github.com/cloudflare/ai` (check demos directory) + +Other authentication providers: +- Auth0 +- WorkOS AuthKit +- Logto +- Descope +- Stytch + +**Cloudflare tooling:** `github.com/cloudflare/mcp-server-cloudflare` + +--- + +## Selection Matrix + +| Goal | Boilerplate | +|------|-------------| +| Testing/learning | authless | +| GitHub API access | github-oauth | +| Google API access | google-oauth | +| Enterprise auth | auth0 / authkit | +| Slack apps | slack-oauth | +| Zero Trust | cf-access | + +--- + +## Platform Documentation + +- developers.cloudflare.com/agents/model-context-protocol/ +- developers.cloudflare.com/agents/guides/remote-mcp-server/ +- developers.cloudflare.com/agents/guides/test-remote-mcp-server/ +- developers.cloudflare.com/agents/model-context-protocol/authorization/ + +--- + +## Commands Reference + +**Local execution:** + +```bash +cd my-mcp-server +npm install +npm start +# Accessible at http://localhost:8788/mcp +``` + +**Production push:** + +```bash +npx wrangler deploy +# Accessible at https://[worker-name].[subdomain].workers.dev/mcp +``` + +**Codex MCP client setup:** + +```bash +codex mcp add my-server -- npx mcp-remote https://my-mcp-server.my-account.workers.dev/mcp +``` + +**Inspector testing:** + +```bash +npx @modelcontextprotocol/inspector@latest +# Launch browser at http://localhost:5173 +# Input your server URL: http://localhost:8788/mcp +``` + +--- + +## Help Channels + +- Cloudflare Discord +- GitHub discussions on cloudflare/ai repository diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/oauth-setup.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/oauth-setup.md new file mode 100644 index 0000000000000000000000000000000000000000..e97479d7a4ad09626c7d1edae86847eb5dce49a9 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/oauth-setup.md @@ -0,0 +1,338 @@ +# Securing MCP Servers + +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. + +Cloudflare's `workers-oauth-provider` handles token management, client registration, and access token validation automatically. + +## Basic Setup + +```typescript +import { OAuthProvider } from "@cloudflare/workers-oauth-provider"; +import { createMcpHandler } from "agents/mcp"; + +const apiHandler = { + async fetch(request: Request, env: unknown, ctx: ExecutionContext) { + return createMcpHandler(server)(request, env, ctx); + } +}; + +export default new OAuthProvider({ + authorizeEndpoint: "/authorize", + tokenEndpoint: "/oauth/token", + clientRegistrationEndpoint: "/oauth/register", + apiRoute: "/mcp", + apiHandler: apiHandler, + defaultHandler: AuthHandler +}); +``` + +## Proxy Server Pattern + +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. + +Building a secure proxy server requires careful attention to several security concerns. + +--- + +## Security Requirements + +### Redirect URI Validation + +The `workers-oauth-provider` validates that `redirect_uri` in authorization requests matches registered URIs. This prevents attackers from redirecting authorization codes to malicious endpoints. + +### Consent Dialog + +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. + +Your consent dialog should: +- Identify the requesting MCP client by name +- Display the specific scopes being requested + +--- + +## CSRF Protection + +Prevent attackers from tricking users into approving malicious OAuth clients. Use a random token stored in a secure cookie. + +```typescript +// Generate token when showing consent form +function generateCSRFProtection(): { token: string; setCookie: string } { + const token = crypto.randomUUID(); + const setCookie = `__Host-CSRF_TOKEN=${token}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`; + return { token, setCookie }; +} + +// Validate token when user approves +function validateCSRFToken(formData: FormData, request: Request): { clearCookie: string } { + const tokenFromForm = formData.get("csrf_token"); + const cookieHeader = request.headers.get("Cookie") || ""; + const tokenFromCookie = cookieHeader + .split(";") + .find((c) => c.trim().startsWith("__Host-CSRF_TOKEN=")) + ?.split("=")[1]; + + if (!tokenFromForm || !tokenFromCookie || tokenFromForm !== tokenFromCookie) { + throw new Error("CSRF token mismatch"); + } + + return { + clearCookie: `__Host-CSRF_TOKEN=; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=0` + }; +} +``` + +Include the token as a hidden form field: + +```html + +``` + +--- + +## Input Sanitization + +Client-controlled content (names, logos, URIs) can execute malicious scripts if not sanitized. Treat all client metadata as untrusted. + +```typescript +function sanitizeText(text: string): string { + return text + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function sanitizeUrl(url: string): string { + if (!url) return ""; + try { + const parsed = new URL(url); + if (!["http:", "https:"].includes(parsed.protocol)) { + return ""; + } + return url; + } catch { + return ""; + } +} +``` + +**Required protections:** +- Client names/descriptions: HTML-escape before rendering +- Logo URLs: Allow only `http:` and `https:` schemes +- Client URIs: Same as logo URLs +- Scopes: Treat as text, HTML-escape + +--- + +## Content Security Policy + +CSP headers block dangerous content and provide defense in depth. + +```typescript +function buildSecurityHeaders(setCookie: string, nonce?: string): HeadersInit { + const cspDirectives = [ + "default-src 'none'", + "script-src 'self'" + (nonce ? ` 'nonce-${nonce}'` : ""), + "style-src 'self' 'unsafe-inline'", + "img-src 'self' https:", + "font-src 'self'", + "form-action 'self'", + "frame-ancestors 'none'", + "base-uri 'self'", + "connect-src 'self'" + ].join("; "); + + return { + "Content-Security-Policy": cspDirectives, + "X-Frame-Options": "DENY", + "X-Content-Type-Options": "nosniff", + "Content-Type": "text/html; charset=utf-8", + "Set-Cookie": setCookie + }; +} +``` + +--- + +## State Management + +Ensure the same user that hits authorize reaches the callback. Use a random state token stored in KV with short expiration. + +```typescript +// Create state before redirecting to upstream provider +async function createOAuthState( + oauthReqInfo: AuthRequest, + kv: KVNamespace +): Promise<{ stateToken: string }> { + const stateToken = crypto.randomUUID(); + await kv.put(`oauth:state:${stateToken}`, JSON.stringify(oauthReqInfo), { + expirationTtl: 600 + }); + return { stateToken }; +} + +// Bind state to browser session via hashed cookie +async function bindStateToSession(stateToken: string): Promise<{ setCookie: string }> { + const encoder = new TextEncoder(); + const data = encoder.encode(stateToken); + const hashBuffer = await crypto.subtle.digest("SHA-256", data); + const hashArray = Array.from(new Uint8Array(hashBuffer)); + const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); + + return { + setCookie: `__Host-CONSENTED_STATE=${hashHex}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600` + }; +} + +// Validate in callback - check both KV and session cookie +async function validateOAuthState( + request: Request, + kv: KVNamespace +): Promise<{ oauthReqInfo: AuthRequest; clearCookie: string }> { + const url = new URL(request.url); + const stateFromQuery = url.searchParams.get("state"); + + if (!stateFromQuery) { + throw new Error("Missing state parameter"); + } + + // Check KV + const storedDataJson = await kv.get(`oauth:state:${stateFromQuery}`); + if (!storedDataJson) { + throw new Error("Invalid or expired state"); + } + + // Check session cookie matches + const cookieHeader = request.headers.get("Cookie") || ""; + const consentedStateHash = cookieHeader + .split(";") + .find((c) => c.trim().startsWith("__Host-CONSENTED_STATE=")) + ?.split("=")[1]; + + if (!consentedStateHash) { + throw new Error("Missing session binding cookie"); + } + + // Hash state and compare + const encoder = new TextEncoder(); + const hashBuffer = await crypto.subtle.digest("SHA-256", encoder.encode(stateFromQuery)); + const stateHash = Array.from(new Uint8Array(hashBuffer)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); + + if (stateHash !== consentedStateHash) { + throw new Error("State token does not match session"); + } + + await kv.delete(`oauth:state:${stateFromQuery}`); + + return { + oauthReqInfo: JSON.parse(storedDataJson), + clearCookie: `__Host-CONSENTED_STATE=; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=0` + }; +} +``` + +--- + +## Approved Clients Registry + +Maintain a registry of approved client IDs per user. Store in a cryptographically signed cookie with HMAC-SHA256. + +```typescript +export async function addApprovedClient( + request: Request, + clientId: string, + cookieSecret: string +): Promise { + const existingClients = await getApprovedClientsFromCookie(request, cookieSecret) || []; + const updatedClients = Array.from(new Set([...existingClients, clientId])); + + const payload = JSON.stringify(updatedClients); + const signature = await signData(payload, cookieSecret); + const cookieValue = `${signature}.${btoa(payload)}`; + + return `__Host-APPROVED_CLIENTS=${cookieValue}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=2592000`; +} +``` + +When reading the cookie, verify the signature before trusting data. If client isn't approved, show consent dialog. + +--- + +## Cookie Security + +### Why `__Host-` prefix? + +The `__Host-` prefix prevents subdomain attacks on `*.workers.dev` domains. Requirements: +- Must have `Secure` flag (HTTPS only) +- Must have `Path=/` +- Must not have `Domain` attribute + +Without this prefix, an attacker on `evil.workers.dev` could set cookies for your `mcp-server.workers.dev` domain. + +### Multiple OAuth Providers + +If running multiple OAuth flows on the same domain, namespace your cookies: +- `__Host-CSRF_TOKEN_GITHUB` vs `__Host-CSRF_TOKEN_GOOGLE` +- `__Host-APPROVED_CLIENTS_GITHUB` vs `__Host-APPROVED_CLIENTS_GOOGLE` + +--- + +## Inline JavaScript + +If your consent dialog needs inline JavaScript, use data attributes and nonces: + +```typescript +const nonce = crypto.randomUUID(); + +const html = ` + +`; + +return new Response(html, { + headers: buildSecurityHeaders(setCookie, nonce) +}); +``` + +Data attributes store user-controlled data separately from executable code. Nonces with CSP allow your specific script while blocking injected scripts. + +--- + +## Provider-Specific Setup + +### GitHub + +1. Create OAuth App at github.com/settings/developers +2. Set callback URL: `https://[worker].workers.dev/callback` +3. Store secrets: + ```bash + wrangler secret put GITHUB_CLIENT_ID + wrangler secret put GITHUB_CLIENT_SECRET + ``` + +### Google + +1. Create OAuth Client at console.cloud.google.com/apis/credentials +2. Set authorized redirect URI +3. Scopes: `openid email profile` + +### Auth0 + +1. Create Regular Web Application in Auth0 Dashboard +2. Set allowed callback URLs +3. Endpoints: `https://${AUTH0_DOMAIN}/authorize`, `/oauth/token`, `/userinfo` + +--- + +## References + +- [MCP Authorization Spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) +- [MCP Security Best Practices](https://modelcontextprotocol.io/specification/draft/basic/security_best_practices) +- [RFC 9700 - OAuth Security](https://www.rfc-editor.org/rfc/rfc9700) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/troubleshooting.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..f1e62e7767870715790200be6d0beec7479d6282 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/troubleshooting.md @@ -0,0 +1,317 @@ +# MCP Server Troubleshooting + +Common errors and solutions for MCP servers on Cloudflare. + +## Connection Issues + +### "Failed to connect to MCP server" + +**Symptoms:** Client cannot establish connection to deployed server. + +**Causes & Solutions:** + +1. **Wrong URL path** + ``` + # Wrong + https://my-server.workers.dev/ + + # Correct + https://my-server.workers.dev/mcp + ``` + +2. **Worker not deployed** + ```bash + wrangler deployments list + # If empty, deploy first: + wrangler deploy + ``` + +3. **Worker crashed on startup** + ```bash + wrangler tail + # Check for initialization errors + ``` + +### "WebSocket connection failed" + +MCP uses SSE (Server-Sent Events), not WebSockets. Ensure your client is configured for SSE transport: + +```json +{ + "mcpServers": { + "my-server": { + "command": "npx", + "args": ["mcp-remote", "https://my-server.workers.dev/mcp"] + } + } +} +``` + +### CORS Errors in Browser + +If calling from browser-based client: + +```typescript +// Add CORS headers to your worker +export default { + async fetch(request: Request, env: Env) { + // Handle preflight + if (request.method === "OPTIONS") { + return new Response(null, { + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, POST, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type", + }, + }); + } + + const response = await handleRequest(request, env); + + // Add CORS headers to response + const headers = new Headers(response.headers); + headers.set("Access-Control-Allow-Origin", "*"); + + return new Response(response.body, { + status: response.status, + headers, + }); + }, +}; +``` + +## Tool Errors + +### "Tool not found: [tool_name]" + +**Causes:** + +1. Tool not registered in `init()` +2. Tool name mismatch (case-sensitive) +3. `init()` threw an error before registering tool + +**Debug:** + +```typescript +async init() { + console.log("Registering tools..."); + + this.server.tool("my_tool", { ... }, async () => { ... }); + + console.log("Tools registered:", this.server.listTools()); +} +``` + +Check logs: `wrangler tail` + +### "Invalid parameters for tool" + +Zod validation failed. Check parameter schema: + +```typescript +// Schema expects number, client sent string +this.server.tool( + "calculate", + { value: z.number() }, // Client must send number, not "123" + async ({ value }) => { ... } +); + +// Fix: Coerce string to number +this.server.tool( + "calculate", + { value: z.coerce.number() }, // "123" → 123 + async ({ value }) => { ... } +); +``` + +### Tool Timeout + +Workers have CPU time limits (10-30ms for free, longer for paid). For long operations: + +```typescript +this.server.tool( + "long_operation", + { ... }, + async (params) => { + // Break into smaller chunks + // Or use Queues/Durable Objects for background work + + // Don't do this: + // await sleep(5000); // Will timeout + + return { content: [{ type: "text", text: "Queued for processing" }] }; + } +); +``` + +## Authentication Errors + +### "401 Unauthorized" + +OAuth token missing or expired. + +1. **Check client is handling OAuth flow** +2. **Verify secrets are set:** + ```bash + wrangler secret list + # Should show GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET + ``` + +3. **Check KV namespace exists:** + ```bash + wrangler kv namespace list + # Should show OAUTH_KV + ``` + +### "Invalid redirect_uri" + +OAuth callback URL doesn't match app configuration. + +**Local development:** +- OAuth app callback: `http://localhost:8788/callback` + +**Production:** +- OAuth app callback: `https://[worker-name].[account].workers.dev/callback` + +Must match EXACTLY (including trailing slash or lack thereof). + +### "State mismatch" / CSRF Error + +State parameter validation failed. + +1. **Clear browser cookies and retry** +2. **Check KV is storing state:** + ```typescript + // In your auth handler + console.log("Storing state:", state); + await env.OAUTH_KV.put(`state:${state}`, "1", { expirationTtl: 600 }); + ``` + +3. **Verify same domain for all requests** + +## Binding Errors + +### "Binding not found: [BINDING_NAME]" + +Binding not in `wrangler.toml` or not deployed. + +```toml +# wrangler.toml +[[d1_databases]] +binding = "DB" # Must match env.DB in code +database_name = "mydb" +database_id = "xxx-xxx" +``` + +After adding bindings: `wrangler deploy` + +### "D1_ERROR: no such table" + +Migrations not applied. + +```bash +# Local +wrangler d1 migrations apply DB_NAME --local + +# Production +wrangler d1 migrations apply DB_NAME +``` + +### Durable Object Not Found + +```toml +# wrangler.toml must have: +[durable_objects] +bindings = [{ name = "MCP", class_name = "MyMCP" }] + +[[migrations]] +tag = "v1" +new_classes = ["MyMCP"] +``` + +And class must be exported: + +```typescript +export { MyMCP }; // Don't forget this! +``` + +## Deployment Errors + +### "Class MyMCP is not exported" + +```typescript +// src/index.ts - Must export the class +export { MyMCP } from "./mcp"; + +// OR in same file +export class MyMCP extends McpAgent { ... } +``` + +### "Migration required" + +New Durable Object class needs migration: + +```toml +# Add to wrangler.toml +[[migrations]] +tag = "v2" # Increment version +new_classes = ["NewClassName"] +# Or for renames: +# renamed_classes = [{ from = "OldName", to = "NewName" }] +``` + +### Build Errors + +```bash +# Clear cache and rebuild +rm -rf node_modules .wrangler +npm install +wrangler deploy +``` + +## Debugging Tips + +### Enable Verbose Logging + +```typescript +export class MyMCP extends McpAgent { + async init() { + console.log("MCP Server initializing..."); + console.log("Environment:", Object.keys(this.env)); + + this.server.tool("test", {}, async () => { + console.log("Test tool called"); + return { content: [{ type: "text", text: "OK" }] }; + }); + + console.log("Tools registered"); + } +} +``` + +View logs: +```bash +wrangler tail --format pretty +``` + +### Test Locally First + +```bash +npm start +npx @modelcontextprotocol/inspector@latest +``` + +Always verify tools work locally before deploying. + +### Check Worker Health + +```bash +# List deployments +wrangler deployments list + +# View recent logs +wrangler tail + +# Check worker status +curl -I https://your-worker.workers.dev/mcp +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/LICENSE.txt b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..13e25df86ce06eb6488e6a6bc5c5847f5dedc352 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/LICENSE.txt @@ -0,0 +1,201 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf of + any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don\'t include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..1e49c5c59924762524bc4a012c3aec9f08282606 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/SKILL.md @@ -0,0 +1,228 @@ +--- +name: cloudflare +description: Comprehensive Cloudflare platform skill covering Workers, Pages, storage (KV, D1, R2), AI (Workers AI, Vectorize, Agents SDK), networking (Tunnel, Spectrum), security (WAF, DDoS), and infrastructure-as-code (Terraform, Pulumi). Use for any Cloudflare development task. Biases towards retrieval from Cloudflare docs over pre-trained knowledge. +references: + - workers + - pages + - d1 + - durable-objects + - workers-ai +--- + +# Cloudflare Platform Skill + +Consolidated skill for building on the Cloudflare platform. Use decision trees below to find the right product, then load detailed references. + +Your knowledge of Cloudflare APIs, types, limits, and pricing may be outdated. **Prefer retrieval over pre-training** — the references in this skill are starting points, not source of truth. + +## Retrieval Sources + +Fetch the **latest** information before citing specific numbers, API signatures, or configuration options. Do not rely on baked-in knowledge or these reference files alone. + +| Source | How to retrieve | Use for | +|--------|----------------|---------| +| Cloudflare docs | Search `https://developers.cloudflare.com/` directly | Limits, pricing, API reference, compatibility dates/flags | +| Workers types | `npm pack @cloudflare/workers-types` or check `node_modules` | Type signatures, binding shapes, handler types | +| Wrangler config schema | `node_modules/wrangler/config-schema.json` | Config fields, binding shapes, allowed values | +| Product changelogs | `https://developers.cloudflare.com/changelog/` | Recent changes to limits, features, deprecations | + +When a reference file and the docs disagree, **trust the docs**. This is especially important for: numeric limits, pricing tiers, type signatures, and configuration options. + +## Quick Decision Trees + +### "I need to run code" + +``` +Need to run code? +├─ Serverless functions at the edge → workers/ +├─ Full-stack web app with Git deploys → pages/ +├─ Stateful coordination/real-time → durable-objects/ +├─ Long-running multi-step jobs → workflows/ +├─ Run containers → containers/ +├─ Multi-tenant (customers deploy code) → workers-for-platforms/ +├─ Scheduled tasks (cron) → cron-triggers/ +├─ Lightweight edge logic (modify HTTP) → snippets/ +├─ Process Worker execution events (logs/observability) → tail-workers/ +└─ Optimize latency to backend infrastructure → smart-placement/ +``` + +### "I need to store data" + +``` +Need storage? +├─ Key-value (config, sessions, cache) → kv/ +├─ Relational SQL → d1/ (SQLite) or hyperdrive/ (existing Postgres/MySQL) +├─ Object/file storage (S3-compatible) → r2/ +├─ Message queue (async processing) → queues/ +├─ Vector embeddings (AI/semantic search) → vectorize/ +├─ Strongly-consistent per-entity state → durable-objects/ (DO storage) +├─ Secrets management → secrets-store/ +├─ Streaming ETL to R2 → pipelines/ +└─ Persistent cache (long-term retention) → cache-reserve/ +``` + +### "I need AI/ML" + +``` +Need AI? +├─ Run inference (LLMs, embeddings, images) → workers-ai/ +├─ Vector database for RAG/search → vectorize/ +├─ Build stateful AI agents → agents-sdk/ +├─ Gateway for any AI provider (caching, routing) → ai-gateway/ +└─ AI-powered search widget → ai-search/ +``` + +### "I need networking/connectivity" + +``` +Need networking? +├─ Expose local service to internet → tunnel/ +├─ TCP/UDP proxy (non-HTTP) → spectrum/ +├─ WebRTC TURN server → turn/ +├─ Private network connectivity → network-interconnect/ +├─ Optimize routing → argo-smart-routing/ +├─ Optimize latency to backend (not user) → smart-placement/ +└─ Real-time video/audio → realtimekit/ or realtime-sfu/ +``` + +### "I need security" + +``` +Need security? +├─ Web Application Firewall → waf/ +├─ DDoS protection → ddos/ +├─ Bot detection/management → bot-management/ +├─ API protection → api-shield/ +├─ CAPTCHA alternative → turnstile/ +└─ Credential leak detection → waf/ (managed ruleset) +``` + +### "I need media/content" + +``` +Need media? +├─ Image optimization/transformation → images/ +├─ Video streaming/encoding → stream/ +├─ Browser automation/screenshots → browser-rendering/ +└─ Third-party script management → zaraz/ +``` + +### "I need analytics/metrics data" + +``` +Need analytics? +├─ Query across all Cloudflare products (HTTP, Workers, DNS, etc.) → graphql-api/ +├─ Custom high-cardinality metrics from Workers → analytics-engine/ +├─ Client-side (RUM) performance data → web-analytics/ +├─ Workers Logs and real-time debugging → observability/ +└─ Raw logs (Logpush to external tools) → Cloudflare docs +``` + +### "I need infrastructure-as-code" + +``` +Need IaC? → pulumi/ (Pulumi), terraform/ (Terraform), or api/ (REST API) +``` + +## Product Index + +### Compute & Runtime +| Product | Reference | +|---------|-----------| +| Workers | `references/workers/` | +| Pages | `references/pages/` | +| Pages Functions | `references/pages-functions/` | +| Durable Objects | `references/durable-objects/` | +| Workflows | `references/workflows/` | +| Containers | `references/containers/` | +| Workers for Platforms | `references/workers-for-platforms/` | +| Cron Triggers | `references/cron-triggers/` | +| Tail Workers | `references/tail-workers/` | +| Snippets | `references/snippets/` | +| Smart Placement | `references/smart-placement/` | + +### Storage & Data +| Product | Reference | +|---------|-----------| +| KV | `references/kv/` | +| D1 | `references/d1/` | +| R2 | `references/r2/` | +| Queues | `references/queues/` | +| Hyperdrive | `references/hyperdrive/` | +| DO Storage | `references/do-storage/` | +| Secrets Store | `references/secrets-store/` | +| Pipelines | `references/pipelines/` | +| R2 Data Catalog | `references/r2-data-catalog/` | +| R2 SQL | `references/r2-sql/` | + +### AI & Machine Learning +| Product | Reference | +|---------|-----------| +| Workers AI | `references/workers-ai/` | +| Vectorize | `references/vectorize/` | +| Agents SDK | `references/agents-sdk/` | +| AI Gateway | `references/ai-gateway/` | +| AI Search | `references/ai-search/` | + +### Networking & Connectivity +| Product | Reference | +|---------|-----------| +| Tunnel | `references/tunnel/` | +| Spectrum | `references/spectrum/` | +| TURN | `references/turn/` | +| Network Interconnect | `references/network-interconnect/` | +| Argo Smart Routing | `references/argo-smart-routing/` | +| Workers VPC | `references/workers-vpc/` | + +### Security +| Product | Reference | +|---------|-----------| +| WAF | `references/waf/` | +| DDoS Protection | `references/ddos/` | +| Bot Management | `references/bot-management/` | +| API Shield | `references/api-shield/` | +| Turnstile | `references/turnstile/` | + +### Media & Content +| Product | Reference | +|---------|-----------| +| Images | `references/images/` | +| Stream | `references/stream/` | +| Browser Rendering | `references/browser-rendering/` | +| Zaraz | `references/zaraz/` | + +### Real-Time Communication +| Product | Reference | +|---------|-----------| +| RealtimeKit | `references/realtimekit/` | +| Realtime SFU | `references/realtime-sfu/` | + +### Developer Tools +| Product | Reference | +|---------|-----------| +| Wrangler | `references/wrangler/` | +| Miniflare | `references/miniflare/` | +| C3 | `references/c3/` | +| Observability | `references/observability/` | +| GraphQL Analytics API | `references/graphql-api/` | +| Analytics Engine | `references/analytics-engine/` | +| Web Analytics | `references/web-analytics/` | +| Sandbox | `references/sandbox/` | +| Workerd | `references/workerd/` | +| Workers Playground | `references/workers-playground/` | + +### Infrastructure as Code +| Product | Reference | +|---------|-----------| +| Pulumi | `references/pulumi/` | +| Terraform | `references/terraform/` | +| API | `references/api/` | + +### Other Services +| Product | Reference | +|---------|-----------| +| Email Routing | `references/email-routing/` | +| Email Workers | `references/email-workers/` | +| Static Assets | `references/static-assets/` | +| Bindings | `references/bindings/` | +| Cache Reserve | `references/cache-reserve/` | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..43075bbc76917d6567d843d14b15e2be9b753a49 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/agents/openai.yaml @@ -0,0 +1,6 @@ +interface: + display_name: "Cloudflare" + short_description: "Choose the right Cloudflare product and workflow" + icon_small: "./assets/cloudflare-small.svg" + icon_large: "./assets/cloudflare.png" + default_prompt: "Use Cloudflare context to choose the right product, verify setup, or plan the right deployment, data, or analytics workflow without guessing infrastructure." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/assets/cloudflare-small.svg b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/assets/cloudflare-small.svg new file mode 100644 index 0000000000000000000000000000000000000000..7feedbc2b37ff9f28f81d30aff52e605090bee86 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/assets/cloudflare-small.svg @@ -0,0 +1,3 @@ + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/README.md new file mode 100644 index 0000000000000000000000000000000000000000..535667f7041e6517f2c8d59a93c7673f756d1fa1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/README.md @@ -0,0 +1,138 @@ +# Cloudflare AI Search Reference + +Expert guidance for implementing Cloudflare AI Search (formerly AutoRAG), Cloudflare's managed semantic search and RAG service. + +## Overview + +**AI Search** is a managed RAG (Retrieval-Augmented Generation) pipeline that combines: +- Automatic semantic indexing of your content +- Vector similarity search +- Built-in LLM generation + +**Key value propositions:** +- **Zero vector management** - No manual embedding, indexing, or storage +- **Auto-indexing** - Content automatically re-indexed every 6 hours +- **Built-in generation** - Optional AI response generation from retrieved context +- **Multi-source** - Index from R2 buckets or website crawls + +**Data source options:** +- **R2 bucket** - Index files from Cloudflare R2 (supports MD, TXT, HTML, PDF, DOC, CSV, JSON) +- **Website** - Crawl and index website content (requires Cloudflare-hosted domain) + +**Indexing lifecycle:** +- Automatic 6-hour refresh cycle +- Manual "Force Sync" available (30s rate limit) +- Not designed for real-time updates + +## Quick Start + +**1. Create AI Search instance in dashboard:** +- Go to Cloudflare Dashboard → AI Search → Create +- Choose data source (R2 or website) +- Configure instance name and settings + +**2. Configure Worker:** + +```jsonc +// wrangler.jsonc +{ + "ai": { + "binding": "AI" + } +} +``` + +**3. Use in Worker:** + +```typescript +export default { + async fetch(request, env) { + const answer = await env.AI.autorag("my-search-instance").aiSearch({ + query: "How do I configure caching?", + model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast" + }); + + return Response.json({ answer: answer.response }); + } +}; +``` + +## When to Use AI Search + +### AI Search vs Vectorize + +| Factor | AI Search | Vectorize | +|--------|-----------|-----------| +| **Management** | Fully managed | Manual embedding + indexing | +| **Use when** | Want zero-ops RAG pipeline | Need custom embeddings/control | +| **Indexing** | Automatic (6hr cycle) | Manual via API | +| **Generation** | Built-in optional | Bring your own LLM | +| **Data sources** | R2 or website | Manual insert | +| **Best for** | Docs, support, enterprise search | Custom ML pipelines, real-time | + +### AI Search vs Direct Workers AI + +| Factor | AI Search | Workers AI (direct) | +|--------|-----------|---------------------| +| **Context** | Automatic retrieval | Manual context building | +| **Use when** | Need RAG (search + generate) | Simple generation tasks | +| **Indexing** | Built-in | Not applicable | +| **Best for** | Knowledge bases, docs | Simple chat, transformations | + +### search() vs aiSearch() + +| Method | Returns | Use When | +|--------|---------|----------| +| `search()` | Search results only | Building custom UI, need raw chunks | +| `aiSearch()` | AI response + results | Need ready-to-use answer (chatbot, Q&A) | + +### Real-time Updates Consideration + +**AI Search is NOT ideal if:** +- Need real-time content updates (<6 hours) +- Content changes multiple times per hour +- Strict freshness requirements + +**AI Search IS ideal if:** +- Content relatively stable (docs, policies, knowledge bases) +- 6-hour refresh acceptable +- Prefer zero-ops over real-time + +## Platform Limits + +| Limit | Value | +|-------|-------| +| Max instances per account | 10 | +| Max files per instance | 100,000 | +| Max file size | 4 MB | +| Index frequency | Every 6 hours | +| Force Sync rate limit | Once per 30 seconds | +| Filter nesting depth | 2 levels | +| Filters per compound | 10 | +| Score threshold range | 0.0 - 1.0 | + +## Reading Order + +Navigate these references based on your task: + +| Task | Read | Est. Time | +|------|------|-----------| +| **Understand AI Search** | README only | 5 min | +| **Implement basic search** | README → api.md | 10 min | +| **Configure data source** | README → configuration.md | 10 min | +| **Production patterns** | patterns.md | 15 min | +| **Debug issues** | gotchas.md | 10 min | +| **Full implementation** | README → api.md → patterns.md | 30 min | + +## In This Reference + +- **[api.md](api.md)** - API endpoints, methods, TypeScript interfaces +- **[configuration.md](configuration.md)** - Setup, data sources, wrangler config +- **[patterns.md](patterns.md)** - Common patterns, decision guidance, code examples +- **[gotchas.md](gotchas.md)** - Troubleshooting, code-level gotchas, limits + +## See Also + +- [Cloudflare AI Search Docs](https://developers.cloudflare.com/ai-search/) +- [Workers AI Docs](https://developers.cloudflare.com/workers-ai/) +- [Vectorize Docs](https://developers.cloudflare.com/vectorize/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/api.md new file mode 100644 index 0000000000000000000000000000000000000000..b6220c464a687aaa35a923f4c0781e4fa6b50f6f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/api.md @@ -0,0 +1,87 @@ +# AI Search API Reference + +## Workers Binding + +```typescript +const answer = await env.AI.autorag("instance-name").aiSearch(options); +const results = await env.AI.autorag("instance-name").search(options); +const instances = await env.AI.autorag("_").listInstances(); +``` + +## aiSearch() Options + +```typescript +interface AiSearchOptions { + query: string; // User query + model: string; // Workers AI model ID + system_prompt?: string; // LLM instructions + rewrite_query?: boolean; // Fix typos (default: false) + max_num_results?: number; // Max chunks (default: 10) + ranking_options?: { score_threshold?: number }; // 0.0-1.0 (default: 0.3) + reranking?: { enabled: boolean; model: string }; + stream?: boolean; // Stream response (default: false) + filters?: Filter; // Metadata filters + page?: string; // Pagination token +} +``` + +## Response + +```typescript +interface AiSearchResponse { + search_query: string; // Query used (rewritten if enabled) + response: string; // AI-generated answer + data: SearchResult[]; // Retrieved chunks + has_more: boolean; + next_page?: string; +} + +interface SearchResult { + id: string; + score: number; + content: string; + metadata: { filename: string; folder: string; timestamp: number }; +} +``` + +## Filters + +```typescript +// Comparison +{ column: "folder", operator: "gte", value: "docs/" } + +// Compound +{ operator: "and", filters: [ + { column: "folder", operator: "gte", value: "docs/" }, + { column: "timestamp", operator: "gte", value: 1704067200 } +]} +``` + +**Operators:** `eq`, `ne`, `gt`, `gte`, `lt`, `lte` + +**Built-in metadata:** `filename`, `folder`, `timestamp` (Unix seconds) + +## Streaming + +```typescript +const stream = await env.AI.autorag("docs").aiSearch({ query, model, stream: true }); +return new Response(stream, { headers: { "Content-Type": "text/event-stream" } }); +``` + +## Error Types + +| Error | Cause | +|-------|-------| +| `AutoRAGNotFoundError` | Instance doesn't exist | +| `AutoRAGUnauthorizedError` | Invalid/missing token | +| `AutoRAGValidationError` | Invalid parameters | + +## REST API + +```bash +curl https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/autorag/rags/{NAME}/ai-search \ + -H "Authorization: Bearer {TOKEN}" \ + -d '{"query": "...", "model": "@cf/meta/llama-3.3-70b-instruct-fp8-fast"}' +``` + +Requires Service API token with "AI Search - Read" permission. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..d1f34adb5410af9e4b766e9cd5ae75628af4e6bc --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/configuration.md @@ -0,0 +1,88 @@ +# AI Search Configuration + +## Worker Setup + +```jsonc +// wrangler.jsonc +{ + "ai": { "binding": "AI" } +} +``` + +```typescript +interface Env { + AI: Ai; +} + +const answer = await env.AI.autorag("my-instance").aiSearch({ + query: "How do I configure caching?", + model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast" +}); +``` + +## Data Sources + +### R2 Bucket + +Dashboard: AI Search → Create Instance → Select R2 bucket + +**Supported formats:** `.md`, `.txt`, `.html`, `.pdf`, `.doc`, `.docx`, `.csv`, `.json` + +**Auto-indexed metadata:** `filename`, `folder`, `timestamp` + +### Website Crawler + +Requirements: +- Domain on Cloudflare +- `sitemap.xml` at root +- Bot protection must allow `CloudflareAISearch` user agent + +## Path Filtering (R2) + +``` +docs/**/*.md # All .md in docs/ recursively +**/*.draft.md # Exclude (use in exclude patterns) +``` + +## Indexing + +- **Automatic:** Every 6 hours +- **Force Sync:** Dashboard button (30s rate limit between syncs) +- **Pause:** Settings → Pause Indexing (existing index remains searchable) + +## Service API Token + +Dashboard: AI Search → Instance → Use AI Search → API → Create Token + +Permissions: +- **Read** - search operations +- **Edit** - instance management + +Store securely: +```bash +wrangler secret put AI_SEARCH_TOKEN +``` + +## Multi-Environment + +```toml +# wrangler.toml +[env.production.vars] +AI_SEARCH_INSTANCE = "prod-docs" + +[env.staging.vars] +AI_SEARCH_INSTANCE = "staging-docs" +``` + +```typescript +const answer = await env.AI.autorag(env.AI_SEARCH_INSTANCE).aiSearch({ query }); +``` + +## Monitoring + +```typescript +const instances = await env.AI.autorag("_").listInstances(); +console.log(instances.find(i => i.name === "docs")); +``` + +Dashboard shows: files indexed, status, last index time, storage usage. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..04c987f6a6813bccec5625ff8e126e84dd145383 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/gotchas.md @@ -0,0 +1,81 @@ +# AI Search Gotchas + +## Type Safety + +**Timestamp precision:** Use seconds (10-digit), not milliseconds. +```typescript +const nowInSeconds = Math.floor(Date.now() / 1000); // Correct +``` + +**Folder prefix matching:** Use `gte` for "starts with" on paths. +```typescript +filters: { column: "folder", operator: "gte", value: "docs/api/" } // Matches nested +``` + +## Filter Limitations + +| Limit | Value | +|-------|-------| +| Max nesting depth | 2 levels | +| Filters per compound | 10 | +| `or` operator | Same column, `eq` only | + +**OR restriction example:** +```typescript +// ✅ Valid: same column, eq only +{ operator: "or", filters: [ + { column: "folder", operator: "eq", value: "docs/" }, + { column: "folder", operator: "eq", value: "guides/" } +]} +``` + +## Indexing Issues + +| Problem | Cause | Solution | +|---------|-------|----------| +| File not indexed | Unsupported format or >4MB | Check format (.md/.txt/.html/.pdf/.doc/.csv/.json) | +| Index out of sync | 6-hour index cycle | Wait or use "Force Sync" (30s rate limit) | +| Empty results | Index incomplete | Check dashboard for indexing status | + +## Auth Errors + +| Error | Cause | Fix | +|-------|-------|-----| +| `AutoRAGUnauthorizedError` | Invalid/missing token | Create Service API token with AI Search permissions | +| `AutoRAGNotFoundError` | Wrong instance name | Verify exact name from dashboard | + +## Performance + +**Slow responses (>3s):** +```typescript +// Add score threshold + limit results +ranking_options: { score_threshold: 0.5 }, +max_num_results: 10 +``` + +**Empty results debug:** +1. Remove filters, test basic query +2. Lower `score_threshold` to 0.1 +3. Check index is populated + +## Limits + +| Resource | Limit | +|----------|-------| +| Instances per account | 10 | +| Files per instance | 100,000 | +| Max file size | 4 MB | +| Index frequency | 6 hours | + +## Anti-Patterns + +**Use env vars for instance names:** +```typescript +const answer = await env.AI.autorag(env.AI_SEARCH_INSTANCE).aiSearch({...}); +``` + +**Handle specific error types:** +```typescript +if (error instanceof AutoRAGNotFoundError) { /* 404 */ } +if (error instanceof AutoRAGUnauthorizedError) { /* 401 */ } +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..4a70f089beb85cc9088176d48c311337d7407257 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/ai-search/patterns.md @@ -0,0 +1,85 @@ +# AI Search Patterns + +## search() vs aiSearch() + +| Use | Method | Returns | +|-----|--------|---------| +| Custom UI, analytics | `search()` | Raw chunks only (~100-300ms) | +| Chatbots, Q&A | `aiSearch()` | AI response + chunks (~500-2000ms) | + +## rewrite_query + +| Setting | Use When | +|---------|----------| +| `true` | User input (typos, vague queries) | +| `false` | LLM-generated queries (already optimized) | + +## Multitenancy (Folder-Based) + +```typescript +const answer = await env.AI.autorag("saas-docs").aiSearch({ + query: "refund policy", + model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast", + filters: { + column: "folder", + operator: "gte", // "starts with" pattern + value: `tenants/${tenantId}/` + } +}); +``` + +## Streaming + +```typescript +const stream = await env.AI.autorag("docs").aiSearch({ + query, model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast", stream: true +}); +return new Response(stream, { headers: { "Content-Type": "text/event-stream" } }); +``` + +## Score Threshold + +| Threshold | Use | +|-----------|-----| +| 0.3 (default) | Broad recall, exploratory | +| 0.5 | Balanced, production default | +| 0.7 | High precision, critical accuracy | + +## System Prompt Template + +```typescript +const systemPrompt = `You are a documentation assistant. +- Answer ONLY based on provided context +- If context doesn't contain answer, say "I don't have information" +- Include code examples from context`; +``` + +## Compound Filters + +```typescript +// OR: Multiple folders +filters: { + operator: "or", + filters: [ + { column: "folder", operator: "gte", value: "docs/api/" }, + { column: "folder", operator: "gte", value: "docs/auth/" } + ] +} + +// AND: Folder + date +filters: { + operator: "and", + filters: [ + { column: "folder", operator: "gte", value: "docs/" }, + { column: "timestamp", operator: "gte", value: oneWeekAgoSeconds } + ] +} +``` + +## Reranking + +Enable for high-stakes use cases (adds ~300ms latency): + +```typescript +reranking: { enabled: true, model: "@cf/baai/bge-reranker-base" } +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/README.md new file mode 100644 index 0000000000000000000000000000000000000000..524123b4cbdca4005c8c05cce308d431a102c3a9 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/README.md @@ -0,0 +1,92 @@ +# Cloudflare Workers Analytics Engine Reference + +Expert guidance for implementing unlimited-cardinality analytics at scale using Cloudflare Workers Analytics Engine. + +## What is Analytics Engine? + +Time-series analytics database designed for high-cardinality data (millions of unique dimensions). Write data points from Workers, query via SQL API. Use for: +- Custom user-facing analytics dashboards +- Usage-based billing & metering +- Per-customer/per-feature monitoring +- High-frequency instrumentation without performance impact + +**Key Capability:** Track metrics with unlimited unique values (e.g., millions of user IDs, API keys) without performance degradation. + +## Core Concepts + +| Concept | Description | Example | +|---------|-------------|---------| +| **Dataset** | Logical table for related metrics | `api_requests`, `user_events` | +| **Data Point** | Single measurement with timestamp | One API request's metrics | +| **Blobs** | String dimensions (max 20) | endpoint, method, status, user_id | +| **Doubles** | Numeric values (max 20) | latency_ms, request_count, bytes | +| **Indexes** | Filtered blobs for efficient queries | customer_id, api_key | + +## Reading Order + +| Task | Start Here | Then Read | +|------|------------|-----------| +| **First-time setup** | [configuration.md](configuration.md) → [api.md](api.md) → [patterns.md](patterns.md) | | +| **Writing data** | [api.md](api.md) → [gotchas.md](gotchas.md) (sampling) | | +| **Querying data** | [api.md](api.md) (SQL API) → [patterns.md](patterns.md) (examples) | | +| **Debugging** | [gotchas.md](gotchas.md) → [api.md](api.md) (limits) | | +| **Optimization** | [patterns.md](patterns.md) (anti-patterns) → [gotchas.md](gotchas.md) | | + +## When to Use Analytics Engine + +``` +Need to track metrics? → Yes + ↓ +Millions of unique dimension values? → Yes + ↓ + Need real-time queries? → Yes + ↓ + Use Analytics Engine ✓ + +Alternative scenarios: +- Low cardinality (<10k unique values) → Workers Analytics (free tier) +- Complex joins/relations → D1 Database +- Logs/debugging → Tail Workers (logpush) +- External tools → Send to external analytics (Datadog, etc.) +``` + +## Quick Start + +1. Add binding to `wrangler.jsonc`: +```jsonc +{ + "analytics_engine_datasets": [ + { "binding": "ANALYTICS", "dataset": "my_events" } + ] +} +``` + +2. Write data points (fire-and-forget, no await): +```typescript +env.ANALYTICS.writeDataPoint({ + blobs: ["/api/users", "GET", "200"], + doubles: [145.2, 1], // latency_ms, count + indexes: [customerId] +}); +``` + +3. Query via SQL API (HTTP): +```sql +SELECT blob1, SUM(double2) AS total_requests +FROM my_events +WHERE index1 = 'customer_123' + AND timestamp >= NOW() - INTERVAL '7' DAY +GROUP BY blob1 +ORDER BY total_requests DESC +``` + +## In This Reference + +- **[configuration.md](configuration.md)** - Setup, bindings, TypeScript types, limits +- **[api.md](api.md)** - `writeDataPoint()`, SQL API, query syntax +- **[patterns.md](patterns.md)** - Use cases, examples, anti-patterns +- **[gotchas.md](gotchas.md)** - Sampling, index selection, troubleshooting + +## See Also + +- [Cloudflare Analytics Engine Docs](https://developers.cloudflare.com/analytics/analytics-engine/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/api.md new file mode 100644 index 0000000000000000000000000000000000000000..20e7084151fcef6ea33a1613e7dce17a7f20301f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/api.md @@ -0,0 +1,112 @@ +# Analytics Engine API Reference + +## Writing Data + +### `writeDataPoint()` + +Fire-and-forget (returns `void`, not Promise). Writes happen asynchronously. + +```typescript +interface AnalyticsEngineDataPoint { + blobs?: string[]; // Up to 20 strings (dimensions), 16KB each + doubles?: number[]; // Up to 20 numbers (metrics) + indexes?: string[]; // 1 indexed string for high-cardinality filtering +} + +env.ANALYTICS.writeDataPoint({ + blobs: ["/api/users", "GET", "200"], + doubles: [145.2, 1], // latency_ms, count + indexes: ["customer_abc123"] +}); +``` + +**Behaviors:** No await needed, no error thrown (check tail logs), auto-sampled at high volumes, auto-timestamped. + +**Blob vs Index:** Blob for GROUP BY (<100k unique), Index for filter-only (millions unique). + +### Full Example + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const start = Date.now(); + const url = new URL(request.url); + try { + const response = await handleRequest(request); + env.ANALYTICS.writeDataPoint({ + blobs: [url.pathname, request.method, response.status.toString()], + doubles: [Date.now() - start, 1], + indexes: [request.headers.get("x-api-key") || "anonymous"] + }); + return response; + } catch (error) { + env.ANALYTICS.writeDataPoint({ + blobs: [url.pathname, request.method, "500"], + doubles: [Date.now() - start, 1, 0], + }); + throw error; + } + } +}; +``` + +## SQL API (External Only) + +```bash +curl -X POST https://api.cloudflare.com/client/v4/accounts/{account_id}/analytics_engine/sql \ + -H "Authorization: Bearer $TOKEN" \ + -d "SELECT blob1 AS endpoint, COUNT(*) AS requests FROM dataset WHERE timestamp >= NOW() - INTERVAL '1' HOUR GROUP BY blob1" +``` + +### Column References + +```sql +-- blob1..blob20, double1..double20, index1, timestamp +SELECT blob1 AS endpoint, SUM(double1) AS latency, COUNT(*) AS requests +FROM my_dataset +WHERE index1 = 'customer_123' AND timestamp >= NOW() - INTERVAL '7' DAY +GROUP BY blob1 +HAVING COUNT(*) > 100 +ORDER BY requests DESC LIMIT 100 +``` + +**Aggregations:** `SUM()`, `AVG()`, `COUNT()`, `MIN()`, `MAX()`, `quantile(0.95)()` + +**Time ranges:** `NOW() - INTERVAL '1' HOUR`, `BETWEEN '2026-01-01' AND '2026-01-31'` + +### Query Examples + +```sql +-- Top endpoints +SELECT blob1, COUNT(*) AS requests, AVG(double1) AS avg_latency +FROM api_requests WHERE timestamp >= NOW() - INTERVAL '24' HOUR +GROUP BY blob1 ORDER BY requests DESC LIMIT 20 + +-- Error rate +SELECT blob1, COUNT(*) AS total, + SUM(CASE WHEN blob3 LIKE '5%' THEN 1 ELSE 0 END) AS errors +FROM api_requests WHERE timestamp >= NOW() - INTERVAL '1' HOUR +GROUP BY blob1 HAVING total > 50 + +-- P95 latency +SELECT blob1, quantile(0.95)(double1) AS p95 +FROM api_requests GROUP BY blob1 +``` + +## Response Format + +```json +{"data": [{"endpoint": "/api/users", "requests": 1523}], "rows": 2} +``` + +## Limits + +| Resource | Limit | +|----------|-------| +| Blobs/Doubles per point | 20 each | +| Indexes per point | 1 | +| Blob/Index size | 16KB | +| Data retention | 90 days | +| Query timeout | 30s | + +**Critical:** High write volumes (>1M/min) trigger automatic sampling. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..a71af96ff553398bfb270c85c1c1060c1edeb9df --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/configuration.md @@ -0,0 +1,112 @@ +# Analytics Engine Configuration + +## Setup + +1. Add binding to `wrangler.jsonc` +2. Deploy Worker +3. Dataset created automatically on first write +4. Query via SQL API + +## wrangler.jsonc + +```jsonc +{ + "name": "my-worker", + "analytics_engine_datasets": [ + { "binding": "ANALYTICS", "dataset": "my_events" } + ] +} +``` + +Multiple datasets for separate concerns: +```jsonc +{ + "analytics_engine_datasets": [ + { "binding": "API_ANALYTICS", "dataset": "api_requests" }, + { "binding": "USER_EVENTS", "dataset": "user_activity" } + ] +} +``` + +## TypeScript + +```typescript +interface Env { + ANALYTICS: AnalyticsEngineDataset; +} + +export default { + async fetch(request: Request, env: Env) { + // No await - returns void, fire-and-forget + env.ANALYTICS.writeDataPoint({ + blobs: [pathname, method, status], // String dimensions (max 20) + doubles: [latency, 1], // Numeric metrics (max 20) + indexes: [apiKey] // High-cardinality filter (max 1) + }); + return response; + } +}; +``` + +## Data Point Limits + +| Field | Limit | SQL Access | +|-------|-------|------------| +| blobs | 20 strings, 16KB each | `blob1`...`blob20` | +| doubles | 20 numbers | `double1`...`double20` | +| indexes | 1 string, 16KB | `index1` | + +## Write Behavior + +| Scenario | Behavior | +|----------|----------| +| <1M writes/min | All accepted | +| >1M writes/min | Automatic sampling | +| Invalid data | Silent failure (check tail logs) | + +**Mitigate sampling:** Pre-aggregate, use multiple datasets, write only critical metrics. + +## Query Limits + +| Resource | Limit | +|----------|-------| +| Query timeout | 30 seconds | +| Data retention | 90 days (default) | +| Result size | ~10MB | + +## Cost + +**Free tier:** 10M writes/month, 1M reads/month + +**Paid:** $0.05 per 1M writes, $1.00 per 1M reads + +## Environment-Specific + +```jsonc +{ + "analytics_engine_datasets": [ + { "binding": "ANALYTICS", "dataset": "prod_events" } + ], + "env": { + "staging": { + "analytics_engine_datasets": [ + { "binding": "ANALYTICS", "dataset": "staging_events" } + ] + } + } +} +``` + +## Monitoring + +```bash +npx wrangler tail # Check for sampling/write errors +``` + +```sql +-- Check write activity +SELECT DATE_TRUNC('hour', timestamp) AS hour, COUNT(*) AS writes +FROM my_dataset +WHERE timestamp >= NOW() - INTERVAL '24' HOUR +GROUP BY hour +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..a6c39cb7b5ba8b9dda54082047e7b942a7df8853 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/gotchas.md @@ -0,0 +1,85 @@ +# Analytics Engine Gotchas + +## Critical Issues + +### Sampling at High Volumes + +**Problem:** Queries return fewer points than written at >1M writes/min. + +**Solution:** +```typescript +// Pre-aggregate before writing +let buffer = { count: 0, total: 0 }; +buffer.count++; buffer.total += value; + +// Write once per second instead of per request +if (Date.now() % 1000 === 0) { + env.ANALYTICS.writeDataPoint({ doubles: [buffer.count, buffer.total] }); +} +``` + +**Detection:** `npx wrangler tail` → look for "sampling enabled" + +### writeDataPoint Returns void + +```typescript +// ❌ Pointless await +await env.ANALYTICS.writeDataPoint({...}); + +// ✅ Fire-and-forget +env.ANALYTICS.writeDataPoint({...}); +``` + +Writes can fail silently. Check tail logs. + +### Index vs Blob + +| Cardinality | Use | Example | +|-------------|-----|---------| +| Millions | **Index** | user_id, api_key | +| Hundreds | **Blob** | endpoint, status_code, country | + +```typescript +// ✅ Correct +{ blobs: [method, path, status], indexes: [userId] } +``` + +### Can't Query from Workers + +Query API requires HTTP auth. Use external service or cache in KV/D1. + +### No Custom Timestamps + +Auto-generated at write time. Store original in blob if needed. + +## Common Errors + +| Error | Fix | +|-------|-----| +| Binding not found | Check wrangler.jsonc, redeploy | +| No data in query | Wait 30s; check dataset name; check time range | +| Query timeout | Add time filter; use index for filtering | + +## Limits + +| Resource | Limit | +|----------|-------| +| Blobs per point | 20 | +| Doubles per point | 20 | +| Indexes per point | 1 | +| Blob/Index size | 16KB | +| Write rate (no sampling) | ~1M/min | +| Retention | 90 days | +| Query timeout | 30s | + +## Best Practices + +✅ Pre-aggregate at high volumes +✅ Use index for high-cardinality (millions) +✅ Always include time filter in queries +✅ Design schema before coding + +❌ Don't await writeDataPoint +❌ Don't use index for low-cardinality +❌ Don't query without time range +❌ Don't assume all writes succeed diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..d213c47b86984ed2fee25d65d407cd1399a92c98 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/analytics-engine/patterns.md @@ -0,0 +1,83 @@ +# Analytics Engine Patterns + +## Use Cases + +| Use Case | Key Metrics | Index On | +|----------|-------------|----------| +| API Metering | requests, bytes, compute_units | api_key | +| Feature Usage | feature, action, duration | user_id | +| Error Tracking | error_type, endpoint, count | customer_id | +| Performance | latency_ms, cache_status | endpoint | +| A/B Testing | variant, conversions | user_id | + +## API Metering (Billing) + +```typescript +env.ANALYTICS.writeDataPoint({ + blobs: [pathname, method, status, tier], + doubles: [1, computeUnits, bytes, latencyMs], + indexes: [apiKey] +}); + +// Query: Monthly usage by customer +// SELECT index1 AS api_key, SUM(double2) AS compute_units +// FROM usage WHERE timestamp >= DATE_TRUNC('month', NOW()) GROUP BY index1 +``` + +## Error Tracking + +```typescript +env.ANALYTICS.writeDataPoint({ + blobs: [endpoint, method, errorName, errorMessage.slice(0, 1000)], + doubles: [1, timeToErrorMs], + indexes: [customerId] +}); +``` + +## Performance Monitoring + +```typescript +env.ANALYTICS.writeDataPoint({ + blobs: [pathname, method, cacheStatus, status], + doubles: [latencyMs, 1], + indexes: [userId] +}); + +// Query: P95 latency by endpoint +// SELECT blob1, quantile(0.95)(double1) AS p95_ms FROM perf GROUP BY blob1 +``` + +## Anti-Patterns + +| ❌ Wrong | ✅ Correct | +|----------|-----------| +| `await writeDataPoint()` | `writeDataPoint()` (fire-and-forget) | +| `indexes: [method]` (low cardinality) | `blobs: [method]`, `indexes: [userId]` | +| `blobs: [JSON.stringify(obj)]` | Store ID in blob, full object in D1/KV | +| Write every request at 10M/min | Pre-aggregate per second | +| Query from Worker | Query from external service/API | + +## Best Practices + +1. **Design schema upfront** - Document blob/double/index assignments +2. **Always include count metric** - `doubles: [latency, 1]` for AVG calculations +3. **Use enums for blobs** - Consistent values like `Status.SUCCESS` +4. **Handle sampling** - Use ratios (avg_latency = SUM(latency)/SUM(count)) +5. **Test queries early** - Validate schema before heavy writes + +## Schema Template + +```typescript +/** + * Dataset: my_metrics + * + * Blobs: + * blob1: endpoint, blob2: method, blob3: status + * + * Doubles: + * double1: latency_ms, double2: count (always 1) + * + * Indexes: + * index1: customer_id (high cardinality) + */ +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/README.md new file mode 100644 index 0000000000000000000000000000000000000000..86613c86fe683ffe0b1fe9f6856614200458659f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/README.md @@ -0,0 +1,44 @@ +# Cloudflare API Shield Reference + +Expert guidance for API Shield - comprehensive API security suite for discovery, protection, and monitoring. + +## Reading Order + +| Task | Files to Read | +|------|---------------| +| Initial setup | README → configuration.md | +| Implement JWT validation | configuration.md → api.md | +| Add schema validation | configuration.md → patterns.md | +| Detect API attacks | patterns.md → api.md | +| Debug issues | gotchas.md | + +## Feature Selection + +What protection do you need? + +``` +├─ Validate request/response structure → Schema Validation 2.0 (configuration.md) +├─ Verify auth tokens → JWT Validation (configuration.md) +├─ Client certificates → mTLS (configuration.md) +├─ Detect BOLA attacks → BOLA Detection (patterns.md) +├─ Track auth coverage → Auth Posture (patterns.md) +├─ Stop volumetric abuse → Abuse Detection (patterns.md) +└─ Discover shadow APIs → API Discovery (api.md) +``` + +## In This Reference + +- **[configuration.md](configuration.md)** - Setup, session identifiers, rules, token/mTLS configs +- **[api.md](api.md)** - Endpoint management, discovery, validation APIs, GraphQL operations +- **[patterns.md](patterns.md)** - Common patterns, progressive rollout, OWASP mappings, workflows +- **[gotchas.md](gotchas.md)** - Troubleshooting, false positives, performance, best practices + +## Quick Start + +API Shield: Enterprise-grade API security (Discovery, Schema Validation 2.0, JWT, mTLS, BOLA Detection, Auth Posture). Available as Enterprise add-on with preview access. + +## See Also + +- [API Shield Docs](https://developers.cloudflare.com/api-shield/) +- [API Reference](https://developers.cloudflare.com/api/resources/api_gateway/) +- [OWASP API Security Top 10](https://owasp.org/www-project-api-security/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/api.md new file mode 100644 index 0000000000000000000000000000000000000000..c833501ff6838eb7c602729bfc1f9a5cd2425049 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/api.md @@ -0,0 +1,141 @@ +# API Reference + +Base: `/zones/{zone_id}/api_gateway` + +## Endpoints + +```bash +GET /operations # List +GET /operations/{op_id} # Get single +POST /operations/item # Create: {endpoint,host,method} +POST /operations # Bulk: {operations:[{endpoint,host,method}]} +DELETE /operations/{op_id} # Delete +DELETE /operations # Bulk delete: {operation_ids:[...]} +``` + +## Discovery + +```bash +GET /discovery/operations # List discovered +PATCH /discovery/operations/{op_id} # Update: {state:"saved"|"ignored"} +PATCH /discovery/operations # Bulk: {operation_ids:{id:{state}}} +GET /discovery # OpenAPI export +``` + +## Config + +```bash +GET /configuration # Get session ID config +PUT /configuration # Update: {auth_id_characteristics:[{name,type:"header"|"cookie"}]} +``` + +## Token Validation + +```bash +GET /token_validation # List +POST /token_validation # Create: {name,location:{header:"..."},jwks:"..."} +POST /jwt_validation_rules # Rule: {name,hostname,token_validation_id,action:"block"} +``` + +## Workers Integration + +### Access JWT Claims +```js +export default { + async fetch(req, env) { + // Access validated JWT payload + const jwt = req.cf?.jwt?.payload?.[env.JWT_CONFIG_ID]?.[0]; + if (jwt) { + const userId = jwt.sub; + const role = jwt.role; + } + } +} +``` + +### Access mTLS Info +```js +export default { + async fetch(req, env) { + const tls = req.cf?.tlsClientAuth; + if (tls?.certVerified === 'SUCCESS') { + const fingerprint = tls.certFingerprintSHA256; + // Authenticated client + } + } +} +``` + +### Dynamic JWKS Update +```js +export default { + async scheduled(event, env) { + const jwks = await (await fetch('https://auth.example.com/.well-known/jwks.json')).json(); + await fetch(`https://api.cloudflare.com/client/v4/zones/${env.ZONE_ID}/api_gateway/token_validation/${env.CONFIG_ID}`, { + method: 'PATCH', + headers: {'Authorization': `Bearer ${env.CF_API_TOKEN}`, 'Content-Type': 'application/json'}, + body: JSON.stringify({jwks: JSON.stringify(jwks)}) + }); + } +} +``` + +## Firewall Fields + +### Core Fields +```js +cf.api_gateway.auth_id_present // Session ID present +cf.api_gateway.request_violates_schema // Schema violation +cf.api_gateway.fallthrough_triggered // No endpoint match +cf.tls_client_auth.cert_verified // mTLS cert valid +cf.tls_client_auth.cert_fingerprint_sha256 +``` + +### JWT Validation (2026) +```js +// Modern validation syntax +is_jwt_valid(http.request.jwt.payload["{config_id}"][0]) + +// Legacy (still supported) +cf.api_gateway.jwt_claims_valid + +// Extract claims +lookup_json_string(http.request.jwt.payload["{config_id}"][0], "claim_name") +``` + +### Risk Labels (2026) +```js +// BOLA detection +cf.api_gateway.cf-risk-bola-enumeration // Sequential resource access detected +cf.api_gateway.cf-risk-bola-pollution // Parameter pollution detected + +// Authentication posture +cf.api_gateway.cf-risk-missing-auth // Endpoint lacks authentication +cf.api_gateway.cf-risk-mixed-auth // Inconsistent auth patterns +``` + +## BOLA Detection + +```bash +GET /user_schemas/{schema_id}/bola # Get BOLA config +PATCH /user_schemas/{schema_id}/bola # Update: {enabled:true} +``` + +## Auth Posture + +```bash +GET /discovery/authentication_posture # List unprotected endpoints +``` + +## GraphQL Protection + +```bash +GET /settings/graphql_protection # Get limits +PUT /settings/graphql_protection # Set: {max_depth,max_size} +``` + +## See Also + +- [configuration.md](configuration.md) - Setup guides for all features +- [patterns.md](patterns.md) - Firewall rules and common patterns +- [API Gateway API Docs](https://developers.cloudflare.com/api/resources/api_gateway/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..f95744c5e30ba80255ef66d1eee6ca97bc94c513 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/configuration.md @@ -0,0 +1,192 @@ +# Configuration + +## Schema Validation 2.0 Setup + +> ⚠️ **Classic Schema Validation deprecated.** Use Schema Validation 2.0. + +**Upload schema (Dashboard):** +``` +Security > API Shield > Schema Validation > Add validation +- Upload .yml/.yaml/.json (OpenAPI v3.0) +- Endpoints auto-added to Endpoint Management +- Action: Log | Block | None +- Body inspection: JSON payloads +``` + +**Change validation action:** +``` +Security > API Shield > Settings > Schema Validation +Per-endpoint: Filter → ellipses → Change action +Default action: Set global mitigation action +``` + +**Migration from Classic:** +``` +1. Export existing schema (if available) +2. Delete all Classic schema validation rules +3. Wait 5 min for cache clear +4. Re-upload via Schema Validation 2.0 interface +5. Verify in Security > Events +``` + +**Fallthrough rule** (catch-all unknown endpoints): +``` +Security > API Shield > Settings > Fallthrough > Use Template +- Select hostnames +- Create rule with cf.api_gateway.fallthrough_triggered +- Action: Log (discover) or Block (strict) +``` + +**Body inspection:** Supports `application/json`, `*/*`, `application/*`. Disable origin MIME sniffing to prevent bypasses. + +## JWT Validation + +**Setup token config:** +``` +Security > API Shield > Settings > JWT Settings > Add configuration +- Name: "Auth0 JWT Config" +- Location: Header/Cookie + name (e.g., "Authorization") +- JWKS: Paste public keys from IdP +``` + +**Create validation rule:** +``` +Security > API Shield > API Rules > Add rule +- Hostname: api.example.com +- Deselect endpoints to ignore +- Token config: Select config +- Enforce presence: Ignore or Mark as non-compliant +- Action: Log/Block/Challenge +``` + +**Rate limit by JWT claim:** +```wirefilter +lookup_json_string(http.request.jwt.claims["{config_id}"][0], "sub") +``` + +**Special cases:** +- Two JWTs, different IdPs: Create 2 configs, select both, "Validate all" +- IdP migration: 2 configs + 2 rules, adjust actions per state +- Bearer prefix: API Shield handles with/without +- Nested claims: Dot notation `user.email` + +## Mutual TLS (mTLS) + +**Setup:** +``` +SSL/TLS > Client Certificates > Create Certificate +- Generate CF-managed CA (all plans) +- Upload custom CA (Enterprise, max 5) +``` + +**Configure mTLS rule:** +``` +Security > API Shield > mTLS +- Select hostname(s) +- Choose certificate(s) +- Action: Block/Log/Challenge +``` + +**Test:** +```bash +openssl req -x509 -newkey rsa:4096 -keyout client-key.pem -out client-cert.pem -days 365 +curl https://api.example.com/endpoint --cert client-cert.pem --key client-key.pem +``` + +## Session Identifiers + +Critical for BOLA Detection, Sequence Mitigation, and analytics. Configure header/cookie that uniquely IDs API users. + +**Examples:** JWT sub claim, session token, API key, custom user ID header + +**Configure:** +``` +Security > API Shield > Settings > Session Identifiers +- Type: Header/Cookie +- Name: "X-User-ID" or "Authorization" +``` + +## BOLA Detection + +Detects Broken Object Level Authorization attacks (enumeration + parameter pollution). + +**Enable:** +``` +Security > API Shield > Schema Validation > [Select Schema] > BOLA Detection +- Enable detection +- Threshold: Sensitivity level (Low/Medium/High) +- Action: Log or Block +``` + +**Requirements:** +- Schema Validation 2.0 enabled +- Session identifiers configured +- Minimum traffic: 1000+ requests/day per endpoint + +## Authentication Posture + +Identifies unprotected or inconsistently protected endpoints. + +**View report:** +``` +Security > API Shield > Authentication Posture +- Shows endpoints lacking JWT/mTLS +- Highlights mixed authentication patterns +``` + +**Remediate:** +1. Review flagged endpoints +2. Add JWT validation rules +3. Configure mTLS for sensitive endpoints +4. Monitor posture score + +## Volumetric Abuse + GraphQL + +**Volumetric Abuse Detection:** +`Security > API Shield > Settings > Volumetric Abuse Detection` +- Enable per-endpoint monitoring, set thresholds, action: Log | Challenge | Block + +**GraphQL Protection:** +`Security > API Shield > Settings > GraphQL Protection` +- Max query depth: 10, max size: 100KB, block introspection (production) + +## Terraform + +```hcl +# Session identifier +resource "cloudflare_api_shield" "main" { + zone_id = var.zone_id + auth_id_characteristics { + type = "header" + name = "Authorization" + } +} + +# Add endpoint +resource "cloudflare_api_shield_operation" "users_get" { + zone_id = var.zone_id + method = "GET" + host = "api.example.com" + endpoint = "/api/users/{id}" +} + +# JWT validation rule +resource "cloudflare_ruleset" "jwt_validation" { + zone_id = var.zone_id + name = "API JWT Validation" + kind = "zone" + phase = "http_request_firewall_custom" + + rules { + action = "block" + expression = "(http.host eq \"api.example.com\" and not is_jwt_valid(http.request.jwt.payload[\"{config_id}\"][0]))" + description = "Block invalid JWTs" + } +} +``` + +## See Also + +- [api.md](api.md) - API endpoints and Workers integration +- [patterns.md](patterns.md) - Firewall rules and deployment patterns +- [gotchas.md](gotchas.md) - Troubleshooting and limits diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..607f071cc27b807b430f6a5ca5ae9bb55ef9c632 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/gotchas.md @@ -0,0 +1,125 @@ +# Gotchas & Troubleshooting + +## Common Errors + +### "Schema Validation 2.0 not working after migration" + +**Cause:** Classic rules still active, conflicting with new system +**Solution:** +1. Delete ALL Classic schema validation rules +2. Clear Cloudflare cache (wait 5 min) +3. Re-upload schema via new Schema Validation 2.0 interface +4. Verify in Security > Events +5. Check action is set (Log/Block) + +### "Schema validation blocking valid requests" + +**Cause:** Schema too restrictive, missing fields, or incorrect types +**Solution:** +1. Check Firewall Events for violation details +2. Review schema in Settings +3. Test schema in Swagger Editor +4. Use Log mode to validate before blocking +5. Update schema with correct specifications +6. Ensure Schema Validation 2.0 (not Classic) + +### "JWT validation failing" + +**Cause:** JWKS mismatch with IdP, expired token, wrong header/cookie name, or clock skew +**Solution:** +1. Verify JWKS matches IdP configuration +2. Check token `exp` claim is valid +3. Confirm header/cookie name matches config +4. Test token at jwt.io +5. Account for clock skew (±5 min tolerance) +6. Use modern syntax: `is_jwt_valid(http.request.jwt.payload["{config_id}"][0])` + +### "BOLA detection false positives" + +**Cause:** Legitimate sequential access patterns, bulk operations, or sensitivity too high +**Solution:** +1. Review BOLA events in Security > Events +2. Lower sensitivity threshold (High → Medium → Low) +3. Exclude legitimate bulk operations from detection +4. Ensure session identifiers uniquely identify users +5. Verify minimum traffic requirements met (1000+ req/day) + +### "Risk labels not appearing in firewall rules" + +**Cause:** Feature not enabled, insufficient traffic, or missing session identifiers +**Solution:** +1. Verify Schema Validation 2.0 enabled +2. Enable BOLA Detection in schema settings +3. Configure session identifiers (required for BOLA) +4. Wait 24-48h for ML model training +5. Check minimum traffic thresholds met + +### "Endpoint discovery not finding APIs" + +**Cause:** Insufficient traffic (<500 reqs/10d), non-2xx responses, Worker direct requests, or incorrect session ID config +**Solution:** Ensure 500+ requests in 10 days, 2xx responses from edge (not Workers direct), configure session IDs correctly. ML updates daily. + +### "Sequence detection false positives" + +**Cause:** Lookback window issues, non-unique session IDs, or model sensitivity +**Solution:** +1. Review lookback settings (10 reqs to managed endpoints, 10min window) +2. Ensure session ID uniqueness per user (not shared tokens) +3. Adjust positive/negative model balance +4. Exclude legitimate workflows from detection + +### "GraphQL protection blocking valid queries" + +**Cause:** Query depth/size limits too restrictive, complex but legitimate queries +**Solution:** +1. Review blocked query patterns in Security > Events +2. Increase max_depth (default: 10) if needed +3. Increase max_size (default: 100KB) for complex queries +4. Whitelist specific query signatures +5. Use Log mode to tune before blocking + +### "Token invalid" + +**Cause:** Configuration error, JWKS mismatch, or expired token +**Solution:** Verify config matches IdP, update JWKS, check token expiration + +### "Schema violation" + +**Cause:** Missing required fields, wrong data types, or spec mismatch +**Solution:** Review schema against actual requests, ensure all required fields present, validate types match spec + +### "Fallthrough" + +**Cause:** Unknown endpoint or pattern mismatch +**Solution:** Update schema with all endpoints, check path pattern matching + +### "mTLS failed" + +**Cause:** Certificate untrusted/expired or wrong CA +**Solution:** Verify cert chain, check expiration, confirm correct CA uploaded + +## Limits (2026) + +| Resource/Limit | Value | Notes | +|----------------|-------|-------| +| OpenAPI version | v3.0.x only | No external refs, must be valid | +| Schema operations | 10K (Enterprise) | Contact for higher limits | +| JWT validation sources | Headers/cookies only | No query params/body | +| Endpoint discovery | 500+ reqs/10d | Minimum for ML model | +| Path normalization | Automatic | `/profile/238` → `/profile/{var1}` | +| Schema parameters | No `content` field | No object param validation | +| BOLA detection | 1000+ reqs/day/endpoint | Per-endpoint minimum | +| Session ID uniqueness | Required | BOLA/Sequence need unique IDs | +| GraphQL max depth | 1-50 | Default: 10 | +| GraphQL max size | 1KB-1MB | Default: 100KB | +| JWT claim nesting | 10 levels max | Use dot notation | +| mTLS CA certificates | 5 custom max | CF-managed unlimited | +| Schema upload size | 5MB max | Compressed OpenAPI spec | +| Volumetric abuse baseline | 7 days training | Initial ML period | +| Auth Posture refresh | Daily | Updated nightly | + +## See Also + +- [configuration.md](configuration.md) - Setup guides to avoid common issues +- [patterns.md](patterns.md) - Best practices and progressive rollout +- [API Shield Docs](https://developers.cloudflare.com/api-shield/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..410aea52532a9ac8f3b208a4d5383785085d8bb5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api-shield/patterns.md @@ -0,0 +1,180 @@ +# Patterns & Use Cases + +## Protect API with Schema + JWT + +```bash +# 1. Upload OpenAPI schema +POST /zones/{zone_id}/api_gateway/user_schemas + +# 2. Configure JWT validation +POST /zones/{zone_id}/api_gateway/token_validation +{ + "name": "Auth0", + "location": {"header": "Authorization"}, + "jwks": "{...}" +} + +# 3. Create JWT rule +POST /zones/{zone_id}/api_gateway/jwt_validation_rules + +# 4. Set schema validation action +PUT /zones/{zone_id}/api_gateway/settings/schema_validation +{"validation_default_mitigation_action": "block"} +``` + +## Progressive Rollout + +``` +1. Log mode: Observe false positives + - Schema: Action = Log + - JWT: Action = Log + +2. Block subset: Protect critical endpoints + - Change specific endpoint actions to Block + - Monitor firewall events + +3. Full enforcement: Block all violations + - Change default action to Block + - Handle fallthrough with custom rule +``` + +## BOLA Detection + +### Enumeration Detection +Detects sequential resource access (e.g., `/users/1`, `/users/2`, `/users/3`). + +```javascript +// Block BOLA enumeration attempts +(cf.api_gateway.cf-risk-bola-enumeration and http.host eq "api.example.com") +// Action: Block or Challenge +``` + +### Parameter Pollution +Detects duplicate/excessive parameters in requests. + +```javascript +// Block parameter pollution +(cf.api_gateway.cf-risk-bola-pollution and http.host eq "api.example.com") +// Action: Block +``` + +### Combined BOLA Protection +```javascript +// Comprehensive BOLA rule +(cf.api_gateway.cf-risk-bola-enumeration or cf.api_gateway.cf-risk-bola-pollution) +and http.host eq "api.example.com" +// Action: Block +``` + +## Authentication Posture + +### Detect Missing Auth +```javascript +// Log endpoints lacking authentication +(cf.api_gateway.cf-risk-missing-auth and http.host eq "api.example.com") +// Action: Log (for audit) +``` + +### Detect Mixed Auth +```javascript +// Alert on inconsistent auth patterns +(cf.api_gateway.cf-risk-mixed-auth and http.host eq "api.example.com") +// Action: Log (review required) +``` + +## Fallthrough Detection (Shadow APIs) + +```javascript +// WAF Custom Rule +(cf.api_gateway.fallthrough_triggered and http.host eq "api.example.com") +// Action: Log (discover unknown) or Block (strict) +``` + +## Rate Limiting by User + +```javascript +// Rate Limiting Rule (modern syntax) +(http.host eq "api.example.com" and + is_jwt_valid(http.request.jwt.payload["{config_id}"][0])) + +// Rate: 100 req/60s +// Counting expression: lookup_json_string(http.request.jwt.payload["{config_id}"][0], "sub") +``` + +## Volumetric Abuse Response + +```javascript +// Detect abnormal traffic spikes +(cf.api_gateway.volumetric_abuse_detected and http.host eq "api.example.com") +// Action: Challenge or Rate Limit + +// Combined with rate limiting +(cf.api_gateway.volumetric_abuse_detected or + cf.threat_score gt 50) and http.host eq "api.example.com" +// Action: JS Challenge +``` + +## GraphQL Protection + +```javascript +// Block oversized queries +(http.request.uri.path eq "/graphql" and + cf.api_gateway.graphql_query_size gt 100000) +// Action: Block + +// Block deep nested queries +(http.request.uri.path eq "/graphql" and + cf.api_gateway.graphql_query_depth gt 10) +// Action: Block +``` + +## Architecture Patterns + +**Public API:** Discovery + Schema Validation 2.0 + JWT + Rate Limiting + Bot Management +**Partner API:** mTLS + Schema Validation + Sequence Mitigation +**Internal API:** Discovery + Schema Learning + Auth Posture + +## OWASP API Security Top 10 Mapping (2026) + +| OWASP Issue | API Shield Solutions | +|-------------|---------------------| +| API1:2023 Broken Object Level Authorization | **BOLA Detection** (enumeration + pollution), Sequence mitigation, Schema, JWT, Rate Limiting | +| API2:2023 Broken Authentication | **Auth Posture**, mTLS, JWT validation, Bot Management | +| API3:2023 Broken Object Property Auth | Schema validation, JWT validation | +| API4:2023 Unrestricted Resource Access | Rate Limiting, **Volumetric Abuse Detection**, **GraphQL Protection**, Bot Management | +| API5:2023 Broken Function Level Auth | Schema validation, JWT validation, Auth Posture | +| API6:2023 Unrestricted Business Flows | Sequence mitigation, Bot Management | +| API7:2023 SSRF | Schema validation, WAF managed rules | +| API8:2023 Security Misconfiguration | **Schema Validation 2.0**, Auth Posture, WAF rules | +| API9:2023 Improper Inventory Management | **API Discovery**, Schema learning, Auth Posture | +| API10:2023 Unsafe API Consumption | JWT validation, Schema validation, WAF managed | + +## Monitoring + +**Security Events:** `Security > Events` → Filter: Action = block, Service = API Shield +**Firewall Analytics:** `Analytics > Security` → Filter by `cf.api_gateway.*` fields +**Logpush fields:** APIGatewayAuthIDPresent, APIGatewayRequestViolatesSchema, APIGatewayFallthroughDetected, JWTValidationResult + +## Availability (2026) + +| Feature | Availability | Notes | +|---------|-------------|-------| +| mTLS (CF-managed CA) | All plans | Self-service | +| Endpoint Management | All plans | Limited operations | +| Schema Validation 2.0 | All plans | Limited operations | +| API Discovery | Enterprise | 10K+ ops | +| JWT Validation | Enterprise add-on | Full validation | +| BOLA Detection | Enterprise add-on | Requires session IDs | +| Auth Posture | Enterprise add-on | Security audit | +| Volumetric Abuse Detection | Enterprise add-on | Traffic analysis | +| GraphQL Protection | Enterprise add-on | Query limits | +| Sequence Mitigation | Enterprise (beta) | Contact team | +| Full Suite | Enterprise add-on | All features | + +**Enterprise limits:** 10K operations (contact for higher). Preview access available for non-contract evaluation. + +## See Also + +- [configuration.md](configuration.md) - Setup all features before creating rules +- [api.md](api.md) - Firewall field reference and API endpoints +- [gotchas.md](gotchas.md) - Common issues and limits diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5e02109c69c7176494318c1a72277364ca5d18e7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/README.md @@ -0,0 +1,65 @@ +# Cloudflare API Integration + +Guide for working with Cloudflare's REST API - authentication, SDK usage, common patterns, and troubleshooting. + +## Quick Decision Tree + +``` +How are you calling the Cloudflare API? +├─ From Workers runtime → Use bindings, not REST API (see ../bindings/) +├─ Server-side (Node/Python/Go) → Official SDK (see api.md) +├─ CLI/scripts → Wrangler or curl (see configuration.md) +├─ Infrastructure-as-code → See ../pulumi/ or ../terraform/ +└─ One-off requests → curl examples (see api.md) +``` + +## SDK Selection + +| Language | Package | Best For | Default Retries | +|----------|---------|----------|-----------------| +| TypeScript | `cloudflare` | Node.js, Bun, Next.js, Workers | 2 | +| Python | `cloudflare` | FastAPI, Django, scripts | 2 | +| Go | `cloudflare-go/v4` | CLI tools, microservices | 10 | + +All SDKs are Stainless-generated from OpenAPI spec (consistent APIs). + +## Authentication Methods + +| Method | Security | Use Case | Scope | +|--------|----------|----------|-------| +| **API Token** ✓ | Scoped, rotatable | Production | Per-zone or account | +| API Key + Email | Full account access | Legacy only | Everything | +| User Service Key | Limited | Origin CA certs only | Origin CA | + +**Always use API tokens** for new projects. + +## Rate Limits + +| Limit | Value | +|-------|-------| +| Per user/token | 1200 requests / 5 minutes | +| Per IP | 200 requests / second | +| GraphQL | 320 / 5 minutes (cost-based) | + +## Reading Order + +| Task | Files to Read | +|------|---------------| +| Initialize SDK client | api.md | +| Configure auth/timeout/retry | configuration.md | +| Find usage patterns | patterns.md | +| Debug errors/rate limits | gotchas.md | +| Product-specific APIs | ../workers/, ../r2/, ../kv/, etc. | + +## In This Reference + +- **[api.md](api.md)** - SDK client initialization, pagination, error handling, examples +- **[configuration.md](configuration.md)** - Environment variables, SDK config, Wrangler setup +- **[patterns.md](patterns.md)** - Real-world patterns, batch operations, workflows +- **[gotchas.md](gotchas.md)** - Rate limits, SDK-specific issues, troubleshooting + +## See Also + +- [Cloudflare API Docs](https://developers.cloudflare.com/api/) +- [Bindings Reference](../bindings/) - Workers runtime bindings (preferred over REST API) +- [Wrangler Reference](../wrangler/) - CLI tool for Cloudflare development diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/api.md new file mode 100644 index 0000000000000000000000000000000000000000..33710149c916b6c3bada3a7e3debc229554fc68a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/api.md @@ -0,0 +1,204 @@ +# API Reference + +## Client Initialization + +### TypeScript + +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ + apiToken: process.env.CLOUDFLARE_API_TOKEN, +}); +``` + +### Python + +```python +from cloudflare import Cloudflare + +client = Cloudflare(api_token=os.environ.get("CLOUDFLARE_API_TOKEN")) + +# For async: +from cloudflare import AsyncCloudflare +client = AsyncCloudflare(api_token=os.environ["CLOUDFLARE_API_TOKEN"]) +``` + +### Go + +```go +import ( + "github.com/cloudflare/cloudflare-go/v4" + "github.com/cloudflare/cloudflare-go/v4/option" +) + +client := cloudflare.NewClient( + option.WithAPIToken(os.Getenv("CLOUDFLARE_API_TOKEN")), +) +``` + +## Authentication + +### API Token (Recommended) + +**Create token**: Dashboard → My Profile → API Tokens → Create Token + +```bash +export CLOUDFLARE_API_TOKEN='your-token-here' + +curl "https://api.cloudflare.com/client/v4/zones" \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" +``` + +**Token scopes**: Always use minimal permissions (zone-specific, time-limited). + +### API Key (Legacy) + +```bash +curl "https://api.cloudflare.com/client/v4/zones" \ + --header "X-Auth-Email: user@example.com" \ + --header "X-Auth-Key: $CLOUDFLARE_API_KEY" +``` + +**Not recommended:** Full account access, cannot scope permissions. + +## Auto-Pagination + +All SDKs support automatic pagination for list operations. + +```typescript +// TypeScript: for await...of +for await (const zone of client.zones.list()) { + console.log(zone.id); +} +``` + +```python +# Python: iterator protocol +for zone in client.zones.list(): + print(zone.id) +``` + +```go +// Go: ListAutoPaging +iter := client.Zones.ListAutoPaging(ctx, cloudflare.ZoneListParams{}) +for iter.Next() { + zone := iter.Current() + fmt.Println(zone.ID) +} +``` + +## Error Handling + +```typescript +try { + const zone = await client.zones.get({ zone_id: 'xxx' }); +} catch (err) { + if (err instanceof Cloudflare.NotFoundError) { + // 404 + } else if (err instanceof Cloudflare.RateLimitError) { + // 429 - SDK auto-retries with backoff + } else if (err instanceof Cloudflare.APIError) { + console.log(err.status, err.message); + } +} +``` + +**Common Error Types:** +- `AuthenticationError` (401) - Invalid token +- `PermissionDeniedError` (403) - Insufficient scope +- `NotFoundError` (404) - Resource not found +- `RateLimitError` (429) - Rate limit exceeded +- `InternalServerError` (≥500) - Cloudflare error + +## Zone Management + +```typescript +// List zones +const zones = await client.zones.list({ + account: { id: 'account-id' }, + status: 'active', +}); + +// Create zone +const zone = await client.zones.create({ + account: { id: 'account-id' }, + name: 'example.com', + type: 'full', // or 'partial' +}); + +// Update zone +await client.zones.edit('zone-id', { + paused: false, +}); + +// Delete zone +await client.zones.delete('zone-id'); +``` + +```go +// Go: requires cloudflare.F() wrapper +zone, err := client.Zones.New(ctx, cloudflare.ZoneNewParams{ + Account: cloudflare.F(cloudflare.ZoneNewParamsAccount{ + ID: cloudflare.F("account-id"), + }), + Name: cloudflare.F("example.com"), + Type: cloudflare.F(cloudflare.ZoneNewParamsTypeFull), +}) +``` + +## DNS Management + +```typescript +// Create DNS record +await client.dns.records.create({ + zone_id: 'zone-id', + type: 'A', + name: 'subdomain.example.com', + content: '192.0.2.1', + ttl: 1, // auto + proxied: true, // Orange cloud +}); + +// List DNS records (with auto-pagination) +for await (const record of client.dns.records.list({ + zone_id: 'zone-id', + type: 'A', +})) { + console.log(record.name, record.content); +} + +// Update DNS record +await client.dns.records.update({ + zone_id: 'zone-id', + dns_record_id: 'record-id', + type: 'A', + name: 'subdomain.example.com', + content: '203.0.113.1', + proxied: true, +}); + +// Delete DNS record +await client.dns.records.delete({ + zone_id: 'zone-id', + dns_record_id: 'record-id', +}); +``` + +```python +# Python example +client.dns.records.create( + zone_id="zone-id", + type="A", + name="subdomain.example.com", + content="192.0.2.1", + ttl=1, + proxied=True, +) +``` + +## See Also + +- [configuration.md](./configuration.md) - SDK configuration, environment variables +- [patterns.md](./patterns.md) - Real-world patterns and workflows +- [gotchas.md](./gotchas.md) - Rate limits, troubleshooting diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..4d4a299c84aa67463f7e07a2011ac85fe872e740 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/configuration.md @@ -0,0 +1,160 @@ +# Configuration + +## Environment Variables + +### Set Variables + +| Platform | Command | +|----------|---------| +| Linux/macOS | `export CLOUDFLARE_API_TOKEN='token'` | +| PowerShell | `$env:CLOUDFLARE_API_TOKEN = 'token'` | +| Windows CMD | `set CLOUDFLARE_API_TOKEN=token` | + +**Security:** Never commit tokens. Use `.env` files (gitignored) or secret managers. + +### .env File Pattern + +```bash +# .env (add to .gitignore) +CLOUDFLARE_API_TOKEN=your-token-here +CLOUDFLARE_ACCOUNT_ID=your-account-id +``` + +```typescript +// TypeScript +import 'dotenv/config'; + +const client = new Cloudflare({ + apiToken: process.env.CLOUDFLARE_API_TOKEN, +}); +``` + +```python +# Python +from dotenv import load_dotenv +load_dotenv() + +client = Cloudflare(api_token=os.environ["CLOUDFLARE_API_TOKEN"]) +``` + +## SDK Configuration + +### TypeScript + +```typescript +const client = new Cloudflare({ + apiToken: process.env.CLOUDFLARE_API_TOKEN, + timeout: 120000, // 2 min (default 60s), in milliseconds + maxRetries: 5, // default 2 + baseURL: 'https://...', // proxy (rare) +}); + +// Per-request overrides +await client.zones.get( + { zone_id: 'zone-id' }, + { timeout: 5000, maxRetries: 0 } +); +``` + +### Python + +```python +client = Cloudflare( + api_token=os.environ["CLOUDFLARE_API_TOKEN"], + timeout=120, # seconds (default 60) + max_retries=5, # default 2 + base_url="https://...", # proxy (rare) +) + +# Per-request overrides +client.with_options(timeout=5, max_retries=0).zones.get(zone_id="zone-id") +``` + +### Go + +```go +client := cloudflare.NewClient( + option.WithAPIToken(os.Getenv("CLOUDFLARE_API_TOKEN")), + option.WithMaxRetries(5), // default 10 (higher than TS/Python) + option.WithRequestTimeout(2 * time.Minute), // default 60s + option.WithBaseURL("https://..."), // proxy (rare) +) + +// Per-request overrides +client.Zones.Get(ctx, "zone-id", option.WithMaxRetries(0)) +``` + +## Configuration Options + +| Option | TypeScript | Python | Go | Default | +|--------|-----------|--------|-----|---------| +| Timeout | `timeout` (ms) | `timeout` (s) | `WithRequestTimeout` | 60s | +| Retries | `maxRetries` | `max_retries` | `WithMaxRetries` | 2 (Go: 10) | +| Base URL | `baseURL` | `base_url` | `WithBaseURL` | api.cloudflare.com | + +**Note:** Go SDK has higher default retries (10) than TypeScript/Python (2). + +## Timeout Configuration + +**When to increase:** +- Large zone transfers +- Bulk DNS operations +- Worker script uploads + +```typescript +const client = new Cloudflare({ + timeout: 300000, // 5 minutes +}); +``` + +## Retry Configuration + +**When to increase:** Rate-limit-heavy workflows, flaky network + +**When to decrease:** Fast-fail requirements, user-facing requests + +```typescript +// Increase retries for batch operations +const client = new Cloudflare({ maxRetries: 10 }); + +// Disable retries for fast-fail +const fastClient = new Cloudflare({ maxRetries: 0 }); +``` + +## Wrangler CLI Integration + +```bash +# Configure authentication +wrangler login +# Or +export CLOUDFLARE_API_TOKEN='token' + +# Common commands that use API +wrangler deploy # Uploads worker via API +wrangler kv:key put # KV operations +wrangler r2 bucket create # R2 operations +wrangler d1 execute # D1 operations +wrangler pages deploy # Pages operations + +# Get API configuration +wrangler whoami # Shows authenticated user +``` + +### wrangler.toml + +```toml +name = "my-worker" +main = "src/index.ts" +compatibility_date = "2024-01-01" +account_id = "your-account-id" + +# Can also use env vars: +# CLOUDFLARE_ACCOUNT_ID +# CLOUDFLARE_API_TOKEN +``` + +## See Also + +- [api.md](./api.md) - Client initialization, authentication +- [gotchas.md](./gotchas.md) - Rate limits, timeout errors +- [Wrangler Reference](../wrangler/) - CLI tool details diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..e6666dc5906b969f945ecc825357eba3e4eb2422 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/gotchas.md @@ -0,0 +1,225 @@ +# Gotchas & Troubleshooting + +## Rate Limits & 429 Errors + +**Actual Limits:** +- **1200 requests / 5 minutes** per user/token (global) +- **200 requests / second** per IP address +- **GraphQL: 320 / 5 minutes** (cost-based) + +**SDK Behavior:** +- Auto-retry with exponential backoff (default 2 retries, Go: 10) +- Respects `Retry-After` header +- Throws `RateLimitError` after exhausting retries + +**Solution:** + +```typescript +// Increase retries for rate-limit-heavy workflows +const client = new Cloudflare({ maxRetries: 5 }); + +// Add application-level throttling +import pLimit from 'p-limit'; +const limit = pLimit(10); // Max 10 concurrent requests +``` + +## SDK-Specific Issues + +### Go: Required Field Wrapper + +**Problem:** Go SDK requires `cloudflare.F()` wrapper for optional fields. + +```go +// ❌ WRONG - Won't compile or send field +client.Zones.New(ctx, cloudflare.ZoneNewParams{ + Name: "example.com", +}) + +// ✅ CORRECT +client.Zones.New(ctx, cloudflare.ZoneNewParams{ + Name: cloudflare.F("example.com"), + Account: cloudflare.F(cloudflare.ZoneNewParamsAccount{ + ID: cloudflare.F("account-id"), + }), +}) +``` + +**Why:** Distinguishes between zero value, null, and omitted fields. + +### Python: Async vs Sync Clients + +**Problem:** Using sync client in async context or vice versa. + +```python +# ❌ WRONG - Can't await sync client +from cloudflare import Cloudflare +client = Cloudflare() +await client.zones.list() # TypeError + +# ✅ CORRECT - Use AsyncCloudflare +from cloudflare import AsyncCloudflare +client = AsyncCloudflare() +await client.zones.list() +``` + +## Token Permission Errors (403) + +**Problem:** API returns 403 Forbidden despite valid token. + +**Cause:** Token lacks required permissions (scope). + +**Scopes Required:** + +| Operation | Required Scope | +|-----------|----------------| +| List zones | Zone:Read (zone-level or account-level) | +| Create zone | Zone:Edit (account-level) | +| Edit DNS | DNS:Edit (zone-level) | +| Deploy Worker | Workers Script:Edit (account-level) | +| Read KV | Workers KV Storage:Read | +| Write KV | Workers KV Storage:Edit | + +**Solution:** Re-create token with correct permissions in Dashboard → My Profile → API Tokens. + +## Pagination Truncation + +**Problem:** Only getting first 20 results (default page size). + +**Solution:** Use auto-pagination iterators. + +```typescript +// ❌ WRONG - Only first page (20 items) +const page = await client.zones.list(); + +// ✅ CORRECT - All results +const zones = []; +for await (const zone of client.zones.list()) { + zones.push(zone); +} +``` + +## Workers Subrequests + +**Problem:** Rate limit hit faster than expected in Workers. + +**Cause:** Workers subrequests count as separate API calls. + +**Solution:** Use bindings instead of REST API in Workers (see ../bindings/). + +```typescript +// ❌ WRONG - REST API in Workers (counts against rate limit) +const client = new Cloudflare({ apiToken: env.CLOUDFLARE_API_TOKEN }); +const zones = await client.zones.list(); + +// ✅ CORRECT - Use bindings (no rate limit) +// Access via env.MY_BINDING +``` + +## Authentication Errors (401) + +**Problem:** "Authentication failed" or "Invalid token" + +**Causes:** +- Token expired +- Token deleted/revoked +- Token not set in environment +- Wrong token format + +**Solution:** + +```typescript +// Verify token is set +if (!process.env.CLOUDFLARE_API_TOKEN) { + throw new Error('CLOUDFLARE_API_TOKEN not set'); +} + +// Test token +const user = await client.user.tokens.verify(); +console.log('Token valid:', user.status); +``` + +## Timeout Errors + +**Problem:** Request times out (default 60s). + +**Cause:** Large operations (bulk DNS, zone transfers). + +**Solution:** Increase timeout or split operations. + +```typescript +// Increase timeout +const client = new Cloudflare({ + timeout: 300000, // 5 minutes +}); + +// Or split operations +const batchSize = 100; +for (let i = 0; i < records.length; i += batchSize) { + const batch = records.slice(i, i + batchSize); + await processBatch(batch); +} +``` + +## Zone Not Found (404) + +**Problem:** Zone ID valid but returns 404. + +**Causes:** +- Zone not in account associated with token +- Zone deleted +- Wrong zone ID format + +**Solution:** + +```typescript +// List all zones to find correct ID +for await (const zone of client.zones.list()) { + console.log(zone.id, zone.name); +} +``` + +## Limits Reference + +| Resource/Limit | Value | Notes | +|----------------|-------|-------| +| API rate limit | 1200/5min | Per user/token | +| IP rate limit | 200/sec | Per IP | +| GraphQL rate limit | 320/5min | Cost-based | +| Parallel requests (recommended) | < 10 | Avoid overwhelming API | +| Default page size | 20 | Use auto-pagination | +| Max page size | 50 | Some endpoints | + +## Best Practices + +**Security:** +- Never commit tokens +- Use minimal permissions +- Rotate tokens regularly +- Set token expiration + +**Performance:** +- Batch operations +- Use pagination wisely +- Cache responses +- Handle rate limits + +**Code Organization:** + +```typescript +// Create reusable client instance +export const cfClient = new Cloudflare({ + apiToken: process.env.CLOUDFLARE_API_TOKEN, + maxRetries: 5, +}); + +// Wrap common operations +export async function getZoneDetails(zoneId: string) { + return await cfClient.zones.get({ zone_id: zoneId }); +} +``` + +## See Also + +- [api.md](./api.md) - Error types, authentication +- [configuration.md](./configuration.md) - Timeout/retry configuration +- [patterns.md](./patterns.md) - Error handling patterns diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..3c7c693b1ae5097b96a7968a813652c52194c8be --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/api/patterns.md @@ -0,0 +1,204 @@ +# Common Patterns + +## List All with Auto-Pagination + +**Problem:** API returns paginated results. Default page size is 20. + +**Solution:** Use SDK auto-pagination to iterate all results. + +```typescript +// TypeScript +for await (const zone of client.zones.list()) { + console.log(zone.name); +} +``` + +```python +# Python +for zone in client.zones.list(): + print(zone.name) +``` + +```go +// Go +iter := client.Zones.ListAutoPaging(ctx, cloudflare.ZoneListParams{}) +for iter.Next() { + fmt.Println(iter.Current().Name) +} +``` + +## Error Handling with Retry + +**Problem:** Rate limits (429) and transient errors need retry. + +**Solution:** SDKs auto-retry with exponential backoff. Customize as needed. + +```typescript +// Increase retries for rate-limit-heavy operations +const client = new Cloudflare({ maxRetries: 5 }); + +try { + const zone = await client.zones.create({ /* ... */ }); +} catch (err) { + if (err instanceof Cloudflare.RateLimitError) { + // Already retried 5 times with backoff + const retryAfter = err.headers['retry-after']; + console.log(`Rate limited. Retry after ${retryAfter}s`); + } +} +``` + +## Batch Parallel Operations + +**Problem:** Need to create multiple resources quickly. + +**Solution:** Use `Promise.all()` for parallel requests (respect rate limits). + +```typescript +// Create multiple DNS records in parallel +const records = ['www', 'api', 'cdn'].map(subdomain => + client.dns.records.create({ + zone_id: 'zone-id', + type: 'A', + name: `${subdomain}.example.com`, + content: '192.0.2.1', + }) +); +await Promise.all(records); +``` + +**Controlled concurrency** (avoid rate limits): + +```typescript +import pLimit from 'p-limit'; +const limit = pLimit(10); // Max 10 concurrent + +const subdomains = ['www', 'api', 'cdn', /* many more */]; +const records = subdomains.map(subdomain => + limit(() => client.dns.records.create({ + zone_id: 'zone-id', + type: 'A', + name: `${subdomain}.example.com`, + content: '192.0.2.1', + })) +); +await Promise.all(records); +``` + +## Zone CRUD Workflow + +```typescript +// Create +const zone = await client.zones.create({ + account: { id: 'account-id' }, + name: 'example.com', + type: 'full', +}); + +// Read +const fetched = await client.zones.get({ zone_id: zone.id }); + +// Update +await client.zones.edit(zone.id, { paused: false }); + +// Delete +await client.zones.delete(zone.id); +``` + +## DNS Bulk Update + +```typescript +// Fetch all A records +const records = []; +for await (const record of client.dns.records.list({ + zone_id: 'zone-id', + type: 'A', +})) { + records.push(record); +} + +// Update all to new IP +await Promise.all(records.map(record => + client.dns.records.update({ + zone_id: 'zone-id', + dns_record_id: record.id, + type: 'A', + name: record.name, + content: '203.0.113.1', // New IP + proxied: record.proxied, + ttl: record.ttl, + }) +)); +``` + +## Filter and Collect Results + +```typescript +// Find all proxied A records +const proxiedRecords = []; +for await (const record of client.dns.records.list({ + zone_id: 'zone-id', + type: 'A', +})) { + if (record.proxied) { + proxiedRecords.push(record); + } +} +``` + +## Error Recovery Pattern + +```typescript +async function createZoneWithRetry(name: string, maxAttempts = 3) { + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + return await client.zones.create({ + account: { id: 'account-id' }, + name, + type: 'full', + }); + } catch (err) { + if (err instanceof Cloudflare.RateLimitError && attempt < maxAttempts) { + const retryAfter = parseInt(err.headers['retry-after'] || '5'); + console.log(`Rate limited, waiting ${retryAfter}s (retry ${attempt}/${maxAttempts})`); + await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); + } else { + throw err; + } + } + } +} +``` + +## Conditional Update Pattern + +```typescript +// Only update if zone is active +const zone = await client.zones.get({ zone_id: 'zone-id' }); +if (zone.status === 'active') { + await client.zones.edit(zone.id, { paused: false }); +} +``` + +## Batch with Error Handling + +```typescript +// Process multiple zones, continue on errors +const results = await Promise.allSettled( + zoneIds.map(id => client.zones.get({ zone_id: id })) +); + +results.forEach((result, i) => { + if (result.status === 'fulfilled') { + console.log(`Zone ${i}: ${result.value.name}`); + } else { + console.error(`Zone ${i} failed:`, result.reason.message); + } +}); +``` + +## See Also + +- [api.md](./api.md) - SDK client initialization, basic operations +- [gotchas.md](./gotchas.md) - Rate limits, common errors +- [configuration.md](./configuration.md) - SDK configuration options diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ef5539d0652a4c777274324272209f2049331ce7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/README.md @@ -0,0 +1,90 @@ +# Cloudflare Argo Smart Routing Skill Reference + +## Overview + +Cloudflare Argo Smart Routing is a performance optimization service that detects real-time network issues and routes web traffic across the most efficient network path. It continuously monitors network conditions and intelligently routes traffic through the fastest, most reliable routes in Cloudflare's network. + +**Note on Smart Shield:** Argo Smart Routing is being integrated into Cloudflare's Smart Shield product for enhanced DDoS protection and performance. Existing Argo customers maintain full functionality with gradual migration to Smart Shield features. + +## Quick Start + +### Enable via cURL +```bash +curl -X PATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/argo/smart_routing" \ + -H "Authorization: Bearer YOUR_API_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"value": "on"}' +``` + +### Enable via TypeScript SDK +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN }); + +const result = await client.argo.smartRouting.edit({ + zone_id: 'your-zone-id', + value: 'on', +}); + +console.log(`Argo enabled: ${result.value}`); +``` + +## Core Concepts + +### What It Does +- **Intelligent routing**: Detects congestion, outages, packet loss in real-time +- **Global optimization**: Routes across 300+ Cloudflare data centers +- **Automatic failover**: Switches paths when issues detected (typically <1s) +- **Works with existing setup**: No origin changes required + +### Billing Model +- Usage-based: Charged per GB of traffic (excluding DDoS/WAF mitigated traffic) +- Requires billing configuration before enabling +- Available on Enterprise+ plans (check zone eligibility) + +### When to Use +- **High-traffic production sites** with global user base +- **Latency-sensitive applications** (APIs, real-time services) +- **Sites behind Cloudflare proxy** (orange-clouded DNS records) +- **Combined with Tiered Cache** for maximum performance gains + +### When NOT to Use +- Development/staging environments (cost control) +- Low-traffic sites (<1TB/month) where cost may exceed benefit +- Sites with primarily single-region traffic + +## Should I Enable Argo? + +| Your Situation | Recommendation | +|----------------|----------------| +| Global production app, >1TB/month traffic | ✅ Enable - likely ROI positive | +| Enterprise plan, latency-critical APIs | ✅ Enable - performance matters | +| Regional site, <100GB/month traffic | ⚠️ Evaluate - cost may not justify | +| Development/staging environment | ❌ Disable - use in production only | +| Not yet configured billing | ❌ Configure billing first | + +## Reading Order by Task + +| Your Goal | Start With | Then Read | +|-----------|------------|-----------| +| Enable Argo for first time | Quick Start above → [configuration.md](configuration.md) | [gotchas.md](gotchas.md) | +| Use TypeScript/Python SDK | [api.md](api.md) | [patterns.md](patterns.md) | +| Terraform/IaC setup | [configuration.md](configuration.md) | - | +| Enable for Spectrum TCP app | [patterns.md](patterns.md) → Spectrum section | [api.md](api.md) | +| Troubleshoot enablement issue | [gotchas.md](gotchas.md) | [api.md](api.md) | +| Manage billing/usage | [patterns.md](patterns.md) → Billing section | [gotchas.md](gotchas.md) | + +## In This Reference + +- **[api.md](api.md)** - API endpoints, SDK methods, error handling, Python/TypeScript examples +- **[configuration.md](configuration.md)** - Terraform setup, environment config, billing configuration +- **[patterns.md](patterns.md)** - Tiered Cache integration, Spectrum TCP apps, billing management, validation patterns +- **[gotchas.md](gotchas.md)** - Common errors, permission issues, limits, best practices + +## See Also + +- [Cloudflare Argo Smart Routing Docs](https://developers.cloudflare.com/argo-smart-routing/) +- [Cloudflare Smart Shield](https://developers.cloudflare.com/smart-shield/) +- [Spectrum Documentation](https://developers.cloudflare.com/spectrum/) +- [Tiered Cache](https://developers.cloudflare.com/cache/how-to/tiered-cache/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/api.md new file mode 100644 index 0000000000000000000000000000000000000000..c5dacb5c8e2ce6b7b72c47bc5bfd6f7da1518dd0 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/api.md @@ -0,0 +1,240 @@ +## API Reference + +**Note on Smart Shield:** Argo Smart Routing is being integrated into Cloudflare's Smart Shield product. API endpoints remain stable; existing integrations continue to work without changes. + +### Base Endpoint +``` +https://api.cloudflare.com/client/v4 +``` + +### Authentication +Use API tokens with Zone:Argo Smart Routing:Edit permissions: + +```bash +# Headers required +X-Auth-Email: user@example.com +Authorization: Bearer YOUR_API_TOKEN +``` + +### Get Argo Smart Routing Status + +**Endpoint:** `GET /zones/{zone_id}/argo/smart_routing` + +**Description:** Retrieves current Argo Smart Routing enablement status. + +**cURL Example:** +```bash +curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/argo/smart_routing" \ + -H "Authorization: Bearer YOUR_API_TOKEN" \ + -H "Content-Type: application/json" +``` + +**Response:** +```json +{ + "result": { + "id": "smart_routing", + "value": "on", + "editable": true, + "modified_on": "2024-01-11T12:00:00Z" + }, + "success": true, + "errors": [], + "messages": [] +} +``` + +**TypeScript SDK Example:** +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ + apiToken: process.env.CLOUDFLARE_API_TOKEN +}); + +const status = await client.argo.smartRouting.get({ zone_id: 'your-zone-id' }); +console.log(`Argo status: ${status.value}, editable: ${status.editable}`); +``` + +**Python SDK Example:** +```python +from cloudflare import Cloudflare + +client = Cloudflare(api_token=os.environ.get('CLOUDFLARE_API_TOKEN')) + +status = client.argo.smart_routing.get(zone_id='your-zone-id') +print(f"Argo status: {status.value}, editable: {status.editable}") +``` + +### Update Argo Smart Routing Status + +**Endpoint:** `PATCH /zones/{zone_id}/argo/smart_routing` + +**Description:** Enable or disable Argo Smart Routing for a zone. + +**Request Body:** +```json +{ + "value": "on" // or "off" +} +``` + +**cURL Example:** +```bash +curl -X PATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/argo/smart_routing" \ + -H "Authorization: Bearer YOUR_API_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"value": "on"}' +``` + +**TypeScript SDK Example:** +```typescript +const result = await client.argo.smartRouting.edit({ + zone_id: 'your-zone-id', + value: 'on', +}); +console.log(`Updated: ${result.value} at ${result.modified_on}`); +``` + +**Python SDK Example:** +```python +result = client.argo.smart_routing.edit( + zone_id='your-zone-id', + value='on' +) +print(f"Updated: {result.value} at {result.modified_on}") +``` + +## Checking Editability Before Updates + +**Critical:** Always check the `editable` field before attempting to enable/disable Argo. When `editable: false`, the zone has restrictions (billing not configured, insufficient permissions, or plan limitations). + +**Pattern:** +```typescript +async function safelyEnableArgo(client: Cloudflare, zoneId: string): Promise { + const status = await client.argo.smartRouting.get({ zone_id: zoneId }); + + if (!status.editable) { + console.error('Cannot modify Argo: editable=false (check billing/permissions)'); + return false; + } + + if (status.value === 'on') { + console.log('Argo already enabled'); + return true; + } + + await client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' }); + console.log('Argo enabled successfully'); + return true; +} +``` + +**Python Pattern:** +```python +def safely_enable_argo(client: Cloudflare, zone_id: str) -> bool: + status = client.argo.smart_routing.get(zone_id=zone_id) + + if not status.editable: + print('Cannot modify Argo: editable=false (check billing/permissions)') + return False + + if status.value == 'on': + print('Argo already enabled') + return True + + client.argo.smart_routing.edit(zone_id=zone_id, value='on') + print('Argo enabled successfully') + return True +``` + +## Error Handling + +The TypeScript SDK provides typed error classes for robust error handling: + +```typescript +import Cloudflare from 'cloudflare'; +import { APIError, APIConnectionError, RateLimitError } from 'cloudflare'; + +async function enableArgoWithErrorHandling(client: Cloudflare, zoneId: string) { + try { + const result = await client.argo.smartRouting.edit({ + zone_id: zoneId, + value: 'on', + }); + return result; + } catch (error) { + if (error instanceof RateLimitError) { + console.error('Rate limited. Retry after:', error.response?.headers.get('retry-after')); + // Implement exponential backoff + } else if (error instanceof APIError) { + console.error('API error:', error.status, error.message); + if (error.status === 403) { + console.error('Permission denied - check API token scopes'); + } else if (error.status === 400) { + console.error('Bad request - verify zone_id and payload'); + } + } else if (error instanceof APIConnectionError) { + console.error('Connection failed:', error.message); + // Retry with exponential backoff + } else { + console.error('Unexpected error:', error); + } + throw error; + } +} +``` + +**Python Error Handling:** +```python +from cloudflare import Cloudflare, APIError, RateLimitError + +def enable_argo_with_error_handling(client: Cloudflare, zone_id: str): + try: + result = client.argo.smart_routing.edit(zone_id=zone_id, value='on') + return result + except RateLimitError as e: + print(f"Rate limited. Retry after: {e.response.headers.get('retry-after')}") + raise + except APIError as e: + print(f"API error: {e.status} - {e.message}") + if e.status == 403: + print('Permission denied - check API token scopes') + elif e.status == 400: + print('Bad request - verify zone_id and payload') + raise + except Exception as e: + print(f"Unexpected error: {e}") + raise +``` + +## Response Schema + +All Argo Smart Routing API responses follow this structure: + +```typescript +interface ArgoSmartRoutingResponse { + result: { + id: 'smart_routing'; + value: 'on' | 'off'; + editable: boolean; + modified_on: string; // ISO 8601 timestamp + }; + success: boolean; + errors: Array<{ + code: number; + message: string; + }>; + messages: Array; +} +``` + +## Key Response Fields + +| Field | Type | Description | +|-------|------|-------------| +| `value` | `"on" \| "off"` | Current enablement status | +| `editable` | `boolean` | Whether changes are allowed (check before PATCH) | +| `modified_on` | `string` | ISO timestamp of last modification | +| `success` | `boolean` | Whether request succeeded | +| `errors` | `Array` | Error details if `success: false` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..40a7b12139c45db8f01d43264ecd0837f60aa16f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/configuration.md @@ -0,0 +1,197 @@ +## Configuration Management + +**Note on Smart Shield Evolution:** Argo Smart Routing is being integrated into Smart Shield. Configuration methods below remain valid; Terraform and IaC patterns unchanged. + +### Infrastructure as Code (Terraform) + +```hcl +# terraform/argo.tf +# Note: Use Cloudflare Terraform provider + +resource "cloudflare_argo" "example" { + zone_id = var.zone_id + smart_routing = "on" + tiered_caching = "on" +} + +variable "zone_id" { + description = "Cloudflare Zone ID" + type = string +} + +output "argo_enabled" { + value = cloudflare_argo.example.smart_routing + description = "Argo Smart Routing status" +} +``` + +### Environment-Based Configuration + +```typescript +// config/argo.ts +interface ArgoEnvironmentConfig { + enabled: boolean; + tieredCache: boolean; + monitoring: { + usageAlerts: boolean; + threshold: number; + }; +} + +const configs: Record = { + production: { + enabled: true, + tieredCache: true, + monitoring: { + usageAlerts: true, + threshold: 1000, // GB + }, + }, + staging: { + enabled: true, + tieredCache: false, + monitoring: { + usageAlerts: false, + threshold: 100, // GB + }, + }, + development: { + enabled: false, + tieredCache: false, + monitoring: { + usageAlerts: false, + threshold: 0, + }, + }, +}; + +export function getArgoConfig(env: string): ArgoEnvironmentConfig { + return configs[env] || configs.development; +} +``` + +### Pulumi Configuration + +```typescript +// pulumi/argo.ts +import * as cloudflare from '@pulumi/cloudflare'; + +const zone = new cloudflare.Zone('example-zone', { + zone: 'example.com', + plan: 'enterprise', +}); + +const argoSettings = new cloudflare.Argo('argo-config', { + zoneId: zone.id, + smartRouting: 'on', + tieredCaching: 'on', +}); + +export const argoEnabled = argoSettings.smartRouting; +export const zoneId = zone.id; +``` + +## Billing Configuration + +Before enabling Argo Smart Routing, ensure billing is configured for the account: + +**Prerequisites:** +1. Valid payment method on file +2. Enterprise or higher plan +3. Zone must have billing enabled + +**Check Billing Status via Dashboard:** +1. Navigate to Account → Billing +2. Verify payment method configured +3. Check zone subscription status + +**Note:** Attempting to enable Argo without billing configured will result in `editable: false` in API responses. + +## Environment Variable Setup + +**Required Environment Variables:** +```bash +# .env +CLOUDFLARE_API_TOKEN=your_api_token_here +CLOUDFLARE_ZONE_ID=your_zone_id_here +CLOUDFLARE_ACCOUNT_ID=your_account_id_here + +# Optional +ARGO_ENABLED=true +ARGO_TIERED_CACHE=true +``` + +**TypeScript Configuration Loader:** +```typescript +// config/env.ts +import { z } from 'zod'; + +const envSchema = z.object({ + CLOUDFLARE_API_TOKEN: z.string().min(1), + CLOUDFLARE_ZONE_ID: z.string().min(1), + CLOUDFLARE_ACCOUNT_ID: z.string().min(1), + ARGO_ENABLED: z.string().optional().default('false'), + ARGO_TIERED_CACHE: z.string().optional().default('false'), +}); + +export const env = envSchema.parse(process.env); + +export const argoConfig = { + enabled: env.ARGO_ENABLED === 'true', + tieredCache: env.ARGO_TIERED_CACHE === 'true', +}; +``` + +## CI/CD Integration + +**GitHub Actions Example:** +```yaml +# .github/workflows/deploy-argo.yml +name: Deploy Argo Configuration + +on: + push: + branches: [main] + paths: + - 'terraform/argo.tf' + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup Terraform + uses: hashicorp/setup-terraform@v2 + + - name: Terraform Init + run: terraform init + working-directory: ./terraform + + - name: Terraform Apply + run: terraform apply -auto-approve + working-directory: ./terraform + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + TF_VAR_zone_id: ${{ secrets.CLOUDFLARE_ZONE_ID }} +``` + +## Enterprise Preview Program + +For early access to Argo Smart Routing features and Smart Shield integration: + +**Eligibility:** +- Enterprise plan customers +- Active Cloudflare support contract +- Production traffic >100GB/month + +**How to Join:** +1. Contact Cloudflare account team or support +2. Request Argo/Smart Shield preview access +3. Receive preview zone configuration + +**Preview Features:** +- Enhanced analytics and reporting +- Smart Shield DDoS integration +- Advanced routing policies +- Priority support for routing issues \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..834742468d5b8a6d1be36fbf79d3501ca8400f15 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/gotchas.md @@ -0,0 +1,111 @@ +## Best Practices Summary + +**Smart Shield Note:** Argo Smart Routing evolving into Smart Shield. Best practices below remain applicable; monitor Cloudflare changelog for Smart Shield updates. + +1. **Always check editability** before attempting to enable/disable Argo +2. **Set up billing notifications** to avoid unexpected costs +3. **Combine with Tiered Cache** for maximum performance benefit +4. **Use in production only** - disable for dev/staging to control costs +5. **Monitor analytics** - require 500+ requests in 48h for detailed metrics +6. **Handle errors gracefully** - check for billing, permissions, zone compatibility +7. **Test configuration changes** in staging before production +8. **Use TypeScript SDK** for type safety and better developer experience +9. **Implement retry logic** for API calls in production systems +10. **Document zone-specific settings** for team visibility + +## Common Errors + +### "Argo unavailable" + +**Problem:** API returns error "Argo Smart Routing is unavailable for this zone" + +**Cause:** Zone not eligible or billing not set up + +**Solution:** +1. Verify zone has Enterprise or higher plan +2. Check billing is configured in Account → Billing +3. Ensure payment method is valid and current +4. Contact Cloudflare support if eligibility unclear + +### "Cannot enable/disable" + +**Problem:** API call succeeds but status remains unchanged, or `editable: false` in GET response + +**Cause:** Insufficient permissions or zone restrictions + +**Solution:** +1. Check API token has `Zone:Argo Smart Routing:Edit` permission +2. Verify `editable: true` in GET response before attempting PATCH +3. If `editable: false`, check: + - Billing configured for account + - Zone plan includes Argo (Enterprise+) + - No active zone holds or suspensions + - API token has correct scopes + +### `editable: false` Error + +**Problem:** GET request returns `"editable": false`, preventing enable/disable + +**Cause:** Zone-level restrictions from billing, plan, or permissions + +**Solution Pattern:** +```typescript +const status = await client.argo.smartRouting.get({ zone_id: zoneId }); + +if (!status.editable) { + // Don't attempt to modify - will fail + console.error('Cannot modify Argo settings:'); + console.error('- Check billing is configured'); + console.error('- Verify zone has Enterprise+ plan'); + console.error('- Confirm API token has Edit permission'); + throw new Error('Argo is not editable for this zone'); +} + +// Safe to proceed with enable/disable +await client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' }); +``` + +### Rate Limiting + +**Problem:** `429 Too Many Requests` error from API + +**Cause:** Exceeded API rate limits (typically 1200 requests per 5 minutes) + +**Solution:** +```typescript +import { RateLimitError } from 'cloudflare'; + +try { + await client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' }); +} catch (error) { + if (error instanceof RateLimitError) { + const retryAfter = error.response?.headers.get('retry-after'); + console.log(`Rate limited. Retry after ${retryAfter} seconds`); + + // Implement exponential backoff + await new Promise(resolve => setTimeout(resolve, (retryAfter || 60) * 1000)); + // Retry request + } +} +``` + +## Limits + +| Resource/Limit | Value | Notes | +|----------------|-------|-------| +| Min requests for analytics | 500 in 48h | For detailed metrics via GraphQL | +| Zones supported | Enterprise+ | Check zone plan in dashboard | +| Billing requirement | Must be configured | Before enabling; verify payment method | +| API rate limit | 1200 req / 5 min | Per API token across all endpoints | +| Spectrum apps | No hard limit | Each app can enable Argo independently | +| Traffic counting | Proxied only | Only orange-clouded DNS records count | +| DDoS/WAF exemption | Yes | Mitigated traffic excluded from billing | +| Analytics latency | 1-5 minutes | Real-time metrics not available | + +## Additional Resources + +- [Official Argo Smart Routing Docs](https://developers.cloudflare.com/argo-smart-routing/) +- [Cloudflare Smart Shield](https://developers.cloudflare.com/smart-shield/) +- [API Authentication](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/) +- [Cloudflare TypeScript SDK](https://github.com/cloudflare/cloudflare-typescript) +- [Cloudflare Python SDK](https://github.com/cloudflare/cloudflare-python) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..d7daa6199fc3ddb7dddcbe5871cdce469b226f15 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/argo-smart-routing/patterns.md @@ -0,0 +1,104 @@ +# Integration Patterns + +## Enable Argo + Tiered Cache + +```typescript +async function enableOptimalPerformance(client: Cloudflare, zoneId: string) { + await Promise.all([ + client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' }), + client.argo.tieredCaching.edit({ zone_id: zoneId, value: 'on' }), + ]); +} +``` + +**Flow:** Visitor → Edge (Lower-Tier) → [Cache Miss] → Upper-Tier → [Cache Miss + Argo] → Origin + +**Impact:** Argo ~30% latency reduction + Tiered Cache 50-80% origin offload + +## Usage Analytics (GraphQL) + +```graphql +query ArgoAnalytics($zoneTag: string!) { + viewer { + zones(filter: { zoneTag: $zoneTag }) { + httpRequestsAdaptiveGroups(limit: 1000) { + sum { argoBytes, bytes } + } + } + } +} +``` + +**Billing:** ~$0.10/GB. DDoS-mitigated and WAF-blocked traffic NOT charged. + +## Spectrum TCP Integration + +Enable Argo for non-HTTP traffic (databases, game servers, IoT): + +```typescript +// Update existing app +await client.spectrum.apps.update(appId, { zone_id: zoneId, argo_smart_routing: true }); + +// Create new app with Argo +await client.spectrum.apps.create({ + zone_id: zoneId, + dns: { type: 'CNAME', name: 'tcp.example.com' }, + origin_direct: ['tcp://origin.example.com:3306'], + protocol: 'tcp/3306', + argo_smart_routing: true, +}); +``` + +**Use cases:** MySQL/PostgreSQL (3306/5432), game servers, MQTT (1883), SSH (22) + +## Pre-Flight Validation + +```typescript +async function validateArgoEligibility(client: Cloudflare, zoneId: string) { + const status = await client.argo.smartRouting.get({ zone_id: zoneId }); + const zone = await client.zones.get({ zone_id: zoneId }); + + const issues: string[] = []; + if (!status.editable) issues.push('Zone not editable'); + if (['free', 'pro'].includes(zone.plan.legacy_id)) issues.push('Requires Business+ plan'); + if (zone.status !== 'active') issues.push('Zone not active'); + + return { canEnable: issues.length === 0, issues }; +} +``` + +## Post-Enable Verification + +```typescript +async function verifyArgoEnabled(client: Cloudflare, zoneId: string): Promise { + await new Promise(r => setTimeout(r, 2000)); // Wait for propagation + const status = await client.argo.smartRouting.get({ zone_id: zoneId }); + return status.value === 'on'; +} +``` + +## Full Setup Pattern + +```typescript +async function setupArgo(client: Cloudflare, zoneId: string) { + // 1. Validate + const { canEnable, issues } = await validateArgoEligibility(client, zoneId); + if (!canEnable) throw new Error(issues.join(', ')); + + // 2. Enable both features + await Promise.all([ + client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' }), + client.argo.tieredCaching.edit({ zone_id: zoneId, value: 'on' }), + ]); + + // 3. Verify + const [argo, cache] = await Promise.all([ + client.argo.smartRouting.get({ zone_id: zoneId }), + client.argo.tieredCaching.get({ zone_id: zoneId }), + ]); + + return { argo: argo.value === 'on', tieredCache: cache.value === 'on' }; +} +``` + +**When to combine:** High-traffic sites (>1TB/mo), global users, cacheable content. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fc3e8ebfe3d899ab6e4136e168b515fac03112b5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/README.md @@ -0,0 +1,122 @@ +# Cloudflare Bindings Skill Reference + +Expert guidance on Cloudflare Workers Bindings - the runtime APIs that connect Workers to Cloudflare platform resources. + +## What Are Bindings? + +Bindings are how Workers access Cloudflare resources (storage, compute, services) via the `env` object. They're configured in `wrangler.jsonc`, type-safe via TypeScript, and zero-overhead at runtime. + +## Reading Order + +1. **This file** - Binding catalog and selection guide +2. **[api.md](api.md)** - TypeScript types and env access patterns +3. **[configuration.md](configuration.md)** - Complete wrangler.jsonc examples +4. **[patterns.md](patterns.md)** - Best practices and common patterns +5. **[gotchas.md](gotchas.md)** - Critical pitfalls and troubleshooting + +## Binding Catalog + +### Storage Bindings + +| Binding | Use Case | Access Pattern | +|---------|----------|----------------| +| **KV** | Key-value cache, CDN-backed reads | `env.MY_KV.get(key)` | +| **R2** | Object storage (S3-compatible) | `env.MY_BUCKET.get(key)` | +| **D1** | SQL database (SQLite) | `env.DB.prepare(sql).all()` | +| **Durable Objects** | Coordination, real-time state | `env.MY_DO.get(id)` | +| **Vectorize** | Vector embeddings search | `env.VECTORIZE.query(vector)` | +| **Queues** | Async message processing | `env.MY_QUEUE.send(msg)` | + +### Compute Bindings + +| Binding | Use Case | Access Pattern | +|---------|----------|----------------| +| **Service** | Worker-to-Worker RPC | `env.MY_SERVICE.fetch(req)` | +| **Workers AI** | LLM inference | `env.AI.run(model, input)` | +| **Browser Rendering** | Headless Chrome | `env.BROWSER.fetch(url)` | + +### Platform Bindings + +| Binding | Use Case | Access Pattern | +|---------|----------|----------------| +| **Analytics Engine** | Custom metrics | `env.ANALYTICS.writeDataPoint(data)` | +| **mTLS** | Client certificates | `env.MY_CERT` (string) | +| **Hyperdrive** | Database pooling | `env.HYPERDRIVE.connectionString` | +| **Rate Limiting** | Request throttling | `env.RATE_LIMITER.limit(id)` | +| **Workflows** | Long-running workflows | `env.MY_WORKFLOW.create()` | + +### Configuration Bindings + +| Binding | Use Case | Access Pattern | +|---------|----------|----------------| +| **Environment Variables** | Non-sensitive config | `env.API_URL` (string) | +| **Secrets** | Sensitive values | `env.API_KEY` (string) | +| **Text/Data Blobs** | Static files | `env.MY_BLOB` (string) | +| **WASM** | WebAssembly modules | `env.MY_WASM` (WebAssembly.Module) | + +## Quick Selection Guide + +**Need persistent storage?** +- Key-value < 25MB → **KV** +- Files/objects → **R2** +- Relational data → **D1** +- Real-time coordination → **Durable Objects** + +**Need AI/compute?** +- LLM inference → **Workers AI** +- Scraping/PDFs → **Browser Rendering** +- Call another Worker → **Service binding** + +**Need async processing?** +- Background jobs → **Queues** + +**Need config?** +- Public values → **Environment Variables** +- Secrets → **Secrets** (never commit) + +## Quick Start + +1. **Add binding to wrangler.jsonc:** +```jsonc +{ + "kv_namespaces": [ + { "binding": "MY_KV", "id": "your-kv-id" } + ] +} +``` + +2. **Generate types:** +```bash +npx wrangler types +``` + +3. **Access in Worker:** +```typescript +export default { + async fetch(request, env, ctx) { + await env.MY_KV.put('key', 'value'); + return new Response('OK'); + } +} +``` + +## Type Safety + +Bindings are fully typed via `wrangler types`. See [api.md](api.md) for details. + +## Limits + +- 64 bindings max per Worker (all types combined) +- See [gotchas.md](gotchas.md) for per-binding limits + +## Key Concepts + +**Zero-overhead access:** Bindings compiled into Worker, no network calls to access +**Type-safe:** Full TypeScript support via `wrangler types` +**Per-environment:** Different IDs for dev/staging/production +**Secrets vs Vars:** Secrets encrypted at rest, never in config files + +## See Also + +- [Cloudflare Docs: Bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/) +- [Wrangler Configuration](https://developers.cloudflare.com/workers/wrangler/configuration/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/api.md new file mode 100644 index 0000000000000000000000000000000000000000..6f160dbaa12222959412bc1b8a1f6959624d2d71 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/api.md @@ -0,0 +1,203 @@ +# Bindings API Reference + +## TypeScript Types + +Cloudflare generates binding types via `npx wrangler types`. This creates `.wrangler/types/runtime.d.ts` with your Env interface. + +### Generated Env Interface + +After running `wrangler types`, TypeScript knows your bindings: + +```typescript +interface Env { + // From wrangler.jsonc bindings + MY_KV: KVNamespace; + MY_BUCKET: R2Bucket; + DB: D1Database; + MY_SERVICE: Fetcher; + AI: Ai; + + // From vars + API_URL: string; + + // From secrets (set via wrangler secret put) + API_KEY: string; +} +``` + +### Binding Types + +| Config | TypeScript Type | Package | +|--------|-----------------|---------| +| `kv_namespaces` | `KVNamespace` | `@cloudflare/workers-types` | +| `r2_buckets` | `R2Bucket` | `@cloudflare/workers-types` | +| `d1_databases` | `D1Database` | `@cloudflare/workers-types` | +| `durable_objects.bindings` | `DurableObjectNamespace` | `@cloudflare/workers-types` | +| `vectorize` | `VectorizeIndex` | `@cloudflare/workers-types` | +| `queues.producers` | `Queue` | `@cloudflare/workers-types` | +| `services` | `Fetcher` | `@cloudflare/workers-types` | +| `ai` | `Ai` | `@cloudflare/workers-types` | +| `browser` | `Fetcher` | `@cloudflare/workers-types` | +| `analytics_engine_datasets` | `AnalyticsEngineDataset` | `@cloudflare/workers-types` | +| `hyperdrive` | `Hyperdrive` | `@cloudflare/workers-types` | +| `rate_limiting` | `RateLimit` | `@cloudflare/workers-types` | +| `workflows` | `Workflow` | `@cloudflare/workers-types` | +| `mtls_certificates` / `vars` / `text_blobs` / `data_blobs` | `string` | Built-in | +| `wasm_modules` | `WebAssembly.Module` | Built-in | + +## Accessing Bindings + +### Method 1: fetch() Handler (Recommended) + +```typescript +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const value = await env.MY_KV.get('key'); + return new Response(value); + } +} +``` + +**Why:** Type-safe, aligns with Workers API, supports ctx for waitUntil/passThroughOnException. + +### Method 2: Hono Framework + +```typescript +import { Hono } from 'hono'; + +const app = new Hono<{ Bindings: Env }>(); + +app.get('/', async (c) => { + const value = await c.env.MY_KV.get('key'); + return c.json({ value }); +}); + +export default app; +``` + +**Why:** c.env auto-typed, ergonomic for routing-heavy apps. + +### Method 3: Module Workers (Legacy) + +```typescript +export async function handleRequest(request: Request, env: Env): Promise { + const value = await env.MY_KV.get('key'); + return new Response(value); +} + +addEventListener('fetch', (event) => { + // env not directly available - requires workarounds +}); +``` + +**Avoid:** Use fetch() handler instead (Method 1). + +## Type Generation Workflow + +### Initial Setup + +```bash +# Install wrangler +npm install -D wrangler + +# Generate types from wrangler.jsonc +npx wrangler types +``` + +### After Changing Bindings + +```bash +# Added/modified binding in wrangler.jsonc +npx wrangler types + +# TypeScript now sees updated Env interface +``` + +**Note:** `wrangler types` outputs to `.wrangler/types/runtime.d.ts`. TypeScript picks this up automatically if `@cloudflare/workers-types` is in `tsconfig.json` `"types"` array. + +## Key Binding Methods + +**KV:** +```typescript +await env.MY_KV.get(key, { type: 'json' }); // text|json|arrayBuffer|stream +await env.MY_KV.put(key, value, { expirationTtl: 3600 }); +await env.MY_KV.delete(key); +await env.MY_KV.list({ prefix: 'user:' }); +``` + +**R2:** +```typescript +await env.BUCKET.get(key); +await env.BUCKET.put(key, value); +await env.BUCKET.delete(key); +await env.BUCKET.list({ prefix: 'images/' }); +``` + +**D1:** +```typescript +await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first(); +await env.DB.batch([stmt1, stmt2]); +``` + +**Service:** +```typescript +await env.MY_SERVICE.fetch(new Request('https://fake/path')); +``` + +**Workers AI:** +```typescript +await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { prompt: 'Hello' }); +``` + +**Queues:** +```typescript +await env.MY_QUEUE.send({ userId: 123, action: 'process' }); +``` + +**Durable Objects:** +```typescript +const id = env.MY_DO.idFromName('user-123'); +const stub = env.MY_DO.get(id); +await stub.fetch(new Request('https://fake/increment')); +``` + +## Runtime vs Build-Time Types + +| Type Source | When Generated | Use Case | +|-------------|----------------|----------| +| `@cloudflare/workers-types` | npm install | Base Workers APIs (Request, Response, etc.) | +| `wrangler types` | After config change | Your specific bindings (Env interface) | + +**Install both:** +```bash +npm install -D @cloudflare/workers-types +npx wrangler types +``` + +## Type Safety Best Practices + +1. **Never use `any` for env:** +```typescript +// ❌ BAD +async fetch(request: Request, env: any) { } + +// ✅ GOOD +async fetch(request: Request, env: Env) { } +``` + +2. **Run wrangler types after config changes:** +```bash +# After editing wrangler.jsonc +npx wrangler types +``` + +3. **Check generated types match config:** +```bash +# View generated Env interface +cat .wrangler/types/runtime.d.ts +``` + +## See Also + +- [Workers Types Package](https://www.npmjs.com/package/@cloudflare/workers-types) +- [Wrangler Types Command](https://developers.cloudflare.com/workers/wrangler/commands/#types) \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..f388e186916a957e0f54c366792562eb2463dde3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/configuration.md @@ -0,0 +1,188 @@ +# Binding Configuration Reference + +## Storage Bindings + +```jsonc +{ + "kv_namespaces": [{ "binding": "MY_KV", "id": "..." }], + "r2_buckets": [{ "binding": "MY_BUCKET", "bucket_name": "my-bucket" }], + "d1_databases": [{ "binding": "DB", "database_name": "my-db", "database_id": "..." }], + "durable_objects": { "bindings": [{ "name": "MY_DO", "class_name": "MyDO" }] }, + "vectorize": [{ "binding": "VECTORIZE", "index_name": "my-index" }], + "queues": { "producers": [{ "binding": "MY_QUEUE", "queue": "my-queue" }] } +} +``` + +**Create commands:** +```bash +npx wrangler kv namespace create MY_KV +npx wrangler r2 bucket create my-bucket +npx wrangler d1 create my-db +npx wrangler vectorize create my-index --dimensions=768 --metric=cosine +npx wrangler queues create my-queue + +# List existing resources +npx wrangler kv namespace list +npx wrangler r2 bucket list +npx wrangler d1 list +npx wrangler vectorize list +npx wrangler queues list +``` + +## Compute Bindings + +```jsonc +{ + "services": [{ + "binding": "MY_SERVICE", + "service": "other-worker", + "environment": "production" // Optional: target specific env + }], + "ai": { "binding": "AI" }, + "browser": { "binding": "BROWSER" }, + "workflows": [{ "binding": "MY_WORKFLOW", "name": "my-workflow" }] +} +``` + +**Create workflows:** +```bash +npx wrangler workflows create my-workflow +``` + +## Platform Bindings + +```jsonc +{ + "analytics_engine_datasets": [{ "binding": "ANALYTICS" }], + "mtls_certificates": [{ "binding": "MY_CERT", "certificate_id": "..." }], + "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "..." }], + "unsafe": { + "bindings": [{ "name": "RATE_LIMITER", "type": "ratelimit", "namespace_id": "..." }] + } +} +``` + +## Configuration Bindings + +```jsonc +{ + "vars": { + "API_URL": "https://api.example.com", + "MAX_RETRIES": "3" + }, + "text_blobs": { "MY_TEXT": "./data/template.html" }, + "data_blobs": { "MY_DATA": "./data/config.bin" }, + "wasm_modules": { "MY_WASM": "./build/module.wasm" } +} +``` + +**Secrets (never in config):** +```bash +npx wrangler secret put API_KEY +``` + +## Environment-Specific Configuration + +```jsonc +{ + "name": "my-worker", + "vars": { "ENV": "production" }, + "kv_namespaces": [{ "binding": "CACHE", "id": "prod-kv-id" }], + + "env": { + "staging": { + "vars": { "ENV": "staging" }, + "kv_namespaces": [{ "binding": "CACHE", "id": "staging-kv-id" }] + } + } +} +``` + +**Deploy:** +```bash +npx wrangler deploy # Production +npx wrangler deploy --env staging +``` + +## Local Development + +```jsonc +{ + "kv_namespaces": [{ + "binding": "MY_KV", + "id": "prod-id", + "preview_id": "dev-id" // Used in wrangler dev + }] +} +``` + +**Or use remote:** +```bash +npx wrangler dev --remote # Uses production bindings +``` + +## Complete Example + +```jsonc +{ + "$schema": "./node_modules/wrangler/config-schema.json", + "name": "my-app", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", + + "vars": { "API_URL": "https://api.example.com" }, + "kv_namespaces": [{ "binding": "CACHE", "id": "abc123" }], + "r2_buckets": [{ "binding": "ASSETS", "bucket_name": "my-assets" }], + "d1_databases": [{ "binding": "DB", "database_name": "my-db", "database_id": "xyz789" }], + "services": [{ "binding": "AUTH", "service": "auth-worker" }], + "ai": { "binding": "AI" } +} +``` + +## Binding-Specific Configuration + +### Durable Objects with Class Export + +```jsonc +{ + "durable_objects": { + "bindings": [ + { "name": "COUNTER", "class_name": "Counter", "script_name": "my-worker" } + ] + } +} +``` + +```typescript +// In same Worker or script_name Worker +export class Counter { + constructor(private state: DurableObjectState, private env: Env) {} + async fetch(request: Request) { /* ... */ } +} +``` + +### Queue Consumers + +```jsonc +{ + "queues": { + "producers": [{ "binding": "MY_QUEUE", "queue": "my-queue" }], + "consumers": [{ "queue": "my-queue", "max_batch_size": 10 }] + } +} +``` + +Queue consumer handler: `export default { async queue(batch, env) { /* process batch.messages */ } }` + +## Key Points + +- **64 binding limit** (all types combined) +- **Secrets**: Always use `wrangler secret put`, never commit +- **Types**: Run `npx wrangler types` after config changes +- **Environments**: Use `env` field for staging/production variants +- **Development**: Use `preview_id` or `--remote` flag +- **IDs vs Names**: Some bindings use `id` (KV, D1), others use `name` (R2, Queues) + +## See Also + +- [Wrangler Configuration](https://developers.cloudflare.com/workers/wrangler/configuration/) \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..05b952fe48a8f036ab9b59da9a291e9c4d59ca77 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/gotchas.md @@ -0,0 +1,208 @@ +# Binding Gotchas and Troubleshooting + +## Critical: Global Scope Mutation + +### ❌ THE #1 GOTCHA: Caching env in Global Scope + +```typescript +// ❌ DANGEROUS - env cached at deploy time +const apiKey = env.API_KEY; // ERROR: env not available in global scope + +export default { + async fetch(request: Request, env: Env) { + // Uses undefined or stale value! + } +} +``` + +**Why it breaks:** +- `env` not available in global scope +- If using workarounds, secrets may not update without redeployment +- Leads to "Cannot read property 'X' of undefined" errors + +**✅ Always access env per-request:** +```typescript +export default { + async fetch(request: Request, env: Env) { + const apiKey = env.API_KEY; // Fresh every request + } +} +``` + +## Common Errors + +### "env.MY_KV is undefined" + +**Cause:** Name mismatch or not configured +**Solution:** Check wrangler.jsonc (case-sensitive), run `npx wrangler types`, verify `npx wrangler kv namespace list` + +### "Property 'MY_KV' does not exist on type 'Env'" + +**Cause:** Types not generated +**Solution:** `npx wrangler types` + +### "preview_id is required for --remote" + +**Cause:** Missing preview binding +**Solution:** Add `"preview_id": "dev-id"` or use `npx wrangler dev` (local mode) + +### "Secret updated but Worker still uses old value" + +**Cause:** Cached in global scope or not redeployed +**Solution:** Avoid global caching, redeploy after secret change + +### "KV get() returns null for existing key" + +**Cause:** Eventual consistency (60s), wrong namespace, wrong environment +**Solution:** +```bash +# Check key exists +npx wrangler kv key get --binding=MY_KV "your-key" + +# Verify namespace ID +npx wrangler kv namespace list + +# Check environment +npx wrangler deployments list +``` + +### "D1 database not found" + +**Solution:** `npx wrangler d1 list`, verify ID in wrangler.jsonc + +### "Service binding returns 'No such service'" + +**Cause:** Target Worker not deployed, name mismatch, environment mismatch +**Solution:** +```bash +# List deployed Workers +npx wrangler deployments list --name=target-worker + +# Check service binding config +cat wrangler.jsonc | grep -A2 services + +# Deploy target first +cd ../target-worker && npx wrangler deploy +``` + +### "Rate limit exceeded" on KV writes + +**Cause:** >1 write/second per key +**Solution:** Use different keys, Durable Objects, or Queues + +## Type Safety Gotchas + +### Missing @cloudflare/workers-types + +**Error:** `Cannot find name 'Request'` +**Solution:** `npm install -D @cloudflare/workers-types`, add to tsconfig.json `"types"` + +### Binding Type Mismatches + +```typescript +// ❌ Wrong - KV returns string | null +const value: string = await env.MY_KV.get('key'); + +// ✅ Handle null +const value = await env.MY_KV.get('key'); +if (!value) return new Response('Not found', { status: 404 }); +``` + +## Environment Gotchas + +### Wrong Environment Deployed + +**Solution:** Check `npx wrangler deployments list`, use `--env` flag + +### Secrets Not Per-Environment + +**Solution:** Set per environment: `npx wrangler secret put API_KEY --env staging` + +## Development Gotchas + +**wrangler dev vs deploy:** +- dev: Uses `preview_id` or local bindings, secrets not available +- deploy: Uses production `id`, secrets available + +**Access secrets in dev:** `npx wrangler dev --remote` +**Persist local data:** `npx wrangler dev --persist` + +## Performance Gotchas + +### Sequential Binding Calls + +```typescript +// ❌ Slow +const user = await env.DB.prepare('...').first(); +const config = await env.MY_KV.get('config'); + +// ✅ Parallel +const [user, config] = await Promise.all([ + env.DB.prepare('...').first(), + env.MY_KV.get('config') +]); +``` + +## Security Gotchas + +**❌ Secrets in logs:** `console.log('Key:', env.API_KEY)` - visible in dashboard +**✅** `console.log('Key:', env.API_KEY ? '***' : 'missing')` + +**❌ Exposing env:** `return Response.json(env)` - exposes all bindings +**✅** Never return env object in responses + +## Limits Reference + +| Resource | Limit | Impact | Plan | +|----------|-------|--------|------| +| **Bindings per Worker** | 64 total | All binding types combined | All | +| **Environment variables** | 64 max, 5KB each | Per Worker | All | +| **Secret size** | 1KB | Per secret | All | +| **KV key size** | 512 bytes | UTF-8 encoded | All | +| **KV value size** | 25 MB | Per value | All | +| **KV writes per key** | 1/second | Per key; exceeding = 429 error | All | +| **KV list() results** | 1000 keys | Per call; use cursor for more | All | +| **KV operations** | 1000 reads/day | Free tier only | Free | +| **R2 object size** | 5 TB | Per object | All | +| **R2 operations** | 1M Class A/month free | Writes | All | +| **D1 database size** | 10 GB | Per database | All | +| **D1 rows per query** | 100,000 | Result set limit | All | +| **D1 databases** | 10 | Free tier | Free | +| **Queue batch size** | 100 messages | Per consumer batch | All | +| **Queue message size** | 128 KB | Per message | All | +| **Service binding calls** | Unlimited | Counts toward CPU time | All | +| **Durable Objects** | 1M requests/month free | First 1M | Free | + +## Debugging Tips + +```bash +# Check configuration +npx wrangler deploy --dry-run # Validate config without deploying +npx wrangler kv namespace list # List KV namespaces +npx wrangler secret list # List secrets (not values) +npx wrangler deployments list # Recent deployments + +# Inspect bindings +npx wrangler kv key list --binding=MY_KV +npx wrangler kv key get --binding=MY_KV "key-name" +npx wrangler r2 object get my-bucket/file.txt +npx wrangler d1 execute my-db --command="SELECT * FROM sqlite_master" + +# Test locally +npx wrangler dev # Local mode +npx wrangler dev --remote # Production bindings +npx wrangler dev --persist # Persist data across restarts + +# Verify types +npx wrangler types +cat .wrangler/types/runtime.d.ts | grep "interface Env" + +# Debug specific binding issues +npx wrangler tail # Stream logs in real-time +npx wrangler tail --format=pretty # Formatted logs +``` + +## See Also + +- [Workers Limits](https://developers.cloudflare.com/workers/platform/limits/) +- [Wrangler Commands](https://developers.cloudflare.com/workers/wrangler/commands/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..6bfb5154b940d057be447c9c24f0f3b9f8df4f2c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bindings/patterns.md @@ -0,0 +1,200 @@ +# Binding Patterns and Best Practices + +## Service Binding Patterns + +### RPC via Service Bindings + +```typescript +// auth-worker +export default { + async fetch(request: Request, env: Env) { + const token = request.headers.get('Authorization'); + return new Response(JSON.stringify({ valid: await validateToken(token) })); + } +} + +// api-worker +const response = await env.AUTH_SERVICE.fetch( + new Request('https://fake-host/validate', { + headers: { 'Authorization': token } + }) +); +``` + +**Why RPC?** Zero latency (same datacenter), no DNS, free, type-safe. + +**HTTP vs Service:** +```typescript +// ❌ HTTP (slow, paid, cross-region latency) +await fetch('https://auth-worker.example.com/validate'); + +// ✅ Service binding (fast, free, same isolate) +await env.AUTH_SERVICE.fetch(new Request('https://fake-host/validate')); +``` + +**URL doesn't matter:** Service bindings ignore hostname/protocol, routing happens via binding name. + +### Typed Service RPC + +```typescript +// shared-types.ts +export interface AuthRequest { token: string; } +export interface AuthResponse { valid: boolean; userId?: string; } + +// auth-worker +export default { + async fetch(request: Request): Promise { + const body: AuthRequest = await request.json(); + const response: AuthResponse = { valid: true, userId: '123' }; + return Response.json(response); + } +} + +// api-worker +const response = await env.AUTH_SERVICE.fetch( + new Request('https://fake/validate', { + method: 'POST', + body: JSON.stringify({ token } satisfies AuthRequest) + }) +); +const data: AuthResponse = await response.json(); +``` + +## Secrets Management + +```bash +# Set secret +npx wrangler secret put API_KEY +cat api-key.txt | npx wrangler secret put API_KEY +npx wrangler secret put API_KEY --env staging +``` + +```typescript +// Use secret +const response = await fetch('https://api.example.com', { + headers: { 'Authorization': `Bearer ${env.API_KEY}` } +}); +``` + +**Never commit secrets:** +```jsonc +// ❌ NEVER +{ "vars": { "API_KEY": "sk_live_abc123" } } +``` + +## Testing with Mock Bindings + +### Vitest Mock + +```typescript +import { vi } from 'vitest'; + +const mockKV: KVNamespace = { + get: vi.fn(async (key) => key === 'test' ? 'value' : null), + put: vi.fn(async () => {}), + delete: vi.fn(async () => {}), + list: vi.fn(async () => ({ keys: [], list_complete: true, cursor: '' })), + getWithMetadata: vi.fn(), +} as unknown as KVNamespace; + +const mockEnv: Env = { MY_KV: mockKV }; +const mockCtx: ExecutionContext = { + waitUntil: vi.fn(), + passThroughOnException: vi.fn(), +}; + +const response = await worker.fetch( + new Request('http://localhost/test'), + mockEnv, + mockCtx +); +``` + +## Binding Access Patterns + +### Lazy Access + +```typescript +// ✅ Access only when needed +if (url.pathname === '/cached') { + const cached = await env.MY_KV.get('data'); + if (cached) return new Response(cached); +} +``` + +### Parallel Access + +```typescript +// ✅ Parallelize independent calls +const [user, config, cache] = await Promise.all([ + env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first(), + env.MY_KV.get('config'), + env.CACHE.get('data') +]); +``` + +## Storage Selection + +### KV: CDN-Backed Reads + +```typescript +const config = await env.MY_KV.get('app-config', { type: 'json' }); +``` + +**Use when:** Read-heavy, <25MB, global distribution, eventual consistency OK +**Latency:** <10ms reads (cached), writes eventually consistent (60s) + +### D1: Relational Queries + +```typescript +const results = await env.DB.prepare(` + SELECT u.name, COUNT(o.id) FROM users u + LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id +`).all(); +``` + +**Use when:** Relational data, JOINs, ACID transactions +**Limits:** 10GB database size, 100k rows per query + +### R2: Large Objects + +```typescript +const object = await env.MY_BUCKET.get('large-file.zip'); +return new Response(object.body); +``` + +**Use when:** Files >25MB, S3-compatible API needed +**Limits:** 5TB per object, unlimited storage + +### Durable Objects: Coordination + +```typescript +const id = env.COUNTER.idFromName('global'); +const stub = env.COUNTER.get(id); +await stub.fetch(new Request('https://fake/increment')); +``` + +**Use when:** Strong consistency, real-time coordination, WebSocket state +**Guarantees:** Single-threaded execution, transactional storage + +## Anti-Patterns + +**❌ Hardcoding credentials:** `const apiKey = 'sk_live_abc123'` +**✅** `npx wrangler secret put API_KEY` + +**❌ Using REST API:** `fetch('https://api.cloudflare.com/.../kv/...')` +**✅** `env.MY_KV.get('key')` + +**❌ Polling storage:** `setInterval(() => env.KV.get('config'), 1000)` +**✅** Use Durable Objects for real-time state + +**❌ Large data in vars:** `{ "vars": { "HUGE_CONFIG": "..." } }` (5KB max) +**✅** `env.MY_KV.put('config', data)` + +**❌ Caching env globally:** `const apiKey = env.API_KEY` outside fetch() +**✅** Access `env.API_KEY` per-request inside fetch() + +## See Also + +- [Service Bindings Docs](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) +- [Miniflare Testing](https://miniflare.dev/) \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a76808db1bf2abb8ff76677cdf36acee592dd142 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/README.md @@ -0,0 +1,94 @@ +# Cloudflare Bot Management + +Enterprise-grade bot detection, protection, and mitigation using ML/heuristics, bot scores, JavaScript detections, and verified bot handling. + +## Overview + +Bot Management provides multi-tier protection: +- **Free (Bot Fight Mode)**: Auto-blocks definite bots, no config +- **Pro/Business (Super Bot Fight Mode)**: Configurable actions, static resource protection, analytics groupings +- **Enterprise (Bot Management)**: Granular 1-99 scores, WAF integration, JA3/JA4 fingerprinting, Workers API, Advanced Analytics + +## Quick Start + +```txt +# Dashboard: Security > Bots +# Enterprise: Deploy rule template +(cf.bot_management.score eq 1 and not cf.bot_management.verified_bot) → Block +(cf.bot_management.score le 29 and not cf.bot_management.verified_bot) → Managed Challenge +``` + +## What Do You Need? + +```txt +├─ Initial setup → configuration.md +│ ├─ Free tier → "Bot Fight Mode" +│ ├─ Pro/Business → "Super Bot Fight Mode" +│ └─ Enterprise → "Bot Management for Enterprise" +├─ Workers API integration → api.md +├─ WAF rules → patterns.md +├─ Debugging → gotchas.md +└─ Analytics → api.md#bot-analytics +``` + +## Reading Order + +| Task | Files to Read | +|------|---------------| +| Enable bot protection | README → configuration.md | +| Workers bot detection | README → api.md | +| WAF rule templates | README → patterns.md | +| Debug bot issues | gotchas.md | +| Advanced analytics | api.md#bot-analytics | + +## Core Concepts + +**Bot Scores**: 1-99 (1 = definitely automated, 99 = definitely human). Threshold: <30 indicates bot traffic. Enterprise gets granular 1-99; Pro/Business get groupings only. + +**Detection Engines**: Heuristics (known fingerprints, assigns score=1), ML (majority of detections, supervised learning on billions of requests), Anomaly Detection (optional, baseline traffic analysis), JavaScript Detections (headless browser detection). + +**Verified Bots**: Allowlisted good bots (search engines, AI crawlers) verified via reverse DNS or Web Bot Auth. Access via `cf.bot_management.verified_bot` or `cf.verified_bot_category`. + +## Platform Limits + +| Plan | Bot Scores | JA3/JA4 | Custom Rules | Analytics Retention | +|------|------------|---------|--------------|---------------------| +| Free | No (auto-block only) | No | 5 | N/A (no analytics) | +| Pro/Business | Groupings only | No | 20/100 | 30 days (72h at a time) | +| Enterprise | 1-99 granular | Yes | 1,000+ | 30 days (1 week at a time) | + +## Basic Patterns + +```typescript +// Workers: Check bot score +export default { + async fetch(request: Request): Promise { + const botScore = request.cf?.botManagement?.score; + if (botScore && botScore < 30 && !request.cf?.botManagement?.verifiedBot) { + return new Response('Bot detected', { status: 403 }); + } + return fetch(request); + } +}; +``` + +```txt +# WAF: Block definite bots +(cf.bot_management.score eq 1 and not cf.bot_management.verified_bot) + +# WAF: Protect sensitive endpoints +(cf.bot_management.score lt 50 and http.request.uri.path in {"/login" "/checkout"} and not cf.bot_management.verified_bot) +``` + +## In This Reference + +- [configuration.md](./configuration.md) - Product tiers, WAF rule setup, JavaScript Detections, ML auto-updates +- [api.md](./api.md) - Workers BotManagement interface, WAF fields, JA4 Signals +- [patterns.md](./patterns.md) - E-commerce, API protection, mobile app allowlisting, SEO-friendly handling +- [gotchas.md](./gotchas.md) - False positives/negatives, score=0 issues, JSD limitations, CSP requirements + +## See Also + +- [waf](../waf/) - WAF custom rules for bot enforcement +- [workers](../workers/) - Workers request.cf.botManagement API +- [api-shield](../api-shield/) - API-specific bot protection diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/api.md new file mode 100644 index 0000000000000000000000000000000000000000..9badf4337a6e47dab667e7a147fcec687eade65b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/api.md @@ -0,0 +1,169 @@ +# Bot Management API + +## Workers: BotManagement Interface + +```typescript +interface BotManagement { + score: number; // 1-99 (Enterprise), 0 if not computed + verifiedBot: boolean; // Is verified bot + staticResource: boolean; // Serves static resource + ja3Hash: string; // JA3 fingerprint (Enterprise, HTTPS only) + ja4: string; // JA4 fingerprint (Enterprise, HTTPS only) + jsDetection?: { + passed: boolean; // Passed JS detection (if enabled) + }; + detectionIds: number[]; // Heuristic detection IDs + corporateProxy?: boolean; // From corporate proxy (Enterprise) +} + +// DEPRECATED: Use botManagement.score instead +// request.cf.clientTrustScore (legacy, duplicate of botManagement.score) + +// Access via request.cf +import type { IncomingRequestCfProperties } from '@cloudflare/workers-types'; + +export default { + async fetch(request: Request): Promise { + const cf = request.cf as IncomingRequestCfProperties | undefined; + const botMgmt = cf?.botManagement; + + if (!botMgmt) return fetch(request); + if (botMgmt.verifiedBot) return fetch(request); // Allow verified bots + if (botMgmt.score === 1) return new Response('Blocked', { status: 403 }); + if (botMgmt.score < 30) return new Response('Challenge required', { status: 429 }); + + return fetch(request); + } +}; +``` + +## WAF Fields Reference + +```txt +# Score fields +cf.bot_management.score # 0-99 (0 = not computed) +cf.bot_management.verified_bot # boolean +cf.bot_management.static_resource # boolean +cf.bot_management.ja3_hash # string (Enterprise) +cf.bot_management.ja4 # string (Enterprise) +cf.bot_management.detection_ids # array +cf.bot_management.js_detection.passed # boolean +cf.bot_management.corporate_proxy # boolean (Enterprise) +cf.verified_bot_category # string + +# Workers equivalent +request.cf.botManagement.score +request.cf.botManagement.verifiedBot +request.cf.botManagement.ja3Hash +request.cf.botManagement.ja4 +request.cf.botManagement.jsDetection.passed +request.cf.verifiedBotCategory +``` + +## JA4 Signals (Enterprise) + +```typescript +import type { IncomingRequestCfProperties } from '@cloudflare/workers-types'; + +interface JA4Signals { + // Ratios (0.0-1.0) + heuristic_ratio_1h?: number; // Fraction flagged by heuristics + browser_ratio_1h?: number; // Fraction from real browsers + cache_ratio_1h?: number; // Fraction hitting cache + h2h3_ratio_1h?: number; // Fraction using HTTP/2 or HTTP/3 + // Ranks (relative position in distribution) + uas_rank_1h?: number; // User-Agent diversity rank + paths_rank_1h?: number; // Path diversity rank + reqs_rank_1h?: number; // Request volume rank + ips_rank_1h?: number; // IP diversity rank + // Quantiles (0.0-1.0, percentile in distribution) + reqs_quantile_1h?: number; // Request volume quantile + ips_quantile_1h?: number; // IP count quantile +} + +export default { + async fetch(request: Request): Promise { + const cf = request.cf as IncomingRequestCfProperties | undefined; + const ja4Signals = cf?.ja4Signals as JA4Signals | undefined; + + if (!ja4Signals) return fetch(request); // Not available for HTTP or Worker routing + + // Check for anomalous behavior + // High heuristic_ratio or low browser_ratio = suspicious + const heuristicRatio = ja4Signals.heuristic_ratio_1h ?? 0; + const browserRatio = ja4Signals.browser_ratio_1h ?? 0; + + if (heuristicRatio > 0.5 || browserRatio < 0.3) { + return new Response('Suspicious traffic', { status: 403 }); + } + + return fetch(request); + } +}; +``` + +## Common Patterns + +See [patterns.md](./patterns.md) for Workers examples: mobile app allowlisting, corporate proxy exemption, datacenter detection, conditional delay, and more. + +## Bot Analytics + +### Access Locations +- Dashboard: Security > Bots (old) or Security > Analytics > Bot analysis (new) +- GraphQL API for programmatic access +- Security Events & Security Analytics +- Logpush/Logpull + +### Available Data +- **Enterprise BM**: Bot scores (1-99), bot score source, distribution +- **Pro/Business**: Bot groupings (automated, likely automated, likely human) +- Top attributes: IPs, paths, user agents, countries +- Detection sources: Heuristics, ML, AD, JSD +- Verified bot categories + +### Time Ranges +- **Enterprise BM**: Up to 1 week at a time, 30 days history +- **Pro/Business**: Up to 72 hours at a time, 30 days history +- Real-time in most cases, adaptive sampling (1-10% depending on volume) + +## Logpush Fields + +```txt +BotScore # 1-99 or 0 if not computed +BotScoreSrc # Detection engine (ML, Heuristics, etc.) +BotTags # Classification tags +BotDetectionIDs # Heuristic detection IDs +``` + +**BotScoreSrc values:** +- `"Heuristics"` - Known fingerprint +- `"Machine Learning"` - ML model +- `"Anomaly Detection"` - Baseline anomaly +- `"JS Detection"` - JavaScript check +- `"Cloudflare Service"` - Zero Trust +- `"Not Computed"` - Score = 0 + +Access via Logpush (stream to cloud storage/SIEM), Logpull (API to fetch logs), or GraphQL API (query analytics data). + +## Testing with Miniflare + +Miniflare provides mock botManagement data for local development: + +**Default values:** +- `score: 99` (human) +- `verifiedBot: false` +- `corporateProxy: false` +- `ja3Hash: "25b4882c2bcb50cd6b469ff28c596742"` +- `staticResource: false` +- `detectionIds: []` + +**Override in tests:** +```typescript +import { getPlatformProxy } from 'wrangler'; + +const { cf, dispose } = await getPlatformProxy(); +// cf.botManagement is frozen mock object +expect(cf.botManagement.score).toBe(99); +``` + +For custom test data, mock request.cf in your test setup. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..450f5b00334d34f8c256defc83e7dbc7f385fcb6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/configuration.md @@ -0,0 +1,163 @@ +# Bot Management Configuration + +## Product Tiers + +**Note:** Dashboard paths differ between old and new UI: +- **New:** Security > Settings > Filter "Bot traffic" +- **Old:** Security > Bots + +Both UIs access same settings. + +### Bot Score Groupings (Pro/Business) + +Pro/Business users see bot score groupings instead of granular 1-99 scores: + +| Score | Grouping | Meaning | +|-------|----------|---------| +| 0 | Not computed | Bot Management didn't run | +| 1 | Automated | Definite bot (heuristic match) | +| 2-29 | Likely automated | Probably bot (ML detection) | +| 30-99 | Likely human | Probably human | +| N/A | Verified bot | Allowlisted good bot | + +Enterprise plans get granular 1-99 scores for custom thresholds. + +### Bot Fight Mode (Free) +- Auto-blocks definite bots (score=1), excludes verified bots by default +- JavaScript Detections always enabled, no configuration options + +### Super Bot Fight Mode (Pro/Business) +```txt +Dashboard: Security > Bots > Configure +- Definitely automated: Block/Challenge +- Likely automated: Challenge/Allow +- Verified bots: Allow (recommended) +- Static resource protection: ON (may block mail clients) +- JavaScript Detections: Optional +``` + +### Bot Management for Enterprise +```txt +Dashboard: Security > Bots > Configure > Auto-updates: ON (recommended) + +# Template 1: Block definite bots +(cf.bot_management.score eq 1 and not cf.bot_management.verified_bot and not cf.bot_management.static_resource) +Action: Block + +# Template 2: Challenge likely bots +(cf.bot_management.score ge 2 and cf.bot_management.score le 29 and not cf.bot_management.verified_bot and not cf.bot_management.static_resource) +Action: Managed Challenge +``` + +## JavaScript Detections Setup + +### Enable via Dashboard +```txt +Security > Bots > Configure Bot Management > JS Detections: ON + +Update CSP: script-src 'self' /cdn-cgi/challenge-platform/; +``` + +### Manual JS Injection (API) +```html + + +``` + +**Use API for**: Selective deployment on specific pages +**Don't combine**: Zone-wide toggle + manual injection + +### WAF Rules for JSD +```txt +# NEVER use on first page visit (needs HTML page first) +(not cf.bot_management.js_detection.passed and http.request.uri.path eq "/api/user/create" and http.request.method eq "POST" and not cf.bot_management.verified_bot) +Action: Managed Challenge (always use Managed Challenge, not Block) +``` + +### Limitations +- First request won't have JSD data (needs HTML page first) +- Strips ETags from HTML responses +- Not supported with CSP via `` tags +- Websocket endpoints not supported +- Native mobile apps won't pass +- cf_clearance cookie: 15-minute lifespan, max 4096 bytes + +## __cf_bm Cookie + +Cloudflare sets `__cf_bm` cookie to smooth bot scores across user sessions: + +- **Purpose:** Reduces false positives from score volatility +- **Scope:** Per-domain, HTTP-only +- **Lifespan:** Session duration +- **Privacy:** No PII—only session classification +- **Automatic:** No configuration required + +Bot scores for repeat visitors consider session history via this cookie. + +## Static Resource Protection + +**File Extensions**: ico, jpg, png, jpeg, gif, css, js, tif, tiff, bmp, pict, webp, svg, svgz, class, jar, txt, csv, doc, docx, xls, xlsx, pdf, ps, pls, ppt, pptx, ttf, otf, woff, woff2, eot, eps, ejs, swf, torrent, midi, mid, m3u8, m4a, mp3, ogg, ts +**Plus**: `/.well-known/` path (all files) + +```txt +# Exclude static resources from bot rules +(cf.bot_management.score lt 30 and not cf.bot_management.static_resource) +``` + +**WARNING**: May block mail clients fetching static images + +## JA3/JA4 Fingerprinting (Enterprise) + +```txt +# Block specific attack fingerprint +(cf.bot_management.ja3_hash eq "8b8e3d5e3e8b3d5e") + +# Allow mobile app by fingerprint +(cf.bot_management.ja4 eq "your_mobile_app_fingerprint") +``` + +Only available for HTTPS/TLS traffic. Missing for Worker-routed traffic or HTTP requests. + +## Verified Bot Categories + +```txt +# Allow search engines only +(cf.verified_bot_category eq "Search Engine Crawler") + +# Block AI crawlers +(cf.verified_bot_category eq "AI Crawler") +Action: Block + +# Or use dashboard: Security > Settings > Bot Management > Block AI Bots +``` + +| Category | String Value | Example | +|----------|--------------|---------| +| AI Crawler | `AI Crawler` | GPTBot, Claude-Web | +| AI Assistant | `AI Assistant` | Perplexity-User, DuckAssistBot | +| AI Search | `AI Search` | OAI-SearchBot | +| Accessibility | `Accessibility` | Accessible Web Bot | +| Academic Research | `Academic Research` | Library of Congress | +| Advertising & Marketing | `Advertising & Marketing` | Google Adsbot | +| Aggregator | `Aggregator` | Pinterest, Indeed | +| Archiver | `Archiver` | Internet Archive, CommonCrawl | +| Feed Fetcher | `Feed Fetcher` | RSS/Podcast updaters | +| Monitoring & Analytics | `Monitoring & Analytics` | Uptime monitors | +| Page Preview | `Page Preview` | Facebook/Slack link preview | +| SEO | `Search Engine Optimization` | Google Lighthouse | +| Security | `Security` | Vulnerability scanners | +| Social Media Marketing | `Social Media Marketing` | Brandwatch | +| Webhooks | `Webhooks` | Payment processors | +| Other | `Other` | Uncategorized bots | + +## Best Practices + +- **ML Auto-Updates**: Enable on Enterprise for latest models +- **Start with Managed Challenge**: Test before blocking +- **Always exclude verified bots**: Use `not cf.bot_management.verified_bot` +- **Exempt corporate proxies**: For B2B traffic via `cf.bot_management.corporate_proxy` +- **Use static resource exception**: Improves performance, reduces overhead diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..f98554e41530b24f5a0db277fae9b17a731136c8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/gotchas.md @@ -0,0 +1,114 @@ +# Bot Management Gotchas + +## Common Errors + +### "Bot Score = 0" + +**Cause:** Bot Management didn't run (internal Cloudflare request, Worker routing to zone (Orange-to-Orange), or request handled before BM (Redirect Rules, etc.)) +**Solution:** Check request flow and ensure Bot Management runs in request lifecycle + +### "JavaScript Detections Not Working" + +**Cause:** `js_detection.passed` always false or undefined due to: CSP headers don't allow `/cdn-cgi/challenge-platform/`, using on first page visit (needs HTML page first), ad blockers or disabled JS, JSD not enabled in dashboard, or using Block action (must use Managed Challenge) +**Solution:** Add CSP header `Content-Security-Policy: script-src 'self' /cdn-cgi/challenge-platform/;` and ensure JSD is enabled with Managed Challenge action + +### "False Positives (Legitimate Users Blocked)" + +**Cause:** Bot detection incorrectly flagging legitimate users +**Solution:** Check Bot Analytics for affected IPs/paths, identify detection source (ML, Heuristics, etc.), create exception rule like `(cf.bot_management.score lt 30 and http.request.uri.path eq "/problematic-path")` with Action: Skip (Bot Management), or allowlist by IP/ASN/country + +### "False Negatives (Bots Not Caught)" + +**Cause:** Bots bypassing detection +**Solution:** Lower score threshold (30 → 50), enable JavaScript Detections, add JA3/JA4 fingerprinting rules, or use rate limiting as fallback + +### "Verified Bot Blocked" + +**Cause:** Search engine bot blocked by WAF Managed Rules (not just Bot Management) +**Solution:** Create WAF exception for specific rule ID and verify bot via reverse DNS + +### "Yandex Bot Blocked During IP Update" + +**Cause:** Yandex updates bot IPs; new IPs unrecognized for 48h during propagation +**Solution:** +1. Check Security Events for specific WAF rule ID blocking Yandex +2. Create WAF exception: + ```txt + (http.user_agent contains "YandexBot" and ip.src in {}) + Action: Skip (WAF Managed Ruleset) + ``` +3. Monitor Bot Analytics for 48h +4. Remove exception after propagation completes + +Issue resolves automatically after 48h. Contact Cloudflare Support if persists. + +### "JA3/JA4 Missing" + +**Cause:** Non-HTTPS traffic, Worker routing traffic, Orange-to-Orange traffic via Worker, or Bot Management skipped +**Solution:** JA3/JA4 only available for HTTPS/TLS traffic; check request routing + +**JA3/JA4 Not User-Unique:** Same browser/library version = same fingerprint +- Don't use for user identification +- Use for client profiling only +- Fingerprints change with browser updates + +## Bot Verification Methods + +Cloudflare verifies bots via: + +1. **Reverse DNS (IP validation):** Traditional method—bot IP resolves to expected domain +2. **Web Bot Auth:** Modern cryptographic verification—faster propagation + +When `verifiedBot=true`, bot passed at least one method. + +**Inactive verified bots:** IPs removed after 24h of no traffic. + +## Detection Engine Behavior + +| Engine | Score | Timing | Plan | Notes | +|--------|-------|--------|------|-------| +| Heuristics | Always 1 | Immediate | All | Known fingerprints—overrides ML | +| ML | 1-99 | Immediate | All | Majority of detections | +| Anomaly Detection | Influences | After baseline | Enterprise | Optional, baseline analysis | +| JavaScript Detections | Pass/fail | After JS | Pro+ | Headless browser detection | +| Cloudflare Service | N/A | N/A | Enterprise | Zero Trust internal source | + +**Priority:** Heuristics > ML—if heuristic matches, score=1 regardless of ML. + +## Limits + +| Limit | Value | Notes | +|-------|-------|-------| +| Bot Score = 0 | Means not computed | Not score = 100 | +| First request JSD data | May not be available | JSD data appears on subsequent requests | +| Score accuracy | Not 100% guaranteed | False positives/negatives possible | +| JSD on first HTML page visit | Not supported | Requires subsequent page load | +| JSD requirements | JavaScript-enabled browser | Won't work with JS disabled or ad blockers | +| JSD ETag stripping | Strips ETags from HTML responses | May affect caching behavior | +| JSD CSP compatibility | Requires specific CSP | Not compatible with some CSP configurations | +| JSD meta CSP tags | Not supported | Must use HTTP headers | +| JSD WebSocket support | Not supported | WebSocket endpoints won't work with JSD | +| JSD mobile app support | Native apps won't pass | Only works in browsers | +| JA3/JA4 traffic type | HTTPS/TLS only | Not available for non-HTTPS traffic | +| JA3/JA4 Worker routing | Missing for Worker-routed traffic | Check request routing | +| JA3/JA4 uniqueness | Not unique per user | Shared by clients with same browser/library | +| JA3/JA4 stability | Can change with updates | Browser/library updates affect fingerprints | +| WAF custom rules (Free) | 5 | Varies by plan | +| WAF custom rules (Pro) | 20 | Varies by plan | +| WAF custom rules (Business) | 100 | Varies by plan | +| WAF custom rules (Enterprise) | 1,000+ | Varies by plan | +| Workers CPU time | Varies by plan | Applies to bot logic | +| Bot Analytics sampling | 1-10% adaptive | High-volume zones sampled more aggressively | +| Bot Analytics history | 30 days max | Historical data retention limit | +| CSP requirements for JSD | Must allow `/cdn-cgi/challenge-platform/` | Required for JSD to function | + +### Plan Restrictions + +| Feature | Free | Pro/Business | Enterprise | +|---------|------|--------------|------------| +| Granular scores (1-99) | No | No | Yes | +| JA3/JA4 | No | No | Yes | +| Anomaly Detection | No | No | Yes | +| Corporate Proxy detection | No | No | Yes | +| Verified bot categories | Limited | Limited | Full | +| Custom WAF rules | 5 | 20/100 | 1,000+ | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..2bfab7b18b60019fde5b2e6c7364c0c42be40ed5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/bot-management/patterns.md @@ -0,0 +1,182 @@ +# Bot Management Patterns + +## E-commerce Protection + +```txt +# High security for checkout +(cf.bot_management.score lt 50 and http.request.uri.path in {"/checkout" "/cart/add"} and not cf.bot_management.verified_bot and not cf.bot_management.corporate_proxy) +Action: Managed Challenge +``` + +## API Protection + +```txt +# Protect API with JS detection + score +(http.request.uri.path matches "^/api/" and (cf.bot_management.score lt 30 or not cf.bot_management.js_detection.passed) and not cf.bot_management.verified_bot) +Action: Block +``` + +## SEO-Friendly Bot Handling + +```txt +# Allow search engine crawlers +(cf.bot_management.score lt 30 and not cf.verified_bot_category in {"Search Engine Crawler"}) +Action: Managed Challenge +``` + +## Block AI Scrapers + +```txt +# Block training crawlers only (allow AI assistants/search) +(cf.verified_bot_category eq "AI Crawler") +Action: Block + +# Block all AI-related bots (training + assistants + search) +(cf.verified_bot_category in {"AI Crawler" "AI Assistant" "AI Search"}) +Action: Block + +# Allow AI Search, block AI Crawler and AI Assistant +(cf.verified_bot_category in {"AI Crawler" "AI Assistant"}) +Action: Block + +# Or use dashboard: Security > Settings > Bot Management > Block AI Bots +``` + +## Rate Limiting by Bot Score + +```txt +# Stricter limits for suspicious traffic +(cf.bot_management.score lt 50) +Rate: 10 requests per 10 seconds + +(cf.bot_management.score ge 50) +Rate: 100 requests per 10 seconds +``` + +## Mobile App Allowlisting + +```txt +# Identify mobile app by JA3/JA4 +(cf.bot_management.ja4 in {"fingerprint1" "fingerprint2"}) +Action: Skip (all remaining rules) +``` + +## Datacenter Detection + +```typescript +import type { IncomingRequestCfProperties } from '@cloudflare/workers-types'; + +// Low score + not corporate proxy = likely datacenter bot +export default { + async fetch(request: Request): Promise { + const cf = request.cf as IncomingRequestCfProperties | undefined; + const botMgmt = cf?.botManagement; + + if (botMgmt?.score && botMgmt.score < 30 && + !botMgmt.corporateProxy && !botMgmt.verifiedBot) { + return new Response('Datacenter traffic blocked', { status: 403 }); + } + + return fetch(request); + } +}; +``` + +## Conditional Delay (Tarpit) + +```typescript +import type { IncomingRequestCfProperties } from '@cloudflare/workers-types'; + +// Add delay proportional to bot suspicion +export default { + async fetch(request: Request): Promise { + const cf = request.cf as IncomingRequestCfProperties | undefined; + const botMgmt = cf?.botManagement; + + if (botMgmt?.score && botMgmt.score < 50 && !botMgmt.verifiedBot) { + // Delay: 0-2 seconds for scores 50-0 + const delayMs = Math.max(0, (50 - botMgmt.score) * 40); + await new Promise(r => setTimeout(r, delayMs)); + } + + return fetch(request); + } +}; +``` + +## Layered Defense + +```txt +1. Bot Management (score-based) +2. JavaScript Detections (for JS-capable clients) +3. Rate Limiting (fallback protection) +4. WAF Managed Rules (OWASP, etc.) +``` + +## Progressive Enhancement + +```txt +Public content: High threshold (score < 10) +Authenticated: Medium threshold (score < 30) +Sensitive: Low threshold (score < 50) + JSD +``` + +## Zero Trust for Bots + +```txt +1. Default deny (all scores < 30) +2. Allowlist verified bots +3. Allowlist mobile apps (JA3/JA4) +4. Allowlist corporate proxies +5. Allowlist static resources +``` + +## Workers: Score + JS Detection + +```typescript +import type { IncomingRequestCfProperties } from '@cloudflare/workers-types'; + +export default { + async fetch(request: Request): Promise { + const cf = request.cf as IncomingRequestCfProperties | undefined; + const botMgmt = cf?.botManagement; + const url = new URL(request.url); + + if (botMgmt?.staticResource) return fetch(request); // Skip static + + // API endpoints: require JS detection + good score + if (url.pathname.startsWith('/api/')) { + const jsDetectionPassed = botMgmt?.jsDetection?.passed ?? false; + const score = botMgmt?.score ?? 100; + + if (!jsDetectionPassed || score < 30) { + return new Response('Unauthorized', { status: 401 }); + } + } + + return fetch(request); + } +}; +``` + +## Rate Limiting by JWT Claim + Bot Score + +```txt +# Enterprise: Combine bot score with JWT validation +Rate limiting > Custom rules +- Field: lookup_json_string(http.request.jwt.claims["{config_id}"][0], "sub") +- Matches: user ID claim +- Additional condition: cf.bot_management.score lt 50 +``` + +## WAF Integration Points + +- **WAF Custom Rules**: Primary enforcement mechanism +- **Rate Limiting Rules**: Bot score as dimension, stricter limits for low scores +- **Transform Rules**: Pass score to origin via custom header +- **Workers**: Programmatic bot logic, custom scoring algorithms +- **Page Rules / Configuration Rules**: Zone-level overrides, path-specific settings + +## See Also + +- [gotchas.md](./gotchas.md) - Common errors, false positives/negatives, limitations diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eca7220bfa4f74def1c030c895b3964882a4ce23 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/README.md @@ -0,0 +1,78 @@ +# Cloudflare Browser Rendering Skill Reference + +**Description**: Expert knowledge for Cloudflare Browser Rendering - control headless Chrome on Cloudflare's global network for browser automation, screenshots, PDFs, web scraping, testing, and content generation. + +**When to use**: Any task involving Cloudflare Browser Rendering including: taking screenshots, generating PDFs, web scraping, browser automation, testing web applications, extracting structured data, capturing page metrics, or automating browser interactions. + +## Decision Tree + +### REST API vs Workers Bindings + +**Use REST API when:** +- One-off, stateless tasks (screenshot, PDF, content fetch) +- No Workers infrastructure yet +- Simple integrations from external services +- Need quick prototyping without deployment + +**Use Workers Bindings when:** +- Complex browser automation workflows +- Need session reuse for performance +- Multiple page interactions per request +- Custom scripting and logic required +- Building production applications + +### Puppeteer vs Playwright + +| Feature | Puppeteer | Playwright | +|---------|-----------|------------| +| API Style | Chrome DevTools Protocol | High-level abstractions | +| Selectors | CSS, XPath | CSS, text, role, test-id | +| Best for | Advanced control, CDP access | Quick automation, testing | +| Learning curve | Steeper | Gentler | + +**Use Puppeteer:** Need CDP protocol access, Chrome-specific features, migration from existing Puppeteer code +**Use Playwright:** Modern selector APIs, cross-browser patterns, faster development + +## Tier Limits Summary + +| Limit | Free Tier | Paid Tier | +|-------|-----------|-----------| +| Daily browser time | 10 minutes | Unlimited* | +| Concurrent sessions | 3 | 30 | +| Requests per minute | 6 | 180 | + +*Subject to fair-use policy. See [gotchas.md](gotchas.md) for details. + +## Reading Order + +**New to Browser Rendering:** +1. [configuration.md](configuration.md) - Setup and deployment +2. [patterns.md](patterns.md) - Common use cases with examples +3. [api.md](api.md) - API reference +4. [gotchas.md](gotchas.md) - Avoid common pitfalls + +**Specific task:** +- **Setup/deployment** → [configuration.md](configuration.md) +- **API reference/endpoints** → [api.md](api.md) +- **Example code/patterns** → [patterns.md](patterns.md) +- **Debugging/troubleshooting** → [gotchas.md](gotchas.md) + +**REST API users:** +- Start with [api.md](api.md) REST API section +- Check [gotchas.md](gotchas.md) for rate limits + +**Workers users:** +- Start with [configuration.md](configuration.md) +- Review [patterns.md](patterns.md) for session management +- Reference [api.md](api.md) for Workers Bindings + +## In This Reference + +- **[configuration.md](configuration.md)** - Setup, deployment, wrangler config, compatibility +- **[api.md](api.md)** - REST API endpoints + Workers Bindings (Puppeteer/Playwright) +- **[patterns.md](patterns.md)** - Common patterns, use cases, real examples +- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, tier limits, common errors + +## See Also + +- [Cloudflare Docs](https://developers.cloudflare.com/browser-rendering/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/api.md new file mode 100644 index 0000000000000000000000000000000000000000..15284fcde2d2b31644823ac6a5b6403850e45967 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/api.md @@ -0,0 +1,108 @@ +# Browser Rendering API + +## REST API + +**Base:** `https://api.cloudflare.com/client/v4/accounts/{accountId}/browser-rendering` +**Auth:** `Authorization: Bearer ` (Browser Rendering - Edit permission) + +### Endpoints + +| Endpoint | Description | Key Options | +|----------|-------------|-------------| +| `/content` | Get rendered HTML | `url`, `waitUntil` | +| `/screenshot` | Capture image | `screenshotOptions: {type, fullPage, clip}` | +| `/pdf` | Generate PDF | `pdfOptions: {format, landscape, margin}` | +| `/snapshot` | HTML + inlined resources | `url` | +| `/scrape` | Extract by selectors | `selectors: ["h1", ".price"]` | +| `/json` | AI-structured extraction | `schema: {name: "string", price: "number"}` | +| `/links` | Get all links | `url` | +| `/markdown` | Convert to markdown | `url` | + +```bash +curl -X POST '.../browser-rendering/screenshot' \ + -H "Authorization: Bearer $TOKEN" \ + -d '{"url":"https://example.com","screenshotOptions":{"fullPage":true}}' +``` + +## Workers Binding + +```jsonc +// wrangler.jsonc +{ "browser": { "binding": "MYBROWSER" } } +``` + +## Puppeteer + +```typescript +import puppeteer from "@cloudflare/puppeteer"; + +const browser = await puppeteer.launch(env.MYBROWSER, { keep_alive: 600000 }); +const page = await browser.newPage(); +await page.goto('https://example.com', { waitUntil: 'networkidle0' }); + +// Content +const html = await page.content(); +const title = await page.title(); + +// Screenshot/PDF +await page.screenshot({ fullPage: true, type: 'png' }); +await page.pdf({ format: 'A4', printBackground: true }); + +// Interaction +await page.click('#button'); +await page.type('#input', 'text'); +await page.evaluate(() => document.querySelector('h1')?.textContent); + +// Session management +const sessions = await puppeteer.sessions(env.MYBROWSER); +const limits = await puppeteer.limits(env.MYBROWSER); + +await browser.close(); +``` + +## Playwright + +```typescript +import { launch, connect } from "@cloudflare/playwright"; + +const browser = await launch(env.MYBROWSER, { keep_alive: 600000 }); +const page = await browser.newPage(); + +await page.goto('https://example.com', { waitUntil: 'networkidle' }); + +// Modern selectors +await page.locator('.button').click(); +await page.getByText('Submit').click(); +await page.getByTestId('search').fill('query'); + +// Context for isolation +const context = await browser.newContext({ + viewport: { width: 1920, height: 1080 }, + userAgent: 'custom' +}); + +await browser.close(); +``` + +## Session Management + +```typescript +// List sessions +await puppeteer.sessions(env.MYBROWSER); + +// Connect to existing +await puppeteer.connect(env.MYBROWSER, sessionId); + +// Check limits +await puppeteer.limits(env.MYBROWSER); +// { remaining: ms, total: ms, concurrent: n } +``` + +## Key Options + +| Option | Values | +|--------|--------| +| `waitUntil` | `load`, `domcontentloaded`, `networkidle0`, `networkidle2` | +| `keep_alive` | Max 600000ms (10 min) | +| `screenshot.type` | `png`, `jpeg` | +| `pdf.format` | `A4`, `Letter`, `Legal` | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..84bad26b88b35639961f10c15d743274e4390e4b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/configuration.md @@ -0,0 +1,78 @@ +# Configuration & Setup + +## Installation + +```bash +npm install @cloudflare/puppeteer # or @cloudflare/playwright +``` + +**Use Cloudflare packages** - standard `puppeteer`/`playwright` won't work in Workers. + +## wrangler.json + +```json +{ + "name": "browser-worker", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", + "compatibility_flags": ["nodejs_compat"], + "browser": { + "binding": "MYBROWSER" + } +} +``` + +**Required:** `nodejs_compat` flag and `browser.binding`. + +## TypeScript + +```typescript +interface Env { + MYBROWSER: Fetcher; +} + +export default { + async fetch(request: Request, env: Env): Promise { + // ... + } +} satisfies ExportedHandler; +``` + +## Development + +```bash +wrangler dev --remote # --remote required for browser binding +``` + +**Local mode does NOT support Browser Rendering** - must use `--remote`. + +## REST API + +No wrangler config needed. Get API token with "Browser Rendering - Edit" permission. + +```bash +curl -X POST \ + 'https://api.cloudflare.com/client/v4/accounts/{accountId}/browser-rendering/screenshot' \ + -H 'Authorization: Bearer TOKEN' \ + -d '{"url": "https://example.com"}' --output screenshot.png +``` + +## Requirements + +| Requirement | Value | +|-------------|-------| +| Node.js compatibility | `nodejs_compat` flag | +| Compatibility date | 2023-03-01+ | +| Module format | ES modules only | +| Browser | Chromium 119+ (no Firefox/Safari) | + +**Not supported:** WebGL, WebRTC, extensions, `file://` protocol, Service Worker syntax. + +## Troubleshooting + +| Error | Solution | +|-------|----------| +| `MYBROWSER is undefined` | Use `wrangler dev --remote` | +| `nodejs_compat not enabled` | Add to `compatibility_flags` | +| `Module not found` | `npm install @cloudflare/puppeteer` | +| `Browser Rendering not available` | Enable in dashboard | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..7e34f2bd89610d745f58efd207072734887ac835 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/gotchas.md @@ -0,0 +1,88 @@ +# Browser Rendering Gotchas + +## Tier Limits + +| Limit | Free | Paid | +|-------|------|------| +| Daily browser time | 10 min | Unlimited* | +| Concurrent sessions | 3 | 30 | +| Requests/minute | 6 | 180 | +| Session keep-alive | 10 min max | 10 min max | + +*Subject to fair-use policy. + +**Check quota:** +```typescript +const limits = await puppeteer.limits(env.MYBROWSER); +// { remaining: 540000, total: 600000, concurrent: 2 } +``` + +## Always Close Browsers + +```typescript +const browser = await puppeteer.launch(env.MYBROWSER); +try { + const page = await browser.newPage(); + await page.goto("https://example.com"); + return new Response(await page.content()); +} finally { + await browser.close(); // ALWAYS in finally +} +``` + +**Workers vs REST:** REST auto-closes after timeout. Workers must call `close()` or session stays open until `keep_alive` expires. + +## Optimize Concurrency + +```typescript +// ❌ 3 sessions (hits free tier limit) +const browser1 = await puppeteer.launch(env.MYBROWSER); +const browser2 = await puppeteer.launch(env.MYBROWSER); + +// ✅ 1 session, multiple pages +const browser = await puppeteer.launch(env.MYBROWSER); +const page1 = await browser.newPage(); +const page2 = await browser.newPage(); +``` + +## Common Errors + +| Error | Cause | Fix | +|-------|-------|-----| +| Session limit exceeded | Too many concurrent | Close unused browsers, use pages not browsers | +| Page navigation timeout | Slow page or `networkidle` on busy page | Increase timeout, use `waitUntil: "load"` | +| Session not found | Expired session | Catch error, launch new session | +| Evaluation failed | DOM element missing | Use `?.` optional chaining | +| Protocol error: Target closed | Page closed during operation | Await all ops before closing | + +## page.evaluate() Gotchas + +```typescript +// ❌ Outer scope not available +const selector = "h1"; +await page.evaluate(() => document.querySelector(selector)); + +// ✅ Pass as argument +await page.evaluate((sel) => document.querySelector(sel)?.textContent, selector); +``` + +## Performance + +**waitUntil options (fastest to slowest):** +1. `domcontentloaded` - DOM ready +2. `load` - load event (default) +3. `networkidle0` - no network for 500ms + +**Block unnecessary resources:** +```typescript +await page.setRequestInterception(true); +page.on("request", (req) => { + if (["image", "stylesheet", "font"].includes(req.resourceType())) { + req.abort(); + } else { + req.continue(); + } +}); +``` + +**Session reuse:** Cold start ~1-2s, warm connect ~100-200ms. Store sessionId in KV for reuse. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..a652c2b58ab87261904ede1cc8799f24eb34ee4c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/browser-rendering/patterns.md @@ -0,0 +1,91 @@ +# Browser Rendering Patterns + +## Basic Worker + +```typescript +import puppeteer from "@cloudflare/puppeteer"; + +export default { + async fetch(request, env) { + const browser = await puppeteer.launch(env.MYBROWSER); + try { + const page = await browser.newPage(); + await page.goto("https://example.com"); + return new Response(await page.content()); + } finally { + await browser.close(); // ALWAYS in finally + } + } +}; +``` + +## Session Reuse + +Keep sessions alive for performance: +```typescript +let sessionId = await env.SESSION_KV.get("browser-session"); +if (sessionId) { + browser = await puppeteer.connect(env.MYBROWSER, sessionId); +} else { + browser = await puppeteer.launch(env.MYBROWSER, { keep_alive: 600000 }); + await env.SESSION_KV.put("browser-session", browser.sessionId(), { expirationTtl: 600 }); +} +// Don't close browser to keep session alive +``` + +## Common Operations + +| Task | Code | +|------|------| +| Screenshot | `await page.screenshot({ type: "png", fullPage: true })` | +| PDF | `await page.pdf({ format: "A4", printBackground: true })` | +| Extract data | `await page.evaluate(() => document.querySelector('h1').textContent)` | +| Fill form | `await page.type('#input', 'value'); await page.click('button')` | +| Wait nav | `await Promise.all([page.waitForNavigation(), page.click('a')])` | + +## Parallel Scraping + +```typescript +const pages = await Promise.all(urls.map(() => browser.newPage())); +await Promise.all(pages.map((p, i) => p.goto(urls[i]))); +const titles = await Promise.all(pages.map(p => p.title())); +``` + +## Playwright Selectors + +```typescript +import { launch } from "@cloudflare/playwright"; +const browser = await launch(env.MYBROWSER); +await page.getByRole("button", { name: "Sign in" }).click(); +await page.getByLabel("Email").fill("user@example.com"); +await page.getByTestId("submit-button").click(); +``` + +## Incognito Contexts + +Isolated sessions without multiple browsers: +```typescript +const ctx1 = await browser.createIncognitoBrowserContext(); +const ctx2 = await browser.createIncognitoBrowserContext(); +// Each has isolated cookies/storage +``` + +## Quota Check + +```typescript +const limits = await puppeteer.limits(env.MYBROWSER); +if (limits.remaining < 60000) return new Response("Quota low", { status: 429 }); +``` + +## Error Handling + +```typescript +try { + await page.goto(url, { timeout: 30000, waitUntil: "networkidle0" }); +} catch (e) { + if (e.message.includes("timeout")) return new Response("Timeout", { status: 504 }); + if (e.message.includes("Session limit")) return new Response("Too many sessions", { status: 429 }); +} finally { + if (browser) await browser.close(); +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0516fc6e5854386c47f6e0b2a34268c60837cc0b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/README.md @@ -0,0 +1,111 @@ +# C3 (create-cloudflare) + +Official CLI for scaffolding Cloudflare Workers and Pages projects with templates, TypeScript, and instant deployment. + +## Quick Start + +```bash +# Interactive (recommended for first-time) +npm create cloudflare@latest my-app + +# Worker (API/WebSocket/Cron) +npm create cloudflare@latest my-api -- --type=hello-world --ts + +# Pages (static/SSG/full-stack) +npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pages +``` + +## Platform Decision Tree + +``` +What are you building? + +├─ API / WebSocket / Cron / Email handler +│ └─ Workers (default) - no --platform flag needed +│ npm create cloudflare@latest my-api -- --type=hello-world + +├─ Static site / SSG / Documentation +│ └─ Pages - requires --platform=pages +│ npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pages + +├─ Full-stack app (Next.js/Remix/SvelteKit) +│ ├─ Need Durable Objects, Queues, or Workers-only features? +│ │ └─ Workers (default) +│ └─ Otherwise use Pages for git integration and branch previews +│ └─ Add --platform=pages + +└─ Convert existing project + └─ npm create cloudflare@latest . -- --type=pre-existing --existing-script=./src/worker.ts +``` + +**Critical:** Pages projects require `--platform=pages` flag. Without it, C3 defaults to Workers. + +## Interactive Flow + +When run without flags, C3 prompts in this order: + +1. **Project name** - Directory to create (defaults to current dir with `.`) +2. **Application type** - `hello-world`, `web-app`, `demo`, `pre-existing`, `remote-template` +3. **Platform** - `workers` (default) or `pages` (for web apps only) +4. **Framework** - If web-app: `next`, `remix`, `astro`, `react-router`, `solid`, `svelte`, etc. +5. **TypeScript** - `yes` (recommended) or `no` +6. **Git** - Initialize repository? `yes` or `no` +7. **Deploy** - Deploy now? `yes` or `no` (requires `wrangler login`) + +## Installation Methods + +```bash +# NPM +npm create cloudflare@latest + +# Yarn +yarn create cloudflare + +# PNPM +pnpm create cloudflare@latest +``` + +## In This Reference + +| File | Purpose | Use When | +|------|---------|----------| +| **api.md** | Complete CLI flag reference | Scripting, CI/CD, advanced usage | +| **configuration.md** | Generated files, bindings, types | Understanding output, customization | +| **patterns.md** | Workflows, CI/CD, monorepos | Real-world integration | +| **gotchas.md** | Troubleshooting failures | Deployment blocked, errors | + +## Reading Order + +| Task | Read | +|------|------| +| Create first project | README only | +| Set up CI/CD | README → api → patterns | +| Debug failed deploy | gotchas | +| Understand generated files | configuration | +| Full CLI reference | api | +| Create custom template | patterns → configuration | +| Convert existing project | README → patterns | + +## Post-Creation + +```bash +cd my-app + +# Local dev with hot reload +npm run dev + +# Generate TypeScript types for bindings +npm run cf-typegen + +# Deploy to Cloudflare +npm run deploy +``` + +## See Also + +- **workers/README.md** - Workers runtime, bindings, APIs +- **workers-ai/README.md** - AI/ML models +- **pages/README.md** - Pages-specific features +- **wrangler/README.md** - Wrangler CLI beyond initial setup +- **d1/README.md** - SQLite database +- **r2/README.md** - Object storage diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/api.md new file mode 100644 index 0000000000000000000000000000000000000000..29c2b0c5eb7a1d9aa8e3419632918f8020dcd32f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/api.md @@ -0,0 +1,71 @@ +# C3 CLI Reference + +## Invocation + +```bash +npm create cloudflare@latest [name] [-- flags] # NPM requires -- +yarn create cloudflare [name] [flags] +pnpm create cloudflare@latest [name] [-- flags] +``` + +## Core Flags + +| Flag | Values | Description | +|------|--------|-------------| +| `--type` | `hello-world`, `web-app`, `demo`, `pre-existing`, `remote-template` | Application type | +| `--platform` | `workers` (default), `pages` | Target platform | +| `--framework` | `next`, `remix`, `astro`, `react-router`, `solid`, `svelte`, `qwik`, `vue`, `angular`, `hono` | Web framework (requires `--type=web-app`) | +| `--lang` | `ts`, `js`, `python` | Language (for `--type=hello-world`) | +| `--ts` / `--no-ts` | - | TypeScript for web apps | + +## Deployment Flags + +| Flag | Description | +|------|-------------| +| `--deploy` / `--no-deploy` | Deploy immediately (prompts interactive, skips in CI) | +| `--git` / `--no-git` | Initialize git (default: yes) | +| `--open` | Open browser after deploy | + +## Advanced Flags + +| Flag | Description | +|------|-------------| +| `--template=user/repo` | GitHub template or local path | +| `--existing-script=./src/worker.ts` | Existing script (requires `--type=pre-existing`) | +| `--category=ai\|database\|realtime` | Demo filter (requires `--type=demo`) | +| `--experimental` | Enable experimental features | +| `--wrangler-defaults` | Skip wrangler prompts | + +## Environment Variables + +```bash +CLOUDFLARE_API_TOKEN=xxx # For deployment +CLOUDFLARE_ACCOUNT_ID=xxx # Account ID +CF_TELEMETRY_DISABLED=1 # Disable telemetry +``` + +## Exit Codes + +`0` success, `1` user abort, `2` error + +## Examples + +```bash +# TypeScript Worker +npm create cloudflare@latest my-api -- --type=hello-world --lang=ts --no-deploy + +# Next.js on Pages +npm create cloudflare@latest my-app -- --type=web-app --framework=next --platform=pages --ts + +# Astro blog +npm create cloudflare@latest my-blog -- --type=web-app --framework=astro --ts --deploy + +# CI: non-interactive +npm create cloudflare@latest my-app -- --type=web-app --framework=next --ts --no-git --no-deploy + +# GitHub template +npm create cloudflare@latest -- --template=cloudflare/templates/worker-openapi + +# Convert existing project +npm create cloudflare@latest . -- --type=pre-existing --existing-script=./build/worker.js +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..37f9f828240898e23aa2f6ca8b28ef0383a28c96 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/configuration.md @@ -0,0 +1,81 @@ +# C3 Generated Configuration + +## Output Structure + +``` +my-app/ +├── src/index.ts # Worker entry point +├── wrangler.jsonc # Cloudflare config +├── package.json # Scripts +├── tsconfig.json +└── .gitignore +``` + +## wrangler.jsonc + +```jsonc +{ + "$schema": "https://raw.githubusercontent.com/cloudflare/workers-sdk/main/packages/wrangler/config-schema.json", + "name": "my-app", + "main": "src/index.ts", + "compatibility_date": "2026-01-27" +} +``` + +## Binding Placeholders + +C3 generates **placeholder IDs** that must be replaced before deploy: + +```jsonc +{ + "kv_namespaces": [{ "binding": "MY_KV", "id": "placeholder_kv_id" }], + "d1_databases": [{ "binding": "DB", "database_id": "00000000-..." }] +} +``` + +**Replace with real IDs:** +```bash +npx wrangler kv namespace create MY_KV # Returns real ID +npx wrangler d1 create my-database # Returns real database_id +``` + +**Deployment error if not replaced:** +``` +Error: Invalid KV namespace ID "placeholder_kv_id" +``` + +## Scripts + +```json +{ + "scripts": { + "dev": "wrangler dev", + "deploy": "wrangler deploy", + "cf-typegen": "wrangler types" + } +} +``` + +## Type Generation + +Run after adding bindings: +```bash +npm run cf-typegen +``` + +Generates `.wrangler/types/runtime.d.ts`: +```typescript +interface Env { + MY_KV: KVNamespace; + DB: D1Database; +} +``` + +## Post-Creation Checklist + +1. Review `wrangler.jsonc` - check name, compatibility_date +2. Replace placeholder binding IDs with real resource IDs +3. Run `npm run cf-typegen` +4. Test: `npm run dev` +5. Deploy: `npm run deploy` +6. Add secrets: `npx wrangler secret put SECRET_NAME` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..3c0cd5db13928732b115418ad00c7370c6c66c40 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/gotchas.md @@ -0,0 +1,92 @@ +# C3 Troubleshooting + +## Deployment Issues + +### Placeholder IDs + +**Error:** "Invalid namespace ID" +**Fix:** Replace placeholders in wrangler.jsonc with real IDs: +```bash +npx wrangler kv namespace create MY_KV # Get real ID +``` + +### Authentication + +**Error:** "Not authenticated" +**Fix:** `npx wrangler login` or set `CLOUDFLARE_API_TOKEN` + +### Name Conflict + +**Error:** "Worker already exists" +**Fix:** Change `name` in wrangler.jsonc + +## Platform Selection + +| Need | Platform | +|------|----------| +| Git integration, branch previews | `--platform=pages` | +| Durable Objects, D1, Queues | Workers (default) | + +Wrong platform? Recreate with correct `--platform` flag. + +## TypeScript Issues + +**"Cannot find name 'KVNamespace'"** +```bash +npm run cf-typegen # Regenerate types +# Restart TS server in editor +``` + +**Missing types after config change:** Re-run `npm run cf-typegen` + +## Package Manager + +**Multiple lockfiles causing issues:** +```bash +rm pnpm-lock.yaml # If using npm +rm package-lock.json # If using pnpm +``` + +## CI/CD + +**CI hangs on prompts:** +```bash +npm create cloudflare@latest my-app -- \ + --type=hello-world --lang=ts --no-git --no-deploy +``` + +**Auth in CI:** +```yaml +env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} +``` + +## Framework-Specific + +| Framework | Issue | Fix | +|-----------|-------|-----| +| Next.js | create-next-app failed | `npm cache clean --force`, retry | +| Astro | Adapter missing | Install `@astrojs/cloudflare` | +| Remix | Module errors | Update `@remix-run/cloudflare*` | + +## Compatibility Date + +**"Feature X requires compatibility_date >= ..."** +**Fix:** Update `compatibility_date` in wrangler.jsonc to today's date + +## Node.js Version + +**"Node.js version not supported"** +**Fix:** Install Node.js 18+ (`nvm install 20`) + +## Quick Reference + +| Error | Cause | Fix | +|-------|-------|-----| +| Invalid namespace ID | Placeholder binding | Create resource, update config | +| Not authenticated | No login | `npx wrangler login` | +| Cannot find KVNamespace | Missing types | `npm run cf-typegen` | +| Worker already exists | Name conflict | Change `name` | +| CI hangs | Missing flags | Add --type, --lang, --no-deploy | +| Template not found | Bad name | Check cloudflare/templates | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..78b61c24dea0d03ba0982fe96346b6bc9584b4e5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/c3/patterns.md @@ -0,0 +1,82 @@ +# C3 Usage Patterns + +## Quick Workflows + +```bash +# TypeScript API Worker +npm create cloudflare@latest my-api -- --type=hello-world --lang=ts --deploy + +# Next.js on Pages +npm create cloudflare@latest my-app -- --type=web-app --framework=next --platform=pages --ts --deploy + +# Astro static site +npm create cloudflare@latest my-blog -- --type=web-app --framework=astro --platform=pages --ts +``` + +## CI/CD (GitHub Actions) + +```yaml +- name: Deploy + run: npm run deploy + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} +``` + +**Non-interactive requires:** +```bash +--type= # Required +--no-git # Recommended (CI already in git) +--no-deploy # Deploy separately with secrets +--framework= # For web-app +--ts / --no-ts # Required +``` + +## Monorepo + +C3 detects workspace config (`package.json` workspaces or `pnpm-workspace.yaml`). + +```bash +cd packages/ +npm create cloudflare@latest my-worker -- --type=hello-world --lang=ts --no-deploy +``` + +## Custom Templates + +```bash +# GitHub repo +npm create cloudflare@latest -- --template=username/repo +npm create cloudflare@latest -- --template=cloudflare/templates/worker-openapi + +# Local path +npm create cloudflare@latest my-app -- --template=../my-template +``` + +**Template requires `c3.config.json`:** +```json +{ + "name": "my-template", + "category": "hello-world", + "copies": [{ "path": "src/" }, { "path": "wrangler.jsonc" }], + "transforms": [{ "path": "package.json", "jsonc": { "name": "{{projectName}}" }}] +} +``` + +## Existing Projects + +```bash +# Add Cloudflare to existing Worker +npm create cloudflare@latest . -- --type=pre-existing --existing-script=./dist/index.js + +# Add to existing framework app +npm create cloudflare@latest . -- --type=web-app --framework=next --platform=pages --ts +``` + +## Post-Creation Checklist + +1. Review `wrangler.jsonc` - set `compatibility_date`, verify `name` +2. Create bindings: `wrangler kv namespace create`, `wrangler d1 create`, `wrangler r2 bucket create` +3. Generate types: `npm run cf-typegen` +4. Test: `npm run dev` +5. Deploy: `npm run deploy` +6. Set secrets: `wrangler secret put SECRET_NAME` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/README.md new file mode 100644 index 0000000000000000000000000000000000000000..395347a21dcae34c29d2a25452b0480c2391f58a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/README.md @@ -0,0 +1,147 @@ +# Cloudflare Cache Reserve + +**Persistent cache storage built on R2 for long-term content retention** + +## Smart Shield Integration + +Cache Reserve is part of **Smart Shield**, Cloudflare's comprehensive security and performance suite: + +- **Smart Shield Advanced tier**: Includes 2TB Cache Reserve storage +- **Standalone purchase**: Available separately if not using Smart Shield +- **Migration**: Existing standalone customers can migrate to Smart Shield bundles + +**Decision**: Already on Smart Shield Advanced? Cache Reserve is included. Otherwise evaluate standalone purchase vs Smart Shield upgrade. + +## Overview + +Cache Reserve is Cloudflare's persistent, large-scale cache storage layer built on R2. It acts as the ultimate upper-tier cache, storing cacheable content for extended periods (30+ days) to maximize cache hits, reduce origin egress fees, and shield origins from repeated requests for long-tail content. + +## Core Concepts + +### What is Cache Reserve? + +- **Persistent storage layer**: Built on R2, sits above tiered cache hierarchy +- **Long-term retention**: 30-day default retention, extended on each access +- **Automatic operation**: Works seamlessly with existing CDN, no code changes required +- **Origin shielding**: Dramatically reduces origin egress by serving cached content longer +- **Usage-based pricing**: Pay only for storage + read/write operations + +### Cache Hierarchy + +``` +Visitor Request + ↓ +Lower-Tier Cache (closest to visitor) + ↓ (on miss) +Upper-Tier Cache (closest to origin) + ↓ (on miss) +Cache Reserve (R2 persistent storage) + ↓ (on miss) +Origin Server +``` + +### How It Works + +1. **On cache miss**: Content fetched from origin �� written to Cache Reserve + edge caches simultaneously +2. **On edge eviction**: Content may be evicted from edge cache but remains in Cache Reserve +3. **On subsequent request**: If edge cache misses but Cache Reserve hits → content restored to edge caches +4. **Retention**: Assets remain in Cache Reserve for 30 days since last access (configurable via TTL) + +## When to Use Cache Reserve + +``` +Need persistent caching? +├─ High origin egress costs → Cache Reserve ✓ +├─ Long-tail content (archives, media libraries) → Cache Reserve ✓ +├─ Already using Smart Shield Advanced → Included! ✓ +├─ Video streaming with seeking (range requests) → ✗ Not supported +├─ Dynamic/personalized content → ✗ Use edge cache only +├─ Need per-request cache control from Workers → ✗ Use R2 directly +└─ Frequently updated content (< 10hr lifetime) → ✗ Not eligible +``` + +## Asset Eligibility + +Cache Reserve only stores assets meeting **ALL** criteria: + +- Cacheable per Cloudflare's standard rules +- Minimum 10-hour TTL (36000 seconds) +- `Content-Length` header present +- Original files only (not transformed images) + +### Eligibility Checklist + +Use this checklist to verify if an asset is eligible: + +- [ ] Zone has Cache Reserve enabled +- [ ] Zone has Tiered Cache enabled (required) +- [ ] Asset TTL ≥ 10 hours (36,000 seconds) +- [ ] `Content-Length` header present on origin response +- [ ] No `Set-Cookie` header (or uses private directive) +- [ ] `Vary` header is NOT `*` (can be `Accept-Encoding`) +- [ ] Not an image transformation variant (original images OK) +- [ ] Not a range request (no HTTP 206 support) +- [ ] Not O2O (Orange-to-Orange) proxied request + +**All boxes must be checked for Cache Reserve eligibility.** + +### Not Eligible + +- Assets with TTL < 10 hours +- Responses without `Content-Length` header +- Image transformation variants (original images are eligible) +- Responses with `Set-Cookie` headers +- Responses with `Vary: *` header +- Assets from R2 public buckets on same zone +- O2O (Orange-to-Orange) setup requests +- **Range requests** (video seeking, partial content downloads) + +## Quick Start + +```bash +# Enable via Dashboard +https://dash.cloudflare.com/caching/cache-reserve +# Click "Enable Storage Sync" or "Purchase" button +``` + +**Prerequisites:** +- Paid Cache Reserve plan or Smart Shield Advanced required +- Tiered Cache required for optimal performance + +## Essential Commands + +```bash +# Check Cache Reserve status +curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/cache_reserve" \ + -H "Authorization: Bearer $API_TOKEN" + +# Enable Cache Reserve +curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/cache_reserve" \ + -H "Authorization: Bearer $API_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"value": "on"}' + +# Check asset cache status +curl -I https://example.com/asset.jpg | grep -i cache +``` + +## In This Reference + +| Task | Files | +|------|-------| +| Evaluate if Cache Reserve fits your use case | README.md (this file) | +| Enable Cache Reserve for your zone | README.md + [configuration.md](./configuration.md) | +| Use with Workers (understand limitations) | [api.md](./api.md) | +| Setup via SDKs or IaC (TypeScript, Python, Terraform) | [configuration.md](./configuration.md) | +| Optimize costs and debug issues | [patterns.md](./patterns.md) + [gotchas.md](./gotchas.md) | +| Understand eligibility and troubleshoot | [gotchas.md](./gotchas.md) → [patterns.md](./patterns.md) | + +**Files:** +- [configuration.md](./configuration.md) - Setup, API, SDKs, and Cache Rules +- [api.md](./api.md) - Purging, monitoring, Workers integration +- [patterns.md](./patterns.md) - Best practices, cost optimization, debugging +- [gotchas.md](./gotchas.md) - Common issues, limitations, troubleshooting + +## See Also +- [r2](../r2/) - Cache Reserve built on R2 storage +- [workers](../workers/) - Workers integration with Cache API diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/api.md new file mode 100644 index 0000000000000000000000000000000000000000..f34c120d06e5f58f8ef3334b4826ad9998ce20a5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/api.md @@ -0,0 +1,194 @@ +# Cache Reserve API + +## Workers Integration + +``` +┌────────────────────────────────────────────────────────────────┐ +│ CRITICAL: Workers Cache API ≠ Cache Reserve │ +│ │ +│ • Workers caches.default / cache.put() → edge cache ONLY │ +│ • Cache Reserve → zone-level setting, automatic, no per-req │ +│ • You CANNOT selectively write to Cache Reserve from Workers │ +│ • Cache Reserve works with standard fetch(), not cache.put() │ +└────────────────────────────────────────────────────────────────┘ +``` + +Cache Reserve is a **zone-level configuration**, not a per-request API. It works automatically when enabled for the zone: + +### Standard Fetch (Recommended) + +```typescript +// Cache Reserve works automatically via standard fetch +export default { + async fetch(request: Request, env: Env): Promise { + // Standard fetch uses Cache Reserve automatically + return await fetch(request); + } +}; +``` + +### Cache API Limitations + +**IMPORTANT**: `cache.put()` is **NOT compatible** with Cache Reserve or Tiered Cache. + +```typescript +// ❌ WRONG: cache.put() bypasses Cache Reserve +const cache = caches.default; +let response = await cache.match(request); +if (!response) { + response = await fetch(request); + await cache.put(request, response.clone()); // Bypasses Cache Reserve! +} + +// ✅ CORRECT: Use standard fetch for Cache Reserve compatibility +return await fetch(request); + +// ✅ CORRECT: Use Cache API only for custom cache namespaces +const customCache = await caches.open('my-custom-cache'); +let response = await customCache.match(request); +if (!response) { + response = await fetch(request); + await customCache.put(request, response.clone()); // Custom cache OK +} +``` + +## Purging and Cache Management + +### Purge by URL (Instant) + +```typescript +// Purge specific URL from Cache Reserve immediately +const purgeCacheReserveByURL = async ( + zoneId: string, + apiToken: string, + urls: string[] +) => { + const response = await fetch( + `https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`, + { + method: 'POST', + headers: { + 'Authorization': `Bearer ${apiToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ files: urls }) + } + ); + return await response.json(); +}; + +// Example usage +await purgeCacheReserveByURL('zone123', 'token456', [ + 'https://example.com/image.jpg', + 'https://example.com/video.mp4' +]); +``` + +### Purge by Tag/Host/Prefix (Revalidation) + +```typescript +// Purge by cache tag - forces revalidation, not immediate removal +await fetch( + `https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`, + { + method: 'POST', + headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ tags: ['tag1', 'tag2'] }) + } +); +``` + +**Purge behavior:** +- **By URL**: Immediate removal from Cache Reserve + edge cache +- **By tag/host/prefix**: Revalidation only, assets remain in storage (costs continue) + +### Clear All Cache Reserve Data + +```typescript +// Requires Cache Reserve OFF first +await fetch( + `https://api.cloudflare.com/client/v4/zones/${zoneId}/cache/cache_reserve_clear`, + { method: 'POST', headers: { 'Authorization': `Bearer ${apiToken}` } } +); + +// Check status: GET same endpoint returns { state: "In-progress" | "Completed" } +``` + +**Process**: Disable Cache Reserve → Call clear endpoint → Wait up to 24hr → Re-enable + +## Monitoring and Analytics + +### Dashboard Analytics + +Navigate to **Caching > Cache Reserve** to view: + +- **Egress Savings**: Total bytes served from Cache Reserve vs origin egress cost saved +- **Requests Served**: Cache Reserve hits vs misses breakdown +- **Storage Used**: Current GB stored in Cache Reserve (billed monthly) +- **Operations**: Class A (writes) and Class B (reads) operation counts +- **Cost Tracking**: Estimated monthly costs based on current usage + +### Logpush Integration + +```typescript +// Logpush field: CacheReserveUsed (boolean) - filter for Cache Reserve hits +// Query Cache Reserve hits in analytics +const logpushQuery = ` + SELECT + ClientRequestHost, + COUNT(*) as requests, + SUM(EdgeResponseBytes) as bytes_served, + COUNT(CASE WHEN CacheReserveUsed = true THEN 1 END) as cache_reserve_hits, + COUNT(CASE WHEN CacheReserveUsed = false THEN 1 END) as cache_reserve_misses + FROM http_requests + WHERE Timestamp >= NOW() - INTERVAL '24 hours' + GROUP BY ClientRequestHost + ORDER BY requests DESC +`; + +// Filter only Cache Reserve hits +const crHitsQuery = ` + SELECT ClientRequestHost, COUNT(*) as requests, SUM(EdgeResponseBytes) as bytes + FROM http_requests + WHERE CacheReserveUsed = true AND Timestamp >= NOW() - INTERVAL '7 days' + GROUP BY ClientRequestHost + ORDER BY bytes DESC +`; +``` + +### GraphQL Analytics + +```graphql +query CacheReserveAnalytics($zoneTag: string, $since: string, $until: string) { + viewer { + zones(filter: { zoneTag: $zoneTag }) { + httpRequests1dGroups( + filter: { datetime_geq: $since, datetime_leq: $until } + limit: 1000 + ) { + dimensions { date } + sum { + cachedBytes + cachedRequests + bytes + requests + } + } + } + } +} +``` + +## Pricing + +```typescript +// Storage: $0.015/GB-month | Class A (writes): $4.50/M | Class B (reads): $0.36/M +// Cache miss: 1A + 1B | Cache hit: 1B | Assets >1GB: proportionally more ops +``` + +## See Also + +- [README](./README.md) - Overview and core concepts +- [Configuration](./configuration.md) - Setup and Cache Rules +- [Patterns](./patterns.md) - Best practices and optimization +- [Gotchas](./gotchas.md) - Common issues and troubleshooting diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..84a66161dd8f4f425ec3aeaca9ee501a8ede03d3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/configuration.md @@ -0,0 +1,169 @@ +# Cache Reserve Configuration + +## Dashboard Setup + +**Minimum steps to enable:** + +```bash +# Navigate to dashboard +https://dash.cloudflare.com/caching/cache-reserve + +# Click "Enable Storage Sync" or "Purchase" button +``` + +**Prerequisites:** +- Paid Cache Reserve plan or Smart Shield Advanced required +- Tiered Cache **required** for Cache Reserve to function optimally + +## API Configuration + +### REST API + +```bash +# Enable +curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/cache_reserve" \ + -H "Authorization: Bearer $API_TOKEN" -H "Content-Type: application/json" \ + -d '{"value": "on"}' + +# Check status +curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/cache_reserve" \ + -H "Authorization: Bearer $API_TOKEN" +``` + +### TypeScript SDK + +```bash +npm install cloudflare +``` + +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ + apiToken: process.env.CLOUDFLARE_API_TOKEN, +}); + +// Enable Cache Reserve +await client.cache.cacheReserve.edit({ + zone_id: 'abc123', + value: 'on', +}); + +// Get Cache Reserve status +const status = await client.cache.cacheReserve.get({ + zone_id: 'abc123', +}); +console.log(status.value); // 'on' or 'off' +``` + +### Python SDK + +```bash +pip install cloudflare +``` + +```python +from cloudflare import Cloudflare + +client = Cloudflare(api_token=os.environ.get("CLOUDFLARE_API_TOKEN")) + +# Enable Cache Reserve +client.cache.cache_reserve.edit( + zone_id="abc123", + value="on" +) + +# Get Cache Reserve status +status = client.cache.cache_reserve.get(zone_id="abc123") +print(status.value) # 'on' or 'off' +``` + +### Terraform + +```hcl +terraform { + required_providers { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.0" + } + } +} + +provider "cloudflare" { + api_token = var.cloudflare_api_token +} + +resource "cloudflare_zone_cache_reserve" "example" { + zone_id = var.zone_id + enabled = true +} + +# Tiered Cache is required for Cache Reserve +resource "cloudflare_tiered_cache" "example" { + zone_id = var.zone_id + cache_type = "smart" +} +``` + +### Pulumi + +```typescript +import * as cloudflare from "@pulumi/cloudflare"; + +// Enable Cache Reserve +const cacheReserve = new cloudflare.ZoneCacheReserve("example", { + zoneId: zoneId, + enabled: true, +}); + +// Enable Tiered Cache (required) +const tieredCache = new cloudflare.TieredCache("example", { + zoneId: zoneId, + cacheType: "smart", +}); +``` + +### Required API Token Permissions + +- `Zone Settings Read` +- `Zone Settings Write` +- `Zone Read` +- `Zone Write` + +## Cache Rules Integration + +Control Cache Reserve eligibility via Cache Rules: + +```typescript +// Enable for static assets +{ + action: 'set_cache_settings', + action_parameters: { + cache_reserve: { eligible: true, minimum_file_ttl: 86400 }, + edge_ttl: { mode: 'override_origin', default: 86400 }, + cache: true + }, + expression: '(http.request.uri.path matches "\\.(jpg|png|webp|pdf|zip)$")' +} + +// Disable for APIs +{ + action: 'set_cache_settings', + action_parameters: { cache_reserve: { eligible: false } }, + expression: '(http.request.uri.path matches "^/api/")' +} + +// Create via API: PUT to zones/{zone_id}/rulesets/phases/http_request_cache_settings/entrypoint +``` + +## Wrangler Integration + +Cache Reserve works automatically with Workers deployed via Wrangler. No special wrangler.jsonc configuration needed - enable Cache Reserve via Dashboard or API for the zone. + +## See Also + +- [README](./README.md) - Overview and core concepts +- [API Reference](./api.md) - Purging and monitoring APIs +- [Patterns](./patterns.md) - Best practices and optimization +- [Gotchas](./gotchas.md) - Common issues and troubleshooting diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..107753ae89a4426a847a97e6670f98c46452aa16 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/gotchas.md @@ -0,0 +1,132 @@ +# Cache Reserve Gotchas + +## Common Errors + +### "Assets Not Being Cached in Cache Reserve" + +**Cause:** Asset is not cacheable, TTL < 10 hours, Content-Length header missing, or blocking headers present (Set-Cookie, Vary: *) +**Solution:** Ensure minimum TTL of 10+ hours (`Cache-Control: public, max-age=36000`), add Content-Length header, remove Set-Cookie header, and set `Vary: Accept-Encoding` (not *) + +### "Range Requests Not Working" (Video Seeking Fails) + +**Cause:** Cache Reserve does **NOT** support range requests (HTTP 206 Partial Content) +**Solution:** Range requests bypass Cache Reserve entirely. For video streaming with seeking: +- Use edge cache only (shorter TTLs) +- Consider R2 with direct access for range-heavy workloads +- Accept that seekable content won't benefit from Cache Reserve persistence + +### "Origin Bandwidth Higher Than Expected" + +**Cause:** Cache Reserve fetches **uncompressed** content from origin, even though it serves compressed to visitors +**Solution:** +- If origin charges by bandwidth, factor in uncompressed transfer costs +- Cache Reserve compresses for visitors automatically (saves visitor bandwidth) +- Compare: origin egress savings vs higher uncompressed fetch costs + +### "Cloudflare Images Not Caching with Cache Reserve" + +**Cause:** Cloudflare Images with `Vary: Accept` header (format negotiation) is incompatible with Cache Reserve +**Solution:** +- Cache Reserve silently skips images with Vary for format negotiation +- Original images (non-transformed) may still be eligible +- Use Cloudflare Images variants or edge cache for transformed images + +### "High Class A Operations Costs" + +**Cause:** Frequent cache misses, short TTLs, or frequent revalidation +**Solution:** Increase TTL for stable content (24+ hours), enable Tiered Cache to reduce direct Cache Reserve misses, or use stale-while-revalidate + +### "Purge Not Working as Expected" + +**Cause:** Purge by tag only triggers revalidation but doesn't remove from Cache Reserve storage +**Solution:** Use purge by URL for immediate removal, or disable Cache Reserve then clear all data for complete removal + +### "O2O (Orange-to-Orange) Assets Not Caching" + +**Cause:** Orange-to-Orange (proxied zone requesting another proxied zone on Cloudflare) bypasses Cache Reserve +**Solution:** +- **What is O2O**: Zone A (proxied) → Zone B (proxied), both on Cloudflare +- **Detection**: Check `cf-cache-status` for `BYPASS` and review request path +- **Workaround**: Use R2 or direct origin access instead of O2O proxy chains + +### "Cache Reserve must be OFF before clearing data" + +**Cause:** Attempting to clear Cache Reserve data while it's still enabled +**Solution:** Disable Cache Reserve first, wait briefly for propagation (5s), then clear data (can take up to 24 hours) + +## Limits + +| Limit | Value | Notes | +|-------|-------|-------| +| Minimum TTL | 10 hours (36000 seconds) | Assets with shorter TTL not eligible | +| Default retention | 30 days (2592000 seconds) | Configurable | +| Maximum file size | Same as R2 limits | No practical limit | +| Purge/clear time | Up to 24 hours | Complete propagation time | +| Plan requirement | Paid Cache Reserve or Smart Shield | Not available on free plans | +| Content-Length header | Required | Must be present for eligibility | +| Set-Cookie header | Blocks caching | Must not be present (or use private directive) | +| Vary header | Cannot be * | Can use Vary: Accept-Encoding | +| Image transformations | Variants not eligible | Original images only | +| Range requests | NOT supported | HTTP 206 bypasses Cache Reserve | +| Compression | Fetches uncompressed | Serves compressed to visitors | +| Worker control | Zone-level only | Cannot control per-request | +| O2O requests | Bypassed | Orange-to-Orange not eligible | + +## Additional Resources + +- **Official Docs**: https://developers.cloudflare.com/cache/advanced-configuration/cache-reserve/ +- **API Reference**: https://developers.cloudflare.com/api/resources/cache/subresources/cache_reserve/ +- **Cache Rules**: https://developers.cloudflare.com/cache/how-to/cache-rules/ +- **Workers Cache API**: https://developers.cloudflare.com/workers/runtime-apis/cache/ +- **R2 Documentation**: https://developers.cloudflare.com/r2/ +- **Smart Shield**: https://developers.cloudflare.com/smart-shield/ +- **Tiered Cache**: https://developers.cloudflare.com/cache/how-to/tiered-cache/ + +## Troubleshooting Flowchart + +Asset not caching in Cache Reserve? + +``` +1. Is Cache Reserve enabled for zone? + → No: Enable via Dashboard or API + → Yes: Continue to step 2 + +2. Is Tiered Cache enabled? + → No: Enable Tiered Cache (required!) + → Yes: Continue to step 3 + +3. Does asset have TTL ≥ 10 hours? + → No: Increase via Cache Rules (edge_ttl override) + → Yes: Continue to step 4 + +4. Is Content-Length header present? + → No: Fix origin to include Content-Length + → Yes: Continue to step 5 + +5. Is Set-Cookie header present? + → Yes: Remove Set-Cookie or scope appropriately + → No: Continue to step 6 + +6. Is Vary header set to *? + → Yes: Change to specific value (e.g., Accept-Encoding) + → No: Continue to step 7 + +7. Is this a range request? + → Yes: Range requests bypass Cache Reserve (not supported) + → No: Continue to step 8 + +8. Is this an O2O (Orange-to-Orange) request? + → Yes: O2O bypasses Cache Reserve + → No: Continue to step 9 + +9. Check Logpush CacheReserveUsed field + → Filter logs to see if assets ever hit Cache Reserve + → Verify cf-cache-status header (should be HIT after first request) +``` + +## See Also + +- [README](./README.md) - Overview and core concepts +- [Configuration](./configuration.md) - Setup and Cache Rules +- [API Reference](./api.md) - Purging and monitoring +- [Patterns](./patterns.md) - Best practices and optimization diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..32550caed567987890d98f744fdc31e993e606e5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cache-reserve/patterns.md @@ -0,0 +1,197 @@ +# Cache Reserve Patterns + +## Best Practices + +### 1. Always Enable Tiered Cache + +```typescript +// Cache Reserve is designed for use WITH Tiered Cache +const configuration = { + tieredCache: 'enabled', // Required for optimal performance + cacheReserve: 'enabled', // Works best with Tiered Cache + + hierarchy: [ + 'Lower-Tier Cache (visitor)', + 'Upper-Tier Cache (origin region)', + 'Cache Reserve (persistent)', + 'Origin' + ] +}; +``` + +### 2. Set Appropriate Cache-Control Headers + +```typescript +// Origin response headers for Cache Reserve eligibility +const originHeaders = { + 'Cache-Control': 'public, max-age=86400', // 24hr (minimum 10hr) + 'Content-Length': '1024000', // Required + 'Cache-Tag': 'images,product-123', // Optional: purging + 'ETag': '"abc123"', // Optional: revalidation + // Avoid: 'Set-Cookie' and 'Vary: *' prevent caching +}; +``` + +### 3. Use Cache Rules for Fine-Grained Control + +```typescript +// Different TTLs for different content types +const cacheRules = [ + { + description: 'Long-term cache for immutable assets', + expression: '(http.request.uri.path matches "^/static/.*\\.[a-f0-9]{8}\\.")', + action_parameters: { + cache_reserve: { eligible: true }, + edge_ttl: { mode: 'override_origin', default: 2592000 }, // 30 days + cache: true + } + }, + { + description: 'Moderate cache for regular images', + expression: '(http.request.uri.path matches "\\.(jpg|png|webp)$")', + action_parameters: { + cache_reserve: { eligible: true }, + edge_ttl: { mode: 'override_origin', default: 86400 }, // 24 hours + cache: true + } + }, + { + description: 'Exclude API from Cache Reserve', + expression: '(http.request.uri.path matches "^/api/")', + action_parameters: { cache_reserve: { eligible: false }, cache: false } + } +]; +``` + +### 4. Making Assets Cache Reserve Eligible from Workers + +**Note**: This modifies response headers to meet eligibility criteria but does NOT directly control Cache Reserve storage (which is zone-level automatic). + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const response = await fetch(request); + if (!response.ok) return response; + + const headers = new Headers(response.headers); + headers.set('Cache-Control', 'public, max-age=36000'); // 10hr minimum + headers.delete('Set-Cookie'); // Blocks caching + + // Ensure Content-Length present + if (!headers.has('Content-Length')) { + const blob = await response.blob(); + headers.set('Content-Length', blob.size.toString()); + return new Response(blob, { status: response.status, headers }); + } + + return new Response(response.body, { status: response.status, headers }); + } +}; +``` + +### 5. Hostname Best Practices + +Use Worker's hostname for efficient caching - avoid overriding hostname unnecessarily. + +## Architecture Patterns + +### Multi-Tier Caching + Immutable Assets + +```typescript +// Optimal: L1 (visitor) → L2 (region) → L3 (Cache Reserve) → Origin +export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + const isImmutable = /\.[a-f0-9]{8,}\.(js|css|jpg|png|woff2)$/.test(url.pathname); + const response = await fetch(request); + + if (isImmutable) { + const headers = new Headers(response.headers); + headers.set('Cache-Control', 'public, max-age=31536000, immutable'); + return new Response(response.body, { status: response.status, headers }); + } + return response; + } +}; +``` + +## Cost Optimization + +### Cost Calculator + +```typescript +interface CacheReserveEstimate { + avgAssetSizeGB: number; + uniqueAssets: number; + monthlyReads: number; + monthlyWrites: number; + originEgressCostPerGB: number; // e.g., AWS: $0.09/GB +} + +function estimateMonthlyCost(input: CacheReserveEstimate) { + // Cache Reserve pricing + const storageCostPerGBMonth = 0.015; + const classAPerMillion = 4.50; // writes + const classBPerMillion = 0.36; // reads + + // Calculate Cache Reserve costs + const totalStorageGB = input.avgAssetSizeGB * input.uniqueAssets; + const storageCost = totalStorageGB * storageCostPerGBMonth; + const writeCost = (input.monthlyWrites / 1_000_000) * classAPerMillion; + const readCost = (input.monthlyReads / 1_000_000) * classBPerMillion; + + const cacheReserveCost = storageCost + writeCost + readCost; + + // Calculate origin egress cost (what you'd pay without Cache Reserve) + const totalTrafficGB = (input.monthlyReads * input.avgAssetSizeGB); + const originEgressCost = totalTrafficGB * input.originEgressCostPerGB; + + // Savings calculation + const savings = originEgressCost - cacheReserveCost; + const savingsPercent = ((savings / originEgressCost) * 100).toFixed(1); + + return { + cacheReserveCost: `$${cacheReserveCost.toFixed(2)}`, + originEgressCost: `$${originEgressCost.toFixed(2)}`, + monthlySavings: `$${savings.toFixed(2)}`, + savingsPercent: `${savingsPercent}%`, + breakdown: { + storage: `$${storageCost.toFixed(2)}`, + writes: `$${writeCost.toFixed(2)}`, + reads: `$${readCost.toFixed(2)}`, + } + }; +} + +// Example: Media library +const mediaLibrary = estimateMonthlyCost({ + avgAssetSizeGB: 0.005, // 5MB images + uniqueAssets: 10_000, + monthlyReads: 5_000_000, + monthlyWrites: 50_000, + originEgressCostPerGB: 0.09, // AWS S3 +}); + +console.log(mediaLibrary); +// { +// cacheReserveCost: "$9.98", +// originEgressCost: "$25.00", +// monthlySavings: "$15.02", +// savingsPercent: "60.1%", +// breakdown: { storage: "$0.75", writes: "$0.23", reads: "$9.00" } +// } +``` + +### Optimization Guidelines + +- **Set appropriate TTLs**: 10hr minimum, 24hr+ optimal for stable content, 30d max cautiously +- **Cache high-value stable assets**: Images, media, fonts, archives, documentation +- **Exclude frequently changing**: APIs, user-specific content, real-time data +- **Compression note**: Cache Reserve fetches uncompressed from origin, serves compressed to visitors - factor in origin egress costs + +## See Also + +- [README](./README.md) - Overview and core concepts +- [Configuration](./configuration.md) - Setup and Cache Rules +- [API Reference](./api.md) - Purging and monitoring +- [Gotchas](./gotchas.md) - Common issues and troubleshooting diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a6c488db63606beaf73fd453f8bd514f7574305d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/README.md @@ -0,0 +1,85 @@ +# Cloudflare Containers Skill Reference + +**APPLIES TO: Cloudflare Containers ONLY - NOT general Cloudflare Workers** + +Use when working with Cloudflare Containers: deploying containerized apps on Workers platform, configuring container-enabled Durable Objects, managing container lifecycle, or implementing stateful/stateless container patterns. + +## Beta Status + +⚠️ Containers is currently in **beta**. API may change without notice. No SLA guarantees. Custom instance types added Jan 2026. + +## Core Concepts + +**Container as Durable Object:** Each container is a Durable Object with persistent identity. Accessed via `getByName(id)` or `getRandom()`. + +**Image deployment:** Images pre-fetched globally. Deployments use rolling strategy (not instant like Workers). + +**Lifecycle:** cold start (2-3s) → running → `sleepAfter` timeout → stopped. No autoscaling - manual load balancing via `getRandom()`. + +**Persistent identity, ephemeral disk:** Container ID persists, but disk resets on stop. Use Durable Object storage for persistence. + +## Quick Start + +```typescript +import { Container } from "@cloudflare/containers"; + +export class MyContainer extends Container { + defaultPort = 8080; + sleepAfter = "30m"; +} + +export default { + async fetch(request: Request, env: Env) { + const container = env.MY_CONTAINER.getByName("instance-1"); + await container.startAndWaitForPorts(); + return container.fetch(request); + } +}; +``` + +## Reading Order + +| Task | Files | +|------|-------| +| Setup new container project | README → configuration.md | +| Implement container logic | README → api.md → patterns.md | +| Choose routing pattern | patterns.md (routing section) | +| Debug issues | gotchas.md | +| Production hardening | gotchas.md → patterns.md (lifecycle) | + +## Routing Decision Tree + +**How should requests reach containers?** + +- **Same user/session → same container:** Use `getByName(sessionId)` for session affinity +- **Stateless, spread load:** Use `getRandom()` for load balancing +- **Job per container:** Use `getByName(jobId)` + explicit lifecycle management +- **Single global instance:** Use `getByName("singleton")` + +## When to Use Containers vs Workers + +**Use Containers when:** +- Need stateful, long-lived processes (sessions, WebSockets, games) +- Running existing containerized apps (Node.js, Python, custom binaries) +- Need filesystem access or specific system dependencies +- Per-user/session isolation with dedicated compute + +**Use Workers when:** +- Stateless HTTP handlers +- Sub-millisecond cold starts required +- Auto-scaling to zero critical +- Simple request/response patterns + +## In This Reference + +- **[configuration.md](configuration.md)** - Wrangler config, instance types, Container class properties, environment variables, account limits +- **[api.md](api.md)** - Container class API, startup methods, communication (HTTP/TCP/WebSocket), routing helpers, lifecycle hooks, scheduling, state inspection +- **[patterns.md](patterns.md)** - Routing patterns (session affinity, load balancing, singleton), WebSocket forwarding, graceful shutdown, Workflow/Queue integration +- **[gotchas.md](gotchas.md)** - Critical gotchas (WebSocket, startup methods), common errors with solutions, specific limits, beta caveats + +## See Also + +- [Durable Objects](../durable-objects/) - Containers extend Durable Objects +- [Workflows](../workflows/) - Orchestrate container operations +- [Queues](../queues/) - Trigger containers from queue messages +- [Cloudflare Docs](https://developers.cloudflare.com/containers/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/api.md new file mode 100644 index 0000000000000000000000000000000000000000..91c8356c739ca70687999766b935884b2aae8e5d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/api.md @@ -0,0 +1,187 @@ +## Container Class API + +```typescript +import { Container } from "@cloudflare/containers"; + +export class MyContainer extends Container { + defaultPort = 8080; + requiredPorts = [8080]; + sleepAfter = "30m"; + enableInternet = true; + pingEndpoint = "/health"; + envVars = {}; + entrypoint = []; + + onStart() { /* container started */ } + onStop() { /* container stopping */ } + onError(error: Error) { /* container error */ } + onActivityExpired(): boolean { /* timeout, return true to stay alive */ } + async alarm() { /* scheduled task */ } +} +``` + +## Routing + +**getByName(id)** - Named instance for session affinity, per-user state +**getRandom()** - Random instance for load balancing stateless services + +```typescript +const container = env.MY_CONTAINER.getByName("user-123"); +const container = env.MY_CONTAINER.getRandom(); +``` + +## Startup Methods + +### start() - Basic start (8s timeout) + +```typescript +await container.start(); +await container.start({ envVars: { KEY: "value" } }); +``` + +Returns when **process starts**, NOT when ports ready. Use for fire-and-forget. + +### startAndWaitForPorts() - Recommended (20s timeout) + +```typescript +await container.startAndWaitForPorts(); // Uses requiredPorts +await container.startAndWaitForPorts({ ports: [8080, 9090] }); +await container.startAndWaitForPorts({ + ports: [8080], + startOptions: { envVars: { KEY: "value" } } +}); +``` + +Returns when **ports listening**. Use before HTTP/TCP requests. + +**Port resolution:** explicit ports → requiredPorts → defaultPort → port 33 + +### waitForPort() - Wait for specific port + +```typescript +await container.waitForPort(8080); +await container.waitForPort(8080, { timeout: 30000 }); +``` + +## Communication + +### fetch() - HTTP with WebSocket support + +```typescript +// ✅ Supports WebSocket upgrades +const response = await container.fetch(request); +const response = await container.fetch("http://container/api", { + method: "POST", + body: JSON.stringify({ data: "value" }) +}); +``` + +**Use for:** All HTTP, especially WebSocket. + +### containerFetch() - HTTP only (no WebSocket) + +```typescript +// ❌ No WebSocket support +const response = await container.containerFetch(request); +``` + +**⚠️ Critical:** Use `fetch()` for WebSocket, not `containerFetch()`. + +### TCP Connections + +```typescript +const port = this.ctx.container.getTcpPort(8080); +const conn = port.connect(); +await conn.opened; + +if (request.body) await request.body.pipeTo(conn.writable); +return new Response(conn.readable); +``` + +### switchPort() - Change default port + +```typescript +this.switchPort(8081); // Subsequent fetch() uses this port +``` + +## Lifecycle Hooks + +### onStart() + +Called when container process starts (ports may not be ready). Runs in `blockConcurrencyWhile` - no concurrent requests. + +```typescript +onStart() { + console.log("Container starting"); +} +``` + +### onStop() + +Called when SIGTERM received. 15 minutes until SIGKILL. Use for graceful shutdown. + +```typescript +onStop() { + // Save state, close connections, flush logs +} +``` + +### onError() + +Called when container crashes or fails to start. + +```typescript +onError(error: Error) { + console.error("Container error:", error); +} +``` + +### onActivityExpired() + +Called when `sleepAfter` timeout reached. Return `true` to stay alive, `false` to stop. + +```typescript +onActivityExpired(): boolean { + if (this.hasActiveConnections()) return true; // Keep alive + return false; // OK to stop +} +``` + +## Scheduling + +```typescript +export class ScheduledContainer extends Container { + async fetch(request: Request) { + await this.schedule(Date.now() + 60000); // 1 minute + await this.schedule("2026-01-28T00:00:00Z"); // ISO string + return new Response("Scheduled"); + } + + async alarm() { + // Called when schedule fires (SQLite-backed, survives restarts) + } +} +``` + +**⚠️ Don't override `alarm()` directly when using `schedule()` helper.** + +## State Inspection + +### External state check + +```typescript +const state = await container.getState(); +// state.status: "starting" | "running" | "stopping" | "stopped" +``` + +### Internal state check + +```typescript +export class MyContainer extends Container { + async fetch(request: Request) { + if (this.ctx.container.running) { ... } + } +} +``` + +**⚠️ Use `getState()` for external checks, `ctx.container.running` for internal.** diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..fd39cc4d2ee0a0f069b806c84f2cba530b70afaf --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/configuration.md @@ -0,0 +1,188 @@ +## Wrangler Configuration + +### Basic Container Config + +```jsonc +{ + "name": "my-worker", + "main": "src/index.ts", + "compatibility_date": "2026-01-10", + "containers": [ + { + "class_name": "MyContainer", + "image": "./Dockerfile", // Path to Dockerfile or directory with Dockerfile + "instance_type": "standard-1", // Predefined or custom (see below) + "max_instances": 10 + } + ], + "durable_objects": { + "bindings": [ + { + "name": "MY_CONTAINER", + "class_name": "MyContainer" + } + ] + }, + "migrations": [ + { + "tag": "v1", + "new_sqlite_classes": ["MyContainer"] // Must use new_sqlite_classes + } + ] +} +``` + +Key config requirements: +- `image` - Path to Dockerfile or directory containing Dockerfile +- `class_name` - Must match Container class export name +- `max_instances` - Max concurrent container instances +- Must configure Durable Objects binding AND migrations + +### Instance Types + +#### Predefined Types + +| Type | vCPU | Memory | Disk | +|------|------|--------|------| +| lite | 1/16 | 256 MiB | 2 GB | +| basic | 1/4 | 1 GiB | 4 GB | +| standard-1 | 1/2 | 4 GiB | 8 GB | +| standard-2 | 1 | 6 GiB | 12 GB | +| standard-3 | 2 | 8 GiB | 16 GB | +| standard-4 | 4 | 12 GiB | 20 GB | + +```jsonc +{ + "containers": [ + { + "class_name": "MyContainer", + "image": "./Dockerfile", + "instance_type": "standard-2" // Use predefined type + } + ] +} +``` + +#### Custom Types (Jan 2026 Feature) + +```jsonc +{ + "containers": [ + { + "class_name": "MyContainer", + "image": "./Dockerfile", + "instance_type_custom": { + "vcpu": 2, // 1-4 vCPU + "memory_mib": 8192, // 512-12288 MiB (up to 12 GiB) + "disk_mib": 16384 // 2048-20480 MiB (up to 20 GB) + } + } + ] +} +``` + +**Custom type constraints:** +- Minimum 3 GiB memory per vCPU +- Maximum 2 GB disk per 1 GiB memory +- Max 4 vCPU, 12 GiB memory, 20 GB disk per container + +### Account Limits + +| Resource | Limit | Notes | +|----------|-------|-------| +| Total memory (all containers) | 400 GiB | Across all running containers | +| Total vCPU (all containers) | 100 | Across all running containers | +| Total disk (all containers) | 2 TB | Across all running containers | +| Image storage per account | 50 GB | Stored container images | + +### Container Class Properties + +```typescript +import { Container } from "@cloudflare/containers"; + +export class MyContainer extends Container { + // Port Configuration + defaultPort = 8080; // Default port for fetch() calls + requiredPorts = [8080, 9090]; // Ports to wait for in startAndWaitForPorts() + + // Lifecycle + sleepAfter = "30m"; // Inactivity timeout (5m, 30m, 2h, etc.) + + // Network + enableInternet = true; // Allow outbound internet access + + // Health Check + pingEndpoint = "/health"; // Health check endpoint path + + // Environment + envVars = { // Environment variables passed to container + NODE_ENV: "production", + LOG_LEVEL: "info" + }; + + // Startup + entrypoint = ["/bin/start.sh"]; // Override image entrypoint (optional) +} +``` + +**Property details:** + +- **`defaultPort`**: Port used when calling `container.fetch()` without explicit port. Falls back to port 33 if not set. + +- **`requiredPorts`**: Array of ports that must be listening before `startAndWaitForPorts()` returns. First port becomes default if `defaultPort` not set. + +- **`sleepAfter`**: Duration string (e.g., "5m", "30m", "2h"). Container stops after this period of inactivity. Timer resets on each request. + +- **`enableInternet`**: Boolean. If `true`, container can make outbound HTTP/TCP requests. + +- **`pingEndpoint`**: Path used for health checks. Should respond with 2xx status. + +- **`envVars`**: Object of environment variables. Merged with runtime-provided vars (see below). + +- **`entrypoint`**: Array of strings. Overrides container image's CMD/ENTRYPOINT. + +### Runtime Environment Variables + +Cloudflare automatically provides these environment variables to containers: + +| Variable | Description | +|----------|-------------| +| `CLOUDFLARE_APPLICATION_ID` | Worker application ID | +| `CLOUDFLARE_COUNTRY_A2` | Two-letter country code of request origin | +| `CLOUDFLARE_LOCATION` | Cloudflare data center location | +| `CLOUDFLARE_REGION` | Region identifier | +| `CLOUDFLARE_DURABLE_OBJECT_ID` | Container's Durable Object ID | + +Custom `envVars` from Container class are merged with these. Custom vars override runtime vars if names conflict. + +### Image Management + +**Distribution model:** Images pre-fetched to all global locations before deployment. Ensures fast cold starts (2-3s typical). + +**Rolling deploys:** Unlike Workers (instant), container deployments roll out gradually. Old versions continue running during rollout. + +**Ephemeral disk:** Container disk is ephemeral and resets on each stop. Use Durable Object storage (`this.ctx.storage`) for persistence. + +## wrangler.toml Format + +```toml +name = "my-worker" +main = "src/index.ts" +compatibility_date = "2026-01-10" + +[[containers]] +class_name = "MyContainer" +image = "./Dockerfile" +instance_type = "standard-2" +max_instances = 10 + +[[durable_objects.bindings]] +name = "MY_CONTAINER" +class_name = "MyContainer" + +[[migrations]] +tag = "v1" +new_sqlite_classes = ["MyContainer"] +``` + +Both `wrangler.jsonc` and `wrangler.toml` are supported. Use `wrangler.jsonc` for comments and better IDE support. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..306e8c5b379fc3d2c2534c319a201c62eb88db43 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/gotchas.md @@ -0,0 +1,178 @@ +## Critical Gotchas + +### ⚠️ WebSocket: fetch() vs containerFetch() + +**Problem:** WebSocket connections fail silently + +**Cause:** `containerFetch()` doesn't support WebSocket upgrades + +**Fix:** Always use `fetch()` for WebSocket + +```typescript +// ❌ WRONG +return container.containerFetch(request); + +// ✅ CORRECT +return container.fetch(request); +``` + +### ⚠️ startAndWaitForPorts() vs start() + +**Problem:** "connection refused" after `start()` + +**Cause:** `start()` returns when process starts, NOT when ports ready + +**Fix:** Use `startAndWaitForPorts()` before requests + +```typescript +// ❌ WRONG +await container.start(); +return container.fetch(request); + +// ✅ CORRECT +await container.startAndWaitForPorts(); +return container.fetch(request); +``` + +### ⚠️ Activity Timeout on Long Operations + +**Problem:** Container stops during long work + +**Cause:** `sleepAfter` based on request activity, not internal work + +**Fix:** Renew timeout by touching storage + +```typescript +const interval = setInterval(() => { + this.ctx.storage.put("keepalive", Date.now()); +}, 60000); + +try { + await this.doLongWork(data); +} finally { + clearInterval(interval); +} +``` + +### ⚠️ blockConcurrencyWhile for Startup + +**Problem:** Race conditions during initialization + +**Fix:** Use `blockConcurrencyWhile` for atomic initialization + +```typescript +await this.ctx.blockConcurrencyWhile(async () => { + if (!this.initialized) { + await this.startAndWaitForPorts(); + this.initialized = true; + } +}); +``` + +### ⚠️ Lifecycle Hooks Block Requests + +**Problem:** Container unresponsive during `onStart()` + +**Cause:** Hooks run in `blockConcurrencyWhile` - no concurrent requests + +**Fix:** Keep hooks fast, avoid long operations + +### ⚠️ Don't Override alarm() When Using schedule() + +**Problem:** Scheduled tasks don't execute + +**Cause:** `schedule()` uses `alarm()` internally + +**Fix:** Implement `alarm()` to handle scheduled tasks + +## Common Errors + +### "Container start timeout" + +**Cause:** Container took >8s (`start()`) or >20s (`startAndWaitForPorts()`) + +**Solutions:** +- Optimize image (smaller base, fewer layers) +- Check `entrypoint` correct +- Verify app listens on correct ports +- Increase timeout if needed + +### "Port not available" + +**Cause:** Calling `fetch()` before port ready + +**Solution:** Use `startAndWaitForPorts()` + +### "Container memory exceeded" + +**Cause:** Using more memory than instance type allows + +**Solutions:** +- Use larger instance type (standard-2, standard-3, standard-4) +- Optimize app memory usage +- Use custom instance type + +```jsonc +"instance_type_custom": { + "vcpu": 2, + "memory_mib": 8192 +} +``` + +### "Max instances reached" + +**Cause:** All `max_instances` slots in use + +**Solutions:** +- Increase `max_instances` +- Implement proper `sleepAfter` +- Use `getRandom()` for distribution +- Check for instance leaks + +### "No container instance available" + +**Cause:** Account capacity limits reached + +**Solutions:** +- Check account limits +- Review instance types across containers +- Contact Cloudflare support + +## Limits + +| Resource | Limit | Notes | +|----------|-------|-------| +| Cold start | 2-3s | Image pre-fetched globally | +| Graceful shutdown | 15 min | SIGTERM → SIGKILL | +| `start()` timeout | 8s | Process start | +| `startAndWaitForPorts()` timeout | 20s | Port ready | +| Max vCPU per container | 4 | standard-4 or custom | +| Max memory per container | 12 GiB | standard-4 or custom | +| Max disk per container | 20 GB | Ephemeral, resets | +| Account total memory | 400 GiB | All containers | +| Account total vCPU | 100 | All containers | +| Account total disk | 2 TB | All containers | +| Image storage | 50 GB | Per account | +| Disk persistence | None | Use DO storage | + +## Best Practices + +1. **Use `startAndWaitForPorts()` by default** - Prevents port errors +2. **Set appropriate `sleepAfter`** - Balance resources vs cold starts +3. **Use `fetch()` for WebSocket** - Not `containerFetch()` +4. **Design for restarts** - Ephemeral disk, implement graceful shutdown +5. **Monitor resources** - Stay within account limits +6. **Keep hooks fast** - Run in `blockConcurrencyWhile` +7. **Renew activity for long ops** - Touch storage to prevent timeout + +## Beta Caveats + +⚠️ Containers in **beta**: + +- **API may change** without notice +- **No SLA** guarantees +- **Limited regions** initially +- **No autoscaling** - manual via `getRandom()` +- **Rolling deploys** only (not instant like Workers) + +Plan for API changes, test thoroughly before production. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..ebd0b54bb5f632e21ed599e89b0ef0a184e5e3f2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/containers/patterns.md @@ -0,0 +1,202 @@ +## Routing Patterns + +### Session Affinity (Stateful) + +```typescript +export class SessionBackend extends Container { + defaultPort = 3000; + sleepAfter = "30m"; +} + +export default { + async fetch(request: Request, env: Env) { + const sessionId = request.headers.get("X-Session-ID") || crypto.randomUUID(); + const container = env.SESSION_BACKEND.getByName(sessionId); + await container.startAndWaitForPorts(); + return container.fetch(request); + } +}; +``` + +**Use:** User sessions, WebSocket, stateful games, per-user caching. + +### Load Balancing (Stateless) + +```typescript +export default { + async fetch(request: Request, env: Env) { + const container = env.STATELESS_API.getRandom(); + await container.startAndWaitForPorts(); + return container.fetch(request); + } +}; +``` + +**Use:** Stateless HTTP APIs, CPU-intensive work, read-only queries. + +### Singleton Pattern + +```typescript +export default { + async fetch(request: Request, env: Env) { + const container = env.GLOBAL_SERVICE.getByName("singleton"); + await container.startAndWaitForPorts(); + return container.fetch(request); + } +}; +``` + +**Use:** Global cache, centralized coordinator, single source of truth. + +## WebSocket Forwarding + +```typescript +export default { + async fetch(request: Request, env: Env) { + if (request.headers.get("Upgrade") === "websocket") { + const sessionId = request.headers.get("X-Session-ID") || crypto.randomUUID(); + const container = env.WS_BACKEND.getByName(sessionId); + await container.startAndWaitForPorts(); + + // ⚠️ MUST use fetch(), not containerFetch() + return container.fetch(request); + } + return new Response("Not a WebSocket request", { status: 400 }); + } +}; +``` + +**⚠️ Critical:** Always use `fetch()` for WebSocket. + +## Graceful Shutdown + +```typescript +export class GracefulContainer extends Container { + private connections = new Set(); + + onStop() { + // SIGTERM received, 15 minutes until SIGKILL + for (const ws of this.connections) { + ws.close(1001, "Server shutting down"); + } + this.ctx.storage.put("shutdown-time", Date.now()); + } + + onActivityExpired(): boolean { + return this.connections.size > 0; // Keep alive if connections + } +} +``` + +## Concurrent Request Handling + +```typescript +export class SafeContainer extends Container { + private initialized = false; + + async fetch(request: Request) { + await this.ctx.blockConcurrencyWhile(async () => { + if (!this.initialized) { + await this.startAndWaitForPorts(); + this.initialized = true; + } + }); + return super.fetch(request); + } +} +``` + +**Use:** One-time initialization, preventing concurrent startup. + +## Activity Timeout Renewal + +```typescript +export class LongRunningContainer extends Container { + sleepAfter = "5m"; + + async processLongJob(data: unknown) { + const interval = setInterval(() => { + this.ctx.storage.put("keepalive", Date.now()); + }, 60000); + + try { + await this.doLongWork(data); + } finally { + clearInterval(interval); + } + } +} +``` + +**Use:** Long operations exceeding `sleepAfter`. + +## Multiple Port Routing + +```typescript +export class MultiPortContainer extends Container { + requiredPorts = [8080, 8081, 9090]; + + async fetch(request: Request) { + const path = new URL(request.url).pathname; + if (path.startsWith("/grpc")) this.switchPort(8081); + else if (path.startsWith("/metrics")) this.switchPort(9090); + return super.fetch(request); + } +} +``` + +**Use:** Multi-protocol services (HTTP + gRPC), separate metrics endpoints. + +## Workflow Integration + +```typescript +import { WorkflowEntrypoint } from "cloudflare:workers"; + +export class ProcessingWorkflow extends WorkflowEntrypoint { + async run(event, step) { + const container = this.env.PROCESSOR.getByName(event.payload.jobId); + + await step.do("start", async () => { + await container.startAndWaitForPorts(); + }); + + const result = await step.do("process", async () => { + return container.fetch("/process", { + method: "POST", + body: JSON.stringify(event.payload.data) + }).then(r => r.json()); + }); + + return result; + } +} +``` + +**Use:** Orchestrating multi-step container operations, durable execution. + +## Queue Consumer Integration + +```typescript +export default { + async queue(batch, env) { + for (const msg of batch.messages) { + try { + const container = env.PROCESSOR.getByName(msg.body.jobId); + await container.startAndWaitForPorts(); + + const response = await container.fetch("/process", { + method: "POST", + body: JSON.stringify(msg.body) + }); + + response.ok ? msg.ack() : msg.retry(); + } catch (err) { + console.error("Queue processing error:", err); + msg.retry(); + } + } + } +}; +``` + +**Use:** Asynchronous job processing, batch operations, event-driven execution. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8aa019b55b1139151c0eaec9c9110875d95f0faf --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/README.md @@ -0,0 +1,99 @@ +# Cloudflare Cron Triggers + +Schedule Workers execution using cron expressions. Runs on Cloudflare's global network during underutilized periods. + +## Key Features + +- **UTC-only execution** - All schedules run on UTC time +- **5-field cron syntax** - Quartz scheduler extensions (L, W, #) +- **Global propagation** - 15min deployment delay +- **At-least-once delivery** - Rare duplicate executions possible +- **Workflow integration** - Trigger long-running multi-step tasks +- **Green Compute** - Optional carbon-aware scheduling during low-carbon periods + +## Cron Syntax + +``` + ┌─────────── minute (0-59) + │ ┌───────── hour (0-23) + │ │ ┌─────── day of month (1-31) + │ │ │ ┌───── month (1-12, JAN-DEC) + │ │ │ │ ┌─── day of week (1-7, SUN-SAT, 1=Sunday) + * * * * * +``` + +**Special chars:** `*` (any), `,` (list), `-` (range), `/` (step), `L` (last), `W` (weekday), `#` (nth) + +## Common Schedules + +```bash +*/5 * * * * # Every 5 minutes +0 * * * * # Hourly +0 2 * * * # Daily 2am UTC (off-peak) +0 9 * * MON-FRI # Weekdays 9am UTC +0 0 1 * * # Monthly 1st midnight UTC +0 9 L * * # Last day of month 9am UTC +0 10 * * MON#2 # 2nd Monday 10am UTC +*/10 9-17 * * MON-FRI # Every 10min, 9am-5pm weekdays +``` + +## Quick Start + +**wrangler.jsonc:** +```jsonc +{ + "name": "my-cron-worker", + "triggers": { + "crons": ["*/5 * * * *", "0 2 * * *"] + } +} +``` + +**Handler:** +```typescript +export default { + async scheduled( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, + ): Promise { + console.log("Cron:", controller.cron); + console.log("Time:", new Date(controller.scheduledTime)); + + ctx.waitUntil(asyncTask(env)); // Non-blocking + }, +}; +``` + +**Test locally:** +```bash +npx wrangler dev +curl "http://localhost:8787/__scheduled?cron=*/5+*+*+*+*" +``` + +## Limits + +- **Free:** 3 triggers/worker, 10ms CPU +- **Paid:** Unlimited triggers, 50ms CPU +- **Propagation:** 15min global deployment +- **Timezone:** UTC only + +## Reading Order + +**New to cron triggers?** Start here: +1. This README - Overview and quick start +2. [configuration.md](./configuration.md) - Set up your first cron trigger +3. [api.md](./api.md) - Understand the handler API +4. [patterns.md](./patterns.md) - Common use cases and examples + +**Troubleshooting?** Jump to [gotchas.md](./gotchas.md) + +## In This Reference +- [configuration.md](./configuration.md) - wrangler config, env-specific schedules, Green Compute +- [api.md](./api.md) - ScheduledController, noRetry(), waitUntil, testing patterns +- [patterns.md](./patterns.md) - Use cases, monitoring, queue integration, Durable Objects +- [gotchas.md](./gotchas.md) - Timezone issues, idempotency, security, testing + +## See Also +- [workflows](../workflows/) - Alternative for long-running scheduled tasks +- [workers](../workers/) - Worker runtime documentation diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/api.md new file mode 100644 index 0000000000000000000000000000000000000000..8c3194dd1aa3e3548246b18cea98935fbc122be3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/api.md @@ -0,0 +1,196 @@ +# Cron Triggers API + +## Basic Handler + +```typescript +export default { + async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise { + console.log("Cron executed:", new Date(controller.scheduledTime)); + }, +}; +``` + +**JavaScript:** Same signature without types +**Python:** `class Default(WorkerEntrypoint): async def scheduled(self, controller, env, ctx)` + +## ScheduledController + +```typescript +interface ScheduledController { + scheduledTime: number; // Unix ms when scheduled to run + cron: string; // Expression that triggered (e.g., "*/5 * * * *") + type: string; // Always "scheduled" + noRetry(): void; // Prevent automatic retry on failure +} +``` + +**Prevent retry on failure:** +```typescript +export default { + async scheduled(controller, env, ctx) { + try { + await riskyOperation(env); + } catch (error) { + // Don't retry - failure is expected/acceptable + controller.noRetry(); + console.error("Operation failed, not retrying:", error); + } + }, +}; +``` + +**When to use noRetry():** +- External API failures outside your control (avoid hammering failed services) +- Rate limit errors (retry would fail again immediately) +- Duplicate execution detected (idempotency check failed) +- Non-critical operations where skip is acceptable (analytics, caching) +- Validation errors that won't resolve on retry + +## Handler Parameters + +**`controller: ScheduledController`** +- Access cron expression and scheduled time + +**`env: Env`** +- All bindings: KV, R2, D1, secrets, service bindings + +**`ctx: ExecutionContext`** +- `ctx.waitUntil(promise)` - Extend execution for async tasks (logging, cleanup, external APIs) +- First `waitUntil` failure recorded in Cron Events + +## Multiple Schedules + +```typescript +export default { + async scheduled(controller, env, ctx) { + switch (controller.cron) { + case "*/3 * * * *": ctx.waitUntil(updateRecentData(env)); break; + case "0 * * * *": ctx.waitUntil(processHourlyAggregation(env)); break; + case "0 2 * * *": ctx.waitUntil(performDailyMaintenance(env)); break; + default: console.warn(`Unhandled: ${controller.cron}`); + } + }, +}; +``` + +## ctx.waitUntil Usage + +```typescript +export default { + async scheduled(controller, env, ctx) { + const data = await fetchCriticalData(); // Critical path + + // Non-blocking background tasks + ctx.waitUntil(Promise.all([ + logToAnalytics(data), + cleanupOldRecords(env.DB), + notifyWebhook(env.WEBHOOK_URL, data), + ])); + }, +}; +``` + +## Workflow Integration + +```typescript +import { WorkflowEntrypoint } from "cloudflare:workers"; + +export class DataProcessingWorkflow extends WorkflowEntrypoint { + async run(event, step) { + const data = await step.do("fetch-data", () => fetchLargeDataset()); + const processed = await step.do("process-data", () => processDataset(data)); + await step.do("store-results", () => storeResults(processed)); + } +} + +export default { + async scheduled(controller, env, ctx) { + const instance = await env.MY_WORKFLOW.create({ + params: { scheduledTime: controller.scheduledTime, cron: controller.cron }, + }); + console.log(`Started workflow: ${instance.id}`); + }, +}; +``` + +## Testing Handler + +**Local development (/__scheduled endpoint):** +```bash +# Start dev server +npx wrangler dev + +# Trigger any cron +curl "http://localhost:8787/__scheduled?cron=*/5+*+*+*+*" + +# Trigger specific cron with custom time +curl "http://localhost:8787/__scheduled?cron=0+2+*+*+*&scheduledTime=1704067200000" +``` + +**Query parameters:** +- `cron` - Required. URL-encoded cron expression (use `+` for spaces) +- `scheduledTime` - Optional. Unix timestamp in milliseconds (defaults to current time) + +**Production security:** The `/__scheduled` endpoint is available in production and can be triggered by anyone. Block it or implement authentication - see [gotchas.md](./gotchas.md#security-concerns) + +**Unit testing (Vitest):** +```typescript +// test/scheduled.test.ts +import { describe, it, expect } from "vitest"; +import { env } from "cloudflare:test"; +import worker from "../src/index"; + +describe("Scheduled Handler", () => { + it("processes scheduled event", async () => { + const controller = { scheduledTime: Date.now(), cron: "*/5 * * * *", type: "scheduled" as const, noRetry: () => {} }; + const ctx = { waitUntil: (p: Promise) => p, passThroughOnException: () => {} }; + await worker.scheduled(controller, env, ctx); + expect(await env.MY_KV.get("last_run")).toBeDefined(); + }); + + it("handles multiple crons", async () => { + const ctx = { waitUntil: () => {}, passThroughOnException: () => {} }; + await worker.scheduled({ scheduledTime: Date.now(), cron: "*/5 * * * *", type: "scheduled", noRetry: () => {} }, env, ctx); + expect(await env.MY_KV.get("last_type")).toBe("frequent"); + }); +}); +``` + +## Error Handling + +**Automatic retries:** +- Failed cron executions are retried automatically unless `noRetry()` is called +- Retry happens after a delay (typically minutes) +- Only first `waitUntil()` failure is recorded in Cron Events + +**Best practices:** +```typescript +export default { + async scheduled(controller, env, ctx) { + try { + await criticalOperation(env); + } catch (error) { + // Log error details + console.error("Cron failed:", { + cron: controller.cron, + scheduledTime: controller.scheduledTime, + error: error.message, + stack: error.stack, + }); + + // Decide: retry or skip + if (error.message.includes("rate limit")) { + controller.noRetry(); // Skip retry for rate limits + } + // Otherwise allow automatic retry + throw error; + } + }, +}; +``` + +## See Also + +- [README.md](./README.md) - Overview +- [patterns.md](./patterns.md) - Use cases, examples +- [gotchas.md](./gotchas.md) - Common errors, testing issues diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..f98b18a5515ffbe88f79efc067e8697c461ce4e7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/configuration.md @@ -0,0 +1,180 @@ +# Cron Triggers Configuration + +## wrangler.jsonc + +```jsonc +{ + "$schema": "./node_modules/wrangler/config-schema.json", + "name": "my-cron-worker", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", // Use current date for new projects + + "triggers": { + "crons": [ + "*/5 * * * *", // Every 5 minutes + "0 */2 * * *", // Every 2 hours + "0 9 * * MON-FRI", // Weekdays at 9am UTC + "0 2 1 * *" // Monthly on 1st at 2am UTC + ] + } +} +``` + +## Green Compute (Beta) + +Schedule crons during low-carbon periods for carbon-aware execution: + +```jsonc +{ + "name": "eco-cron-worker", + "triggers": { + "crons": ["0 2 * * *"] + }, + "placement": { + "mode": "smart" // Runs during low-carbon periods + } +} +``` + +**Modes:** +- `"smart"` - Carbon-aware scheduling (may delay up to 24h for optimal window) +- Default (no placement config) - Standard scheduling (no delay) + +**How it works:** +- Cloudflare delays execution until grid carbon intensity is lower +- Maximum delay: 24 hours from scheduled time +- Ideal for batch jobs with flexible timing requirements + +**Use cases:** +- Nightly data processing and ETL pipelines +- Weekly/monthly report generation +- Database backups and maintenance +- Analytics aggregation +- ML model training + +**Not suitable for:** +- Time-sensitive operations (SLA requirements) +- User-facing features requiring immediate execution +- Real-time monitoring and alerting +- Compliance tasks with strict time windows + +## Environment-Specific Schedules + +```jsonc +{ + "name": "my-cron-worker", + "triggers": { + "crons": ["0 */6 * * *"] // Prod: every 6 hours + }, + "env": { + "staging": { + "triggers": { + "crons": ["*/15 * * * *"] // Staging: every 15min + } + }, + "dev": { + "triggers": { + "crons": ["*/5 * * * *"] // Dev: every 5min + } + } + } +} +``` + +## Schedule Format + +**Structure:** `minute hour day-of-month month day-of-week` + +**Special chars:** `*` (any), `,` (list), `-` (range), `/` (step), `L` (last), `W` (weekday), `#` (nth) + +## Managing Triggers + +**Remove all:** `"triggers": { "crons": [] }` +**Preserve existing:** Omit `"triggers"` field entirely + +## Deployment + +```bash +# Deploy with config crons +npx wrangler deploy + +# Deploy specific environment +npx wrangler deploy --env production + +# View deployments +npx wrangler deployments list +``` + +**⚠️ Changes take up to 15 minutes to propagate globally** + +## API Management + +**Get triggers:** +```bash +curl "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{script_name}/schedules" \ + -H "Authorization: Bearer {api_token}" +``` + +**Update triggers:** +```bash +curl -X PUT "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{script_name}/schedules" \ + -H "Authorization: Bearer {api_token}" \ + -H "Content-Type: application/json" \ + -d '{"crons": ["*/5 * * * *", "0 2 * * *"]}' +``` + +**Delete all:** +```bash +curl -X PUT "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{script_name}/schedules" \ + -H "Authorization: Bearer {api_token}" \ + -H "Content-Type: application/json" \ + -d '{"crons": []}' +``` + +## Combining Multiple Workers + +For complex schedules, use multiple workers: + +```jsonc +// worker-frequent.jsonc +{ + "name": "data-sync-frequent", + "triggers": { "crons": ["*/5 * * * *"] } +} + +// worker-daily.jsonc +{ + "name": "reports-daily", + "triggers": { "crons": ["0 2 * * *"] }, + "placement": { "mode": "smart" } +} + +// worker-weekly.jsonc +{ + "name": "cleanup-weekly", + "triggers": { "crons": ["0 3 * * SUN"] } +} +``` + +**Benefits:** +- Separate CPU limits per worker +- Independent error isolation +- Different Green Compute policies +- Easier to maintain and debug + +## Validation + +**Test cron syntax:** +- [crontab.guru](https://crontab.guru/) - Interactive validator +- Wrangler validates on deploy but won't catch logic errors + +**Common mistakes:** +- `0 0 * * *` runs daily at midnight UTC, not your local timezone +- `*/60 * * * *` is invalid (use `0 * * * *` for hourly) +- `0 2 31 * *` only runs on months with 31 days + +## See Also + +- [README.md](./README.md) - Overview, quick start +- [api.md](./api.md) - Handler implementation +- [patterns.md](./patterns.md) - Multi-cron routing examples diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..0278c06174ac7532ed3287089095b6df909bb15c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/gotchas.md @@ -0,0 +1,199 @@ +# Cron Triggers Gotchas + +## Common Errors + +### "Timezone Issues" + +**Problem:** Cron runs at wrong time relative to local timezone +**Cause:** All crons execute in UTC, no local timezone support +**Solution:** Convert local time to UTC manually + +**Conversion formula:** `utcHour = (localHour - utcOffset + 24) % 24` + +**Examples:** +- 9am PST (UTC-8) → `(9 - (-8) + 24) % 24 = 17` → `0 17 * * *` +- 2am EST (UTC-5) → `(2 - (-5) + 24) % 24 = 7` → `0 7 * * *` +- 6pm JST (UTC+9) → `(18 - 9 + 24) % 24 = 33 % 24 = 9` → `0 9 * * *` + +**Daylight Saving Time:** Adjust manually when DST changes, or schedule at times unaffected by DST (e.g., 2am-4am local time usually safe) + +### "Cron Not Executing" + +**Cause:** Missing `scheduled()` export, invalid syntax, propagation delay (<15min), or plan limits +**Solution:** Verify export exists, validate at crontab.guru, wait 15+ min after deploy, check plan limits + +### "Duplicate Executions" + +**Cause:** At-least-once delivery +**Solution:** Track execution IDs in KV - see idempotency pattern below + +### "Execution Failures" + +**Cause:** CPU exceeded, unhandled exceptions, network timeouts, binding errors +**Solution:** Use try-catch, AbortController timeouts, `ctx.waitUntil()` for long ops, or Workflows for heavy tasks + +### "Local Testing Not Working" + +**Problem:** `/__scheduled` endpoint returns 404 or doesn't trigger handler +**Cause:** Missing `scheduled()` export, wrangler not running, or incorrect endpoint format +**Solution:** + +1. Verify `scheduled()` is exported: +```typescript +export default { + async scheduled(controller, env, ctx) { + console.log("Cron triggered"); + }, +}; +``` + +2. Start dev server: +```bash +npx wrangler dev +``` + +3. Use correct endpoint format (URL-encode spaces as `+`): +```bash +# Correct +curl "http://localhost:8787/__scheduled?cron=*/5+*+*+*+*" + +# Wrong (will fail) +curl "http://localhost:8787/__scheduled?cron=*/5 * * * *" +``` + +4. Update Wrangler if outdated: +```bash +npm install -g wrangler@latest +``` + +### "waitUntil() Tasks Not Completing" + +**Problem:** Background tasks in `ctx.waitUntil()` fail silently or don't execute +**Cause:** Promises rejected without error handling, or handler returns before promise settles +**Solution:** Always await or handle errors in waitUntil promises: + +```typescript +export default { + async scheduled(controller, env, ctx) { + // BAD: Silent failures + ctx.waitUntil(riskyOperation()); + + // GOOD: Explicit error handling + ctx.waitUntil( + riskyOperation().catch(err => { + console.error("Background task failed:", err); + return logError(err, env); + }) + ); + }, +}; +``` + +### "Idempotency Issues" + +**Problem:** At-least-once delivery causes duplicate side effects (double charges, duplicate emails) +**Cause:** No deduplication mechanism +**Solution:** Use KV to track execution IDs: + +```typescript +export default { + async scheduled(controller, env, ctx) { + const executionId = `${controller.cron}-${controller.scheduledTime}`; + const existing = await env.EXECUTIONS.get(executionId); + + if (existing) { + console.log("Already executed, skipping"); + controller.noRetry(); + return; + } + + await env.EXECUTIONS.put(executionId, "1", { expirationTtl: 86400 }); // 24h TTL + await performIdempotentOperation(env); + }, +}; +``` + +### "Security Concerns" + +**Problem:** `__scheduled` endpoint exposed in production allows unauthorized cron triggering +**Cause:** Testing endpoint available in deployed Workers +**Solution:** Block `__scheduled` in production: + +```typescript +export default { + async fetch(request, env, ctx) { + const url = new URL(request.url); + + // Block __scheduled in production + if (url.pathname === "/__scheduled" && env.ENVIRONMENT === "production") { + return new Response("Not Found", { status: 404 }); + } + + return handleRequest(request, env, ctx); + }, + + async scheduled(controller, env, ctx) { + // Your cron logic + }, +}; +``` + +**Also:** Use `env.API_KEY` for secrets (never hardcode) + +**Alternative:** Add middleware to verify request origin: +```typescript +export default { + async fetch(request, env, ctx) { + const url = new URL(request.url); + + if (url.pathname === "/__scheduled") { + // Check Cloudflare headers to verify internal request + const cfRay = request.headers.get("cf-ray"); + if (!cfRay && env.ENVIRONMENT === "production") { + return new Response("Not Found", { status: 404 }); + } + } + + return handleRequest(request, env, ctx); + }, + + async scheduled(controller, env, ctx) { + // Your cron logic + }, +}; +``` + +## Limits & Quotas + +| Limit | Free | Paid | Notes | +|-------|------|------|-------| +| Triggers per Worker | 3 | Unlimited | Maximum cron schedules per Worker | +| CPU time | 10ms | 50ms | May need `ctx.waitUntil()` or Workflows | +| Execution guarantee | At-least-once | At-least-once | Duplicates possible - use idempotency | +| Propagation delay | Up to 15 minutes | Up to 15 minutes | Time for changes to take effect globally | +| Min interval | 1 minute | 1 minute | Cannot schedule more frequently | +| Cron accuracy | ±1 minute | ±1 minute | Execution may drift slightly | + +## Testing Best Practices + +**Unit tests:** +- Mock `ScheduledController`, `ExecutionContext`, and bindings +- Test each cron expression separately +- Verify `noRetry()` is called when expected +- Use Vitest with `@cloudflare/vitest-pool-workers` for realistic env + +**Integration tests:** +- Test via `/__scheduled` endpoint in dev environment +- Verify idempotency logic with duplicate `scheduledTime` values +- Test error handling and retry behavior + +**Production:** Start with long intervals (`*/30 * * * *`), monitor Cron Events for 24h, set up alerts before reducing interval + +## Resources + +- [Cron Triggers Docs](https://developers.cloudflare.com/workers/configuration/cron-triggers/) +- [Scheduled Handler API](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/) +- [Cloudflare Workflows](https://developers.cloudflare.com/workflows/) +- [Workers Limits](https://developers.cloudflare.com/workers/platform/limits/) +- [Crontab Guru](https://crontab.guru/) - Validator +- [Vitest Pool Workers](https://github.com/cloudflare/workers-sdk/tree/main/fixtures/vitest-pool-workers-examples) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..b48477df991fcf86035ee0ae312196710881340d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/cron-triggers/patterns.md @@ -0,0 +1,190 @@ +# Cron Triggers Patterns + +## API Data Sync + +```typescript +export default { + async scheduled(controller, env, ctx) { + const response = await fetch("https://api.example.com/data", {headers: { "Authorization": `Bearer ${env.API_KEY}` }}); + if (!response.ok) throw new Error(`API error: ${response.status}`); + ctx.waitUntil(env.MY_KV.put("cached_data", JSON.stringify(await response.json()), {expirationTtl: 3600})); + }, +}; +``` + +## Database Cleanup + +```typescript +export default { + async scheduled(controller, env, ctx) { + const result = await env.DB.prepare(`DELETE FROM sessions WHERE expires_at < datetime('now')`).run(); + console.log(`Deleted ${result.meta.changes} expired sessions`); + ctx.waitUntil(env.DB.prepare("VACUUM").run()); + }, +}; +``` + +## Report Generation + +```typescript +export default { + async scheduled(controller, env, ctx) { + const startOfWeek = new Date(); startOfWeek.setDate(startOfWeek.getDate() - 7); + const { results } = await env.DB.prepare(`SELECT date, revenue, orders FROM daily_stats WHERE date >= ? ORDER BY date`).bind(startOfWeek.toISOString()).all(); + const report = {period: "weekly", totalRevenue: results.reduce((sum, d) => sum + d.revenue, 0), totalOrders: results.reduce((sum, d) => sum + d.orders, 0), dailyBreakdown: results}; + const reportKey = `reports/weekly-${Date.now()}.json`; + await env.REPORTS_BUCKET.put(reportKey, JSON.stringify(report)); + ctx.waitUntil(env.SEND_EMAIL.fetch("https://example.com/send", {method: "POST", body: JSON.stringify({to: "team@example.com", subject: "Weekly Report", reportUrl: `https://reports.example.com/${reportKey}`})})); + }, +}; +``` + +## Health Checks + +```typescript +export default { + async scheduled(controller, env, ctx) { + const services = [{name: "API", url: "https://api.example.com/health"}, {name: "CDN", url: "https://cdn.example.com/health"}]; + const checks = await Promise.all(services.map(async (service) => { + const start = Date.now(); + try { + const response = await fetch(service.url, { signal: AbortSignal.timeout(5000) }); + return {name: service.name, status: response.ok ? "up" : "down", responseTime: Date.now() - start}; + } catch (error) { + return {name: service.name, status: "down", responseTime: Date.now() - start, error: error.message}; + } + })); + ctx.waitUntil(env.STATUS_KV.put("health_status", JSON.stringify(checks))); + const failures = checks.filter(c => c.status === "down"); + if (failures.length > 0) ctx.waitUntil(fetch(env.ALERT_WEBHOOK, {method: "POST", body: JSON.stringify({text: `${failures.length} service(s) down: ${failures.map(f => f.name).join(", ")}`})})); + }, +}; +``` + +## Batch Processing (Rate-Limited) + +```typescript +export default { + async scheduled(controller, env, ctx) { + const queueData = await env.QUEUE_KV.get("pending_items", "json"); + if (!queueData || queueData.length === 0) return; + const batch = queueData.slice(0, 100); + const results = await Promise.allSettled(batch.map(item => fetch("https://api.example.com/process", {method: "POST", headers: {"Authorization": `Bearer ${env.API_KEY}`, "Content-Type": "application/json"}, body: JSON.stringify(item)}))); + console.log(`Processed ${results.filter(r => r.status === "fulfilled").length}/${batch.length} items`); + ctx.waitUntil(env.QUEUE_KV.put("pending_items", JSON.stringify(queueData.slice(100)))); + }, +}; +``` + +## Queue Integration + +```typescript +export default { + async scheduled(controller, env, ctx) { + const batch = await env.MY_QUEUE.receive({ batchSize: 100 }); + const results = await Promise.allSettled(batch.messages.map(async (msg) => { + await processMessage(msg.body, env); + await msg.ack(); + })); + console.log(`Processed ${results.filter(r => r.status === "fulfilled").length}/${batch.messages.length}`); + }, +}; +``` + +## Monitoring & Observability + +```typescript +export default { + async scheduled(controller, env, ctx) { + const startTime = Date.now(); + const meta = { cron: controller.cron, scheduledTime: controller.scheduledTime }; + console.log("[START]", meta); + try { + const result = await performTask(env); + console.log("[SUCCESS]", { ...meta, duration: Date.now() - startTime, count: result.count }); + ctx.waitUntil(env.METRICS.put(`cron:${controller.scheduledTime}`, JSON.stringify({ ...meta, status: "success" }), { expirationTtl: 2592000 })); + } catch (error) { + console.error("[ERROR]", { ...meta, duration: Date.now() - startTime, error: error.message }); + ctx.waitUntil(fetch(env.ALERT_WEBHOOK, { method: "POST", body: JSON.stringify({ text: `Cron failed: ${controller.cron}`, error: error.message }) })); + throw error; + } + }, +}; +``` + +**View logs:** `npx wrangler tail` or Dashboard → Workers & Pages → Worker → Logs + +## Durable Objects Coordination + +```typescript +export default { + async scheduled(controller, env, ctx) { + const stub = env.COORDINATOR.get(env.COORDINATOR.idFromName("cron-lock")); + const acquired = await stub.tryAcquireLock(controller.scheduledTime); + if (!acquired) { + controller.noRetry(); + return; + } + try { + await performTask(env); + } finally { + await stub.releaseLock(); + } + }, +}; +``` + +## Python Handler + +```python +from workers import WorkerEntrypoint + +class Default(WorkerEntrypoint): + async def scheduled(self, controller, env, ctx): + data = await env.MY_KV.get("key") + ctx.waitUntil(env.DB.execute("DELETE FROM logs WHERE created_at < datetime('now', '-7 days')")) +``` + +## Testing Patterns + +**Local testing with /__scheduled:** +```bash +# Start dev server +npx wrangler dev + +# Test specific cron +curl "http://localhost:8787/__scheduled?cron=*/5+*+*+*+*" + +# Test with specific time +curl "http://localhost:8787/__scheduled?cron=0+2+*+*+*&scheduledTime=1704067200000" +``` + +**Unit tests:** +```typescript +// test/scheduled.test.ts +import { describe, it, expect, vi } from "vitest"; +import { env } from "cloudflare:test"; +import worker from "../src/index"; + +describe("Scheduled Handler", () => { + it("executes cron", async () => { + const controller = { scheduledTime: Date.now(), cron: "*/5 * * * *", type: "scheduled" as const, noRetry: vi.fn() }; + const ctx = { waitUntil: vi.fn(), passThroughOnException: vi.fn() }; + await worker.scheduled(controller, env, ctx); + expect(await env.MY_KV.get("last_run")).toBeDefined(); + }); + + it("calls noRetry on duplicate", async () => { + const controller = { scheduledTime: 1704067200000, cron: "0 2 * * *", type: "scheduled" as const, noRetry: vi.fn() }; + await env.EXECUTIONS.put("0 2 * * *-1704067200000", "1"); + await worker.scheduled(controller, env, { waitUntil: vi.fn(), passThroughOnException: vi.fn() }); + expect(controller.noRetry).toHaveBeenCalled(); + }); +}); +``` + +## See Also + +- [README.md](./README.md) - Overview +- [api.md](./api.md) - Handler implementation +- [gotchas.md](./gotchas.md) - Troubleshooting diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e40d44c1d8e4630383754b65f8080c8c7afeab4e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/README.md @@ -0,0 +1,133 @@ +# Cloudflare D1 Database + +Expert guidance for Cloudflare D1, a serverless SQLite database designed for horizontal scale-out across multiple databases. + +## Overview + +D1 is Cloudflare's managed, serverless database with: +- SQLite SQL semantics and compatibility +- Built-in disaster recovery via Time Travel (30-day point-in-time recovery) +- Horizontal scale-out architecture (10 GB per database) +- Worker and HTTP API access +- Pricing based on query and storage costs only + +**Architecture Philosophy**: D1 is optimized for per-user, per-tenant, or per-entity database patterns rather than single large databases. + +## Quick Start + +```bash +# Create database +wrangler d1 create + +# Execute migration +wrangler d1 migrations apply --remote + +# Local development +wrangler dev +``` + +## Core Query Methods + +```typescript +// .all() - Returns all rows; .first() - First row or null; .first(col) - Single column value +// .run() - INSERT/UPDATE/DELETE; .raw() - Array of arrays (efficient) +const { results, success, meta } = await env.DB.prepare('SELECT * FROM users WHERE active = ?').bind(true).all(); +const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first(); +``` + +## Batch Operations + +```typescript +// Multiple queries in single round trip (atomic transaction) +const results = await env.DB.batch([ + env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(1), + env.DB.prepare('SELECT * FROM posts WHERE author_id = ?').bind(1), + env.DB.prepare('UPDATE users SET last_access = ? WHERE id = ?').bind(Date.now(), 1) +]); +``` + +## Sessions API (Paid Plans) + +```typescript +// Create long-running session for analytics/migrations (up to 15 minutes) +const session = env.DB.withSession(); +try { + await session.prepare('CREATE INDEX idx_heavy ON large_table(column)').run(); + await session.prepare('ANALYZE').run(); +} finally { + session.close(); // Always close to release resources +} +``` + +## Read Replication (Paid Plans) + +```typescript +// Read from nearest replica for lower latency (automatic failover) +const user = await env.DB_REPLICA.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first(); + +// Writes always go to primary +await env.DB.prepare('UPDATE users SET last_login = ? WHERE id = ?').bind(Date.now(), userId).run(); +``` + +## Platform Limits + +| Limit | Free Tier | Paid Plans | +|-------|-----------|------------| +| Database size | 500 MB | 10 GB per database | +| Row size | 1 MB max | 1 MB max | +| Query timeout | 30 seconds | 30 seconds | +| Batch size | 1,000 statements | 10,000 statements | +| Time Travel retention | 7 days | 30 days | +| Read replicas | Not available | Yes (paid add-on) | + +**Pricing**: $5/month per database beyond free tier + $0.001 per 1K reads + $1 per 1M writes + $0.75/GB storage/month + +## CLI Commands + +```bash +# Database management +wrangler d1 create +wrangler d1 list +wrangler d1 delete + +# Migrations +wrangler d1 migrations create # Create new migration file +wrangler d1 migrations apply --remote # Apply pending migrations +wrangler d1 migrations apply --local # Apply locally +wrangler d1 migrations list --remote # Show applied migrations + +# Direct SQL execution +wrangler d1 execute --remote --command="SELECT * FROM users" +wrangler d1 execute --local --file=./schema.sql + +# Backups & Import/Export +wrangler d1 export --remote --output=./backup.sql # Full export with schema +wrangler d1 export --remote --no-schema --output=./data.sql # Data only +wrangler d1 time-travel restore --timestamp="2024-01-15T14:30:00Z" # Point-in-time recovery + +# Development +wrangler dev --persist-to=./.wrangler/state +``` + +## Reading Order + +**Start here**: Quick Start above → configuration.md (setup) → api.md (queries) + +**Common tasks**: +- First time setup: configuration.md → Run migrations +- Adding queries: api.md → Prepared statements +- Pagination/caching: patterns.md +- Production optimization: Read Replication + Sessions API (this file) +- Debugging: gotchas.md + +## In This Reference + +- [configuration.md](./configuration.md) - wrangler.jsonc setup, migrations, TypeScript types, ORMs, local dev +- [api.md](./api.md) - Query methods (.all/.first/.run/.raw), batch, sessions, read replicas, error handling +- [patterns.md](./patterns.md) - Pagination, bulk operations, caching, multi-tenant, sessions, analytics +- [gotchas.md](./gotchas.md) - SQL injection, limits by plan tier, performance, common errors + +## See Also + +- [workers](../workers/) - Worker runtime and fetch handler patterns +- [hyperdrive](../hyperdrive/) - Connection pooling for external databases diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/api.md new file mode 100644 index 0000000000000000000000000000000000000000..b3c26de7b54c358279632884933bb8d75c4c7f03 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/api.md @@ -0,0 +1,196 @@ +# D1 API Reference + +## Prepared Statements (Required for Security) + +```typescript +// ❌ NEVER: Direct string interpolation (SQL injection risk) +const result = await env.DB.prepare(`SELECT * FROM users WHERE id = ${userId}`).all(); + +// ✅ CORRECT: Prepared statements with bind() +const result = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).all(); + +// Multiple parameters +const result = await env.DB.prepare('SELECT * FROM users WHERE email = ? AND active = ?').bind(email, true).all(); +``` + +## Query Execution Methods + +```typescript +// .all() - Returns all rows +const { results, success, meta } = await env.DB.prepare('SELECT * FROM users WHERE active = ?').bind(true).all(); +// results: Array of row objects; success: boolean +// meta: { duration: number, rows_read: number, rows_written: number } + +// .first() - Returns first row or null +const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first(); + +// .first(columnName) - Returns single column value +const email = await env.DB.prepare('SELECT email FROM users WHERE id = ?').bind(userId).first('email'); +// Returns string | number | null + +// .run() - For INSERT/UPDATE/DELETE (no row data returned) +const result = await env.DB.prepare('UPDATE users SET last_login = ? WHERE id = ?').bind(Date.now(), userId).run(); +// result.meta: { duration, rows_read, rows_written, last_row_id, changes } + +// .raw() - Returns array of arrays (efficient for large datasets) +const rawResults = await env.DB.prepare('SELECT id, name FROM users').raw(); +// [[1, 'Alice'], [2, 'Bob']] +``` + +## Batch Operations + +```typescript +// Execute multiple queries in single round trip (atomic transaction) +const results = await env.DB.batch([ + env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(1), + env.DB.prepare('SELECT * FROM posts WHERE author_id = ?').bind(1), + env.DB.prepare('UPDATE users SET last_access = ? WHERE id = ?').bind(Date.now(), 1) +]); +// results is array: [result1, result2, result3] + +// Batch with same prepared statement, different params +const userIds = [1, 2, 3]; +const stmt = env.DB.prepare('SELECT * FROM users WHERE id = ?'); +const results = await env.DB.batch(userIds.map(id => stmt.bind(id))); +``` + +## Transactions (via batch) + +```typescript +// D1 executes batch() as atomic transaction - all succeed or all fail +const results = await env.DB.batch([ + env.DB.prepare('INSERT INTO accounts (id, balance) VALUES (?, ?)').bind(1, 100), + env.DB.prepare('INSERT INTO accounts (id, balance) VALUES (?, ?)').bind(2, 200), + env.DB.prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?').bind(50, 1), + env.DB.prepare('UPDATE accounts SET balance = balance + ? WHERE id = ?').bind(50, 2) +]); +``` + +## Sessions API (Paid Plans) + +Long-running sessions for operations exceeding 30s timeout (up to 15 min). + +```typescript +const session = env.DB.withSession({ timeout: 600 }); // 10 min (1-900s) +try { + await session.prepare('CREATE INDEX idx_large ON big_table(column)').run(); + await session.prepare('ANALYZE').run(); +} finally { + session.close(); // CRITICAL: always close to prevent leaks +} +``` + +**Use cases**: Migrations, ANALYZE, large index creation, bulk transformations + +## Read Replication (Paid Plans) + +Routes queries to nearest replica for lower latency. Writes always go to primary. + +```typescript +interface Env { + DB: D1Database; // Primary (writes) + DB_REPLICA: D1Database; // Replica (reads) +} + +// Reads: use replica +const user = await env.DB_REPLICA.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first(); + +// Writes: use primary +await env.DB.prepare('UPDATE users SET last_login = ? WHERE id = ?').bind(Date.now(), userId).run(); + +// Read-after-write: use primary for consistency (replication lag <100ms-2s) +await env.DB.prepare('INSERT INTO posts (title) VALUES (?)').bind(title).run(); +const post = await env.DB.prepare('SELECT * FROM posts WHERE title = ?').bind(title).first(); // Primary +``` + +## Error Handling + +```typescript +async function getUser(userId: number, env: Env): Promise { + try { + const result = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).all(); + if (!result.success) return new Response('Database error', { status: 500 }); + if (result.results.length === 0) return new Response('User not found', { status: 404 }); + return Response.json(result.results[0]); + } catch (error) { + return new Response('Internal error', { status: 500 }); + } +} + +// Constraint violations +try { + await env.DB.prepare('INSERT INTO users (email, name) VALUES (?, ?)').bind(email, name).run(); +} catch (error) { + if (error.message?.includes('UNIQUE constraint failed')) return new Response('Email exists', { status: 409 }); + throw error; +} +``` + +## REST API (HTTP) Access + +Access D1 from external services (non-Worker contexts) using Cloudflare API. + +```typescript +// Single query +const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/d1/database/${DATABASE_ID}/query`, + { + method: 'POST', + headers: { + 'Authorization': `Bearer ${CLOUDFLARE_API_TOKEN}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + sql: 'SELECT * FROM users WHERE id = ?', + params: [userId] + }) + } +); + +const { result, success, errors } = await response.json(); +// result: [{ results: [...], success: true, meta: {...} }] + +// Batch queries via HTTP +const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/d1/database/${DATABASE_ID}/query`, + { + method: 'POST', + headers: { + 'Authorization': `Bearer ${CLOUDFLARE_API_TOKEN}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify([ + { sql: 'SELECT * FROM users WHERE id = ?', params: [1] }, + { sql: 'SELECT * FROM posts WHERE author_id = ?', params: [1] } + ]) + } +); +``` + +**Use cases**: Server-side scripts, CI/CD migrations, administrative tools, non-Worker integrations + +## Testing & Debugging + +```typescript +// Vitest with unstable_dev +import { unstable_dev } from 'wrangler'; +describe('D1', () => { + let worker: Awaited>; + beforeAll(async () => { worker = await unstable_dev('src/index.ts'); }); + afterAll(async () => { await worker.stop(); }); + it('queries users', async () => { expect((await worker.fetch('/users')).status).toBe(200); }); +}); + +// Debug query performance +const result = await env.DB.prepare('SELECT * FROM users').all(); +console.log('Duration:', result.meta.duration, 'ms'); + +// Query plan analysis +const plan = await env.DB.prepare('EXPLAIN QUERY PLAN SELECT * FROM users WHERE email = ?').bind(email).all(); +``` + +```bash +# Inspect local database +sqlite3 .wrangler/state/v3/d1/.sqlite +.tables; .schema users; PRAGMA table_info(users); +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..8a073fc731a7a81ca97d808d3e8774ff5612a3c0 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/configuration.md @@ -0,0 +1,188 @@ +# D1 Configuration + +## wrangler.jsonc Setup + +```jsonc +{ + "name": "your-worker-name", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", // Use current date for new projects + "d1_databases": [ + { + "binding": "DB", // Env variable name + "database_name": "your-db-name", // Human-readable name + "database_id": "your-database-id", // UUID from dashboard/CLI + "migrations_dir": "migrations" // Optional: default is "migrations" + }, + // Read replica (paid plans only) + { + "binding": "DB_REPLICA", + "database_name": "your-db-name", + "database_id": "your-database-id" // Same ID, different binding + }, + // Multiple databases + { + "binding": "ANALYTICS_DB", + "database_name": "analytics-db", + "database_id": "yyy-yyy-yyy" + } + ] +} +``` + +## TypeScript Types + +```typescript +interface Env { DB: D1Database; ANALYTICS_DB?: D1Database; } + +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const result = await env.DB.prepare('SELECT * FROM users').all(); + return Response.json(result.results); + } +} +``` + +## Migrations + +File structure: `migrations/0001_initial_schema.sql`, `0002_add_posts.sql`, etc. + +### Example Migration + +```sql +-- migrations/0001_initial_schema.sql +CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + email TEXT UNIQUE NOT NULL, + name TEXT NOT NULL, + created_at TEXT DEFAULT CURRENT_TIMESTAMP, + updated_at TEXT DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_users_email ON users(email); + +CREATE TABLE IF NOT EXISTS posts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + title TEXT NOT NULL, + content TEXT, + published BOOLEAN DEFAULT 0, + created_at TEXT DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); + +CREATE INDEX idx_posts_user_id ON posts(user_id); +CREATE INDEX idx_posts_published ON posts(published); +``` + +### Running Migrations + +```bash +# Create new migration file +wrangler d1 migrations create add_users_table +# Creates: migrations/0001_add_users_table.sql + +# Apply migrations +wrangler d1 migrations apply --local # Apply to local DB +wrangler d1 migrations apply --remote # Apply to production DB + +# List applied migrations +wrangler d1 migrations list --remote + +# Direct SQL execution (bypasses migration tracking) +wrangler d1 execute --remote --command="SELECT * FROM users" +wrangler d1 execute --local --file=./schema.sql +``` + +**Migration tracking**: Wrangler creates `d1_migrations` table automatically to track applied migrations + +## Indexing Strategy + +```sql +-- Index frequently queried columns +CREATE INDEX idx_users_email ON users(email); + +-- Composite indexes for multi-column queries +CREATE INDEX idx_posts_user_published ON posts(user_id, published); + +-- Covering indexes (include queried columns) +CREATE INDEX idx_users_email_name ON users(email, name); + +-- Partial indexes for filtered queries +CREATE INDEX idx_active_users ON users(email) WHERE active = 1; + +-- Check if query uses index +EXPLAIN QUERY PLAN SELECT * FROM users WHERE email = ?; +``` + +## Drizzle ORM + +```typescript +// drizzle.config.ts +export default { + schema: './src/schema.ts', out: './migrations', dialect: 'sqlite', driver: 'd1-http', + dbCredentials: { accountId: process.env.CLOUDFLARE_ACCOUNT_ID!, databaseId: process.env.D1_DATABASE_ID!, token: process.env.CLOUDFLARE_API_TOKEN! } +} satisfies Config; + +// schema.ts +import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'; +export const users = sqliteTable('users', { + id: integer('id').primaryKey({ autoIncrement: true }), + email: text('email').notNull().unique(), + name: text('name').notNull() +}); + +// worker.ts +import { drizzle } from 'drizzle-orm/d1'; +import { users } from './schema'; +export default { + async fetch(request: Request, env: Env) { + const db = drizzle(env.DB); + return Response.json(await db.select().from(users)); + } +} +``` + +## Import & Export + +```bash +# Export full database (schema + data) +wrangler d1 export --remote --output=./backup.sql + +# Export data only (no schema) +wrangler d1 export --remote --no-schema --output=./data-only.sql + +# Export with foreign key constraints preserved +# (Default: foreign keys are disabled during export for import compatibility) + +# Import SQL file +wrangler d1 execute --remote --file=./backup.sql + +# Limitations +# - BLOB data may not export correctly (use R2 for binary files) +# - Very large exports (>1GB) may timeout (split into chunks) +# - Import is NOT atomic (use batch() for transactional imports in Workers) +``` + +## Plan Tiers + +| Feature | Free | Paid | +|---------|------|------| +| Database size | 500 MB | 10 GB | +| Batch size | 1,000 statements | 10,000 statements | +| Time Travel | 7 days | 30 days | +| Read replicas | ❌ | ✅ | +| Sessions API | ❌ | ✅ (up to 15 min) | +| Pricing | Free | $5/mo + usage | + +**Usage pricing** (paid plans): $0.001 per 1K reads + $1 per 1M writes + $0.75/GB storage/month + +## Local Development + +```bash +wrangler dev --persist-to=./.wrangler/state # Persist across restarts +# Local DB: .wrangler/state/v3/d1/.sqlite +sqlite3 .wrangler/state/v3/d1/.sqlite # Inspect + +# Local dev uses free tier limits by default +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..49771b76af484d76f23591ec3ad3ffbd6c4f53f2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/gotchas.md @@ -0,0 +1,98 @@ +# D1 Gotchas & Troubleshooting + +## Common Errors + +### "SQL Injection Vulnerability" + +**Cause:** Using string interpolation instead of prepared statements with bind() +**Solution:** ALWAYS use prepared statements: `env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).all()` instead of string interpolation which allows attackers to inject malicious SQL + +### "no such table" + +**Cause:** Table doesn't exist because migrations haven't been run, or using wrong database binding +**Solution:** Run migrations using `wrangler d1 migrations apply --remote` and verify binding name in wrangler.jsonc matches code + +### "UNIQUE constraint failed" + +**Cause:** Attempting to insert duplicate value in column with UNIQUE constraint +**Solution:** Catch error and return 409 Conflict status code + +### "Query Timeout (30s exceeded)" + +**Cause:** Query execution exceeds 30 second timeout limit +**Solution:** Break into smaller queries, add indexes to speed up queries, or reduce dataset size + +### "N+1 Query Problem" + +**Cause:** Making multiple individual queries in a loop instead of single optimized query +**Solution:** Use JOIN to fetch related data in single query or use `batch()` method for multiple queries + +### "Missing Indexes" + +**Cause:** Queries performing full table scans without indexes +**Solution:** Use `EXPLAIN QUERY PLAN` to check if index is used, then create index with `CREATE INDEX idx_users_email ON users(email)` + +### "Boolean Type Issues" + +**Cause:** SQLite uses INTEGER (0/1) not native boolean type +**Solution:** Bind 1 or 0 instead of true/false when working with boolean values + +### "Date/Time Type Issues" + +**Cause:** SQLite doesn't have native DATE/TIME types +**Solution:** Use TEXT (ISO 8601 format) or INTEGER (unix timestamp) for date/time values + +## Plan Tier Limits + +| Limit | Free Tier | Paid Plans | Notes | +|-------|-----------|------------|-------| +| Database size | 500 MB | 10 GB | Design for multiple DBs per tenant on paid | +| Row size | 1 MB | 1 MB | Store large files in R2, not D1 | +| Query timeout | 30s | 30s (900s with sessions) | Use sessions API for migrations | +| Batch size | 1,000 statements | 10,000 statements | Split large batches accordingly | +| Time Travel | 7 days | 30 days | Point-in-time recovery window | +| Read replicas | ❌ Not available | ✅ Available | Paid add-on for lower latency | +| Sessions API | ❌ Not available | ✅ Up to 15 min | For migrations and heavy operations | +| Concurrent requests | 10,000/min | Higher | Contact support for custom limits | + +## Production Gotchas + +### "Batch size exceeded" + +**Cause:** Attempting to send >1,000 statements on free tier or >10,000 on paid +**Solution:** Chunk batches: `for (let i = 0; i < stmts.length; i += MAX_BATCH) await env.DB.batch(stmts.slice(i, i + MAX_BATCH))` + +### "Session not closed / resource leak" + +**Cause:** Forgot to call `session.close()` after using sessions API +**Solution:** Always use try/finally block: `try { await session.prepare(...) } finally { session.close() }` + +### "Replication lag causing stale reads" + +**Cause:** Reading from replica immediately after write - replication lag can be 100ms-2s +**Solution:** Use primary for read-after-write: `await env.DB.prepare(...)` not `env.DB_REPLICA` + +### "Migration applied to local but not remote" + +**Cause:** Forgot `--remote` flag when applying migrations +**Solution:** Always run `wrangler d1 migrations apply --remote` for production + +### "Foreign key constraint failed" + +**Cause:** Inserting row with FK to non-existent parent, or deleting parent before children +**Solution:** Enable FK enforcement: `PRAGMA foreign_keys = ON;` and use ON DELETE CASCADE in schema + +### "BLOB data corrupted on export" + +**Cause:** D1 export may not handle BLOB correctly +**Solution:** Store binary files in R2, only store R2 URLs/keys in D1 + +### "Database size approaching limit" + +**Cause:** Storing too much data in single database +**Solution:** Horizontal scale-out: create per-tenant/per-user databases, archive old data, or upgrade to paid plan + +### "Local dev vs production behavior differs" + +**Cause:** Local uses SQLite file, production uses distributed D1 - different performance/limits +**Solution:** Always test migrations on remote with `--remote` flag before production rollout diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..d5624f3f96e1645d65e3ee923f7cc07ff5802937 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/d1/patterns.md @@ -0,0 +1,189 @@ +# D1 Patterns & Best Practices + +## Pagination + +```typescript +async function getUsers({ page, pageSize }: { page: number; pageSize: number }, env: Env) { + const offset = (page - 1) * pageSize; + const [countResult, dataResult] = await env.DB.batch([ + env.DB.prepare('SELECT COUNT(*) as total FROM users'), + env.DB.prepare('SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?').bind(pageSize, offset) + ]); + return { data: dataResult.results, total: countResult.results[0].total, page, pageSize, totalPages: Math.ceil(countResult.results[0].total / pageSize) }; +} +``` + +## Conditional Queries + +```typescript +async function searchUsers(filters: { name?: string; email?: string; active?: boolean }, env: Env) { + const conditions: string[] = [], params: (string | number | boolean | null)[] = []; + if (filters.name) { conditions.push('name LIKE ?'); params.push(`%${filters.name}%`); } + if (filters.email) { conditions.push('email = ?'); params.push(filters.email); } + if (filters.active !== undefined) { conditions.push('active = ?'); params.push(filters.active ? 1 : 0); } + const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''; + return await env.DB.prepare(`SELECT * FROM users ${whereClause}`).bind(...params).all(); +} +``` + +## Bulk Insert + +```typescript +async function bulkInsertUsers(users: Array<{ name: string; email: string }>, env: Env) { + const stmt = env.DB.prepare('INSERT INTO users (name, email) VALUES (?, ?)'); + const batch = users.map(user => stmt.bind(user.name, user.email)); + return await env.DB.batch(batch); +} +``` + +## Caching with KV + +```typescript +async function getCachedUser(userId: number, env: { DB: D1Database; CACHE: KVNamespace }) { + const cacheKey = `user:${userId}`; + const cached = await env.CACHE?.get(cacheKey, 'json'); + if (cached) return cached; + const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first(); + if (user) await env.CACHE?.put(cacheKey, JSON.stringify(user), { expirationTtl: 300 }); + return user; +} +``` + +## Query Optimization + +```typescript +// ✅ Use indexes in WHERE clauses +const users = await env.DB.prepare('SELECT * FROM users WHERE email = ?').bind(email).all(); + +// ✅ Limit result sets +const recentPosts = await env.DB.prepare('SELECT * FROM posts ORDER BY created_at DESC LIMIT 100').all(); + +// ✅ Use batch() for multiple independent queries +const [user, posts, comments] = await env.DB.batch([ + env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId), + env.DB.prepare('SELECT * FROM posts WHERE user_id = ?').bind(userId), + env.DB.prepare('SELECT * FROM comments WHERE user_id = ?').bind(userId) +]); + +// ❌ Avoid N+1 queries +for (const post of posts) { + const author = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(post.user_id).first(); // Bad: multiple round trips +} + +// ✅ Use JOINs instead +const postsWithAuthors = await env.DB.prepare(` + SELECT posts.*, users.name as author_name + FROM posts + JOIN users ON posts.user_id = users.id +`).all(); +``` + +## Multi-Tenant SaaS + +```typescript +// Each tenant gets own database +export default { + async fetch(request: Request, env: { [key: `TENANT_${string}`]: D1Database }) { + const tenantId = request.headers.get('X-Tenant-ID'); + const data = await env[`TENANT_${tenantId}`].prepare('SELECT * FROM records').all(); + return Response.json(data.results); + } +} +``` + +## Session Storage + +```typescript +async function createSession(userId: number, token: string, env: Env) { + const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(); + return await env.DB.prepare('INSERT INTO sessions (user_id, token, expires_at) VALUES (?, ?, ?)').bind(userId, token, expiresAt).run(); +} + +async function validateSession(token: string, env: Env) { + return await env.DB.prepare('SELECT s.*, u.email FROM sessions s JOIN users u ON s.user_id = u.id WHERE s.token = ? AND s.expires_at > CURRENT_TIMESTAMP').bind(token).first(); +} +``` + +## Analytics/Events + +```typescript +async function logEvent(event: { type: string; userId?: number; metadata: object }, env: Env) { + return await env.DB.prepare('INSERT INTO events (type, user_id, metadata) VALUES (?, ?, ?)').bind(event.type, event.userId || null, JSON.stringify(event.metadata)).run(); +} + +async function getEventStats(startDate: string, endDate: string, env: Env) { + return await env.DB.prepare('SELECT type, COUNT(*) as count FROM events WHERE timestamp BETWEEN ? AND ? GROUP BY type ORDER BY count DESC').bind(startDate, endDate).all(); +} +``` + +## Read Replication Pattern (Paid Plans) + +```typescript +interface Env { DB: D1Database; DB_REPLICA: D1Database; } + +export default { + async fetch(request: Request, env: Env) { + if (request.method === 'GET') { + // Reads: use replica for lower latency + const users = await env.DB_REPLICA.prepare('SELECT * FROM users WHERE active = 1').all(); + return Response.json(users.results); + } + + if (request.method === 'POST') { + const { name, email } = await request.json(); + const result = await env.DB.prepare('INSERT INTO users (name, email) VALUES (?, ?)').bind(name, email).run(); + + // Read-after-write: use primary for consistency (replication lag <100ms-2s) + const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(result.meta.last_row_id).first(); + return Response.json(user, { status: 201 }); + } + } +} +``` + +**Use replicas for**: Analytics dashboards, search results, public queries (eventual consistency OK) +**Use primary for**: Read-after-write, financial transactions, authentication (consistency required) + +## Sessions API Pattern (Paid Plans) + +```typescript +// Migration with long-running session (up to 15 min) +async function runMigration(env: Env) { + const session = env.DB.withSession({ timeout: 600 }); // 10 min + try { + await session.prepare('CREATE INDEX idx_users_email ON users(email)').run(); + await session.prepare('CREATE INDEX idx_posts_user ON posts(user_id)').run(); + await session.prepare('ANALYZE').run(); + } finally { + session.close(); // Always close to prevent leaks + } +} + +// Bulk transformation with batching +async function transformLargeDataset(env: Env) { + const session = env.DB.withSession({ timeout: 900 }); // 15 min max + try { + const BATCH_SIZE = 1000; + let offset = 0; + while (true) { + const rows = await session.prepare('SELECT id, data FROM legacy LIMIT ? OFFSET ?').bind(BATCH_SIZE, offset).all(); + if (rows.results.length === 0) break; + const updates = rows.results.map(row => + session.prepare('UPDATE legacy SET new_data = ? WHERE id = ?').bind(transform(row.data), row.id) + ); + await session.batch(updates); + offset += BATCH_SIZE; + } + } finally { session.close(); } +} +``` + +## Time Travel & Backups + +```bash +wrangler d1 time-travel restore --timestamp="2024-01-15T14:30:00Z" # Point-in-time +wrangler d1 time-travel info # List restore points (7 days free, 30 days paid) +wrangler d1 export --remote --output=./backup.sql # Full export +wrangler d1 export --remote --no-schema --output=./data.sql # Data only +wrangler d1 execute --remote --file=./backup.sql # Import +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6ed5f417931e2aaeb7b3a218bec29698a56c0421 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/README.md @@ -0,0 +1,75 @@ +# Cloudflare Durable Objects Storage + +Persistent storage API for Durable Objects with SQLite and KV backends, PITR, and automatic concurrency control. + +## Overview + +DO Storage provides: +- SQLite-backed (recommended) or KV-backed +- SQL API + synchronous/async KV APIs +- Automatic input/output gates (race-free) +- 30-day point-in-time recovery (PITR) +- Transactions and alarms + +**Use cases:** Stateful coordination, real-time collaboration, counters, sessions, rate limiters + +**Billing:** Charged by request, GB-month storage, and rowsRead/rowsWritten for SQL operations + +## Quick Start + +```typescript +export class Counter extends DurableObject { + sql: SqlStorage; + + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + this.sql = ctx.storage.sql; + this.sql.exec('CREATE TABLE IF NOT EXISTS data(key TEXT PRIMARY KEY, value INTEGER)'); + } + + async increment(): Promise { + const result = this.sql.exec( + 'INSERT INTO data VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = value + 1 RETURNING value', + 'counter', 1 + ).one(); + return result?.value || 1; + } +} +``` + +## Storage Backends + +| Backend | Create Method | APIs | PITR | +|---------|---------------|------|------| +| SQLite (recommended) | `new_sqlite_classes` | SQL + sync KV + async KV | ✅ | +| KV (legacy) | `new_classes` | async KV only | ❌ | + +## Core APIs + +- **SQL API** (`ctx.storage.sql`): Full SQLite with extensions (FTS5, JSON, math) +- **Sync KV** (`ctx.storage.kv`): Synchronous key-value (SQLite only) +- **Async KV** (`ctx.storage`): Asynchronous key-value (both backends) +- **Transactions** (`transactionSync()`, `transaction()`) +- **PITR** (`getBookmarkForTime()`, `onNextSessionRestoreBookmark()`) +- **Alarms** (`setAlarm()`, `alarm()` handler) + +## Reading Order + +**New to DO storage:** configuration.md → api.md → patterns.md → gotchas.md +**Building features:** patterns.md → api.md → gotchas.md +**Debugging issues:** gotchas.md → api.md +**Writing tests:** testing.md + +## In This Reference + +- [configuration.md](./configuration.md) - wrangler.jsonc migrations, SQLite vs KV setup, RPC binding +- [api.md](./api.md) - SQL exec/cursors, KV methods, storage options, transactions, alarms, PITR +- [patterns.md](./patterns.md) - Schema migrations, caching, rate limiting, batch processing, parent-child coordination +- [gotchas.md](./gotchas.md) - Concurrency gates, INTEGER precision, transaction rules, SQL limits +- [testing.md](./testing.md) - vitest-pool-workers setup, testing DOs with SQL/alarms/PITR + +## See Also + +- [durable-objects](../durable-objects/) - DO fundamentals and coordination patterns +- [workers](../workers/) - Worker runtime for DO stubs +- [d1](../d1/) - Shared database alternative to per-DO storage diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/api.md new file mode 100644 index 0000000000000000000000000000000000000000..e659598b41d6ab2aa76a902953ab9286f7ee73e3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/api.md @@ -0,0 +1,102 @@ +# DO Storage API Reference + +## SQL API + +```typescript +const cursor = this.sql.exec('SELECT * FROM users WHERE email = ?', email); +for (let row of cursor) {} // Objects: { id, name, email } +cursor.toArray(); cursor.one(); // Single row (throws if != 1) +for (let row of cursor.raw()) {} // Arrays: [1, "Alice", "..."] + +// Manual iteration +const iter = cursor[Symbol.iterator](); +const first = iter.next(); // { value: {...}, done: false } + +cursor.columnNames; // ["id", "name", "email"] +cursor.rowsRead; cursor.rowsWritten; // Billing + +type User = { id: number; name: string; email: string }; +const user = this.sql.exec('...', userId).one(); +``` + +## Sync KV API (SQLite only) + +```typescript +this.ctx.storage.kv.get("counter"); // undefined if missing +this.ctx.storage.kv.put("counter", 42); +this.ctx.storage.kv.put("user", { name: "Alice", age: 30 }); +this.ctx.storage.kv.delete("counter"); // true if existed + +for (let [key, value] of this.ctx.storage.kv.list()) {} + +// List options: start, prefix, reverse, limit +this.ctx.storage.kv.list({ start: "user:", prefix: "user:", reverse: true, limit: 100 }); +``` + +## Async KV API (Both backends) + +```typescript +await this.ctx.storage.get("key"); // Single +await this.ctx.storage.get(["key1", "key2"]); // Multiple (max 128) +await this.ctx.storage.put("key", value); // Single +await this.ctx.storage.put({ "key1": "v1", "key2": { nested: true } }); // Multiple (max 128) +await this.ctx.storage.delete("key"); +await this.ctx.storage.delete(["key1", "key2"]); +await this.ctx.storage.list({ prefix: "user:", limit: 100 }); + +// Options: allowConcurrency, noCache, allowUnconfirmed +await this.ctx.storage.get("key", { allowConcurrency: true, noCache: true }); +await this.ctx.storage.put("key", value, { allowUnconfirmed: true, noCache: true }); +``` + +### Storage Options + +| Option | Methods | Effect | Use Case | +|--------|---------|--------|----------| +| `allowConcurrency` | get, list | Skip input gate; allow concurrent requests during read | Read-heavy metrics that don't need strict consistency | +| `noCache` | get, put, list | Skip in-memory cache; always read from disk | Rarely-accessed data or testing storage directly | +| `allowUnconfirmed` | put, delete | Return before write confirms (still protected by output gate) | Non-critical writes where latency matters more than confirmation | + +## Transactions + +```typescript +// Sync (SQL/sync KV only) +this.ctx.storage.transactionSync(() => { + this.sql.exec('UPDATE accounts SET balance = balance - ? WHERE id = ?', 100, 1); + this.sql.exec('UPDATE accounts SET balance = balance + ? WHERE id = ?', 100, 2); + return "result"; +}); + +// Async +await this.ctx.storage.transaction(async () => { + const value = await this.ctx.storage.get("counter"); + await this.ctx.storage.put("counter", value + 1); + if (value > 100) this.ctx.storage.rollback(); // Explicit rollback +}); +``` + +## Point-in-Time Recovery + +```typescript +await this.ctx.storage.getCurrentBookmark(); +await this.ctx.storage.getBookmarkForTime(Date.now() - 2 * 24 * 60 * 60 * 1000); +await this.ctx.storage.onNextSessionRestoreBookmark(bookmark); +this.ctx.abort(); // Restart to apply; bookmarks lexically comparable (earlier < later) +``` + +## Alarms + +```typescript +await this.ctx.storage.setAlarm(Date.now() + 60000); // Timestamp or Date +await this.ctx.storage.getAlarm(); +await this.ctx.storage.deleteAlarm(); + +async alarm() { await this.doScheduledWork(); } +``` + +## Misc + +```typescript +await this.ctx.storage.deleteAll(); // Atomic for SQLite; alarm NOT included +this.ctx.storage.sql.databaseSize; // Bytes +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..8c4c9f337869d0a6886951c62262a2823fe50440 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/configuration.md @@ -0,0 +1,112 @@ +# DO Storage Configuration + +## SQLite-backed (Recommended) + +**wrangler.jsonc:** +```jsonc +{ + "migrations": [ + { + "tag": "v1", + "new_sqlite_classes": ["Counter", "Session", "RateLimiter"] + } + ] +} +``` + +**Migration lifecycle:** Migrations run once per deployment. Existing DO instances get new storage backend on next invocation. Renaming/removing classes requires `renamed_classes` or `deleted_classes` entries. + +## KV-backed (Legacy) + +**wrangler.jsonc:** +```jsonc +{ + "migrations": [ + { + "tag": "v1", + "new_classes": ["OldCounter"] + } + ] +} +``` + +## TypeScript Setup + +```typescript +export class MyDurableObject extends DurableObject { + sql: SqlStorage; + + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + this.sql = ctx.storage.sql; + + // Initialize schema + this.sql.exec(` + CREATE TABLE IF NOT EXISTS users( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + email TEXT UNIQUE + ); + `); + } +} + +// Binding +interface Env { + MY_DO: DurableObjectNamespace; +} + +export default { + async fetch(request: Request, env: Env): Promise { + const id = env.MY_DO.idFromName('singleton'); + const stub = env.MY_DO.get(id); + + // Modern RPC: call methods directly (recommended) + const result = await stub.someMethod(); + return Response.json(result); + + // Legacy: forward request (still works) + // return stub.fetch(request); + } +} +``` + +## CPU Limits + +```jsonc +{ + "limits": { + "cpu_ms": 300000 // 5 minutes (default 30s) + } +} +``` + +## Location Control + +```typescript +// Jurisdiction (GDPR/FedRAMP) +const euNamespace = env.MY_DO.jurisdiction("eu"); +const id = euNamespace.newUniqueId(); +const stub = euNamespace.get(id); + +// Location hint (best effort) +const stub = env.MY_DO.get(id, { locationHint: "enam" }); +// Hints: wnam, enam, sam, weur, eeur, apac, oc, afr, me +``` + +## Initialization + +```typescript +export class Counter extends DurableObject { + value: number; + + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + + // Block concurrent requests during init + ctx.blockConcurrencyWhile(async () => { + this.value = (await ctx.storage.get("value")) || 0; + }); + } +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..0a388a64a7b214362cb83b26889431eaa6e9e312 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/gotchas.md @@ -0,0 +1,150 @@ +# DO Storage Gotchas & Troubleshooting + +## Concurrency Model (CRITICAL) + +Durable Objects use **input/output gates** to prevent race conditions: + +### Input Gates +Block new requests during storage reads from CURRENT request: + +```typescript +// SAFE: Input gate active during await +async increment() { + const val = await this.ctx.storage.get("counter"); // Input gate blocks other requests + await this.ctx.storage.put("counter", val + 1); + return val; +} +``` + +### Output Gates +Hold response until ALL writes from current request confirm: + +```typescript +// SAFE: Output gate waits for put() to confirm before returning response +async increment() { + const val = await this.ctx.storage.get("counter"); + this.ctx.storage.put("counter", val + 1); // No await + return new Response(String(val)); // Response delayed until write confirms +} +``` + +### Write Coalescing +Multiple writes to same key = atomic (last write wins): + +```typescript +// SAFE: All three writes coalesce atomically +this.ctx.storage.put("key", 1); +this.ctx.storage.put("key", 2); +this.ctx.storage.put("key", 3); // Final value: 3 +``` + +### Breaking Gates (DANGER) + +**fetch() breaks input/output gates** → allows request interleaving: + +```typescript +// UNSAFE: fetch() allows another request to interleave +async unsafe() { + const val = await this.ctx.storage.get("counter"); + await fetch("https://api.example.com"); // Gate broken! + await this.ctx.storage.put("counter", val + 1); // Race condition possible +} +``` + +**Solution:** Use `blockConcurrencyWhile()` or `transaction()`: + +```typescript +// SAFE: Block concurrent requests explicitly +async safe() { + return await this.ctx.blockConcurrencyWhile(async () => { + const val = await this.ctx.storage.get("counter"); + await fetch("https://api.example.com"); + await this.ctx.storage.put("counter", val + 1); + return val; + }); +} +``` + +### allowConcurrency Option + +Opt out of input gate for reads that don't need protection: + +```typescript +// Allow concurrent reads (no consistency guarantee) +const val = await this.ctx.storage.get("metrics", { allowConcurrency: true }); +``` + +## Common Errors + +### "Race Condition in Concurrent Calls" + +**Cause:** Multiple concurrent storage operations initiated from same event (e.g., `Promise.all()`) are not protected by input gate +**Solution:** Avoid concurrent storage operations within single event; input gate only serializes requests from different events, not operations within same event + +### "Direct SQL Transaction Statements" + +**Cause:** Using `BEGIN TRANSACTION` directly instead of transaction methods +**Solution:** Use `this.ctx.storage.transactionSync()` for sync operations or `this.ctx.storage.transaction()` for async operations + +### "Async in transactionSync" + +**Cause:** Using async operations inside `transactionSync()` callback +**Solution:** Use async `transaction()` method instead of `transactionSync()` when async operations needed + +### "TypeScript Type Mismatch at Runtime" + +**Cause:** Query doesn't return all fields specified in TypeScript type +**Solution:** Ensure SQL query selects all columns that match the TypeScript type definition + +### "Silent Data Corruption with Large IDs" + +**Cause:** JavaScript numbers have 53-bit precision; SQLite INTEGER is 64-bit +**Symptom:** IDs > 9007199254740991 (Number.MAX_SAFE_INTEGER) silently truncate/corrupt +**Solution:** Store large IDs as TEXT: + +```typescript +// BAD: Snowflake/Twitter IDs will corrupt +this.sql.exec("CREATE TABLE events(id INTEGER PRIMARY KEY)"); +this.sql.exec("INSERT INTO events VALUES (?)", 1234567890123456789n); // Corrupts! + +// GOOD: Store as TEXT +this.sql.exec("CREATE TABLE events(id TEXT PRIMARY KEY)"); +this.sql.exec("INSERT INTO events VALUES (?)", "1234567890123456789"); +``` + +### "Alarm Not Deleted with deleteAll()" + +**Cause:** `deleteAll()` doesn't delete alarms automatically +**Solution:** Call `deleteAlarm()` explicitly before `deleteAll()` to remove alarm + +### "Slow Performance" + +**Cause:** Using async KV API instead of sync API +**Solution:** Use sync KV API (`ctx.storage.kv`) for better performance with simple key-value operations + +### "High Billing from Storage Operations" + +**Cause:** Excessive `rowsRead`/`rowsWritten` or unused objects not cleaned up +**Solution:** Monitor `rowsRead`/`rowsWritten` metrics and ensure unused objects call `deleteAll()` + +### "Durable Object Overloaded" + +**Cause:** Single DO exceeding ~1K req/sec soft limit +**Solution:** Shard across multiple DOs with random IDs or other distribution strategy + +## Limits + +| Limit | Value | Notes | +|-------|-------|-------| +| Max columns per table | 100 | SQL limitation | +| Max string/BLOB per row | 2 MB | SQL limitation | +| Max row size | 2 MB | SQL limitation | +| Max SQL statement size | 100 KB | SQL limitation | +| Max SQL parameters | 100 | SQL limitation | +| Max LIKE/GLOB pattern | 50 B | SQL limitation | +| SQLite storage per object | 10 GB | SQLite-backed storage | +| SQLite key+value size | 2 MB | SQLite-backed storage | +| KV storage per object | Unlimited | KV-style storage | +| KV key size | 2 KiB | KV-style storage | +| KV value size | 128 KiB | KV-style storage | +| Request throughput | ~1K req/sec | Soft limit per DO | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..59761093b24ef63c469ed62109bfbe8464bf6668 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/patterns.md @@ -0,0 +1,182 @@ +# DO Storage Patterns & Best Practices + +## Schema Migration + +```typescript +export class MyDurableObject extends DurableObject { + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + this.sql = ctx.storage.sql; + + // Use SQLite's built-in user_version pragma + const ver = this.sql.exec("PRAGMA user_version").one()?.user_version || 0; + + if (ver === 0) { + this.sql.exec(`CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)`); + this.sql.exec("PRAGMA user_version = 1"); + } + if (ver === 1) { + this.sql.exec(`ALTER TABLE users ADD COLUMN email TEXT`); + this.sql.exec("PRAGMA user_version = 2"); + } + } +} +``` + +## In-Memory Caching + +```typescript +export class UserCache extends DurableObject { + cache = new Map(); + async getUser(id: string): Promise { + if (this.cache.has(id)) { + const cached = this.cache.get(id); + if (cached) return cached; + } + const user = await this.ctx.storage.get(`user:${id}`); + if (user) this.cache.set(id, user); + return user; + } + async updateUser(id: string, data: Partial) { + const updated = { ...await this.getUser(id), ...data }; + this.cache.set(id, updated); + await this.ctx.storage.put(`user:${id}`, updated); + return updated; + } +} +``` + +## Rate Limiting + +```typescript +export class RateLimiter extends DurableObject { + async checkLimit(key: string, limit: number, window: number): Promise { + const now = Date.now(); + this.sql.exec('DELETE FROM requests WHERE key = ? AND timestamp < ?', key, now - window); + const count = this.sql.exec('SELECT COUNT(*) as count FROM requests WHERE key = ?', key).one().count; + if (count >= limit) return false; + this.sql.exec('INSERT INTO requests (key, timestamp) VALUES (?, ?)', key, now); + return true; + } +} +``` + +## Batch Processing with Alarms + +```typescript +export class BatchProcessor extends DurableObject { + pending: string[] = []; + async addItem(item: string) { + this.pending.push(item); + if (!await this.ctx.storage.getAlarm()) await this.ctx.storage.setAlarm(Date.now() + 5000); + } + async alarm() { + const items = [...this.pending]; + this.pending = []; + this.sql.exec(`INSERT INTO processed_items (item, timestamp) VALUES ${items.map(() => "(?, ?)").join(", ")}`, ...items.flatMap(item => [item, Date.now()])); + } +} +``` + +## Initialization Pattern + +```typescript +export class Counter extends DurableObject { + value: number; + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + ctx.blockConcurrencyWhile(async () => { this.value = (await ctx.storage.get("value")) || 0; }); + } + async increment() { + this.value++; + this.ctx.storage.put("value", this.value); // Don't await (output gate protects) + return this.value; + } +} +``` + +## Safe Counter / Optimized Write + +```typescript +// Input gate blocks other requests +async getUniqueNumber(): Promise { + let val = await this.ctx.storage.get("counter"); + await this.ctx.storage.put("counter", val + 1); + return val; +} + +// No await on write - output gate delays response until write confirms +async increment(): Promise { + let val = await this.ctx.storage.get("counter"); + this.ctx.storage.put("counter", val + 1); + return new Response(String(val)); +} +``` + +## Parent-Child Coordination + +Hierarchical DO pattern where parent manages child DOs: + +```typescript +// Parent DO coordinates children +export class Workspace extends DurableObject { + async createDocument(name: string): Promise { + const docId = crypto.randomUUID(); + const childId = this.env.DOCUMENT.idFromName(`${this.ctx.id.toString()}:${docId}`); + const childStub = this.env.DOCUMENT.get(childId); + await childStub.initialize(name); + + // Track child in parent storage + this.sql.exec('INSERT INTO documents (id, name, created) VALUES (?, ?, ?)', + docId, name, Date.now()); + return docId; + } + + async listDocuments(): Promise { + return this.sql.exec('SELECT id FROM documents').toArray().map(r => r.id); + } +} + +// Child DO +export class Document extends DurableObject { + async initialize(name: string) { + this.sql.exec('CREATE TABLE IF NOT EXISTS content(key TEXT PRIMARY KEY, value TEXT)'); + this.sql.exec('INSERT INTO content VALUES (?, ?)', 'name', name); + } +} +``` + +## Write Coalescing Pattern + +Multiple writes to same key coalesce atomically (last write wins): + +```typescript +async updateMetrics(userId: string, actions: Action[]) { + // All writes coalesce - no await needed + for (const action of actions) { + this.ctx.storage.put(`user:${userId}:lastAction`, action.type); + this.ctx.storage.put(`user:${userId}:count`, + await this.ctx.storage.get(`user:${userId}:count`) + 1); + } + // Output gate ensures all writes confirm before response + return new Response("OK"); +} + +// Atomic batch with SQL +async batchUpdate(items: Item[]) { + this.sql.exec('BEGIN'); + for (const item of items) { + this.sql.exec('INSERT OR REPLACE INTO items VALUES (?, ?)', item.id, item.value); + } + this.sql.exec('COMMIT'); +} +``` + +## Cleanup + +```typescript +async cleanup() { + await this.ctx.storage.deleteAlarm(); // Separate from deleteAll + await this.ctx.storage.deleteAll(); +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/testing.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/testing.md new file mode 100644 index 0000000000000000000000000000000000000000..3b29902f1eaab76fcf8d9421df2d76f43fff165f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/do-storage/testing.md @@ -0,0 +1,183 @@ +# DO Storage Testing + +Testing Durable Objects with storage using `vitest-pool-workers`. + +## Setup + +**vitest.config.ts:** +```typescript +import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; + +export default defineWorkersConfig({ + test: { + poolOptions: { + workers: { wrangler: { configPath: "./wrangler.toml" } } + } + } +}); +``` + +**package.json:** Add `@cloudflare/vitest-pool-workers` and `vitest` to devDependencies + +## Basic Testing + +```typescript +import { env, runInDurableObject } from "cloudflare:test"; +import { describe, it, expect } from "vitest"; + +describe("Counter DO", () => { + it("increments counter", async () => { + const id = env.COUNTER.idFromName("test"); + const result = await runInDurableObject(env.COUNTER, id, async (instance, state) => { + const val1 = await instance.increment(); + const val2 = await instance.increment(); + return { val1, val2 }; + }); + expect(result.val1).toBe(1); + expect(result.val2).toBe(2); + }); +}); +``` + +## Testing SQL Storage + +```typescript +it("creates and queries users", async () => { + const id = env.USER_MANAGER.idFromName("test"); + await runInDurableObject(env.USER_MANAGER, id, async (instance, state) => { + await instance.createUser("alice@example.com", "Alice"); + const user = await instance.getUser("alice@example.com"); + expect(user).toEqual({ email: "alice@example.com", name: "Alice" }); + }); +}); + +it("handles schema migrations", async () => { + const id = env.USER_MANAGER.idFromName("migration-test"); + await runInDurableObject(env.USER_MANAGER, id, async (instance, state) => { + const version = state.storage.sql.exec( + "SELECT value FROM _meta WHERE key = 'schema_version'" + ).one()?.value; + expect(version).toBe("1"); + }); +}); +``` + +## Testing Alarms + +```typescript +import { runDurableObjectAlarm } from "cloudflare:test"; + +it("processes batch on alarm", async () => { + const id = env.BATCH_PROCESSOR.idFromName("test"); + + // Add items + await runInDurableObject(env.BATCH_PROCESSOR, id, async (instance) => { + await instance.addItem("item1"); + await instance.addItem("item2"); + }); + + // Trigger alarm + await runDurableObjectAlarm(env.BATCH_PROCESSOR, id); + + // Verify processed + await runInDurableObject(env.BATCH_PROCESSOR, id, async (instance, state) => { + const count = state.storage.sql.exec( + "SELECT COUNT(*) as count FROM processed_items" + ).one().count; + expect(count).toBe(2); + }); +}); +``` + +## Testing Concurrency + +```typescript +it("handles concurrent increments safely", async () => { + const id = env.COUNTER.idFromName("concurrent-test"); + + // Parallel increments + const results = await Promise.all([ + runInDurableObject(env.COUNTER, id, (i) => i.increment()), + runInDurableObject(env.COUNTER, id, (i) => i.increment()), + runInDurableObject(env.COUNTER, id, (i) => i.increment()) + ]); + + // All should get unique values + expect(new Set(results).size).toBe(3); + expect(Math.max(...results)).toBe(3); +}); +``` + +## Test Isolation + +```typescript +// Per-test unique IDs +let testId: string; +beforeEach(() => { testId = crypto.randomUUID(); }); + +it("isolated test", async () => { + const id = env.MY_DO.idFromName(testId); + // Uses unique DO instance +}); + +// Cleanup pattern +it("with cleanup", async () => { + const id = env.MY_DO.idFromName("cleanup-test"); + try { + await runInDurableObject(env.MY_DO, id, async (instance) => {}); + } finally { + await runInDurableObject(env.MY_DO, id, async (instance, state) => { + await state.storage.deleteAll(); + }); + } +}); +``` + +## Testing PITR + +```typescript +it("restores from bookmark", async () => { + const id = env.MY_DO.idFromName("pitr-test"); + + // Create checkpoint + const bookmark = await runInDurableObject(env.MY_DO, id, async (instance, state) => { + await state.storage.put("value", 1); + return await state.storage.getCurrentBookmark(); + }); + + // Modify and restore + await runInDurableObject(env.MY_DO, id, async (instance, state) => { + await state.storage.put("value", 2); + await state.storage.onNextSessionRestoreBookmark(bookmark); + state.abort(); + }); + + // Verify restored + await runInDurableObject(env.MY_DO, id, async (instance, state) => { + const value = await state.storage.get("value"); + expect(value).toBe(1); + }); +}); +``` + +## Testing Transactions + +```typescript +it("rolls back on error", async () => { + const id = env.BANK.idFromName("transaction-test"); + + await runInDurableObject(env.BANK, id, async (instance, state) => { + await state.storage.put("balance", 100); + + await expect( + state.storage.transaction(async () => { + await state.storage.put("balance", 50); + throw new Error("Cancel"); + }) + ).rejects.toThrow("Cancel"); + + const balance = await state.storage.get("balance"); + expect(balance).toBe(100); // Rolled back + }); +}); +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6203d91a0b8a6eead456cf5a6c1b0c50660233b2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/README.md @@ -0,0 +1,184 @@ +# Cloudflare Durable Objects + +Expert guidance for building stateful applications with Cloudflare Durable Objects. + +## Reading Order + +1. **First time?** Read this overview + Quick Start +2. **Setting up?** See [Configuration](./configuration.md) +3. **Building features?** Use decision trees below → [Patterns](./patterns.md) +4. **Debugging issues?** Check [Gotchas](./gotchas.md) +5. **Deep dive?** [API](./api.md) and [DO Storage](../do-storage/README.md) + +## Overview + +Durable Objects combine compute with storage in globally-unique, strongly-consistent packages: +- **Globally unique instances**: Each DO has unique ID for multi-client coordination +- **Co-located storage**: Fast, strongly-consistent storage with compute +- **Automatic placement**: Objects spawn near first request location +- **Stateful serverless**: In-memory state + persistent storage +- **Single-threaded**: Serial request processing (no race conditions) + +## Rules of Durable Objects + +Critical rules preventing most production issues: + +1. **One alarm per DO** - Schedule multiple events via queue pattern +2. **~1K req/s per DO max** - Shard for higher throughput +3. **Constructor runs every wake** - Keep initialization light; use lazy loading +4. **Hibernation clears memory** - In-memory state lost; persist critical data +5. **Use `ctx.waitUntil()` for cleanup** - Ensures completion after response sent +6. **No setTimeout for persistence** - Use `setAlarm()` for reliable scheduling + +## Core Concepts + +### Class Structure +All DOs extend `DurableObject` base class with constructor receiving `DurableObjectState` (storage, WebSockets, alarms) and `Env` (bindings). + +### Lifecycle States + +``` +[Not Created] → [Active] ⇄ [Hibernated] → [Evicted] + ↓ + [Destroyed] +``` + +- **Not Created**: DO ID exists but instance never spawned +- **Active**: Processing requests, in-memory state valid, billed per GB-hour +- **Hibernated**: WebSocket connections open but zero compute, zero cost +- **Evicted**: Removed from memory; next request triggers cold start +- **Destroyed**: Data deleted via migration or manual deletion + +### Accessing from Workers +Workers use bindings to get stubs, then call RPC methods directly (recommended) or use fetch handler (legacy). + +**RPC vs fetch() decision:** +``` +├─ New project + compat ≥2024-04-03 → RPC (type-safe, simpler) +├─ Need HTTP semantics (headers, status) → fetch() +├─ Proxying requests to DO → fetch() +└─ Legacy compatibility → fetch() +``` + +See [Patterns: RPC vs fetch()](./patterns.md) for examples. + +### ID Generation +- `idFromName()`: Deterministic, named coordination (rate limiting, locks) +- `newUniqueId()`: Random IDs for sharding high-throughput workloads +- `idFromString()`: Derive from existing IDs +- Jurisdiction option: Data locality compliance + +### Storage Options + +**Which storage API?** +``` +├─ Structured data, relations, transactions → SQLite (recommended) +├─ Simple KV on SQLite DO → ctx.storage.kv (sync KV) +└─ Legacy KV-only DO → ctx.storage (async KV) +``` + +- **SQLite** (recommended): Structured data, transactions, 10GB/DO +- **Synchronous KV API**: Simple key-value on SQLite objects +- **Asynchronous KV API**: Legacy/advanced use cases + +See [DO Storage](../do-storage/README.md) for deep dive. + +### Special Features +- **Alarms**: Schedule future execution per-DO (1 per DO - use queue pattern for multiple) +- **WebSocket Hibernation**: Zero-cost idle connections (memory cleared on hibernation) +- **Point-in-Time Recovery**: Restore to any point in 30 days (SQLite only) + +## Quick Start + +```typescript +import { DurableObject } from "cloudflare:workers"; + +export class Counter extends DurableObject { + async increment(): Promise { + const result = this.ctx.storage.sql.exec( + `INSERT INTO counters (id, value) VALUES (1, 1) + ON CONFLICT(id) DO UPDATE SET value = value + 1 + RETURNING value` + ).one(); + return result.value; + } +} + +// Worker access +export default { + async fetch(request: Request, env: Env): Promise { + const id = env.COUNTER.idFromName("global"); + const stub = env.COUNTER.get(id); + const count = await stub.increment(); + return new Response(`Count: ${count}`); + } +}; +``` + +## Decision Trees + +### What do you need? + +``` +├─ Coordinate requests (rate limit, lock, session) +│ → idFromName(identifier) → [Patterns: Rate Limiting/Locks](./patterns.md) +│ +├─ High throughput (>1K req/s) +│ → Sharding with newUniqueId() or hash → [Patterns: Sharding](./patterns.md) +│ +├─ Real-time updates (WebSocket, chat, collab) +│ → WebSocket hibernation + room pattern → [Patterns: Real-time](./patterns.md) +│ +├─ Background work (cleanup, notifications, scheduled tasks) +│ → Alarms + queue pattern (1 alarm/DO) → [Patterns: Multiple Events](./patterns.md) +│ +└─ User sessions with expiration + → Session pattern + alarm cleanup → [Patterns: Session Management](./patterns.md) +``` + +### Which access pattern? + +``` +├─ New project + typed methods → RPC (compat ≥2024-04-03) +├─ Need HTTP semantics → fetch() +├─ Proxying to DO → fetch() +└─ Legacy compat → fetch() +``` + +See [Patterns: RPC vs fetch()](./patterns.md) for examples. + +### Which storage? + +``` +├─ Structured data, SQL queries, transactions → SQLite (recommended) +├─ Simple KV on SQLite DO → ctx.storage.kv (sync API) +└─ Legacy KV-only DO → ctx.storage (async API) +``` + +See [DO Storage](../do-storage/README.md) for complete guide. + +## Essential Commands + +```bash +npx wrangler dev # Local dev with DOs +npx wrangler dev --remote # Test against prod DOs +npx wrangler deploy # Deploy + auto-apply migrations +``` + +## Resources + +**Docs**: https://developers.cloudflare.com/durable-objects/ +**API Reference**: https://developers.cloudflare.com/durable-objects/api/ +**Examples**: https://developers.cloudflare.com/durable-objects/examples/ + +## In This Reference + +- **[Configuration](./configuration.md)** - wrangler.jsonc setup, migrations, bindings, environments +- **[API](./api.md)** - Class structure, ctx methods, alarms, WebSocket hibernation +- **[Patterns](./patterns.md)** - Sharding, rate limiting, locks, real-time, sessions +- **[Gotchas](./gotchas.md)** - Limits, hibernation caveats, common errors + +## See Also + +- **[DO Storage](../do-storage/README.md)** - SQLite, KV, transactions (detailed storage guide) +- **[Workers](../workers/README.md)** - Core Workers runtime features diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/api.md new file mode 100644 index 0000000000000000000000000000000000000000..425ed75594a9c169cf2f3c06fb33a980d199b5af --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/api.md @@ -0,0 +1,187 @@ +# Durable Objects API + +## Class Structure + +```typescript +import { DurableObject } from "cloudflare:workers"; + +export class MyDO extends DurableObject { + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + // Runs on EVERY wake - keep light! + } + + // RPC methods (called directly from worker) + async myMethod(arg: string): Promise { return arg; } + + // fetch handler (legacy/HTTP semantics) + async fetch(req: Request): Promise { /* ... */ } + + // Lifecycle handlers + async alarm() { /* alarm fired */ } + async webSocketMessage(ws: WebSocket, msg: string | ArrayBuffer) { /* ... */ } + async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) { /* ... */ } + async webSocketError(ws: WebSocket, error: unknown) { /* ... */ } +} +``` + +## DurableObjectState Context Methods + +### Concurrency Control + +```typescript +// Complete work after response sent (e.g., cleanup, logging) +this.ctx.waitUntil(promise: Promise): void + +// Critical section - blocks all other requests until complete +await this.ctx.blockConcurrencyWhile(async () => { + // No other requests processed during this block + // Use for initialization or critical operations +}) +``` + +**When to use:** +- `waitUntil()`: Background cleanup, logging, non-critical work after response +- `blockConcurrencyWhile()`: First-time init, schema migration, critical state setup + +### Lifecycle + +```typescript +this.ctx.id // DurableObjectId of this instance +this.ctx.abort() // Force eviction (use after PITR restore to reload state) +``` + +### Storage Access + +```typescript +this.ctx.storage.sql // SQLite API (recommended) +this.ctx.storage.kv // Sync KV API (SQLite DOs only) +this.ctx.storage // Async KV API (legacy/KV-only DOs) +``` + +See **[DO Storage](../do-storage/README.md)** for complete storage API reference. + +### WebSocket Management + +```typescript +this.ctx.acceptWebSocket(ws: WebSocket, tags?: string[]) // Enable hibernation +this.ctx.getWebSockets(tag?: string): WebSocket[] // Get by tag or all +this.ctx.getTags(ws: WebSocket): string[] // Get tags for connection +``` + +### Alarms + +```typescript +await this.ctx.storage.setAlarm(timestamp: number | Date) // Schedule (overwrites existing) +await this.ctx.storage.getAlarm(): number | null // Get next alarm time +await this.ctx.storage.deleteAlarm(): void // Cancel alarm +``` + +**Limit:** 1 alarm per DO. Use queue pattern for multiple events (see [Patterns](./patterns.md)). + +## Storage APIs + +For detailed storage documentation including SQLite queries, KV operations, transactions, and Point-in-Time Recovery, see **[DO Storage](../do-storage/README.md)**. + +Quick reference: + +```typescript +// SQLite (recommended) +this.ctx.storage.sql.exec("SELECT * FROM users WHERE id = ?", userId).one() + +// Sync KV (SQLite DOs only) +this.ctx.storage.kv.get("key") + +// Async KV (legacy) +await this.ctx.storage.get("key") +``` + +## Alarms + +Schedule future work that survives eviction: + +```typescript +// Set alarm (overwrites any existing alarm) +await this.ctx.storage.setAlarm(Date.now() + 3600000) // 1 hour from now +await this.ctx.storage.setAlarm(new Date("2026-02-01")) // Absolute time + +// Check next alarm +const nextRun = await this.ctx.storage.getAlarm() // null if none + +// Cancel alarm +await this.ctx.storage.deleteAlarm() + +// Handler called when alarm fires +async alarm() { + // Runs once alarm triggers + // DO wakes from hibernation if needed + // Use for cleanup, notifications, scheduled tasks +} +``` + +**Limitations:** +- 1 alarm per DO maximum +- Overwrites previous alarm when set +- Use queue pattern for multiple scheduled events (see [Patterns](./patterns.md)) + +**Reliability:** +- Alarms survive DO eviction/restart +- Cloudflare retries failed alarms automatically +- Not guaranteed exactly-once (handle idempotently) + +## WebSocket Hibernation + +Hibernation allows DOs with open WebSocket connections to consume zero compute/memory until message arrives. + +```typescript +async fetch(req: Request): Promise { + const [client, server] = Object.values(new WebSocketPair()); + this.ctx.acceptWebSocket(server, ["room:123"]); // Tags for filtering + server.serializeAttachment({ userId: "abc" }); // Persisted metadata + return new Response(null, { status: 101, webSocket: client }); +} + +// Called when message arrives (DO wakes from hibernation) +async webSocketMessage(ws: WebSocket, msg: string | ArrayBuffer) { + const data = ws.deserializeAttachment(); // Retrieve metadata + for (const c of this.ctx.getWebSockets("room:123")) c.send(msg); +} + +// Called on close (optional handler) +async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) { + // Cleanup logic, remove from lists, etc. +} + +// Called on error (optional handler) +async webSocketError(ws: WebSocket, error: unknown) { + console.error("WebSocket error:", error); + // Handle error, close connection, etc. +} +``` + +**Key concepts:** +- **Auto-hibernation:** DO hibernates when no active requests/alarms +- **Zero cost:** Hibernated DOs incur no charges while preserving connections +- **Memory cleared:** All in-memory state lost on hibernation +- **Attachment persistence:** Use `serializeAttachment()` for per-connection metadata that survives hibernation +- **Tags for filtering:** Group connections by room/channel/user for targeted broadcasts + +**Handler lifecycle:** +- `webSocketMessage`: DO wakes, processes message, may hibernate after +- `webSocketClose`: Called when client closes (optional - implement for cleanup) +- `webSocketError`: Called on connection error (optional - implement for error handling) + +**Metadata persistence:** +```typescript +// Store connection metadata (survives hibernation) +ws.serializeAttachment({ userId: "abc", room: "lobby" }) + +// Retrieve after hibernation +const { userId, room } = ws.deserializeAttachment() +``` + +## See Also + +- **[DO Storage](../do-storage/README.md)** - Complete storage API reference +- **[Patterns](./patterns.md)** - Real-world usage patterns +- **[Gotchas](./gotchas.md)** - Hibernation caveats and limits diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..13d391c4be5d3d0aa560c810122f04db5a3bd1d2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/configuration.md @@ -0,0 +1,160 @@ +# Durable Objects Configuration + +## Basic Setup + +```jsonc +{ + "name": "my-worker", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", // Use latest; ≥2024-04-03 for RPC + "durable_objects": { + "bindings": [ + { + "name": "MY_DO", // Env binding name + "class_name": "MyDO" // Class exported from this worker + }, + { + "name": "EXTERNAL", // Access DO from another worker + "class_name": "ExternalDO", + "script_name": "other-worker" + } + ] + }, + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["MyDO"] } // Prefer SQLite + ] +} +``` + +## Binding Options + +```jsonc +{ + "name": "BINDING_NAME", + "class_name": "ClassName", + "script_name": "other-worker", // Optional: external DO + "environment": "production" // Optional: isolate by env +} +``` + +## Jurisdiction (Data Locality) + +Specify jurisdiction at ID creation for data residency compliance: + +```typescript +// EU data residency +const id = env.MY_DO.idFromName("user:123", { jurisdiction: "eu" }) + +// Available jurisdictions +const jurisdictions = ["eu", "fedramp"] // More may be added + +// All operations on this DO stay within jurisdiction +const stub = env.MY_DO.get(id) +await stub.someMethod() // Data stays in EU +``` + +**Key points:** +- Set at ID creation time, immutable afterward +- DO instance physically located within jurisdiction +- Storage and compute guaranteed within boundary +- Use for GDPR, FedRAMP, other compliance requirements +- No cross-jurisdiction access (requests fail if DO in different jurisdiction) + +## Migrations + +```jsonc +{ + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["MyDO"] }, // Create SQLite (recommended) + // { "tag": "v1", "new_classes": ["MyDO"] }, // Create KV (paid only) + { "tag": "v2", "renamed_classes": [{ "from": "Old", "to": "New" }] }, + { "tag": "v3", "transferred_classes": [{ "from": "Src", "from_script": "old", "to": "Dest" }] }, + { "tag": "v4", "deleted_classes": ["Obsolete"] } // Destroys ALL data! + ] +} +``` + +**Migration rules:** +- Tags must be unique and sequential (v1, v2, v3...) +- No rollback supported (test with `--dry-run` first) +- Auto-applied on deploy +- `new_sqlite_classes` recommended over `new_classes` (SQLite vs KV) +- `deleted_classes` immediately destroys ALL data (irreversible) + +## Environment Isolation + +Separate DO namespaces per environment (staging/production have distinct object instances): + +```jsonc +{ + "durable_objects": { + "bindings": [{ "name": "MY_DO", "class_name": "MyDO" }] + }, + "env": { + "production": { + "durable_objects": { + "bindings": [ + { "name": "MY_DO", "class_name": "MyDO", "environment": "production" } + ] + } + } + } +} +``` + +Deploy: `npx wrangler deploy --env production` + +## Limits & Settings + +```jsonc +{ + "limits": { + "cpu_ms": 300000 // Max CPU time: 30s default, 300s max + } +} +``` + +See [Gotchas](./gotchas.md) for complete limits table. + +## Types + +```typescript +import { DurableObject } from "cloudflare:workers"; + +interface Env { + MY_DO: DurableObjectNamespace; +} + +export class MyDO extends DurableObject {} + +type DurableObjectNamespace = { + newUniqueId(options?: { jurisdiction?: string }): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get(id: DurableObjectId): DurableObjectStub; +}; +``` + +## Commands + +```bash +# Development +npx wrangler dev # Local dev +npx wrangler dev --remote # Test against production DOs + +# Deployment +npx wrangler deploy # Deploy + auto-apply migrations +npx wrangler deploy --dry-run # Validate migrations without deploying +npx wrangler deploy --env production + +# Management +npx wrangler durable-objects list # List namespaces +npx wrangler durable-objects info # Inspect specific DO +npx wrangler durable-objects delete # Delete DO (destroys data) +``` + +## See Also + +- **[API](./api.md)** - DurableObjectState and lifecycle handlers +- **[Patterns](./patterns.md)** - Multi-environment patterns +- **[Gotchas](./gotchas.md)** - Migration caveats, limits diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..63e023069eea05bc6747f3fab6f7d75bbaebd4a7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/gotchas.md @@ -0,0 +1,197 @@ +# Durable Objects Gotchas + +## Common Errors + +### "Hibernation Cleared My In-Memory State" + +**Problem:** Variables lost after hibernation +**Cause:** DO auto-hibernates when idle; in-memory state not persisted +**Solution:** Use `ctx.storage` for critical data, `ws.serializeAttachment()` for per-connection metadata + +```typescript +// ❌ Wrong - lost on hibernation +private userCount = 0; +async webSocketMessage(ws: WebSocket, msg: string) { + this.userCount++; // Lost! +} + +// ✅ Right - persisted +async webSocketMessage(ws: WebSocket, msg: string) { + const count = this.ctx.storage.kv.get("userCount") || 0; + this.ctx.storage.kv.put("userCount", count + 1); +} +``` + +### "setTimeout Didn't Fire After Restart" + +**Problem:** Scheduled work lost on eviction +**Cause:** `setTimeout` in-memory only; eviction clears timers +**Solution:** Use `ctx.storage.setAlarm()` for reliable scheduling + +```typescript +// ❌ Wrong - lost on eviction +setTimeout(() => this.cleanup(), 3600000); + +// ✅ Right - survives eviction +await this.ctx.storage.setAlarm(Date.now() + 3600000); +async alarm() { await this.cleanup(); } +``` + +### "Constructor Runs on Every Wake" + +**Problem:** Expensive init logic slows all requests +**Cause:** Constructor runs on every wake (first request after eviction OR after hibernation) +**Solution:** Lazy initialization or cache in storage + +**Critical understanding:** Constructor runs in two scenarios: +1. **Cold start** - DO evicted from memory, first request creates new instance +2. **Wake from hibernation** - DO with WebSockets hibernated, message/alarm wakes it + +```typescript +// ❌ Wrong - expensive on every wake +constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + this.heavyData = this.loadExpensiveData(); // Slow! +} + +// ✅ Right - lazy load +private heavyData?: HeavyData; +private getHeavyData() { + if (!this.heavyData) this.heavyData = this.loadExpensiveData(); + return this.heavyData; +} +``` + +### "Durable Object Overloaded (503 errors)" + +**Problem:** 503 errors under load +**Cause:** Single DO exceeding ~1K req/s throughput limit +**Solution:** Shard across multiple DOs (see [Patterns: Sharding](./patterns.md)) + +### "Storage Quota Exceeded (Write failures)" + +**Problem:** Write operations failing +**Cause:** DO storage exceeding 10GB limit or account quota +**Solution:** Cleanup with alarms, use `deleteAll()` for old data, upgrade plan + +### "CPU Time Exceeded (Terminated)" + +**Problem:** Request terminated mid-execution +**Cause:** Processing exceeding 30s CPU time default limit +**Solution:** Increase `limits.cpu_ms` in wrangler.jsonc (max 300s) or chunk work + +### "WebSockets Disconnect on Eviction" + +**Problem:** Connections drop unexpectedly +**Cause:** DO evicted from memory without hibernation API +**Solution:** Use WebSocket hibernation handlers + client reconnection logic + +### "Migration Failed (Deploy error)" + +**Cause:** Non-unique tags, non-sequential tags, or invalid class names in migration +**Solution:** Check tag uniqueness/sequential ordering and verify class names are correct + +### "RPC Method Not Found" + +**Cause:** compatibility_date < 2024-04-03 preventing RPC usage +**Solution:** Update compatibility_date to >= 2024-04-03 or use fetch() instead of RPC + +### "Only One Alarm Allowed" + +**Cause:** Need multiple scheduled tasks but only one alarm supported per DO +**Solution:** Use event queue pattern to schedule multiple tasks with single alarm + +### "Race Condition Despite Single-Threading" + +**Problem:** Concurrent requests see inconsistent state +**Cause:** Async operations allow request interleaving (await = yield point) +**Solution:** Use `blockConcurrencyWhile()` for critical sections or atomic storage ops + +```typescript +// ❌ Wrong - race condition +async incrementCounter() { + const count = await this.ctx.storage.get("count") || 0; + // ⚠️ Another request could execute here during await + await this.ctx.storage.put("count", count + 1); +} + +// ✅ Right - atomic operation +async incrementCounter() { + return this.ctx.storage.sql.exec( + "INSERT INTO counters (id, value) VALUES (1, 1) ON CONFLICT(id) DO UPDATE SET value = value + 1 RETURNING value" + ).one().value; +} + +// ✅ Right - explicit locking +async criticalOperation() { + await this.ctx.blockConcurrencyWhile(async () => { + const count = await this.ctx.storage.get("count") || 0; + await this.ctx.storage.put("count", count + 1); + }); +} +``` + +### "Migration Rollback Not Supported" + +**Cause:** Attempting to rollback a migration after deployment +**Solution:** Test with `--dry-run` before deploying; migrations cannot be rolled back + +### "deleted_classes Destroys Data" + +**Problem:** Migration deleted all data +**Cause:** `deleted_classes` migration immediately destroys all DO instances and data +**Solution:** Test with `--dry-run`; use `transferred_classes` to preserve data during moves + +### "Cold Starts Are Slow" + +**Problem:** First request after eviction takes longer +**Cause:** DO constructor + initial storage access on cold start +**Solution:** Expected behavior; optimize constructor, use connection pooling in clients, consider warming strategy for critical DOs + +```typescript +// Warming strategy (periodically ping critical DOs) +export default { + async scheduled(event: ScheduledEvent, env: Env) { + const criticalIds = ["auth", "sessions", "locks"]; + await Promise.all(criticalIds.map(name => { + const id = env.MY_DO.idFromName(name); + const stub = env.MY_DO.get(id); + return stub.ping(); // Keep warm + })); + } +}; +``` + +## Limits + +| Limit | Free | Paid | Notes | +|-------|------|------|-------| +| SQLite storage per DO | 10 GB | 10 GB | Per Durable Object instance | +| SQLite total storage | 5 GB | Unlimited | Account-wide quota | +| Key+value size | 2 MB | 2 MB | Single KV pair (SQLite/async) | +| CPU time default | 30s | 30s | Per request; configurable | +| CPU time max | 300s | 300s | Set via `limits.cpu_ms` | +| DO classes | 100 | 500 | Distinct DO class definitions | +| SQL columns | 100 | 100 | Per table | +| SQL statement size | 100 KB | 100 KB | Max SQL query size | +| WebSocket message size | 32 MiB | 32 MiB | Per message | +| Request throughput | ~1K req/s | ~1K req/s | Per DO (soft limit - shard for more) | +| Alarms per DO | 1 | 1 | Use queue pattern for multiple events | +| Total DOs | Unlimited | Unlimited | Create as many instances as needed | +| WebSockets | Unlimited | Unlimited | Within 128MB memory limit per DO | +| Memory per DO | 128 MB | 128 MB | In-memory state + WebSocket buffers | + +## Hibernation Caveats + +1. **Memory cleared** - All in-memory variables lost; reconstruct from storage or `deserializeAttachment()` +2. **Constructor reruns** - Runs on wake; avoid expensive operations, use lazy initialization +3. **No guarantees** - DO may evict instead of hibernate; design for both +4. **Attachment limit** - `serializeAttachment()` data must be JSON-serializable, keep small +5. **Alarm wakes DO** - Alarm prevents hibernation until handler completes +6. **WebSocket state not automatic** - Must explicitly persist with `serializeAttachment()` or storage + +## See Also + +- **[Patterns](./patterns.md)** - Workarounds for common limitations +- **[API](./api.md)** - Storage limits and quotas +- **[Configuration](./configuration.md)** - Setting CPU limits diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..3e08f012bbc240cf76d905fc310ef01f6e8226d1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/durable-objects/patterns.md @@ -0,0 +1,201 @@ +# Durable Objects Patterns + +## When to Use Which Pattern + +| Need | Pattern | ID Strategy | +|------|---------|-------------| +| Rate limit per user/IP | Rate Limiting | `idFromName(identifier)` | +| Mutual exclusion | Distributed Lock | `idFromName(resource)` | +| >1K req/s throughput | Sharding | `newUniqueId()` or hash | +| Real-time updates | WebSocket Collab | `idFromName(room)` | +| User sessions | Session Management | `idFromName(sessionId)` | +| Background cleanup | Alarm-based | Any | + +## RPC vs fetch() + +**RPC** (compat ≥2024-04-03): Type-safe, simpler, default for new projects +**fetch()**: Legacy compat, HTTP semantics, proxying + +```typescript +const count = await stub.increment(); // RPC +const count = await (await stub.fetch(req)).json(); // fetch() +``` + +## Sharding (High Throughput) + +Single DO ~1K req/s max. Shard for higher throughput: + +```typescript +export default { + async fetch(req: Request, env: Env): Promise { + const userId = new URL(req.url).searchParams.get("user"); + const hash = hashCode(userId) % 100; // 100 shards + const id = env.COUNTER.idFromName(`shard:${hash}`); + return env.COUNTER.get(id).fetch(req); + } +}; + +function hashCode(str: string): number { + let hash = 0; + for (let i = 0; i < str.length; i++) hash = ((hash << 5) - hash) + str.charCodeAt(i); + return Math.abs(hash); +} +``` + +**Decisions:** +- **Shard count**: 10-1000 typical (start with 100, measure, adjust) +- **Shard key**: User ID, IP, session - must distribute evenly (use hash) +- **Aggregation**: Coordinator DO or external system (D1, R2) + +## Rate Limiting + +```typescript +async checkLimit(key: string, limit: number, windowMs: number): Promise { + const req = this.ctx.storage.sql.exec("SELECT COUNT(*) as count FROM requests WHERE key = ? AND timestamp > ?", key, Date.now() - windowMs).one(); + if (req.count >= limit) return false; + this.ctx.storage.sql.exec("INSERT INTO requests (key, timestamp) VALUES (?, ?)", key, Date.now()); + return true; +} +``` + +## Distributed Lock + +```typescript +private held = false; +async acquire(timeoutMs = 5000): Promise { + if (this.held) return false; + this.held = true; + await this.ctx.storage.setAlarm(Date.now() + timeoutMs); + return true; +} +async release() { this.held = false; await this.ctx.storage.deleteAlarm(); } +async alarm() { this.held = false; } // Auto-release on timeout +``` + +## Hibernation-Aware Pattern + +Preserve state across hibernation: + +```typescript +async fetch(req: Request): Promise { + const [client, server] = Object.values(new WebSocketPair()); + const userId = new URL(req.url).searchParams.get("user"); + server.serializeAttachment({ userId }); // Survives hibernation + this.ctx.acceptWebSocket(server, ["room:lobby"]); + server.send(JSON.stringify({ type: "init", state: this.ctx.storage.kv.get("state") })); + return new Response(null, { status: 101, webSocket: client }); +} + +async webSocketMessage(ws: WebSocket, msg: string) { + const { userId } = ws.deserializeAttachment(); // Retrieve after wake + const state = this.ctx.storage.kv.get("state") || {}; + state[userId] = JSON.parse(msg); + this.ctx.storage.kv.put("state", state); + for (const c of this.ctx.getWebSockets("room:lobby")) c.send(msg); +} +``` + +## Real-time Collaboration + +Broadcast updates to all connected clients: + +```typescript +async webSocketMessage(ws: WebSocket, msg: string) { + const data = JSON.parse(msg); + this.ctx.storage.kv.put("doc", data.content); // Persist + for (const c of this.ctx.getWebSockets()) if (c !== ws) c.send(msg); // Broadcast +} +``` + +### WebSocket Reconnection + +**Client-side** (exponential backoff): +```typescript +class ResilientWS { + private delay = 1000; + connect(url: string) { + const ws = new WebSocket(url); + ws.onclose = () => setTimeout(() => { + this.connect(url); + this.delay = Math.min(this.delay * 2, 30000); + }, this.delay); + } +} +``` + +**Server-side** (cleanup on close): +```typescript +async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) { + const { userId } = ws.deserializeAttachment(); + this.ctx.storage.sql.exec("UPDATE users SET online = false WHERE id = ?", userId); + for (const c of this.ctx.getWebSockets()) c.send(JSON.stringify({ type: "user_left", userId })); +} +``` + +## Session Management + +```typescript +async createSession(userId: string, data: object): Promise { + const id = crypto.randomUUID(), exp = Date.now() + 86400000; + this.ctx.storage.sql.exec("INSERT INTO sessions VALUES (?, ?, ?, ?)", id, userId, JSON.stringify(data), exp); + await this.ctx.storage.setAlarm(exp); + return id; +} + +async getSession(id: string): Promise { + const row = this.ctx.storage.sql.exec("SELECT data FROM sessions WHERE id = ? AND expires_at > ?", id, Date.now()).one(); + return row ? JSON.parse(row.data) : null; +} + +async alarm() { this.ctx.storage.sql.exec("DELETE FROM sessions WHERE expires_at <= ?", Date.now()); } +``` + +## Multiple Events (Single Alarm) + +Queue pattern to schedule multiple events: + +```typescript +async scheduleEvent(id: string, runAt: number) { + await this.ctx.storage.put(`event:${id}`, { id, runAt }); + const curr = await this.ctx.storage.getAlarm(); + if (!curr || runAt < curr) await this.ctx.storage.setAlarm(runAt); +} + +async alarm() { + const events = await this.ctx.storage.list({ prefix: "event:" }), now = Date.now(); + let next = null; + for (const [key, ev] of events) { + if (ev.runAt <= now) { + await this.processEvent(ev); + await this.ctx.storage.delete(key); + } else if (!next || ev.runAt < next) next = ev.runAt; + } + if (next) await this.ctx.storage.setAlarm(next); +} +``` + +## Graceful Cleanup + +Use `ctx.waitUntil()` to complete work after response: + +```typescript +async myMethod() { + const response = { success: true }; + this.ctx.waitUntil(this.ctx.storage.sql.exec("DELETE FROM old_data WHERE timestamp < ?", cutoff)); + return response; +} +``` + +## Best Practices + +- **Design**: Use `idFromName()` for coordination, `newUniqueId()` for sharding, minimize constructor work +- **Storage**: Prefer SQLite, batch with transactions, set alarms for cleanup, use PITR before risky ops +- **Performance**: ~1K req/s per DO max - shard for more, cache in memory, use alarms for deferred work +- **Reliability**: Handle 503 with retry+backoff, design for cold starts, test migrations with `--dry-run` +- **Security**: Validate inputs in Workers, rate limit DO creation, use jurisdiction for compliance + +## See Also + +- **[API](./api.md)** - ctx methods, WebSocket handlers +- **[Gotchas](./gotchas.md)** - Hibernation caveats, common errors +- **[DO Storage](../do-storage/README.md)** - Storage patterns and transactions diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..66eb2adf3ce65e4b6f5735abc62538e7ea58f37d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/README.md @@ -0,0 +1,151 @@ +# Cloudflare Email Workers + +Process incoming emails programmatically using Cloudflare Workers runtime. + +## Overview + +Email Workers enable custom email processing logic at the edge. Build spam filters, auto-responders, ticket systems, notification handlers, and more using the same Workers runtime you use for HTTP requests. + +**Key capabilities**: +- Process inbound emails with full message access +- Forward to verified destinations +- Send replies with proper threading +- Parse MIME content and attachments +- Integrate with KV, R2, D1, and external APIs + +## Quick Start + +### Minimal ES Modules Handler + +```typescript +export default { + async email(message, env, ctx) { + // Reject spam + if (message.from.includes('spam.com')) { + message.setReject('Blocked'); + return; + } + + // Forward to inbox + await message.forward('inbox@example.com'); + } +}; +``` + +### Core Operations + +| Operation | Method | Use Case | +|-----------|--------|----------| +| Forward | `message.forward(to, headers?)` | Route to verified destination | +| Reject | `message.setReject(reason)` | Block with SMTP error | +| Reply | `message.reply(emailMessage)` | Auto-respond with threading | +| Parse | postal-mime library | Extract subject, body, attachments | + +## Reading Order + +For comprehensive understanding, read files in this order: + +1. **README.md** (this file) - Overview and quick start +2. **configuration.md** - Setup, deployment, bindings +3. **api.md** - Complete API reference +4. **patterns.md** - Real-world implementation examples +5. **gotchas.md** - Critical pitfalls and debugging + +## In This Reference + +| File | Description | Key Topics | +|------|-------------|------------| +| [api.md](./api.md) | Complete API reference | ForwardableEmailMessage, SendEmail bindings, reply() method, postal-mime/mimetext APIs | +| [configuration.md](./configuration.md) | Setup and configuration | wrangler.jsonc, bindings, deployment, dependencies | +| [patterns.md](./patterns.md) | Real-world examples | Allowlists from KV, auto-reply with threading, attachment extraction, webhook notifications | +| [gotchas.md](./gotchas.md) | Pitfalls and debugging | Stream consumption, ctx.waitUntil errors, security, limits | + +## Architecture + +``` +Incoming Email → Email Routing → Email Worker + ↓ + Process + Decide + ↓ + ┌───────────────┼───────────────┐ + ↓ ↓ ↓ + Forward Reply Reject +``` + +**Event flow**: +1. Email arrives at your domain +2. Email Routing matches route (e.g., `support@example.com`) +3. Bound Email Worker receives `ForwardableEmailMessage` +4. Worker processes and takes action (forward/reply/reject) +5. Email delivered or rejected based on worker logic + +## Key Concepts + +### Envelope vs Headers + +- **Envelope addresses** (`message.from`, `message.to`): SMTP transport addresses (trusted) +- **Header addresses** (parsed from body): Display addresses (can be spoofed) + +Use envelope addresses for security decisions. + +### Single-Use Streams + +`message.raw` is a ReadableStream that can only be read once. Buffer to ArrayBuffer for multiple uses. + +```typescript +// Buffer first +const buffer = await new Response(message.raw).arrayBuffer(); +const email = await PostalMime.parse(buffer); +``` + +See [gotchas.md](./gotchas.md#readablestream-can-only-be-consumed-once) for details. + +### Verified Destinations + +`forward()` only works with addresses verified in the Cloudflare Email Routing dashboard. Add destinations before deployment. + +## Use Cases + +- **Spam filtering**: Block based on sender, content, or reputation +- **Auto-responders**: Send acknowledgment replies with threading +- **Ticket creation**: Parse emails and create support tickets +- **Email archival**: Store in KV, R2, or D1 +- **Notification routing**: Forward to Slack, Discord, or webhooks +- **Attachment processing**: Extract files to R2 storage +- **Multi-tenant routing**: Route based on recipient subdomain +- **Size filtering**: Reject oversized attachments + +## Limits + +| Limit | Value | +|-------|-------| +| Max message size | 25 MiB | +| Max routing rules | 200 | +| Max destinations | 200 | +| CPU time (free tier) | 10ms | +| CPU time (paid tier) | 50ms | + +See [gotchas.md](./gotchas.md#limits-reference) for complete limits table. + +## Prerequisites + +Before deploying Email Workers: + +1. **Enable Email Routing** in Cloudflare dashboard for your domain +2. **Verify destination addresses** for forwarding +3. **Configure DMARC/SPF** for sending domains (required for replies) +4. **Set up wrangler.jsonc** with SendEmail binding + +See [configuration.md](./configuration.md) for detailed setup. + +## Service Worker Syntax (Deprecated) + +Modern projects should use ES modules format shown above. Service Worker syntax (`addEventListener('email', ...)`) is deprecated but still supported. + +## See Also + +- [Email Routing Documentation](https://developers.cloudflare.com/email-routing/) +- [Workers Platform](https://developers.cloudflare.com/workers/) +- [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) +- [postal-mime on npm](https://www.npmjs.com/package/postal-mime) +- [mimetext on npm](https://www.npmjs.com/package/mimetext) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/api.md new file mode 100644 index 0000000000000000000000000000000000000000..36d56de858fa78075257341dbf67222d771ff908 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/api.md @@ -0,0 +1,237 @@ +# Email Workers API Reference + +Complete API reference for Cloudflare Email Workers runtime. + +## ForwardableEmailMessage Interface + +The main interface passed to email handlers. + +```typescript +interface ForwardableEmailMessage { + readonly from: string; // Envelope MAIL FROM (SMTP sender) + readonly to: string; // Envelope RCPT TO (SMTP recipient) + readonly headers: Headers; // Web-standard Headers object + readonly raw: ReadableStream; // Raw MIME message (single-use stream) + readonly rawSize: number; // Total message size in bytes + + setReject(reason: string): void; + forward(rcptTo: string, headers?: Headers): Promise; + reply(message: EmailMessage): Promise; +} +``` + +### Properties + +| Property | Type | Description | +|----------|------|-------------| +| `from` | string | Envelope sender (SMTP MAIL FROM) - use for security | +| `to` | string | Envelope recipient (SMTP RCPT TO) | +| `headers` | Headers | Message headers (Subject, Message-ID, etc.) | +| `raw` | ReadableStream | Raw MIME message (**single-use**, buffer first) | +| `rawSize` | number | Message size in bytes | + +### Methods + +#### setReject(reason: string): void + +Reject with permanent SMTP 5xx error. Email not delivered, sender may receive bounce. + +```typescript +if (blockList.includes(message.from)) { + message.setReject('Sender blocked'); +} +``` + +#### forward(rcptTo: string, headers?: Headers): Promise + +Forward to verified destination. Only `X-*` custom headers allowed. + +```typescript +await message.forward('inbox@example.com'); + +// With custom headers +const h = new Headers(); +h.set('X-Processed-By', 'worker'); +await message.forward('inbox@example.com', h); +``` + +#### reply(message: EmailMessage): Promise + +Send a reply to the original sender (March 2025 feature). + +```typescript +import { EmailMessage } from 'cloudflare:email'; +import { createMimeMessage } from 'mimetext'; + +const msg = createMimeMessage(); +msg.setSender({ name: 'Support', addr: 'support@example.com' }); +msg.setRecipient(message.from); +msg.setSubject(`Re: ${message.headers.get('Subject')}`); +msg.setHeader('In-Reply-To', message.headers.get('Message-ID')); +msg.setHeader('References', message.headers.get('References') || ''); +msg.addMessage({ + contentType: 'text/plain', + data: 'Thank you for your message.' +}); + +await message.reply(new EmailMessage( + 'support@example.com', + message.from, + msg.asRaw() +)); +``` + +**Requirements**: +- Incoming email needs valid DMARC +- Reply once per event, recipient = `message.from` +- Sender domain = receiving domain, with DMARC/SPF/DKIM +- Max 100 `References` entries +- Threading: `In-Reply-To` (original Message-ID), `References`, new `Message-ID` + +## EmailMessage Constructor + +```typescript +import { EmailMessage } from 'cloudflare:email'; + +new EmailMessage(from: string, to: string, raw: ReadableStream | string) +``` + +Used for sending emails (replies or via SendEmail binding). Domain must be verified. + +## SendEmail Interface + +```typescript +interface SendEmail { + send(message: EmailMessage): Promise; +} + +// Usage +await env.EMAIL.send(new EmailMessage(from, to, mimeContent)); +``` + +## SendEmail Binding Types + +```jsonc +{ + "send_email": [ + { "name": "EMAIL" }, // Type 1: Any verified address + { "name": "LOGS", "destination_address": "logs@example.com" }, // Type 2: Single dest + { "name": "TEAM", "allowed_destination_addresses": ["a@ex.com", "b@ex.com"] }, // Type 3: Dest allowlist + { "name": "NOREPLY", "allowed_sender_addresses": ["noreply@ex.com"] } // Type 4: Sender allowlist + ] +} +``` + +## postal-mime Parsed Output + +postal-mime v2.7.3 parses incoming emails into structured data. + +```typescript +interface ParsedEmail { + headers: Array<{ key: string; value: string }>; + from: { name: string; address: string } | null; + to: Array<{ name: string; address: string }> | { name: string; address: string } | null; + cc: Array<{ name: string; address: string }> | null; + bcc: Array<{ name: string; address: string }> | null; + subject: string; + messageId: string | null; + inReplyTo: string | null; + references: string | null; + date: string | null; + html: string | null; + text: string | null; + attachments: Array<{ + filename: string; + mimeType: string; + disposition: string | null; + related: boolean; + contentId: string | null; + content: Uint8Array; + }>; +} +``` + +### Usage + +```typescript +import PostalMime from 'postal-mime'; + +const buffer = await new Response(message.raw).arrayBuffer(); +const email = await PostalMime.parse(buffer); + +console.log(email.subject); +console.log(email.from?.address); +console.log(email.text); +console.log(email.attachments.length); +``` + +## mimetext API Quick Reference + +mimetext v3.0.27 composes outgoing emails. + +```typescript +import { createMimeMessage } from 'mimetext'; + +const msg = createMimeMessage(); + +// Sender +msg.setSender({ name: 'John Doe', addr: 'john@example.com' }); + +// Recipients +msg.setRecipient('alice@example.com'); +msg.setRecipients(['bob@example.com', 'carol@example.com']); +msg.setCc('manager@example.com'); +msg.setBcc(['audit@example.com']); + +// Headers +msg.setSubject('Meeting Notes'); +msg.setHeader('In-Reply-To', ''); +msg.setHeader('References', ' '); +msg.setHeader('Message-ID', `<${crypto.randomUUID()}@example.com>`); + +// Content +msg.addMessage({ + contentType: 'text/plain', + data: 'Plain text content' +}); + +msg.addMessage({ + contentType: 'text/html', + data: '

HTML content

' +}); + +// Attachments +msg.addAttachment({ + filename: 'report.pdf', + contentType: 'application/pdf', + data: pdfBuffer // Uint8Array or base64 string +}); + +// Generate raw MIME +const raw = msg.asRaw(); // Returns string +``` + +## TypeScript Types + +```typescript +import { + ForwardableEmailMessage, + EmailMessage +} from 'cloudflare:email'; + +interface Env { + EMAIL: SendEmail; + EMAIL_ARCHIVE: KVNamespace; + ALLOWED_SENDERS: KVNamespace; +} + +export default { + async email( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext + ): Promise { + // Fully typed + } +}; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..7928d04149f8159b45402db41e3898b763010e9f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/configuration.md @@ -0,0 +1,112 @@ +# Email Workers Configuration + +## wrangler.jsonc + +```jsonc +{ + "name": "email-worker", + "main": "src/index.ts", + "compatibility_date": "2025-01-27", + "send_email": [ + { "name": "EMAIL" }, // Unrestricted + { "name": "EMAIL_LOGS", "destination_address": "logs@example.com" }, // Single dest + { "name": "EMAIL_TEAM", "allowed_destination_addresses": ["a@ex.com", "b@ex.com"] }, + { "name": "EMAIL_NOREPLY", "allowed_sender_addresses": ["noreply@ex.com"] } + ], + "kv_namespaces": [{ "binding": "ARCHIVE", "id": "xxx" }], + "r2_buckets": [{ "binding": "ATTACHMENTS", "bucket_name": "email-attachments" }], + "vars": { "WEBHOOK_URL": "https://hooks.example.com" } +} +``` + +## TypeScript Types + +```typescript +interface Env { + EMAIL: SendEmail; + ARCHIVE: KVNamespace; + ATTACHMENTS: R2Bucket; + WEBHOOK_URL: string; +} + +export default { + async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) {} +}; +``` + +## Dependencies + +```bash +npm install postal-mime mimetext +npm install -D @cloudflare/workers-types wrangler typescript +``` + +Use postal-mime v2.x, mimetext v3.x. + +## tsconfig.json + +```json +{ + "compilerOptions": { + "target": "ES2022", "module": "ES2022", "lib": ["ES2022"], + "types": ["@cloudflare/workers-types"], + "moduleResolution": "bundler", "strict": true + } +} +``` + +## Local Development + +```bash +npx wrangler dev + +# Test receiving +curl --request POST 'http://localhost:8787/cdn-cgi/handler/email' \ + --url-query 'from=sender@example.com' --url-query 'to=recipient@example.com' \ + --header 'Content-Type: text/plain' --data-raw 'Subject: Test\n\nHello' +``` + +Sent emails write to local `.eml` files. + +## Deployment Checklist + +- [ ] Enable Email Routing in dashboard +- [ ] Verify destination addresses +- [ ] Configure DMARC/SPF/DKIM for sending +- [ ] Create KV/R2 resources if needed +- [ ] Update wrangler.jsonc with production IDs + +```bash +npx wrangler deploy +npx wrangler deployments list +``` + +## Dashboard Setup + +1. **Email Routing:** Domain → Email → Enable Email Routing +2. **Verify addresses:** Email → Destination addresses → Add & verify +3. **Bind Worker:** Email → Email Workers → Create route → Select pattern & Worker +4. **DMARC:** Add TXT `_dmarc.domain.com`: `v=DMARC1; p=quarantine;` + +## Secrets + +```bash +npx wrangler secret put API_KEY +# Access: env.API_KEY +``` + +## Monitoring + +```bash +npx wrangler tail +npx wrangler tail --status error +npx wrangler tail --format json +``` + +## Troubleshooting + +| Error | Fix | +|-------|-----| +| "Binding not found" | Check `send_email` name matches code | +| "Invalid destination" | Verify in Email Routing dashboard | +| Type errors | Install `@cloudflare/workers-types` | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..3700a50fdd84497e1158b7b24fdf6082a66cccbc --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/gotchas.md @@ -0,0 +1,125 @@ +# Email Workers Gotchas + +## Critical Issues + +### ReadableStream Single-Use + +```typescript +// ❌ WRONG: Stream consumed twice +const email = await PostalMime.parse(await new Response(message.raw).arrayBuffer()); +const rawText = await new Response(message.raw).text(); // EMPTY! + +// ✅ CORRECT: Buffer first +const buffer = await new Response(message.raw).arrayBuffer(); +const email = await PostalMime.parse(buffer); +const rawText = new TextDecoder().decode(buffer); +``` + +### ctx.waitUntil() Errors Silent + +```typescript +// ❌ Errors dropped silently +ctx.waitUntil(fetch(webhookUrl, { method: 'POST', body: data })); + +// ✅ Catch and log +ctx.waitUntil( + fetch(webhookUrl, { method: 'POST', body: data }) + .catch(err => env.ERROR_LOG.put(`error:${Date.now()}`, err.message)) +); +``` + +## Security + +### Envelope vs Header From (Spoofing) + +```typescript +const envelopeFrom = message.from; // SMTP MAIL FROM (trusted) +const headerFrom = (await PostalMime.parse(buffer)).from?.address; // (untrusted) +// Use envelope for security decisions +``` + +### Input Validation + +```typescript +if (message.rawSize > 5_000_000) { message.setReject('Too large'); return; } +if ((message.headers.get('Subject') || '').length > 1000) { + message.setReject('Invalid subject'); return; +} +``` + +### DMARC for Replies + +Replies fail silently without DMARC. Verify: `dig TXT _dmarc.example.com` + +## Parsing + +### Address Parsing + +```typescript +const email = await PostalMime.parse(buffer); +const fromAddress = email.from?.address || 'unknown'; +const toAddresses = Array.isArray(email.to) ? email.to.map(t => t.address) : [email.to?.address]; +``` + +### Character Encoding + +Let postal-mime handle decoding - `email.subject`, `email.text`, `email.html` are UTF-8. + +## API Behavior + +### setReject() vs throw + +```typescript +// setReject() for SMTP rejection +if (blockList.includes(message.from)) { message.setReject('Blocked'); return; } + +// throw for worker errors +if (!env.KV) throw new Error('KV not configured'); +``` + +### forward() Only X-* Headers + +```typescript +headers.set('X-Processed-By', 'worker'); // ✅ Works +headers.set('Subject', 'Modified'); // ❌ Dropped +``` + +### Reply Requires Verified Domain + +```typescript +// Use same domain as receiving address +const receivingDomain = message.to.split('@')[1]; +await message.reply(new EmailMessage(`noreply@${receivingDomain}`, message.from, rawMime)); +``` + +## Performance + +### CPU Limit + +```typescript +// Skip parsing large emails +if (message.rawSize > 5_000_000) { + await message.forward('inbox@example.com'); + return; +} +``` + +Monitor: `npx wrangler tail` + +## Limits + +| Limit | Value | +|-------|-------| +| Max message size | 25 MiB | +| Max rules/zone | 200 | +| CPU time (free/paid) | 10ms / 50ms | +| Reply References | 100 | + +## Common Errors + +| Error | Fix | +|-------|-----| +| "Address not verified" | Add in Email Routing dashboard | +| "Exceeded CPU time" | Use `ctx.waitUntil()` or upgrade | +| "Stream is locked" | Buffer `message.raw` first | +| Silent reply failure | Check DMARC records | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..f1e65f506ed6d8ca3e2ca7266fa56802dc40b99b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/email-workers/patterns.md @@ -0,0 +1,102 @@ +# Email Workers Patterns + +## Parse Email + +```typescript +import PostalMime from 'postal-mime'; + +export default { + async email(message, env, ctx) { + const buffer = await new Response(message.raw).arrayBuffer(); + const email = await PostalMime.parse(buffer); + console.log(email.from, email.subject, email.text, email.attachments.length); + await message.forward('inbox@example.com'); + } +}; +``` + +## Filtering + +```typescript +// Allowlist from KV +const allowList = await env.ALLOWED_SENDERS.get('list', 'json') || []; +if (!allowList.includes(message.from)) { + message.setReject('Not allowed'); + return; +} + +// Size check (avoid parsing large emails) +if (message.rawSize > 5_000_000) { + await message.forward('inbox@example.com'); // Forward without parsing + return; +} +``` + +## Auto-Reply with Threading + +```typescript +import { EmailMessage } from 'cloudflare:email'; +import { createMimeMessage } from 'mimetext'; + +const msg = createMimeMessage(); +msg.setSender({ addr: 'support@example.com' }); +msg.setRecipient(message.from); +msg.setSubject(`Re: ${message.headers.get('Subject')}`); +msg.setHeader('In-Reply-To', message.headers.get('Message-ID') || ''); +msg.addMessage({ contentType: 'text/plain', data: 'Thank you. We will respond.' }); + +await message.reply(new EmailMessage('support@example.com', message.from, msg.asRaw())); +``` + +## Rate-Limited Auto-Reply + +```typescript +const rateKey = `rate:${message.from}`; +if (!await env.RATE_LIMIT.get(rateKey)) { + // Send reply... + ctx.waitUntil(env.RATE_LIMIT.put(rateKey, '1', { expirationTtl: 3600 })); +} +``` + +## Subject-Based Routing + +```typescript +const subject = (message.headers.get('Subject') || '').toLowerCase(); +if (subject.includes('billing')) await message.forward('billing@example.com'); +else if (subject.includes('support')) await message.forward('support@example.com'); +else await message.forward('general@example.com'); +``` + +## Multi-Tenant Routing + +```typescript +// support+tenant123@example.com → tenant123 +const tenantId = message.to.split('@')[0].match(/\+(.+)$/)?.[1] || 'default'; +const config = await env.TENANT_CONFIG.get(tenantId, 'json'); +config?.forwardTo ? await message.forward(config.forwardTo) : message.setReject('Unknown'); +``` + +## Archive & Extract Attachments + +```typescript +// Archive to KV +ctx.waitUntil(env.ARCHIVE.put(`email:${Date.now()}`, JSON.stringify({ + from: message.from, subject: email.subject +}))); + +// Attachments to R2 +for (const att of email.attachments) { + ctx.waitUntil(env.R2.put(`${Date.now()}-${att.filename}`, att.content)); +} +``` + +## Webhook Integration + +```typescript +ctx.waitUntil( + fetch(env.WEBHOOK_URL, { + method: 'POST', + body: JSON.stringify({ from: message.from, subject: message.headers.get('Subject') }) + }).catch(err => console.error(err)) +); +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f1dd644b399b1f196d46b611a64125a74b3d1751 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/README.md @@ -0,0 +1,61 @@ +# Cloudflare Images Skill Reference + +**Cloudflare Images** is an end-to-end image management solution providing storage, transformation, optimization, and delivery at scale via Cloudflare's global network. + +## Quick Decision Tree + +**Need to:** +- **Transform in Worker?** → [api.md](api.md#workers-binding-api-2026-primary-method) (Workers Binding API) +- **Upload from Worker?** → [api.md](api.md#upload-from-worker) (REST API) +- **Upload from client?** → [patterns.md](patterns.md#upload-from-client-direct-creator-upload) (Direct Creator Upload) +- **Set up variants?** → [configuration.md](configuration.md#variants-configuration) +- **Serve responsive images?** → [patterns.md](patterns.md#responsive-images) +- **Add watermarks?** → [patterns.md](patterns.md#watermarking) +- **Fix errors?** → [gotchas.md](gotchas.md#common-errors) + +## Reading Order + +**For building image upload/transform feature:** +1. [configuration.md](configuration.md) - Setup Workers binding +2. [api.md](api.md#workers-binding-api-2026-primary-method) - Learn transform API +3. [patterns.md](patterns.md#upload-from-client-direct-creator-upload) - Direct upload pattern +4. [gotchas.md](gotchas.md) - Check limits and errors + +**For URL-based transforms:** +1. [configuration.md](configuration.md#variants-configuration) - Create variants +2. [api.md](api.md#url-transform-api) - URL syntax +3. [patterns.md](patterns.md#responsive-images) - Responsive patterns + +**For troubleshooting:** +1. [gotchas.md](gotchas.md#common-errors) - Error messages +2. [gotchas.md](gotchas.md#limits) - Size/format limits + +## Core Methods + +| Method | Use Case | Location | +|--------|----------|----------| +| `env.IMAGES.input().transform()` | Transform in Worker | [api.md:11](api.md) | +| REST API `/images/v1` | Upload images | [api.md:57](api.md) | +| Direct Creator Upload | Client-side upload | [api.md:127](api.md) | +| URL transforms | Static image delivery | [api.md:112](api.md) | + +## In This Reference + +- **[api.md](api.md)** - Complete API: Workers binding, REST endpoints, URL transforms +- **[configuration.md](configuration.md)** - Setup: wrangler.toml, variants, auth, signed URLs +- **[patterns.md](patterns.md)** - Patterns: responsive images, watermarks, format negotiation, caching +- **[gotchas.md](gotchas.md)** - Troubleshooting: limits, errors, best practices + +## Key Features + +- **Automatic Optimization** - AVIF/WebP format negotiation +- **On-the-fly Transforms** - Resize, crop, blur, sharpen via URL or API +- **Workers Binding** - Transform images in Workers (2026 primary method) +- **Direct Upload** - Secure client-side uploads without backend proxy +- **Global Delivery** - Cached at 300+ Cloudflare data centers +- **Watermarking** - Overlay images programmatically + +## See Also + +- [Official Docs](https://developers.cloudflare.com/images/) +- [Workers Examples](https://developers.cloudflare.com/images/tutorials/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/api.md new file mode 100644 index 0000000000000000000000000000000000000000..c172e2269e4e1db2eea8912395a825e02e96b89a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/api.md @@ -0,0 +1,96 @@ +# API Reference + +## Workers Binding API + +```toml +# wrangler.toml +[images] +binding = "IMAGES" +``` + +### Transform Images + +```typescript +const imageResponse = await env.IMAGES + .input(fileBuffer) + .transform({ width: 800, height: 600, fit: "cover", quality: 85, format: "avif" }) + .output(); +return imageResponse.response(); +``` + +### Transform Options + +```typescript +interface TransformOptions { + width?: number; height?: number; + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad"; + quality?: number; // 1-100 + format?: "avif" | "webp" | "jpeg" | "png"; + dpr?: number; // 1-3 + gravity?: "auto" | "left" | "right" | "top" | "bottom" | "face" | string; + sharpen?: number; // 0-10 + blur?: number; // 1-250 + rotate?: 90 | 180 | 270; + background?: string; // CSS color for pad + metadata?: "none" | "copyright" | "keep"; + brightness?: number; contrast?: number; gamma?: number; // 0-2 +} +``` + +### Draw/Watermark + +```typescript +await env.IMAGES.input(baseImage) + .draw(env.IMAGES.input(watermark).transform({ width: 100 }), { top: 10, left: 10, opacity: 0.8 }) + .output(); +``` + +## REST API + +### Upload Image + +```bash +curl -X POST https://api.cloudflare.com/client/v4/accounts/{account_id}/images/v1 \ + -H "Authorization: Bearer {token}" -F file=@image.jpg -F metadata='{"key":"value"}' +``` + +### Other Operations + +```bash +GET /accounts/{account_id}/images/v1/{image_id} # Get details +DELETE /accounts/{account_id}/images/v1/{image_id} # Delete +GET /accounts/{account_id}/images/v1?page=1 # List +``` + +## URL Transform API + +``` +https://imagedelivery.net/{hash}/{id}/width=800,height=600,fit=cover,format=avif +``` + +**Params:** `w=`, `h=`, `fit=`, `q=`, `f=`, `dpr=`, `gravity=`, `sharpen=`, `blur=`, `rotate=`, `background=`, `metadata=` + +## Direct Creator Upload + +```typescript +// 1. Get upload URL (backend) +const { result } = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/images/v2/direct_upload`, + { method: 'POST', headers: { 'Authorization': `Bearer ${token}` }, + body: JSON.stringify({ requireSignedURLs: false }) } +).then(r => r.json()); + +// 2. Client uploads to result.uploadURL +const formData = new FormData(); +formData.append('file', file); +await fetch(result.uploadURL, { method: 'POST', body: formData }); +``` + +## Error Codes + +| Code | Message | Solution | +|------|---------|----------| +| 5400 | Invalid format | Use JPEG, PNG, GIF, WebP | +| 5401 | Too large | Max 100MB | +| 5403 | Invalid transform | Check params | +| 9413 | Rate limit | Implement backoff | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..1d7a3a1dbabfcb8a5bd8b94fa7692d628c7368d4 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/configuration.md @@ -0,0 +1,211 @@ +# Configuration + +## Wrangler Integration + +### Workers Binding Setup + +Add to `wrangler.toml`: + +```toml +name = "my-image-worker" +main = "src/index.ts" +compatibility_date = "2024-01-01" + +[images] +binding = "IMAGES" +``` + +Access in Worker: + +```typescript +interface Env { + IMAGES: ImageBinding; +} + +export default { + async fetch(request: Request, env: Env): Promise { + return await env.IMAGES + .input(imageBuffer) + .transform({ width: 800 }) + .output() + .response(); + } +}; +``` + +### Upload via Script + +Wrangler doesn't have built-in Images commands, use REST API: + +```typescript +// scripts/upload-image.ts +import fs from 'fs'; +import FormData from 'form-data'; + +async function uploadImage(filePath: string) { + const accountId = process.env.CLOUDFLARE_ACCOUNT_ID!; + const apiToken = process.env.CLOUDFLARE_API_TOKEN!; + + const formData = new FormData(); + formData.append('file', fs.createReadStream(filePath)); + + const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/images/v1`, + { + method: 'POST', + headers: { + 'Authorization': `Bearer ${apiToken}`, + }, + body: formData, + } + ); + + const result = await response.json(); + console.log('Uploaded:', result); +} + +uploadImage('./photo.jpg'); +``` + +### Environment Variables + +Store account hash for URL construction: + +```toml +[vars] +IMAGES_ACCOUNT_HASH = "your-account-hash" +ACCOUNT_ID = "your-account-id" +``` + +Access in Worker: + +```typescript +const imageUrl = `https://imagedelivery.net/${env.IMAGES_ACCOUNT_HASH}/${imageId}/public`; +``` + +## Variants Configuration + +Variants are named presets for transformations. + +### Create Variant (Dashboard) + +1. Navigate to Images → Variants +2. Click "Create Variant" +3. Set name (e.g., `thumbnail`) +4. Configure: `width=200,height=200,fit=cover` + +### Create Variant (API) + +```bash +curl -X POST \ + https://api.cloudflare.com/client/v4/accounts/{account_id}/images/v1/variants \ + -H "Authorization: Bearer {api_token}" \ + -H "Content-Type: application/json" \ + -d '{ + "id": "thumbnail", + "options": { + "width": 200, + "height": 200, + "fit": "cover" + }, + "neverRequireSignedURLs": true + }' +``` + +### Use Variant + +``` +https://imagedelivery.net/{account_hash}/{image_id}/thumbnail +``` + +### Common Variant Presets + +```json +{ + "thumbnail": { + "width": 200, + "height": 200, + "fit": "cover" + }, + "avatar": { + "width": 128, + "height": 128, + "fit": "cover", + "gravity": "face" + }, + "hero": { + "width": 1920, + "height": 1080, + "fit": "cover", + "quality": 90 + }, + "mobile": { + "width": 640, + "fit": "scale-down", + "quality": 80, + "format": "avif" + } +} +``` + +## Authentication + +### API Token (Recommended) + +Generate at: Dashboard → My Profile → API Tokens + +Required permissions: +- Account → Cloudflare Images → Edit + +```bash +curl -H "Authorization: Bearer {api_token}" \ + https://api.cloudflare.com/client/v4/accounts/{account_id}/images/v1 +``` + +### API Key (Legacy) + +```bash +curl -H "X-Auth-Email: {email}" \ + -H "X-Auth-Key: {api_key}" \ + https://api.cloudflare.com/client/v4/accounts/{account_id}/images/v1 +``` + +## Signed URLs + +For private images, enable signed URLs: + +```bash +# Upload with signed URLs required +curl -X POST \ + https://api.cloudflare.com/client/v4/accounts/{account_id}/images/v1 \ + -H "Authorization: Bearer {api_token}" \ + -F file=@private.jpg \ + -F requireSignedURLs=true +``` + +Generate signed URL: + +```typescript +import { createHmac } from 'crypto'; + +function signUrl(imageId: string, variant: string, expiry: number, key: string): string { + const path = `/${imageId}/${variant}`; + const toSign = `${path}${expiry}`; + const signature = createHmac('sha256', key) + .update(toSign) + .digest('hex'); + + return `https://imagedelivery.net/{hash}${path}?exp=${expiry}&sig=${signature}`; +} + +// Sign URL valid for 1 hour +const signedUrl = signUrl('image-id', 'public', Date.now() + 3600, env.SIGNING_KEY); +``` + +## Local Development + +```bash +npx wrangler dev --remote +``` + +Must use `--remote` for Images binding access. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..6f52455a248b1d7a52c14f9185ca6ba88e69ba6f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/gotchas.md @@ -0,0 +1,99 @@ +# Gotchas & Best Practices + +## Fit Modes + +| Mode | Best For | Behavior | +|------|----------|----------| +| `cover` | Hero images, thumbnails | Fills space, crops excess | +| `contain` | Product images, artwork | Preserves full image, may add padding | +| `scale-down` | User uploads | Never enlarges | +| `crop` | Precise crops | Uses gravity | +| `pad` | Fixed aspect ratio | Adds background | + +## Format Selection + +```typescript +format: 'auto' // Recommended - negotiates best format +``` + +**Support:** AVIF (Chrome 85+, Firefox 93+, Safari 16.4+), WebP (Chrome 23+, Firefox 65+, Safari 14+) + +## Quality Settings + +| Use Case | Quality | +|----------|---------| +| Thumbnails | 75-80 | +| Standard | 85 (default) | +| High-quality | 90-95 | + +## Common Errors + +### 5403: "Image transformation failed" +- Verify `width`/`height` ≤ 12000 +- Check `quality` 1-100, `dpr` 1-3 +- Don't combine incompatible options + +### 9413: "Rate limit exceeded" +Implement caching and exponential backoff: +```typescript +for (let i = 0; i < 3; i++) { + try { return await env.IMAGES.input(buffer).transform({...}).output(); } + catch { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } +} +``` + +### 5401: "Image too large" +Pre-process images before upload (max 100MB, 12000×12000px) + +### 5400: "Invalid image format" +Supported: JPEG, PNG, GIF, WebP, AVIF, SVG + +### 401/403: "Unauthorized" +Verify API token has `Cloudflare Images → Edit` permission + +## Limits + +| Resource | Limit | +|----------|-------| +| Max input size | 100MB | +| Max dimensions | 12000×12000px | +| Quality range | 1-100 | +| DPR range | 1-3 | +| API rate limit | ~1200 req/min | + +## AVIF Gotchas + +- **Slower encoding**: First request may have higher latency +- **Browser detection**: +```typescript +const format = /image\/avif/.test(request.headers.get('Accept') || '') ? 'avif' : 'webp'; +``` + +## Anti-Patterns + +```typescript +// ❌ No caching - transforms every request +return env.IMAGES.input(buffer).transform({...}).output().response(); + +// ❌ cover without both dimensions +transform({ width: 800, fit: 'cover' }) + +// ✅ Always set both for cover +transform({ width: 800, height: 600, fit: 'cover' }) + +// ❌ Exposes API token to client +// ✅ Use Direct Creator Upload (patterns.md) +``` + +## Debugging + +```typescript +// Check response headers +console.log('Content-Type:', response.headers.get('Content-Type')); + +// Test with curl +// curl -I "https://imagedelivery.net/{hash}/{id}/width=800,format=avif" + +// Monitor logs +// npx wrangler tail +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..c07bf3cd2f9fff0e41830e0b7810b7dda025680f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/images/patterns.md @@ -0,0 +1,115 @@ +# Common Patterns + +## URL Transform Options + +``` +width= height= fit=scale-down|contain|cover|crop|pad +quality=85 format=auto|webp|avif|jpeg|png dpr=2 +gravity=auto|face|left|right|top|bottom sharpen=2 blur=10 +rotate=90|180|270 background=white metadata=none|copyright|keep +``` + +## Responsive Images (srcset) + +```html + +``` + +## Format Negotiation + +```typescript +async fetch(request: Request, env: Env): Promise { + const accept = request.headers.get('Accept') || ''; + const format = /image\/avif/.test(accept) ? 'avif' : /image\/webp/.test(accept) ? 'webp' : 'jpeg'; + return env.IMAGES.input(buffer).transform({ format, quality: 85 }).output().response(); +} +``` + +## Direct Creator Upload + +```typescript +// Backend: Generate upload URL +const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/images/v2/direct_upload`, + { method: 'POST', headers: { 'Authorization': `Bearer ${env.API_TOKEN}` }, + body: JSON.stringify({ requireSignedURLs: false, metadata: { userId } }) } +); + +// Frontend: Upload to returned uploadURL +const formData = new FormData(); +formData.append('file', file); +await fetch(result.uploadURL, { method: 'POST', body: formData }); +// Use: https://imagedelivery.net/{hash}/${result.id}/public +``` + +## Transform & Store to R2 + +```typescript +async fetch(request: Request, env: Env): Promise { + const file = (await request.formData()).get('image') as File; + const transformed = await env.IMAGES + .input(await file.arrayBuffer()) + .transform({ width: 800, format: 'avif', quality: 80 }) + .output(); + await env.R2.put(`images/${Date.now()}.avif`, transformed.response().body); + return Response.json({ success: true }); +} +``` + +## Watermarking + +```typescript +const watermark = await env.ASSETS.fetch(new URL('/watermark.png', request.url)); +const result = await env.IMAGES + .input(await image.arrayBuffer()) + .draw(env.IMAGES.input(watermark.body).transform({ width: 100 }), { bottom: 20, right: 20, opacity: 0.7 }) + .transform({ format: 'avif' }) + .output(); +return result.response(); +``` + +## Device-Based Transforms + +```typescript +const ua = request.headers.get('User-Agent') || ''; +const isMobile = /Mobile|Android|iPhone/i.test(ua); +return env.IMAGES.input(buffer) + .transform({ width: isMobile ? 400 : 1200, quality: isMobile ? 75 : 85, format: 'avif' }) + .output().response(); +``` + +## Caching Strategy + +```typescript +async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const cache = caches.default; + let response = await cache.match(request); + if (!response) { + response = await env.IMAGES.input(buffer).transform({ width: 800, format: 'avif' }).output().response(); + response = new Response(response.body, { headers: { ...response.headers, 'Cache-Control': 'public, max-age=86400' } }); + ctx.waitUntil(cache.put(request, response.clone())); + } + return response; +} +``` + +## Batch Processing + +```typescript +const results = await Promise.all(images.map(buffer => + env.IMAGES.input(buffer).transform({ width: 800, fit: 'cover', format: 'avif' }).output() +)); +``` + +## Error Handling + +```typescript +try { + return (await env.IMAGES.input(buffer).transform({ width: 800 }).output()).response(); +} catch (error) { + console.error('Transform failed:', error); + return new Response('Image processing failed', { status: 500 }); +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/README.md new file mode 100644 index 0000000000000000000000000000000000000000..82baf7cb79369a371febf26798396271852f5809 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/README.md @@ -0,0 +1,105 @@ +# Miniflare + +Local simulator for Cloudflare Workers development/testing. Runs Workers in workerd sandbox implementing runtime APIs - no internet required. + +## Features + +- Full-featured: KV, Durable Objects, R2, D1, WebSockets, Queues +- Fully-local: test without internet, instant reload +- TypeScript-native: detailed logging, source maps +- Advanced testing: dispatch events without HTTP, simulate Worker connections + +## When to Use + +**Decision tree for testing Workers:** + +``` +Need to test Workers? +│ +├─ Unit tests for business logic only? +│ └─ getPlatformProxy (Vitest/Jest) → [patterns.md](./patterns.md#getplatformproxy) +│ Fast, no HTTP, direct binding access +│ +├─ Integration tests with full runtime? +│ ├─ Single Worker? +│ │ └─ Miniflare API → [Quick Start](#quick-start) +│ │ Full control, programmatic access +│ │ +│ ├─ Multiple Workers + service bindings? +│ │ └─ Miniflare workers array → [configuration.md](./configuration.md#multiple-workers) +│ │ Shared storage, inter-worker calls +│ │ +│ └─ Vitest test runner integration? +│ └─ vitest-pool-workers → [patterns.md](./patterns.md#vitest-pool-workers) +│ Full Workers env in Vitest +│ +└─ Local dev server? + └─ wrangler dev (not Miniflare) + Hot reload, automatic config +``` + +**Use Miniflare for:** +- Integration tests with full Worker runtime +- Testing bindings/storage locally +- Multiple Workers with service bindings +- Programmatic event dispatch (fetch, queue, scheduled) + +**Use getPlatformProxy for:** +- Fast unit tests of business logic +- Testing without HTTP overhead +- Vitest/Jest environments + +**Use Wrangler for:** +- Local development workflow +- Production deployments + +## Setup + +```bash +npm i -D miniflare +``` + +Requires ES modules in `package.json`: +```json +{"type": "module"} +``` + +## Quick Start + +```js +import { Miniflare } from "miniflare"; + +const mf = new Miniflare({ + modules: true, + script: ` + export default { + async fetch(request, env, ctx) { + return new Response("Hello Miniflare!"); + } + } + `, +}); + +const res = await mf.dispatchFetch("http://localhost:8787/"); +console.log(await res.text()); // Hello Miniflare! +await mf.dispose(); +``` + +## Reading Order + +**New to Miniflare?** Start here: +1. [Quick Start](#quick-start) - Running in 2 minutes +2. [When to Use](#when-to-use) - Choose your testing approach +3. [patterns.md](./patterns.md) - Testing patterns (getPlatformProxy, Vitest, node:test) +4. [configuration.md](./configuration.md) - Configure bindings, storage, multiple workers + +**Troubleshooting:** +- [gotchas.md](./gotchas.md) - Common errors and debugging + +**API reference:** +- [api.md](./api.md) - Complete method reference + +## See Also +- [wrangler](../wrangler/) - CLI tool that embeds Miniflare for `wrangler dev` +- [workerd](../workerd/) - Runtime that powers Miniflare +- [workers](../workers/) - Workers runtime API documentation diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/api.md new file mode 100644 index 0000000000000000000000000000000000000000..b482e4a4c708eca6e44807f8330c5cab8ec1f89d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/api.md @@ -0,0 +1,187 @@ +# Programmatic API + +## Miniflare Class + +```typescript +class Miniflare { + constructor(options: MiniflareOptions); + + // Lifecycle + ready: Promise; // Resolves when server ready, returns URL + dispose(): Promise; // Cleanup resources + setOptions(options: MiniflareOptions): Promise; // Reload config + + // Event dispatching + dispatchFetch(url: string | URL | Request, init?: RequestInit): Promise; + getWorker(name?: string): Promise; + + // Bindings access + getBindings>(name?: string): Promise; + getCf(name?: string): Promise; + getKVNamespace(name: string): Promise; + getR2Bucket(name: string): Promise; + getDurableObjectNamespace(name: string): Promise; + getDurableObjectStorage(id: DurableObjectId): Promise; + getD1Database(name: string): Promise; + getCaches(): Promise; + getQueueProducer(name: string): Promise; + + // Debugging + getInspectorURL(): Promise; // Chrome DevTools inspector URL +} +``` + +## Event Dispatching + +**Fetch (no HTTP server):** +```js +const res = await mf.dispatchFetch("http://localhost:8787/path", { + method: "POST", + headers: { "Authorization": "Bearer token" }, + body: JSON.stringify({ data: "value" }), +}); +``` + +**Custom Host routing:** +```js +const res = await mf.dispatchFetch("http://localhost:8787/", { + headers: { "Host": "api.example.com" }, +}); +``` + +**Scheduled:** +```js +const worker = await mf.getWorker(); +const result = await worker.scheduled({ cron: "30 * * * *" }); +// result: { outcome: "ok", noRetry: false } +``` + +**Queue:** +```js +const worker = await mf.getWorker(); +const result = await worker.queue("queue-name", [ + { id: "msg1", timestamp: new Date(), body: "data", attempts: 1 }, +]); +// result: { outcome: "ok", retryAll: false, ackAll: false, ... } +``` + +## Bindings Access + +**Environment variables:** +```js +// Basic usage +const bindings = await mf.getBindings(); +console.log(bindings.SECRET_KEY); + +// With type safety (recommended): +interface Env { + SECRET_KEY: string; + API_URL: string; + KV: KVNamespace; +} +const env = await mf.getBindings(); +env.SECRET_KEY; // string (typed!) +env.KV.get("key"); // KVNamespace methods available +``` + +**Request.cf object:** +```js +const cf = await mf.getCf(); +console.log(cf?.colo); // "DFW" +console.log(cf?.country); // "US" +``` + +**KV:** +```js +const ns = await mf.getKVNamespace("TEST_NAMESPACE"); +await ns.put("key", "value"); +const value = await ns.get("key"); +``` + +**R2:** +```js +const bucket = await mf.getR2Bucket("BUCKET"); +await bucket.put("file.txt", "content"); +const object = await bucket.get("file.txt"); +``` + +**Durable Objects:** +```js +const ns = await mf.getDurableObjectNamespace("COUNTER"); +const id = ns.idFromName("test"); +const stub = ns.get(id); +const res = await stub.fetch("http://localhost/"); + +// Access storage directly: +const storage = await mf.getDurableObjectStorage(id); +await storage.put("key", "value"); +``` + +**D1:** +```js +const db = await mf.getD1Database("DB"); +await db.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)`); +await db.prepare("INSERT INTO users (name) VALUES (?)").bind("Alice").run(); +``` + +**Cache:** +```js +const caches = await mf.getCaches(); +const defaultCache = caches.default; +await defaultCache.put("http://example.com", new Response("cached")); +``` + +**Queue producer:** +```js +const producer = await mf.getQueueProducer("QUEUE"); +await producer.send({ body: "message data" }); +``` + +## Lifecycle + +**Reload:** +```js +await mf.setOptions({ + scriptPath: "worker.js", + bindings: { VERSION: "2.0" }, +}); +``` + +**Watch (manual):** +```js +import { watch } from "fs"; + +const config = { scriptPath: "worker.js" }; +const mf = new Miniflare(config); + +watch("worker.js", async () => { + console.log("Reloading..."); + await mf.setOptions(config); +}); +``` + +**Cleanup:** +```js +await mf.dispose(); +``` + +## Debugging + +**Inspector URL for DevTools:** +```js +const url = await mf.getInspectorURL(); +console.log(`DevTools: ${url}`); +// Open in Chrome DevTools for breakpoints, profiling +``` + +**Wait for server ready:** +```js +const mf = new Miniflare({ scriptPath: "worker.js" }); +const url = await mf.ready; // Promise +console.log(`Server running at ${url}`); // http://127.0.0.1:8787 + +// Note: dispatchFetch() waits automatically, no need to await ready +const res = await mf.dispatchFetch("http://localhost/"); // Works immediately +``` + +See [configuration.md](./configuration.md) for all constructor options. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..0c57bd0c4c83ffdf6e1241f8962e41f9c28d0628 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/configuration.md @@ -0,0 +1,173 @@ +# Configuration + +## Script Loading + +```js +// Inline +new Miniflare({ modules: true, script: `export default { ... }` }); + +// File-based +new Miniflare({ scriptPath: "worker.js" }); + +// Multi-module +new Miniflare({ + scriptPath: "src/index.js", + modules: true, + modulesRules: [ + { type: "ESModule", include: ["**/*.js"] }, + { type: "Text", include: ["**/*.txt"] }, + ], +}); +``` + +## Compatibility + +```js +new Miniflare({ + compatibilityDate: "2026-01-01", // Use recent date for latest features + compatibilityFlags: [ + "nodejs_compat", // Node.js APIs (process, Buffer, etc) + "streams_enable_constructors", // Stream constructors + ], + upstream: "https://example.com", // Fallback for unhandled requests +}); +``` + +**Critical:** Use `compatibilityDate: "2026-01-01"` or latest to match production runtime. Old dates limit available APIs. + +## HTTP Server & Request.cf + +```js +new Miniflare({ + port: 8787, // Default: 8787 + host: "127.0.0.1", + https: true, // Self-signed cert + liveReload: true, // Auto-reload HTML + + cf: true, // Fetch live Request.cf data (cached) + // cf: "./cf.json", // Or load from file + // cf: { colo: "DFW" }, // Or inline mock +}); +``` + +**Note:** For tests, use `dispatchFetch()` (no port conflicts). + +## Storage Bindings + +```js +new Miniflare({ + // KV + kvNamespaces: ["TEST_NAMESPACE", "CACHE"], + kvPersist: "./kv-data", // Optional: persist to disk + + // R2 + r2Buckets: ["BUCKET", "IMAGES"], + r2Persist: "./r2-data", + + // Durable Objects + modules: true, + durableObjects: { + COUNTER: "Counter", // className + API_OBJECT: { className: "ApiObject", scriptName: "api-worker" }, + }, + durableObjectsPersist: "./do-data", + + // D1 + d1Databases: ["DB"], + d1Persist: "./d1-data", + + // Cache + cache: true, // Default + cachePersist: "./cache-data", +}); +``` + +## Bindings + +```js +new Miniflare({ + // Environment variables + bindings: { + SECRET_KEY: "my-secret-value", + API_URL: "https://api.example.com", + DEBUG: true, + }, + + // Other bindings + wasmBindings: { ADD_MODULE: "./add.wasm" }, + textBlobBindings: { TEXT: "./data.txt" }, + queueProducers: ["QUEUE"], +}); +``` + +## Multiple Workers + +```js +new Miniflare({ + workers: [ + { + name: "main", + kvNamespaces: { DATA: "shared" }, + serviceBindings: { API: "api-worker" }, + script: `export default { ... }`, + }, + { + name: "api-worker", + kvNamespaces: { DATA: "shared" }, // Shared storage + script: `export default { ... }`, + }, + ], +}); +``` + +**With routing:** +```js +workers: [ + { name: "api", scriptPath: "./api.js", routes: ["api.example.com/*"] }, + { name: "web", scriptPath: "./web.js", routes: ["example.com/*"] }, +], +``` + +## Logging & Performance + +```js +import { Log, LogLevel } from "miniflare"; + +new Miniflare({ + log: new Log(LogLevel.DEBUG), // DEBUG | INFO | WARN | ERROR | NONE + scriptTimeout: 30000, // CPU limit (ms) + workersConcurrencyLimit: 10, // Max concurrent workers +}); +``` + +## Workers Sites + +```js +new Miniflare({ + sitePath: "./public", + siteInclude: ["**/*.html", "**/*.css"], + siteExclude: ["**/*.map"], +}); +``` + +## From wrangler.toml + +Miniflare doesn't auto-read `wrangler.toml`: + +```toml +# wrangler.toml +name = "my-worker" +main = "src/index.ts" +compatibility_date = "2026-01-01" +[[kv_namespaces]] +binding = "KV" +``` + +```js +// Miniflare equivalent +new Miniflare({ + scriptPath: "src/index.ts", + compatibilityDate: "2026-01-01", + kvNamespaces: ["KV"], +}); +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..b90192047a108c7af0d58ebe9ba291032157d242 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/gotchas.md @@ -0,0 +1,160 @@ +# Gotchas & Troubleshooting + +## Miniflare Limitations + +**Not supported:** +- Analytics Engine (use mocks) +- Cloudflare Images/Stream +- Browser Rendering API +- Tail Workers +- Workers for Platforms (partial support) + +**Behavior differences from production:** +- Runs workerd locally, not Cloudflare edge +- Storage is local (filesystem/memory), not distributed +- `Request.cf` is cached/mocked, not real edge data +- Performance differs from edge +- Caching implementation may vary slightly + +## Common Errors + +### "Cannot find module" +**Cause:** Module path wrong or `modulesRules` not configured +**Solution:** +```js +new Miniflare({ + modules: true, + modulesRules: [{ type: "ESModule", include: ["**/*.js"] }], +}); +``` + +### "Data not persisting" +**Cause:** Persist paths are files, not directories +**Solution:** +```js +kvPersist: "./data/kv", // Directory, not file +``` + +### "Cannot run TypeScript" +**Cause:** Miniflare doesn't transpile TypeScript +**Solution:** Build first with esbuild/tsc, then run compiled JS + +### "`request.cf` is undefined" +**Cause:** CF data not configured +**Solution:** +```js +new Miniflare({ cf: true }); // Or cf: "./cf.json" +``` + +### "EADDRINUSE" port conflict +**Cause:** Multiple instances using same port +**Solution:** Use `dispatchFetch()` (no HTTP server) or `port: 0` for auto-assign + +### "Durable Object not found" +**Cause:** Class export doesn't match config name +**Solution:** +```js +export class Counter {} // Must match +new Miniflare({ durableObjects: { COUNTER: "Counter" } }); +``` + +## Debugging + +**Enable verbose logging:** +```js +import { Log, LogLevel } from "miniflare"; +new Miniflare({ log: new Log(LogLevel.DEBUG) }); +``` + +**Chrome DevTools:** +```js +const url = await mf.getInspectorURL(); +console.log(`DevTools: ${url}`); // Open in Chrome +``` + +**Inspect bindings:** +```js +const env = await mf.getBindings(); +console.log(Object.keys(env)); +``` + +**Verify storage:** +```js +const ns = await mf.getKVNamespace("TEST"); +const { keys } = await ns.list(); +``` + +## Best Practices + +**✓ Do:** +- Use `dispatchFetch()` for tests (no HTTP server) +- In-memory storage for CI (omit persist options) +- New instances per test for isolation +- Type-safe bindings with interfaces +- `await mf.dispose()` in cleanup + +**✗ Avoid:** +- HTTP server in tests +- Shared instances without cleanup +- Old compatibility dates (use 2026+) + +## Migration Guides + +### From Miniflare 2.x to 3+ + +Breaking changes in v3+: + +| v2 | v3+ | +|----|-----| +| `getBindings()` sync | `getBindings()` returns Promise | +| `ready` is void | `ready` returns `Promise` | +| service-worker-mock | Built on workerd | +| Different options | Restructured constructor | + +**Example migration:** +```js +// v2 +const bindings = mf.getBindings(); +mf.ready; // void + +// v3+ +const bindings = await mf.getBindings(); +const url = await mf.ready; // Promise +``` + +### From unstable_dev to Miniflare + +```js +// Old (deprecated) +import { unstable_dev } from "wrangler"; +const worker = await unstable_dev("src/index.ts"); + +// New +import { Miniflare } from "miniflare"; +const mf = new Miniflare({ scriptPath: "src/index.ts" }); +``` + +### From Wrangler Dev + +Miniflare doesn't auto-read `wrangler.toml`: + +```js +// Translate manually: +new Miniflare({ + scriptPath: "dist/worker.js", + compatibilityDate: "2026-01-01", + kvNamespaces: ["KV"], + bindings: { API_KEY: process.env.API_KEY }, +}); +``` + +## Resource Limits + +| Limit | Value | Notes | +|-------|-------|-------| +| CPU time | 30s default | Configurable via `scriptTimeout` | +| Storage | Filesystem | Performance varies by disk | +| Memory | System dependent | No artificial limits | +| Request.cf | Cached/mocked | Not live edge data | + +See [patterns.md](./patterns.md) for testing examples. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..4d2bab96594d90b7d5cd8296f91e4bc5a6039b44 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/miniflare/patterns.md @@ -0,0 +1,181 @@ +# Testing Patterns + +## Choosing a Testing Approach + +| Approach | Use Case | Speed | Setup | Runtime | +|----------|----------|-------|-------|---------| +| **getPlatformProxy** | Unit tests, logic testing | Fast | Low | Miniflare | +| **Miniflare API** | Integration tests, full control | Medium | Medium | Miniflare | +| **vitest-pool-workers** | Vitest runner integration | Medium | Medium | workerd | + +**Quick guide:** +- Unit tests → getPlatformProxy +- Integration tests → Miniflare API +- Vitest workflows → vitest-pool-workers + +## getPlatformProxy + +Lightweight unit testing - provides bindings without full Worker runtime. + +```js +// vitest.config.js +export default { test: { environment: "node" } }; +``` + +```js +import { env } from "cloudflare:test"; +import { describe, it, expect } from "vitest"; + +describe("Business logic", () => { + it("processes data with KV", async () => { + await env.KV.put("test", "value"); + expect(await env.KV.get("test")).toBe("value"); + }); +}); +``` + +**Pros:** Fast, simple +**Cons:** No full runtime, can't test fetch handler + +## vitest-pool-workers + +Full Workers runtime in Vitest. Reads `wrangler.toml`. + +```bash +npm i -D @cloudflare/vitest-pool-workers +``` + +```js +// vitest.config.js +import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; + +export default defineWorkersConfig({ + test: { + poolOptions: { workers: { wrangler: { configPath: "./wrangler.toml" } } }, + }, +}); +``` + +```js +import { env, SELF } from "cloudflare:test"; +import { it, expect } from "vitest"; + +it("handles fetch", async () => { + const res = await SELF.fetch("http://example.com/"); + expect(res.status).toBe(200); +}); +``` + +**Pros:** Full runtime, uses wrangler.toml +**Cons:** Requires Wrangler config + +## Miniflare API (node:test) + +```js +import assert from "node:assert"; +import test, { after, before } from "node:test"; +import { Miniflare } from "miniflare"; + +let mf; +before(() => { + mf = new Miniflare({ scriptPath: "src/index.js", kvNamespaces: ["TEST_KV"] }); +}); + +test("fetch", async () => { + const res = await mf.dispatchFetch("http://localhost/"); + assert.strictEqual(await res.text(), "Hello"); +}); + +after(() => mf.dispose()); +``` + +## Testing Durable Objects & Events + +```js +// Durable Objects +const ns = await mf.getDurableObjectNamespace("COUNTER"); +const stub = ns.get(ns.idFromName("test-counter")); +await stub.fetch("http://localhost/increment"); + +// Direct storage +const storage = await mf.getDurableObjectStorage(ns.idFromName("test-counter")); +const count = await storage.get("count"); + +// Queue +const worker = await mf.getWorker(); +await worker.queue("my-queue", [ + { id: "msg1", timestamp: new Date(), body: { userId: 123 }, attempts: 1 }, +]); + +// Scheduled +await worker.scheduled({ cron: "0 0 * * *" }); +``` + +## Test Isolation & Mocking + +```js +// Per-test isolation +beforeEach(() => { mf = new Miniflare({ kvNamespaces: ["TEST"] }); }); +afterEach(() => mf.dispose()); + +// Mock external APIs +new Miniflare({ + workers: [ + { name: "main", serviceBindings: { API: "mock-api" }, script: `...` }, + { name: "mock-api", script: `export default { async fetch() { return Response.json({mock: true}); } }` }, + ], +}); +``` + +## Type Safety + +```ts +import type { KVNamespace } from "@cloudflare/workers-types"; + +interface Env { + KV: KVNamespace; + API_KEY: string; +} + +const env = await mf.getBindings(); +await env.KV.put("key", "value"); // Typed! + +export default { + async fetch(req: Request, env: Env) { + return new Response(await env.KV.get("key")); + } +} satisfies ExportedHandler; +``` + +## WebSocket Testing + +```js +const res = await mf.dispatchFetch("http://localhost/ws", { + headers: { Upgrade: "websocket" }, +}); +assert.strictEqual(res.status, 101); +``` + +## Migration from unstable_dev + +```js +// Old (deprecated) +import { unstable_dev } from "wrangler"; +const worker = await unstable_dev("src/index.ts"); + +// New +import { Miniflare } from "miniflare"; +const mf = new Miniflare({ scriptPath: "src/index.ts" }); +``` + +## CI/CD Tips + +```js +// In-memory storage (faster) +new Miniflare({ kvNamespaces: ["TEST"] }); // No persist = in-memory + +// Use dispatchFetch (no port conflicts) +await mf.dispatchFetch("http://localhost/"); +``` + +See [gotchas.md](./gotchas.md) for troubleshooting. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e337f1bd54a33362d5d83febae558c875fbdc64e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/README.md @@ -0,0 +1,99 @@ +# Cloudflare Network Interconnect (CNI) + +Private, high-performance connectivity to Cloudflare's network. **Enterprise-only**. + +## Connection Types + +**Direct**: Physical fiber in shared datacenter. 10/100 Gbps. You order cross-connect. + +**Partner**: Virtual via Console Connect, Equinix, Megaport, etc. Managed via partner SDN. + +**Cloud**: AWS Direct Connect or GCP Cloud Interconnect. Magic WAN only. + +## Dataplane Versions + +**v1 (Classic)**: GRE tunnel support, VLAN/BFD/LACP, asymmetric MTU (1500↓/1476↑), peering support. + +**v2 (Beta)**: No GRE, 1500 MTU both ways, no VLAN/BFD/LACP yet, ECMP instead. + +## Use Cases + +- **Magic Transit DSR**: DDoS protection, egress via ISP (v1/v2) +- **Magic Transit + Egress**: DDoS + egress via CF (v1/v2) +- **Magic WAN + Zero Trust**: Private backbone (v1 needs GRE, v2 native) +- **Peering**: Public routes at PoP (v1 only) +- **App Security**: WAF/Cache/LB (v1/v2 over Magic Transit) + +## Prerequisites + +- Enterprise plan +- IPv4 /24+ or IPv6 /48+ prefixes +- BGP ASN for v1 +- See [locations PDF](https://developers.cloudflare.com/network-interconnect/static/cni-locations-2026-01.pdf) + +## Specs + +- /31 point-to-point subnets +- 10km max optical distance +- 10G: 10GBASE-LR single-mode +- 100G: 100GBASE-LR4 single-mode +- **No SLA** (free service) +- Backup Internet required + +## Throughput + +| Direction | 10G | 100G | +|-----------|-----|------| +| CF → Customer | 10 Gbps | 100 Gbps | +| Customer → CF (peering) | 10 Gbps | 100 Gbps | +| Customer → CF (Magic) | 1 Gbps/tunnel or CNI | 1 Gbps/tunnel or CNI | + +## Timeline + +2-4 weeks typical. Steps: request → config review → order connection → configure → test → enable health checks → activate → monitor. + +## In This Reference +- [configuration.md](./configuration.md) - BGP, routing, setup +- [api.md](./api.md) - API endpoints, SDKs +- [patterns.md](./patterns.md) - HA, hybrid cloud, failover +- [gotchas.md](./gotchas.md) - Troubleshooting, limits + +## Reading Order by Task + +| Task | Files to Load | +|------|---------------| +| Initial setup | README → configuration.md → api.md | +| Create interconnect via API | api.md → gotchas.md | +| Design HA architecture | patterns.md → README | +| Troubleshoot connection | gotchas.md → configuration.md | +| Cloud integration (AWS/GCP) | configuration.md → patterns.md | +| Monitor + alerts | configuration.md | + +## Automation Boundary + +**API-Automatable:** +- List/create/delete interconnects (Direct, Partner) +- List available slots +- Get interconnect status +- Download LOA PDF +- Create/update CNI objects (BGP config) +- Query settings + +**Requires Account Team:** +- Initial request approval +- AWS Direct Connect setup (send LOA+VLAN to CF) +- GCP Cloud Interconnect final activation +- Partner interconnect acceptance (Equinix, Megaport) +- VLAN assignment (v1) +- Configuration document generation (v1) +- Escalations + troubleshooting support + +**Cannot Be Automated:** +- Physical cross-connect installation (Direct) +- Partner portal operations (virtual circuit ordering) +- AWS/GCP portal operations +- Maintenance window coordination + +## See Also +- [tunnel](../tunnel/) - Alternative for private network connectivity +- [spectrum](../spectrum/) - Layer 4 proxy for TCP/UDP traffic diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/api.md new file mode 100644 index 0000000000000000000000000000000000000000..7f654e630667d980c9bfd52cd7d7aca8268c7f7e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/api.md @@ -0,0 +1,199 @@ +# CNI API Reference + +See [README.md](README.md) for overview. + +## Base + +``` +https://api.cloudflare.com/client/v4 +Auth: Authorization: Bearer +``` + +## SDK Namespaces + +**Primary (recommended):** +```typescript +client.networkInterconnects.interconnects.* +client.networkInterconnects.cnis.* +client.networkInterconnects.slots.* +``` + +**Alternate (deprecated):** +```typescript +client.magicTransit.cfInterconnects.* +``` + +Use `networkInterconnects` namespace for all new code. + +## Interconnects + +```http +GET /accounts/{account_id}/cni/interconnects # Query: page, per_page +POST /accounts/{account_id}/cni/interconnects # Query: validate_only=true (optional) +GET /accounts/{account_id}/cni/interconnects/{icon} +GET /accounts/{account_id}/cni/interconnects/{icon}/status +GET /accounts/{account_id}/cni/interconnects/{icon}/loa # Returns PDF +DELETE /accounts/{account_id}/cni/interconnects/{icon} +``` + +**Create Body:** `account`, `slot_id`, `type`, `facility`, `speed`, `name`, `description` +**Status Values:** `active` | `healthy` | `unhealthy` | `pending` | `down` + +**Response Example:** +```json +{"result": [{"id": "icon_abc", "name": "prod", "type": "direct", "facility": "EWR1", "speed": "10G", "status": "active"}]} +``` + +## CNI Objects (BGP config) + +```http +GET /accounts/{account_id}/cni/cnis +POST /accounts/{account_id}/cni/cnis +GET /accounts/{account_id}/cni/cnis/{cni} +PUT /accounts/{account_id}/cni/cnis/{cni} +DELETE /accounts/{account_id}/cni/cnis/{cni} +``` + +Body: `account`, `cust_ip`, `cf_ip`, `bgp_asn`, `bgp_password`, `vlan` + +## Slots + +```http +GET /accounts/{account_id}/cni/slots +GET /accounts/{account_id}/cni/slots/{slot} +``` + +Query: `facility`, `occupied`, `speed` + +## Health Checks + +Configure via Magic Transit/WAN tunnel endpoints (CNI v2). + +```typescript +await client.magicTransit.tunnels.update(accountId, tunnelId, { + health_check: { enabled: true, target: '192.0.2.1', rate: 'high', type: 'request' }, +}); +``` + +Rates: `high` | `medium` | `low`. Types: `request` | `reply`. See [Magic Transit docs](https://developers.cloudflare.com/magic-transit/how-to/configure-tunnel-endpoints/#add-tunnels). + +## Settings + +```http +GET /accounts/{account_id}/cni/settings +PUT /accounts/{account_id}/cni/settings +``` + +Body: `default_asn` + +## TypeScript SDK + +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ apiToken: process.env.CF_TOKEN }); + +// List +await client.networkInterconnects.interconnects.list({ account_id: id }); + +// Create with validation +await client.networkInterconnects.interconnects.create({ + account_id: id, + account: id, + slot_id: 'slot_abc', + type: 'direct', + facility: 'EWR1', + speed: '10G', + name: 'prod-interconnect', +}, { + query: { validate_only: true }, // Dry-run validation +}); + +// Create without validation +await client.networkInterconnects.interconnects.create({ + account_id: id, + account: id, + slot_id: 'slot_abc', + type: 'direct', + facility: 'EWR1', + speed: '10G', + name: 'prod-interconnect', +}); + +// Status +await client.networkInterconnects.interconnects.get(accountId, iconId); + +// LOA (use fetch) +const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${id}/cni/interconnects/${iconId}/loa`, { + headers: { Authorization: `Bearer ${token}` }, +}); +await fs.writeFile('loa.pdf', Buffer.from(await res.arrayBuffer())); + +// CNI object +await client.networkInterconnects.cnis.create({ + account_id: id, + account: id, + cust_ip: '192.0.2.1/31', + cf_ip: '192.0.2.0/31', + bgp_asn: 65000, + vlan: 100, +}); + +// Slots (filter by facility and speed) +await client.networkInterconnects.slots.list({ + account_id: id, + occupied: false, + facility: 'EWR1', + speed: '10G', +}); +``` + +## Python SDK + +```python +from cloudflare import Cloudflare + +client = Cloudflare(api_token=os.environ["CF_TOKEN"]) + +# List, create, status (same pattern as TypeScript) +client.network_interconnects.interconnects.list(account_id=id) +client.network_interconnects.interconnects.create(account_id=id, account=id, slot_id="slot_abc", type="direct", facility="EWR1", speed="10G") +client.network_interconnects.interconnects.get(account_id=id, icon=icon_id) + +# CNI objects and slots +client.network_interconnects.cnis.create(account_id=id, cust_ip="192.0.2.1/31", cf_ip="192.0.2.0/31", bgp_asn=65000) +client.network_interconnects.slots.list(account_id=id, occupied=False) +``` + +## cURL + +```bash +# List interconnects +curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/cni/interconnects" \ + -H "Authorization: Bearer ${CF_TOKEN}" + +# Create interconnect +curl -X POST "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/cni/interconnects?validate_only=true" \ + -H "Authorization: Bearer ${CF_TOKEN}" -H "Content-Type: application/json" \ + -d '{"account": "id", "slot_id": "slot_abc", "type": "direct", "facility": "EWR1", "speed": "10G"}' + +# LOA PDF +curl "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/cni/interconnects/${ICON_ID}/loa" \ + -H "Authorization: Bearer ${CF_TOKEN}" --output loa.pdf +``` + +## Not Available via API + +**Missing Capabilities:** +- BGP session state query (use Dashboard or BGP logs) +- Bandwidth utilization metrics (use external monitoring) +- Traffic statistics per interconnect +- Historical uptime/downtime data +- Light level readings (contact account team) +- Maintenance window scheduling (notifications only) + +## Resources + +- [API Docs](https://developers.cloudflare.com/api/resources/network_interconnects/) +- [TypeScript SDK](https://github.com/cloudflare/cloudflare-typescript) +- [Python SDK](https://github.com/cloudflare/cloudflare-python) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..0f1005ccc254096228f997c564f7e05a1f0c9e4a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/configuration.md @@ -0,0 +1,114 @@ +# CNI Configuration + +See [README.md](README.md) for overview. + +## Workflow (2-4 weeks) + +1. **Submit request** (Week 1): Contact account team, provide type/location/use case +2. **Review config** (Week 1-2, v1 only): Approve IP/VLAN/spec doc +3. **Order connection** (Week 2-3): + - **Direct**: Get LOA, order cross-connect from facility + - **Partner**: Order virtual circuit in partner portal + - **Cloud**: Order Direct Connect/Cloud Interconnect, send LOA+VLAN to CF +4. **Configure** (Week 3): Both sides configure per doc +5. **Test** (Week 3-4): Ping, verify BGP, check routes +6. **Health checks** (Week 4): Configure [Magic Transit](https://developers.cloudflare.com/magic-transit/how-to/configure-tunnel-endpoints/#add-tunnels) or [Magic WAN](https://developers.cloudflare.com/magic-wan/configuration/manually/how-to/configure-tunnel-endpoints/#add-tunnels) health checks +7. **Activate** (Week 4): Route traffic, verify flow +8. **Monitor**: Enable [maintenance notifications](https://developers.cloudflare.com/network-interconnect/monitoring-and-alerts/#enable-cloudflare-status-maintenance-notification) + +## BGP Configuration + +**v1 Requirements:** +- BGP ASN (provide during setup) +- /31 subnet for peering +- Optional: BGP password + +**v2:** Simplified, less BGP config needed. + +**BGP over CNI (Dec 2024):** Magic WAN/Transit can now peer BGP directly over CNI v2 (no GRE tunnel required). + +**Example v1 BGP:** +``` +Router ID: 192.0.2.1 +Peer IP: 192.0.2.0 +Remote ASN: 13335 +Local ASN: 65000 +Password: [optional] +VLAN: 100 +``` + +## Cloud Interconnect Setup + +### AWS Direct Connect (Beta) + +**Requirements:** Magic WAN, AWS Dedicated Direct Connect 1/10 Gbps. + +**Process:** +1. Contact CF account team +2. Choose location +3. Order in AWS portal +4. AWS provides LOA + VLAN ID +5. Send to CF account team +6. Wait ~4 weeks + +**Post-setup:** Add [static routes](https://developers.cloudflare.com/magic-wan/configuration/manually/how-to/configure-routes/#configure-static-routes) to Magic WAN. Enable [bidirectional health checks](https://developers.cloudflare.com/magic-wan/configuration/manually/how-to/configure-tunnel-endpoints/#legacy-bidirectional-health-checks). + +### GCP Cloud Interconnect (Beta) + +**Setup via Dashboard:** +1. Interconnects → Create → Cloud Interconnect → Google +2. Provide name, MTU (match GCP VLAN attachment), speed (50M-50G granular options available for partner interconnects) +3. Enter VLAN attachment pairing key +4. Confirm order + +**Routing to GCP:** Add [static routes](https://developers.cloudflare.com/magic-wan/configuration/manually/how-to/configure-routes/#configure-static-routes). BGP routes from GCP Cloud Router **ignored**. + +**Routing to CF:** Configure [custom learned routes](https://cloud.google.com/network-connectivity/docs/router/how-to/configure-custom-learned-routes) in Cloud Router. Request prefixes from CF account team. + +## Monitoring + +**Dashboard Status:** + +| Status | Meaning | +|--------|---------| +| **Healthy** | Link operational, traffic flowing, health checks passing | +| **Active** | Link up, sufficient light, Ethernet negotiated | +| **Unhealthy** | Link down, no/low light (<-20 dBm), can't negotiate | +| **Pending** | Cross-connect incomplete, device unresponsive, RX/TX swapped | +| **Down** | Physical link down, no connectivity | + +**Alerts:** + +**CNI Connection Maintenance** (Magic Networking only): +``` +Dashboard → Notifications → Add +Product: Cloudflare Network Interconnect +Type: Connection Maintenance Alert +``` +Warnings up to 2 weeks advance. 6hr delay for new additions. + +**Cloudflare Status Maintenance** (entire PoP): +``` +Dashboard → Notifications → Add +Product: Cloudflare Status +Filter PoPs: gru,fra,lhr +``` + +**Find PoP code:** +``` +Dashboard → Magic Transit/WAN → Configuration → Interconnects +Select CNI → Note Data Center (e.g., "gru-b") +Use first 3 letters: "gru" +``` + +## Best Practices + +**Critical config-specific practices:** +- /31 subnets required for BGP +- BGP passwords recommended +- BFD for fast failover (v1 only) +- Test ping connectivity before BGP +- Enable maintenance notifications immediately after activation +- Monitor status programmatically via API + +For design patterns, HA architecture, and security best practices, see [patterns.md](./patterns.md). diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..ef5a814e801f83b6d925d1069c7102147380a7b4 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/gotchas.md @@ -0,0 +1,165 @@ +# CNI Gotchas & Troubleshooting + +## Common Errors + +### "Status: Pending" + +**Cause:** Cross-connect not installed, RX/TX fibers reversed, wrong fiber type, or low light levels +**Solution:** +1. Verify cross-connect installed +2. Check fiber at patch panel +3. Swap RX/TX fibers +4. Check light with optical power meter (target > -20 dBm) +5. Contact account team + +### "Status: Unhealthy" + +**Cause:** Physical issue, low light (<-20 dBm), optic mismatch, or dirty connectors +**Solution:** +1. Check physical connections +2. Clean fiber connectors +3. Verify optic types (10GBASE-LR/100GBASE-LR4) +4. Test with known-good optics +5. Check patch panel +6. Contact account team + +### "BGP Session Down" + +**Cause:** Wrong IP addressing, wrong ASN, password mismatch, or firewall blocking TCP/179 +**Solution:** +1. Verify IPs match CNI object +2. Confirm ASN correct +3. Check BGP password +4. Verify no firewall on TCP/179 +5. Check BGP logs +6. Review BGP timers + +### "Low Throughput" + +**Cause:** MTU mismatch, fragmentation, single GRE tunnel (v1), or routing inefficiency +**Solution:** +1. Check MTU (1500↓/1476↑ for v1, 1500 both for v2) +2. Test various packet sizes +3. Add more GRE tunnels (v1) +4. Consider upgrading to v2 +5. Review routing tables +6. Use LACP for bundling (v1) + +## API Errors + +### 400 Bad Request: "slot_id already occupied" + +**Cause:** Another interconnect already uses this slot +**Solution:** Use `occupied=false` filter when listing slots: +```typescript +await client.networkInterconnects.slots.list({ + account_id: id, + occupied: false, + facility: 'EWR1', +}); +``` + +### 400 Bad Request: "invalid facility code" + +**Cause:** Typo or unsupported facility +**Solution:** Check [locations PDF](https://developers.cloudflare.com/network-interconnect/static/cni-locations-2026-01.pdf) for valid codes + +### 403 Forbidden: "Enterprise plan required" + +**Cause:** Account not enterprise-level +**Solution:** Contact account team to upgrade + +### 422 Unprocessable: "validate_only request failed" + +**Cause:** Dry-run validation found issues (wrong slot, invalid config) +**Solution:** Review error message details, fix config before real creation + +### Rate Limiting + +**Limit:** 1200 requests/5min per token +**Solution:** Implement exponential backoff, cache slot listings + +## Cloud-Specific Issues + +### AWS Direct Connect: "VLAN not matching" + +**Cause:** VLAN ID from AWS LOA doesn't match CNI config +**Solution:** +1. Get VLAN from AWS Console after ordering +2. Send exact VLAN to CF account team +3. Verify match in CNI object config + +### AWS: "Connection stuck in Pending" + +**Cause:** LOA not provided to CF or AWS connection not accepted +**Solution:** +1. Verify AWS connection status is "Available" +2. Confirm LOA sent to CF account team +3. Wait for CF team acceptance (can take days) + +### GCP: "BGP routes not propagating" + +**Cause:** BGP routes from GCP Cloud Router **ignored by design** +**Solution:** Use [static routes](https://developers.cloudflare.com/magic-wan/configuration/manually/how-to/configure-routes/#configure-static-routes) in Magic WAN instead + +### GCP: "Cannot query VLAN attachment status via API" + +**Cause:** GCP Cloud Interconnect Dashboard-only (no API yet) +**Solution:** Check status in CF Dashboard or GCP Console + +## Partner Interconnect Issues + +### Equinix: "Virtual circuit not appearing" + +**Cause:** CF hasn't accepted Equinix connection request +**Solution:** +1. Verify VC created in Equinix Fabric Portal +2. Contact CF account team to accept +3. Allow 2-3 business days + +### Console Connect/Megaport: "API creation fails" + +**Cause:** Partner interconnects require partner portal + CF approval +**Solution:** Cannot fully automate. Order in partner portal, notify CF account team. + +## Anti-Patterns + +| Anti-Pattern | Why Bad | Solution | +|--------------|---------|----------| +| Single interconnect for production | No SLA, single point of failure | Use ≥2 with device diversity | +| No backup Internet | CNI fails = total outage | Always maintain alternate path | +| Polling status every second | Rate limits, wastes API calls | Poll every 30-60s max | +| Using v1 for Magic WAN v2 workloads | GRE overhead, complexity | Use v2 for simplified routing | +| Assuming BGP session = traffic flowing | BGP up ≠ routes installed | Verify routing tables + test traffic | +| Not enabling maintenance alerts | Surprise downtime during maintenance | Enable notifications immediately | +| Hardcoding VLAN in automation | VLAN assigned by CF (v1) | Get VLAN from CNI object response | +| Using Direct without colocation | Can't access cross-connect | Use Partner or Cloud interconnect | + +## What's Not Queryable via API + +**Cannot retrieve:** +- BGP session state (use Dashboard or BGP logs) +- Light levels (contact account team) +- Historical metrics (uptime, traffic) +- Bandwidth utilization per interconnect +- Maintenance window schedules (notifications only) +- Fiber path details +- Cross-connect installation status + +**Workarounds:** +- External monitoring for BGP state +- Log aggregation for historical data +- Notifications for maintenance windows + +## Limits + +| Resource/Limit | Value | Notes | +|----------------|-------|-------| +| Max optical distance | 10km | Physical limit | +| MTU (v1) | 1500↓ / 1476↑ | Asymmetric | +| MTU (v2) | 1500 both | Symmetric | +| GRE tunnel throughput | 1 Gbps | Per tunnel (v1) | +| Recovery time | Days | No formal SLA | +| Light level minimum | -20 dBm | Target threshold | +| API rate limit | 1200 req/5min | Per token | +| Health check delay | 6 hours | New maintenance alert subscriptions | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..7ff9dd3057f103f69d988ca9ca63e212e36673b2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/network-interconnect/patterns.md @@ -0,0 +1,166 @@ +# CNI Patterns + +See [README.md](README.md) for overview. + +## High Availability + +**Critical:** Design for resilience from day one. + +**Requirements:** +- Device-level diversity (separate hardware) +- Backup Internet connectivity (no SLA on CNI) +- Network-resilient locations preferred +- Regular failover testing + +**Architecture:** +``` +Your Network A ──10G CNI v2──> CF CCR Device 1 + │ +Your Network B ──10G CNI v2──> CF CCR Device 2 + │ + CF Global Network (AS13335) +``` + +**Capacity Planning:** +- Plan across all links +- Account for failover scenarios +- Your responsibility + +## Pattern: Magic Transit + CNI v2 + +**Use Case:** DDoS protection, private connectivity, no GRE overhead. + +```typescript +// 1. Create interconnect +const ic = await client.networkInterconnects.interconnects.create({ + account_id: id, + type: 'direct', + facility: 'EWR1', + speed: '10G', + name: 'magic-transit-primary', +}); + +// 2. Poll until active +const status = await pollUntilActive(id, ic.id); + +// 3. Configure Magic Transit tunnel via Dashboard/API +``` + +**Benefits:** 1500 MTU both ways, simplified routing. + +## Pattern: Multi-Cloud Hybrid + +**Use Case:** AWS/GCP workloads with Cloudflare. + +**AWS Direct Connect:** +```typescript +// 1. Order Direct Connect in AWS Console +// 2. Get LOA + VLAN from AWS +// 3. Send to CF account team (no API) +// 4. Configure static routes in Magic WAN + +await configureStaticRoutes(id, { + prefix: '10.0.0.0/8', + nexthop: 'aws-direct-connect', +}); +``` + +**GCP Cloud Interconnect:** +``` +1. Get VLAN attachment pairing key from GCP Console +2. Create via Dashboard: Interconnects → Create → Cloud Interconnect → Google + - Enter pairing key, name, MTU, speed +3. Configure static routes in Magic WAN (BGP routes from GCP ignored) +4. Configure custom learned routes in GCP Cloud Router +``` + +**Note:** Dashboard-only. No API/SDK support yet. + +## Pattern: Multi-Location HA + +**Use Case:** 99.99%+ uptime. + +```typescript +// Primary (NY) +const primary = await client.networkInterconnects.interconnects.create({ + account_id: id, + type: 'direct', + facility: 'EWR1', + speed: '10G', + name: 'primary-ewr1', +}); + +// Secondary (NY, different hardware) +const secondary = await client.networkInterconnects.interconnects.create({ + account_id: id, + type: 'direct', + facility: 'EWR2', + speed: '10G', + name: 'secondary-ewr2', +}); + +// Tertiary (LA, different geography) +const tertiary = await client.networkInterconnects.interconnects.create({ + account_id: id, + type: 'partner', + facility: 'LAX1', + speed: '10G', + name: 'tertiary-lax1', +}); + +// BGP local preferences: +// Primary: 200 +// Secondary: 150 +// Tertiary: 100 +// Internet: Last resort +``` + +## Pattern: Partner Interconnect (Equinix) + +**Use Case:** Quick deployment, no colocation. + +**Setup:** +1. Order virtual circuit in Equinix Fabric Portal +2. Select Cloudflare as destination +3. Choose facility +4. Send details to CF account team +5. CF accepts in portal +6. Configure BGP + +**No API automation** – partner portals managed separately. + +## Failover & Security + +**Failover Best Practices:** +- Use BGP local preferences for priority +- Configure BFD for fast detection (v1) +- Test regularly with traffic shift +- Document runbooks + +**Security:** +- BGP password authentication +- BGP route filtering +- Monitor unexpected routes +- Magic Firewall for DDoS/threats +- Minimum API token permissions +- Rotate credentials periodically + +## Decision Matrix + +| Requirement | Recommended | +|-------------|-------------| +| Collocated with CF | Direct | +| Not collocated | Partner | +| AWS/GCP workloads | Cloud | +| 1500 MTU both ways | v2 | +| VLAN tagging | v1 | +| Public peering | v1 | +| Simplest config | v2 | +| BFD fast failover | v1 | +| LACP bundling | v1 | + +## Resources + +- [Magic Transit Docs](https://developers.cloudflare.com/magic-transit/) +- [Magic WAN Docs](https://developers.cloudflare.com/magic-wan/) +- [Argo Smart Routing](https://developers.cloudflare.com/argo/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/README.md new file mode 100644 index 0000000000000000000000000000000000000000..58feed6363f5efae8b1aafb1aeb56ebf204e9b99 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/README.md @@ -0,0 +1,87 @@ +# Cloudflare Observability Skill Reference + +**Purpose**: Comprehensive guidance for implementing observability in Cloudflare Workers, covering traces, logs, metrics, and analytics. + +**Scope**: Cloudflare Observability features ONLY - Workers Logs, Traces, Analytics Engine, Logpush, Metrics & Analytics, and OpenTelemetry exports. + +--- + +## Decision Tree: Which File to Load? + +Use this to route to the correct file without loading all content: + +``` +├─ "How do I enable/configure X?" → configuration.md +├─ "What's the API/method/binding for X?" → api.md +├─ "How do I implement X pattern?" → patterns.md +│ ├─ Usage tracking/billing → patterns.md +│ ├─ Error tracking → patterns.md +│ ├─ Performance monitoring → patterns.md +│ ├─ Multi-tenant tracking → patterns.md +│ ├─ Tail Worker filtering → patterns.md +│ └─ OpenTelemetry export → patterns.md +└─ "Why isn't X working?" / "Limits?" → gotchas.md +``` + +## Reading Order + +Load files in this order based on task: + +| Task Type | Load Order | Reason | +|-----------|------------|--------| +| **Initial setup** | configuration.md → gotchas.md | Setup first, avoid pitfalls | +| **Implement feature** | patterns.md → api.md → gotchas.md | Pattern → API details → edge cases | +| **Debug issue** | gotchas.md → configuration.md | Common issues first | +| **Query data** | api.md → patterns.md | API syntax → query examples | + +## Product Overview + +### Workers Logs +- **What:** Console output from Workers (console.log/warn/error) +- **Access:** Dashboard (Real-time Logs), Logpush, Tail Workers +- **Cost:** Free (included with all Workers) +- **Retention:** Real-time only (no historical storage in dashboard) + +### Workers Traces +- **What:** Execution traces with timing, CPU usage, outcome +- **Access:** Dashboard (Workers Analytics → Traces), Logpush +- **Cost:** $0.10/1M spans (GA pricing starts March 1, 2026), 10M free/month +- **Retention:** 14 days included + +### Analytics Engine +- **What:** High-cardinality event storage and SQL queries +- **Access:** SQL API, Dashboard (Analytics → Analytics Engine) +- **Cost:** $0.25/1M writes beyond 10M free/month +- **Retention:** 90 days (configurable up to 1 year) + +### Tail Workers +- **What:** Workers that receive logs/traces from other Workers +- **Use Cases:** Log filtering, transformation, external export +- **Cost:** Standard Workers pricing + +### Logpush +- **What:** Stream logs to external storage (S3, R2, Datadog, etc.) +- **Access:** Dashboard, API +- **Cost:** Requires Business/Enterprise plan + +## Pricing Summary (2026) + +| Feature | Free Tier | Cost Beyond Free Tier | Plan Requirement | +|---------|-----------|----------------------|------------------| +| Workers Logs | Unlimited | Free | Any | +| Workers Traces | 10M spans/month | $0.10/1M spans | Paid Workers (GA: March 1, 2026) | +| Analytics Engine | 10M writes/month | $0.25/1M writes | Paid Workers | +| Logpush | N/A | Included in plan | Business/Enterprise | + +## In This Reference + +- **[configuration.md](configuration.md)** - Setup, deployment, configuration (Logs, Traces, Analytics Engine, Tail Workers, Logpush) +- **[api.md](api.md)** - API endpoints, methods, interfaces (GraphQL, SQL, bindings, types) +- **[patterns.md](patterns.md)** - Common patterns, use cases, examples (billing, monitoring, error tracking, exports) +- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations (common errors, performance gotchas, pricing) + +## See Also + +- [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/) +- [Analytics Engine Docs](https://developers.cloudflare.com/analytics/analytics-engine/) +- [Workers Traces Docs](https://developers.cloudflare.com/workers/observability/traces/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/api.md new file mode 100644 index 0000000000000000000000000000000000000000..c3d06050791509d2b7a14aa8488801e30168048e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/api.md @@ -0,0 +1,164 @@ +## API Reference + +### GraphQL Analytics API + +**Endpoint**: `https://api.cloudflare.com/client/v4/graphql` + +**Query Workers Metrics**: +```graphql +query { + viewer { + accounts(filter: { accountTag: $accountId }) { + workersInvocationsAdaptive( + limit: 100 + filter: { + datetime_geq: "2025-01-01T00:00:00Z" + datetime_leq: "2025-01-31T23:59:59Z" + scriptName: "my-worker" + } + ) { + sum { + requests + errors + subrequests + } + quantiles { + cpuTimeP50 + cpuTimeP99 + wallTimeP50 + wallTimeP99 + } + } + } + } +} +``` + +### Analytics Engine SQL API + +**Endpoint**: `https://api.cloudflare.com/client/v4/accounts/{account_id}/analytics_engine/sql` + +**Authentication**: `Authorization: Bearer ` (Account Analytics Read permission) + +**Common Queries**: + +```sql +-- List all datasets +SHOW TABLES; + +-- Time-series aggregation (5-minute buckets) +SELECT + intDiv(toUInt32(timestamp), 300) * 300 AS time_bucket, + blob1 AS endpoint, + SUM(_sample_interval) AS total_requests, + AVG(double1) AS avg_response_time_ms +FROM api_metrics +WHERE timestamp >= NOW() - INTERVAL '24' HOUR +GROUP BY time_bucket, endpoint +ORDER BY time_bucket DESC; + +-- Top customers by usage +SELECT + index1 AS customer_id, + SUM(_sample_interval * double1) AS total_api_calls, + AVG(double2) AS avg_response_time_ms +FROM api_usage +WHERE timestamp >= NOW() - INTERVAL '7' DAY +GROUP BY customer_id +ORDER BY total_api_calls DESC +LIMIT 100; + +-- Error rate analysis +SELECT + blob1 AS error_type, + COUNT(*) AS occurrences, + MAX(timestamp) AS last_seen +FROM error_tracking +WHERE timestamp >= NOW() - INTERVAL '1' HOUR +GROUP BY error_type +ORDER BY occurrences DESC; +``` + +### Console Logging API + +**Methods**: +```typescript +// Standard methods (all appear in Workers Logs) +console.log('info message'); +console.info('info message'); +console.warn('warning message'); +console.error('error message'); +console.debug('debug message'); + +// Structured logging (recommended) +console.log({ + level: 'info', + user_id: '123', + action: 'checkout', + amount: 99.99, + currency: 'USD' +}); +``` + +**Log Levels**: All console methods produce logs; use structured fields for filtering: +```typescript +console.log({ + level: 'error', + message: 'Payment failed', + error_code: 'CARD_DECLINED' +}); +``` + +### Analytics Engine Binding Types + +```typescript +interface AnalyticsEngineDataset { + writeDataPoint(event: AnalyticsEngineDataPoint): void; +} + +interface AnalyticsEngineDataPoint { + // Indexed strings (use for filtering/grouping) + indexes?: string[]; + + // Non-indexed strings (metadata, IDs, URLs) + blobs?: string[]; + + // Numeric values (counts, durations, amounts) + doubles?: number[]; +} +``` + +**Field Limits**: +- Max 20 indexes +- Max 20 blobs +- Max 20 doubles +- Max 25 `writeDataPoint` calls per request + +### Tail Consumer Event Type + +```typescript +interface TraceItem { + event: TraceEvent; + logs: TraceLog[]; + exceptions: TraceException[]; + scriptName?: string; +} + +interface TraceEvent { + outcome: 'ok' | 'exception' | 'exceededCpu' | 'exceededMemory' | 'unknown'; + cpuTime: number; // microseconds + wallTime: number; // microseconds +} + +interface TraceLog { + timestamp: number; + level: 'log' | 'info' | 'debug' | 'warn' | 'error'; + message: any; // string or structured object +} + +interface TraceException { + name: string; + message: string; + timestamp: number; +} +``` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..3a5a3808f788c4bf2340ad43c2e786f8b5de9748 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/configuration.md @@ -0,0 +1,169 @@ +## Configuration Patterns + +### Enable Workers Logs + +```jsonc +{ + "observability": { + "enabled": true, + "head_sampling_rate": 1 // 100% sampling (default) + } +} +``` + +**Best Practice**: Use structured JSON logging for better indexing + +```typescript +// Good - structured logging +console.log({ + user_id: 123, + action: "login", + status: "success", + duration_ms: 45 +}); + +// Avoid - unstructured string +console.log("user_id: 123 logged in successfully in 45ms"); +``` + +### Enable Workers Traces + +```jsonc +{ + "observability": { + "traces": { + "enabled": true, + "head_sampling_rate": 0.05 // 5% sampling + } + } +} +``` + +**Note**: Default sampling is 100%. For high-traffic Workers, use lower sampling (0.01-0.1). + +### Configure Analytics Engine + +**Bind to Worker**: +```toml +# wrangler.toml +analytics_engine_datasets = [ + { binding = "ANALYTICS", dataset = "api_metrics" } +] +``` + +**Write Data Points**: +```typescript +export interface Env { + ANALYTICS: AnalyticsEngineDataset; +} + +export default { + async fetch(request: Request, env: Env): Promise { + // Track metrics + env.ANALYTICS.writeDataPoint({ + blobs: ['customer_123', 'POST', '/api/v1/users'], + doubles: [1, 245.5], // request_count, response_time_ms + indexes: ['customer_123'] // for efficient filtering + }); + + return new Response('OK'); + } +} +``` + +### Configure Tail Workers + +Tail Workers receive logs/traces from other Workers for filtering, transformation, or export. + +**Setup**: +```toml +# wrangler.toml +name = "log-processor" +main = "src/tail.ts" + +[[tail_consumers]] +service = "my-worker" # Worker to tail +``` + +**Tail Worker Example**: +```typescript +export default { + async tail(events: TraceItem[], env: Env, ctx: ExecutionContext) { + // Filter errors only + const errors = events.filter(event => + event.outcome === 'exception' || event.outcome === 'exceededCpu' + ); + + if (errors.length > 0) { + // Send to external monitoring + ctx.waitUntil( + fetch('https://monitoring.example.com/errors', { + method: 'POST', + body: JSON.stringify(errors) + }) + ); + } + } +} +``` + +### Configure Logpush + +Send logs to external storage (S3, R2, GCS, Azure, Datadog, etc.). Requires Business/Enterprise plan. + +**Via Dashboard**: +1. Navigate to Analytics → Logs → Logpush +2. Select destination type +3. Provide credentials and bucket/endpoint +4. Choose dataset (e.g., Workers Trace Events) +5. Configure filters and fields + +**Via API**: +```bash +curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/logpush/jobs" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{ + "name": "workers-logs-to-s3", + "destination_conf": "s3://my-bucket/logs?region=us-east-1", + "dataset": "workers_trace_events", + "enabled": true, + "frequency": "high", + "filter": "{\"where\":{\"and\":[{\"key\":\"ScriptName\",\"operator\":\"eq\",\"value\":\"my-worker\"}]}}" + }' +``` + +### Environment-Specific Configuration + +**Development** (verbose logs, full sampling): +```jsonc +// wrangler.dev.jsonc +{ + "observability": { + "enabled": true, + "head_sampling_rate": 1.0, + "traces": { + "enabled": true + } + } +} +``` + +**Production** (reduced sampling, structured logs): +```jsonc +// wrangler.prod.jsonc +{ + "observability": { + "enabled": true, + "head_sampling_rate": 0.1, // 10% sampling + "traces": { + "enabled": true + } + } +} +``` + +Deploy with env-specific config: +```bash +wrangler deploy --config wrangler.prod.jsonc --env production +``` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..9ec92a569cdc24414b73fbb7a5486bb19e9546cb --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/gotchas.md @@ -0,0 +1,115 @@ +## Common Errors + +### "Logs not appearing" + +**Cause:** Observability disabled, Worker not redeployed, no traffic, low sampling rate, or log size exceeds 256 KB +**Solution:** +```bash +# Verify config +cat wrangler.jsonc | jq '.observability' + +# Check deployment +wrangler deployments list + +# Test with curl +curl https://your-worker.workers.dev +``` +Ensure `observability.enabled = true`, redeploy Worker, check `head_sampling_rate`, verify traffic + +### "Traces not being captured" + +**Cause:** Traces not enabled, incorrect sampling rate, Worker not redeployed, or destination unavailable +**Solution:** +```jsonc +// Temporarily set to 100% sampling for debugging +{ + "observability": { + "enabled": true, + "head_sampling_rate": 1.0, + "traces": { + "enabled": true + } + } +} +``` +Ensure `observability.traces.enabled = true`, set `head_sampling_rate` to 1.0 for testing, redeploy, check destination status + +## Limits + +| Resource/Limit | Value | Notes | +|----------------|-------|-------| +| Max log size | 256 KB | Logs exceeding this are truncated | +| Default sampling rate | 1.0 (100%) | Reduce for high-traffic Workers | +| Max destinations | Varies by plan | Check dashboard | +| Trace context propagation | 100 spans max | Deep call chains may lose spans | +| Analytics Engine write rate | 25 writes/request | Excess writes dropped silently | + +## Performance Gotchas + +### Spectre Mitigation Timing + +**Problem:** `Date.now()` and `performance.now()` have reduced precision (coarsened to 100μs) +**Cause:** Spectre vulnerability mitigation in V8 +**Solution:** Accept reduced precision or use Workers Traces for accurate timing +```typescript +// Date.now() is coarsened - trace spans are accurate +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + // For user-facing timing, Date.now() is fine + const start = Date.now(); + const response = await processRequest(request); + const duration = Date.now() - start; + + // For detailed performance analysis, use Workers Traces instead + return response; + } +} +``` + +### Analytics Engine _sample_interval Aggregation + +**Problem:** Queries return incorrect totals when not multiplying by `_sample_interval` +**Cause:** Analytics Engine stores sampled data points, each representing multiple events +**Solution:** Always multiply counts/sums by `_sample_interval` in aggregations +```sql +-- WRONG: Undercounts actual events +SELECT blob1 AS customer_id, COUNT(*) AS total_calls +FROM api_usage GROUP BY customer_id; + +-- CORRECT: Accounts for sampling +SELECT blob1 AS customer_id, SUM(_sample_interval) AS total_calls +FROM api_usage GROUP BY customer_id; +``` + +### Trace Context Propagation Limits + +**Problem:** Deep call chains lose trace context after 100 spans +**Cause:** Cloudflare limits trace depth to prevent performance impact +**Solution:** Design for flatter architectures or use custom correlation IDs for deep chains +```typescript +// For deep call chains, add custom correlation ID +const correlationId = crypto.randomUUID(); +console.log({ correlationId, event: 'request_start' }); + +// Pass correlationId through headers to downstream services +await fetch('https://api.example.com', { + headers: { 'X-Correlation-ID': correlationId } +}); +``` + +## Pricing (2026) + +### Workers Traces +- **GA Pricing (starts March 1, 2026):** + - $0.10 per 1M trace spans captured + - Retention: 14 days included +- **Free tier:** 10M trace spans/month +- **Note:** Beta usage (before March 1, 2026) is free + +### Workers Logs +- **Included:** Free for all Workers +- **Logpush:** Requires Business/Enterprise plan + +### Analytics Engine +- **Included:** 10M writes/month on Paid Workers plan +- **Additional:** $0.25 per 1M writes beyond included quota diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..e5fbbdb4bdc5ad5efadffd5021dd20561480c7ad --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/observability/patterns.md @@ -0,0 +1,105 @@ +# Observability Patterns + +## Usage-Based Billing + +```typescript +env.ANALYTICS.writeDataPoint({ + blobs: [customerId, request.url, request.method], + doubles: [1], // request_count + indexes: [customerId] +}); +``` + +```sql +SELECT blob1 AS customer_id, SUM(_sample_interval * double1) AS total_calls +FROM api_usage WHERE timestamp >= DATE_TRUNC('month', NOW()) +GROUP BY customer_id +``` + +## Performance Monitoring + +```typescript +const start = Date.now(); +const response = await fetch(url); +env.ANALYTICS.writeDataPoint({ + blobs: [url, response.status.toString()], + doubles: [Date.now() - start, response.status] +}); +``` + +```sql +SELECT blob1 AS url, AVG(double1) AS avg_ms, percentile(double1, 0.95) AS p95_ms +FROM fetch_metrics WHERE timestamp >= NOW() - INTERVAL '1' HOUR +GROUP BY url +``` + +## Error Tracking + +```typescript +env.ANALYTICS.writeDataPoint({ + blobs: [error.name, request.url, request.method], + doubles: [1], + indexes: [error.name] +}); +``` + +## Multi-Tenant Tracking + +```typescript +env.ANALYTICS.writeDataPoint({ + indexes: [tenantId], // efficient filtering + blobs: [tenantId, url.pathname, method, status], + doubles: [1, duration, bytesSize] +}); +``` + +## Tail Worker Log Filtering + +```typescript +export default { + async tail(events, env, ctx) { + const critical = events.filter(e => + e.exceptions.length > 0 || e.event.wallTime > 1000000 + ); + if (critical.length === 0) return; + + ctx.waitUntil( + fetch('https://logging.example.com/ingest', { + method: 'POST', + headers: { 'Authorization': `Bearer ${env.API_KEY}` }, + body: JSON.stringify(critical.map(e => ({ + outcome: e.event.outcome, + cpu_ms: e.event.cpuTime / 1000, + errors: e.exceptions + }))) + }) + ); + } +}; +``` + +## OpenTelemetry Export + +```typescript +export default { + async tail(events, env, ctx) { + const otelSpans = events.map(e => ({ + traceId: generateId(32), + spanId: generateId(16), + name: e.scriptName || 'worker.request', + attributes: [ + { key: 'worker.outcome', value: { stringValue: e.event.outcome } }, + { key: 'worker.cpu_time_us', value: { intValue: String(e.event.cpuTime) } } + ] + })); + + ctx.waitUntil( + fetch('https://api.honeycomb.io/v1/traces', { + method: 'POST', + headers: { 'X-Honeycomb-Team': env.HONEYCOMB_KEY }, + body: JSON.stringify({ resourceSpans: [{ scopeSpans: [{ spans: otelSpans }] }] }) + }) + ); + } +}; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/README.md new file mode 100644 index 0000000000000000000000000000000000000000..70f37b16bb8dc0ef594fa3a0a7a3489732d7f607 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/README.md @@ -0,0 +1,98 @@ +# Cloudflare Pages Functions + +Serverless functions on Cloudflare Pages using Workers runtime. Full-stack dev with file-based routing. + +## Quick Navigation + +**Need to...** +| Task | Go to | +|------|-------| +| Set up TypeScript types | [configuration.md](./configuration.md) - TypeScript Setup | +| Configure bindings (KV, D1, R2) | [configuration.md](./configuration.md) - wrangler.jsonc | +| Access request/env/params | [api.md](./api.md) - EventContext | +| Add middleware or auth | [patterns.md](./patterns.md) - Middleware, Auth | +| Background tasks (waitUntil) | [patterns.md](./patterns.md) - Background Tasks | +| Debug errors or check limits | [gotchas.md](./gotchas.md) - Common Errors, Limits | + +## Decision Tree: Is This Pages Functions? + +``` +Need serverless backend? +├─ Yes, for a static site → Pages Functions +├─ Yes, standalone API → Workers +└─ Just static hosting → Pages (no functions) + +Have existing Worker? +├─ Complex routing logic → Use _worker.js (Advanced Mode) +└─ Simple routes → Migrate to /functions (File-Based) + +Framework-based? +├─ Next.js/SvelteKit/Remix → Uses _worker.js automatically +└─ Vanilla/HTML/React SPA → Use /functions +``` + +## File-Based Routing + +``` +/functions + ├── index.js → / + ├── api.js → /api + ├── users/ + │ ├── index.js → /users/ + │ ├── [user].js → /users/:user + │ └── [[catchall]].js → /users/* + └── _middleware.js → runs on all routes +``` + +**Rules:** +- `index.js` → directory root +- Trailing slash optional +- Specific routes precede catch-alls +- Falls back to static if no match + +## Dynamic Routes + +**Single segment** `[param]` → string: +```js +// /functions/users/[user].js +export function onRequest(context) { + return new Response(`Hello ${context.params.user}`); +} +// Matches: /users/nevi +``` + +**Multi-segment** `[[param]]` → array: +```js +// /functions/users/[[catchall]].js +export function onRequest(context) { + return new Response(JSON.stringify(context.params.catchall)); +} +// Matches: /users/nevi/foobar → ["nevi", "foobar"] +``` + +## Key Features + +- **Method handlers:** `onRequestGet`, `onRequestPost`, etc. +- **Middleware:** `_middleware.js` for cross-cutting concerns +- **Bindings:** KV, D1, R2, Durable Objects, Workers AI, Service bindings +- **TypeScript:** Full type support via `wrangler types` command +- **Advanced mode:** Use `_worker.js` for custom routing logic + +## Reading Order + +**New to Pages Functions?** Start here: +1. [README.md](./README.md) - Overview, routing, decision tree (you are here) +2. [configuration.md](./configuration.md) - TypeScript setup, wrangler.jsonc, bindings +3. [api.md](./api.md) - EventContext, handlers, bindings reference +4. [patterns.md](./patterns.md) - Middleware, auth, CORS, rate limiting, caching +5. [gotchas.md](./gotchas.md) - Common errors, debugging, limits + +**Quick reference lookup:** +- Bindings table → [api.md](./api.md) +- Error diagnosis → [gotchas.md](./gotchas.md) +- TypeScript setup → [configuration.md](./configuration.md) + +## See Also +- [pages](../pages/) - Pages platform overview and static site deployment +- [workers](../workers/) - Workers runtime API reference +- [d1](../d1/) - D1 database integration with Pages Functions diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/api.md new file mode 100644 index 0000000000000000000000000000000000000000..21e61bb14b4a57eb545367740d7288e112996520 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/api.md @@ -0,0 +1,143 @@ +# Function API + +## EventContext + +```typescript +interface EventContext { + request: Request; // Incoming request + functionPath: string; // Request path + waitUntil(promise: Promise): void; // Background tasks (non-blocking) + passThroughOnException(): void; // Fallback to static on error + next(input?: Request | string, init?: RequestInit): Promise; + env: Env; // Bindings, vars, secrets + params: Record; // Route params ([user] or [[catchall]]) + data: any; // Middleware shared state +} +``` + +**TypeScript:** See [configuration.md](./configuration.md) for `wrangler types` setup + +## Handlers + +```typescript +// Generic (fallback for any method) +export async function onRequest(ctx: EventContext): Promise { + return new Response('Any method'); +} + +// Method-specific (takes precedence over generic) +export async function onRequestGet(ctx: EventContext): Promise { + return Response.json({ message: 'GET' }); +} + +export async function onRequestPost(ctx: EventContext): Promise { + const body = await ctx.request.json(); + return Response.json({ received: body }); +} +// Also: onRequestPut, onRequestPatch, onRequestDelete, onRequestHead, onRequestOptions +``` + +## Bindings Reference + +| Binding Type | Interface | Config Key | Use Case | +|--------------|-----------|------------|----------| +| KV | `KVNamespace` | `kv_namespaces` | Key-value cache, sessions, config | +| D1 | `D1Database` | `d1_databases` | Relational data, SQL queries | +| R2 | `R2Bucket` | `r2_buckets` | Large files, user uploads, assets | +| Durable Objects | `DurableObjectNamespace` | `durable_objects.bindings` | Stateful coordination, websockets | +| Workers AI | `Ai` | `ai.binding` | LLM inference, embeddings | +| Vectorize | `VectorizeIndex` | `vectorize` | Vector search, embeddings | +| Service Binding | `Fetcher` | `services` | Worker-to-worker RPC | +| Analytics Engine | `AnalyticsEngineDataset` | `analytics_engine_datasets` | Event logging, metrics | +| Environment Vars | `string` | `vars` | Non-sensitive config | + +See [configuration.md](./configuration.md) for wrangler.jsonc examples. + +## Bindings + +### KV + +```typescript +interface Env { KV: KVNamespace; } +export const onRequest: PagesFunction = async (ctx) => { + await ctx.env.KV.put('key', 'value', { expirationTtl: 3600 }); + const val = await ctx.env.KV.get('key', { type: 'json' }); + const keys = await ctx.env.KV.list({ prefix: 'user:' }); + return Response.json({ val }); +}; +``` + +### D1 + +```typescript +interface Env { DB: D1Database; } +export const onRequest: PagesFunction = async (ctx) => { + const user = await ctx.env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(123).first(); + return Response.json(user); +}; +``` + +### R2 + +```typescript +interface Env { BUCKET: R2Bucket; } +export const onRequest: PagesFunction = async (ctx) => { + const obj = await ctx.env.BUCKET.get('file.txt'); + if (!obj) return new Response('Not found', { status: 404 }); + await ctx.env.BUCKET.put('file.txt', ctx.request.body); + return new Response(obj.body); +}; +``` + +### Durable Objects + +```typescript +interface Env { COUNTER: DurableObjectNamespace; } +export const onRequest: PagesFunction = async (ctx) => { + const stub = ctx.env.COUNTER.get(ctx.env.COUNTER.idFromName('global')); + return stub.fetch(ctx.request); +}; +``` + +### Workers AI + +```typescript +interface Env { AI: Ai; } +export const onRequest: PagesFunction = async (ctx) => { + const resp = await ctx.env.AI.run('@cf/meta/llama-3.1-8b-instruct', { prompt: 'Hello' }); + return Response.json(resp); +}; +``` + +### Service Bindings & Env Vars + +```typescript +interface Env { AUTH: Fetcher; API_KEY: string; } +export const onRequest: PagesFunction = async (ctx) => { + // Service binding: forward to another Worker + return ctx.env.AUTH.fetch(ctx.request); + + // Environment variable + return Response.json({ key: ctx.env.API_KEY }); +}; +``` + +## Advanced Mode (env.ASSETS) + +When using `_worker.js`, access static assets via `env.ASSETS.fetch()`: + +```typescript +interface Env { ASSETS: Fetcher; KV: KVNamespace; } + +export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + if (url.pathname.startsWith('/api/')) { + return Response.json({ data: await env.KV.get('key') }); + } + return env.ASSETS.fetch(request); // Fallback to static + } +} satisfies ExportedHandler; +``` + +**See also:** [configuration.md](./configuration.md) for TypeScript setup and wrangler.jsonc | [patterns.md](./patterns.md) for middleware and auth patterns diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..9cdacce513a0dbb1a096c008f6f618958a6de09c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/configuration.md @@ -0,0 +1,122 @@ +# Configuration + +## TypeScript Setup + +**Generate types from wrangler.jsonc** (replaces deprecated `@cloudflare/workers-types`): + +```bash +npx wrangler types +``` + +Creates `worker-configuration.d.ts` with typed `Env` interface based on your bindings. + +```typescript +// functions/api.ts +export const onRequest: PagesFunction = async (ctx) => { + // ctx.env.KV, ctx.env.DB, etc. are fully typed + return Response.json({ ok: true }); +}; +``` + +**Manual types** (if not using wrangler types): + +```typescript +interface Env { + KV: KVNamespace; + DB: D1Database; + API_KEY: string; +} +export const onRequest: PagesFunction = async (ctx) => { /* ... */ }; +``` + +## wrangler.jsonc + +```jsonc +{ + "$schema": "./node_modules/wrangler/config-schema.json", + "name": "my-pages-app", + "pages_build_output_dir": "./dist", + "compatibility_date": "2025-01-01", + "compatibility_flags": ["nodejs_compat"], + + "vars": { "API_URL": "https://api.example.com" }, + "kv_namespaces": [{ "binding": "KV", "id": "abc123" }], + "d1_databases": [{ "binding": "DB", "database_name": "prod-db", "database_id": "xyz789" }], + "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "my-bucket" }], + "durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter", "script_name": "counter-worker" }] }, + "services": [{ "binding": "AUTH", "service": "auth-worker" }], + "ai": { "binding": "AI" }, + "vectorize": [{ "binding": "VECTORIZE", "index_name": "my-index" }], + "analytics_engine_datasets": [{ "binding": "ANALYTICS" }] +} +``` + +## Environment Overrides + +Top-level → local dev, `env.preview` → preview, `env.production` → production + +```jsonc +{ + "vars": { "API_URL": "http://localhost:8787" }, + "env": { + "production": { "vars": { "API_URL": "https://api.example.com" } } + } +} +``` + +**Note:** If overriding `vars`, `kv_namespaces`, `d1_databases`, etc., ALL must be redefined (non-inheritable) + +## Local Secrets (.dev.vars) + +**Local dev only** - NOT deployed: + +```bash +# .dev.vars (add to .gitignore) +SECRET_KEY="my-secret-value" +``` + +Accessed via `ctx.env.SECRET_KEY`. Set production secrets: +```bash +echo "value" | npx wrangler pages secret put SECRET_KEY --project-name=my-app +``` + +## Static Config Files + +**_routes.json** - Custom routing: +```json +{ "version": 1, "include": ["/api/*"], "exclude": ["/static/*"] } +``` + +**_headers** - Static headers: +``` +/static/* + Cache-Control: public, max-age=31536000 +``` + +**_redirects** - Redirects: +``` +/old /new 301 +``` + +## Local Dev & Deployment + +```bash +# Dev server +npx wrangler pages dev ./dist + +# With bindings +npx wrangler pages dev ./dist --kv=KV --d1=DB=db-id --r2=BUCKET + +# Durable Objects (2 terminals) +cd do-worker && npx wrangler dev +cd pages-project && npx wrangler pages dev ./dist --do COUNTER=Counter@do-worker + +# Deploy +npx wrangler pages deploy ./dist +npx wrangler pages deploy ./dist --branch preview + +# Download config +npx wrangler pages download config my-project +``` + +**See also:** [api.md](./api.md) for binding usage examples diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..1ffae67877bd2361caf464195d563401a46f6203 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/gotchas.md @@ -0,0 +1,94 @@ +# Gotchas & Debugging + +## Error Diagnosis + +| Symptom | Likely Cause | Solution | +|---------|--------------|----------| +| **Function not invoking** | Wrong `/functions` location, wrong extension, or `_routes.json` excludes path | Check `pages_build_output_dir`, use `.js`/`.ts`, verify `_routes.json` | +| **`ctx.env.BINDING` undefined** | Binding not configured or name mismatch | Add to `wrangler.jsonc`, verify exact name (case-sensitive), redeploy | +| **TypeScript errors on `ctx.env`** | Missing type definition | Run `wrangler types` or define `interface Env {}` | +| **Middleware not running** | Wrong filename/location or missing `ctx.next()` | Name exactly `_middleware.js`, export `onRequest`, call `ctx.next()` | +| **Secrets missing in production** | `.dev.vars` not deployed | `.dev.vars` is local only - set production secrets via dashboard or `wrangler secret put` | +| **Type mismatch on binding** | Wrong interface type | See [api.md](./api.md) bindings table for correct types | +| **"KV key not found" but exists** | Key in wrong namespace or env | Verify namespace binding, check preview vs production env | +| **Function times out** | Synchronous wait or missing `await` | All I/O must be async/await, use `ctx.waitUntil()` for background tasks | + +## Common Errors + +### TypeScript type errors + +**Problem:** `ctx.env.MY_BINDING` shows type error +**Cause:** No type definition for `Env` +**Solution:** Run `npx wrangler types` or manually define: +```typescript +interface Env { MY_BINDING: KVNamespace; } +export const onRequest: PagesFunction = async (ctx) => { /* ... */ }; +``` + +### Secrets not available in production + +**Problem:** `ctx.env.SECRET_KEY` is undefined in production +**Cause:** `.dev.vars` is local-only, not deployed +**Solution:** Set production secrets: +```bash +echo "value" | npx wrangler pages secret put SECRET_KEY --project-name=my-app +``` + +## Debugging + +```typescript +// Console logging +export async function onRequest(ctx) { + console.log('Request:', ctx.request.method, ctx.request.url); + const res = await ctx.next(); + console.log('Status:', res.status); + return res; +} +``` + +```bash +# Stream real-time logs +npx wrangler pages deployment tail +npx wrangler pages deployment tail --status error +``` + +```jsonc +// Source maps (wrangler.jsonc) +{ "upload_source_maps": true } +``` + +## Limits + +| Resource | Free | Paid | +|----------|------|------| +| CPU time | 10ms | 50ms | +| Memory | 128 MB | 128 MB | +| Script size | 10 MB compressed | 10 MB compressed | +| Env vars | 5 KB per var, 64 max | 5 KB per var, 64 max | +| Requests | 100k/day | Unlimited ($0.50/million) | + +## Best Practices + +**Performance:** Minimize deps (cold start), use KV for cache/D1 for relational/R2 for large files, set `Cache-Control` headers, batch DB ops, handle errors gracefully + +**Security:** Never commit secrets (use `.dev.vars` + gitignore), validate input, sanitize before DB, implement auth middleware, set CORS headers, rate limit per-IP + +## Migration + +**Workers → Pages Functions:** +- `export default { fetch(req, env) {} }` → `export function onRequest(ctx) { const { request, env } = ctx; }` +- Use `_worker.js` for complex routing: `env.ASSETS.fetch(request)` for static files + +**Other platforms → Pages:** +- File-based routing: `/functions/api/users.js` → `/api/users` +- Dynamic routes: `[param]` not `:param` +- Replace Node.js deps with Workers APIs or add `nodejs_compat` flag + +## Resources + +- [Official Docs](https://developers.cloudflare.com/pages/functions/) +- [Workers APIs](https://developers.cloudflare.com/workers/runtime-apis/) +- [Examples](https://github.com/cloudflare/pages-example-projects) +- [Discord](https://discord.gg/cloudflaredev) + +**See also:** [configuration.md](./configuration.md) for TypeScript setup | [patterns.md](./patterns.md) for middleware/auth | [api.md](./api.md) for bindings diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..b568a302fbdcfc7e7d002dd638f1db6aec0ebed8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pages-functions/patterns.md @@ -0,0 +1,137 @@ +# Common Patterns + +## Background Tasks (waitUntil) + +Non-blocking tasks after response sent (analytics, cleanup, webhooks): + +```typescript +export async function onRequest(ctx: EventContext) { + const res = Response.json({ success: true }); + + ctx.waitUntil(ctx.env.KV.put('last-visit', new Date().toISOString())); + ctx.waitUntil(Promise.all([ + ctx.env.ANALYTICS.writeDataPoint({ event: 'view' }), + fetch('https://webhook.site/...', { method: 'POST' }) + ])); + + return res; // Returned immediately +} +``` + +## Middleware & Auth + +```typescript +// functions/_middleware.js (global) or functions/users/_middleware.js (scoped) +export async function onRequest(ctx) { + try { return await ctx.next(); } + catch (err) { return new Response(err.message, { status: 500 }); } +} + +// Chained: export const onRequest = [errorHandler, auth, logger]; + +// Auth +async function auth(ctx: EventContext) { + const token = ctx.request.headers.get('authorization')?.replace('Bearer ', ''); + if (!token) return new Response('Unauthorized', { status: 401 }); + const session = await ctx.env.KV.get(`session:${token}`); + if (!session) return new Response('Invalid', { status: 401 }); + ctx.data.user = JSON.parse(session); + return ctx.next(); +} +``` + +## CORS & Rate Limiting + +```typescript +// CORS middleware +const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST' }; +export async function onRequestOptions() { return new Response(null, { headers: cors }); } +export async function onRequest(ctx) { + const res = await ctx.next(); + Object.entries(cors).forEach(([k, v]) => res.headers.set(k, v)); + return res; +} + +// Rate limiting (KV-based) +async function rateLimit(ctx: EventContext) { + const ip = ctx.request.headers.get('CF-Connecting-IP') || 'unknown'; + const count = parseInt(await ctx.env.KV.get(`rate:${ip}`) || '0'); + if (count >= 100) return new Response('Rate limited', { status: 429 }); + await ctx.env.KV.put(`rate:${ip}`, (count + 1).toString(), { expirationTtl: 3600 }); + return ctx.next(); +} +``` + +## Forms, Caching, Redirects + +```typescript +// JSON & file upload +export async function onRequestPost(ctx) { + const ct = ctx.request.headers.get('content-type') || ''; + if (ct.includes('application/json')) return Response.json(await ctx.request.json()); + if (ct.includes('multipart/form-data')) { + const file = (await ctx.request.formData()).get('file') as File; + await ctx.env.BUCKET.put(file.name, file.stream()); + return Response.json({ uploaded: file.name }); + } +} + +// Cache API +export async function onRequest(ctx) { + let res = await caches.default.match(ctx.request); + if (!res) { + res = new Response('Data'); + res.headers.set('Cache-Control', 'public, max-age=3600'); + ctx.waitUntil(caches.default.put(ctx.request, res.clone())); + } + return res; +} + +// Redirects +export async function onRequest(ctx) { + if (new URL(ctx.request.url).pathname === '/old') { + return Response.redirect(new URL('/new', ctx.request.url), 301); + } + return ctx.next(); +} +``` + +## Testing + +**Unit tests** (Vitest + cloudflare:test): +```typescript +import { env } from 'cloudflare:test'; +import { it, expect } from 'vitest'; +import { onRequest } from '../functions/api'; + +it('returns JSON', async () => { + const req = new Request('http://localhost/api'); + const ctx = { request: req, env, params: {}, data: {} } as EventContext; + const res = await onRequest(ctx); + expect(res.status).toBe(200); +}); +``` + +**Integration:** `wrangler pages dev` + Playwright/Cypress + +## Advanced Mode (_worker.js) + +Use `_worker.js` for complex routing (replaces `/functions`): + +```typescript +interface Env { ASSETS: Fetcher; KV: KVNamespace; } + +export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + if (url.pathname.startsWith('/api/')) { + return Response.json({ data: await env.KV.get('key') }); + } + return env.ASSETS.fetch(request); // Static files + } +} satisfies ExportedHandler; +``` + +**When:** Existing Worker, framework-generated (Next.js/SvelteKit), custom routing logic + +**See also:** [api.md](./api.md) for `env.ASSETS.fetch()` | [gotchas.md](./gotchas.md) for debugging diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/README.md new file mode 100644 index 0000000000000000000000000000000000000000..87601648522bd26aa2a99d52f50c0da06c7741b2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/README.md @@ -0,0 +1,105 @@ +# Cloudflare Pipelines + +ETL streaming platform for ingesting, transforming, and loading data into R2 with SQL transformations. + +## Overview + +Pipelines provides: +- **Streams**: Durable event buffers (HTTP/Workers ingestion) +- **Pipelines**: SQL-based transformations +- **Sinks**: R2 destinations (Iceberg tables or Parquet/JSON files) + +**Status**: Open beta (Workers Paid plan) +**Pricing**: No charge beyond standard R2 storage/operations + +## Architecture + +``` +Data Sources → Streams → Pipelines (SQL) → Sinks → R2 + ↑ ↓ ↓ + HTTP/Workers Transform Iceberg/Parquet +``` + +| Component | Purpose | Key Feature | +|-----------|---------|-------------| +| Streams | Event ingestion | Structured (validated) or unstructured | +| Pipelines | Transform with SQL | Immutable after creation | +| Sinks | Write to R2 | Exactly-once delivery | + +## Quick Start + +```bash +# Interactive setup (recommended) +npx wrangler pipelines setup +``` + +**Minimal Worker example:** +```typescript +interface Env { + STREAM: Pipeline; +} + +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const event = { user_id: "123", event_type: "purchase", amount: 29.99 }; + + // Fire-and-forget pattern + ctx.waitUntil(env.STREAM.send([event])); + + return new Response('OK'); + } +} satisfies ExportedHandler; +``` + +## Which Sink Type? + +``` +Need SQL queries on data? + → R2 Data Catalog (Iceberg) + ✅ ACID transactions, time-travel, schema evolution + ❌ More setup complexity (namespace, table, catalog token) + +Just file storage/archival? + → R2 Storage (Parquet) + ✅ Simple, direct file access + ❌ No built-in SQL queries + +Using external tools (Spark/Athena)? + → R2 Storage (Parquet with partitioning) + ✅ Standard format, partition pruning for performance + ❌ Must manage schema compatibility yourself +``` + +## Common Use Cases + +- **Analytics pipelines**: Clickstream, telemetry, server logs +- **Data warehousing**: ETL into queryable Iceberg tables +- **Event processing**: Mobile/IoT with enrichment +- **Ecommerce analytics**: User events, purchases, views + +## Reading Order + +**New to Pipelines?** Start here: +1. [configuration.md](./configuration.md) - Setup streams, sinks, pipelines +2. [api.md](./api.md) - Send events, TypeScript types, SQL functions +3. [patterns.md](./patterns.md) - Best practices, integrations, complete example +4. [gotchas.md](./gotchas.md) - Critical warnings, troubleshooting + +**Task-based routing:** +- Setup pipeline → [configuration.md](./configuration.md) +- Send/query data → [api.md](./api.md) +- Implement pattern → [patterns.md](./patterns.md) +- Debug issue → [gotchas.md](./gotchas.md) + +## In This Reference + +- [configuration.md](./configuration.md) - wrangler.jsonc bindings, schema definition, sink options, CLI commands +- [api.md](./api.md) - Pipeline binding interface, send() method, HTTP ingest, SQL function reference +- [patterns.md](./patterns.md) - Fire-and-forget, schema validation with Zod, integrations, performance tuning +- [gotchas.md](./gotchas.md) - Silent validation failures, immutable pipelines, latency expectations, limits + +## See Also + +- [r2](../r2/) - R2 storage backend for sinks +- [queues](../queues/) - Compare with Queues for async processing +- [workers](../workers/) - Worker runtime for event ingestion diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/api.md new file mode 100644 index 0000000000000000000000000000000000000000..f46e489aaec3316819e86977f26e7c608ae91ad0 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/api.md @@ -0,0 +1,208 @@ +# Pipelines API Reference + +## Pipeline Binding Interface + +```typescript +// From @cloudflare/workers-types +interface Pipeline { + send(data: object | object[]): Promise; +} + +interface Env { + STREAM: Pipeline; +} + +export default { + async fetch(request: Request, env: Env): Promise { + // send() returns Promise - no result data + await env.STREAM.send([event]); + return new Response('OK'); + } +} satisfies ExportedHandler; +``` + +**Key points:** +- `send()` accepts single object or array +- Always returns `Promise` (no confirmation data) +- Throws on network/validation errors (wrap in try/catch) +- Use `ctx.waitUntil()` for fire-and-forget pattern + +## Writing Events + +### Single Event + +```typescript +await env.STREAM.send([{ + user_id: "12345", + event_type: "purchase", + product_id: "widget-001", + amount: 29.99 +}]); +``` + +### Batch Events + +```typescript +const events = [ + { user_id: "user1", event_type: "view" }, + { user_id: "user2", event_type: "purchase", amount: 50 } +]; +await env.STREAM.send(events); +``` + +**Limits:** +- Max 1 MB per request +- 5 MB/s per stream + +### Fire-and-Forget Pattern + +```typescript +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const event = { /* ... */ }; + + // Don't block response on send + ctx.waitUntil(env.STREAM.send([event])); + + return new Response('OK'); + } +}; +``` + +### Error Handling + +```typescript +try { + await env.STREAM.send([event]); +} catch (error) { + console.error('Pipeline send failed:', error); + // Log to another system, retry, or return error response + return new Response('Failed to track event', { status: 500 }); +} +``` + +## HTTP Ingest API + +### Endpoint Format + +``` +https://{stream-id}.ingest.cloudflare.com +``` + +Get `{stream-id}` from: `npx wrangler pipelines streams list` + +### Request Format + +**CRITICAL:** Must send array, not single object + +```bash +# ✅ Correct +curl -X POST https://{stream-id}.ingest.cloudflare.com \ + -H "Content-Type: application/json" \ + -d '[{"user_id": "123", "event_type": "purchase"}]' + +# ❌ Wrong - will fail +curl -X POST https://{stream-id}.ingest.cloudflare.com \ + -H "Content-Type: application/json" \ + -d '{"user_id": "123", "event_type": "purchase"}' +``` + +### Authentication + +```bash +curl -X POST https://{stream-id}.ingest.cloudflare.com \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer YOUR_API_TOKEN" \ + -d '[{"event": "data"}]' +``` + +**Required permission:** Workers Pipeline Send + +Create token: Dashboard → Workers → API tokens → Create with Pipeline Send permission + +### Response Codes + +| Code | Meaning | Action | +|------|---------|--------| +| 200 | Accepted | Success | +| 400 | Invalid format | Check JSON array, schema match | +| 401 | Auth failed | Verify token valid | +| 413 | Payload too large | Split into smaller batches (<1 MB) | +| 429 | Rate limited | Back off, retry with delay | +| 5xx | Server error | Retry with exponential backoff | + +## SQL Functions Quick Reference + +Available in `INSERT INTO sink SELECT ... FROM stream` transformations: + +| Function | Example | Use Case | +|----------|---------|----------| +| `UPPER(s)` | `UPPER(event_type)` | Normalize strings | +| `LOWER(s)` | `LOWER(email)` | Case-insensitive matching | +| `CONCAT(...)` | `CONCAT(user_id, '_', product_id)` | Generate composite keys | +| `CASE WHEN ... THEN ... END` | `CASE WHEN amount > 100 THEN 'high' ELSE 'low' END` | Conditional enrichment | +| `CAST(x AS type)` | `CAST(timestamp AS string)` | Type conversion | +| `COALESCE(x, y)` | `COALESCE(amount, 0.0)` | Default values | +| Math operators | `amount * 1.1`, `price / quantity` | Calculations | +| Comparison | `amount > 100`, `status IN ('active', 'pending')` | Filtering | + +**String types for CAST:** `string`, `int32`, `int64`, `float32`, `float64`, `bool`, `timestamp` + +Full reference: [Pipelines SQL Reference](https://developers.cloudflare.com/pipelines/sql-reference/) + +## SQL Transform Examples + +### Filter Events + +```sql +INSERT INTO my_sink +SELECT * FROM my_stream +WHERE event_type = 'purchase' AND amount > 100 +``` + +### Select Specific Fields + +```sql +INSERT INTO my_sink +SELECT user_id, event_type, timestamp, amount +FROM my_stream +``` + +### Transform and Enrich + +```sql +INSERT INTO my_sink +SELECT + user_id, + UPPER(event_type) as event_type, + timestamp, + amount * 1.1 as amount_with_tax, + CONCAT(user_id, '_', product_id) as unique_key, + CASE + WHEN amount > 1000 THEN 'high_value' + WHEN amount > 100 THEN 'medium_value' + ELSE 'low_value' + END as customer_tier +FROM my_stream +WHERE event_type IN ('purchase', 'refund') +``` + +## Querying Results (R2 Data Catalog) + +```bash +export WRANGLER_R2_SQL_AUTH_TOKEN=YOUR_CATALOG_TOKEN + +npx wrangler r2 sql query "warehouse_name" " +SELECT + event_type, + COUNT(*) as event_count, + SUM(amount) as total_revenue +FROM default.my_table +WHERE event_type = 'purchase' + AND timestamp >= '2025-01-01' +GROUP BY event_type +ORDER BY total_revenue DESC +LIMIT 100" +``` + +**Note:** Iceberg tables support standard SQL queries with GROUP BY, JOINs, WHERE, ORDER BY, etc. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..75e65f5f33457400e2e7b52cd578bbad847ac8f1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/configuration.md @@ -0,0 +1,98 @@ +# Pipelines Configuration + +## Worker Binding + +```jsonc +// wrangler.jsonc +{ + "pipelines": [ + { "pipeline": "", "binding": "STREAM" } + ] +} +``` + +Get stream ID: `npx wrangler pipelines streams list` + +## Schema (Structured Streams) + +```json +{ + "fields": [ + { "name": "user_id", "type": "string", "required": true }, + { "name": "event_type", "type": "string", "required": true }, + { "name": "amount", "type": "float64", "required": false }, + { "name": "timestamp", "type": "timestamp", "required": true } + ] +} +``` + +**Types:** `string`, `int32`, `int64`, `float32`, `float64`, `bool`, `timestamp`, `json`, `binary`, `list`, `struct` + +## Stream Setup + +```bash +# With schema +npx wrangler pipelines streams create my-stream --schema-file schema.json + +# Unstructured (no validation) +npx wrangler pipelines streams create my-stream + +# List/get/delete +npx wrangler pipelines streams list +npx wrangler pipelines streams get +npx wrangler pipelines streams delete +``` + +## Sink Configuration + +**R2 Data Catalog (Iceberg):** +```bash +npx wrangler pipelines sinks create my-sink \ + --type r2-data-catalog \ + --bucket my-bucket --namespace default --table events \ + --catalog-token $TOKEN \ + --compression zstd --roll-interval 60 +``` + +**R2 Raw (Parquet):** +```bash +npx wrangler pipelines sinks create my-sink \ + --type r2 --bucket my-bucket --format parquet \ + --path analytics/events \ + --partitioning "year=%Y/month=%m/day=%d" \ + --access-key-id $KEY --secret-access-key $SECRET +``` + +| Option | Values | Guidance | +|--------|--------|----------| +| `--compression` | `zstd`, `snappy`, `gzip` | `zstd` best ratio, `snappy` fastest | +| `--roll-interval` | Seconds | Low latency: 10-60, Query perf: 300 | +| `--roll-size` | MB | Larger = better compression | + +## Pipeline Creation + +```bash +npx wrangler pipelines create my-pipeline \ + --sql "INSERT INTO my_sink SELECT * FROM my_stream WHERE event_type = 'purchase'" +``` + +**⚠️ Pipelines are immutable** - cannot modify SQL. Must delete/recreate. + +## Credentials + +| Type | Permission | Get From | +|------|------------|----------| +| Catalog token | R2 Admin Read & Write | Dashboard → R2 → API tokens | +| R2 credentials | Object Read & Write | `wrangler r2 bucket create` output | +| HTTP ingest token | Workers Pipeline Send | Dashboard → Workers → API tokens | + +## Complete Example + +```bash +npx wrangler r2 bucket create my-bucket +npx wrangler r2 bucket catalog enable my-bucket +npx wrangler pipelines streams create my-stream --schema-file schema.json +npx wrangler pipelines sinks create my-sink --type r2-data-catalog --bucket my-bucket ... +npx wrangler pipelines create my-pipeline --sql "INSERT INTO my_sink SELECT * FROM my_stream" +npx wrangler deploy +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..2a2a75fdadc52b0ee0017da83233a12eef947a05 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/gotchas.md @@ -0,0 +1,80 @@ +# Pipelines Gotchas + +## Critical Issues + +### Events Silently Dropped + +**Most common issue.** Events accepted (HTTP 200) but never appear in sink. + +**Causes:** +1. Schema validation fails - structured streams drop invalid events silently +2. Waiting for roll interval (10-300s) - expected behavior + +**Solution:** Validate client-side with Zod: +```typescript +const EventSchema = z.object({ user_id: z.string(), amount: z.number() }); +try { + const validated = EventSchema.parse(rawEvent); + await env.STREAM.send([validated]); +} catch (e) { /* get immediate feedback */ } +``` + +### Pipelines Are Immutable + +Cannot modify SQL after creation. Must delete and recreate. + +```bash +npx wrangler pipelines delete old-pipeline +npx wrangler pipelines create new-pipeline --sql "..." +``` + +**Tip:** Use version naming (`events-pipeline-v1`) and keep SQL in version control. + +### Worker Binding Not Found + +**`env.STREAM is undefined`** + +1. Use **stream ID** (not pipeline ID) in `wrangler.jsonc` +2. Redeploy after adding binding + +```bash +npx wrangler pipelines streams list # Get stream ID +npx wrangler deploy +``` + +## Common Errors + +| Error | Cause | Fix | +|-------|-------|-----| +| Events not in R2 | Roll interval not elapsed | Wait 10-300s, check `roll_interval` | +| Schema validation failures | Type mismatch, missing fields | Validate client-side | +| Rate limit (429) | >5 MB/s per stream | Batch events, request increase | +| Payload too large (413) | >1 MB request | Split into smaller batches | +| Cannot delete stream | Pipeline references it | Delete pipelines first | +| Sink credential errors | Token expired | Recreate sink with new credentials | + +## Limits (Open Beta) + +| Resource | Limit | +|----------|-------| +| Streams/Sinks/Pipelines per account | 20 each | +| Payload size | 1 MB | +| Ingest rate per stream | 5 MB/s | +| Event retention | 24 hours | +| Recommended batch size | 100 events | + +## SQL Limitations + +- **No JOINs** - single stream per pipeline +- **No window functions** - basic SQL only +- **No subqueries** - must use `INSERT INTO ... SELECT ... FROM` +- **No schema evolution** - cannot modify after creation + +## Debug Checklist + +- [ ] Stream exists: `npx wrangler pipelines streams list` +- [ ] Pipeline healthy: `npx wrangler pipelines get ` +- [ ] SQL syntax matches schema +- [ ] Worker redeployed after binding added +- [ ] Waited for roll interval +- [ ] Accepted vs processed count matches (no validation drops) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..186b6a2ce4bc7d756f809f0c359f2786cd64e0d5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pipelines/patterns.md @@ -0,0 +1,87 @@ +# Pipelines Patterns + +## Fire-and-Forget + +```typescript +export default { + async fetch(request, env, ctx) { + const event = { user_id: '...', event_type: 'page_view', timestamp: new Date().toISOString() }; + ctx.waitUntil(env.STREAM.send([event])); // Don't block response + return new Response('OK'); + } +}; +``` + +## Schema Validation with Zod + +```typescript +import { z } from 'zod'; + +const EventSchema = z.object({ + user_id: z.string(), + event_type: z.enum(['purchase', 'view']), + amount: z.number().positive().optional() +}); + +const validated = EventSchema.parse(rawEvent); // Throws on invalid +await env.STREAM.send([validated]); +``` + +**Why:** Structured streams drop invalid events silently. Client validation gives immediate feedback. + +## SQL Transform Patterns + +```sql +-- Filter early (reduce storage) +INSERT INTO my_sink +SELECT user_id, event_type, amount +FROM my_stream +WHERE event_type = 'purchase' AND amount > 10 + +-- Select only needed fields +INSERT INTO my_sink +SELECT user_id, event_type, timestamp FROM my_stream + +-- Enrich with CASE +INSERT INTO my_sink +SELECT user_id, amount, + CASE WHEN amount > 1000 THEN 'vip' ELSE 'standard' END as tier +FROM my_stream +``` + +## Pipelines + Queues Fan-out + +```typescript +await Promise.all([ + env.ANALYTICS_STREAM.send([event]), // Long-term storage + env.PROCESS_QUEUE.send(event) // Immediate processing +]); +``` + +| Need | Use | +|------|-----| +| Long-term storage, SQL queries | Pipelines | +| Immediate processing, retries | Queues | +| Both | Fan-out pattern | + +## Performance Tuning + +| Goal | Config | +|------|--------| +| Low latency | `--roll-interval 10` | +| Query performance | `--roll-interval 300 --roll-size 100` | +| Cost optimal | `--compression zstd --roll-interval 300` | + +## Schema Evolution + +Pipelines are immutable. Use versioning: + +```bash +# Create v2 stream/sink/pipeline +npx wrangler pipelines streams create events-v2 --schema-file v2.json + +# Dual-write during transition +await Promise.all([env.EVENTS_V1.send([event]), env.EVENTS_V2.send([event])]); + +# Query across versions with UNION ALL +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e78d807bbeeb8fa915373715499cafe5793522a8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/README.md @@ -0,0 +1,100 @@ +# Cloudflare Pulumi Provider + +Expert guidance for Cloudflare Pulumi Provider (@pulumi/cloudflare). + +## Overview + +Programmatic management of Cloudflare resources: Workers, Pages, D1, KV, R2, DNS, Queues, etc. + +**Packages:** +- TypeScript/JS: `@pulumi/cloudflare` +- Python: `pulumi-cloudflare` +- Go: `github.com/pulumi/pulumi-cloudflare/sdk/v6/go/cloudflare` +- .NET: `Pulumi.Cloudflare` + +**Version:** v6.x + +## Core Principles + +1. Use API tokens (not legacy API keys) +2. Store accountId in stack config +3. Match binding names across code/config +4. Use `module: true` for ES modules +5. Set `compatibilityDate` to lock behavior + +## Authentication + +```typescript +import * as cloudflare from "@pulumi/cloudflare"; + +// API Token (recommended): CLOUDFLARE_API_TOKEN env +const provider = new cloudflare.Provider("cf", { apiToken: process.env.CLOUDFLARE_API_TOKEN }); + +// API Key (legacy): CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL env +const provider = new cloudflare.Provider("cf", { apiKey: process.env.CLOUDFLARE_API_KEY, email: process.env.CLOUDFLARE_EMAIL }); + +// API User Service Key: CLOUDFLARE_API_USER_SERVICE_KEY env +const provider = new cloudflare.Provider("cf", { apiUserServiceKey: process.env.CLOUDFLARE_API_USER_SERVICE_KEY }); +``` + +## Setup + +**Pulumi.yaml:** +```yaml +name: my-cloudflare-app +runtime: nodejs +config: + cloudflare:apiToken: + value: ${CLOUDFLARE_API_TOKEN} +``` + +**Pulumi..yaml:** +```yaml +config: + cloudflare:accountId: "abc123..." +``` + +**index.ts:** +```typescript +import * as pulumi from "@pulumi/pulumi"; +import * as cloudflare from "@pulumi/cloudflare"; +const accountId = new pulumi.Config("cloudflare").require("accountId"); +``` + +## Common Resource Types +- `Provider` - Provider config +- `WorkerScript` - Worker +- `WorkersKvNamespace` - KV +- `R2Bucket` - R2 +- `D1Database` - D1 +- `Queue` - Queue +- `PagesProject` - Pages +- `DnsRecord` - DNS +- `WorkerRoute` - Worker route +- `WorkersDomain` - Custom domain + +## Key Properties +- `accountId` - Required for most resources +- `zoneId` - Required for DNS/domain +- `name`/`title` - Resource identifier +- `*Bindings` - Connect resources to Workers + +## Reading Order + +| Order | File | What | When to Read | +|-------|------|------|--------------| +| 1 | [configuration.md](./configuration.md) | Resource config for Workers/KV/D1/R2/Queues/Pages | First time setup, resource reference | +| 2 | [patterns.md](./patterns.md) | Architecture patterns, multi-env, component resources | Building complex apps, best practices | +| 3 | [api.md](./api.md) | Outputs, dependencies, imports, dynamic providers | Advanced features, integrations | +| 4 | [gotchas.md](./gotchas.md) | Common errors, troubleshooting, limits | Debugging, deployment issues | + +## In This Reference +- [configuration.md](./configuration.md) - Provider config, stack setup, Workers/bindings +- [api.md](./api.md) - Resource types, Workers script, KV/D1/R2/queues/Pages +- [patterns.md](./patterns.md) - Multi-env, secrets, CI/CD, stack management +- [gotchas.md](./gotchas.md) - State issues, deployment failures, limits + +## See Also +- [terraform](../terraform/) - Alternative IaC for Cloudflare +- [wrangler](../wrangler/) - CLI deployment alternative +- [workers](../workers/) - Worker runtime documentation diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/api.md new file mode 100644 index 0000000000000000000000000000000000000000..332cfef3fb678168ee6b97949679618c74e7951a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/api.md @@ -0,0 +1,200 @@ +# API & Data Sources + +## Outputs and Exports + +Export resource identifiers: + +```typescript +export const kvId = kv.id; +export const bucketName = bucket.name; +export const workerUrl = worker.subdomain; +export const dbId = db.id; +``` + +## Resource Dependencies + +Implicit dependencies via outputs: + +```typescript +const kv = new cloudflare.WorkersKvNamespace("kv", { + accountId: accountId, + title: "my-kv", +}); + +// Worker depends on KV (implicit via kv.id) +const worker = new cloudflare.WorkerScript("worker", { + accountId: accountId, + name: "my-worker", + content: code, + kvNamespaceBindings: [{name: "MY_KV", namespaceId: kv.id}], // Creates dependency +}); +``` + +Explicit dependencies: + +```typescript +const migration = new command.local.Command("migration", { + create: pulumi.interpolate`wrangler d1 execute ${db.name} --file ./schema.sql`, +}, {dependsOn: [db]}); + +const worker = new cloudflare.WorkerScript("worker", { + accountId: accountId, + name: "worker", + content: code, + d1DatabaseBindings: [{name: "DB", databaseId: db.id}], +}, {dependsOn: [migration]}); // Ensure migrations run first +``` + +## Using Outputs with API Calls + +```typescript +const db = new cloudflare.D1Database("db", {accountId, name: "my-db"}); + +db.id.apply(async (dbId) => { + const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/d1/database/${dbId}/query`, + {method: "POST", headers: {"Authorization": `Bearer ${apiToken}`, "Content-Type": "application/json"}, + body: JSON.stringify({sql: "CREATE TABLE users (id INT)"})} + ); + return response.json(); +}); +``` + +## Custom Dynamic Providers + +For resources not in provider: + +```typescript +import * as pulumi from "@pulumi/pulumi"; + +class D1MigrationProvider implements pulumi.dynamic.ResourceProvider { + async create(inputs: any): Promise { + const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${inputs.accountId}/d1/database/${inputs.databaseId}/query`, + {method: "POST", headers: {"Authorization": `Bearer ${inputs.apiToken}`, "Content-Type": "application/json"}, + body: JSON.stringify({sql: inputs.sql})} + ); + return {id: `${inputs.databaseId}-${Date.now()}`, outs: await response.json()}; + } + async update(id: string, olds: any, news: any): Promise { + if (olds.sql !== news.sql) await this.create(news); + return {}; + } + async delete(id: string, props: any): Promise {} +} + +class D1Migration extends pulumi.dynamic.Resource { + constructor(name: string, args: any, opts?: pulumi.CustomResourceOptions) { + super(new D1MigrationProvider(), name, args, opts); + } +} + +const migration = new D1Migration("migration", { + accountId, databaseId: db.id, apiToken, sql: "CREATE TABLE users (id INT)", +}, {dependsOn: [db]}); +``` + +## Data Sources + +**Get Zone:** +```typescript +const zone = cloudflare.getZone({name: "example.com"}); +const zoneId = zone.then(z => z.id); +``` + +**Get Accounts (via API):** +Use Cloudflare API directly or custom dynamic resources. + +## Import Existing Resources + +```bash +# Import worker +pulumi import cloudflare:index/workerScript:WorkerScript my-worker / + +# Import KV namespace +pulumi import cloudflare:index/workersKvNamespace:WorkersKvNamespace my-kv + +# Import R2 bucket +pulumi import cloudflare:index/r2Bucket:R2Bucket my-bucket / + +# Import D1 database +pulumi import cloudflare:index/d1Database:D1Database my-db / + +# Import DNS record +pulumi import cloudflare:index/dnsRecord:DnsRecord my-record / +``` + +## Secrets Management + +```typescript +import * as pulumi from "@pulumi/pulumi"; + +const config = new pulumi.Config(); +const apiKey = config.requireSecret("apiKey"); // Encrypted in state + +const worker = new cloudflare.WorkerScript("worker", { + accountId: accountId, + name: "my-worker", + content: code, + secretTextBindings: [{name: "API_KEY", text: apiKey}], +}); +``` + +Store secrets: +```bash +pulumi config set --secret apiKey "secret-value" +``` + +## Transform Pattern + +Modify resource args before creation: + +```typescript +import {Transform} from "@pulumi/pulumi"; + +interface BucketArgs { + accountId: pulumi.Input; + transform?: {bucket?: Transform}; +} + +function createBucket(name: string, args: BucketArgs) { + const bucketArgs: cloudflare.R2BucketArgs = { + accountId: args.accountId, + name: name, + location: "auto", + }; + const finalArgs = args.transform?.bucket?.(bucketArgs) ?? bucketArgs; + return new cloudflare.R2Bucket(name, finalArgs); +} +``` + +## v6.x Worker Versioning Resources + +**Worker** - Container for versions: +```typescript +const worker = new cloudflare.Worker("api", {accountId, name: "api-worker"}); +export const workerId = worker.id; +``` + +**WorkerVersion** - Immutable code + config: +```typescript +const version = new cloudflare.WorkerVersion("v1", { + accountId, workerId: worker.id, + content: fs.readFileSync("./dist/worker.js", "utf8"), + compatibilityDate: "2025-01-01", +}); +export const versionId = version.id; +``` + +**WorkersDeployment** - Active deployment with bindings: +```typescript +const deployment = new cloudflare.WorkersDeployment("prod", { + accountId, workerId: worker.id, versionId: version.id, + kvNamespaceBindings: [{name: "MY_KV", namespaceId: kv.id}], +}); +``` + +**Use:** Advanced deployments (canary, blue-green). Most apps should use `WorkerScript` (auto-versioning). + +--- +See: [README.md](./README.md), [configuration.md](./configuration.md), [patterns.md](./patterns.md), [gotchas.md](./gotchas.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..615eacc272a1aa0ccc4cffde657e3447a8b366ba --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/configuration.md @@ -0,0 +1,198 @@ +# Resource Configuration + +## Workers (cloudflare.WorkerScript) + +```typescript +import * as cloudflare from "@pulumi/cloudflare"; +import * as fs from "fs"; + +const worker = new cloudflare.WorkerScript("my-worker", { + accountId: accountId, + name: "my-worker", + content: fs.readFileSync("./dist/worker.js", "utf8"), + module: true, // ES modules + compatibilityDate: "2025-01-01", + compatibilityFlags: ["nodejs_compat"], + + // v6.x: Observability + logpush: true, // Enable Workers Logpush + tailConsumers: [{service: "log-consumer"}], // Stream logs to Worker + + // v6.x: Placement + placement: {mode: "smart"}, // Smart placement for latency optimization + + // Bindings + kvNamespaceBindings: [{name: "MY_KV", namespaceId: kv.id}], + r2BucketBindings: [{name: "MY_BUCKET", bucketName: bucket.name}], + d1DatabaseBindings: [{name: "DB", databaseId: db.id}], + queueBindings: [{name: "MY_QUEUE", queue: queue.id}], + serviceBindings: [{name: "OTHER_SERVICE", service: other.name}], + plainTextBindings: [{name: "ENV_VAR", text: "value"}], + secretTextBindings: [{name: "API_KEY", text: secret}], + + // v6.x: Advanced bindings + analyticsEngineBindings: [{name: "ANALYTICS", dataset: "my-dataset"}], + browserBinding: {name: "BROWSER"}, // Browser Rendering + aiBinding: {name: "AI"}, // Workers AI + hyperdriveBindings: [{name: "HYPERDRIVE", id: hyperdriveConfig.id}], +}); +``` + +## Workers KV (cloudflare.WorkersKvNamespace) + +```typescript +const kv = new cloudflare.WorkersKvNamespace("my-kv", { + accountId: accountId, + title: "my-kv-namespace", +}); + +// Write values +const kvValue = new cloudflare.WorkersKvValue("config", { + accountId: accountId, + namespaceId: kv.id, + key: "config", + value: JSON.stringify({foo: "bar"}), +}); +``` + +## R2 Buckets (cloudflare.R2Bucket) + +```typescript +const bucket = new cloudflare.R2Bucket("my-bucket", { + accountId: accountId, + name: "my-bucket", + location: "auto", // or "wnam", etc. +}); +``` + +## D1 Databases (cloudflare.D1Database) + +```typescript +const db = new cloudflare.D1Database("my-db", {accountId, name: "my-database"}); + +// Migrations via wrangler +import * as command from "@pulumi/command"; +const migration = new command.local.Command("d1-migration", { + create: pulumi.interpolate`wrangler d1 execute ${db.name} --file ./schema.sql`, +}, {dependsOn: [db]}); +``` + +## Queues (cloudflare.Queue) + +```typescript +const queue = new cloudflare.Queue("my-queue", {accountId, name: "my-queue"}); + +// Producer +const producer = new cloudflare.WorkerScript("producer", { + accountId, name: "producer", content: code, + queueBindings: [{name: "MY_QUEUE", queue: queue.id}], +}); + +// Consumer +const consumer = new cloudflare.WorkerScript("consumer", { + accountId, name: "consumer", content: code, + queueConsumers: [{queue: queue.name, maxBatchSize: 10, maxRetries: 3}], +}); +``` + +## Pages Projects (cloudflare.PagesProject) + +```typescript +const pages = new cloudflare.PagesProject("my-site", { + accountId, name: "my-site", productionBranch: "main", + buildConfig: {buildCommand: "npm run build", destinationDir: "dist"}, + source: { + type: "github", + config: {owner: "my-org", repoName: "my-repo", productionBranch: "main"}, + }, + deploymentConfigs: { + production: { + environmentVariables: {NODE_VERSION: "18"}, + kvNamespaces: {MY_KV: kv.id}, + d1Databases: {DB: db.id}, + }, + }, +}); +``` + +## DNS Records (cloudflare.DnsRecord) + +```typescript +const zone = cloudflare.getZone({name: "example.com"}); +const record = new cloudflare.DnsRecord("www", { + zoneId: zone.then(z => z.id), name: "www", type: "A", + content: "192.0.2.1", ttl: 3600, proxied: true, +}); +``` + +## Workers Domains/Routes + +```typescript +// Route (pattern-based) +const route = new cloudflare.WorkerRoute("my-route", { + zoneId: zoneId, + pattern: "example.com/api/*", + scriptName: worker.name, +}); + +// Domain (dedicated subdomain) +const domain = new cloudflare.WorkersDomain("my-domain", { + accountId: accountId, + hostname: "api.example.com", + service: worker.name, + zoneId: zoneId, +}); +``` + +## Assets Configuration (v6.x) + +Serve static assets from Workers: + +```typescript +const worker = new cloudflare.WorkerScript("app", { + accountId: accountId, + name: "my-app", + content: code, + assets: { + path: "./public", // Local directory + // Assets uploaded and served from Workers + }, +}); +``` + +## v6.x Versioned Deployments (Advanced) + +For gradual rollouts, use 3-resource pattern: + +```typescript +// 1. Worker (container for versions) +const worker = new cloudflare.Worker("api", { + accountId: accountId, + name: "api-worker", +}); + +// 2. Version (immutable code + config) +const version = new cloudflare.WorkerVersion("v1", { + accountId: accountId, + workerId: worker.id, + content: fs.readFileSync("./dist/worker.js", "utf8"), + compatibilityDate: "2025-01-01", + compatibilityFlags: ["nodejs_compat"], + // Note: Bindings configured at deployment level +}); + +// 3. Deployment (version + bindings + traffic split) +const deployment = new cloudflare.WorkersDeployment("prod", { + accountId: accountId, + workerId: worker.id, + versionId: version.id, + // Bindings applied to deployment + kvNamespaceBindings: [{name: "MY_KV", namespaceId: kv.id}], +}); +``` + +**When to use:** Blue-green deployments, canary releases, gradual rollouts +**When NOT to use:** Simple single-version deployments (use WorkerScript) + +--- +See: [README.md](./README.md), [api.md](./api.md), [patterns.md](./patterns.md), [gotchas.md](./gotchas.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..605457ac8b10f5cf188d0e718adab5f61802b027 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/gotchas.md @@ -0,0 +1,181 @@ +# Troubleshooting & Best Practices + +## Common Errors + +### "No bundler/build step" - Pulumi uploads raw code + +**Problem:** Worker fails with "Cannot use import statement outside a module" +**Cause:** Pulumi doesn't bundle Worker code - uploads exactly what you provide +**Solution:** Build Worker BEFORE Pulumi deploy + +```typescript +// WRONG: Pulumi won't bundle this +const worker = new cloudflare.WorkerScript("worker", { + content: fs.readFileSync("./src/index.ts", "utf8"), // Raw TS file +}); + +// RIGHT: Build first, then deploy +import * as command from "@pulumi/command"; +const build = new command.local.Command("build", { + create: "npm run build", + dir: "./worker", +}); +const worker = new cloudflare.WorkerScript("worker", { + content: build.stdout.apply(() => fs.readFileSync("./worker/dist/index.js", "utf8")), +}, {dependsOn: [build]}); +``` + +### "wrangler.toml not consumed" - Config drift + +**Problem:** Local wrangler dev works, Pulumi deploy fails +**Cause:** Pulumi ignores wrangler.toml - must duplicate config +**Solution:** Generate wrangler.toml from Pulumi or keep synced manually + +```typescript +// Pattern: Export Pulumi config to wrangler.toml +const workerConfig = { + name: "my-worker", + compatibilityDate: "2025-01-01", + compatibilityFlags: ["nodejs_compat"], +}; + +new command.local.Command("generate-wrangler", { + create: pulumi.interpolate`cat > wrangler.toml <.yaml +config: + cloudflare:accountId: "abc123..." +``` + +### "Binding name mismatch" + +**Problem:** Worker fails with "env.MY_KV is undefined" +**Cause:** Binding name in Pulumi != name in Worker code +**Solution:** Match exactly (case-sensitive) + +```typescript +// Pulumi +kvNamespaceBindings: [{name: "MY_KV", namespaceId: kv.id}] + +// Worker code +export default { async fetch(request, env) { await env.MY_KV.get("key"); }} +``` + +### "API token permissions insufficient" + +**Problem:** `Error: authentication error (10000)` +**Cause:** Token lacks required permissions +**Solution:** Grant token permissions: Account.Workers Scripts:Edit, Account.Account Settings:Read + +### "Resource not found after import" + +**Problem:** Imported resource shows as changed on next `pulumi up` +**Cause:** State mismatch between actual resource and Pulumi config +**Solution:** Check property names/types match exactly + +```bash +pulumi import cloudflare:index/workerScript:WorkerScript my-worker / +pulumi preview # If shows changes, adjust Pulumi code to match actual resource +``` + +### "v6.x Worker versioning confusion" + +**Problem:** Worker deployed but not receiving traffic +**Cause:** v6.x requires Worker + WorkerVersion + WorkersDeployment (3 resources) +**Solution:** Use WorkerScript (auto-versioning) OR full versioning pattern + +```typescript +// SIMPLE: WorkerScript auto-versions (default behavior) +const worker = new cloudflare.WorkerScript("worker", { + accountId, name: "my-worker", content: code, +}); + +// ADVANCED: Manual versioning for gradual rollouts (v6.x) +const worker = new cloudflare.Worker("worker", {accountId, name: "my-worker"}); +const version = new cloudflare.WorkerVersion("v1", { + accountId, workerId: worker.id, content: code, compatibilityDate: "2025-01-01", +}); +const deployment = new cloudflare.WorkersDeployment("prod", { + accountId, workerId: worker.id, versionId: version.id, +}); +``` + +## Best Practices + +1. **Always set compatibilityDate** - Locks Worker behavior, prevents breaking changes +2. **Build before deploy** - Pulumi doesn't bundle; use Command resource or CI build step +3. **Match binding names** - Case-sensitive, must match between Pulumi and Worker code +4. **Use dependsOn for migrations** - Ensure D1 migrations run before Worker deploys +5. **Version Worker content** - Add VERSION binding to force redeployment on content changes +6. **Store secrets in stack config** - Use `pulumi config set --secret` for API keys + +## Limits + +| Resource | Limit | Notes | +|----------|-------|-------| +| Worker script size | 10 MB | Includes all dependencies, after compression | +| Worker CPU time | 50ms (free), 30s (paid) | Per request | +| KV keys per namespace | Unlimited | 1000 ops/sec write, 100k ops/sec read | +| R2 storage | Unlimited | Class A ops: 1M/mo free, Class B: 10M/mo free | +| D1 databases | 50,000 per account | Free: 10 per account, 5 GB each | +| Queues | 10,000 per account | Free: 1M ops/day | +| Pages projects | 500 per account | Free: 100 projects | +| API requests | Varies by plan | ~1200 req/5min on free | + +## Resources + +- **Pulumi Registry:** https://www.pulumi.com/registry/packages/cloudflare/ +- **API Docs:** https://www.pulumi.com/registry/packages/cloudflare/api-docs/ +- **GitHub:** https://github.com/pulumi/pulumi-cloudflare +- **Cloudflare Docs:** https://developers.cloudflare.com/ +- **Workers Docs:** https://developers.cloudflare.com/workers/ + +--- +See: [README.md](./README.md), [configuration.md](./configuration.md), [api.md](./api.md), [patterns.md](./patterns.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..c843d54a520934fffa29f7b1a0f3fcc4bb890eda --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/pulumi/patterns.md @@ -0,0 +1,191 @@ +# Architecture Patterns + +## Component Resources + +```typescript +class WorkerApp extends pulumi.ComponentResource { + constructor(name: string, args: WorkerAppArgs, opts?) { + super("custom:cloudflare:WorkerApp", name, {}, opts); + const defaultOpts = {parent: this}; + + this.kv = new cloudflare.WorkersKvNamespace(`${name}-kv`, {accountId: args.accountId, title: `${name}-kv`}, defaultOpts); + this.worker = new cloudflare.WorkerScript(`${name}-worker`, { + accountId: args.accountId, name: `${name}-worker`, content: args.workerCode, + module: true, kvNamespaceBindings: [{name: "KV", namespaceId: this.kv.id}], + }, defaultOpts); + this.domain = new cloudflare.WorkersDomain(`${name}-domain`, { + accountId: args.accountId, hostname: args.domain, service: this.worker.name, + }, defaultOpts); + } +} +``` + +## Full-Stack Worker App + +```typescript +const kv = new cloudflare.WorkersKvNamespace("cache", {accountId, title: "api-cache"}); +const db = new cloudflare.D1Database("db", {accountId, name: "app-database"}); +const bucket = new cloudflare.R2Bucket("assets", {accountId, name: "app-assets"}); + +const apiWorker = new cloudflare.WorkerScript("api", { + accountId, name: "api-worker", content: fs.readFileSync("./dist/api.js", "utf8"), + module: true, kvNamespaceBindings: [{name: "CACHE", namespaceId: kv.id}], + d1DatabaseBindings: [{name: "DB", databaseId: db.id}], + r2BucketBindings: [{name: "ASSETS", bucketName: bucket.name}], +}); +``` + +## Multi-Environment Setup + +```typescript +const stack = pulumi.getStack(); +const worker = new cloudflare.WorkerScript(`worker-${stack}`, { + accountId, name: `my-worker-${stack}`, content: code, + plainTextBindings: [{name: "ENVIRONMENT", text: stack}], +}); +``` + +## Queue-Based Processing + +```typescript +const queue = new cloudflare.Queue("processing-queue", {accountId, name: "image-processing"}); + +// Producer: API receives requests +const apiWorker = new cloudflare.WorkerScript("api", { + accountId, name: "api-worker", content: apiCode, + queueBindings: [{name: "PROCESSING_QUEUE", queue: queue.id}], +}); + +// Consumer: Process async +const processorWorker = new cloudflare.WorkerScript("processor", { + accountId, name: "processor-worker", content: processorCode, + queueConsumers: [{queue: queue.name, maxBatchSize: 10, maxRetries: 3, maxWaitTimeMs: 5000}], + r2BucketBindings: [{name: "OUTPUT_BUCKET", bucketName: outputBucket.name}], +}); +``` + +## Microservices with Service Bindings + +```typescript +const authWorker = new cloudflare.WorkerScript("auth", {accountId, name: "auth-service", content: authCode}); +const apiWorker = new cloudflare.WorkerScript("api", { + accountId, name: "api-service", content: apiCode, + serviceBindings: [{name: "AUTH", service: authWorker.name}], +}); +``` + +## Event-Driven Architecture + +```typescript +const eventQueue = new cloudflare.Queue("events", {accountId, name: "event-bus"}); +const producer = new cloudflare.WorkerScript("producer", { + accountId, name: "api-producer", content: producerCode, + queueBindings: [{name: "EVENTS", queue: eventQueue.id}], +}); +const consumer = new cloudflare.WorkerScript("consumer", { + accountId, name: "email-consumer", content: consumerCode, + queueConsumers: [{queue: eventQueue.name, maxBatchSize: 10}], +}); +``` + +## v6.x Versioned Deployments (Blue-Green/Canary) + +```typescript +const worker = new cloudflare.Worker("api", {accountId, name: "api-worker"}); +const v1 = new cloudflare.WorkerVersion("v1", {accountId, workerId: worker.id, content: fs.readFileSync("./dist/v1.js", "utf8"), compatibilityDate: "2025-01-01"}); +const v2 = new cloudflare.WorkerVersion("v2", {accountId, workerId: worker.id, content: fs.readFileSync("./dist/v2.js", "utf8"), compatibilityDate: "2025-01-01"}); + +// Gradual rollout: 10% v2, 90% v1 +const deployment = new cloudflare.WorkersDeployment("canary", { + accountId, workerId: worker.id, + versions: [{versionId: v2.id, percentage: 10}, {versionId: v1.id, percentage: 90}], + kvNamespaceBindings: [{name: "MY_KV", namespaceId: kv.id}], +}); +``` + +**Use:** Canary releases, A/B testing, blue-green. Most apps use `WorkerScript` (auto-versioning). + +## Wrangler.toml Generation (Bridge IaC with Local Dev) + +Generate wrangler.toml from Pulumi config to keep local dev in sync: + +```typescript +import * as command from "@pulumi/command"; + +const workerConfig = { + name: "my-worker", + compatibilityDate: "2025-01-01", + compatibilityFlags: ["nodejs_compat"], +}; + +// Create resources +const kv = new cloudflare.WorkersKvNamespace("kv", {accountId, title: "my-kv"}); +const db = new cloudflare.D1Database("db", {accountId, name: "my-db"}); +const bucket = new cloudflare.R2Bucket("bucket", {accountId, name: "my-bucket"}); + +// Generate wrangler.toml after resources created +const wranglerGen = new command.local.Command("gen-wrangler", { + create: pulumi.interpolate`cat > wrangler.toml < fs.readFileSync("./worker/dist/index.js", "utf8")), +}, {dependsOn: [build]}); +``` + +## Content SHA Pattern (Force Updates) + +Prevent false "no changes" detections: + +```typescript +const version = Date.now().toString(); +const worker = new cloudflare.WorkerScript("worker", { + accountId, name: "my-worker", content: code, + plainTextBindings: [{name: "VERSION", text: version}], // Forces deployment +}); +``` + +--- +See: [README.md](./README.md), [configuration.md](./configuration.md), [api.md](./api.md), [gotchas.md](./gotchas.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/README.md new file mode 100644 index 0000000000000000000000000000000000000000..88702fad986bfc1ff982f2307cb55133638e9074 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/README.md @@ -0,0 +1,149 @@ +# Cloudflare R2 Data Catalog Skill Reference + +Expert guidance for Cloudflare R2 Data Catalog - Apache Iceberg catalog built into R2 buckets. + +## Reading Order + +**New to R2 Data Catalog?** Start here: +1. Read "What is R2 Data Catalog?" and "When to Use" below +2. [configuration.md](configuration.md) - Enable catalog, create tokens +3. [patterns.md](patterns.md) - PyIceberg setup and common patterns +4. [api.md](api.md) - REST API reference as needed +5. [gotchas.md](gotchas.md) - Troubleshooting when issues arise + +**Quick reference?** Jump to: +- [Enable catalog on bucket](configuration.md#enable-catalog-on-bucket) +- [PyIceberg connection pattern](patterns.md#pyiceberg-connection-pattern) +- [Permission errors](gotchas.md#permission-errors) + +## What is R2 Data Catalog? + +R2 Data Catalog is a **managed Apache Iceberg REST catalog** built directly into R2 buckets. It provides: + +- **Apache Iceberg tables** - ACID transactions, schema evolution, time-travel queries +- **Zero-egress costs** - Query from any cloud/region without data transfer fees +- **Standard REST API** - Works with Spark, PyIceberg, Snowflake, Trino, DuckDB +- **No infrastructure** - Fully managed, no catalog servers to run +- **Public beta** - Available to all R2 subscribers, no extra cost beyond R2 storage + +### What is Apache Iceberg? + +Open table format for analytics datasets in object storage. Features: +- **ACID transactions** - Safe concurrent reads/writes +- **Metadata optimization** - Fast queries without full scans +- **Schema evolution** - Add/rename/delete columns without rewrites +- **Time-travel** - Query historical snapshots +- **Partitioning** - Organize data for efficient queries + +## When to Use + +**Use R2 Data Catalog for:** +- **Log analytics** - Store and query application/system logs +- **Data lakes/warehouses** - Analytical datasets queried by multiple engines +- **BI pipelines** - Aggregate data for dashboards and reports +- **Multi-cloud analytics** - Share data across clouds without egress fees +- **Time-series data** - Event streams, metrics, sensor data + +**Don't use for:** +- **Transactional workloads** - Use D1 or external database instead +- **Sub-second latency** - Iceberg optimized for batch/analytical queries +- **Small datasets (<1GB)** - Setup overhead not worth it +- **Unstructured data** - Store files directly in R2, not as Iceberg tables + +## Architecture + +``` +┌─────────────────────────────────────────────────┐ +│ Query Engines │ +│ (PyIceberg, Spark, Trino, Snowflake, DuckDB) │ +└────────────────┬────────────────────────────────┘ + │ + │ REST API (OAuth2 token) + ▼ +┌─────────────────────────────────────────────────┐ +│ R2 Data Catalog (Managed Iceberg REST Catalog)│ +│ • Namespace/table metadata │ +│ • Transaction coordination │ +│ • Snapshot management │ +└────────────────┬────────────────────────────────┘ + │ + │ Vended credentials + ▼ +┌─────────────────────────────────────────────────┐ +│ R2 Bucket Storage │ +│ • Parquet data files │ +│ • Metadata files │ +│ • Manifest files │ +└─────────────────────────────────────────────────┘ +``` + +**Key concepts:** +- **Catalog URI** - REST endpoint for catalog operations (e.g., `https://.r2.cloudflarestorage.com/iceberg/`) +- **Warehouse** - Logical grouping of tables (typically same as bucket name) +- **Namespace** - Schema/database containing tables (e.g., `logs`, `analytics`) +- **Table** - Iceberg table with schema, data files, snapshots +- **Vended credentials** - Temporary S3 credentials catalog provides for data access + +## Limits + +| Resource | Limit | Notes | +|----------|-------|-------| +| Namespaces per catalog | No hard limit | Organize tables logically | +| Tables per namespace | <10,000 recommended | Performance degrades beyond this | +| Files per table | <100,000 recommended | Run compaction regularly | +| Snapshots per table | Configurable retention | Expire >7 days old | +| Partitions per table | 100-1,000 optimal | Too many = slow metadata ops | +| Table size | Same as R2 bucket | 10GB-10TB+ common | +| API rate limits | Standard R2 API limits | Shared with R2 storage operations | +| Target file size | 128-512 MB | After compaction | + +## Current Status + +**Public Beta** (as of Jan 2026) +- Available to all R2 subscribers +- No extra cost beyond standard R2 storage/operations +- Production-ready, but breaking changes possible +- Supports: namespaces, tables, snapshots, compaction, time-travel, table maintenance + +## Decision Tree: Is R2 Data Catalog Right For You? + +``` +Start → Need analytics on object storage data? + │ + ├─ No → Use R2 directly for object storage + │ + └─ Yes → Dataset >1GB with structured schema? + │ + ├─ No → Too small, use R2 + ad-hoc queries + │ + └─ Yes → Need ACID transactions or schema evolution? + │ + ├─ No → Consider simpler solutions (Parquet on R2) + │ + └─ Yes → Need multi-cloud/multi-tool access? + │ + ├─ No → D1 or external DB may be simpler + │ + └─ Yes → ✅ Use R2 Data Catalog +``` + +**Quick check:** If you answer "yes" to all: +- Dataset >1GB and growing +- Structured/tabular data (logs, events, metrics) +- Multiple query tools or cloud environments +- Need versioning, schema changes, or concurrent access + +→ R2 Data Catalog is a good fit. + +## In This Reference + +- **[configuration.md](configuration.md)** - Enable catalog, create API tokens, connect clients +- **[api.md](api.md)** - REST endpoints, operations, maintenance +- **[patterns.md](patterns.md)** - PyIceberg examples, common use cases +- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations + +## See Also + +- [Cloudflare R2 Data Catalog Docs](https://developers.cloudflare.com/r2/data-catalog/) +- [Apache Iceberg Docs](https://iceberg.apache.org/) +- [PyIceberg Docs](https://py.iceberg.apache.org/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/api.md new file mode 100644 index 0000000000000000000000000000000000000000..3d57d4fc9d4fe0fcbce3bbcedf23a94662ad940d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/api.md @@ -0,0 +1,199 @@ +# API Reference + +R2 Data Catalog exposes standard [Apache Iceberg REST Catalog API](https://github.com/apache/iceberg/blob/main/open-api/rest-catalog-open-api.yaml). + +## Quick Reference + +**Most common operations:** + +| Task | PyIceberg Code | +|------|----------------| +| Connect | `RestCatalog(name="r2", warehouse=bucket, uri=uri, token=token)` | +| List namespaces | `catalog.list_namespaces()` | +| Create namespace | `catalog.create_namespace("logs")` | +| Create table | `catalog.create_table(("ns", "table"), schema=schema)` | +| Load table | `catalog.load_table(("ns", "table"))` | +| Append data | `table.append(pyarrow_table)` | +| Query data | `table.scan().to_pandas()` | +| Compact files | `table.rewrite_data_files(target_file_size_bytes=128*1024*1024)` | +| Expire snapshots | `table.expire_snapshots(older_than=timestamp_ms, retain_last=10)` | + +## REST Endpoints + +Base: `https://.r2.cloudflarestorage.com/iceberg/` + +| Operation | Method | Path | +|-----------|--------|------| +| Catalog config | GET | `/v1/config` | +| List namespaces | GET | `/v1/namespaces` | +| Create namespace | POST | `/v1/namespaces` | +| Delete namespace | DELETE | `/v1/namespaces/{ns}` | +| List tables | GET | `/v1/namespaces/{ns}/tables` | +| Create table | POST | `/v1/namespaces/{ns}/tables` | +| Load table | GET | `/v1/namespaces/{ns}/tables/{table}` | +| Update table | POST | `/v1/namespaces/{ns}/tables/{table}` | +| Delete table | DELETE | `/v1/namespaces/{ns}/tables/{table}` | +| Rename table | POST | `/v1/tables/rename` | + +**Authentication:** Bearer token in header: `Authorization: Bearer ` + +## PyIceberg Client API + +Most users use PyIceberg, not raw REST. + +### Connection + +```python +from pyiceberg.catalog.rest import RestCatalog + +catalog = RestCatalog( + name="my_catalog", + warehouse="", + uri="", + token="", +) +``` + +### Namespace Operations + +```python +from pyiceberg.exceptions import NamespaceAlreadyExistsError + +namespaces = catalog.list_namespaces() # [('default',), ('logs',)] +catalog.create_namespace("logs", properties={"owner": "team"}) +catalog.drop_namespace("logs") # Must be empty +``` + +### Table Operations + +```python +from pyiceberg.schema import Schema +from pyiceberg.types import NestedField, StringType, IntegerType + +schema = Schema( + NestedField(1, "id", IntegerType(), required=True), + NestedField(2, "name", StringType(), required=False), +) +table = catalog.create_table(("logs", "app_logs"), schema=schema) +tables = catalog.list_tables("logs") +table = catalog.load_table(("logs", "app_logs")) +catalog.rename_table(("logs", "old"), ("logs", "new")) +``` + +### Data Operations + +```python +import pyarrow as pa + +data = pa.table({"id": [1, 2], "name": ["Alice", "Bob"]}) +table.append(data) +table.overwrite(data) + +# Read with filters +scan = table.scan(row_filter="id > 100", selected_fields=["id", "name"]) +df = scan.to_pandas() +``` + +### Schema Evolution + +```python +from pyiceberg.types import IntegerType, LongType + +with table.update_schema() as update: + update.add_column("user_id", IntegerType(), doc="User ID") + update.rename_column("msg", "message") + update.delete_column("old_field") + update.update_column("id", field_type=LongType()) # int→long only +``` + +### Time-Travel + +```python +from datetime import datetime, timedelta + +# Query specific snapshot or timestamp +scan = table.scan(snapshot_id=table.snapshots()[-2].snapshot_id) +yesterday_ms = int((datetime.now() - timedelta(days=1)).timestamp() * 1000) +scan = table.scan(as_of_timestamp=yesterday_ms) +``` + +### Partitioning + +```python +from pyiceberg.partitioning import PartitionSpec, PartitionField +from pyiceberg.transforms import DayTransform +from pyiceberg.types import TimestampType + +partition_spec = PartitionSpec( + PartitionField(source_id=1, field_id=1000, transform=DayTransform(), name="day") +) +table = catalog.create_table(("events", "actions"), schema=schema, partition_spec=partition_spec) +scan = table.scan(row_filter="day = '2026-01-27'") # Prunes partitions +``` + +## Table Maintenance + +### Compaction + +```python +files = table.scan().plan_files() +avg_mb = sum(f.file_size_in_bytes for f in files) / len(files) / (1024**2) +print(f"Files: {len(files)}, Avg: {avg_mb:.1f} MB") + +table.rewrite_data_files(target_file_size_bytes=128 * 1024 * 1024) +``` + +**When:** Avg <10MB or >1000 files. **Frequency:** High-write daily, medium weekly. + +### Snapshot Expiration + +```python +from datetime import datetime, timedelta + +seven_days_ms = int((datetime.now() - timedelta(days=7)).timestamp() * 1000) +table.expire_snapshots(older_than=seven_days_ms, retain_last=10) +``` + +**Retention:** Production 7-30d, dev 1-7d, audit 90+d. + +### Orphan Cleanup + +```python +three_days_ms = int((datetime.now() - timedelta(days=3)).timestamp() * 1000) +table.delete_orphan_files(older_than=three_days_ms) +``` + +⚠️ Always expire snapshots first, use 3+ day threshold, run during low traffic. + +### Full Maintenance + +```python +# Compact → Expire → Cleanup (in order) +if len(table.scan().plan_files()) > 1000: + table.rewrite_data_files(target_file_size_bytes=128 * 1024 * 1024) +seven_days_ms = int((datetime.now() - timedelta(days=7)).timestamp() * 1000) +table.expire_snapshots(older_than=seven_days_ms, retain_last=10) +three_days_ms = int((datetime.now() - timedelta(days=3)).timestamp() * 1000) +table.delete_orphan_files(older_than=three_days_ms) +``` + +## Metadata Inspection + +```python +table = catalog.load_table(("logs", "app_logs")) +print(table.schema()) +print(table.current_snapshot()) +print(table.properties) +print(f"Files: {len(table.scan().plan_files())}") +``` + +## Error Codes + +| Code | Meaning | Common Causes | +|------|---------|---------------| +| 401 | Unauthorized | Invalid/missing token | +| 404 | Not Found | Catalog not enabled, namespace/table missing | +| 409 | Conflict | Already exists, concurrent update | +| 422 | Validation | Invalid schema, incompatible type | + +See [gotchas.md](gotchas.md) for detailed troubleshooting. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..15915daa7d0df7bf2d189f7cf4b74ef6b922c531 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/configuration.md @@ -0,0 +1,198 @@ +# Configuration + +How to enable R2 Data Catalog and configure authentication. + +## Prerequisites + +- Cloudflare account with [R2 subscription](https://developers.cloudflare.com/r2/pricing/) +- R2 bucket created +- Access to Cloudflare dashboard or Wrangler CLI + +## Enable Catalog on Bucket + +Choose one method: + +### Via Wrangler (Recommended) + +```bash +npx wrangler r2 bucket catalog enable +``` + +**Output:** +``` +✅ Data Catalog enabled for bucket 'my-bucket' + Catalog URI: https://.r2.cloudflarestorage.com/iceberg/my-bucket + Warehouse: my-bucket +``` + +### Via Dashboard + +1. Navigate to **R2** → Select your bucket → **Settings** tab +2. Scroll to "R2 Data Catalog" section → Click **Enable** +3. Note the **Catalog URI** and **Warehouse name** shown + +**Result:** +- Catalog URI: `https://.r2.cloudflarestorage.com/iceberg/` +- Warehouse: `` (same as bucket name) + +### Via API (Programmatic) + +```bash +curl -X POST \ + "https://api.cloudflare.com/client/v4/accounts//r2/buckets//catalog" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" +``` + +**Response:** +```json +{ + "result": { + "catalog_uri": "https://.r2.cloudflarestorage.com/iceberg/", + "warehouse": "" + }, + "success": true +} +``` + +## Check Catalog Status + +```bash +npx wrangler r2 bucket catalog status +``` + +**Output:** +``` +Catalog Status: enabled +Catalog URI: https://.r2.cloudflarestorage.com/iceberg/my-bucket +Warehouse: my-bucket +``` + +## Disable Catalog (If Needed) + +```bash +npx wrangler r2 bucket catalog disable +``` + +⚠️ **Warning:** Disabling does NOT delete tables/data. Files remain in bucket. Metadata becomes inaccessible until re-enabled. + +## API Token Creation + +R2 Data Catalog requires API token with **both** R2 Storage + R2 Data Catalog permissions. + +### Dashboard Method (Recommended) + +1. Go to **R2** → **Manage R2 API Tokens** → **Create API Token** +2. Select permission level: + - **Admin Read & Write** - Full catalog + storage access (read/write) + - **Admin Read only** - Read-only access (for query engines) +3. Copy token value immediately (shown only once) + +**Permission groups included:** +- `Workers R2 Data Catalog Write` (or Read) +- `Workers R2 Storage Bucket Item Write` (or Read) + +### API Method (Programmatic) + +Use Cloudflare API to create tokens programmatically. Required permissions: +- `Workers R2 Data Catalog Write` (or Read) +- `Workers R2 Storage Bucket Item Write` (or Read) + +## Client Configuration + +### PyIceberg + +```python +from pyiceberg.catalog.rest import RestCatalog + +catalog = RestCatalog( + name="my_catalog", + warehouse="", # Same as bucket name + uri="", # From enable command + token="", # From token creation +) +``` + +**Full example with credentials:** +```python +import os +from pyiceberg.catalog.rest import RestCatalog + +# Store credentials in environment variables +WAREHOUSE = os.getenv("R2_WAREHOUSE") # e.g., "my-bucket" +CATALOG_URI = os.getenv("R2_CATALOG_URI") # e.g., "https://abc123.r2.cloudflarestorage.com/iceberg/my-bucket" +TOKEN = os.getenv("R2_TOKEN") # API token + +catalog = RestCatalog( + name="r2_catalog", + warehouse=WAREHOUSE, + uri=CATALOG_URI, + token=TOKEN, +) + +# Test connection +print(catalog.list_namespaces()) +``` + +### Spark / Trino / DuckDB + +See [patterns.md](patterns.md) for integration examples with other query engines. + +## Connection String Format + +For quick reference: + +``` +Catalog URI: https://.r2.cloudflarestorage.com/iceberg/ +Warehouse: +Token: +``` + +**Where to find values:** + +| Value | Source | +|-------|--------| +| `` | Dashboard URL or `wrangler whoami` | +| `` | R2 bucket name | +| Catalog URI | Output from `wrangler r2 bucket catalog enable` | +| Token | R2 API Token creation page | + +## Security Best Practices + +1. **Store tokens securely** - Use environment variables or secret managers, never hardcode +2. **Use least privilege** - Read-only tokens for query engines, write tokens only where needed +3. **Rotate tokens regularly** - Create new tokens, test, then revoke old ones +4. **One token per application** - Easier to track and revoke if compromised +5. **Monitor token usage** - Check R2 analytics for unexpected patterns +6. **Bucket-scoped tokens** - Create tokens per bucket, not account-wide + +## Environment Variables Pattern + +```bash +# .env (never commit) +R2_CATALOG_URI=https://.r2.cloudflarestorage.com/iceberg/ +R2_WAREHOUSE= +R2_TOKEN= +``` + +```python +import os +from pyiceberg.catalog.rest import RestCatalog + +catalog = RestCatalog( + name="r2", + uri=os.getenv("R2_CATALOG_URI"), + warehouse=os.getenv("R2_WAREHOUSE"), + token=os.getenv("R2_TOKEN"), +) +``` + +## Troubleshooting + +| Problem | Solution | +|---------|----------| +| 404 "catalog not found" | Run `wrangler r2 bucket catalog enable ` | +| 401 "unauthorized" | Check token has both Catalog + Storage permissions | +| 403 on data files | Token needs both permission groups | + +See [gotchas.md](gotchas.md) for detailed troubleshooting. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..4dd61647375e49feaf41dbf67891c1a5025bd651 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/gotchas.md @@ -0,0 +1,170 @@ +# Gotchas & Troubleshooting + +Common problems → causes → solutions. + +## Permission Errors + +### 401 Unauthorized + +**Error:** `"401 Unauthorized"` +**Cause:** Token missing R2 Data Catalog permissions. +**Solution:** Use "Admin Read & Write" token (includes catalog + storage permissions). Test with `catalog.list_namespaces()`. + +### 403 Forbidden + +**Error:** `"403 Forbidden"` on data files +**Cause:** Token lacks storage permissions. +**Solution:** Token needs both R2 Data Catalog + R2 Storage Bucket Item permissions. + +### Token Rotation Issues + +**Error:** New token fails after rotation. +**Solution:** Create new token → test in staging → update prod → monitor 24h → revoke old. + +## Catalog URI Issues + +### 404 Not Found + +**Error:** `"404 Catalog not found"` +**Cause:** Catalog not enabled or wrong URI. +**Solution:** Run `wrangler r2 bucket catalog enable `. URI must be HTTPS with `/iceberg/` and case-sensitive bucket name. + +### Wrong Warehouse + +**Error:** Cannot create/load tables. +**Cause:** Warehouse ≠ bucket name. +**Solution:** Set `warehouse="bucket-name"` to match bucket exactly. + +## Table and Schema Issues + +### Table/Namespace Already Exists + +**Error:** `"TableAlreadyExistsError"` +**Solution:** Use try/except to load existing or check first. + +### Namespace Not Found + +**Error:** Cannot create table. +**Solution:** Create namespace first: `catalog.create_namespace("ns")` + +### Schema Evolution Errors + +**Error:** `"422 Validation"` on schema update. +**Cause:** Incompatible change (required field, type shrink). +**Solution:** Only add nullable columns, compatible type widening (int→long, float→double). + +## Data and Query Issues + +### Empty Scan Results + +**Error:** Scan returns no data. +**Cause:** Incorrect filter or partition column. +**Solution:** Test without filter first: `table.scan().to_pandas()`. Verify partition column names. + +### Slow Queries + +**Error:** Performance degrades over time. +**Cause:** Too many small files. +**Solution:** Check file count, compact if >1000 or avg <10MB. See [api.md](api.md#compaction). + +### Type Mismatch + +**Error:** `"Cannot cast"` on append. +**Cause:** PyArrow types don't match Iceberg schema. +**Solution:** Cast to int64 (Iceberg default), not int32. Check `table.schema()`. + +## Compaction Issues + +### Compaction Issues + +**Problem:** File count unchanged or compaction takes hours. +**Cause:** Target size too large, or table too big for PyIceberg. +**Solution:** Only compact if avg <50MB. For >1TB tables, use Spark. Run during low-traffic periods. + +## Maintenance Issues + +### Snapshot/Orphan Issues + +**Problem:** Expiration fails or orphan cleanup deletes active data. +**Cause:** Too aggressive retention or wrong order. +**Solution:** Always expire snapshots first with `retain_last=10`, then cleanup orphans with 3+ day threshold. + +## Concurrency Issues + +### Concurrent Write Conflicts + +**Problem:** `CommitFailedException` with multiple writers. +**Cause:** Optimistic locking - simultaneous commits. +**Solution:** Add retry with exponential backoff (see [patterns.md](patterns.md#pattern-6-concurrent-writes-with-retry)). + +### Stale Metadata + +**Problem:** Old schema/data after external update. +**Cause:** Cached metadata. +**Solution:** Reload table: `table = catalog.load_table(("ns", "table"))` + +## Performance Optimization + +### Performance Tips + +**Scans:** Use `row_filter` and `selected_fields` to reduce data scanned. +**Partitions:** 100-1000 optimal. Avoid high cardinality (millions) or low (<10). +**Files:** Keep 100-500MB avg. Compact if <10MB or >10k files. + +## Limits + +| Resource | Recommended | Impact if Exceeded | +|----------|-------------|-------------------| +| Tables/namespace | <10k | Slow list ops | +| Files/table | <100k | Slow query planning | +| Partitions/table | 100-1k | Metadata overhead | +| Snapshots/table | Expire >7d | Metadata bloat | + +## Common Error Messages Reference + +| Error Message | Likely Cause | Fix | +|---------------|--------------|-----| +| `401 Unauthorized` | Missing/invalid token | Check token has catalog+storage permissions | +| `403 Forbidden` | Token lacks storage permissions | Add R2 Storage Bucket Item permission | +| `404 Not Found` | Catalog not enabled or wrong URI | Run `wrangler r2 bucket catalog enable` | +| `409 Conflict` | Table/namespace already exists | Use try/except or load existing | +| `422 Unprocessable Entity` | Schema validation failed | Check type compatibility, required fields | +| `CommitFailedException` | Concurrent write conflict | Add retry logic with backoff | +| `NamespaceAlreadyExistsError` | Namespace exists | Use try/except or load existing | +| `NoSuchTableError` | Table doesn't exist | Check namespace+table name, create first | +| `TypeError: Cannot cast` | PyArrow type mismatch | Cast data to match Iceberg schema | + +## Debugging Checklist + +When things go wrong, check in order: + +1. ✅ **Catalog enabled:** `npx wrangler r2 bucket catalog status ` +2. ✅ **Token permissions:** Both R2 Data Catalog + R2 Storage in dashboard +3. ✅ **Connection test:** `catalog.list_namespaces()` succeeds +4. ✅ **URI format:** HTTPS, includes `/iceberg/`, correct bucket name +5. ✅ **Warehouse name:** Matches bucket name exactly +6. ✅ **Namespace exists:** Create before `create_table()` +7. ✅ **Enable debug logging:** `logging.basicConfig(level=logging.DEBUG)` +8. ✅ **PyIceberg version:** `pip install --upgrade pyiceberg` (≥0.5.0) +9. ✅ **File health:** Compact if >1000 files or avg <10MB +10. ✅ **Snapshot count:** Expire if >100 snapshots + +## Enable Debug Logging + +```python +import logging +logging.basicConfig(level=logging.DEBUG) +# Now operations show HTTP requests/responses +``` + +## Resources + +- [Cloudflare Community](https://community.cloudflare.com/c/developers/workers/40) +- [Cloudflare Discord](https://discord.cloudflare.com) - #r2 channel +- [PyIceberg GitHub](https://github.com/apache/iceberg-python/issues) +- [Apache Iceberg Slack](https://iceberg.apache.org/community/) + +## Next Steps + +- [patterns.md](patterns.md) - Working examples +- [api.md](api.md) - API reference diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..b6b181f7944b516d4234ba03d5162c904fff73f3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2-data-catalog/patterns.md @@ -0,0 +1,191 @@ +# Common Patterns + +Practical patterns for R2 Data Catalog with PyIceberg. + +## PyIceberg Connection + +```python +import os +from pyiceberg.catalog.rest import RestCatalog +from pyiceberg.exceptions import NamespaceAlreadyExistsError + +catalog = RestCatalog( + name="r2_catalog", + warehouse=os.getenv("R2_WAREHOUSE"), # bucket name + uri=os.getenv("R2_CATALOG_URI"), # catalog endpoint + token=os.getenv("R2_TOKEN"), # API token +) + +# Create namespace (idempotent) +try: + catalog.create_namespace("default") +except NamespaceAlreadyExistsError: + pass +``` + +## Pattern 1: Log Analytics Pipeline + +Ingest logs incrementally, query by time/level. + +```python +import pyarrow as pa +from datetime import datetime +from pyiceberg.schema import Schema +from pyiceberg.types import NestedField, TimestampType, StringType, IntegerType +from pyiceberg.partitioning import PartitionSpec, PartitionField +from pyiceberg.transforms import DayTransform + +# Create partitioned table (once) +schema = Schema( + NestedField(1, "timestamp", TimestampType(), required=True), + NestedField(2, "level", StringType(), required=True), + NestedField(3, "service", StringType(), required=True), + NestedField(4, "message", StringType(), required=False), +) + +partition_spec = PartitionSpec( + PartitionField(source_id=1, field_id=1000, transform=DayTransform(), name="day") +) + +catalog.create_namespace("logs") +table = catalog.create_table(("logs", "app_logs"), schema=schema, partition_spec=partition_spec) + +# Append logs (incremental) +data = pa.table({ + "timestamp": [datetime(2026, 1, 27, 10, 30, 0)], + "level": ["ERROR"], + "service": ["auth-service"], + "message": ["Failed login"], +}) +table.append(data) + +# Query by time + level (leverages partitioning) +scan = table.scan(row_filter="level = 'ERROR' AND day = '2026-01-27'") +errors = scan.to_pandas() +``` + +## Pattern 2: Time-Travel Queries + +```python +from datetime import datetime, timedelta + +table = catalog.load_table(("logs", "app_logs")) + +# Query specific snapshot +snapshot_id = table.current_snapshot().snapshot_id +data = table.scan(snapshot_id=snapshot_id).to_pandas() + +# Query as of timestamp (yesterday) +yesterday_ms = int((datetime.now() - timedelta(days=1)).timestamp() * 1000) +data = table.scan(as_of_timestamp=yesterday_ms).to_pandas() +``` + +## Pattern 3: Schema Evolution + +```python +from pyiceberg.types import StringType + +table = catalog.load_table(("users", "profiles")) + +with table.update_schema() as update: + update.add_column("email", StringType(), required=False) + update.rename_column("name", "full_name") +# Old readers ignore new columns, new readers see nulls for old data +``` + +## Pattern 4: Partitioned Tables + +```python +from pyiceberg.partitioning import PartitionSpec, PartitionField +from pyiceberg.transforms import DayTransform, IdentityTransform + +# Partition by day + country +partition_spec = PartitionSpec( + PartitionField(source_id=1, field_id=1000, transform=DayTransform(), name="day"), + PartitionField(source_id=2, field_id=1001, transform=IdentityTransform(), name="country"), +) +table = catalog.create_table(("events", "user_events"), schema=schema, partition_spec=partition_spec) + +# Queries prune partitions automatically +scan = table.scan(row_filter="country = 'US' AND day = '2026-01-27'") +``` + +## Pattern 5: Table Maintenance + +```python +from datetime import datetime, timedelta + +table = catalog.load_table(("logs", "app_logs")) + +# Compact → expire → cleanup (in order) +table.rewrite_data_files(target_file_size_bytes=128 * 1024 * 1024) +seven_days_ms = int((datetime.now() - timedelta(days=7)).timestamp() * 1000) +table.expire_snapshots(older_than=seven_days_ms, retain_last=10) +three_days_ms = int((datetime.now() - timedelta(days=3)).timestamp() * 1000) +table.delete_orphan_files(older_than=three_days_ms) +``` + +See [api.md](api.md#table-maintenance) for detailed parameters. + +## Pattern 6: Concurrent Writes with Retry + +```python +from pyiceberg.exceptions import CommitFailedException +import time + +def append_with_retry(table, data, max_retries=3): + for attempt in range(max_retries): + try: + table.append(data) + return + except CommitFailedException: + if attempt == max_retries - 1: + raise + time.sleep(2 ** attempt) +``` + +## Pattern 7: Upsert Simulation + +```python +import pandas as pd +import pyarrow as pa + +# Read → merge → overwrite (not atomic, use Spark MERGE INTO for production) +existing = table.scan().to_pandas() +new_data = pd.DataFrame({"id": [1, 3], "value": [100, 300]}) +merged = pd.concat([existing, new_data]).drop_duplicates(subset=["id"], keep="last") +table.overwrite(pa.Table.from_pandas(merged)) +``` + +## Pattern 8: DuckDB Integration + +```python +import duckdb + +arrow_table = table.scan().to_arrow() +con = duckdb.connect() +con.register("logs", arrow_table) +result = con.execute("SELECT level, COUNT(*) FROM logs GROUP BY level").fetchdf() +``` + +## Pattern 9: Monitor Table Health + +```python +files = table.scan().plan_files() +avg_mb = sum(f.file_size_in_bytes for f in files) / len(files) / (1024**2) +print(f"Files: {len(files)}, Avg: {avg_mb:.1f}MB, Snapshots: {len(table.snapshots())}") + +if avg_mb < 10 or len(files) > 1000: + print("⚠️ Needs compaction") +``` + +## Best Practices + +| Area | Guideline | +|------|-----------| +| **Partitioning** | Use day/hour for time-series; 100-1000 partitions; avoid high cardinality | +| **File sizes** | Target 128-512MB; compact when avg <10MB or >10k files | +| **Schema** | Add columns as nullable (`required=False`); batch changes | +| **Maintenance** | Compact high-write daily/weekly; expire snapshots 7-30d; cleanup orphans after | +| **Concurrency** | Reads automatic; writes to different partitions safe; retry same partition | +| **Performance** | Filter on partitions; select only needed columns; batch appends 100MB+ | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..846514a8623e40f1e964ef7c3519cd04f0a5daea --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/README.md @@ -0,0 +1,95 @@ +# Cloudflare R2 Object Storage + +S3-compatible object storage with zero egress fees, optimized for large file storage and delivery. + +## Overview + +R2 provides: +- S3-compatible API (Workers API + S3 REST) +- Zero egress fees globally +- Strong consistency for writes/deletes +- Storage classes (Standard/Infrequent Access) +- SSE-C encryption support + +**Use cases:** Media storage, backups, static assets, user uploads, data lakes + +## Quick Start + +```bash +wrangler r2 bucket create my-bucket --location=enam +wrangler r2 object put my-bucket/file.txt --file=./local.txt +``` + +```typescript +// Upload +await env.MY_BUCKET.put(key, data, { + httpMetadata: { contentType: 'image/jpeg' } +}); + +// Download +const object = await env.MY_BUCKET.get(key); +if (object) return new Response(object.body); +``` + +## Core Operations + +| Method | Purpose | Returns | +|--------|---------|---------| +| `put(key, value, options?)` | Upload object | `R2Object \| null` | +| `get(key, options?)` | Download object | `R2ObjectBody \| R2Object \| null` | +| `head(key)` | Get metadata only | `R2Object \| null` | +| `delete(keys)` | Delete object(s) | `Promise` | +| `list(options?)` | List objects | `R2Objects` | + +## Storage Classes + +- **Standard**: Frequent access, low latency reads +- **InfrequentAccess**: 30-day minimum storage, retrieval fees, lower storage cost + +## Event Notifications + +R2 integrates with Cloudflare Queues for reactive workflows: + +```typescript +// wrangler.jsonc +{ + "event_notifications": [{ + "queue": "r2-notifications", + "actions": ["PutObject", "DeleteObject"] + }] +} + +// Consumer +async queue(batch: MessageBatch, env: Env) { + for (const message of batch.messages) { + const event = message.body; // { action, bucket, object, timestamps } + if (event.action === 'PutObject') { + // Process upload: thumbnail generation, virus scan, etc. + } + } +} +``` + +## Reading Order + +**First-time users:** README → configuration.md → api.md → patterns.md +**Specific tasks:** +- Setup: configuration.md +- Client uploads: patterns.md (presigned URLs) +- Public static site: patterns.md (public access + custom domain) +- Processing uploads: README (event notifications) + queues reference +- Debugging: gotchas.md + +## In This Reference + +- [configuration.md](./configuration.md) - Bindings, S3 SDK, CORS, lifecycles, token scopes +- [api.md](./api.md) - Workers API, multipart, conditional requests, presigned URLs +- [patterns.md](./patterns.md) - Streaming, caching, client uploads, public buckets +- [gotchas.md](./gotchas.md) - List truncation, etag format, stream length, S3 SDK region + +## See Also + +- [workers](../workers/) - Worker runtime and fetch handlers +- [kv](../kv/) - Metadata storage for R2 objects +- [d1](../d1/) - Store R2 URLs in relational database +- [queues](../queues/) - Process R2 uploads asynchronously diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/api.md new file mode 100644 index 0000000000000000000000000000000000000000..9a8cd28e4ec8ec52ba1885b1a648cde93e1bc72c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/api.md @@ -0,0 +1,200 @@ +# R2 API Reference + +## PUT (Upload) + +```typescript +// Basic +await env.MY_BUCKET.put(key, value); + +// With metadata +await env.MY_BUCKET.put(key, value, { + httpMetadata: { + contentType: 'image/jpeg', + contentDisposition: 'attachment; filename="photo.jpg"', + cacheControl: 'max-age=3600' + }, + customMetadata: { userId: '123', version: '2' }, + storageClass: 'Standard', // or 'InfrequentAccess' + sha256: arrayBufferOrHex, // Integrity check + ssecKey: arrayBuffer32bytes // SSE-C encryption +}); + +// Value types: ReadableStream | ArrayBuffer | string | Blob +``` + +## GET (Download) + +```typescript +const object = await env.MY_BUCKET.get(key); +if (!object) return new Response('Not found', { status: 404 }); + +// Body: arrayBuffer(), text(), json(), blob(), body (ReadableStream) + +// Ranged reads +const object = await env.MY_BUCKET.get(key, { range: { offset: 0, length: 1024 } }); + +// Conditional GET +const object = await env.MY_BUCKET.get(key, { onlyIf: { etagMatches: '"abc123"' } }); +``` + +## HEAD (Metadata Only) + +```typescript +const object = await env.MY_BUCKET.head(key); // Returns R2Object without body +``` + +## DELETE + +```typescript +await env.MY_BUCKET.delete(key); +await env.MY_BUCKET.delete([key1, key2, key3]); // Batch (max 1000) +``` +## LIST + +```typescript +const listed = await env.MY_BUCKET.list({ + limit: 1000, + prefix: 'photos/', + cursor: cursorFromPrevious, + delimiter: '/', + include: ['httpMetadata', 'customMetadata'] +}); + +// Pagination (always use truncated flag) +while (listed.truncated) { + const next = await env.MY_BUCKET.list({ cursor: listed.cursor }); + listed.objects.push(...next.objects); + listed.truncated = next.truncated; + listed.cursor = next.cursor; +} +``` + +## Multipart Uploads + +```typescript +const multipart = await env.MY_BUCKET.createMultipartUpload(key, { + httpMetadata: { contentType: 'video/mp4' } +}); + +const uploadedParts: R2UploadedPart[] = []; +for (let i = 0; i < partCount; i++) { + const part = await multipart.uploadPart(i + 1, partData); + uploadedParts.push(part); +} + +const object = await multipart.complete(uploadedParts); +// OR: await multipart.abort(); + +// Resume +const multipart = env.MY_BUCKET.resumeMultipartUpload(key, uploadId); +``` + +## Presigned URLs (S3 SDK) + +```typescript +import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; + +const s3 = new S3Client({ + region: 'auto', + endpoint: `https://${accountId}.r2.cloudflarestorage.com`, + credentials: { accessKeyId: env.R2_ACCESS_KEY_ID, secretAccessKey: env.R2_SECRET_ACCESS_KEY } +}); + +const uploadUrl = await getSignedUrl(s3, new PutObjectCommand({ Bucket: 'my-bucket', Key: key }), { expiresIn: 3600 }); +return Response.json({ uploadUrl }); +``` + +## TypeScript Interfaces + +```typescript +interface R2Bucket { + head(key: string): Promise; + get(key: string, options?: R2GetOptions): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | string | Blob, options?: R2PutOptions): Promise; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; +} + +interface R2Object { + key: string; version: string; size: number; + etag: string; httpEtag: string; // httpEtag is quoted, use for headers + uploaded: Date; httpMetadata?: R2HTTPMetadata; + customMetadata?: Record; + storageClass: 'Standard' | 'InfrequentAccess'; + checksums: R2Checksums; + writeHttpMetadata(headers: Headers): void; +} + +interface R2ObjectBody extends R2Object { + body: ReadableStream; bodyUsed: boolean; + arrayBuffer(): Promise; text(): Promise; + json(): Promise; blob(): Promise; +} + +interface R2HTTPMetadata { + contentType?: string; contentDisposition?: string; + contentEncoding?: string; contentLanguage?: string; + cacheControl?: string; cacheExpiry?: Date; +} + +interface R2PutOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + sha256?: ArrayBuffer | string; // Only ONE checksum allowed + storageClass?: 'Standard' | 'InfrequentAccess'; + ssecKey?: ArrayBuffer; +} + +interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; + ssecKey?: ArrayBuffer; +} + +interface R2ListOptions { + limit?: number; prefix?: string; cursor?: string; delimiter?: string; + startAfter?: string; include?: ('httpMetadata' | 'customMetadata')[]; +} + +interface R2Objects { + objects: R2Object[]; truncated: boolean; + cursor?: string; delimitedPrefixes: string[]; +} + +interface R2Conditional { + etagMatches?: string; etagDoesNotMatch?: string; + uploadedBefore?: Date; uploadedAfter?: Date; +} + +interface R2Range { offset?: number; length?: number; suffix?: number; } + +interface R2Checksums { + md5?: ArrayBuffer; sha1?: ArrayBuffer; sha256?: ArrayBuffer; + sha384?: ArrayBuffer; sha512?: ArrayBuffer; +} + +interface R2MultipartUpload { + key: string; + uploadId: string; + uploadPart(partNumber: number, value: ReadableStream | ArrayBuffer | string | Blob): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} + +interface R2UploadedPart { + partNumber: number; + etag: string; +} +``` + +## CLI Operations + +```bash +wrangler r2 object put my-bucket/file.txt --file=./local.txt +wrangler r2 object get my-bucket/file.txt --file=./download.txt +wrangler r2 object delete my-bucket/file.txt +wrangler r2 object list my-bucket --prefix=photos/ +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..f306acdbe5faf74c9d0f3b217ee7e7201c5bcbab --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/configuration.md @@ -0,0 +1,165 @@ +# R2 Configuration + +## Workers Binding + +**wrangler.jsonc:** +```jsonc +{ + "r2_buckets": [ + { + "binding": "MY_BUCKET", + "bucket_name": "my-bucket-name" + } + ] +} +``` + +## TypeScript Types + +```typescript +interface Env { MY_BUCKET: R2Bucket; } + +export default { + async fetch(request: Request, env: Env): Promise { + const object = await env.MY_BUCKET.get('file.txt'); + return new Response(object?.body); + } +} +``` + +## S3 SDK Setup + +```typescript +import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; + +const s3 = new S3Client({ + region: 'auto', + endpoint: `https://${accountId}.r2.cloudflarestorage.com`, + credentials: { + accessKeyId: env.R2_ACCESS_KEY_ID, + secretAccessKey: env.R2_SECRET_ACCESS_KEY + } +}); + +await s3.send(new PutObjectCommand({ + Bucket: 'my-bucket', + Key: 'file.txt', + Body: data, + StorageClass: 'STANDARD' // or 'STANDARD_IA' +})); +``` + +## Location Hints + +```bash +wrangler r2 bucket create my-bucket --location=enam + +# Hints: wnam, enam, weur, eeur, apac, oc +# Jurisdictions (override hint): --jurisdiction=eu (or fedramp) +``` + +## CORS Configuration + +CORS must be configured via S3 SDK or dashboard (not available in Workers API): + +```typescript +import { S3Client, PutBucketCorsCommand } from '@aws-sdk/client-s3'; + +const s3 = new S3Client({ + region: 'auto', + endpoint: `https://${accountId}.r2.cloudflarestorage.com`, + credentials: { + accessKeyId: env.R2_ACCESS_KEY_ID, + secretAccessKey: env.R2_SECRET_ACCESS_KEY + } +}); + +await s3.send(new PutBucketCorsCommand({ + Bucket: 'my-bucket', + CORSConfiguration: { + CORSRules: [{ + AllowedOrigins: ['https://example.com'], + AllowedMethods: ['GET', 'PUT', 'HEAD'], + AllowedHeaders: ['*'], + ExposeHeaders: ['ETag'], + MaxAgeSeconds: 3600 + }] + } +})); +``` + +## Object Lifecycles + +```typescript +import { PutBucketLifecycleConfigurationCommand } from '@aws-sdk/client-s3'; + +await s3.send(new PutBucketLifecycleConfigurationCommand({ + Bucket: 'my-bucket', + LifecycleConfiguration: { + Rules: [ + { + ID: 'expire-old-logs', + Status: 'Enabled', + Prefix: 'logs/', + Expiration: { Days: 90 } + }, + { + ID: 'transition-to-ia', + Status: 'Enabled', + Prefix: 'archives/', + Transitions: [{ Days: 30, StorageClass: 'STANDARD_IA' }] + } + ] + } +})); +``` + +## API Token Scopes + +When creating R2 tokens, set minimal permissions: + +| Permission | Use Case | +|------------|----------| +| Object Read | Public serving, downloads | +| Object Write | Uploads only | +| Object Read & Write | Full object operations | +| Admin Read & Write | Bucket management, CORS, lifecycles | + +**Best practice:** Separate tokens for Workers (read/write) vs admin tasks (CORS, lifecycles). + +## Event Notifications + +```jsonc +// wrangler.jsonc +{ + "r2_buckets": [ + { + "binding": "MY_BUCKET", + "bucket_name": "my-bucket", + "event_notifications": [ + { + "queue": "r2-events", + "actions": ["PutObject", "DeleteObject", "CompleteMultipartUpload"] + } + ] + } + ], + "queues": { + "producers": [{ "binding": "R2_EVENTS", "queue": "r2-events" }], + "consumers": [{ "queue": "r2-events", "max_batch_size": 10 }] + } +} +``` + +## Bucket Management + +```bash +wrangler r2 bucket create my-bucket --location=enam --storage-class=Standard +wrangler r2 bucket list +wrangler r2 bucket info my-bucket +wrangler r2 bucket delete my-bucket # Must be empty +wrangler r2 bucket update-storage-class my-bucket --storage-class=InfrequentAccess + +# Public bucket via dashboard +wrangler r2 bucket domain add my-bucket --domain=files.example.com +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..d895f53aafb1315ed720bb927447b1b5ff3f108a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/gotchas.md @@ -0,0 +1,190 @@ +# R2 Gotchas & Troubleshooting + +## List Truncation + +```typescript +// ❌ WRONG: Don't compare object count when using include +while (listed.objects.length < options.limit) { ... } + +// ✅ CORRECT: Always use truncated property +while (listed.truncated) { + const next = await env.MY_BUCKET.list({ cursor: listed.cursor }); + // ... +} +``` + +**Reason:** `include` with metadata may return fewer objects per page to fit metadata. + +## ETag Format + +```typescript +// ❌ WRONG: Using etag (unquoted) in headers +headers.set('etag', object.etag); // Missing quotes + +// ✅ CORRECT: Use httpEtag (quoted) +headers.set('etag', object.httpEtag); +``` + +## Checksum Limits + +Only ONE checksum algorithm allowed per PUT: + +```typescript +// ❌ WRONG: Multiple checksums +await env.MY_BUCKET.put(key, data, { md5: hash1, sha256: hash2 }); // Error + +// ✅ CORRECT: Pick one +await env.MY_BUCKET.put(key, data, { sha256: hash }); +``` + +## Multipart Requirements + +- All parts must be uniform size (except last part) +- Part numbers start at 1 (not 0) +- Uncompleted uploads auto-abort after 7 days +- `resumeMultipartUpload` doesn't validate uploadId existence + +## Conditional Operations + +```typescript +// Precondition failure returns object WITHOUT body +const object = await env.MY_BUCKET.get(key, { + onlyIf: { etagMatches: '"wrong"' } +}); + +// Check for body, not just null +if (!object) return new Response('Not found', { status: 404 }); +if (!object.body) return new Response(null, { status: 304 }); // Precondition failed +``` + +## Key Validation + +```typescript +// ❌ DANGEROUS: Path traversal +const key = url.pathname.slice(1); // Could be ../../../etc/passwd +await env.MY_BUCKET.get(key); + +// ✅ SAFE: Validate keys +if (!key || key.includes('..') || key.startsWith('/')) { + return new Response('Invalid key', { status: 400 }); +} +``` + +## Storage Class Pitfalls + +- InfrequentAccess: 30-day minimum billing (even if deleted early) +- Can't transition IA → Standard via lifecycle (use S3 CopyObject) +- Retrieval fees apply for IA reads + +## Stream Length Requirement + +```typescript +// ❌ WRONG: Streaming unknown length fails silently +const response = await fetch(url); +await env.MY_BUCKET.put(key, response.body); // May fail without error + +// ✅ CORRECT: Buffer or use Content-Length +const data = await response.arrayBuffer(); +await env.MY_BUCKET.put(key, data); + +// OR: Pass Content-Length if known +const object = await env.MY_BUCKET.put(key, request.body, { + httpMetadata: { + contentLength: parseInt(request.headers.get('content-length') || '0') + } +}); +``` + +**Reason:** R2 requires known length for streams. Unknown length may cause silent truncation. + +## S3 SDK Region Configuration + +```typescript +// ❌ WRONG: Missing region breaks ALL S3 SDK calls +const s3 = new S3Client({ + endpoint: `https://${accountId}.r2.cloudflarestorage.com`, + credentials: { ... } +}); + +// ✅ CORRECT: MUST set region='auto' +const s3 = new S3Client({ + region: 'auto', // REQUIRED + endpoint: `https://${accountId}.r2.cloudflarestorage.com`, + credentials: { ... } +}); +``` + +**Reason:** S3 SDK requires region. R2 uses 'auto' as placeholder. + +## Local Development Limits + +```typescript +// ❌ Miniflare/wrangler dev: Limited R2 support +// - No multipart uploads +// - No presigned URLs (requires S3 SDK + network) +// - Memory-backed storage (lost on restart) + +// ✅ Use remote bindings for full features +wrangler dev --remote + +// OR: Conditional logic +if (env.ENVIRONMENT === 'development') { + // Fallback for local dev +} else { + // Full R2 features +} +``` + +## Presigned URL Expiry + +```typescript +// ❌ WRONG: URL expires but no client validation +const url = await getSignedUrl(s3, command, { expiresIn: 60 }); +// 61 seconds later: 403 Forbidden + +// ✅ CORRECT: Return expiry to client +return Response.json({ + uploadUrl: url, + expiresAt: new Date(Date.now() + 60000).toISOString() +}); +``` + +## Limits + +| Limit | Value | +|-------|-------| +| Object size | 5 TB | +| Multipart part count | 10,000 | +| Multipart part min size | 5 MB (except last) | +| Batch delete | 1,000 keys | +| List limit | 1,000 per request | +| Key size | 1024 bytes | +| Custom metadata | 2 KB per object | +| Presigned URL max expiry | 7 days | + +## Common Errors + +### "Stream upload failed" / Silent Truncation + +**Cause:** Stream length unknown or Content-Length missing +**Solution:** Buffer data or pass explicit Content-Length + +### "Invalid credentials" / S3 SDK + +**Cause:** Missing `region: 'auto'` in S3Client config +**Solution:** Always set `region: 'auto'` for R2 + +### "Object not found" + +**Cause:** Object key doesn't exist or was deleted +**Solution:** Verify object key correct, check if object was deleted, ensure bucket correct + +### "List compatibility error" + +**Cause:** Missing or old compatibility_date, or flag not enabled +**Solution:** Set `compatibility_date >= 2022-08-04` or enable `r2_list_honor_include` flag + +### "Multipart upload failed" + +**Cause:** Part sizes not uniform or incorrect part number +**Solution:** Ensure uniform size except final part, verify part numbers start at 1 diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..889d496daf566643ea31cc87ab239f8eab4ce6ee --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/r2/patterns.md @@ -0,0 +1,193 @@ +# R2 Patterns & Best Practices + +## Streaming Large Files + +```typescript +const object = await env.MY_BUCKET.get(key); +if (!object) return new Response('Not found', { status: 404 }); + +const headers = new Headers(); +object.writeHttpMetadata(headers); +headers.set('etag', object.httpEtag); + +return new Response(object.body, { headers }); +``` + +## Conditional GET (304 Not Modified) + +```typescript +const ifNoneMatch = request.headers.get('if-none-match'); +const object = await env.MY_BUCKET.get(key, { + onlyIf: { etagDoesNotMatch: ifNoneMatch?.replace(/"/g, '') || '' } +}); + +if (!object) return new Response('Not found', { status: 404 }); +if (!object.body) return new Response(null, { status: 304, headers: { 'etag': object.httpEtag } }); + +return new Response(object.body, { headers: { 'etag': object.httpEtag } }); +``` + +## Upload with Validation + +```typescript +const key = url.pathname.slice(1); +if (!key || key.includes('..')) return new Response('Invalid key', { status: 400 }); + +const object = await env.MY_BUCKET.put(key, request.body, { + httpMetadata: { contentType: request.headers.get('content-type') || 'application/octet-stream' }, + customMetadata: { uploadedAt: new Date().toISOString(), ip: request.headers.get('cf-connecting-ip') || 'unknown' } +}); + +return Response.json({ key: object.key, size: object.size, etag: object.httpEtag }); +``` + +## Multipart with Progress + +```typescript +const PART_SIZE = 5 * 1024 * 1024; // 5MB +const partCount = Math.ceil(file.size / PART_SIZE); +const multipart = await env.MY_BUCKET.createMultipartUpload(key, { httpMetadata: { contentType: file.type } }); + +const uploadedParts: R2UploadedPart[] = []; +try { + for (let i = 0; i < partCount; i++) { + const start = i * PART_SIZE; + const part = await multipart.uploadPart(i + 1, file.slice(start, start + PART_SIZE)); + uploadedParts.push(part); + onProgress?.(Math.round(((i + 1) / partCount) * 100)); + } + return await multipart.complete(uploadedParts); +} catch (error) { + await multipart.abort(); + throw error; +} +``` + +## Batch Delete + +```typescript +async function deletePrefix(prefix: string, env: Env) { + let cursor: string | undefined; + let truncated = true; + + while (truncated) { + const listed = await env.MY_BUCKET.list({ prefix, limit: 1000, cursor }); + if (listed.objects.length > 0) { + await env.MY_BUCKET.delete(listed.objects.map(o => o.key)); + } + truncated = listed.truncated; + cursor = listed.cursor; + } +} +``` + +## Checksum Validation & Storage Transitions + +```typescript +// Upload with checksum +const hash = await crypto.subtle.digest('SHA-256', data); +await env.MY_BUCKET.put(key, data, { sha256: hash }); + +// Transition storage class (requires S3 SDK) +import { S3Client, CopyObjectCommand } from '@aws-sdk/client-s3'; +await s3.send(new CopyObjectCommand({ + Bucket: 'my-bucket', Key: key, + CopySource: `/my-bucket/${key}`, + StorageClass: 'STANDARD_IA' +})); +``` + +## Client-Side Uploads (Presigned URLs) + +```typescript +import { S3Client } from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; +import { PutObjectCommand } from '@aws-sdk/client-s3'; + +// Worker: Generate presigned upload URL +const s3 = new S3Client({ + region: 'auto', + endpoint: `https://${env.ACCOUNT_ID}.r2.cloudflarestorage.com`, + credentials: { accessKeyId: env.R2_ACCESS_KEY_ID, secretAccessKey: env.R2_SECRET_ACCESS_KEY } +}); + +const url = await getSignedUrl(s3, new PutObjectCommand({ Bucket: 'my-bucket', Key: key }), { expiresIn: 3600 }); +return Response.json({ uploadUrl: url }); + +// Client: Upload directly +const { uploadUrl } = await fetch('/api/upload-url').then(r => r.json()); +await fetch(uploadUrl, { method: 'PUT', body: file }); +``` + +## Caching with Cache API + +```typescript +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const cache = caches.default; + const url = new URL(request.url); + const cacheKey = new Request(url.toString(), request); + + // Check cache first + let response = await cache.match(cacheKey); + if (response) return response; + + // Fetch from R2 + const key = url.pathname.slice(1); + const object = await env.MY_BUCKET.get(key); + if (!object) return new Response('Not found', { status: 404 }); + + const headers = new Headers(); + object.writeHttpMetadata(headers); + headers.set('etag', object.httpEtag); + headers.set('cache-control', 'public, max-age=31536000, immutable'); + + response = new Response(object.body, { headers }); + + // Cache for subsequent requests + ctx.waitUntil(cache.put(cacheKey, response.clone())); + + return response; + } +}; +``` + +## Public Bucket with Custom Domain + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + // CORS preflight + if (request.method === 'OPTIONS') { + return new Response(null, { + headers: { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET, HEAD', + 'access-control-max-age': '86400' + } + }); + } + + const key = new URL(request.url).pathname.slice(1); + if (!key) return Response.redirect('/index.html', 302); + + const object = await env.MY_BUCKET.get(key); + if (!object) return new Response('Not found', { status: 404 }); + + const headers = new Headers(); + object.writeHttpMetadata(headers); + headers.set('etag', object.httpEtag); + headers.set('access-control-allow-origin', '*'); + headers.set('cache-control', 'public, max-age=31536000, immutable'); + + return new Response(object.body, { headers }); + } +}; +``` + +## r2.dev Public URLs + +Enable r2.dev in dashboard for simple public access: `https://pub-${hashId}.r2.dev/${key}` +Or add custom domain via dashboard: `https://files.example.com/${key}` + +**Limitations:** No auth, bucket-level CORS, no cache override. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6f999216f421d13fa6ea2aecca5e2f876cb95006 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/README.md @@ -0,0 +1,65 @@ +# Cloudflare Realtime SFU Reference + +Expert guidance for building real-time audio/video/data applications using Cloudflare Realtime SFU (Selective Forwarding Unit). + +## Reading Order + +| Task | Files | ~Tokens | +|------|-------|---------| +| New project | README → configuration | ~1200 | +| Implement publish/subscribe | README → api | ~1600 | +| Add PartyTracks | patterns (PartyTracks section) | ~800 | +| Build presence system | patterns (DO section) | ~800 | +| Debug connection issues | gotchas | ~700 | +| Scale to millions | patterns (Cascading section) | ~600 | +| Add simulcast | patterns (Advanced section) | ~500 | +| Configure TURN | configuration (TURN section) | ~400 | + +## In This Reference + +- **[configuration.md](configuration.md)** - Setup, deployment, environment variables, Wrangler config +- **[api.md](api.md)** - Sessions, tracks, endpoints, request/response patterns +- **[patterns.md](patterns.md)** - Architecture patterns, use cases, integration examples +- **[gotchas.md](gotchas.md)** - Common issues, debugging, performance, security + +## Quick Start + +Cloudflare Realtime SFU: WebRTC infrastructure on global network (310+ cities). Anycast routing, no regional constraints, pub/sub model. + +**Core concepts:** +- **Sessions:** WebRTC PeerConnection to Cloudflare edge +- **Tracks:** Audio/video/data channels you publish or subscribe to +- **No rooms:** Build presence layer yourself via track sharing (see patterns.md) + +**Mental model:** Your client establishes one WebRTC session, publishes tracks (audio/video), shares track IDs via your backend, others subscribe to your tracks using track IDs + your session ID. + +## Choose Your Approach + +| Approach | When to Use | Complexity | +|----------|-------------|------------| +| **PartyTracks** | Production apps with device switching, React | Low - Observable-based, handles reconnections | +| **Raw API** | Custom requirements, non-browser, learning | Medium - Full control, manual WebRTC lifecycle | +| **RealtimeKit** | End-to-end SDK with UI components | Lowest - Managed state, React hooks | + +**Recommendation:** Start with PartyTracks for most production applications. See patterns.md for PartyTracks examples. + +## SFU vs RealtimeKit + +- **Realtime SFU:** WebRTC infrastructure (this reference). Build your own signaling, presence, UI. +- **RealtimeKit:** SDK layer on top of SFU. Includes React hooks, state management, UI components. Part of Cloudflare AI platform. + +Use SFU directly when you need custom signaling or non-React framework. Use RealtimeKit for faster development with React. + +## Setup + +Dashboard: https://dash.cloudflare.com/?to=/:account/calls + +Get `CALLS_APP_ID` and `CALLS_APP_SECRET` from dashboard, then see configuration.md for deployment. + +## See Also + +- [Orange Meets Demo](https://demo.orange.cloudflare.dev/) +- [Orange Source](https://github.com/cloudflare/orange) +- [Calls Examples](https://github.com/cloudflare/calls-examples) +- [API Reference](https://developers.cloudflare.com/api/resources/calls/) +- [RealtimeKit Docs](https://developers.cloudflare.com/workers-ai/realtimekit/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/api.md new file mode 100644 index 0000000000000000000000000000000000000000..c5b753c8051b28b8b4a5f7fbc63cdc83bff5dc22 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/api.md @@ -0,0 +1,158 @@ +# API Reference + +## Authentication + +```bash +curl -X POST 'https://rtc.live/v1/apps/${CALLS_APP_ID}/sessions/new' \ + -H "Authorization: Bearer ${CALLS_APP_SECRET}" +``` + +## Core Concepts + +**Sessions:** PeerConnection to Cloudflare edge +**Tracks:** Media/data channels (audio/video/datachannel) +**No rooms:** Build presence via track sharing + +## Client Libraries + +**PartyTracks (Recommended):** Observable-based client library for production use. Handles device changes, network switches, ICE restarts automatically. Push/pull API with React hooks. See patterns.md for full examples. + +```bash +npm install partytracks @cloudflare/calls +``` + +**Raw API:** Direct HTTP + WebRTC for custom requirements (documented below). + +## Endpoints + +### Create Session +```http +POST /v1/apps/{appId}/sessions/new +→ {sessionId, sessionDescription} +``` + +### Add Track (Publish) +```http +POST /v1/apps/{appId}/sessions/{sessionId}/tracks/new +Body: { + sessionDescription: {sdp, type: "offer"}, + tracks: [{location: "local", trackName: "my-video"}] +} +→ {sessionDescription, tracks: [{trackName}]} +``` + +### Add Track (Subscribe) +```http +POST /v1/apps/{appId}/sessions/{sessionId}/tracks/new +Body: { + tracks: [{ + location: "remote", + trackName: "remote-track-id", + sessionId: "other-session-id" + }] +} +→ {sessionDescription} (server offer) +``` + +### Renegotiate +```http +PUT /v1/apps/{appId}/sessions/{sessionId}/renegotiate +Body: {sessionDescription: {sdp, type: "answer"}} +``` + +### Close Tracks +```http +PUT /v1/apps/{appId}/sessions/{sessionId}/tracks/close +Body: {tracks: [{trackName}]} +→ {requiresImmediateRenegotiation: boolean} +``` + +### Get Session +```http +GET /v1/apps/{appId}/sessions/{sessionId} +→ {sessionId, tracks: TrackMetadata[]} +``` + +## TypeScript Types + +```typescript +interface TrackMetadata { + trackName: string; + location: "local" | "remote"; + sessionId?: string; // For remote tracks + mid?: string; // WebRTC mid +} +``` + +## WebRTC Flow + +```typescript +// 1. Create PeerConnection +const pc = new RTCPeerConnection({ + iceServers: [{urls: 'stun:stun.cloudflare.com:3478'}] +}); + +// 2. Add tracks +const stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true}); +stream.getTracks().forEach(track => pc.addTrack(track, stream)); + +// 3. Create offer +const offer = await pc.createOffer(); +await pc.setLocalDescription(offer); + +// 4. Send to backend → Cloudflare API +const response = await fetch('/api/new-session', { + method: 'POST', + body: JSON.stringify({sdp: offer.sdp}) +}); + +// 5. Set remote answer +const {sessionDescription} = await response.json(); +await pc.setRemoteDescription(sessionDescription); +``` + +## Publishing + +```typescript +const offer = await pc.createOffer(); +await pc.setLocalDescription(offer); + +const res = await fetch(`/api/sessions/${sessionId}/tracks`, { + method: 'POST', + body: JSON.stringify({ + sdp: offer.sdp, + tracks: [{location: 'local', trackName: 'my-video'}] + }) +}); + +const {sessionDescription, tracks} = await res.json(); +await pc.setRemoteDescription(sessionDescription); +const publishedTrackId = tracks[0].trackName; // Share with others +``` + +## Subscribing + +```typescript +const res = await fetch(`/api/sessions/${sessionId}/tracks`, { + method: 'POST', + body: JSON.stringify({ + tracks: [{location: 'remote', trackName: remoteTrackId, sessionId: remoteSessionId}] + }) +}); + +const {sessionDescription} = await res.json(); +await pc.setRemoteDescription(sessionDescription); + +const answer = await pc.createAnswer(); +await pc.setLocalDescription(answer); + +await fetch(`/api/sessions/${sessionId}/renegotiate`, { + method: 'PUT', + body: JSON.stringify({sdp: answer.sdp}) +}); + +pc.ontrack = (event) => { + const [remoteStream] = event.streams; + videoElement.srcObject = remoteStream; +}; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..bc4ac0779470cec469fdeb7d6646347e4a4b5379 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/configuration.md @@ -0,0 +1,137 @@ +# Configuration & Deployment + +## Dashboard Setup + +1. Navigate to https://dash.cloudflare.com/?to=/:account/calls +2. Click "Create Application" (or use existing app) +3. Copy `CALLS_APP_ID` from dashboard +4. Generate and copy `CALLS_APP_SECRET` (treat as sensitive credential) +5. Use credentials in Wrangler config or environment variables below + +## Dependencies + +**Backend (Workers):** Built-in fetch API, no additional packages required + +**Client (PartyTracks):** +```bash +npm install partytracks @cloudflare/calls +``` + +**Client (React + PartyTracks):** +```bash +npm install partytracks @cloudflare/calls observable-hooks +# Observable hooks: useObservableAsValue, useValueAsObservable +``` + +**Client (Raw API):** Native browser WebRTC API only + +## Wrangler Setup + +```jsonc +{ + "name": "my-calls-app", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", // Use current date for new projects + "vars": { + "CALLS_APP_ID": "your-app-id", + "MAX_WEBCAM_BITRATE": "1200000", + "MAX_WEBCAM_FRAMERATE": "24", + "MAX_WEBCAM_QUALITY_LEVEL": "1080" + }, + // Set secret: wrangler secret put CALLS_APP_SECRET + "durable_objects": { + "bindings": [ + { + "name": "ROOM", + "class_name": "Room" + } + ] + } +} +``` + +## Deploy + +```bash +wrangler login +wrangler secret put CALLS_APP_SECRET +wrangler deploy +``` + +## Environment Variables + +**Required:** +- `CALLS_APP_ID`: From dashboard +- `CALLS_APP_SECRET`: From dashboard (secret) + +**Optional:** +- `MAX_WEBCAM_BITRATE` (default: 1200000) +- `MAX_WEBCAM_FRAMERATE` (default: 24) +- `MAX_WEBCAM_QUALITY_LEVEL` (default: 1080) +- `TURN_SERVICE_ID`: TURN service +- `TURN_SERVICE_TOKEN`: TURN auth (secret) + +## TURN Configuration + +```javascript +const pc = new RTCPeerConnection({ + iceServers: [ + { urls: 'stun:stun.cloudflare.com:3478' }, + { + urls: [ + 'turn:turn.cloudflare.com:3478?transport=udp', + 'turn:turn.cloudflare.com:3478?transport=tcp', + 'turns:turn.cloudflare.com:5349?transport=tcp' + ], + username: turnUsername, + credential: turnCredential + } + ], + bundlePolicy: 'max-bundle', // Recommended: reduces overhead + iceTransportPolicy: 'all' // Use 'relay' to force TURN (testing only) +}); +``` + +**Ports:** 3478 (UDP/TCP), 53 (UDP), 80 (TCP), 443 (TLS), 5349 (TLS) + +**When to use TURN:** Required for restrictive corporate firewalls/networks that block UDP. ~5-10% of connections fallback to TURN. STUN works for most users. + +**ICE candidate filtering:** Cloudflare handles candidate filtering automatically. No need to manually filter candidates. + +## Durable Object Boilerplate + +Minimal presence system: + +```typescript +export class Room { + private sessions = new Map(); + + async fetch(req: Request) { + const {pathname} = new URL(req.url); + const body = await req.json(); + + if (pathname === '/join') { + this.sessions.set(body.sessionId, {userId: body.userId, tracks: []}); + return Response.json({participants: this.sessions.size}); + } + + if (pathname === '/publish') { + this.sessions.get(body.sessionId)?.tracks.push(...body.tracks); + // Broadcast to others via WebSocket (not shown) + return new Response('OK'); + } + + return new Response('Not found', {status: 404}); + } +} +``` + +## Environment Validation + +Check credentials before first API call: + +```typescript +if (!env.CALLS_APP_ID || !env.CALLS_APP_SECRET) { + throw new Error('CALLS_APP_ID and CALLS_APP_SECRET required'); +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..38145aa671630f3fb3c92bfa03488253bae9b670 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/gotchas.md @@ -0,0 +1,133 @@ +# Gotchas & Troubleshooting + +## Common Errors + +### "Slow initial connect (~1.8s)" + +**Cause:** First STUN delayed during consensus forming (normal behavior) +**Solution:** Subsequent connections are faster. CF detects DTLS ClientHello early to compensate. + +### "No media flow" + +**Cause:** SDP exchange incomplete, connection not established, tracks not added before offer, browser permissions missing +**Solution:** +1. Verify SDP exchange complete +2. Check `pc.connectionState === 'connected'` +3. Ensure tracks added before creating offer +4. Confirm browser permissions granted +5. Use `chrome://webrtc-internals` for debugging + +### "Track not receiving" + +**Cause:** Track not published, track ID not shared, session IDs mismatch, `pc.ontrack` not set, renegotiation needed +**Solution:** +1. Verify track published successfully +2. Confirm track ID shared between peers +3. Check session IDs match +4. Set `pc.ontrack` handler before answer +5. Trigger renegotiation if needed + +### "ICE connection failed" + +**Cause:** Network changed, firewall blocked UDP, TURN needed, transient network issue +**Solution:** +```typescript +pc.oniceconnectionstatechange = async () => { + if (pc.iceConnectionState === 'failed') { + console.warn('ICE failed, attempting restart'); + await pc.restartIce(); // Triggers new ICE gathering + + // Create new offer with ICE restart flag + const offer = await pc.createOffer({iceRestart: true}); + await pc.setLocalDescription(offer); + + // Send to backend → Cloudflare API + await fetch(`/api/sessions/${sessionId}/renegotiate`, { + method: 'PUT', + body: JSON.stringify({sdp: offer.sdp}) + }); + } +}; +``` + +### "Track stuck/frozen" + +**Cause:** Sender paused track, network congestion, codec mismatch, mobile browser backgrounded +**Solution:** +1. Check `track.enabled` and `track.readyState === 'live'` +2. Verify sender active: `pc.getSenders().find(s => s.track === track)` +3. Check stats for packet loss/jitter (see patterns.md) +4. On mobile: Re-acquire tracks when app foregrounded +5. Test with different codecs if persistent + +### "Network change disconnects call" + +**Cause:** Mobile switching WiFi↔cellular, laptop changing networks +**Solution:** +```typescript +// Listen for network changes +if ('connection' in navigator) { + (navigator as any).connection.addEventListener('change', async () => { + console.log('Network changed'); + await pc.restartIce(); // Use ICE restart pattern above + }); +} + +// Or use PartyTracks (handles automatically) +``` + +## Retry with Exponential Backoff + +```typescript +async function fetchWithRetry(url: string, options: RequestInit, maxRetries = 3) { + for (let i = 0; i < maxRetries; i++) { + try { + const res = await fetch(url, options); + if (res.ok) return res; + if (res.status >= 500) throw new Error('Server error'); + return res; // Client error, don't retry + } catch (err) { + if (i === maxRetries - 1) throw err; + const delay = Math.min(1000 * 2 ** i, 10000); // Cap at 10s + await new Promise(resolve => setTimeout(resolve, delay)); + } + } +} +``` + +## Debugging with chrome://webrtc-internals + +1. Open `chrome://webrtc-internals` in Chrome/Edge +2. Find your PeerConnection in the list +3. Check **Stats graphs** for packet loss, jitter, bandwidth +4. Check **ICE candidate pairs**: Look for `succeeded` state, relay vs host candidates +5. Check **getStats**: Raw metrics for inbound/outbound RTP +6. Look for errors in **Event log**: `iceConnectionState`, `connectionState` changes +7. Export data with "Download the PeerConnection updates and stats data" button +8. Common issues visible here: ICE failures, high packet loss, bitrate drops + +## Limits + +| Resource/Limit | Value | Notes | +|----------------|-------|-------| +| Egress (Free) | 1TB/month | Per account | +| Egress (Paid) | $0.05/GB | After free tier | +| Inbound traffic | Free | All plans | +| TURN service | Free | Included with SFU | +| Participants | No hard limit | Client bandwidth/CPU bound (typically 10-50 tracks) | +| Tracks per session | No hard limit | Client resources limited | +| Session duration | No hard limit | Production calls run for hours | +| WebRTC ports | UDP 1024-65535 | Outbound only, required for media | +| API rate limit | 600 req/min | Per app, burst allowed | + +## Security Checklist + +- ✅ **Never expose** `CALLS_APP_SECRET` to client +- ✅ **Validate user identity** in backend before creating sessions +- ✅ **Implement auth tokens** for session access (JWT in custom header) +- ✅ **Rate limit** session creation endpoints +- ✅ **Expire sessions** server-side after inactivity +- ✅ **Validate track IDs** before subscribing (prevent unauthorized access) +- ✅ **Use HTTPS** for all signaling (API calls) +- ✅ **Enable DTLS-SRTP** (automatic with Cloudflare, encrypts media) +- ⚠️ **Consider E2EE** for sensitive content (implement client-side with Insertable Streams API) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..5f37a2d5f94498d04aaf65e88a1d009605ad775f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/realtime-sfu/patterns.md @@ -0,0 +1,174 @@ +# Patterns & Use Cases + +## Architecture + +``` +Client (WebRTC) <---> CF Edge <---> Backend (HTTP) + | + CF Backbone (310+ DCs) + | + Other Edges <---> Other Clients +``` + +Anycast: Last-mile <50ms (95%), no region select, NACK shield, distributed consensus + +Cascading trees auto-scale to millions: +``` +Publisher -> Edge A -> Edge B -> Sub1 + \-> Edge C -> Sub2,3 +``` + +## Use Cases + +**1:1:** A creates session+publishes, B creates+subscribes to A+publishes, A subscribes to B +**N:N:** All create session+publish, backend broadcasts track IDs, all subscribe to others +**1:N:** Publisher creates+publishes, viewers each create+subscribe (no fan-out limit) +**Breakout:** Same PeerConnection! Backend closes/adds tracks, no recreation + +## PartyTracks (Recommended) + +Observable-based client with automatic device/network handling: + +```typescript +import {PartyTracks} from 'partytracks'; + +// Create client +const pt = new PartyTracks({ + apiUrl: '/api/calls', + sessionId: 'my-session', + onTrack: (track, peer) => { + const video = document.getElementById(`video-${peer.id}`) as HTMLVideoElement; + video.srcObject = new MediaStream([track]); + } +}); + +// Publish camera (push API) +const camera = await pt.getCamera(); // Auto-requests permissions, handles device changes +await pt.publishTrack(camera, {trackName: 'my-camera'}); + +// Subscribe to remote track (pull API) +await pt.subscribeToTrack({trackName: 'remote-camera', sessionId: 'other-session'}); + +// React hook example +import {useObservableAsValue} from 'observable-hooks'; + +function VideoCall() { + const localTracks = useObservableAsValue(pt.localTracks$); + const remoteTracks = useObservableAsValue(pt.remoteTracks$); + + return
{/* Render tracks */}
; +} + +// Screenshare +const screen = await pt.getScreenshare(); +await pt.publishTrack(screen, {trackName: 'my-screen'}); + +// Handle device changes (automatic) +// PartyTracks detects device changes (e.g., Bluetooth headset) and renegotiates +``` + +## Backend + +Express: +```js +app.post('/api/new-session', async (req, res) => { + const r = await fetch(`${CALLS_API}/apps/${process.env.CALLS_APP_ID}/sessions/new`, + {method: 'POST', headers: {'Authorization': `Bearer ${process.env.CALLS_APP_SECRET}`}}); + res.json(await r.json()); +}); +``` + +Workers: Same pattern, use `env.CALLS_APP_ID` and `env.CALLS_APP_SECRET` + +DO Presence: See configuration.md for boilerplate + +## Audio Level Detection + +```typescript +// Attach analyzer to audio track +function attachAudioLevelDetector(track: MediaStreamTrack) { + const ctx = new AudioContext(); + const analyzer = ctx.createAnalyser(); + const src = ctx.createMediaStreamSource(new MediaStream([track])); + src.connect(analyzer); + + const data = new Uint8Array(analyzer.frequencyBinCount); + const checkLevel = () => { + analyzer.getByteFrequencyData(data); + const level = data.reduce((a, b) => a + b) / data.length; + if (level > 30) console.log('Speaking:', level); // Trigger UI update + requestAnimationFrame(checkLevel); + }; + checkLevel(); +} +``` + +## Connection Quality Monitoring + +```typescript +pc.getStats().then(stats => { + stats.forEach(report => { + if (report.type === 'inbound-rtp' && report.kind === 'video') { + const {packetsLost, packetsReceived, jitter} = report; + const lossRate = packetsLost / (packetsLost + packetsReceived); + if (lossRate > 0.05) console.warn('High packet loss:', lossRate); + if (jitter > 100) console.warn('High jitter:', jitter); + } + }); +}); +``` + +## Stage Management (Limit Visible Participants) + +```typescript +// Subscribe to top 6 active speakers only +let activeSubscriptions = new Set(); + +function updateStage(topSpeakers: string[]) { + const toAdd = topSpeakers.filter(id => !activeSubscriptions.has(id)).slice(0, 6); + const toRemove = [...activeSubscriptions].filter(id => !topSpeakers.includes(id)); + + toRemove.forEach(id => { + pc.getSenders().find(s => s.track?.id === id)?.track?.stop(); + activeSubscriptions.delete(id); + }); + + toAdd.forEach(async id => { + await fetch(`/api/subscribe`, {method: 'POST', body: JSON.stringify({trackId: id})}); + activeSubscriptions.add(id); + }); +} +``` + +## Advanced + +Bandwidth mgmt: +```ts +const s = pc.getSenders().find(s => s.track?.kind === 'video'); +const p = s.getParameters(); +if (!p.encodings) p.encodings = [{}]; +p.encodings[0].maxBitrate = 1200000; p.encodings[0].maxFramerate = 24; +await s.setParameters(p); +``` + +Simulcast (CF auto-forwards best layer): +```ts +pc.addTransceiver('video', {direction: 'sendonly', sendEncodings: [ + {rid: 'high', maxBitrate: 1200000}, + {rid: 'med', maxBitrate: 600000, scaleResolutionDownBy: 2}, + {rid: 'low', maxBitrate: 200000, scaleResolutionDownBy: 4} +]}); +``` + +DataChannel: +```ts +const dc = pc.createDataChannel('chat', {ordered: true, maxRetransmits: 3}); +dc.onopen = () => dc.send(JSON.stringify({type: 'chat', text: 'Hi'})); +dc.onmessage = (e) => console.log('RX:', JSON.parse(e.data)); +``` + +**WHIP/WHEP:** For streaming interop (OBS → SFU, SFU → video players), use WHIP (ingest) and WHEP (egress) protocols. See Cloudflare Stream integration docs. + +Integrations: R2 for recording `env.R2_BUCKET.put(...)`, Queues for analytics + +Perf: 100-250ms connect, ~50ms latency (95%), 200-400ms glass-to-glass, no participant limit (client: 10-50 tracks) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dc709e95fb0d59bf4d5b7413c4d4a7278ee65fa0 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/README.md @@ -0,0 +1,74 @@ +# Cloudflare Secrets Store + +Account-level encrypted secret management for Workers and AI Gateway. + +## Overview + +**Secrets Store**: Centralized, account-level secrets, reusable across Workers +**Worker Secrets**: Per-Worker secrets (`wrangler secret put`) + +### Architecture + +- **Store**: Container (1/account in beta) +- **Secret**: String ≤1024 bytes +- **Scopes**: Permission boundaries controlling access + - `workers`: For Workers runtime access + - `ai-gateway`: For AI Gateway access + - Secrets must have correct scope for binding to work +- **Bindings**: Connect secrets via `env` object + +**Regional Availability**: Global except China Network (unavailable) + +### Access Control + +- **Super Admin**: Full access +- **Admin**: Create/edit/delete secrets, view metadata +- **Deployer**: View metadata + bindings +- **Reporter**: View metadata only + +API Token permissions: `Account Secrets Store Edit/Read` + +### Limits (Beta) + +- 100 secrets/account +- 1 store/account +- 1024 bytes max/secret +- Production secrets count toward limit + +## When to Use + +**Use Secrets Store when:** +- Multiple Workers share same credential +- Centralized management needed +- Compliance requires audit trail +- Team collaboration on secrets + +**Use Worker Secrets when:** +- Secret unique to one Worker +- Simple single-Worker project +- No cross-Worker sharing needed + +## In This Reference + +### Reading Order by Task + +| Task | Start Here | Then Read | +|------|------------|-----------| +| Quick overview | README.md | - | +| First-time setup | README.md → configuration.md | api.md | +| Add secret to Worker | configuration.md | api.md | +| Implement access pattern | api.md | patterns.md | +| Debug errors | gotchas.md | api.md | +| Secret rotation | patterns.md | configuration.md | +| Best practices | gotchas.md | patterns.md | + +### Files + +- [configuration.md](./configuration.md) - Wrangler commands, binding config +- [api.md](./api.md) - Binding API, get/put/delete operations +- [patterns.md](./patterns.md) - Rotation, encryption, access control +- [gotchas.md](./gotchas.md) - Security issues, limits, best practices + +## See Also +- [workers](../workers/) - Worker bindings integration +- [wrangler](../wrangler/) - CLI secret management commands diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/api.md new file mode 100644 index 0000000000000000000000000000000000000000..2e4e6e2401728afc23a26d97a5e3b20b36218fed --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/api.md @@ -0,0 +1,200 @@ +# API Reference + +## Binding API + +### Basic Access + +**CRITICAL**: Async `.get()` required - secrets NOT directly available. + +**`.get()` throws on error** - does NOT return null. Always use try/catch. + +```typescript +interface Env { + API_KEY: { get(): Promise }; +} + +export default { + async fetch(request: Request, env: Env): Promise { + const apiKey = await env.API_KEY.get(); + return fetch("https://api.example.com", { + headers: { "Authorization": `Bearer ${apiKey}` } + }); + } +} +``` + +### Error Handling + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + try { + const apiKey = await env.API_KEY.get(); + return fetch("https://api.example.com", { + headers: { "Authorization": `Bearer ${apiKey}` } + }); + } catch (error) { + console.error("Secret access failed:", error); + return new Response("Configuration error", { status: 500 }); + } + } +} +``` + +### Multiple Secrets & Patterns + +```typescript +// Parallel fetch +const [stripeKey, sendgridKey] = await Promise.all([ + env.STRIPE_KEY.get(), + env.SENDGRID_KEY.get() +]); + +// ❌ Missing .get() +const key = env.API_KEY; + +// ❌ Module-level cache +const CACHED_KEY = await env.API_KEY.get(); // Fails + +// ✅ Request-scope cache +const key = await env.API_KEY.get(); // OK - reuse within request +``` + +## REST API + +Base: `https://api.cloudflare.com/client/v4` + +### Auth + +```bash +curl -H "Authorization: Bearer $CF_TOKEN" \ + https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/secrets_store/stores +``` + +### Store Operations + +```bash +# List +GET /accounts/{account_id}/secrets_store/stores + +# Create +POST /accounts/{account_id}/secrets_store/stores +{"name": "my-store"} + +# Delete +DELETE /accounts/{account_id}/secrets_store/stores/{store_id} +``` + +### Secret Operations + +```bash +# List +GET /accounts/{account_id}/secrets_store/stores/{store_id}/secrets + +# Create (single) +POST /accounts/{account_id}/secrets_store/stores/{store_id}/secrets +{ + "name": "my_secret", + "value": "secret_value", + "scopes": ["workers"], + "comment": "Optional" +} + +# Create (batch) +POST /accounts/{account_id}/secrets_store/stores/{store_id}/secrets +[ + {"name": "secret_one", "value": "val1", "scopes": ["workers"]}, + {"name": "secret_two", "value": "val2", "scopes": ["workers", "ai-gateway"]} +] + +# Get metadata +GET /accounts/{account_id}/secrets_store/stores/{store_id}/secrets/{secret_id} + +# Update +PATCH /accounts/{account_id}/secrets_store/stores/{store_id}/secrets/{secret_id} +{"value": "new_value", "comment": "Updated"} + +# Delete (single) +DELETE /accounts/{account_id}/secrets_store/stores/{store_id}/secrets/{secret_id} + +# Delete (batch) +DELETE /accounts/{account_id}/secrets_store/stores/{store_id}/secrets +{"secret_ids": ["id-1", "id-2"]} + +# Duplicate +POST /accounts/{account_id}/secrets_store/stores/{store_id}/secrets/{secret_id}/duplicate +{"name": "new_name"} + +# Quota +GET /accounts/{account_id}/secrets_store/quota +``` + +### Responses + +Success: +```json +{ + "success": true, + "result": { + "id": "secret-id-123", + "name": "my_secret", + "created": "2025-01-11T12:00:00Z", + "scopes": ["workers"] + } +} +``` + +Error: +```json +{ + "success": false, + "errors": [{"code": 10000, "message": "Name exists"}] +} +``` + +## TypeScript Helpers + +Official types available via `@cloudflare/workers-types`: + +```typescript +import type { SecretsStoreSecret } from "@cloudflare/workers-types"; + +interface Env { + STRIPE_API_KEY: SecretsStoreSecret; + DATABASE_URL: SecretsStoreSecret; + WORKER_SECRET: string; // Regular Worker secret (direct access) +} +``` + +Custom helper type: + +```typescript +interface SecretsStoreBinding { + get(): Promise; +} + +// Fallback helper +async function getSecretWithFallback( + primary: SecretsStoreBinding, + fallback?: SecretsStoreBinding +): Promise { + try { + return await primary.get(); + } catch (error) { + if (fallback) return await fallback.get(); + throw error; + } +} + +// Batch helper +async function getAllSecrets( + secrets: Record +): Promise> { + const entries = await Promise.all( + Object.entries(secrets).map(async ([k, v]) => [k, await v.get()]) + ); + return Object.fromEntries(entries); +} +``` + +See: [configuration.md](./configuration.md), [patterns.md](./patterns.md), [gotchas.md](./gotchas.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..a1e2eee251db39a9b7e21861e1357da1d12a6394 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/configuration.md @@ -0,0 +1,185 @@ +# Configuration + +## Wrangler Config + +### Basic Binding + +**wrangler.jsonc**: + +```jsonc +{ + "secrets_store_secrets": [ + { + "binding": "API_KEY", + "store_id": "abc123", + "secret_name": "stripe_api_key" + } + ] +} +``` + +**wrangler.toml** (alternative): + +```toml +[[secrets_store_secrets]] +binding = "API_KEY" +store_id = "abc123" +secret_name = "stripe_api_key" +``` + +Fields: +- `binding`: Variable name for `env` access +- `store_id`: From `wrangler secrets-store store list` +- `secret_name`: Identifier (no spaces) + +### Environment-Specific + +**wrangler.jsonc**: + +```jsonc +{ + "env": { + "production": { + "secrets_store_secrets": [ + { + "binding": "API_KEY", + "store_id": "prod-store", + "secret_name": "prod_api_key" + } + ] + }, + "staging": { + "secrets_store_secrets": [ + { + "binding": "API_KEY", + "store_id": "staging-store", + "secret_name": "staging_api_key" + } + ] + } + } +} +``` + +**wrangler.toml** (alternative): + +```toml +[env.production] +[[env.production.secrets_store_secrets]] +binding = "API_KEY" +store_id = "prod-store" +secret_name = "prod_api_key" + +[env.staging] +[[env.staging.secrets_store_secrets]] +binding = "API_KEY" +store_id = "staging-store" +secret_name = "staging_api_key" +``` + +## Wrangler Commands + +### Store Management + +```bash +wrangler secrets-store store list +wrangler secrets-store store create my-store --remote +wrangler secrets-store store delete --remote +``` + +### Secret Management (Production) + +```bash +# Create (interactive) +wrangler secrets-store secret create \ + --name MY_SECRET --scopes workers --remote + +# Create (piped) +cat secret.txt | wrangler secrets-store secret create \ + --name MY_SECRET --scopes workers --remote + +# List/get/update/delete +wrangler secrets-store secret list --remote +wrangler secrets-store secret get --name MY_SECRET --remote +wrangler secrets-store secret update --name MY_SECRET --new-value "val" --remote +wrangler secrets-store secret delete --name MY_SECRET --remote + +# Duplicate +wrangler secrets-store secret duplicate \ + --name ORIG --new-name COPY --remote +``` + +### Local Development + +**CRITICAL**: Production secrets (`--remote`) NOT accessible in local dev. + +```bash +# Create local-only (no --remote) +wrangler secrets-store secret create --name DEV_KEY --scopes workers + +wrangler dev # Uses local secrets +wrangler deploy # Uses production secrets +``` + +Best practice: Separate names for local/prod: + +```jsonc +{ + "env": { + "development": { + "secrets_store_secrets": [ + { "binding": "API_KEY", "store_id": "store", "secret_name": "dev_api_key" } + ] + }, + "production": { + "secrets_store_secrets": [ + { "binding": "API_KEY", "store_id": "store", "secret_name": "prod_api_key" } + ] + } + } +} +``` + +## Dashboard + +### Creating Secrets + +1. **Secrets Store** → **Create secret** +2. Fill: Name (no spaces), Value, Scope (`Workers`), Comment +3. **Save** (value hidden after) + +### Adding Bindings + +**Method 1**: Worker → Settings → Bindings → Add → Secrets Store +**Method 2**: Create secret directly from Worker settings dropdown + +Deploy options: +- **Deploy**: Immediate 100% +- **Save version**: Gradual rollout + +## CI/CD + +### GitHub Actions + +```yaml +- name: Create secret + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_TOKEN }} + run: | + echo "${{ secrets.API_KEY }}" | \ + npx wrangler secrets-store secret create $STORE_ID \ + --name API_KEY --scopes workers --remote + +- name: Deploy + run: npx wrangler deploy +``` + +### GitLab CI + +```yaml +script: + - echo "$API_KEY_VALUE" | npx wrangler secrets-store secret create $STORE_ID --name API_KEY --scopes workers --remote + - npx wrangler deploy +``` + +See: [api.md](./api.md), [patterns.md](./patterns.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..cf35d5344b0fcdc3ecf7460ff530548f78c369ed --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/gotchas.md @@ -0,0 +1,97 @@ +# Gotchas + +## Common Errors + +### ".get() Throws on Error" + +**Cause:** Assuming `.get()` returns null on failure instead of throwing +**Solution:** Always wrap `.get()` calls in try/catch blocks to handle errors gracefully + +```typescript +try { + const key = await env.API_KEY.get(); +} catch (error) { + return new Response("Configuration error", { status: 500 }); +} +``` + +### "Logging Secret Values" + +**Cause:** Accidentally logging secret values in console or error messages +**Solution:** Only log metadata (e.g., "Retrieved API_KEY") never the actual secret value + +### "Module-Level Secret Access" + +**Cause:** Attempting to access secrets during module initialization before env is available +**Solution:** Cache secrets in request scope only, not at module level + +### "Secret not found in store" + +**Cause:** Secret name doesn't exist, case mismatch, missing workers scope, or incorrect store_id +**Solution:** Verify secret exists with `wrangler secrets-store secret list --remote`, check name matches exactly (case-sensitive), ensure secret has `workers` scope, and verify correct store_id + +### "Scope Mismatch" + +**Cause:** Secret exists but missing `workers` scope (only has `ai-gateway` scope) +**Solution:** Update secret scopes: `wrangler secrets-store secret update --name SECRET --scopes workers --remote` or add via Dashboard + +### "JSON Parsing Failure" + +**Cause:** Storing invalid JSON in secret, then failing to parse during runtime +**Solution:** Validate JSON before storing: + +```bash +# Validate before storing +echo '{"key":"value"}' | jq . && \ + echo '{"key":"value"}' | wrangler secrets-store secret create \ + --name CONFIG --scopes workers --remote +``` + +Runtime parsing with error handling: + +```typescript +try { + const configStr = await env.CONFIG.get(); + const config = JSON.parse(configStr); +} catch (error) { + console.error("Invalid config JSON:", error); + return new Response("Invalid configuration", { status: 500 }); +} +``` + +### "Cannot access secret in local dev" + +**Cause:** Attempting to access production secrets in local development environment +**Solution:** Create local-only secrets (without `--remote` flag) for development: `wrangler secrets-store secret create --name API_KEY --scopes workers` + +### "Property 'get' does not exist" + +**Cause:** Missing TypeScript type definition for secret binding +**Solution:** Define interface with get method: `interface Env { API_KEY: { get(): Promise }; }` + +### "Binding already exists" + +**Cause:** Duplicate binding in dashboard or conflict between wrangler.jsonc and dashboard +**Solution:** Remove duplicate from dashboard Settings → Bindings, check for conflicts, or delete old Worker secret with `wrangler secret delete API_KEY` + +### "Account secret quota exceeded" + +**Cause:** Account has reached 100 secret limit (beta) +**Solution:** Check quota with `wrangler secrets-store quota --remote`, delete unused secrets, consolidate duplicates, or contact Cloudflare for increase + +## Limits + +| Limit | Value | Notes | +|-------|-------|-------| +| Max secrets per account | 100 | Beta limit | +| Max stores per account | 1 | Beta limit | +| Max secret size | 1024 bytes | Per secret | +| Local secrets | Don't count toward limit | Only production secrets count | +| Scopes available | `workers`, `ai-gateway` | Must have correct scope for access | +| Scope | Account-level | Can be reused across multiple Workers | +| Access method | `await env.BINDING.get()` | Async only, throws on error | +| Management | Centralized | Via secrets-store commands | +| Local dev | Separate local secrets | Use without `--remote` flag | +| Regional availability | Global except China Network | Unavailable in China Network | + +See: [configuration.md](./configuration.md), [api.md](./api.md), [patterns.md](./patterns.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..a85b2eee9b4d9032b161d187c3e35b1c63d8c54b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/secrets-store/patterns.md @@ -0,0 +1,207 @@ +# Patterns + +## Secret Rotation + +Zero-downtime rotation with versioned naming (`api_key_v1`, `api_key_v2`): + +```typescript +interface Env { + PRIMARY_KEY: { get(): Promise }; + FALLBACK_KEY?: { get(): Promise }; +} + +async function fetchWithAuth(url: string, key: string) { + return fetch(url, { headers: { "Authorization": `Bearer ${key}` } }); +} + +export default { + async fetch(request: Request, env: Env): Promise { + let resp = await fetchWithAuth("https://api.example.com", await env.PRIMARY_KEY.get()); + + // Fallback during rotation + if (!resp.ok && env.FALLBACK_KEY) { + resp = await fetchWithAuth("https://api.example.com", await env.FALLBACK_KEY.get()); + } + + return resp; + } +} +``` + +Workflow: Create `api_key_v2` → add fallback binding → deploy → swap primary → deploy → remove `v1` + +## Encryption with KV + +```typescript +interface Env { + CACHE: KVNamespace; + ENCRYPTION_KEY: { get(): Promise }; +} + +async function encryptValue(value: string, key: string): Promise { + const enc = new TextEncoder(); + const keyMaterial = await crypto.subtle.importKey( + "raw", enc.encode(key), { name: "AES-GCM" }, false, ["encrypt"] + ); + const iv = crypto.getRandomValues(new Uint8Array(12)); + const encrypted = await crypto.subtle.encrypt( + { name: "AES-GCM", iv }, keyMaterial, enc.encode(value) + ); + + const combined = new Uint8Array(iv.length + encrypted.byteLength); + combined.set(iv); + combined.set(new Uint8Array(encrypted), iv.length); + return btoa(String.fromCharCode(...combined)); +} + +export default { + async fetch(request: Request, env: Env): Promise { + const key = await env.ENCRYPTION_KEY.get(); + const encrypted = await encryptValue("sensitive-data", key); + await env.CACHE.put("user:123:data", encrypted); + return Response.json({ ok: true }); + } +} +``` + +## HMAC Signing + +```typescript +interface Env { + HMAC_SECRET: { get(): Promise }; +} + +async function signRequest(data: string, secret: string): Promise { + const enc = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"] + ); + const sig = await crypto.subtle.sign("HMAC", key, enc.encode(data)); + return btoa(String.fromCharCode(...new Uint8Array(sig))); +} + +export default { + async fetch(request: Request, env: Env): Promise { + const secret = await env.HMAC_SECRET.get(); + const payload = await request.text(); + const signature = await signRequest(payload, secret); + return Response.json({ signature }); + } +} +``` + +## Audit & Monitoring + +```typescript +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext) { + const startTime = Date.now(); + try { + const apiKey = await env.API_KEY.get(); + const resp = await fetch("https://api.example.com", { + headers: { "Authorization": `Bearer ${apiKey}` } + }); + + ctx.waitUntil( + fetch("https://log.example.com/log", { + method: "POST", + body: JSON.stringify({ + event: "secret_used", + secret_name: "API_KEY", + timestamp: new Date().toISOString(), + duration_ms: Date.now() - startTime, + success: resp.ok + }) + }) + ); + return resp; + } catch (error) { + ctx.waitUntil( + fetch("https://log.example.com/log", { + method: "POST", + body: JSON.stringify({ + event: "secret_access_failed", + secret_name: "API_KEY", + error: error instanceof Error ? error.message : "Unknown" + }) + }) + ); + return new Response("Error", { status: 500 }); + } + } +} +``` + +## Migration from Worker Secrets + +Change `env.SECRET` (direct) to `await env.SECRET.get()` (async). + +Steps: +1. Create in Secrets Store: `wrangler secrets-store secret create --name API_KEY --scopes workers --remote` +2. Add binding to `wrangler.jsonc`: `{"binding": "API_KEY", "store_id": "abc123", "secret_name": "api_key"}` +3. Update code: `const key = await env.API_KEY.get();` +4. Test staging, deploy +5. Remove old: `wrangler secret delete API_KEY` + +## Sharing Across Workers + +Same secret, different binding names: + +```jsonc +// worker-1: binding="SHARED_DB", secret_name="postgres_url" +// worker-2: binding="DB_CONN", secret_name="postgres_url" +``` + +## JSON Secret Parsing + +Store structured config as JSON secrets: + +```typescript +interface Env { + DB_CONFIG: { get(): Promise }; +} + +interface DbConfig { + host: string; + port: number; + username: string; + password: string; +} + +export default { + async fetch(request: Request, env: Env): Promise { + try { + const configStr = await env.DB_CONFIG.get(); + const config: DbConfig = JSON.parse(configStr); + + // Use parsed config + const dbUrl = `postgres://${config.username}:${config.password}@${config.host}:${config.port}`; + + return Response.json({ connected: true }); + } catch (error) { + if (error instanceof SyntaxError) { + return new Response("Invalid config JSON", { status: 500 }); + } + throw error; + } + } +} +``` + +Store JSON secret: + +```bash +echo '{"host":"db.example.com","port":5432,"username":"app","password":"secret"}' | \ + wrangler secrets-store secret create \ + --name DB_CONFIG --scopes workers --remote +``` + +## Integration + +### Service Bindings + +Auth Worker signs JWT with Secrets Store; API Worker verifies via service binding. + +See: [workers](../workers/) for service binding patterns. + +See: [api.md](./api.md), [gotchas.md](./gotchas.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bdcc34f9e1b3ad9692f13511fe1e9e4e38166601 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/README.md @@ -0,0 +1,138 @@ +# Cloudflare Workers Smart Placement + +Automatic workload placement optimization to minimize latency by running Workers closer to backend infrastructure rather than end users. + +## Core Concept + +Smart Placement automatically analyzes Worker request duration across Cloudflare's global network and intelligently routes requests to optimal data center locations. Instead of defaulting to the location closest to the end user, Smart Placement can forward requests to locations closer to backend infrastructure when this reduces overall request duration. + +### When to Use + +**Enable Smart Placement when:** +- Worker makes multiple round trips to backend services/databases +- Backend infrastructure is geographically concentrated +- Request duration dominated by backend latency rather than network latency from user +- Running backend logic in Workers (APIs, data aggregation, SSR with DB calls) +- Worker uses `fetch` handler (not RPC methods) + +**Do NOT enable for:** +- Workers serving only static content or cached responses +- Workers without significant backend communication +- Pure edge logic (auth checks, redirects, simple transformations) +- Workers without fetch event handlers +- Workers with RPC methods or named entrypoints (only `fetch` handlers are affected) +- Pages/Assets Workers with `run_worker_first = true` (degrades asset serving) + +### Decision Tree + +``` +Does your Worker have a fetch handler? +├─ No → Smart Placement won't work (skip) +└─ Yes + │ + Does it make multiple backend calls (DB/API)? + ├─ No → Don't enable (won't help) + └─ Yes + │ + Is backend geographically concentrated? + ├─ No (globally distributed) → Probably won't help + └─ Yes or uncertain + │ + Does it serve static assets with run_worker_first=true? + ├─ Yes → Don't enable (will hurt performance) + └─ No → Enable Smart Placement + │ + After 15min, check placement_status + ├─ SUCCESS → Monitor metrics + ├─ INSUFFICIENT_INVOCATIONS → Need more traffic + └─ UNSUPPORTED_APPLICATION → Disable (hurting performance) +``` + +### Key Architecture Pattern + +**Recommended:** Split full-stack applications into separate Workers: +``` +User → Frontend Worker (at edge, close to user) + ↓ Service Binding + Backend Worker (Smart Placement enabled, close to DB/API) + ↓ + Database/Backend Service +``` + +This maintains fast, reactive frontends while optimizing backend latency. + +## Quick Start + +```jsonc +// wrangler.jsonc +{ + "placement": { + "mode": "smart" // or "off" to explicitly disable + } +} +``` + +Deploy and wait 15 minutes for analysis. Check status via API or dashboard metrics. + +**To disable:** Set `"mode": "off"` or remove `placement` field entirely (both equivalent). + +## Requirements + +- Wrangler 2.20.0+ +- Analysis time: Up to 15 minutes after enabling +- Traffic requirements: Consistent traffic from multiple global locations +- Available on all Workers plans (Free, Paid, Enterprise) + +## Placement Status Values + +```typescript +type PlacementStatus = + | undefined // Not yet analyzed + | 'SUCCESS' // Successfully optimized + | 'INSUFFICIENT_INVOCATIONS' // Not enough traffic + | 'UNSUPPORTED_APPLICATION'; // Made Worker slower (reverted) +``` + +## CLI Commands + +```bash +# Deploy with Smart Placement +wrangler deploy + +# Check placement status +curl -H "Authorization: Bearer $TOKEN" \ + https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/workers/services/$WORKER_NAME \ + | jq .result.placement_status + +# Monitor +wrangler tail your-worker-name --header cf-placement +``` + +## Reading Order + +**First time?** Start here: +1. This README - understand core concepts and when to use Smart Placement +2. [configuration.md](./configuration.md) - set up wrangler.jsonc and understand limitations +3. [patterns.md](./patterns.md) - see practical examples for your use case +4. [api.md](./api.md) - monitor and verify Smart Placement is working +5. [gotchas.md](./gotchas.md) - troubleshoot common issues + +**Quick lookup:** +- "Should I enable Smart Placement?" → See "When to Use" above +- "How do I configure it?" → [configuration.md](./configuration.md) +- "How do I split frontend/backend?" → [patterns.md](./patterns.md) +- "Why isn't it working?" → [gotchas.md](./gotchas.md) + +## In This Reference + +- [configuration.md](./configuration.md) - wrangler.jsonc setup, mode values, validation rules +- [api.md](./api.md) - Placement Status API, cf-placement header, monitoring +- [patterns.md](./patterns.md) - Frontend/backend split, database workers, SSR patterns +- [gotchas.md](./gotchas.md) - Troubleshooting INSUFFICIENT_INVOCATIONS, performance issues + +## See Also + +- [workers](../workers/) - Worker runtime and fetch handlers +- [d1](../d1/) - D1 database that benefits from Smart Placement +- [durable-objects](../durable-objects/) - Durable Objects with backend logic +- [bindings](../bindings/) - Service bindings for frontend/backend split diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/api.md new file mode 100644 index 0000000000000000000000000000000000000000..d10fed2f9575f76127f881d334830772a73296f1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/api.md @@ -0,0 +1,183 @@ +# Smart Placement API + +## Placement Status API + +Query Worker placement status via Cloudflare API: + +```bash +curl -X GET "https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/workers/services/{WORKER_NAME}" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" +``` + +Response includes `placement_status` field: + +```typescript +type PlacementStatus = + | undefined // Not yet analyzed + | 'SUCCESS' // Successfully optimized + | 'INSUFFICIENT_INVOCATIONS' // Not enough traffic + | 'UNSUPPORTED_APPLICATION'; // Made Worker slower (reverted) +``` + +## Status Meanings + +**`undefined` (not present)** +- Worker not yet analyzed +- Always runs at default edge location closest to user + +**`SUCCESS`** +- Analysis complete, Smart Placement active +- Worker runs in optimal location (may be edge or remote) + +**`INSUFFICIENT_INVOCATIONS`** +- Not enough requests to make placement decision +- Requires consistent multi-region traffic +- Always runs at default edge location + +**`UNSUPPORTED_APPLICATION`** (rare, <1% of Workers) +- Smart Placement made Worker slower +- Placement decision reverted +- Always runs at edge location +- Won't be re-analyzed until redeployed + +## cf-placement Header (Beta) + +Smart Placement adds response header indicating routing decision: + +```typescript +// Remote placement (Smart Placement routed request) +"cf-placement: remote-LHR" // Routed to London + +// Local placement (default edge routing) +"cf-placement: local-EWR" // Stayed at Newark edge +``` + +Format: `{placement-type}-{IATA-code}` +- `remote-*` = Smart Placement routed to remote location +- `local-*` = Stayed at default edge location +- IATA code = nearest airport to data center + +**Warning:** Beta feature, may be removed before GA. + +## Detecting Smart Placement in Code + +**Note:** `cf-placement` header is a beta feature and may change or be removed. + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const placementHeader = request.headers.get('cf-placement'); + + if (placementHeader?.startsWith('remote-')) { + const location = placementHeader.split('-')[1]; + console.log(`Smart Placement routed to ${location}`); + } else if (placementHeader?.startsWith('local-')) { + const location = placementHeader.split('-')[1]; + console.log(`Running at edge location ${location}`); + } + + return new Response('OK'); + } +} satisfies ExportedHandler; +``` + +## Request Duration Metrics + +Available in Cloudflare dashboard when Smart Placement enabled: + +**Workers & Pages → [Your Worker] → Metrics → Request Duration** + +Shows histogram comparing: +- Request duration WITH Smart Placement (99% of traffic) +- Request duration WITHOUT Smart Placement (1% baseline) + +**Request Duration vs Execution Duration:** +- **Request duration:** Total time from request arrival to response delivery (includes network latency) +- **Execution duration:** Time Worker code actively executing (excludes network waits) + +Use request duration to measure Smart Placement impact. + +### Interpreting Metrics + +| Metric Comparison | Interpretation | Action | +|-------------------|----------------|--------| +| WITH < WITHOUT | Smart Placement helping | Keep enabled | +| WITH ≈ WITHOUT | Neutral impact | Consider disabling to free resources | +| WITH > WITHOUT | Smart Placement hurting | Disable with `mode: "off"` | + +**Why Smart Placement might hurt performance:** +- Worker primarily serves static assets or cached content +- Backend services are globally distributed (no single optimal location) +- Worker has minimal backend communication +- Using Pages with `assets.run_worker_first = true` + +**Typical improvements when Smart Placement helps:** +- 20-50% reduction in request duration for database-heavy Workers +- 30-60% reduction for Workers making multiple backend API calls +- Larger improvements when backend is geographically concentrated + +## Monitoring Commands + +```bash +# Tail Worker logs +wrangler tail your-worker-name + +# Tail with filters +wrangler tail your-worker-name --status error +wrangler tail your-worker-name --header cf-placement + +# Check placement status via API +curl -H "Authorization: Bearer $TOKEN" \ + https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/workers/services/$WORKER_NAME \ + | jq .result.placement_status +``` + +## TypeScript Types + +```typescript +// Placement status returned by API (field may be absent) +type PlacementStatus = + | 'SUCCESS' + | 'INSUFFICIENT_INVOCATIONS' + | 'UNSUPPORTED_APPLICATION' + | undefined; + +// Placement configuration in wrangler.jsonc +type PlacementMode = 'smart' | 'off'; + +interface PlacementConfig { + mode: PlacementMode; + // Legacy fields (deprecated/removed): + // hint?: string; // REMOVED - no longer supported +} + +// Explicit placement (separate feature from Smart Placement) +interface ExplicitPlacementConfig { + region?: string; + host?: string; + hostname?: string; + // Cannot combine with mode field +} + +// Worker metadata from API response +interface WorkerMetadata { + placement?: PlacementConfig | ExplicitPlacementConfig; + placement_status?: PlacementStatus; +} + +// Service Binding for backend Worker +interface Env { + BACKEND_SERVICE: Fetcher; // Service Binding to backend Worker + DATABASE: D1Database; +} + +// Example Worker with Service Binding +export default { + async fetch(request: Request, env: Env): Promise { + // Forward to backend Worker with Smart Placement enabled + const response = await env.BACKEND_SERVICE.fetch(request); + return response; + } +} satisfies ExportedHandler; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..59d5ea13b7492a5fe97554df55bc94230c6a955c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/configuration.md @@ -0,0 +1,196 @@ +# Smart Placement Configuration + +## wrangler.jsonc Setup + +```jsonc +{ + "$schema": "./node_modules/wrangler/config-schema.json", + "placement": { + "mode": "smart" + } +} +``` + +## Placement Mode Values + +| Mode | Behavior | +|------|----------| +| `"smart"` | Enable Smart Placement - automatic optimization based on traffic analysis | +| `"off"` | Explicitly disable Smart Placement - always run at edge closest to user | +| Not specified | Default behavior - run at edge closest to user (same as `"off"`) | + +**Note:** Smart Placement vs Explicit Placement are separate features. Smart Placement (`mode: "smart"`) uses automatic analysis. For manual placement control, see explicit placement options (`region`, `host`, `hostname` fields - not covered in this reference). + +## Frontend + Backend Split Configuration + +### Frontend Worker (No Smart Placement) + +```jsonc +// frontend-worker/wrangler.jsonc +{ + "name": "frontend", + "main": "frontend-worker.ts", + // No "placement" - runs at edge + "services": [ + { + "binding": "BACKEND", + "service": "backend-api" + } + ] +} +``` + +### Backend Worker (Smart Placement Enabled) + +```jsonc +// backend-api/wrangler.jsonc +{ + "name": "backend-api", + "main": "backend-worker.ts", + "placement": { + "mode": "smart" + }, + "d1_databases": [ + { + "binding": "DATABASE", + "database_id": "xxx" + } + ] +} +``` + +## Requirements & Limitations + +### Requirements +- **Wrangler version:** 2.20.0+ +- **Analysis time:** Up to 15 minutes +- **Traffic requirements:** Consistent multi-location traffic +- **Workers plan:** All plans (Free, Paid, Enterprise) + +### What Smart Placement Affects + +**CRITICAL LIMITATION - Smart Placement ONLY Affects `fetch` Handlers:** + +Smart Placement is fundamentally limited to Workers with default `fetch` handlers. This is a key architectural constraint. + +- ✅ **Affects:** `fetch` event handlers ONLY (the default export's fetch method) +- ❌ **Does NOT affect:** + - RPC methods (Service Bindings with `WorkerEntrypoint` - see example below) + - Named entrypoints (exports other than `default`) + - Workers without `fetch` handlers + - Queue consumers, scheduled handlers, or other event types + +**Example - Smart Placement ONLY affects `fetch`:** +```typescript +// ✅ Smart Placement affects this: +export default { + async fetch(request: Request, env: Env): Promise { + // This runs close to backend when Smart Placement enabled + const data = await env.DATABASE.prepare('SELECT * FROM users').all(); + return Response.json(data); + } +} + +// ❌ Smart Placement DOES NOT affect these: +export class MyRPC extends WorkerEntrypoint { + async myMethod() { + // This ALWAYS runs at edge, Smart Placement has NO EFFECT + const data = await this.env.DATABASE.prepare('SELECT * FROM users').all(); + return data; + } +} + +export async function scheduled(event: ScheduledEvent, env: Env) { + // NOT affected by Smart Placement +} +``` + +**Consequence:** If your backend logic uses RPC methods (`WorkerEntrypoint`), Smart Placement cannot optimize those calls. You must use fetch-based patterns for Smart Placement to work. + +**Solution:** Convert RPC methods to fetch endpoints, or use a wrapper Worker with `fetch` handler that calls your backend RPC (though this adds latency). + +### Baseline Traffic +Smart Placement automatically routes 1% of requests WITHOUT optimization as baseline for performance comparison. + +### Validation Rules + +**Mutually exclusive fields:** +- `mode` cannot be used with explicit placement fields (`region`, `host`, `hostname`) +- Choose either Smart Placement OR explicit placement, not both + +```jsonc +// ✅ Valid - Smart Placement +{ "placement": { "mode": "smart" } } + +// ✅ Valid - Explicit Placement (different feature) +{ "placement": { "region": "us-east1" } } + +// ❌ Invalid - Cannot combine +{ "placement": { "mode": "smart", "region": "us-east1" } } +``` + +## Dashboard Configuration + +**Workers & Pages** → Select Worker → **Settings** → **General** → **Placement: Smart** → Wait 15min → Check **Metrics** + +## TypeScript Types + +```typescript +interface Env { + BACKEND: Fetcher; + DATABASE: D1Database; +} + +export default { + async fetch(request: Request, env: Env): Promise { + const data = await env.DATABASE.prepare('SELECT * FROM table').all(); + return Response.json(data); + } +} satisfies ExportedHandler; +``` + +## Cloudflare Pages/Assets Warning + +**CRITICAL PERFORMANCE ISSUE:** Enabling Smart Placement with `assets.run_worker_first = true` in Pages projects **severely degrades asset serving performance**. This is one of the most common misconfigurations. + +**Why this is bad:** +- Smart Placement routes ALL requests (including static assets) away from edge to remote locations +- Static assets (HTML, CSS, JS, images) should ALWAYS be served from edge closest to user +- Result: 2-5x slower asset loading times, poor user experience + +**Problem:** Smart Placement routes asset requests away from edge, but static assets should always be served from edge closest to user. + +**Solutions (in order of preference):** +1. **Recommended:** Split into separate Workers (frontend at edge + backend with Smart Placement) +2. Set `"mode": "off"` to explicitly disable Smart Placement for Pages/Assets Workers +3. Use `assets.run_worker_first = false` (serves assets first, bypasses Worker for static content) + +```jsonc +// ❌ BAD - Degrades asset performance by 2-5x +{ + "name": "pages-app", + "placement": { "mode": "smart" }, + "assets": { "run_worker_first": true } +} + +// ✅ GOOD - Frontend at edge, backend optimized +// frontend-worker/wrangler.jsonc +{ + "name": "frontend", + "assets": { "run_worker_first": true } + // No placement - runs at edge +} + +// backend-worker/wrangler.jsonc +{ + "name": "backend-api", + "placement": { "mode": "smart" }, + "d1_databases": [{ "binding": "DB", "database_id": "xxx" }] +} +``` + +**Key takeaway:** Never enable Smart Placement on Workers that serve static assets with `run_worker_first = true`. + +## Local Development + +Smart Placement does NOT work in `wrangler dev` (local only). Test by deploying: `wrangler deploy --env staging` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..dc94e9b3b7d613744465e43aee3f31037eabf2b6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/gotchas.md @@ -0,0 +1,174 @@ +# Smart Placement Gotchas + +## Common Errors + +### "INSUFFICIENT_INVOCATIONS" + +**Cause:** Not enough traffic for Smart Placement to analyze +**Solution:** +- Ensure Worker receives consistent global traffic +- Wait longer (analysis takes up to 15 minutes) +- Send test traffic from multiple global locations +- Check Worker has fetch event handler + +### "UNSUPPORTED_APPLICATION" + +**Cause:** Smart Placement made Worker slower rather than faster +**Reasons:** +- Worker doesn't make backend calls (runs faster at edge) +- Backend calls are cached (network latency to user more important) +- Backend service has good global distribution +- Worker serves static assets or Pages content + +**Solutions:** +- Disable Smart Placement: `{ "placement": { "mode": "off" } }` +- Review whether Worker actually benefits from Smart Placement +- Consider caching strategy to reduce backend calls +- For Pages/Assets Workers, use separate backend Worker with Smart Placement + +### "No request duration metrics" + +**Cause:** Smart Placement not enabled, insufficient time passed, insufficient traffic, or analysis incomplete +**Solution:** +- Ensure Smart Placement enabled in config +- Wait 15+ minutes after deployment +- Verify Worker has sufficient traffic +- Check `placement_status` is `SUCCESS` + +### "cf-placement header missing" + +**Cause:** Smart Placement not enabled, beta feature removed, or Worker not analyzed yet +**Solution:** Verify Smart Placement enabled, wait for analysis (15min), check if beta feature still available + +## Pages/Assets + Smart Placement Performance Degradation + +**Problem:** Static assets load 2-5x slower when Smart Placement enabled with `run_worker_first = true`. + +**Cause:** Smart Placement routes ALL requests (including static assets like HTML, CSS, JS, images) to remote locations. Static content should ALWAYS be served from edge closest to user. + +**Solution:** Split into separate Workers OR disable Smart Placement: +```jsonc +// ❌ BAD - Assets routed away from user +{ + "name": "pages-app", + "placement": { "mode": "smart" }, + "assets": { "run_worker_first": true } +} + +// ✅ GOOD - Assets at edge, API optimized +// frontend/wrangler.jsonc +{ + "name": "frontend", + "assets": { "run_worker_first": true } + // No placement field - stays at edge +} + +// backend/wrangler.jsonc +{ + "name": "backend-api", + "placement": { "mode": "smart" } +} +``` + +This is one of the most common and impactful Smart Placement misconfigurations. + +## Monolithic Full-Stack Worker + +**Problem:** Frontend and backend logic in single Worker with Smart Placement enabled. + +**Cause:** Smart Placement optimizes for backend latency but increases user-facing response time. + +**Solution:** Split into two Workers: +```jsonc +// frontend/wrangler.jsonc +{ + "name": "frontend", + "placement": { "mode": "off" }, // Explicit: stay at edge + "services": [{ "binding": "BACKEND", "service": "backend-api" }] +} + +// backend/wrangler.jsonc +{ + "name": "backend-api", + "placement": { "mode": "smart" }, + "d1_databases": [{ "binding": "DB", "database_id": "xxx" }] +} +``` + +## Local Development Confusion + +**Issue:** Smart Placement doesn't work in `wrangler dev`. + +**Explanation:** Smart Placement only activates in production deployments, not local development. + +**Solution:** Test Smart Placement in staging environment: `wrangler deploy --env staging` + +## Baseline Traffic & Analysis Time + +**Note:** Smart Placement routes 1% of requests WITHOUT optimization for comparison (expected). + +**Analysis time:** Up to 15 minutes. During analysis, Worker runs at edge. Monitor `placement_status`. + +## RPC Methods Not Affected (Critical Limitation) + +**Problem:** Enabled Smart Placement on backend but RPC calls still slow. + +**Cause:** Smart Placement ONLY affects `fetch` handlers. RPC methods (Service Bindings with `WorkerEntrypoint`) are NEVER affected. + +**Why:** RPC bypasses `fetch` handler - Smart Placement can only route `fetch` requests. + +**Solution:** Convert to fetch-based Service Bindings: + +```typescript +// ❌ RPC - Smart Placement has NO EFFECT +export class BackendRPC extends WorkerEntrypoint { + async getData() { + // ALWAYS runs at edge + return await this.env.DATABASE.prepare('SELECT * FROM table').all(); + } +} + +// ✅ Fetch - Smart Placement WORKS +export default { + async fetch(request: Request, env: Env): Promise { + // Runs close to DATABASE when Smart Placement enabled + const data = await env.DATABASE.prepare('SELECT * FROM table').all(); + return Response.json(data); + } +} +``` + +## Requirements + +- **Wrangler 2.20.0+** required +- **Consistent multi-region traffic** needed for analysis +- **Only affects fetch handlers** - RPC methods and named entrypoints not affected + +## Limits + +| Resource/Limit | Value | Notes | +|----------------|-------|-------| +| Analysis time | Up to 15 minutes | After enabling | +| Baseline traffic | 1% | Routed without optimization | +| Min Wrangler version | 2.20.0+ | Required | +| Traffic requirement | Multi-region | Consistent needed | + +## Disabling Smart Placement + +```jsonc +{ "placement": { "mode": "off" } } // Explicit disable +// OR remove "placement" field entirely (same effect) +``` + +Both behaviors identical - Worker runs at edge closest to user. + +## When NOT to Use Smart Placement + +- Workers serving only static content or cached responses +- Workers without significant backend communication +- Pure edge logic (auth checks, redirects, simple transformations) +- Workers without fetch event handlers +- Pages/Assets Workers with `run_worker_first = true` +- Workers using RPC methods instead of fetch handlers + +These scenarios won't benefit and may perform worse with Smart Placement. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..36df06f3de93ab7412c13f8030fd674a9ca3971a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/smart-placement/patterns.md @@ -0,0 +1,183 @@ +# Smart Placement Patterns + +## Backend Worker with Database Access + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const user = await env.DATABASE.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first(); + const orders = await env.DATABASE.prepare('SELECT * FROM orders WHERE user_id = ?').bind(userId).all(); + return Response.json({ user, orders }); + } +}; +``` + +```jsonc +{ "placement": { "mode": "smart" }, "d1_databases": [{ "binding": "DATABASE", "database_id": "xxx" }] } +``` + +## Frontend + Backend Split (Service Bindings) + +**Frontend:** Runs at edge for fast user response +**Backend:** Smart Placement runs close to database + +```typescript +// Frontend Worker - routes requests to backend +interface Env { + BACKEND: Fetcher; // Service Binding to backend Worker +} + +export default { + async fetch(request: Request, env: Env): Promise { + if (new URL(request.url).pathname.startsWith('/api/')) { + return env.BACKEND.fetch(request); // Forward to backend + } + return new Response('Frontend content'); + } +}; + +// Backend Worker - database operations +interface BackendEnv { + DATABASE: D1Database; +} + +export default { + async fetch(request: Request, env: BackendEnv): Promise { + const data = await env.DATABASE.prepare('SELECT * FROM table').all(); + return Response.json(data); + } +}; +``` + +**CRITICAL:** Use fetch-based Service Bindings (shown above). If using RPC with `WorkerEntrypoint`, Smart Placement will NOT optimize those method calls - only `fetch` handlers are affected. + +**RPC vs Fetch - CRITICAL:** Smart Placement ONLY works with fetch-based bindings, NOT RPC. + +```typescript +// ❌ RPC - Smart Placement has NO EFFECT on backend RPC methods +export class BackendRPC extends WorkerEntrypoint { + async getData() { + // ALWAYS runs at edge, Smart Placement ignored + return await this.env.DATABASE.prepare('SELECT * FROM table').all(); + } +} + +// ✅ Fetch - Smart Placement WORKS +export default { + async fetch(request: Request, env: Env): Promise { + // Runs close to DATABASE when Smart Placement enabled + const data = await env.DATABASE.prepare('SELECT * FROM table').all(); + return Response.json(data); + } +}; +``` + +## External API Integration + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const apiUrl = 'https://api.partner.com'; + const headers = { 'Authorization': `Bearer ${env.API_KEY}` }; + + const [profile, transactions] = await Promise.all([ + fetch(`${apiUrl}/profile`, { headers }), + fetch(`${apiUrl}/transactions`, { headers }) + ]); + + return Response.json({ + profile: await profile.json(), + transactions: await transactions.json() + }); + } +}; +``` + +## SSR / API Gateway Pattern + +```typescript +// Frontend (edge) - auth/routing close to user +export default { + async fetch(request: Request, env: Env) { + if (!request.headers.get('Authorization')) { + return new Response('Unauthorized', { status: 401 }); + } + const data = await env.BACKEND.fetch(request); + return new Response(renderPage(await data.json()), { + headers: { 'Content-Type': 'text/html' } + }); + } +}; + +// Backend (Smart Placement) - DB operations close to data +export default { + async fetch(request: Request, env: Env) { + const data = await env.DATABASE.prepare('SELECT * FROM pages WHERE id = ?').bind(pageId).first(); + return Response.json(data); + } +}; +``` + +## Durable Objects with Smart Placement + +**Key principle:** Smart Placement does NOT control WHERE Durable Objects run. DOs always run in their designated region (based on jurisdiction or smart location hints). + +**What Smart Placement DOES affect:** The location of the coordinator Worker's `fetch` handler that makes calls to multiple DOs. + +**Pattern:** Enable Smart Placement on coordinator Worker that aggregates data from multiple DOs: + +```typescript +// Worker with Smart Placement - aggregates data from multiple DOs +export default { + async fetch(request: Request, env: Env): Promise { + const userId = new URL(request.url).searchParams.get('user'); + + // Get DO stubs + const userDO = env.USER_DO.get(env.USER_DO.idFromName(userId)); + const analyticsID = env.ANALYTICS_DO.idFromName(`analytics-${userId}`); + const analyticsDO = env.ANALYTICS_DO.get(analyticsID); + + // Fetch from multiple DOs + const [userData, analyticsData] = await Promise.all([ + userDO.fetch(new Request('https://do/profile')), + analyticsDO.fetch(new Request('https://do/stats')) + ]); + + return Response.json({ + user: await userData.json(), + analytics: await analyticsData.json() + }); + } +}; +``` + +```jsonc +// wrangler.jsonc +{ + "placement": { "mode": "smart" }, + "durable_objects": { + "bindings": [ + { "name": "USER_DO", "class_name": "UserDO" }, + { "name": "ANALYTICS_DO", "class_name": "AnalyticsDO" } + ] + } +} +``` + +**When this helps:** +- Worker's `fetch` handler runs closer to DO regions, reducing network latency for multiple DO calls +- Most beneficial when DOs are geographically concentrated or in specific jurisdictions +- Helps when coordinator makes many sequential or parallel DO calls + +**When this DOESN'T help:** +- DOs are globally distributed (no single optimal Worker location) +- Worker only calls a single DO +- DO calls are infrequent or cached + +## Best Practices + +- Split full-stack apps: frontend at edge, backend with Smart Placement +- Use fetch-based Service Bindings (not RPC) +- Enable for backend logic: APIs, data aggregation, DB operations +- Don't enable for: static content, edge logic, RPC methods, Pages with `run_worker_first` +- Wait 15+ min for analysis, verify `placement_status = SUCCESS` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a09a1c41230349545de1ff258164a041670f8ca8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/README.md @@ -0,0 +1,68 @@ +# Cloudflare Snippets Skill Reference + +## Description +Expert guidance for **Cloudflare Snippets ONLY** - a lightweight JavaScript-based edge logic platform for modifying HTTP requests and responses. Snippets run as part of the Ruleset Engine and are included at no additional cost on paid plans (Pro, Business, Enterprise). + +## What Are Snippets? +Snippets are JavaScript functions executed at the edge as part of Cloudflare's Ruleset Engine. Key characteristics: +- **Execution time**: 5ms CPU limit per request +- **Size limit**: 32KB per snippet +- **Runtime**: V8 isolate (subset of Workers APIs) +- **Subrequests**: 2-5 fetch calls depending on plan +- **Cost**: Included with Pro/Business/Enterprise plans + +## Snippets vs Workers Decision Matrix + +| Factor | Choose Snippets If... | Choose Workers If... | +|--------|----------------------|---------------------| +| **Complexity** | Simple request/response modifications | Complex business logic, routing, middleware | +| **Execution time** | <5ms sufficient | Need >5ms or variable time | +| **Subrequests** | 2-5 fetch calls sufficient | Need >5 subrequests or complex orchestration | +| **Code size** | <32KB sufficient | Need >32KB or npm dependencies | +| **Cost** | Want zero additional cost | Can afford $5/mo + usage | +| **APIs** | Need basic fetch, headers, URL | Need KV, D1, R2, Durable Objects, cron triggers | +| **Deployment** | Need rule-based triggers | Want custom routing logic | + +**Rule of thumb**: Use Snippets for modifications, Workers for applications. + +## Execution Model +1. Request arrives at Cloudflare edge +2. Ruleset Engine evaluates snippet rules (filter expressions) +3. If rule matches, snippet executes within 5ms limit +4. Modified request/response continues through pipeline +5. Response returned to client + +Snippets execute synchronously in the request path - performance is critical. + +## Reading Order +1. **[configuration.md](configuration.md)** - Start here: setup, deployment methods (Dashboard/API/Terraform) +2. **[api.md](api.md)** - Core APIs: Request, Response, headers, `request.cf` properties +3. **[patterns.md](patterns.md)** - Real-world examples: geo-routing, A/B tests, security headers +4. **[gotchas.md](gotchas.md)** - Troubleshooting: common errors, performance tips, API limitations + +## In This Reference + +- **[configuration.md](configuration.md)** - Setup, deployment, configuration +- **[api.md](api.md)** - API endpoints, methods, interfaces +- **[patterns.md](patterns.md)** - Common patterns, use cases, examples +- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations + +## Quick Start +```javascript +// Snippet: Add security headers +export default { + async fetch(request) { + const response = await fetch(request); + const newResponse = new Response(response.body, response); + newResponse.headers.set("X-Frame-Options", "DENY"); + newResponse.headers.set("X-Content-Type-Options", "nosniff"); + return newResponse; + } +} +``` + +Deploy via Dashboard (Rules → Snippets) or API/Terraform. See configuration.md for details. + +## See Also + +- [Cloudflare Docs](https://developers.cloudflare.com/rules/snippets/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/api.md new file mode 100644 index 0000000000000000000000000000000000000000..14266f0f43f2fddcd7071df178a60e8aff88bab0 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/api.md @@ -0,0 +1,198 @@ +# Snippets API Reference + +## Request Object + +### HTTP Properties +```javascript +request.method // GET, POST, PUT, DELETE, etc. +request.url // Full URL string +request.headers // Headers object +request.body // ReadableStream (for POST/PUT) +request.cf // Cloudflare properties (see below) +``` + +### URL Operations +```javascript +const url = new URL(request.url); +url.hostname // "example.com" +url.pathname // "/path/to/page" +url.search // "?query=value" +url.searchParams.get("q") // "value" +url.searchParams.set("q", "new") +url.searchParams.delete("q") +``` + +### Header Operations +```javascript +// Read headers +request.headers.get("User-Agent") +request.headers.has("Authorization") +request.headers.getSetCookie() // Get all Set-Cookie headers + +// Modify headers (create new request) +const modifiedRequest = new Request(request); +modifiedRequest.headers.set("X-Custom", "value") +modifiedRequest.headers.delete("X-Remove") +``` + +### Cloudflare Properties (`request.cf`) +Access Cloudflare-specific metadata about the request: + +```javascript +// Geolocation +request.cf.city // "San Francisco" +request.cf.continent // "NA" +request.cf.country // "US" +request.cf.region // "California" or "CA" +request.cf.regionCode // "CA" +request.cf.postalCode // "94102" +request.cf.latitude // "37.7749" +request.cf.longitude // "-122.4194" +request.cf.timezone // "America/Los_Angeles" +request.cf.metroCode // "807" (DMA code) + +// Network +request.cf.colo // "SFO" (airport code of datacenter) +request.cf.asn // 13335 (ASN number) +request.cf.asOrganization // "Cloudflare, Inc." + +// Bot Management (if enabled) +request.cf.botManagement.score // 1-99 (1=bot, 99=human) +request.cf.botManagement.verified_bot // true/false +request.cf.botManagement.static_resource // true/false + +// TLS/HTTP version +request.cf.tlsVersion // "TLSv1.3" +request.cf.tlsCipher // "AEAD-AES128-GCM-SHA256" +request.cf.httpProtocol // "HTTP/2" + +// Request metadata +request.cf.requestPriority // "weight=192;exclusive=0" +``` + +**Use cases**: Geo-routing, bot detection, security decisions, analytics. + +## Response Object + +### Response Constructors +```javascript +// Plain text +new Response("Hello", { status: 200 }) + +// JSON +Response.json({ key: "value" }, { status: 200 }) + +// HTML +new Response("

Hi

", { + status: 200, + headers: { "Content-Type": "text/html" } +}) + +// Redirect +Response.redirect("https://example.com", 301) // or 302 + +// Stream (pass through) +new Response(response.body, response) +``` + +### Response Headers +```javascript +// Create modified response +const newResponse = new Response(response.body, response); + +// Set/modify headers +newResponse.headers.set("X-Custom", "value") +newResponse.headers.append("Set-Cookie", "session=abc; Path=/") +newResponse.headers.delete("Server") + +// Common headers +newResponse.headers.set("Cache-Control", "public, max-age=3600") +newResponse.headers.set("Content-Type", "application/json") +``` + +### Response Properties +```javascript +response.status // 200, 404, 500, etc. +response.statusText // "OK", "Not Found", etc. +response.headers // Headers object +response.body // ReadableStream +response.ok // true if status 200-299 +response.redirected // true if redirected +``` + +## REST API Operations + +### List Snippets +```bash +GET /zones/{zone_id}/snippets +``` + +### Get Snippet +```bash +GET /zones/{zone_id}/snippets/{snippet_name} +``` + +### Create/Update Snippet +```bash +PUT /zones/{zone_id}/snippets/{snippet_name} +Content-Type: multipart/form-data + +files=@snippet.js +metadata={"main_module":"snippet.js"} +``` + +### Delete Snippet +```bash +DELETE /zones/{zone_id}/snippets/{snippet_name} +``` + +### List Snippet Rules +```bash +GET /zones/{zone_id}/rulesets/phases/http_request_snippets/entrypoint +``` + +### Update Snippet Rules +```bash +PUT /zones/{zone_id}/snippets/snippet_rules +Content-Type: application/json + +{ + "rules": [{ + "description": "Apply snippet", + "enabled": true, + "expression": "http.host eq \"example.com\"", + "snippet_name": "my_snippet" + }] +} +``` + +## Available APIs in Snippets + +### ✅ Supported +- `fetch()` - HTTP requests (2-5 subrequests per plan) +- `Request` / `Response` - Standard Web APIs +- `URL` / `URLSearchParams` - URL manipulation +- `Headers` - Header manipulation +- `TextEncoder` / `TextDecoder` - Text encoding +- `crypto.subtle` - Web Crypto API (hashing, signing) +- `crypto.randomUUID()` - UUID generation + +### ❌ Not Supported in Snippets +- `caches` API - Not available (use Workers) +- `KV`, `D1`, `R2` - Storage APIs (use Workers) +- `Durable Objects` - Stateful objects (use Workers) +- `WebSocket` - WebSocket upgrades (use Workers) +- `HTMLRewriter` - HTML parsing (use Workers) +- `import` statements - No module imports +- `addEventListener` - Use `export default { async fetch() {}` pattern + +## Snippet Structure +```javascript +export default { + async fetch(request) { + // Your logic here + const response = await fetch(request); + return response; // or modified response + } +} +``` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..159f0cd30e73ab2b4b6b5cfdfd52a55d6bae7722 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/configuration.md @@ -0,0 +1,227 @@ +# Snippets Configuration Guide + +## Configuration Methods + +### 1. Dashboard (GUI) +**Best for**: Quick tests, single snippets, visual rule building + +``` +1. Go to zone → Rules → Snippets +2. Click "Create Snippet" or select template +3. Enter snippet name (a-z, 0-9, _ only, cannot change later) +4. Write JavaScript code (32KB max) +5. Configure snippet rule: + - Expression Builder (visual) or Expression Editor (text) + - Use Ruleset Engine filter expressions +6. Test with Preview/HTTP tabs +7. Deploy or Save as Draft +``` + +### 2. REST API +**Best for**: CI/CD, automation, programmatic management + +```bash +# Create/update snippet +curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/snippets/$SNIPPET_NAME" \ + --request PUT \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + --form "files=@example.js" \ + --form "metadata={\"main_module\": \"example.js\"}" + +# Create snippet rule +curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/snippets/snippet_rules" \ + --request PUT \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + --header "Content-Type: application/json" \ + --data '{ + "rules": [ + { + "description": "Trigger snippet on /api paths", + "enabled": true, + "expression": "starts_with(http.request.uri.path, \"/api/\")", + "snippet_name": "api_snippet" + } + ] + }' + +# List snippets +curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/snippets" \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" + +# Delete snippet +curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/snippets/$SNIPPET_NAME" \ + --request DELETE \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" +``` + +### 3. Terraform +**Best for**: Infrastructure-as-code, multi-zone deployments + +```hcl +# Configure Terraform provider +terraform { + required_providers { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.0" + } + } +} + +provider "cloudflare" { + api_token = var.cloudflare_api_token +} + +# Create snippet +resource "cloudflare_snippet" "security_headers" { + zone_id = var.zone_id + name = "security_headers" + + main_module = "security_headers.js" + files { + name = "security_headers.js" + content = file("${path.module}/snippets/security_headers.js") + } +} + +# Create snippet rule +resource "cloudflare_snippet_rules" "security_rules" { + zone_id = var.zone_id + + rules { + description = "Apply security headers to all requests" + enabled = true + expression = "true" + snippet_name = cloudflare_snippet.security_headers.name + } +} +``` + +### 4. Pulumi +**Best for**: Multi-cloud IaC, TypeScript/Python/Go workflows + +```typescript +import * as cloudflare from "@pulumi/cloudflare"; +import * as fs from "fs"; + +// Create snippet +const securitySnippet = new cloudflare.Snippet("security-headers", { + zoneId: zoneId, + name: "security_headers", + mainModule: "security_headers.js", + files: [{ + name: "security_headers.js", + content: fs.readFileSync("./snippets/security_headers.js", "utf8"), + }], +}); + +// Create snippet rule +const snippetRule = new cloudflare.SnippetRules("security-rules", { + zoneId: zoneId, + rules: [{ + description: "Apply security headers", + enabled: true, + expression: "true", + snippetName: securitySnippet.name, + }], +}); +``` + +## Filter Expressions + +Snippets use Cloudflare's Ruleset Engine expression language to determine when to execute. + +### Common Expression Patterns + +```javascript +// Host matching +http.host eq "example.com" +http.host in {"example.com" "www.example.com"} +http.host contains "example" + +// Path matching +http.request.uri.path eq "/api/users" +starts_with(http.request.uri.path, "/api/") +ends_with(http.request.uri.path, ".json") +matches(http.request.uri.path, "^/api/v[0-9]+/") + +// Query parameters +http.request.uri.query contains "debug=true" + +// Headers +http.headers["user-agent"] contains "Mobile" +http.headers["accept-language"] eq "en-US" + +// Cookies +http.cookie contains "session=" + +// Geolocation +ip.geoip.country eq "US" +ip.geoip.continent eq "EU" + +// Bot detection (requires Bot Management) +cf.bot_management.score lt 30 + +// Method +http.request.method eq "POST" +http.request.method in {"POST" "PUT" "PATCH"} + +// Combine with logical operators +http.host eq "example.com" and starts_with(http.request.uri.path, "/api/") +ip.geoip.country eq "US" or ip.geoip.country eq "CA" +not http.headers["user-agent"] contains "bot" +``` + +### Expression Functions + +| Function | Example | Description | +|----------|---------|-------------| +| `starts_with()` | `starts_with(http.request.uri.path, "/api/")` | Check prefix | +| `ends_with()` | `ends_with(http.request.uri.path, ".json")` | Check suffix | +| `contains()` | `contains(http.headers["user-agent"], "Mobile")` | Check substring | +| `matches()` | `matches(http.request.uri.path, "^/api/")` | Regex match | +| `lower()` | `lower(http.host) eq "example.com"` | Convert to lowercase | +| `upper()` | `upper(http.headers["x-api-key"])` | Convert to uppercase | +| `len()` | `len(http.request.uri.path) gt 100` | String length | + +## Deployment Workflow + +### Development +1. Write snippet code locally +2. Test syntax with `node snippet.js` or TypeScript compiler +3. Deploy to Dashboard or use API with `Save as Draft` +4. Test with Preview/HTTP tabs in Dashboard +5. Enable rule when ready + +### Production +1. Store snippet code in version control +2. Use Terraform/Pulumi for reproducible deployments +3. Deploy to staging zone first +4. Test with real traffic (use low-traffic subdomain) +5. Apply to production zone +6. Monitor with Analytics/Logpush + +## Limits & Requirements + +| Resource | Limit | Notes | +|----------|-------|-------| +| Snippet size | 32 KB | Per snippet, compressed | +| Snippet name | 64 chars | `a-z`, `0-9`, `_` only, immutable | +| Snippets per zone | 20 | Soft limit, contact support for more | +| Rules per zone | 20 | One rule per snippet typical | +| Expression length | 4096 chars | Per rule expression | + +## Authentication + +### API Token (Recommended) +```bash +# Create token at: https://dash.cloudflare.com/profile/api-tokens +# Required permissions: Zone.Snippets:Edit, Zone.Rules:Edit +export CLOUDFLARE_API_TOKEN="your_token_here" +``` + +### API Key (Legacy) +```bash +export CLOUDFLARE_EMAIL="your@email.com" +export CLOUDFLARE_API_KEY="your_global_api_key" +``` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..832077e39f711cbe15e70f215be3538f30fa7db9 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/gotchas.md @@ -0,0 +1,86 @@ +# Gotchas & Best Practices + +## Common Errors + +### 1000: "Snippet execution failed" +Runtime error or syntax error. Wrap code in try/catch: +```javascript +try { return await fetch(request); } +catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }); } +``` + +### 1100: "Exceeded execution limit" +Code takes >5ms CPU. Simplify logic or move to Workers. + +### 1201: "Multiple origin fetches" +Call `fetch(request)` exactly once: +```javascript +// ❌ Multiple origin fetches +const r1 = await fetch(request); const r2 = await fetch(request); +// ✅ Single fetch, reuse response +const response = await fetch(request); +``` + +### 1202: "Subrequest limit exceeded" +Pro: 2 subrequests, Business/Enterprise: 5. Reduce fetch calls. + +### "Cannot set property on immutable object" +Clone before modifying: +```javascript +const modifiedRequest = new Request(request); +modifiedRequest.headers.set("X-Custom", "value"); +``` + +### "caches is not defined" +Cache API NOT available in Snippets. Use Workers. + +### "Module not found" +Snippets don't support `import`. Use inline code or Workers. + +## Best Practices + +### Performance +- Keep code <10KB (32KB limit) +- Optimize for 5ms CPU +- Clone only when modifying +- Minimize subrequests + +### Security +- Validate all inputs +- Use Web Crypto API for hashing +- Sanitize headers before origin +- Don't log secrets + +### Debugging +```javascript +newResponse.headers.set("X-Debug-Country", request.cf.country); +``` +```bash +curl -H "X-Test: true" https://example.com -v +``` + +## Available APIs + +**✅ Available:** `fetch()`, `Request`, `Response`, `Headers`, `URL`, `crypto.subtle`, `crypto.randomUUID()`, `atob()`/`btoa()`, `JSON` + +**❌ NOT Available:** `caches`, `KV`, `D1`, `R2`, `Durable Objects`, `WebSocket`, `HTMLRewriter`, `import`, Node.js APIs + +## Limits + +| Resource | Limit | +|----------|-------| +| Snippet size | 32KB | +| Execution time | 5ms CPU | +| Subrequests (Pro/Biz) | 2/5 | +| Snippets/zone | 20 | + +## Performance Benchmarks + +| Operation | Time | +|-----------|------| +| Header set | <0.1ms | +| URL parsing | <0.2ms | +| fetch() | 1-3ms | +| SHA-256 | 0.5-1ms | + +**Migrate to Workers when:** >5ms needed, >5 subrequests, need storage (KV/D1/R2), need npm packages, >32KB code diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..d943f6506985a3f39a46a7716207b325d1db2a39 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/snippets/patterns.md @@ -0,0 +1,135 @@ +# Snippets Patterns + +## Security Headers + +```javascript +export default { + async fetch(request) { + const response = await fetch(request); + const newResponse = new Response(response.body, response); + newResponse.headers.set("X-Frame-Options", "DENY"); + newResponse.headers.set("X-Content-Type-Options", "nosniff"); + newResponse.headers.delete("X-Powered-By"); + return newResponse; + } +} +``` + +**Rule:** `true` (all requests) + +## Geo-Based Routing + +```javascript +export default { + async fetch(request) { + const country = request.cf.country; + if (["GB", "DE", "FR"].includes(country)) { + const url = new URL(request.url); + url.hostname = url.hostname.replace(".com", ".eu"); + return Response.redirect(url.toString(), 302); + } + return fetch(request); + } +} +``` + +## A/B Testing + +```javascript +export default { + async fetch(request) { + const cookies = request.headers.get("Cookie") || ""; + let variant = cookies.match(/ab_test=([AB])/)?.[1] || (Math.random() < 0.5 ? "A" : "B"); + + const req = new Request(request); + req.headers.set("X-Variant", variant); + const response = await fetch(req); + + if (!cookies.includes("ab_test=")) { + const newResponse = new Response(response.body, response); + newResponse.headers.append("Set-Cookie", `ab_test=${variant}; Path=/; Secure`); + return newResponse; + } + return response; + } +} +``` + +## Bot Detection + +```javascript +export default { + async fetch(request) { + const botScore = request.cf.botManagement?.score; + if (botScore && botScore < 30) return new Response("Denied", { status: 403 }); + return fetch(request); + } +} +``` + +**Requires:** Bot Management plan + +## API Auth Header Injection + +```javascript +export default { + async fetch(request) { + if (new URL(request.url).pathname.startsWith("/api/")) { + const req = new Request(request); + req.headers.set("X-Internal-Auth", "secret_token"); + req.headers.delete("Authorization"); + return fetch(req); + } + return fetch(request); + } +} +``` + +## CORS Headers + +```javascript +export default { + async fetch(request) { + if (request.method === "OPTIONS") { + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE", + "Access-Control-Allow-Headers": "Content-Type, Authorization" + } + }); + } + const response = await fetch(request); + const newResponse = new Response(response.body, response); + newResponse.headers.set("Access-Control-Allow-Origin", "*"); + return newResponse; + } +} +``` + +## Maintenance Mode + +```javascript +export default { + async fetch(request) { + if (request.headers.get("X-Bypass-Token") === "admin") return fetch(request); + return new Response("

Maintenance

", { + status: 503, + headers: { "Content-Type": "text/html", "Retry-After": "3600" } + }); + } +} +``` + +## Pattern Selection + +| Pattern | Complexity | Use Case | +|---------|-----------|----------| +| Security Headers | Low | All sites | +| Geo-Routing | Low | Regional content | +| A/B Testing | Medium | Experiments | +| Bot Detection | Medium | Requires Bot Management | +| API Auth | Low | Backend protection | +| CORS | Low | API endpoints | +| Maintenance | Low | Deployments | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f78350daff3c265ee16ab95840c31e370c0dd73c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/README.md @@ -0,0 +1,52 @@ +# Cloudflare Spectrum Skill Reference + +## Overview + +Cloudflare Spectrum provides security and acceleration for ANY TCP or UDP-based application. It's a global Layer 4 (L4) reverse proxy running on Cloudflare's edge nodes that routes MQTT, email, file transfer, version control, games, and more through Cloudflare to mask origins and protect from DDoS attacks. + +**When to Use Spectrum**: When your protocol isn't HTTP/HTTPS (use Cloudflare proxy for HTTP). Spectrum handles everything else: SSH, gaming, databases, MQTT, SMTP, RDP, custom protocols. + +## Plan Capabilities + +| Capability | Pro/Business | Enterprise | +|------------|--------------|------------| +| TCP protocols | Selected ports only | All ports (1-65535) | +| UDP protocols | Selected ports only | All ports (1-65535) | +| Port ranges | ❌ | ✅ | +| Argo Smart Routing | ✅ | ✅ | +| IP Firewall | ✅ | ✅ | +| Load balancer origins | ✅ | ✅ | + +## Decision Tree + +**What are you trying to do?** + +1. **Create/manage Spectrum app** + - Via Dashboard → See [Cloudflare Dashboard](https://dash.cloudflare.com) + - Via API → See [api.md](api.md) - REST endpoints + - Via SDK → See [api.md](api.md) - TypeScript/Python/Go examples + - Via IaC → See [configuration.md](configuration.md) - Terraform/Pulumi + +2. **Protect specific protocol** + - SSH → See [patterns.md](patterns.md#1-ssh-server-protection) + - Gaming (Minecraft, etc) → See [patterns.md](patterns.md#2-game-server) + - MQTT/IoT → See [patterns.md](patterns.md#3-mqtt-broker) + - SMTP/Email → See [patterns.md](patterns.md#4-smtp-relay) + - Database → See [patterns.md](patterns.md#5-database-proxy) + - RDP → See [patterns.md](patterns.md#6-rdp-remote-desktop) + +3. **Choose origin type** + - Direct IP (single server) → See [configuration.md](configuration.md#direct-ip-origin) + - CNAME (hostname) → See [configuration.md](configuration.md#cname-origin) + - Load balancer (HA/failover) → See [configuration.md](configuration.md#load-balancer-origin) + +## Reading Order + +1. Start with [patterns.md](patterns.md) for your specific protocol +2. Then [configuration.md](configuration.md) for your origin type +3. Check [gotchas.md](gotchas.md) before going to production +4. Use [api.md](api.md) for programmatic access + +## See Also + +- [Cloudflare Docs](https://developers.cloudflare.com/spectrum/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/api.md new file mode 100644 index 0000000000000000000000000000000000000000..645fe2e78229c1ae68a11d0e8691d77b362cb7d1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/api.md @@ -0,0 +1,181 @@ +## REST API Endpoints + +``` +GET /zones/{zone_id}/spectrum/apps # List apps +POST /zones/{zone_id}/spectrum/apps # Create app +GET /zones/{zone_id}/spectrum/apps/{app_id} # Get app +PUT /zones/{zone_id}/spectrum/apps/{app_id} # Update app +DELETE /zones/{zone_id}/spectrum/apps/{app_id} # Delete app + +GET /zones/{zone_id}/spectrum/analytics/aggregate/current +GET /zones/{zone_id}/spectrum/analytics/events/bytime +GET /zones/{zone_id}/spectrum/analytics/events/summary +``` + +## Request/Response Schemas + +### CreateSpectrumAppRequest + +```typescript +interface CreateSpectrumAppRequest { + protocol: string; // "tcp/22", "udp/53" + dns: { + type: "CNAME" | "ADDRESS"; + name: string; // "ssh.example.com" + }; + origin_direct?: string[]; // ["tcp://192.0.2.1:22"] + origin_dns?: { name: string }; // {"name": "origin.example.com"} + origin_port?: number | { start: number; end: number }; + proxy_protocol?: "off" | "v1" | "v2" | "simple"; + ip_firewall?: boolean; + tls?: "off" | "flexible" | "full" | "strict"; + edge_ips?: { + type: "dynamic" | "static"; + connectivity: "all" | "ipv4" | "ipv6"; + }; + traffic_type?: "direct" | "http" | "https"; + argo_smart_routing?: boolean; +} +``` + +### SpectrumApp Response + +```typescript +interface SpectrumApp { + id: string; + protocol: string; + dns: { type: string; name: string }; + origin_direct?: string[]; + origin_dns?: { name: string }; + origin_port?: number | { start: number; end: number }; + proxy_protocol: string; + ip_firewall: boolean; + tls: string; + edge_ips: { type: string; connectivity: string; ips?: string[] }; + argo_smart_routing: boolean; + created_on: string; + modified_on: string; +} +``` + +## TypeScript SDK + +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN }); + +// Create +const app = await client.spectrum.apps.create({ + zone_id: 'your-zone-id', + protocol: 'tcp/22', + dns: { type: 'CNAME', name: 'ssh.example.com' }, + origin_direct: ['tcp://192.0.2.1:22'], + ip_firewall: true, + tls: 'off', +}); + +// List +const apps = await client.spectrum.apps.list({ zone_id: 'your-zone-id' }); + +// Get +const appDetails = await client.spectrum.apps.get({ zone_id: 'your-zone-id', app_id: app.id }); + +// Update +await client.spectrum.apps.update({ zone_id: 'your-zone-id', app_id: app.id, tls: 'full' }); + +// Delete +await client.spectrum.apps.delete({ zone_id: 'your-zone-id', app_id: app.id }); + +// Analytics +const analytics = await client.spectrum.analytics.aggregate({ + zone_id: 'your-zone-id', + metrics: ['bytesIngress', 'bytesEgress'], + since: new Date(Date.now() - 3600000).toISOString(), +}); +``` + +## Python SDK + +```python +from cloudflare import Cloudflare + +client = Cloudflare(api_token="your-api-token") + +# Create +app = client.spectrum.apps.create( + zone_id="your-zone-id", + protocol="tcp/22", + dns={"type": "CNAME", "name": "ssh.example.com"}, + origin_direct=["tcp://192.0.2.1:22"], + ip_firewall=True, + tls="off", +) + +# List +apps = client.spectrum.apps.list(zone_id="your-zone-id") + +# Get +app_details = client.spectrum.apps.get(zone_id="your-zone-id", app_id=app.id) + +# Update +client.spectrum.apps.update(zone_id="your-zone-id", app_id=app.id, tls="full") + +# Delete +client.spectrum.apps.delete(zone_id="your-zone-id", app_id=app.id) + +# Analytics +analytics = client.spectrum.analytics.aggregate( + zone_id="your-zone-id", + metrics=["bytesIngress", "bytesEgress"], + since=datetime.now() - timedelta(hours=1), +) +``` + +## Go SDK + +```go +import "github.com/cloudflare/cloudflare-go" + +api, _ := cloudflare.NewWithAPIToken("your-api-token") + +// Create +app, _ := api.CreateSpectrumApplication(ctx, "zone-id", cloudflare.SpectrumApplication{ + Protocol: "tcp/22", + DNS: cloudflare.SpectrumApplicationDNS{Type: "CNAME", Name: "ssh.example.com"}, + OriginDirect: []string{"tcp://192.0.2.1:22"}, + IPFirewall: true, + ArgoSmartRouting: true, +}) + +// List +apps, _ := api.SpectrumApplications(ctx, "zone-id") + +// Delete +_ = api.DeleteSpectrumApplication(ctx, "zone-id", app.ID) +``` + +## Analytics API + +**Metrics:** +- `bytesIngress` - Bytes received from clients +- `bytesEgress` - Bytes sent to clients +- `count` - Number of connections +- `duration` - Connection duration (seconds) + +**Dimensions:** +- `event` - Connection event type +- `appID` - Spectrum application ID +- `coloName` - Datacenter name +- `ipVersion` - IPv4 or IPv6 + +**Example:** +```bash +curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/spectrum/analytics/aggregate/current?metrics=bytesIngress,bytesEgress,count&dimensions=appID" \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" +``` + +## See Also + +- [configuration.md](configuration.md) - Terraform/Pulumi +- [patterns.md](patterns.md) - Protocol examples diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..cbe9dd9031191db1d0facc6331b05596ae76c4a6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/configuration.md @@ -0,0 +1,194 @@ +## Origin Types + +### Direct IP Origin + +Use when origin is a single server with static IP. + +**TypeScript SDK:** +```typescript +const app = await client.spectrum.apps.create({ + zone_id: 'your-zone-id', + protocol: 'tcp/22', + dns: { type: 'CNAME', name: 'ssh.example.com' }, + origin_direct: ['tcp://192.0.2.1:22'], + ip_firewall: true, + tls: 'off', +}); +``` + +**Terraform:** +```hcl +resource "cloudflare_spectrum_application" "ssh" { + zone_id = var.zone_id + protocol = "tcp/22" + + dns { + type = "CNAME" + name = "ssh.example.com" + } + + origin_direct = ["tcp://192.0.2.1:22"] + ip_firewall = true + tls = "off" + argo_smart_routing = true +} +``` + +### CNAME Origin + +Use when origin is a hostname (not static IP). Spectrum resolves DNS dynamically. + +**TypeScript SDK:** +```typescript +const app = await client.spectrum.apps.create({ + zone_id: 'your-zone-id', + protocol: 'tcp/3306', + dns: { type: 'CNAME', name: 'db.example.com' }, + origin_dns: { name: 'db-primary.internal.example.com' }, + origin_port: 3306, + tls: 'full', +}); +``` + +**Terraform:** +```hcl +resource "cloudflare_spectrum_application" "database" { + zone_id = var.zone_id + protocol = "tcp/3306" + + dns { + type = "CNAME" + name = "db.example.com" + } + + origin_dns { + name = "db-primary.internal.example.com" + } + + origin_port = 3306 + tls = "full" + argo_smart_routing = true +} +``` + +### Load Balancer Origin + +Use for high availability and failover. + +**Terraform:** +```hcl +resource "cloudflare_load_balancer" "game_lb" { + zone_id = var.zone_id + name = "game-lb.example.com" + default_pool_ids = [cloudflare_load_balancer_pool.game_pool.id] +} + +resource "cloudflare_load_balancer_pool" "game_pool" { + name = "game-primary" + origins { name = "game-1"; address = "192.0.2.1" } + monitor = cloudflare_load_balancer_monitor.tcp_monitor.id +} + +resource "cloudflare_load_balancer_monitor" "tcp_monitor" { + type = "tcp"; port = 25565; interval = 60; timeout = 5 +} + +resource "cloudflare_spectrum_application" "game" { + zone_id = var.zone_id + protocol = "tcp/25565" + dns { type = "CNAME"; name = "game.example.com" } + origin_dns { name = cloudflare_load_balancer.game_lb.name } + origin_port = 25565 +} +``` + +## TLS Configuration + +| Mode | Description | Use Case | Origin Cert | +|------|-------------|----------|-------------| +| `off` | No TLS | Non-encrypted (SSH, gaming) | No | +| `flexible` | TLS client→CF, plain CF→origin | Testing | No | +| `full` | TLS end-to-end, self-signed OK | Production | Yes (any) | +| `strict` | Full + valid cert verification | Max security | Yes (CA) | + +**Example:** +```typescript +const app = await client.spectrum.apps.create({ + zone_id: 'your-zone-id', + protocol: 'tcp/3306', + dns: { type: 'CNAME', name: 'db.example.com' }, + origin_direct: ['tcp://192.0.2.1:3306'], + tls: 'strict', // Validates origin certificate +}); +``` + +## Proxy Protocol + +Forwards real client IP to origin. Origin must support parsing. + +| Version | Protocol | Use Case | +|---------|----------|----------| +| `off` | - | Origin doesn't need client IP | +| `v1` | TCP | Most TCP apps (SSH, databases) | +| `v2` | TCP | High-performance TCP | +| `simple` | UDP | UDP applications | + +**Compatibility:** +- **v1**: HAProxy, nginx, SSH, most databases +- **v2**: HAProxy 1.5+, nginx 1.11+ +- **simple**: Cloudflare-specific UDP format + +**Enable:** +```typescript +const app = await client.spectrum.apps.create({ + // ... + proxy_protocol: 'v1', // Origin must parse PROXY header +}); +``` + +**Origin Config (nginx):** +```nginx +stream { + server { + listen 22 proxy_protocol; + proxy_pass backend:22; + } +} +``` + +## IP Access Rules + +Enable `ip_firewall: true` then configure zone-level firewall rules. + +```typescript +const app = await client.spectrum.apps.create({ + // ... + ip_firewall: true, // Applies zone firewall rules +}); +``` + +## Port Ranges (Enterprise Only) + +```hcl +resource "cloudflare_spectrum_application" "game_cluster" { + zone_id = var.zone_id + protocol = "tcp/25565-25575" + + dns { + type = "CNAME" + name = "games.example.com" + } + + origin_direct = ["tcp://192.0.2.1"] + + origin_port { + start = 25565 + end = 25575 + } +} +``` + +## See Also + +- [patterns.md](patterns.md) - Protocol-specific examples +- [api.md](api.md) - REST/SDK reference diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..c0aacb60458ff87ffd6b7120da3be65a126bbe59 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/gotchas.md @@ -0,0 +1,145 @@ +## Common Issues + +### Connection Timeouts + +**Problem:** Connections fail or timeout +**Cause:** Origin firewall blocking Cloudflare IPs, origin service not running, incorrect DNS +**Solution:** +1. Verify origin firewall allows Cloudflare IP ranges +2. Check origin service running on correct port +3. Ensure DNS record is CNAME (not A/AAAA) +4. Verify origin IP/hostname is correct + +```bash +# Test connectivity +nc -zv app.example.com 22 +dig app.example.com +``` + +### Client IP Showing Cloudflare IP + +**Problem:** Origin logs show Cloudflare IPs not real client IPs +**Cause:** Proxy Protocol not enabled or origin not configured +**Solution:** +```typescript +// Enable in Spectrum app +const app = await client.spectrum.apps.create({ + // ... + proxy_protocol: 'v1', // TCP: v1/v2; UDP: simple +}); +``` + +**Origin config:** +- **nginx**: `listen 22 proxy_protocol;` +- **HAProxy**: `bind :22 accept-proxy` + +### TLS Errors + +**Problem:** TLS handshake failures, 525 errors +**Cause:** TLS mode mismatch + +| Error | TLS Mode | Problem | Solution | +|-------|----------|---------|----------| +| Connection refused | `full`/`strict` | Origin not TLS | Use `tls: "off"` or enable TLS | +| 525 cert invalid | `strict` | Self-signed cert | Use `tls: "full"` or valid cert | +| Handshake timeout | `flexible` | Origin expects TLS | Use `tls: "full"` | + +**Debug:** +```bash +openssl s_client -connect app.example.com:443 -showcerts +``` + +### SMTP Reverse DNS + +**Problem:** Email servers reject SMTP via Spectrum +**Cause:** Spectrum IPs lack PTR (reverse DNS) records +**Impact:** Many mail servers require valid rDNS for anti-spam + +**Solution:** +- Outbound SMTP: NOT recommended through Spectrum +- Inbound SMTP: Use Cloudflare Email Routing +- Internal relay: Whitelist Spectrum IPs on destination + +### Proxy Protocol Compatibility + +**Problem:** Connection works but app behaves incorrectly +**Cause:** Origin doesn't support Proxy Protocol + +**Solution:** +1. Verify origin supports version (v1: widely supported, v2: HAProxy 1.5+/nginx 1.11+) +2. Test with `proxy_protocol: 'off'` first +3. Configure origin to parse headers + +**nginx TCP:** +```nginx +stream { + server { + listen 22 proxy_protocol; + proxy_pass backend:22; + } +} +``` + +**HAProxy:** +``` +frontend ft_ssh + bind :22 accept-proxy +``` + +### Analytics Data Retention + +**Problem:** Historical data not available +**Cause:** Retention varies by plan + +| Plan | Real-time | Historical | +|------|-----------|------------| +| Pro | Last hour | ❌ | +| Business | Last hour | Limited | +| Enterprise | Last hour | 90+ days | + +**Solution:** Query within retention window or export to external system + +### Enterprise-Only Features + +**Problem:** Feature unavailable/errors +**Cause:** Requires Enterprise plan + +**Enterprise-only:** +- Port ranges (`tcp/25565-25575`) +- All TCP/UDP ports (Pro/Business: selected only) +- Extended analytics retention +- Advanced load balancing + +### IPv6 Considerations + +**Problem:** IPv6 clients can't connect or origin doesn't support IPv6 +**Solution:** Configure `edge_ips.connectivity` + +```typescript +const app = await client.spectrum.apps.create({ + // ... + edge_ips: { + type: 'dynamic', + connectivity: 'ipv4', // Options: 'all', 'ipv4', 'ipv6' + }, +}); +``` + +**Options:** +- `all`: Dual-stack (default, requires origin support both) +- `ipv4`: IPv4 only (use if origin lacks IPv6) +- `ipv6`: IPv6 only (rare) + +## Limits + +| Resource | Pro/Business | Enterprise | +|----------|--------------|------------| +| Max apps | ~10-15 | 100+ | +| Protocols | Selected | All TCP/UDP | +| Port ranges | ❌ | ✅ | +| Analytics | ~1 hour | 90+ days | + +## See Also + +- [patterns.md](patterns.md) - Protocol examples +- [configuration.md](configuration.md) - TLS/Proxy setup diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..403248698f5e97d9a55684b4b9ddfac7ef53e7b8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/spectrum/patterns.md @@ -0,0 +1,196 @@ +## Common Use Cases + +### 1. SSH Server Protection + +**Terraform:** +```hcl +resource "cloudflare_spectrum_application" "ssh" { + zone_id = var.zone_id + protocol = "tcp/22" + + dns { + type = "CNAME" + name = "ssh.example.com" + } + + origin_direct = ["tcp://10.0.1.5:22"] + ip_firewall = true + argo_smart_routing = true +} +``` + +**Benefits:** Hide origin IP, DDoS protection, IP firewall, Argo reduces latency + +### 2. Game Server + +**TypeScript (Minecraft):** +```typescript +const app = await client.spectrum.apps.create({ + zone_id: 'your-zone-id', + protocol: 'tcp/25565', + dns: { type: 'CNAME', name: 'mc.example.com' }, + origin_direct: ['tcp://192.168.1.10:25565'], + proxy_protocol: 'v1', // Preserves player IPs + argo_smart_routing: true, +}); +``` + +**Benefits:** DDoS protection, hide origin IP, Proxy Protocol for player IPs/bans, Argo reduces latency + +### 3. MQTT Broker + +IoT device communication. + +**TypeScript:** +```typescript +const mqttApp = await client.spectrum.apps.create({ + zone_id: 'your-zone-id', + protocol: 'tcp/8883', // Use 1883 for plain MQTT + dns: { type: 'CNAME', name: 'mqtt.example.com' }, + origin_direct: ['tcp://mqtt-broker.internal:8883'], + tls: 'full', // Use 'off' for plain MQTT +}); +``` + +**Benefits:** DDoS protection, hide broker IP, TLS termination at edge + +### 4. SMTP Relay + +Email submission (port 587). **WARNING**: See [gotchas.md](gotchas.md#smtp-reverse-dns) + +**Terraform:** +```hcl +resource "cloudflare_spectrum_application" "smtp" { + zone_id = var.zone_id + protocol = "tcp/587" + + dns { + type = "CNAME" + name = "smtp.example.com" + } + + origin_direct = ["tcp://mail-server.internal:587"] + tls = "full" # STARTTLS support +} +``` + +**Limitations:** +- Spectrum IPs lack reverse DNS (PTR records) +- Many mail servers reject without valid rDNS +- Best for internal/trusted relay only + +### 5. Database Proxy + +MySQL/PostgreSQL. **Use with caution** - security critical. + +**PostgreSQL:** +```typescript +const postgresApp = await client.spectrum.apps.create({ + zone_id: 'your-zone-id', + protocol: 'tcp/5432', + dns: { type: 'CNAME', name: 'postgres.example.com' }, + origin_dns: { name: 'db-primary.internal.example.com' }, + origin_port: 5432, + tls: 'strict', // REQUIRED + ip_firewall: true, // REQUIRED +}); +``` + +**MySQL:** +```hcl +resource "cloudflare_spectrum_application" "mysql" { + zone_id = var.zone_id + protocol = "tcp/3306" + + dns { + type = "CNAME" + name = "mysql.example.com" + } + + origin_dns { + name = "mysql-primary.internal.example.com" + } + + origin_port = 3306 + tls = "strict" + ip_firewall = true +} +``` + +**Security:** +- ALWAYS use `tls: "strict"` +- ALWAYS use `ip_firewall: true` +- Restrict to known IPs via zone firewall +- Use strong DB authentication +- Consider VPN or Cloudflare Access instead + +### 6. RDP (Remote Desktop) + +**Requires IP firewall.** + +**Terraform:** +```hcl +resource "cloudflare_spectrum_application" "rdp" { + zone_id = var.zone_id + protocol = "tcp/3389" + + dns { + type = "CNAME" + name = "rdp.example.com" + } + + origin_direct = ["tcp://windows-server.internal:3389"] + tls = "off" # RDP has own encryption + ip_firewall = true # REQUIRED +} +``` + +**Security:** ALWAYS `ip_firewall: true`, whitelist admin IPs, RDP is DDoS/brute-force target + +### 7. Multi-Origin Failover + +High availability with load balancer. + +**Terraform:** +```hcl +resource "cloudflare_load_balancer" "database_lb" { + zone_id = var.zone_id + name = "db-lb.example.com" + default_pool_ids = [cloudflare_load_balancer_pool.db_primary.id] + fallback_pool_id = cloudflare_load_balancer_pool.db_secondary.id +} + +resource "cloudflare_load_balancer_pool" "db_primary" { + name = "db-primary-pool" + origins { name = "db-1"; address = "192.0.2.1" } + monitor = cloudflare_load_balancer_monitor.postgres_monitor.id +} + +resource "cloudflare_load_balancer_pool" "db_secondary" { + name = "db-secondary-pool" + origins { name = "db-2"; address = "192.0.2.2" } + monitor = cloudflare_load_balancer_monitor.postgres_monitor.id +} + +resource "cloudflare_load_balancer_monitor" "postgres_monitor" { + type = "tcp"; port = 5432; interval = 30; timeout = 5 +} + +resource "cloudflare_spectrum_application" "postgres_ha" { + zone_id = var.zone_id + protocol = "tcp/5432" + dns { type = "CNAME"; name = "postgres.example.com" } + origin_dns { name = cloudflare_load_balancer.database_lb.name } + origin_port = 5432 + tls = "strict" + ip_firewall = true +} +``` + +**Benefits:** Automatic failover, health monitoring, traffic distribution, zero-downtime deployments + +## See Also + +- [configuration.md](configuration.md) - Origin type setup +- [gotchas.md](gotchas.md) - Protocol limitations +- [api.md](api.md) - SDK reference diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b2ba96a6ddc4a43cd42dfd2f8d0744daad4c2ac1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/README.md @@ -0,0 +1,65 @@ +# Cloudflare Static Assets Skill Reference + +Expert guidance for deploying and configuring static assets with Cloudflare Workers. This skill covers configuration patterns, routing architectures, asset binding usage, and best practices for SPAs, SSG sites, and full-stack applications. + +## Quick Start + +```jsonc +// wrangler.jsonc +{ + "name": "my-app", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", + "assets": { + "directory": "./dist" + } +} +``` + +```typescript +// src/index.ts +export default { + async fetch(request: Request, env: Env): Promise { + return env.ASSETS.fetch(request); + } +}; +``` + +Deploy: `wrangler deploy` + +## When to Use Workers Static Assets vs Pages + +| Factor | Workers Static Assets | Cloudflare Pages | +|--------|----------------------|------------------| +| **Use case** | Hybrid apps (static + dynamic API) | Static sites, SSG | +| **Worker control** | Full control over routing | Limited (Functions) | +| **Configuration** | Code-first, flexible | Git-based, opinionated | +| **Dynamic routing** | Worker-first patterns | Functions (_functions/) | +| **Best for** | Full-stack apps, SPAs with APIs | Jamstack, static docs | + +**Decision tree:** + +- Need custom routing logic? → Workers Static Assets +- Pure static site or SSG? → Pages +- API routes + SPA? → Workers Static Assets +- Framework (Next, Nuxt, Remix)? → Pages + +## Reading Order + +1. **configuration.md** - Setup, wrangler.jsonc options, routing patterns +2. **api.md** - ASSETS binding API, request/response handling +3. **patterns.md** - Common patterns (SPA, API routes, auth, A/B testing) +4. **gotchas.md** - Limits, errors, performance tips + +## In This Reference + +- **[configuration.md](configuration.md)** - Setup, deployment, configuration +- **[api.md](api.md)** - API endpoints, methods, interfaces +- **[patterns.md](patterns.md)** - Common patterns, use cases, examples +- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations + +## See Also + +- [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/) +- [Static Assets Docs](https://developers.cloudflare.com/workers/static-assets/) +- [Cloudflare Pages](https://developers.cloudflare.com/pages/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/api.md new file mode 100644 index 0000000000000000000000000000000000000000..08bb568daabf74ea1817cc7c97d4711f91d7bc4d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/api.md @@ -0,0 +1,199 @@ +# API Reference + +## ASSETS Binding + +The `ASSETS` binding provides access to static assets via the `Fetcher` interface. + +### Type Definition + +```typescript +interface Env { + ASSETS: Fetcher; +} + +interface Fetcher { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +} +``` + +### Method Signatures + +```typescript +// 1. Forward entire request +await env.ASSETS.fetch(request); + +// 2. String path (hostname ignored, only path matters) +await env.ASSETS.fetch("https://any-host/path/to/asset.png"); + +// 3. URL object +await env.ASSETS.fetch(new URL("/index.html", request.url)); + +// 4. Constructed Request object +await env.ASSETS.fetch(new Request(new URL("/logo.png", request.url), { + method: "GET", + headers: request.headers +})); +``` + +**Key behaviors:** + +- Host/origin is ignored for string/URL inputs (only path is used) +- Method must be GET (others return 405) +- Request headers pass through (affects response) +- Returns standard `Response` object + +## Request Handling + +### Path Resolution + +```typescript +// All resolve to same asset: +env.ASSETS.fetch("https://example.com/logo.png") +env.ASSETS.fetch("https://ignored.host/logo.png") +env.ASSETS.fetch("/logo.png") +``` + +Assets are resolved relative to configured `assets.directory`. + +### Headers + +Request headers that affect response: + +| Header | Effect | +|--------|--------| +| `Accept-Encoding` | Controls compression (gzip, brotli) | +| `Range` | Enables partial content (206 responses) | +| `If-None-Match` | Conditional request via ETag | +| `If-Modified-Since` | Conditional request via modification date | + +Custom headers pass through but don't affect asset serving. + +### Method Support + +| Method | Supported | Response | +|--------|-----------|----------| +| `GET` | ✅ Yes | Asset content | +| `HEAD` | ✅ Yes | Headers only, no body | +| `POST`, `PUT`, etc. | ❌ No | 405 Method Not Allowed | + +## Response Behavior + +### Content-Type Inference + +Automatically set based on file extension: + +| Extension | Content-Type | +|-----------|--------------| +| `.html` | `text/html; charset=utf-8` | +| `.css` | `text/css` | +| `.js` | `application/javascript` | +| `.json` | `application/json` | +| `.png` | `image/png` | +| `.jpg`, `.jpeg` | `image/jpeg` | +| `.svg` | `image/svg+xml` | +| `.woff2` | `font/woff2` | + +### Default Headers + +Responses include: + +``` +Content-Type: +ETag: "" +Cache-Control: public, max-age=3600 +Content-Encoding: br (if supported and beneficial) +``` + +**Cache-Control defaults:** + +- 1 hour (`max-age=3600`) for most assets +- Override via Worker response transformation (see patterns.md:27-35) + +### Compression + +Automatic compression based on `Accept-Encoding`: + +- **Brotli** (`br`): Preferred, best compression +- **Gzip** (`gzip`): Fallback +- **None**: If client doesn't support or asset too small + +### ETag Generation + +ETags are content-based hashes: + +``` +ETag: "a3b2c1d4e5f6..." +``` + +Used for conditional requests (`If-None-Match`). Returns `304 Not Modified` if match. + +## Error Responses + +| Status | Condition | Behavior | +|--------|-----------|----------| +| `404` | Asset not found | Body depends on `not_found_handling` config | +| `405` | Non-GET/HEAD method | `{ "error": "Method not allowed" }` | +| `416` | Invalid Range header | Range not satisfiable | + +### 404 Handling + +Depends on configuration (see configuration.md:45-52): + +```typescript +// not_found_handling: "single-page-application" +// Returns /index.html with 200 status + +// not_found_handling: "404-page" +// Returns /404.html if exists, else 404 response + +// not_found_handling: "none" +// Returns 404 response +``` + +## Advanced Usage + +### Modifying Responses + +```typescript +const response = await env.ASSETS.fetch(request); + +// Clone and modify +return new Response(response.body, { + status: response.status, + headers: { + ...Object.fromEntries(response.headers), + 'Cache-Control': 'public, max-age=31536000', + 'X-Custom': 'value' + } +}); +``` + +See patterns.md:27-35 for full example. + +### Error Handling + +```typescript +const response = await env.ASSETS.fetch(request); + +if (!response.ok) { + // Asset not found or error + return new Response('Custom error page', { status: 404 }); +} + +return response; +``` + +### Conditional Serving + +```typescript +const url = new URL(request.url); + +// Serve different assets based on conditions +if (url.pathname === '/') { + return env.ASSETS.fetch('/index.html'); +} + +return env.ASSETS.fetch(request); +``` + +See patterns.md for complete patterns. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..2902698e72277f6a02bf1de2934420425710e500 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/configuration.md @@ -0,0 +1,186 @@ +## Configuration + +### Basic Setup + +Minimal configuration requires only `assets.directory`: + +```jsonc +{ + "name": "my-worker", + "compatibility_date": "2025-01-01", // Use current date for new projects + "assets": { + "directory": "./dist" + } +} +``` + +### Full Configuration Options + +```jsonc +{ + "name": "my-worker", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", + "assets": { + "directory": "./dist", + "binding": "ASSETS", + "not_found_handling": "single-page-application", + "html_handling": "auto-trailing-slash", + "run_worker_first": ["/api/*", "!/api/docs/*"] + } +} +``` + +**Configuration keys:** + +- `directory` (string, required): Path to assets folder (e.g. `./dist`, `./public`, `./build`) +- `binding` (string, optional): Name to access assets in Worker code (e.g. `env.ASSETS`). Default: `"ASSETS"` +- `not_found_handling` (string, optional): Behavior when asset not found + - `"single-page-application"`: Serve `/index.html` for non-asset paths (default for SPAs) + - `"404-page"`: Serve `/404.html` if present, otherwise 404 + - `"none"`: Return 404 for missing assets +- `html_handling` (string, optional): URL trailing slash behavior +- `run_worker_first` (boolean | string[], optional): Routes that invoke Worker before checking assets + +### not_found_handling Modes + +| Mode | Behavior | Use Case | +|------|----------|----------| +| `"single-page-application"` | Serve `/index.html` for non-asset requests | React, Vue, Angular SPAs | +| `"404-page"` | Serve `/404.html` if exists, else 404 | Static sites with custom error page | +| `"none"` | Return 404 for missing assets | API-first or custom routing | + +### html_handling Modes + +Controls trailing slash behavior for HTML files: + +| Mode | `/page` | `/page/` | Use Case | +|------|---------|----------|----------| +| `"auto-trailing-slash"` | Redirect to `/page/` if `/page/index.html` exists | Serve `/page/index.html` | Default, SEO-friendly | +| `"force-trailing-slash"` | Always redirect to `/page/` | Serve if exists | Consistent trailing slashes | +| `"drop-trailing-slash"` | Serve if exists | Redirect to `/page` | Cleaner URLs | +| `"none"` | No modification | No modification | Custom routing logic | + +**Default:** `"auto-trailing-slash"` + +### run_worker_first Configuration + +Controls which requests invoke Worker before checking assets. + +**Boolean syntax:** + +```jsonc +{ + "assets": { + "run_worker_first": true // ALL requests invoke Worker + } +} +``` + +**Array syntax (recommended):** + +```jsonc +{ + "assets": { + "run_worker_first": [ + "/api/*", // Positive pattern: match API routes + "/admin/*", // Match admin routes + "!/admin/assets/*" // Negative pattern: exclude admin assets + ] + } +} +``` + +**Pattern rules:** + +- Glob patterns: `*` (any chars), `**` (any path segments) +- Negative patterns: Prefix with `!` to exclude +- Precedence: Negative patterns override positive patterns +- Default: `false` (assets served directly) + +**Decision guidance:** + +- Use `true` for API-first apps (few static assets) +- Use array patterns for hybrid apps (APIs + static assets) +- Use `false` for static-first sites (minimal dynamic routes) + +### .assetsignore File + +Exclude files from upload using `.assetsignore` (same syntax as `.gitignore`): + +``` +# .assetsignore +_worker.js +*.map +*.md +node_modules/ +.git/ +``` + +**Common patterns:** + +- `_worker.js` - Exclude Worker code from assets +- `*.map` - Exclude source maps +- `*.md` - Exclude markdown files +- Development artifacts + +### Vite Plugin Integration + +For Vite-based projects, use `@cloudflare/vite-plugin`: + +```typescript +// vite.config.ts +import { defineConfig } from 'vite'; +import { cloudflare } from '@cloudflare/vite-plugin'; + +export default defineConfig({ + plugins: [ + cloudflare({ + assets: { + directory: './dist', + binding: 'ASSETS' + } + }) + ] +}); +``` + +**Features:** + +- Automatic asset detection during dev +- Hot module replacement for assets +- Production build integration +- Requires: Wrangler 4.0.0+, `@cloudflare/vite-plugin` 1.0.0+ + +### Key Compatibility Dates + +| Date | Feature | Impact | +|------|---------|--------| +| `2025-04-01` | Navigation request optimization | SPAs skip Worker for navigation, reducing costs | + +Use current date for new projects. See [Compatibility Dates](https://developers.cloudflare.com/workers/configuration/compatibility-dates/) for full list. + +### Environment-Specific Configuration + +Use `wrangler.jsonc` environments for different configs: + +```jsonc +{ + "name": "my-worker", + "assets": { "directory": "./dist" }, + "env": { + "staging": { + "assets": { + "not_found_handling": "404-page" + } + }, + "production": { + "assets": { + "not_found_handling": "single-page-application" + } + } + } +} +``` + +Deploy with: `wrangler deploy --env staging` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..53bb443701413903815b3ca30a97f5e546c79b5b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/gotchas.md @@ -0,0 +1,162 @@ +## Best Practices + +### 1. Use Selective Worker-First Routing + +Instead of `run_worker_first = true`, use array patterns: + +```jsonc +{ + "assets": { + "run_worker_first": [ + "/api/*", // API routes + "/admin/*", // Admin area + "!/admin/assets/*" // Except admin assets + ] + } +} +``` + +**Benefits:** +- Reduces Worker invocations +- Lowers costs +- Improves asset delivery performance + +### 2. Leverage Navigation Request Optimization + +For SPAs, use `compatibility_date = "2025-04-01"` or later: + +```jsonc +{ + "compatibility_date": "2025-04-01", + "assets": { + "not_found_handling": "single-page-application" + } +} +``` + +Navigation requests skip Worker invocation, reducing costs. + +### 3. Type Safety with Bindings + +Always type your environment: + +```typescript +interface Env { + ASSETS: Fetcher; +} +``` + +## Common Errors + +### "Asset not found" + +**Cause:** Asset not in assets directory, wrong path, or assets not deployed +**Solution:** Verify asset exists, check path case-sensitivity, redeploy if needed + +### "Worker not invoked for asset" + +**Cause:** Asset served directly, `run_worker_first` not configured +**Solution:** Configure `run_worker_first` patterns to include asset routes (see configuration.md:66-106) + +### "429 Too Many Requests on free tier" + +**Cause:** `run_worker_first` patterns invoke Worker for many requests, hitting free tier limits (100k req/day) +**Solution:** Use more selective patterns with negative exclusions, or upgrade to paid plan + +### "Smart Placement increases latency" + +**Cause:** `run_worker_first=true` + Smart Placement routes all requests through single smart-placed location +**Solution:** Use selective patterns (array syntax) or disable Smart Placement for asset-heavy apps + +### "CF-Cache-Status header unreliable" + +**Cause:** Header is probabilistically added for privacy reasons +**Solution:** Don't rely on `CF-Cache-Status` for critical routing logic. Use other signals (ETag, age). + +### "JWT expired during deployment" + +**Cause:** Large asset deployments exceed JWT token lifetime +**Solution:** Update to Wrangler 4.34.0+ (automatic token refresh), or reduce asset count + +### "Cannot use 'assets' with 'site'" + +**Cause:** Legacy `site` config conflicts with new `assets` config +**Solution:** Migrate from `site` to `assets` (see configuration.md). Remove `site` key from wrangler.jsonc. + +### "Assets not updating after deployment" + +**Cause:** Browser or CDN cache serving old assets +**Solution:** +- Hard refresh browser (Cmd+Shift+R / Ctrl+F5) +- Use cache-busting (hashed filenames) +- Verify deployment completed: `wrangler tail` + +## Limits + +| Resource/Limit | Free | Paid | Notes | +|----------------|------|------|-------| +| Max asset size | 25 MiB | 25 MiB | Per file | +| Total assets | 20,000 | **100,000** | Requires Wrangler 4.34.0+ (Sep 2025) | +| Worker invocations | 100k/day | 10M/month | Optimize with `run_worker_first` patterns | +| Asset storage | Unlimited | Unlimited | Included | + +### Version Requirements + +| Feature | Minimum Wrangler Version | +|---------|--------------------------| +| 100k file limit (paid) | 4.34.0 | +| Vite plugin | 4.0.0 + @cloudflare/vite-plugin 1.0.0 | +| Navigation optimization | 4.0.0 + compatibility_date: "2025-04-01" | + +## Performance Tips + +### 1. Use Hashed Filenames + +Enable long-term caching with content-hashed filenames: + +``` +app.a3b2c1d4.js +styles.e5f6g7h8.css +``` + +Most bundlers (Vite, Webpack, Parcel) do this automatically. + +### 2. Minimize Worker Invocations + +Serve assets directly when possible: + +```jsonc +{ + "assets": { + // Only invoke Worker for dynamic routes + "run_worker_first": ["/api/*", "/auth/*"] + } +} +``` + +### 3. Leverage Browser Cache + +Set appropriate `Cache-Control` headers: + +```typescript +// Versioned assets +'Cache-Control': 'public, max-age=31536000, immutable' + +// HTML (revalidate often) +'Cache-Control': 'public, max-age=0, must-revalidate' +``` + +See patterns.md:169-189 for implementation. + +### 4. Use .assetsignore + +Reduce upload time by excluding unnecessary files: + +``` +*.map +*.md +.DS_Store +node_modules/ +``` + +See configuration.md:107-126 for details. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..11ddda24b45055cafcac51fc39964eef1fac5b59 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/static-assets/patterns.md @@ -0,0 +1,189 @@ +### Common Patterns + +**1. Forward request to assets:** + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + return env.ASSETS.fetch(request); + } +}; +``` + +**2. Fetch specific asset by path:** + +```typescript +const response = await env.ASSETS.fetch("https://assets.local/logo.png"); +``` + +**3. Modify request before fetching asset:** + +```typescript +const url = new URL(request.url); +url.pathname = "/index.html"; +return env.ASSETS.fetch(new Request(url, request)); +``` + +**4. Transform asset response:** + +```typescript +const response = await env.ASSETS.fetch(request); +const modifiedResponse = new Response(response.body, response); +modifiedResponse.headers.set("X-Custom-Header", "value"); +modifiedResponse.headers.set("Cache-Control", "public, max-age=3600"); +return modifiedResponse; +``` + +**5. Conditional asset serving:** + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + if (url.pathname === '/') { + return env.ASSETS.fetch('/index.html'); + } + return env.ASSETS.fetch(request); + } +}; +``` + +**6. SPA with API routes:** + +Most common full-stack pattern - static SPA with backend API: + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + if (url.pathname.startsWith('/api/')) { + return handleAPI(request, env); + } + return env.ASSETS.fetch(request); + } +}; + +async function handleAPI(request: Request, env: Env): Promise { + return new Response(JSON.stringify({ status: 'ok' }), { + headers: { 'Content-Type': 'application/json' } + }); +} +``` + +**Config:** Set `run_worker_first: ["/api/*"]` (see configuration.md:66-106) + +**7. Auth gating for protected assets:** + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + if (url.pathname.startsWith('/admin/')) { + const session = await validateSession(request, env); + if (!session) { + return Response.redirect('/login', 302); + } + } + return env.ASSETS.fetch(request); + } +}; +``` + +**Config:** Set `run_worker_first: ["/admin/*"]` + +**8. Custom headers for security:** + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const response = await env.ASSETS.fetch(request); + const secureResponse = new Response(response.body, response); + secureResponse.headers.set('X-Frame-Options', 'DENY'); + secureResponse.headers.set('X-Content-Type-Options', 'nosniff'); + secureResponse.headers.set('Content-Security-Policy', "default-src 'self'"); + return secureResponse; + } +}; +``` + +**9. A/B testing via cookies:** + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const cookies = request.headers.get('Cookie') || ''; + const variant = cookies.includes('variant=b') ? 'b' : 'a'; + const url = new URL(request.url); + if (url.pathname === '/') { + return env.ASSETS.fetch(`/index-${variant}.html`); + } + return env.ASSETS.fetch(request); + } +}; +``` + +**10. Locale-based routing:** + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const locale = request.headers.get('Accept-Language')?.split(',')[0] || 'en'; + const url = new URL(request.url); + if (url.pathname === '/') { + return env.ASSETS.fetch(`/${locale}/index.html`); + } + if (!url.pathname.startsWith(`/${locale}/`)) { + url.pathname = `/${locale}${url.pathname}`; + } + return env.ASSETS.fetch(url); + } +}; +``` + +**11. OAuth callback handling:** + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + if (url.pathname === '/auth/callback') { + const code = url.searchParams.get('code'); + if (code) { + const session = await exchangeCode(code, env); + return new Response(null, { + status: 302, + headers: { + 'Location': '/', + 'Set-Cookie': `session=${session}; HttpOnly; Secure; SameSite=Lax` + } + }); + } + } + return env.ASSETS.fetch(request); + } +}; +``` + +**Config:** Set `run_worker_first: ["/auth/*"]` + +**12. Cache control override:** + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const response = await env.ASSETS.fetch(request); + const url = new URL(request.url); + // Immutable assets (hashed filenames) + if (/\.[a-f0-9]{8,}\.(js|css|png|jpg)$/.test(url.pathname)) { + return new Response(response.body, { + ...response, + headers: { + ...Object.fromEntries(response.headers), + 'Cache-Control': 'public, max-age=31536000, immutable' + } + }); + } + return response; + } +}; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..be251e3dff86b37575d17a869eae03e00f5bb80c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/README.md @@ -0,0 +1,114 @@ +# Cloudflare Stream + +Serverless live and on-demand video streaming platform with one API. + +## Overview + +Cloudflare Stream provides video upload, storage, encoding, and delivery without managing infrastructure. Runs on Cloudflare's global network. + +### Key Features +- **On-demand video**: Upload, encode, store, deliver +- **Live streaming**: RTMPS/SRT ingestion with ABR +- **Direct creator uploads**: End users upload without API keys +- **Signed URLs**: Token-based access control +- **Analytics**: Server-side metrics via GraphQL +- **Webhooks**: Processing notifications +- **Captions**: Upload or AI-generate subtitles +- **Watermarks**: Apply branding to videos +- **Downloads**: Enable MP4 offline viewing + +## Core Concepts + +### Video Upload Methods +1. **API Upload (TUS protocol)**: Direct server upload +2. **Upload from URL**: Import from external source +3. **Direct Creator Uploads**: User-generated content (recommended) + +### Playback Options +1. **Stream Player (iframe)**: Built-in, optimized player +2. **Custom Player (HLS/DASH)**: Video.js, HLS.js integration +3. **Thumbnails**: Static or animated previews + +### Access Control +- **Public**: No restrictions +- **requireSignedURLs**: Token-based access +- **allowedOrigins**: Domain restrictions +- **Access Rules**: Geo/IP restrictions in tokens + +### Live Streaming +- RTMPS/SRT ingest from OBS, FFmpeg +- Automatic recording to on-demand +- Simulcast to YouTube, Twitch, etc. +- WebRTC support for browser streaming + +## Quick Start + +**Upload video via API** +```bash +curl -X POST \ + "https://api.cloudflare.com/client/v4/accounts/{account_id}/stream/copy" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{"url": "https://example.com/video.mp4"}' +``` + +**Embed player** +```html + +``` + +**Create live input** +```bash +curl -X POST \ + "https://api.cloudflare.com/client/v4/accounts/{account_id}/stream/live_inputs" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{"recording": {"mode": "automatic"}}' +``` + +## Limits + +- Max file size: 30 GB +- Max frame rate: 60 fps (recommended) +- Supported formats: MP4, MKV, MOV, AVI, FLV, MPEG-2 TS/PS, MXF, LXF, GXF, 3GP, WebM, MPG, QuickTime + +## Pricing + +- $5/1000 min stored +- $1/1000 min delivered + +## Resources + +- Dashboard: https://dash.cloudflare.com/?to=/:account/stream +- API Docs: https://developers.cloudflare.com/api/resources/stream/ +- Stream Docs: https://developers.cloudflare.com/stream/ + +## Reading Order + +| Order | File | Purpose | When to Use | +|-------|------|---------|-------------| +| 1 | [configuration.md](./configuration.md) | Setup SDKs, env vars, signing keys | Starting new project | +| 2 | [api.md](./api.md) | On-demand video APIs | Implementing uploads/playback | +| 3 | [api-live.md](./api-live.md) | Live streaming APIs | Building live streaming | +| 4 | [patterns.md](./patterns.md) | Full-stack flows, TUS, JWT signing | Implementing workflows | +| 5 | [gotchas.md](./gotchas.md) | Errors, limits, troubleshooting | Debugging issues | + +## In This Reference + +- [configuration.md](./configuration.md) - Setup, environment variables, wrangler config +- [api.md](./api.md) - On-demand video upload, playback, management APIs +- [api-live.md](./api-live.md) - Live streaming (RTMPS/SRT/WebRTC), simulcast +- [patterns.md](./patterns.md) - Full-stack flows, state management, best practices +- [gotchas.md](./gotchas.md) - Error codes, troubleshooting, limits + +## See Also + +- [workers](../workers/) - Deploy Stream APIs in Workers +- [pages](../pages/) - Integrate Stream with Pages +- [workers-ai](../workers-ai/) - AI-generate captions diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/api-live.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/api-live.md new file mode 100644 index 0000000000000000000000000000000000000000..5967972e7e7dc90cb31bf7fd94400b70c6c9543e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/api-live.md @@ -0,0 +1,195 @@ +# Stream Live Streaming API + +Live input creation, status checking, simulcast, and WebRTC streaming. + +## Create Live Input + +### Using Cloudflare SDK + +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ apiToken: env.CF_API_TOKEN }); + +const liveInput = await client.stream.liveInputs.create({ + account_id: env.CF_ACCOUNT_ID, + recording: { mode: 'automatic', timeoutSeconds: 30 }, + deleteRecordingAfterDays: 30 +}); + +// Returns: { uid, rtmps, srt, webRTC } +``` + +### Raw fetch API + +```typescript +async function createLiveInput(accountId: string, apiToken: string) { + const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/live_inputs`, + { + method: 'POST', + headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + recording: { mode: 'automatic', timeoutSeconds: 30 }, + deleteRecordingAfterDays: 30 + }) + } + ); + const { result } = await response.json(); + return { + uid: result.uid, + rtmps: { url: result.rtmps.url, streamKey: result.rtmps.streamKey }, + srt: { url: result.srt.url, streamId: result.srt.streamId, passphrase: result.srt.passphrase }, + webRTC: result.webRTC + }; +} +``` + +## Check Live Status + +```typescript +async function getLiveStatus(accountId: string, liveInputId: string, apiToken: string) { + const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/live_inputs/${liveInputId}`, + { headers: { 'Authorization': `Bearer ${apiToken}` } } + ); + const { result } = await response.json(); + return { + isLive: result.status?.current?.state === 'connected', + recording: result.recording, + status: result.status + }; +} +``` + +## Simulcast (Live Outputs) + +### Create Output + +```typescript +async function createLiveOutput( + accountId: string, liveInputId: string, apiToken: string, + outputUrl: string, streamKey: string +) { + return fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/live_inputs/${liveInputId}/outputs`, + { + method: 'POST', + headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + url: `${outputUrl}/${streamKey}`, + enabled: true, + streamKey // For platforms like YouTube, Twitch + }) + } + ).then(r => r.json()); +} +``` + +### Example: Simulcast to YouTube + Twitch + +```typescript +const liveInput = await createLiveInput(accountId, apiToken); + +// Add YouTube output +await createLiveOutput( + accountId, liveInput.uid, apiToken, + 'rtmp://a.rtmp.youtube.com/live2', + 'your-youtube-stream-key' +); + +// Add Twitch output +await createLiveOutput( + accountId, liveInput.uid, apiToken, + 'rtmp://live.twitch.tv/app', + 'your-twitch-stream-key' +); +``` + +## WebRTC Streaming (WHIP/WHEP) + +### Browser to Stream (WHIP) + +```typescript +async function startWebRTCBroadcast(liveInputId: string) { + const pc = new RTCPeerConnection(); + + // Add local media tracks + const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); + stream.getTracks().forEach(track => pc.addTrack(track, stream)); + + // Create offer + const offer = await pc.createOffer(); + await pc.setLocalDescription(offer); + + // Send to Stream via WHIP + const response = await fetch( + `https://customer-.cloudflarestream.com/${liveInputId}/webRTC/publish`, + { + method: 'POST', + headers: { 'Content-Type': 'application/sdp' }, + body: offer.sdp + } + ); + + const answer = await response.text(); + await pc.setRemoteDescription({ type: 'answer', sdp: answer }); +} +``` + +### Stream to Browser (WHEP) + +```typescript +async function playWebRTCStream(videoId: string) { + const pc = new RTCPeerConnection(); + + pc.addTransceiver('video', { direction: 'recvonly' }); + pc.addTransceiver('audio', { direction: 'recvonly' }); + + const offer = await pc.createOffer(); + await pc.setLocalDescription(offer); + + const response = await fetch( + `https://customer-.cloudflarestream.com/${videoId}/webRTC/play`, + { + method: 'POST', + headers: { 'Content-Type': 'application/sdp' }, + body: offer.sdp + } + ); + + const answer = await response.text(); + await pc.setRemoteDescription({ type: 'answer', sdp: answer }); + + return pc; +} +``` + +## Recording Settings + +| Mode | Behavior | +|------|----------| +| `automatic` | Record all live streams | +| `off` | No recording | +| `timeoutSeconds` | Stop recording after N seconds of inactivity | + +```typescript +const recordingConfig = { + mode: 'automatic', + timeoutSeconds: 30, // Auto-stop 30s after stream ends + requireSignedURLs: true, // Require token for VOD playback + allowedOrigins: ['https://yourdomain.com'] +}; +``` + +## In This Reference + +- [README.md](./README.md) - Overview and quick start +- [api.md](./api.md) - On-demand video APIs +- [configuration.md](./configuration.md) - Setup and config +- [patterns.md](./patterns.md) - Full-stack flows, best practices +- [gotchas.md](./gotchas.md) - Error codes, troubleshooting + +## See Also + +- [workers](../workers/) - Deploy live APIs in Workers diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/api.md new file mode 100644 index 0000000000000000000000000000000000000000..0c35a7137613faa3de158bd0bfc79e9dbcba9701 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/api.md @@ -0,0 +1,199 @@ +# Stream API Reference + +Upload, playback, live streaming, and management APIs. + +## Upload APIs + +### Direct Creator Upload (Recommended) + +**Backend: Create upload URL (SDK)** +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ apiToken: env.CF_API_TOKEN }); + +const uploadData = await client.stream.directUpload.create({ + account_id: env.CF_ACCOUNT_ID, + maxDurationSeconds: 3600, + requireSignedURLs: true, + meta: { creator: 'user-123' } +}); +// Returns: { uploadURL: string, uid: string } +``` + +**Frontend: Upload file** +```typescript +async function uploadVideo(file: File, uploadURL: string) { + const formData = new FormData(); + formData.append('file', file); + return fetch(uploadURL, { method: 'POST', body: formData }).then(r => r.json()); +} +``` + +### Upload from URL + +```typescript +const video = await client.stream.copy.create({ + account_id: env.CF_ACCOUNT_ID, + url: 'https://example.com/video.mp4', + meta: { name: 'My Video' }, + requireSignedURLs: false +}); +``` + +## Playback APIs + +### Embed Player (iframe) + +```html + +``` + +### HLS/DASH Manifest URLs + +```typescript +// HLS +const hlsUrl = `https://customer-.cloudflarestream.com/${videoId}/manifest/video.m3u8`; + +// DASH +const dashUrl = `https://customer-.cloudflarestream.com/${videoId}/manifest/video.mpd`; +``` + +### Thumbnails + +```typescript +// At specific time (seconds) +const thumb = `https://customer-.cloudflarestream.com/${videoId}/thumbnails/thumbnail.jpg?time=10s`; + +// By percentage +const thumbPct = `https://customer-.cloudflarestream.com/${videoId}/thumbnails/thumbnail.jpg?time=50%`; + +// Animated GIF +const gif = `https://customer-.cloudflarestream.com/${videoId}/thumbnails/thumbnail.gif`; +``` + +## Signed URLs + +```typescript +// Low volume (<1k/day): Use API +async function getSignedToken(accountId: string, videoId: string, apiToken: string) { + const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/${videoId}/token`, + { + method: 'POST', + headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + exp: Math.floor(Date.now() / 1000) + 3600, + accessRules: [{ type: 'ip.geoip.country', action: 'allow', country: ['US'] }] + }) + } + ); + return (await response.json()).result.token; +} + +// High volume: Self-sign with RS256 JWT (see "Self-Sign JWT" in patterns.md) +``` + +## Captions & Clips + +### Upload Captions + +```typescript +async function uploadCaption( + accountId: string, videoId: string, apiToken: string, + language: string, captionFile: File +) { + const formData = new FormData(); + formData.append('file', captionFile); + return fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/${videoId}/captions/${language}`, + { + method: 'PUT', + headers: { 'Authorization': `Bearer ${apiToken}` }, + body: formData + } + ).then(r => r.json()); +} +``` + +### Generate AI Captions + +```typescript +// TODO: Requires Workers AI integration - see workers-ai reference +async function generateAICaptions(accountId: string, videoId: string, apiToken: string) { + return fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/${videoId}/captions/generate`, + { + method: 'POST', + headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ language: 'en' }) + } + ).then(r => r.json()); +} +``` + +### Clip Video + +```typescript +async function clipVideo( + accountId: string, videoId: string, apiToken: string, + startTime: number, endTime: number +) { + return fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/clip`, + { + method: 'POST', + headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + clippedFromVideoUID: videoId, + startTimeSeconds: startTime, + endTimeSeconds: endTime + }) + } + ).then(r => r.json()); +} +``` + +## Video Management + +```typescript +// List videos +const videos = await client.stream.videos.list({ + account_id: env.CF_ACCOUNT_ID, + search: 'keyword' // optional +}); + +// Get video details +const video = await client.stream.videos.get(videoId, { + account_id: env.CF_ACCOUNT_ID +}); + +// Update video +await client.stream.videos.update(videoId, { + account_id: env.CF_ACCOUNT_ID, + meta: { title: 'New Title' }, + requireSignedURLs: true +}); + +// Delete video +await client.stream.videos.delete(videoId, { + account_id: env.CF_ACCOUNT_ID +}); +``` + +## In This Reference + +- [README.md](./README.md) - Overview and quick start +- [configuration.md](./configuration.md) - Setup and config +- [api-live.md](./api-live.md) - Live streaming APIs (RTMPS/SRT/WebRTC) +- [patterns.md](./patterns.md) - Full-stack flows, best practices +- [gotchas.md](./gotchas.md) - Error codes, troubleshooting + +## See Also + +- [workers](../workers/) - Deploy Stream APIs in Workers diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..c4e66133368730a6a49faf63f2b904fd2186766a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/configuration.md @@ -0,0 +1,141 @@ +# Stream Configuration + +Setup, environment variables, and wrangler configuration. + +## Installation + +```bash +# Official Cloudflare SDK (Node.js, Workers, Pages) +npm install cloudflare + +# React component library +npm install @cloudflare/stream-react + +# TUS resumable uploads (large files) +npm install tus-js-client +``` + +## Environment Variables + +```bash +# Required +CF_ACCOUNT_ID=your-account-id +CF_API_TOKEN=your-api-token + +# For signed URLs (high volume) +STREAM_KEY_ID=your-key-id +STREAM_JWK=base64-encoded-jwk + +# For webhooks +WEBHOOK_SECRET=your-webhook-secret + +# Customer subdomain (from dashboard) +STREAM_CUSTOMER_CODE=your-customer-code +``` + +## Wrangler Configuration + +```jsonc +{ + "name": "stream-worker", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", // Use current date for new projects + "vars": { + "CF_ACCOUNT_ID": "your-account-id" + } + // Store secrets: wrangler secret put CF_API_TOKEN + // wrangler secret put STREAM_KEY_ID + // wrangler secret put STREAM_JWK + // wrangler secret put WEBHOOK_SECRET +} +``` + +## Signing Keys (High Volume) + +Create once for self-signing tokens (thousands of daily users). + +**Create key** +```bash +curl -X POST \ + "https://api.cloudflare.com/client/v4/accounts/{account_id}/stream/keys" \ + -H "Authorization: Bearer " + +# Save `id` and `jwk` (base64) from response +``` + +**Store in secrets** +```bash +wrangler secret put STREAM_KEY_ID +wrangler secret put STREAM_JWK +``` + +## Webhooks + +**Setup webhook URL** +```bash +curl -X PUT \ + "https://api.cloudflare.com/client/v4/accounts/{account_id}/stream/webhook" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{"notificationUrl": "https://your-worker.workers.dev/webhook"}' + +# Save the returned `secret` for signature verification +``` + +**Store secret** +```bash +wrangler secret put WEBHOOK_SECRET +``` + +## Direct Upload / Live / Watermark Config + +```typescript +// Direct upload +const uploadConfig = { + maxDurationSeconds: 3600, + expiry: new Date(Date.now() + 3600000).toISOString(), + requireSignedURLs: true, + allowedOrigins: ['https://yourdomain.com'], + meta: { creator: 'user-123' } +}; + +// Live input +const liveConfig = { + recording: { mode: 'automatic', timeoutSeconds: 30 }, + deleteRecordingAfterDays: 30 +}; + +// Watermark +const watermark = { + name: 'Logo', opacity: 0.7, padding: 20, + position: 'lowerRight', scale: 0.15 +}; +``` + +## Access Rules & Player Config + +```typescript +// Access rules: allow US/CA, block CN/RU, or IP allowlist +const geoRestrict = [ + { type: 'ip.geoip.country', action: 'allow', country: ['US', 'CA'] }, + { type: 'any', action: 'block' } +]; + +// Player params for iframe +const playerParams = new URLSearchParams({ + autoplay: 'true', muted: 'true', preload: 'auto', defaultTextTrack: 'en' +}); +``` + +## In This Reference + +- [README.md](./README.md) - Overview and quick start +- [api.md](./api.md) - On-demand video APIs +- [api-live.md](./api-live.md) - Live streaming APIs +- [patterns.md](./patterns.md) - Full-stack flows, best practices +- [gotchas.md](./gotchas.md) - Error codes, troubleshooting + +## See Also + +- [wrangler](../wrangler/) - Wrangler CLI and configuration +- [workers](../workers/) - Deploy Stream APIs in Workers diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..6d5a17ae9b125af4daba741630dc610abaaf70b1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/gotchas.md @@ -0,0 +1,130 @@ +# Stream Gotchas + +## Common Errors + +### "ERR_NON_VIDEO" + +**Cause:** Uploaded file is not a valid video format +**Solution:** Ensure file is in supported format (MP4, MKV, MOV, AVI, FLV, MPEG-2 TS/PS, MXF, LXF, GXF, 3GP, WebM, MPG, QuickTime) + +### "ERR_DURATION_EXCEED_CONSTRAINT" + +**Cause:** Video duration exceeds `maxDurationSeconds` constraint +**Solution:** Increase `maxDurationSeconds` in direct upload config or trim video before upload + +### "ERR_FETCH_ORIGIN_ERROR" + +**Cause:** Failed to download video from URL (upload from URL) +**Solution:** Ensure URL is publicly accessible, uses HTTPS, and video file is available + +### "ERR_MALFORMED_VIDEO" + +**Cause:** Video file is corrupted or improperly encoded +**Solution:** Re-encode video using FFmpeg or check source file integrity + +### "ERR_DURATION_TOO_SHORT" + +**Cause:** Video must be at least 0.1 seconds long +**Solution:** Ensure video has valid duration (not a single frame) + +## Troubleshooting + +### Video stuck in "inprogress" state +- **Cause**: Processing large/complex video +- **Solution**: Wait up to 5 minutes for processing; use webhooks instead of polling + +### Signed URL returns 403 +- **Cause**: Token expired or invalid signature +- **Solution**: Check expiration timestamp, verify JWK is correct, ensure clock sync + +### Live stream not connecting +- **Cause**: Invalid RTMPS URL or stream key +- **Solution**: Use exact URL/key from API, ensure firewall allows outbound 443 + +### Webhook signature verification fails +- **Cause**: Incorrect secret or timestamp window +- **Solution**: Use exact secret from webhook setup, allow 5-minute timestamp drift + +### Video uploads but isn't visible +- **Cause**: `requireSignedURLs` enabled without providing token +- **Solution**: Generate signed token or set `requireSignedURLs: false` for public videos + +### Player shows infinite loading +- **Cause**: CORS issue with allowedOrigins +- **Solution**: Add your domain to `allowedOrigins` array + +## Limits + +| Resource | Limit | +|----------|-------| +| Max file size | 30 GB | +| Max frame rate | 60 fps (recommended) | +| Max duration per direct upload | Configurable via `maxDurationSeconds` | +| Token generation (API endpoint) | 1,000/day recommended (use signing keys for higher) | +| Live input outputs (simulcast) | 5 per live input | +| Webhook retry attempts | 5 (exponential backoff) | +| Webhook timeout | 30 seconds | +| Caption file size | 5 MB | +| Watermark image size | 2 MB | +| Metadata keys per video | Unlimited | +| Search results per page | Max 1,000 | + +## Performance Issues + +### Upload is slow +- **Cause**: Large file size or network constraints +- **Solution**: Use TUS resumable upload, compress video before upload, check bandwidth + +### Playback buffering +- **Cause**: Network congestion or low bandwidth +- **Solution**: Use ABR (adaptive bitrate) with HLS/DASH, reduce max bitrate + +### High processing time +- **Cause**: Complex video codec, high resolution +- **Solution**: Pre-encode with H.264 (most efficient), reduce resolution + +## Type Safety + +```typescript +// Error response type +interface StreamError { + success: false; + errors: Array<{ + code: number; + message: string; + }>; +} + +// Handle errors +async function uploadWithErrorHandling(url: string, file: File) { + const formData = new FormData(); + formData.append('file', file); + const response = await fetch(url, { method: 'POST', body: formData }); + const result = await response.json(); + + if (!result.success) { + throw new Error(result.errors[0]?.message || 'Upload failed'); + } + return result; +} +``` + +## Security Gotchas + +1. **Never expose API token in frontend** - Use direct creator uploads +2. **Always verify webhook signatures** - Prevent spoofed notifications +3. **Set appropriate token expiration** - Short-lived for security +4. **Use requireSignedURLs for private content** - Prevent unauthorized access +5. **Whitelist allowedOrigins** - Prevent hotlinking/embedding on unauthorized sites + +## In This Reference + +- [README.md](./README.md) - Overview and quick start +- [configuration.md](./configuration.md) - Setup and config +- [api.md](./api.md) - On-demand video APIs +- [api-live.md](./api-live.md) - Live streaming APIs +- [patterns.md](./patterns.md) - Full-stack flows, best practices + +## See Also + +- [workers](../workers/) - Deploy Stream APIs securely diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..15452cfb4021b0928bd847f1b0180834b2b88000 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/stream/patterns.md @@ -0,0 +1,184 @@ +# Stream Patterns + +Common workflows, full-stack flows, and best practices. + +## React Stream Player + +`npm install @cloudflare/stream-react` + +```tsx +import { Stream } from '@cloudflare/stream-react'; + +export function VideoPlayer({ videoId, token }: { videoId: string; token?: string }) { + return ; +} +``` + +## Full-Stack Upload Flow + +**Backend API (Workers/Pages)** +```typescript +import Cloudflare from 'cloudflare'; + +export default { + async fetch(request: Request, env: Env): Promise { + const { videoName } = await request.json(); + const client = new Cloudflare({ apiToken: env.CF_API_TOKEN }); + const { uploadURL, uid } = await client.stream.directUpload.create({ + account_id: env.CF_ACCOUNT_ID, + maxDurationSeconds: 3600, + requireSignedURLs: true, + meta: { name: videoName } + }); + return Response.json({ uploadURL, uid }); + } +}; +``` + +**Frontend component** +```tsx +import { useState } from 'react'; + +export function VideoUploader() { + const [uploading, setUploading] = useState(false); + const [progress, setProgress] = useState(0); + + async function handleUpload(file: File) { + setUploading(true); + const { uploadURL, uid } = await fetch('/api/upload-url', { + method: 'POST', + body: JSON.stringify({ videoName: file.name }) + }).then(r => r.json()); + + const xhr = new XMLHttpRequest(); + xhr.upload.onprogress = (e) => setProgress((e.loaded / e.total) * 100); + xhr.onload = () => { setUploading(false); window.location.href = `/videos/${uid}`; }; + xhr.open('POST', uploadURL); + const formData = new FormData(); + formData.append('file', file); + xhr.send(formData); + } + + return ( +
+ e.target.files?.[0] && handleUpload(e.target.files[0])} disabled={uploading} /> + {uploading && } +
+ ); +} +``` + +## TUS Resumable Upload + +For large files (>500MB). `npm install tus-js-client` + +```typescript +import * as tus from 'tus-js-client'; + +async function uploadWithTUS(file: File, uploadURL: string, onProgress?: (pct: number) => void) { + return new Promise((resolve, reject) => { + const upload = new tus.Upload(file, { + endpoint: uploadURL, + retryDelays: [0, 3000, 5000, 10000, 20000], + chunkSize: 50 * 1024 * 1024, + metadata: { filename: file.name, filetype: file.type }, + onError: reject, + onProgress: (up, total) => onProgress?.((up / total) * 100), + onSuccess: () => resolve(upload.url?.split('/').pop() || '') + }); + upload.start(); + }); +} +``` + +## Video State Polling + +```typescript +async function waitForVideoReady(client: Cloudflare, accountId: string, videoId: string) { + for (let i = 0; i < 60; i++) { + const video = await client.stream.videos.get(videoId, { account_id: accountId }); + if (video.readyToStream || video.status.state === 'error') return video; + await new Promise(resolve => setTimeout(resolve, 5000)); + } + throw new Error('Video processing timeout'); +} +``` + +## Webhook Handler + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const signature = request.headers.get('Webhook-Signature'); + const body = await request.text(); + if (!signature || !await verifyWebhook(signature, body, env.WEBHOOK_SECRET)) { + return new Response('Unauthorized', { status: 401 }); + } + const payload = JSON.parse(body); + if (payload.readyToStream) console.log(`Video ${payload.uid} ready`); + return new Response('OK'); + } +}; + +async function verifyWebhook(sig: string, body: string, secret: string): Promise { + const parts = Object.fromEntries(sig.split(',').map(p => p.split('='))); + const timestamp = parseInt(parts.time || '0', 10); + if (Math.abs(Date.now() / 1000 - timestamp) > 300) return false; + + const key = await crypto.subtle.importKey( + 'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'] + ); + const computed = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${timestamp}.${body}`)); + const hex = Array.from(new Uint8Array(computed), b => b.toString(16).padStart(2, '0')).join(''); + return hex === parts.sig1; +} +``` + +## Self-Sign JWT (High Volume Tokens) + +For >1k tokens/day. Prerequisites: Create signing key (see configuration.md). + +```typescript +async function selfSignToken(keyId: string, jwkBase64: string, videoId: string, expiresIn = 3600) { + const key = await crypto.subtle.importKey( + 'jwk', JSON.parse(atob(jwkBase64)), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign'] + ); + const now = Math.floor(Date.now() / 1000); + const header = btoa(JSON.stringify({ alg: 'RS256', kid: keyId })).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); + const payload = btoa(JSON.stringify({ sub: videoId, kid: keyId, exp: now + expiresIn, nbf: now })) + .replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); + const message = `${header}.${payload}`; + const sig = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, new TextEncoder().encode(message)); + const b64Sig = btoa(String.fromCharCode(...new Uint8Array(sig))).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); + return `${message}.${b64Sig}`; +} + +// With access rules (geo-restriction) +const payloadWithRules = { + sub: videoId, kid: keyId, exp: now + 3600, nbf: now, + accessRules: [{ type: 'ip.geoip.country', action: 'allow', country: ['US'] }] +}; +``` + +## Best Practices + +- **Use Direct Creator Uploads** - Avoid proxying through servers +- **Enable requireSignedURLs** - Control private content access +- **Self-sign tokens at scale** - Use signing keys for >1k/day +- **Set allowedOrigins** - Prevent hotlinking +- **Use webhooks over polling** - Efficient status updates +- **Set maxDurationSeconds** - Prevent abuse +- **Enable live recordings** - Auto VOD after stream + +## In This Reference + +- [README.md](./README.md) - Overview and quick start +- [configuration.md](./configuration.md) - Setup and config +- [api.md](./api.md) - On-demand video APIs +- [api-live.md](./api-live.md) - Live streaming APIs +- [gotchas.md](./gotchas.md) - Error codes, troubleshooting + +## See Also + +- [workers](../workers/) - Deploy Stream APIs in Workers +- [pages](../pages/) - Integrate Stream with Pages diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5f03bcc6030eb84cbb12a1178de59961c79f089c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/README.md @@ -0,0 +1,102 @@ +# Cloudflare Terraform Provider + +**Expert guidance for Cloudflare Terraform Provider - infrastructure as code for Cloudflare resources.** + +## Core Principles + +- **Provider-first**: Use Terraform provider for ALL infrastructure - never mix with wrangler.jsonc for the same resources +- **State management**: Always use remote state (S3, Terraform Cloud, etc.) for team environments +- **Modular architecture**: Create reusable modules for common patterns (zones, workers, pages) +- **Version pinning**: Always pin provider version with `~>` for predictable upgrades +- **Secret management**: Use variables + environment vars for sensitive data - never hardcode API tokens + +## Provider Version + +| Version | Status | Notes | +|---------|--------|-------| +| 5.x | Current | Auto-generated from OpenAPI, breaking changes from v4 | +| 4.x | Legacy | Manual maintenance, deprecated | + +**Critical:** v5 renamed many resources (`cloudflare_record` → `cloudflare_dns_record`, `cloudflare_worker_*` → `cloudflare_workers_*`). See [gotchas.md](./gotchas.md#v5-breaking-changes) for migration details. + +## Provider Setup + +### Basic Configuration + +```hcl +terraform { + required_version = ">= 1.0" + + required_providers { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 5.15.0" + } + } +} + +provider "cloudflare" { + api_token = var.cloudflare_api_token # or CLOUDFLARE_API_TOKEN env var +} +``` + +### Authentication Methods (priority order) + +1. **API Token** (RECOMMENDED): `api_token` or `CLOUDFLARE_API_TOKEN` + - Create: Dashboard → My Profile → API Tokens + - Scope to specific accounts/zones for security + +2. **Global API Key** (LEGACY): `api_key` + `api_email` or `CLOUDFLARE_API_KEY` + `CLOUDFLARE_EMAIL` + - Less secure, use tokens instead + +3. **User Service Key**: `user_service_key` for Origin CA certificates + + + +## Quick Reference: Common Commands + +```bash +terraform init # Initialize provider +terraform plan # Plan changes +terraform apply # Apply changes +terraform destroy # Destroy resources +terraform import cloudflare_zone.example # Import existing +terraform state list # List resources in state +terraform output # Show outputs +terraform fmt -recursive # Format code +terraform validate # Validate configuration +``` + +## Import Existing Resources + +Use cf-terraforming to generate configs from existing Cloudflare resources: + +```bash +# Install +brew install cloudflare/cloudflare/cf-terraforming + +# Generate HCL from existing resources +cf-terraforming generate --resource-type cloudflare_dns_record --zone + +# Import into Terraform state +cf-terraforming import --resource-type cloudflare_dns_record --zone +``` + +## Reading Order + +1. Start with [README.md](./README.md) for provider setup and authentication +2. Review [configuration.md](./configuration.md) for resource configurations +3. Check [api.md](./api.md) for data sources and existing resource queries +4. See [patterns.md](./patterns.md) for multi-environment and CI/CD patterns +5. Read [gotchas.md](./gotchas.md) for state drift, v5 breaking changes, and troubleshooting + +## In This Reference +- [configuration.md](./configuration.md) - Resources for zones, DNS, workers, KV, R2, D1, Pages, rulesets +- [api.md](./api.md) - Data sources for existing resources +- [patterns.md](./patterns.md) - Architecture patterns, multi-env setup, CI/CD integration +- [gotchas.md](./gotchas.md) - Common issues, security, best practices + +## See Also +- [pulumi](../pulumi/) - Alternative IaC tool for Cloudflare +- [wrangler](../wrangler/) - CLI deployment alternative +- [workers](../workers/) - Worker runtime documentation diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/api.md new file mode 100644 index 0000000000000000000000000000000000000000..8a06c1c2582074b9be5c514bd74e496244839270 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/api.md @@ -0,0 +1,178 @@ +# Terraform Data Sources Reference + +Query existing Cloudflare resources to reference in your configurations. + +## v5 Data Source Names + +| v4 Name | v5 Name | Notes | +|---------|---------|-------| +| `cloudflare_record` | `cloudflare_dns_record` | | +| `cloudflare_worker_script` | `cloudflare_workers_script` | Note: plural | +| `cloudflare_access_*` | `cloudflare_zero_trust_*` | Access → Zero Trust | + +## Zone Data Sources + +```hcl +# Get zone by name +data "cloudflare_zone" "example" { + name = "example.com" +} + +# Use in resources +resource "cloudflare_dns_record" "www" { + zone_id = data.cloudflare_zone.example.id + name = "www" + # ... +} +``` + +## Account Data Sources + +```hcl +# List all accounts +data "cloudflare_accounts" "main" { + name = "My Account" +} + +# Use account ID +resource "cloudflare_worker_script" "api" { + account_id = data.cloudflare_accounts.main.accounts[0].id + # ... +} +``` + +## Worker Data Sources + +```hcl +# Get existing worker script (v5: cloudflare_workers_script) +data "cloudflare_workers_script" "existing" { + account_id = var.account_id + name = "existing-worker" +} + +# Reference in service bindings +resource "cloudflare_workers_script" "consumer" { + service_binding { + name = "UPSTREAM" + service = data.cloudflare_workers_script.existing.name + } +} +``` + +## KV Data Sources + +```hcl +# Get KV namespace +data "cloudflare_workers_kv_namespace" "existing" { + account_id = var.account_id + namespace_id = "abc123" +} + +# Use in worker binding +resource "cloudflare_workers_script" "api" { + kv_namespace_binding { + name = "KV" + namespace_id = data.cloudflare_workers_kv_namespace.existing.id + } +} +``` + +## Lists Data Source + +```hcl +# Get IP lists for WAF rules +data "cloudflare_list" "blocked_ips" { + account_id = var.account_id + name = "blocked_ips" +} +``` + +## IP Ranges Data Source + +```hcl +# Get Cloudflare IP ranges (for firewall rules) +data "cloudflare_ip_ranges" "cloudflare" {} + +output "ipv4_cidrs" { + value = data.cloudflare_ip_ranges.cloudflare.ipv4_cidr_blocks +} + +output "ipv6_cidrs" { + value = data.cloudflare_ip_ranges.cloudflare.ipv6_cidr_blocks +} + +# Use in security group rules (AWS example) +resource "aws_security_group_rule" "allow_cloudflare" { + type = "ingress" + from_port = 443 + to_port = 443 + protocol = "tcp" + cidr_blocks = data.cloudflare_ip_ranges.cloudflare.ipv4_cidr_blocks + security_group_id = aws_security_group.web.id +} +``` + +## Common Patterns + +### Import ID Formats + +| Resource | Import ID Format | +|----------|------------------| +| `cloudflare_zone` | `` | +| `cloudflare_dns_record` | `/` | +| `cloudflare_workers_script` | `/` | +| `cloudflare_workers_kv_namespace` | `/` | +| `cloudflare_r2_bucket` | `/` | +| `cloudflare_d1_database` | `/` | +| `cloudflare_pages_project` | `/` | + +```bash +# Example: Import DNS record +terraform import cloudflare_dns_record.example / +``` + +### Reference Across Modules + +```hcl +# modules/worker/main.tf +data "cloudflare_zone" "main" { + name = var.domain +} + +resource "cloudflare_worker_route" "api" { + zone_id = data.cloudflare_zone.main.id + pattern = "api.${var.domain}/*" + script_name = cloudflare_worker_script.api.name +} +``` + +### Output Important Values + +```hcl +output "zone_id" { + value = cloudflare_zone.main.id + description = "Zone ID for DNS management" +} + +output "worker_url" { + value = "https://${cloudflare_worker_domain.api.hostname}" + description = "Worker API endpoint" +} + +output "kv_namespace_id" { + value = cloudflare_workers_kv_namespace.app.id + sensitive = false +} + +output "name_servers" { + value = cloudflare_zone.main.name_servers + description = "Name servers for domain registration" +} +``` + +## See Also + +- [README](./README.md) - Provider setup +- [Configuration Reference](./configuration.md) - All resource types +- [Patterns](./patterns.md) - Architecture patterns +- [Troubleshooting](./gotchas.md) - Common issues diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..4b5eeb583b3fdbf08b4487b79990b593f4def537 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/configuration.md @@ -0,0 +1,197 @@ +# Terraform Configuration Reference + +Complete resource configurations for Cloudflare infrastructure. + +## Zone & DNS + +```hcl +# Zone + settings +resource "cloudflare_zone" "example" { account = { id = var.account_id }; name = "example.com"; type = "full" } +resource "cloudflare_zone_settings_override" "example" { + zone_id = cloudflare_zone.example.id + settings { ssl = "strict"; always_use_https = "on"; min_tls_version = "1.2"; tls_1_3 = "on"; http3 = "on" } +} + +# DNS records (A, CNAME, MX, TXT) +resource "cloudflare_dns_record" "www" { + zone_id = cloudflare_zone.example.id; name = "www"; content = "192.0.2.1"; type = "A"; proxied = true +} +resource "cloudflare_dns_record" "mx" { + for_each = { "10" = "mail1.example.com", "20" = "mail2.example.com" } + zone_id = cloudflare_zone.example.id; name = "@"; content = each.value; type = "MX"; priority = each.key +} +``` + +## Workers + +### Simple Pattern (Legacy - Still Works) + +```hcl +resource "cloudflare_workers_script" "api" { + account_id = var.account_id; name = "api-worker"; content = file("worker.js") + module = true; compatibility_date = "2025-01-01" + kv_namespace_binding { name = "KV"; namespace_id = cloudflare_workers_kv_namespace.cache.id } + r2_bucket_binding { name = "BUCKET"; bucket_name = cloudflare_r2_bucket.assets.name } + d1_database_binding { name = "DB"; database_id = cloudflare_d1_database.app.id } + secret_text_binding { name = "SECRET"; text = var.secret } +} +``` + +### Gradual Rollouts (Recommended for Production) + +```hcl +resource "cloudflare_worker" "api" { account_id = var.account_id; name = "api-worker" } +resource "cloudflare_worker_version" "api_v1" { + account_id = var.account_id; worker_name = cloudflare_worker.api.name + content = file("worker.js"); content_sha256 = filesha256("worker.js") + compatibility_date = "2025-01-01" + bindings { + kv_namespace { name = "KV"; namespace_id = cloudflare_workers_kv_namespace.cache.id } + r2_bucket { name = "BUCKET"; bucket_name = cloudflare_r2_bucket.assets.name } + } +} +resource "cloudflare_workers_deployment" "api" { + account_id = var.account_id; worker_name = cloudflare_worker.api.name + versions { version_id = cloudflare_worker_version.api_v1.id; percentage = 100 } +} +``` + +### Worker Binding Types (v5) + +| Binding | Attribute | Example | +|---------|-----------|---------| +| KV | `kv_namespace_binding` | `{ name = "KV", namespace_id = "..." }` | +| R2 | `r2_bucket_binding` | `{ name = "BUCKET", bucket_name = "..." }` | +| D1 | `d1_database_binding` | `{ name = "DB", database_id = "..." }` | +| Service | `service_binding` | `{ name = "AUTH", service = "auth-worker" }` | +| Secret | `secret_text_binding` | `{ name = "API_KEY", text = "..." }` | +| Queue | `queue_binding` | `{ name = "QUEUE", queue_name = "..." }` | +| Vectorize | `vectorize_binding` | `{ name = "INDEX", index_name = "..." }` | +| Hyperdrive | `hyperdrive_binding` | `{ name = "DB", id = "..." }` | +| AI | `ai_binding` | `{ name = "AI" }` | +| Browser | `browser_binding` | `{ name = "BROWSER" }` | +| Analytics | `analytics_engine_binding` | `{ name = "ANALYTICS", dataset = "..." }` | +| mTLS | `mtls_certificate_binding` | `{ name = "CERT", certificate_id = "..." }` | + +### Routes & Triggers + +```hcl +resource "cloudflare_worker_route" "api" { + zone_id = cloudflare_zone.example.id; pattern = "api.example.com/*" + script_name = cloudflare_workers_script.api.name +} +resource "cloudflare_worker_cron_trigger" "task" { + account_id = var.account_id; script_name = cloudflare_workers_script.api.name + schedules = ["*/5 * * * *"] +} +``` + +## Storage (KV, R2, D1) + +```hcl +# KV +resource "cloudflare_workers_kv_namespace" "cache" { account_id = var.account_id; title = "cache" } +resource "cloudflare_workers_kv" "config" { + account_id = var.account_id; namespace_id = cloudflare_workers_kv_namespace.cache.id + key_name = "config"; value = jsonencode({ version = "1.0" }) +} + +# R2 +resource "cloudflare_r2_bucket" "assets" { account_id = var.account_id; name = "assets"; location = "WNAM" } + +# D1 (migrations via wrangler) & Queues +resource "cloudflare_d1_database" "app" { account_id = var.account_id; name = "app-db" } +resource "cloudflare_queue" "events" { account_id = var.account_id; name = "events-queue" } +``` + +## Pages + +```hcl +resource "cloudflare_pages_project" "site" { + account_id = var.account_id; name = "site"; production_branch = "main" + deployment_configs { + production { + compatibility_date = "2025-01-01" + environment_variables = { NODE_ENV = "production" } + kv_namespaces = { KV = cloudflare_workers_kv_namespace.cache.id } + d1_databases = { DB = cloudflare_d1_database.app.id } + } + } + build_config { build_command = "npm run build"; destination_dir = "dist" } + source { type = "github"; config { owner = "org"; repo_name = "site"; production_branch = "main" }} +} + +resource "cloudflare_pages_domain" "custom" { + account_id = var.account_id; project_name = cloudflare_pages_project.site.name; domain = "site.example.com" +} +``` + +## Rulesets (WAF, Redirects, Cache) + +```hcl +# WAF +resource "cloudflare_ruleset" "waf" { + zone_id = cloudflare_zone.example.id; name = "WAF"; kind = "zone"; phase = "http_request_firewall_custom" + rules { action = "block"; enabled = true; expression = "(cf.client.bot) and not (cf.verified_bot)" } +} + +# Redirects +resource "cloudflare_ruleset" "redirects" { + zone_id = cloudflare_zone.example.id; name = "Redirects"; kind = "zone"; phase = "http_request_dynamic_redirect" + rules { + action = "redirect"; enabled = true; expression = "(http.request.uri.path eq \"/old\")" + action_parameters { from_value { status_code = 301; target_url { value = "https://example.com/new" }}} + } +} + +# Cache rules +resource "cloudflare_ruleset" "cache" { + zone_id = cloudflare_zone.example.id; name = "Cache"; kind = "zone"; phase = "http_request_cache_settings" + rules { + action = "set_cache_settings"; enabled = true; expression = "(http.request.uri.path matches \"\\.(jpg|png|css|js)$\")" + action_parameters { cache = true; edge_ttl { mode = "override_origin"; default = 86400 }} + } +} +``` + +## Load Balancers + +```hcl +resource "cloudflare_load_balancer_monitor" "http" { + account_id = var.account_id; type = "http"; path = "/health"; interval = 60; timeout = 5 +} +resource "cloudflare_load_balancer_pool" "api" { + account_id = var.account_id; name = "api-pool"; monitor = cloudflare_load_balancer_monitor.http.id + origins { name = "api-1"; address = "192.0.2.1" } + origins { name = "api-2"; address = "192.0.2.2" } +} +resource "cloudflare_load_balancer" "api" { + zone_id = cloudflare_zone.example.id; name = "api.example.com" + default_pool_ids = [cloudflare_load_balancer_pool.api.id]; steering_policy = "geo" +} +``` + +## Access (Zero Trust) + +```hcl +resource "cloudflare_access_application" "admin" { + account_id = var.account_id; name = "Admin"; domain = "admin.example.com"; type = "self_hosted" + session_duration = "24h"; allowed_idps = [cloudflare_access_identity_provider.github.id] +} +resource "cloudflare_access_policy" "allow" { + account_id = var.account_id; application_id = cloudflare_access_application.admin.id + name = "Allow"; decision = "allow"; precedence = 1 + include { email = ["admin@example.com"] } +} +resource "cloudflare_access_identity_provider" "github" { + account_id = var.account_id; name = "GitHub"; type = "github" + config { client_id = var.github_id; client_secret = var.github_secret } +} +``` + +## See Also + +- [README](./README.md) - Provider setup +- [API](./api.md) - Data sources +- [Patterns](./patterns.md) - Use cases +- [Troubleshooting](./gotchas.md) - Issues diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..e87233c792679b2f0cf28888a90ca1ac47af2491 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/gotchas.md @@ -0,0 +1,150 @@ +# Terraform Troubleshooting & Best Practices + +Common issues, security considerations, and best practices. + +## State Drift Issues + +Some resources have known state drift. Add lifecycle blocks to prevent perpetual diffs: + +| Resource | Drift Attributes | Workaround | +|----------|------------------|------------| +| `cloudflare_pages_project` | `deployment_configs.*` | `ignore_changes = [deployment_configs]` | +| `cloudflare_workers_script` | secrets returned as REDACTED | `ignore_changes = [secret_text_binding]` | +| `cloudflare_load_balancer` | `adaptive_routing`, `random_steering` | `ignore_changes = [adaptive_routing, random_steering]` | +| `cloudflare_workers_kv` | special chars in keys (< 5.16.0) | Upgrade to 5.16.0+ | + +```hcl +# Example: Ignore secret drift +resource "cloudflare_workers_script" "api" { + account_id = var.account_id + name = "api-worker" + content = file("worker.js") + secret_text_binding { name = "API_KEY"; text = var.api_key } + + lifecycle { + ignore_changes = [secret_text_binding] + } +} +``` + +## v5 Breaking Changes + +Provider v5 is current (auto-generated from OpenAPI). v4→v5 has breaking changes: + +**Resource Renames:** + +| v4 Resource | v5 Resource | Notes | +|-------------|-------------|-------| +| `cloudflare_record` | `cloudflare_dns_record` | | +| `cloudflare_worker_script` | `cloudflare_workers_script` | Note: plural | +| `cloudflare_worker_*` | `cloudflare_workers_*` | All worker resources | +| `cloudflare_access_*` | `cloudflare_zero_trust_*` | Access → Zero Trust | + +**Attribute Changes:** + +| v4 Attribute | v5 Attribute | Resources | +|--------------|--------------|-----------| +| `zone` | `name` | zone | +| `account_id` | `account.id` | zone (object syntax) | +| `key` | `key_name` | KV | +| `location_hint` | `location` | R2 | + +**State Migration:** + +```bash +# Rename resources in state after v5 upgrade +terraform state mv cloudflare_record.example cloudflare_dns_record.example +terraform state mv cloudflare_worker_script.api cloudflare_workers_script.api +``` + +## Resource-Specific Gotchas + +### R2 Location Case Sensitivity + +**Problem:** Terraform creates R2 bucket but fails on subsequent applies +**Cause:** Location must be UPPERCASE +**Solution:** Use `WNAM`, `ENAM`, `WEUR`, `EEUR`, `APAC` (not `wnam`, `enam`, etc.) + +```hcl +resource "cloudflare_r2_bucket" "assets" { + account_id = var.account_id + name = "assets" + location = "WNAM" # UPPERCASE required +} +``` + +### KV Special Characters (< 5.16.0) + +**Problem:** Keys with `+`, `#`, `%` cause encoding issues +**Cause:** URL encoding bug in provider < 5.16.0 +**Solution:** Upgrade to 5.16.0+ or avoid special chars in keys + +### D1 Migrations + +**Problem:** Terraform creates database but schema is empty +**Cause:** Terraform only creates D1 resource, not schema +**Solution:** Run migrations via wrangler after Terraform apply + +```bash +# After terraform apply +wrangler d1 migrations apply +``` + +### Worker Script Size Limit + +**Problem:** Worker deployment fails with "script too large" +**Cause:** Worker script + dependencies exceed 10 MB limit +**Solution:** Use code splitting, external dependencies, or minification + +### Pages Project Drift + +**Problem:** Pages project shows perpetual diff on `deployment_configs` +**Cause:** Cloudflare API adds default values not in Terraform state +**Solution:** Add lifecycle ignore block (see State Drift table above) + +## Common Errors + +### "Error: couldn't find resource" + +**Cause:** Resource was deleted outside Terraform +**Solution:** Import resource back into state with `terraform import cloudflare_zone.example ` or remove from state with `terraform state rm cloudflare_zone.example` + +### "409 Conflict on worker deployment" + +**Cause:** Worker being deployed by both Terraform and wrangler simultaneously +**Solution:** Choose one deployment method; if using Terraform, remove wrangler deployments + +### "DNS record already exists" + +**Cause:** Existing DNS record not imported into Terraform state +**Solution:** Find record ID in Cloudflare dashboard and import with `terraform import cloudflare_dns_record.example /` + +### "Invalid provider configuration" + +**Cause:** API token missing, invalid, or lacking required permissions +**Solution:** Set `CLOUDFLARE_API_TOKEN` environment variable or check token permissions in dashboard + +### "State locking errors" + +**Cause:** Multiple concurrent Terraform runs or stale lock from crashed process +**Solution:** Remove stale lock with `terraform force-unlock ` (use with caution) + +## Limits + +| Resource | Limit | Notes | +|----------|-------|-------| +| API token rate limit | Varies by plan | Use `api_client_logging = true` to debug +| Worker script size | 10 MB | Includes all dependencies +| KV keys per namespace | Unlimited | Pay per operation +| R2 storage | Unlimited | Pay per GB +| D1 databases | 50,000 per account | Free tier: 10 +| Pages projects | 500 per account | 100 for free accounts +| DNS records | 3,500 per zone | Free plan + +## See Also + +- [README](./README.md) - Provider setup +- [Configuration](./configuration.md) - Resources +- [API](./api.md) - Data sources +- [Patterns](./patterns.md) - Use cases +- Provider docs: https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..60f0540e3954598c5f7c944490987873a6e64dec --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/terraform/patterns.md @@ -0,0 +1,174 @@ +# Terraform Patterns & Use Cases + +Architecture patterns, multi-environment setups, and real-world use cases. + +## Recommended Directory Structure + +``` +terraform/ +├── environments/ +│ ├── production/ +│ │ ├── main.tf +│ │ └── terraform.tfvars +│ └── staging/ +│ ├── main.tf +│ └── terraform.tfvars +├── modules/ +│ ├── zone/ +│ ├── worker/ +│ └── dns/ +└── shared/ # Shared resources across envs + └── main.tf +``` + +**Note:** Cloudflare recommends avoiding modules for provider resources due to v5 auto-generation complexity. Prefer environment directories + shared state instead. + +## Multi-Environment Setup + +```hcl +# Directory: environments/{production,staging}/main.tf + modules/{zone,worker,pages} +module "zone" { + source = "../../modules/zone"; account_id = var.account_id; zone_name = "example.com"; environment = "production" +} +module "api_worker" { + source = "../../modules/worker"; account_id = var.account_id; zone_id = module.zone.zone_id + name = "api-worker-prod"; script = file("../../workers/api.js"); environment = "production" +} +``` + +## R2 State Backend + +```hcl +terraform { + backend "s3" { + bucket = "terraform-state" + key = "cloudflare.tfstate" + region = "auto" + endpoints = { s3 = "https://.r2.cloudflarestorage.com" } + skip_credentials_validation = true + skip_region_validation = true + skip_requesting_account_id = true + skip_metadata_api_check = true + skip_s3_checksum = true + } +} +``` + +## Worker with All Bindings + +```hcl +locals { worker_name = "full-stack-worker" } +resource "cloudflare_workers_kv_namespace" "app" { account_id = var.account_id; title = "${local.worker_name}-kv" } +resource "cloudflare_r2_bucket" "app" { account_id = var.account_id; name = "${local.worker_name}-bucket" } +resource "cloudflare_d1_database" "app" { account_id = var.account_id; name = "${local.worker_name}-db" } + +resource "cloudflare_worker_script" "app" { + account_id = var.account_id; name = local.worker_name; content = file("worker.js"); module = true + compatibility_date = "2025-01-01" + kv_namespace_binding { name = "KV"; namespace_id = cloudflare_workers_kv_namespace.app.id } + r2_bucket_binding { name = "BUCKET"; bucket_name = cloudflare_r2_bucket.app.name } + d1_database_binding { name = "DB"; database_id = cloudflare_d1_database.app.id } + secret_text_binding { name = "API_KEY"; text = var.api_key } +} +``` + +## Wrangler Integration + +**CRITICAL**: Wrangler and Terraform must NOT manage same resources. + +**Terraform**: Zones, DNS, security rules, Access, load balancers, worker deployments (CI/CD), KV/R2/D1 resource creation +**Wrangler**: Local dev (`wrangler dev`), manual deploys, D1 migrations, KV bulk ops, log streaming (`wrangler tail`) + +### CI/CD Pattern + +```hcl +# Terraform creates infrastructure +resource "cloudflare_workers_kv_namespace" "app" { account_id = var.account_id; title = "app-kv" } +resource "cloudflare_d1_database" "app" { account_id = var.account_id; name = "app-db" } +output "kv_namespace_id" { value = cloudflare_workers_kv_namespace.app.id } +output "d1_database_id" { value = cloudflare_d1_database.app.id } +``` + +```yaml +# GitHub Actions: terraform apply → envsubst wrangler.jsonc.template → wrangler deploy +- run: terraform apply -auto-approve +- run: | + export KV_NAMESPACE_ID=$(terraform output -raw kv_namespace_id) + envsubst < wrangler.jsonc.template > wrangler.jsonc +- run: wrangler deploy +``` + +## Use Cases + +### Static Site + API Worker + +```hcl +resource "cloudflare_pages_project" "frontend" { + account_id = var.account_id; name = "frontend"; production_branch = "main" + build_config { build_command = "npm run build"; destination_dir = "dist" } +} +resource "cloudflare_worker_script" "api" { + account_id = var.account_id; name = "api"; content = file("api-worker.js") + d1_database_binding { name = "DB"; database_id = cloudflare_d1_database.api_db.id } +} +resource "cloudflare_dns_record" "frontend" { + zone_id = cloudflare_zone.main.id; name = "app"; content = cloudflare_pages_project.frontend.subdomain; type = "CNAME"; proxied = true +} +resource "cloudflare_worker_route" "api" { + zone_id = cloudflare_zone.main.id; pattern = "api.example.com/*"; script_name = cloudflare_worker_script.api.name +} +``` + +### Multi-Region Load Balancing + +```hcl +resource "cloudflare_load_balancer_pool" "us" { + account_id = var.account_id; name = "us-pool"; monitor = cloudflare_load_balancer_monitor.http.id + origins { name = "us-east"; address = var.us_east_ip } +} +resource "cloudflare_load_balancer_pool" "eu" { + account_id = var.account_id; name = "eu-pool"; monitor = cloudflare_load_balancer_monitor.http.id + origins { name = "eu-west"; address = var.eu_west_ip } +} +resource "cloudflare_load_balancer" "global" { + zone_id = cloudflare_zone.main.id; name = "api.example.com"; steering_policy = "geo" + default_pool_ids = [cloudflare_load_balancer_pool.us.id] + region_pools { region = "WNAM"; pool_ids = [cloudflare_load_balancer_pool.us.id] } + region_pools { region = "WEU"; pool_ids = [cloudflare_load_balancer_pool.eu.id] } +} +``` + +### Secure Admin with Access + +```hcl +resource "cloudflare_pages_project" "admin" { account_id = var.account_id; name = "admin"; production_branch = "main" } +resource "cloudflare_access_application" "admin" { + account_id = var.account_id; name = "Admin"; domain = "admin.example.com"; type = "self_hosted"; session_duration = "24h" + allowed_idps = [cloudflare_access_identity_provider.google.id] +} +resource "cloudflare_access_policy" "allow" { + account_id = var.account_id; application_id = cloudflare_access_application.admin.id + name = "Allow admins"; decision = "allow"; precedence = 1; include { email = var.admin_emails } +} +``` + +### Reusable Module + +```hcl +# modules/cloudflare-zone/main.tf +variable "account_id" { type = string }; variable "domain" { type = string }; variable "ssl_mode" { default = "strict" } +resource "cloudflare_zone" "main" { account = { id = var.account_id }; name = var.domain } +resource "cloudflare_zone_settings_override" "main" { + zone_id = cloudflare_zone.main.id; settings { ssl = var.ssl_mode; always_use_https = "on" } +} +output "zone_id" { value = cloudflare_zone.main.id } + +# Usage: module "prod" { source = "./modules/cloudflare-zone"; account_id = var.account_id; domain = "example.com" } +``` + +## See Also + +- [README](./README.md) - Provider setup +- [Configuration Reference](./configuration.md) - All resource types +- [API Reference](./api.md) - Data sources +- [Troubleshooting](./gotchas.md) - Best practices, common issues diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7e0085aef407d92ff6a7de2b7fcf1f79a03e855e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/README.md @@ -0,0 +1,127 @@ +# Cloudflare Tunnel + +Secure outbound-only connections between infrastructure and Cloudflare's global network. + +## Overview + +Cloudflare Tunnel (formerly Argo Tunnel) enables: +- **Outbound-only connections** - No inbound ports or firewall changes +- **Public hostname routing** - Expose local services to internet +- **Private network access** - Connect internal networks via WARP +- **Zero Trust integration** - Built-in access policies + +**Architecture**: Tunnel (persistent object) → Replica (`cloudflared` process) → Origin services + +**Terminology:** +- **Tunnel**: Named persistent object with UUID +- **Replica**: Individual `cloudflared` process connected to tunnel +- **Config Source**: Where ingress rules stored (local file vs Cloudflare dashboard) +- **Connector**: Legacy term for replica + +## Quick Start + +### Local Config +```bash +# Install cloudflared +brew install cloudflared # macOS + +# Authenticate +cloudflared tunnel login + +# Create tunnel +cloudflared tunnel create my-tunnel + +# Route DNS +cloudflared tunnel route dns my-tunnel app.example.com + +# Run tunnel +cloudflared tunnel run my-tunnel +``` + +### Dashboard Config (Recommended) +1. **Zero Trust** > **Networks** > **Tunnels** > **Create** +2. Name tunnel, copy token +3. Configure routes in dashboard +4. Run: `cloudflared tunnel --no-autoupdate run --token ` + +## Decision Tree + +**Choose config source:** +``` +Need centralized config updates? +├─ Yes → Token-based (dashboard config) +└─ No → Local config file + +Multiple environments (dev/staging/prod)? +├─ Yes → Local config (version controlled) +└─ No → Either works + +Need firewall approval? +└─ See networking.md first +``` + +## Core Commands + +```bash +# Tunnel lifecycle +cloudflared tunnel create +cloudflared tunnel list +cloudflared tunnel info +cloudflared tunnel delete + +# DNS routing +cloudflared tunnel route dns +cloudflared tunnel route list + +# Private network +cloudflared tunnel route ip add 10.0.0.0/8 + +# Run tunnel +cloudflared tunnel run +``` + +## Configuration Example + +```yaml +# ~/.cloudflared/config.yml +tunnel: 6ff42ae2-765d-4adf-8112-31c55c1551ef +credentials-file: /root/.cloudflared/6ff42ae2-765d-4adf-8112-31c55c1551ef.json + +ingress: + - hostname: app.example.com + service: http://localhost:8000 + - hostname: api.example.com + service: https://localhost:8443 + originRequest: + noTLSVerify: true + - service: http_status:404 +``` + +## Reading Order + +**New to Cloudflare Tunnel:** +1. This README (overview, quick start) +2. [networking.md](./networking.md) - Firewall rules, connectivity pre-checks +3. [configuration.md](./configuration.md) - Config file options, ingress rules +4. [patterns.md](./patterns.md) - Docker, Kubernetes, production deployment +5. [gotchas.md](./gotchas.md) - Troubleshooting, best practices + +**Enterprise deployment:** +1. [networking.md](./networking.md) - Corporate firewall requirements +2. [gotchas.md](./gotchas.md) - HA setup, security best practices +3. [patterns.md](./patterns.md) - Kubernetes, rolling updates + +**Programmatic control:** +1. [api.md](./api.md) - REST API, TypeScript SDK + +## In This Reference + +- [networking.md](./networking.md) - Firewall rules, ports, connectivity pre-checks +- [configuration.md](./configuration.md) - Config file options, ingress rules, TLS settings +- [api.md](./api.md) - REST API, TypeScript SDK, token-based tunnels +- [patterns.md](./patterns.md) - Docker, Kubernetes, Terraform, HA, use cases +- [gotchas.md](./gotchas.md) - Troubleshooting, limitations, best practices + +## See Also + +- [workers](../workers/README.md) - Workers with Tunnel integration diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/api.md new file mode 100644 index 0000000000000000000000000000000000000000..faa3013b5082080bf7eeaf9c78121eae6318d8c0 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/api.md @@ -0,0 +1,193 @@ +# Tunnel API + +## Cloudflare API Access + +**Base URL**: `https://api.cloudflare.com/client/v4` + +**Authentication**: +```bash +Authorization: Bearer ${CF_API_TOKEN} +``` + +## TypeScript SDK + +Install: `npm install cloudflare` + +```typescript +import Cloudflare from 'cloudflare'; + +const cf = new Cloudflare({ + apiToken: process.env.CF_API_TOKEN, +}); + +const accountId = process.env.CF_ACCOUNT_ID; +``` + +## Create Tunnel + +### cURL +```bash +curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" \ + -H "Content-Type: application/json" \ + --data '{ + "name": "my-tunnel", + "tunnel_secret": "" + }' +``` + +### TypeScript +```typescript +const tunnel = await cf.zeroTrust.tunnels.create({ + account_id: accountId, + name: 'my-tunnel', + tunnel_secret: Buffer.from(crypto.randomBytes(32)).toString('base64'), +}); + +console.log(`Tunnel ID: ${tunnel.id}`); +``` + +## List Tunnels + +### cURL +```bash +curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" +``` + +### TypeScript +```typescript +const tunnels = await cf.zeroTrust.tunnels.list({ + account_id: accountId, +}); + +for (const tunnel of tunnels.result) { + console.log(`${tunnel.name}: ${tunnel.id}`); +} +``` + +## Get Tunnel Info + +### cURL +```bash +curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels/{tunnel_id}" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" +``` + +### TypeScript +```typescript +const tunnel = await cf.zeroTrust.tunnels.get(tunnelId, { + account_id: accountId, +}); + +console.log(`Status: ${tunnel.status}`); +console.log(`Connections: ${tunnel.connections?.length || 0}`); +``` + +## Update Tunnel Config + +### cURL +```bash +curl -X PUT "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels/{tunnel_id}/configurations" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" \ + -H "Content-Type: application/json" \ + --data '{ + "config": { + "ingress": [ + {"hostname": "app.example.com", "service": "http://localhost:8000"}, + {"service": "http_status:404"} + ] + } + }' +``` + +### TypeScript +```typescript +const config = await cf.zeroTrust.tunnels.configurations.update( + tunnelId, + { + account_id: accountId, + config: { + ingress: [ + { hostname: 'app.example.com', service: 'http://localhost:8000' }, + { service: 'http_status:404' }, + ], + }, + } +); +``` + +## Delete Tunnel + +### cURL +```bash +curl -X DELETE "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels/{tunnel_id}" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" +``` + +### TypeScript +```typescript +await cf.zeroTrust.tunnels.delete(tunnelId, { + account_id: accountId, +}); +``` + +## Token-Based Tunnels (Config Source: Cloudflare) + +Token-based tunnels store config in Cloudflare dashboard instead of local files. + +### Via Dashboard +1. **Zero Trust** > **Networks** > **Tunnels** +2. **Create a tunnel** > **Cloudflared** +3. Configure routes in dashboard +4. Copy token +5. Run on origin: +```bash +cloudflared service install +``` + +### Via Token +```bash +# Run with token (no config file needed) +cloudflared tunnel --no-autoupdate run --token ${TUNNEL_TOKEN} + +# Docker +docker run cloudflare/cloudflared:latest tunnel --no-autoupdate run --token ${TUNNEL_TOKEN} +``` + +### Get Tunnel Token (TypeScript) +```typescript +// Get tunnel to retrieve token +const tunnel = await cf.zeroTrust.tunnels.get(tunnelId, { + account_id: accountId, +}); + +// Token available in tunnel.token (only for config source: cloudflare) +const token = tunnel.token; +``` + +## DNS Routes API + +```bash +# Create DNS route +curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels/{tunnel_id}/connections" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" \ + --data '{"hostname": "app.example.com"}' + +# Delete route +curl -X DELETE "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels/{tunnel_id}/connections/{route_id}" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" +``` + +## Private Network Routes API + +```bash +# Add IP route +curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels/{tunnel_id}/routes" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" \ + --data '{"ip_network": "10.0.0.0/8"}' + +# List IP routes +curl -X GET "https://api.cloudflare.com/client/v4/accounts/{account_id}/tunnels/{tunnel_id}/routes" \ + -H "Authorization: Bearer ${CF_API_TOKEN}" +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..f7e979162fa6c2a79110b805aa98835696d791e1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/configuration.md @@ -0,0 +1,157 @@ +# Tunnel Configuration + +## Config Source + +Tunnels use one of two config sources: + +| Config Source | Storage | Updates | Use Case | +|---------------|---------|---------|----------| +| Local | `config.yml` file | Edit file, restart | Dev, multi-env, version control | +| Cloudflare | Dashboard/API | Instant, no restart | Production, centralized management | + +**Token-based tunnels** = config source: Cloudflare +**Locally-managed tunnels** = config source: local + +## Config File Location + +``` +~/.cloudflared/config.yml # User config +/etc/cloudflared/config.yml # System-wide (Linux) +``` + +## Basic Structure + +```yaml +tunnel: +credentials-file: /path/to/.json + +ingress: + - hostname: app.example.com + service: http://localhost:8000 + - service: http_status:404 # Required catch-all +``` + +## Ingress Rules + +Rules evaluated **top to bottom**, first match wins. + +```yaml +ingress: + # Exact hostname + path regex + - hostname: static.example.com + path: \.(jpg|png|css|js)$ + service: https://localhost:8001 + + # Wildcard hostname + - hostname: "*.example.com" + service: https://localhost:8002 + + # Path only (all hostnames) + - path: /api/.* + service: http://localhost:9000 + + # Catch-all (required) + - service: http_status:404 +``` + +**Validation**: +```bash +cloudflared tunnel ingress validate +cloudflared tunnel ingress rule https://foo.example.com +``` + +## Service Types + +| Protocol | Format | Client Requirement | +|----------|--------|-------------------| +| HTTP | `http://localhost:8000` | Browser | +| HTTPS | `https://localhost:8443` | Browser | +| TCP | `tcp://localhost:2222` | `cloudflared access tcp` | +| SSH | `ssh://localhost:22` | `cloudflared access ssh` | +| RDP | `rdp://localhost:3389` | `cloudflared access rdp` | +| Unix | `unix:/path/to/socket` | Browser | +| Test | `hello_world` | Browser | + +## Origin Configuration + +### Connection Settings +```yaml +originRequest: + connectTimeout: 30s + tlsTimeout: 10s + tcpKeepAlive: 30s + keepAliveTimeout: 90s + keepAliveConnections: 100 +``` + +### TLS Settings +```yaml +originRequest: + noTLSVerify: true # Disable cert verification + originServerName: "app.internal" # Override SNI + caPool: /path/to/ca.pem # Custom CA +``` + +### HTTP Settings +```yaml +originRequest: + disableChunkedEncoding: true + httpHostHeader: "app.internal" + http2Origin: true +``` + +## Private Network Mode + +```yaml +tunnel: +credentials-file: /path/to/creds.json + +warp-routing: + enabled: true +``` + +```bash +cloudflared tunnel route ip add 10.0.0.0/8 my-tunnel +cloudflared tunnel route ip add 192.168.1.100/32 my-tunnel +``` + +## Config Source Comparison + +### Local Config +```yaml +# config.yml +tunnel: +credentials-file: /path/to/.json + +ingress: + - hostname: app.example.com + service: http://localhost:8000 + - service: http_status:404 +``` + +```bash +cloudflared tunnel run my-tunnel +``` + +**Pros:** Version control, multi-environment, offline edits +**Cons:** Requires file distribution, manual restarts + +### Cloudflare Config (Token-Based) +```bash +# No config file needed +cloudflared tunnel --no-autoupdate run --token +``` + +Configure routes in dashboard: **Zero Trust** > **Networks** > **Tunnels** > [Tunnel] > **Public Hostname** + +**Pros:** Centralized updates, no file management, instant route changes +**Cons:** Requires dashboard/API access, less portable + +## Environment Variables + +```bash +TUNNEL_TOKEN= # Token for config source: cloudflare +TUNNEL_ORIGIN_CERT=/path/to/cert.pem # Override cert path (local config) +NO_AUTOUPDATE=true # Disable auto-updates +TUNNEL_LOGLEVEL=debug # Log level +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..f368856550e9f4a560c23e5275489deeffc7f5fd --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/gotchas.md @@ -0,0 +1,147 @@ +# Tunnel Gotchas + +## Common Errors + +### "Error 1016 (Origin DNS Error)" + +**Cause:** Tunnel not running or not connected +**Solution:** +```bash +cloudflared tunnel info my-tunnel # Check status +ps aux | grep cloudflared # Verify running +journalctl -u cloudflared -n 100 # Check logs +``` + +### "Self-signed certificate rejected" + +**Cause:** Origin using self-signed certificate +**Solution:** +```yaml +originRequest: + noTLSVerify: true # Dev only + caPool: /path/to/ca.pem # Custom CA +``` + +### "Connection timeout" + +**Cause:** Origin slow to respond or timeout settings too low +**Solution:** +```yaml +originRequest: + connectTimeout: 60s + tlsTimeout: 20s + keepAliveTimeout: 120s +``` + +### "Tunnel not starting" + +**Cause:** Invalid config, missing credentials, or tunnel doesn't exist +**Solution:** +```bash +cloudflared tunnel ingress validate # Validate config +ls -la ~/.cloudflared/*.json # Verify credentials +cloudflared tunnel list # Verify tunnel exists +``` + +### "Connection already registered" + +**Cause:** Multiple replicas with same connector ID or stale connection +**Solution:** +```bash +# Check active connections +cloudflared tunnel info my-tunnel + +# Wait 60s for stale connection cleanup, or restart with new connector ID +cloudflared tunnel run my-tunnel +``` + +### "Tunnel credentials rotated but connections fail" + +**Cause:** Old cloudflared processes using expired credentials +**Solution:** +```bash +# Stop all cloudflared processes +pkill cloudflared + +# Verify stopped +ps aux | grep cloudflared + +# Restart with new credentials +cloudflared tunnel run my-tunnel +``` + +## Limits + +| Resource/Limit | Value | Notes | +|----------------|-------|-------| +| Free tier | Unlimited tunnels | Unlimited traffic | +| Tunnel replicas | 1000 per tunnel | Max concurrent | +| Connection duration | No hard limit | Hours to days | +| Long-lived connections | May drop during updates | WebSocket, SSH, UDP | +| Replica registration | ~5s TTL | Old replica dropped after 5s no heartbeat | +| Token rotation grace | 24 hours | Old tokens work during grace period | + +## Best Practices + +### Security +1. Use token-based tunnels (config source: cloudflare) for centralized control +2. Enable Access policies for sensitive services +3. Rotate tunnel credentials regularly +4. After rotation: stop all old cloudflared processes within 24h grace period +5. Verify TLS certs (`noTLSVerify: false`) +6. Restrict `bastion` service type + +### Performance +1. Run multiple replicas for HA (2-4 typical, load balanced automatically) +2. Replicas share same tunnel UUID, get unique connector IDs +3. Place `cloudflared` close to origin (same network) +4. Use HTTP/2 for gRPC (`http2Origin: true`) +5. Tune keepalive for long-lived connections +6. Monitor connection counts + +### Configuration +1. Use environment variables for secrets +2. Version control config files +3. Validate before deploying (`cloudflared tunnel ingress validate`) +4. Test rules (`cloudflared tunnel ingress rule `) +5. Document rule order (first match wins) + +### Operations +1. Monitor tunnel health in dashboard (shows active replicas) +2. Set up disconnect alerts (when replica count drops to 0) +3. Graceful shutdown for config updates +4. Update replicas in rolling fashion (update 1, wait, update next) +5. Keep `cloudflared` updated (1 year support window) +6. Use `--no-autoupdate` in prod; control updates manually + +## Debug Mode + +```bash +cloudflared tunnel --loglevel debug run my-tunnel +cloudflared tunnel ingress rule https://app.example.com +``` + +## Migration Strategies + +### From Ngrok +```yaml +# Ngrok: ngrok http 8000 +# Cloudflare Tunnel: +ingress: + - hostname: app.example.com + service: http://localhost:8000 + - service: http_status:404 +``` + +### From VPN +```yaml +# Replace VPN with private network routing +warp-routing: + enabled: true +``` + +```bash +cloudflared tunnel route ip add 10.0.0.0/8 my-tunnel +``` + +Users install WARP client instead of VPN. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/networking.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/networking.md new file mode 100644 index 0000000000000000000000000000000000000000..8c3930d9082f1ced84a7596ff77269f8e1c85deb --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/networking.md @@ -0,0 +1,168 @@ +# Tunnel Networking + +## Connectivity Requirements + +### Outbound Ports + +Cloudflared requires outbound access on: + +| Port | Protocol | Purpose | Required | +|------|----------|---------|----------| +| 7844 | TCP/UDP | Primary tunnel protocol (QUIC) | Yes | +| 443 | TCP | Fallback (HTTP/2) | Yes | + +**Network path:** +``` +cloudflared → edge.argotunnel.com:7844 (preferred) +cloudflared → region.argotunnel.com:443 (fallback) +``` + +### Firewall Rules + +#### Minimal (Production) +```bash +# Outbound only +ALLOW tcp/udp 7844 to *.argotunnel.com +ALLOW tcp 443 to *.argotunnel.com +``` + +#### Full (Recommended) +```bash +# Tunnel connectivity +ALLOW tcp/udp 7844 to *.argotunnel.com +ALLOW tcp 443 to *.argotunnel.com + +# API access (for token-based tunnels) +ALLOW tcp 443 to api.cloudflare.com + +# Updates (optional) +ALLOW tcp 443 to github.com +ALLOW tcp 443 to objects.githubusercontent.com +``` + +### IP Ranges + +Cloudflare Anycast IPs (tunnel endpoints): +``` +# IPv4 +198.41.192.0/24 +198.41.200.0/24 + +# IPv6 +2606:4700::/32 +``` + +**Note:** Use DNS resolution for `*.argotunnel.com` rather than hardcoding IPs. Cloudflare may add edge locations. + +## Pre-Flight Check + +Test connectivity before deploying: + +```bash +# Test DNS resolution +dig edge.argotunnel.com +short + +# Test port 7844 (QUIC/UDP) +nc -zvu edge.argotunnel.com 7844 + +# Test port 443 (HTTP/2 fallback) +nc -zv edge.argotunnel.com 443 + +# Test with cloudflared +cloudflared tunnel --loglevel debug run my-tunnel +# Look for "Registered tunnel connection" +``` + +### Common Connectivity Errors + +| Error | Cause | Solution | +|-------|-------|----------| +| "no such host" | DNS blocked | Allow port 53 UDP/TCP | +| "context deadline exceeded" | Port 7844 blocked | Allow UDP/TCP 7844 | +| "TLS handshake timeout" | Port 443 blocked | Allow TCP 443, disable SSL inspection | + +## Protocol Selection + +Cloudflared automatically selects protocol: + +| Protocol | Port | Priority | Use Case | +|----------|------|----------|----------| +| QUIC | 7844 UDP | 1st (preferred) | Low latency, best performance | +| HTTP/2 | 443 TCP | 2nd (fallback) | QUIC blocked by firewall | + +**Force HTTP/2 fallback:** +```bash +cloudflared tunnel --protocol http2 run my-tunnel +``` + +**Verify active protocol:** +```bash +cloudflared tunnel info my-tunnel +# Shows "connections" with protocol type +``` + +## Private Network Routing + +### WARP Client Requirements + +Users accessing private IPs via WARP need: + +```bash +# Outbound (WARP client) +ALLOW udp 500,4500 to 162.159.*.* (IPsec) +ALLOW udp 2408 to 162.159.*.* (WireGuard) +ALLOW tcp 443 to *.cloudflareclient.com +``` + +### Split Tunnel Configuration + +Route only private networks through tunnel: + +```yaml +# warp-routing config +warp-routing: + enabled: true +``` + +```bash +# Add specific routes +cloudflared tunnel route ip add 10.0.0.0/8 my-tunnel +cloudflared tunnel route ip add 172.16.0.0/12 my-tunnel +cloudflared tunnel route ip add 192.168.0.0/16 my-tunnel +``` + +WARP users can access these IPs without VPN. + +## Network Diagnostics + +### Connection Diagnostics + +```bash +# Check edge selection and connection health +cloudflared tunnel info my-tunnel --output json | jq '.connections[]' + +# Enable metrics endpoint +cloudflared tunnel --metrics localhost:9090 run my-tunnel +curl localhost:9090/metrics | grep cloudflared_tunnel + +# Test latency +curl -w "time_total: %{time_total}\n" -o /dev/null https://myapp.example.com +``` + +## Corporate Network Considerations + +Cloudflared honors proxy environment variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`). + +If corporate proxy intercepts TLS, add corporate root CA to system trust store. + +## Bandwidth and Rate Limits + +| Limit | Value | Notes | +|-------|-------|-------| +| Request size | 100 MB | Single HTTP request | +| Upload speed | No hard limit | Governed by network/plan | +| Concurrent connections | 1000 per tunnel | Across all replicas | +| Requests per second | No limit | Subject to DDoS detection | + +**Large file transfers:** +Use R2 or Workers with chunked uploads instead of streaming through tunnel. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..7ef6d2944bb1085ba15d899cd16734850326843a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/tunnel/patterns.md @@ -0,0 +1,192 @@ +# Tunnel Patterns + +## Docker Deployment + +### Token-Based (Recommended) +```yaml +services: + cloudflared: + image: cloudflare/cloudflared:latest + command: tunnel --no-autoupdate run --token ${TUNNEL_TOKEN} + restart: unless-stopped +``` + +### Local Config +```yaml +services: + cloudflared: + image: cloudflare/cloudflared:latest + volumes: + - ./config.yml:/etc/cloudflared/config.yml:ro + - ./credentials.json:/etc/cloudflared/credentials.json:ro + command: tunnel run +``` + +## Kubernetes Deployment + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: cloudflared +spec: + replicas: 2 + selector: + matchLabels: + app: cloudflared + template: + metadata: + labels: + app: cloudflared + spec: + containers: + - name: cloudflared + image: cloudflare/cloudflared:latest + args: + - tunnel + - --no-autoupdate + - run + - --token + - $(TUNNEL_TOKEN) + env: + - name: TUNNEL_TOKEN + valueFrom: + secretKeyRef: + name: tunnel-credentials + key: token +``` + +## High Availability + +```yaml +# Same config on multiple servers +tunnel: +credentials-file: /path/to/creds.json + +ingress: + - hostname: app.example.com + service: http://localhost:8000 + - service: http_status:404 +``` + +Run same config on multiple machines. Cloudflare automatically load balances. Long-lived connections (WebSocket, SSH) may drop during updates. + +## Use Cases + +### Web Application +```yaml +ingress: + - hostname: myapp.example.com + service: http://localhost:3000 + - service: http_status:404 +``` + +### SSH Access +```yaml +ingress: + - hostname: ssh.example.com + service: ssh://localhost:22 + - service: http_status:404 +``` + +Client: `cloudflared access ssh --hostname ssh.example.com` + +### gRPC Service +```yaml +ingress: + - hostname: grpc.example.com + service: http://localhost:50051 + originRequest: + http2Origin: true + - service: http_status:404 +``` + +## Infrastructure as Code + +### Terraform + +```hcl +resource "random_id" "tunnel_secret" { + byte_length = 32 +} + +resource "cloudflare_tunnel" "app" { + account_id = var.cloudflare_account_id + name = "app-tunnel" + secret = random_id.tunnel_secret.b64_std +} + +resource "cloudflare_tunnel_config" "app" { + account_id = var.cloudflare_account_id + tunnel_id = cloudflare_tunnel.app.id + config { + ingress_rule { + hostname = "app.example.com" + service = "http://localhost:8000" + } + ingress_rule { service = "http_status:404" } + } +} + +resource "cloudflare_record" "app" { + zone_id = var.cloudflare_zone_id + name = "app" + value = cloudflare_tunnel.app.cname + type = "CNAME" + proxied = true +} + +output "tunnel_token" { + value = cloudflare_tunnel.app.tunnel_token + sensitive = true +} +``` + +### Pulumi + +```typescript +import * as cloudflare from "@pulumi/cloudflare"; +import * as random from "@pulumi/random"; + +const secret = new random.RandomId("secret", { byteLength: 32 }); + +const tunnel = new cloudflare.ZeroTrustTunnelCloudflared("tunnel", { + accountId: accountId, + name: "app-tunnel", + secret: secret.b64Std, +}); + +const config = new cloudflare.ZeroTrustTunnelCloudflaredConfig("config", { + accountId: accountId, + tunnelId: tunnel.id, + config: { + ingressRules: [ + { hostname: "app.example.com", service: "http://localhost:8000" }, + { service: "http_status:404" }, + ], + }, +}); + +new cloudflare.Record("dns", { + zoneId: zoneId, + name: "app", + value: tunnel.cname, + type: "CNAME", + proxied: true, +}); +``` + +## Service Installation + +### Linux systemd +```bash +cloudflared service install +systemctl start cloudflared && systemctl enable cloudflared +journalctl -u cloudflared -f # Logs +``` + +### macOS launchd +```bash +sudo cloudflared service install +sudo launchctl start com.cloudflare.cloudflared +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cc4b39e8df76cd3cad8e06aaa9f8dab9e05087b1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/README.md @@ -0,0 +1,82 @@ +# Cloudflare TURN Service + +Expert guidance for implementing Cloudflare TURN Service in WebRTC applications. + +## Overview + +Cloudflare TURN (Traversal Using Relays around NAT) Service is a managed relay service for WebRTC applications. TURN acts as a relay point for traffic between WebRTC clients and SFUs, particularly when direct peer-to-peer communication is obstructed by NATs or firewalls. The service runs on Cloudflare's global anycast network across 310+ cities. + +## Key Characteristics + +- **Anycast Architecture**: Automatically connects clients to the closest Cloudflare location +- **Global Network**: Available across Cloudflare's entire network (excluding China Network) +- **Zero Configuration**: No need to manually select regions or servers +- **Protocol Support**: STUN/TURN over UDP, TCP, and TLS +- **Free Tier**: Free when used with Cloudflare Calls SFU, otherwise $0.05/GB outbound + +## In This Reference + +| File | Purpose | +|------|---------| +| [api.md](./api.md) | Credentials API, TURN key management, types, constraints | +| [configuration.md](./configuration.md) | Worker setup, wrangler.jsonc, env vars, IP allowlisting | +| [patterns.md](./patterns.md) | Implementation patterns, use cases, integration examples | +| [gotchas.md](./gotchas.md) | Troubleshooting, limits, security, common mistakes | + +## Reading Order + +| Task | Files to Read | Est. Tokens | +|------|---------------|-------------| +| Quick start | README only | ~500 | +| Generate credentials | README → api | ~1300 | +| Worker integration | README → configuration → patterns | ~2000 | +| Debug connection | gotchas | ~700 | +| Security review | api → gotchas | ~1500 | +| Enterprise firewall | configuration | ~600 | + +## Service Addresses and Ports + +### STUN over UDP +- **Primary**: `stun.cloudflare.com:3478/udp` +- **Alternate**: `stun.cloudflare.com:53/udp` (blocked by browsers, not recommended) + +### TURN over UDP +- **Primary**: `turn.cloudflare.com:3478/udp` +- **Alternate**: `turn.cloudflare.com:53/udp` (blocked by browsers) + +### TURN over TCP +- **Primary**: `turn.cloudflare.com:3478/tcp` +- **Alternate**: `turn.cloudflare.com:80/tcp` + +### TURN over TLS +- **Primary**: `turn.cloudflare.com:5349/tcp` +- **Alternate**: `turn.cloudflare.com:443/tcp` + +## Quick Start + +1. **Create TURN key via API**: see [api.md#create-turn-key](./api.md#create-turn-key) +2. **Generate credentials**: see [api.md#generate-temporary-credentials](./api.md#generate-temporary-credentials) +3. **Configure Worker**: see [configuration.md#cloudflare-worker-integration](./configuration.md#cloudflare-worker-integration) +4. **Implement client**: see [patterns.md#basic-turn-configuration-browser](./patterns.md#basic-turn-configuration-browser) + +## When to Use TURN + +- **Restrictive NATs**: Symmetric NATs that block direct connections +- **Corporate firewalls**: Environments blocking WebRTC ports +- **Mobile networks**: Carrier-grade NAT scenarios +- **Predictable connectivity**: When reliability > efficiency + +## Related Cloudflare Services + +- **Cloudflare Calls SFU**: Managed Selective Forwarding Unit (TURN free when used with SFU) +- **Cloudflare Stream**: Video streaming with WHIP/WHEP support +- **Cloudflare Workers**: Backend for credential generation +- **Cloudflare KV**: Credential caching +- **Cloudflare Durable Objects**: Session state management + +## Additional Resources + +- [Cloudflare Calls Documentation](https://developers.cloudflare.com/calls/) +- [Cloudflare TURN Service Docs](https://developers.cloudflare.com/realtime/turn/) +- [Cloudflare API Reference](https://developers.cloudflare.com/api/resources/calls/subresources/turn/) +- [Orange Meets (Open Source Example)](https://github.com/cloudflare/orange) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/api.md new file mode 100644 index 0000000000000000000000000000000000000000..269ed7522144a485199605aa9d2d09692611d965 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/api.md @@ -0,0 +1,239 @@ +# TURN API Reference + +Complete API documentation for Cloudflare TURN service credentials and key management. + +## Authentication + +All endpoints require Cloudflare API token with "Calls Write" permission. + +Base URL: `https://api.cloudflare.com/client/v4` + +## TURN Key Management + +### List TURN Keys + +``` +GET /accounts/{account_id}/calls/turn_keys +``` + +### Get TURN Key Details + +``` +GET /accounts/{account_id}/calls/turn_keys/{key_id} +``` + +### Create TURN Key + +``` +POST /accounts/{account_id}/calls/turn_keys +Content-Type: application/json + +{ + "name": "my-turn-key" +} +``` + +**Response includes**: +- `uid`: Key identifier +- `key`: The actual secret key (only returned on creation—save immediately) +- `name`: Human-readable name +- `created`: ISO 8601 timestamp +- `modified`: ISO 8601 timestamp + +### Update TURN Key + +``` +PUT /accounts/{account_id}/calls/turn_keys/{key_id} +Content-Type: application/json + +{ + "name": "updated-name" +} +``` + +### Delete TURN Key + +``` +DELETE /accounts/{account_id}/calls/turn_keys/{key_id} +``` + +## Generate Temporary Credentials + +``` +POST https://rtc.live.cloudflare.com/v1/turn/keys/{key_id}/credentials/generate +Authorization: Bearer {key_secret} +Content-Type: application/json + +{ + "ttl": 86400 +} +``` + +### Credential Constraints + +| Parameter | Min | Max | Default | Notes | +|-----------|-----|-----|---------|-------| +| ttl | 1 | 172800 (48hrs) | varies | API rejects values >172800 | + +**CRITICAL**: Maximum TTL is 48 hours (172800 seconds). API will reject requests exceeding this limit. + +### Response Schema + +```json +{ + "iceServers": { + "urls": [ + "stun:stun.cloudflare.com:3478", + "turn:turn.cloudflare.com:3478?transport=udp", + "turn:turn.cloudflare.com:3478?transport=tcp", + "turn:turn.cloudflare.com:53?transport=udp", + "turn:turn.cloudflare.com:80?transport=tcp", + "turns:turn.cloudflare.com:5349?transport=tcp", + "turns:turn.cloudflare.com:443?transport=tcp" + ], + "username": "1738035200:user123", + "credential": "base64encodedhmac==" + } +} +``` + +**Port 53 Warning**: Filter port 53 URLs for browser clients—blocked by Chrome/Firefox. See [gotchas.md](./gotchas.md#using-port-53-in-browsers). + +## Revoke Credentials + +``` +POST https://rtc.live.cloudflare.com/v1/turn/keys/{key_id}/credentials/revoke +Authorization: Bearer {key_secret} +Content-Type: application/json + +{ + "username": "1738035200:user123" +} +``` + +**Response**: 204 No Content + +Billing stops immediately. Active connection drops after short delay (~seconds). + +## TypeScript Types + +```typescript +interface CloudflareTURNConfig { + keyId: string; + keySecret: string; + ttl?: number; // Max 172800 (48 hours) +} + +interface TURNCredentialsRequest { + ttl?: number; // Max 172800 seconds +} + +interface TURNCredentialsResponse { + iceServers: { + urls: string[]; + username: string; + credential: string; + }; +} + +interface RTCIceServer { + urls: string | string[]; + username?: string; + credential?: string; + credentialType?: "password"; +} + +interface TURNKeyResponse { + uid: string; + key: string; // Only present on creation + name: string; + created: string; + modified: string; +} +``` + +## Validation Function + +```typescript +function validateRTCIceServer(obj: unknown): obj is RTCIceServer { + if (!obj || typeof obj !== 'object') { + return false; + } + + const server = obj as Record; + + if (typeof server.urls !== 'string' && !Array.isArray(server.urls)) { + return false; + } + + if (server.username && typeof server.username !== 'string') { + return false; + } + + if (server.credential && typeof server.credential !== 'string') { + return false; + } + + return true; +} +``` + +## Type-Safe Credential Generation + +```typescript +async function fetchTURNServers( + config: CloudflareTURNConfig +): Promise { + // Validate TTL constraint + const ttl = config.ttl ?? 3600; + if (ttl > 172800) { + throw new Error('TTL cannot exceed 172800 seconds (48 hours)'); + } + + const response = await fetch( + `https://rtc.live.cloudflare.com/v1/turn/keys/${config.keyId}/credentials/generate`, + { + method: 'POST', + headers: { + 'Authorization': `Bearer ${config.keySecret}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ ttl }) + } + ); + + if (!response.ok) { + throw new Error(`TURN credential generation failed: ${response.status}`); + } + + const data = await response.json(); + + // Filter port 53 for browser clients + const filteredUrls = data.iceServers.urls.filter( + (url: string) => !url.includes(':53') + ); + + const iceServers = [ + { urls: 'stun:stun.cloudflare.com:3478' }, + { + urls: filteredUrls, + username: data.iceServers.username, + credential: data.iceServers.credential, + credentialType: 'password' as const + } + ]; + + // Validate before returning + if (!iceServers.every(validateRTCIceServer)) { + throw new Error('Invalid ICE server configuration received'); + } + + return iceServers; +} +``` + +## See Also + +- [configuration.md](./configuration.md) - Worker setup, environment variables +- [patterns.md](./patterns.md) - Implementation examples using these APIs +- [gotchas.md](./gotchas.md) - Security best practices, common mistakes diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..2d49736e8980511962fa3a4a5b1f2cc0c6b65045 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/configuration.md @@ -0,0 +1,179 @@ +# TURN Configuration + +Setup and configuration for Cloudflare TURN service in Workers and applications. + +## Environment Variables + +```bash +# .env +CLOUDFLARE_ACCOUNT_ID=your_account_id +CLOUDFLARE_API_TOKEN=your_api_token +TURN_KEY_ID=your_turn_key_id +TURN_KEY_SECRET=your_turn_key_secret +``` + +Validate with zod: + +```typescript +import { z } from 'zod'; + +const envSchema = z.object({ + CLOUDFLARE_ACCOUNT_ID: z.string().min(1), + CLOUDFLARE_API_TOKEN: z.string().min(1), + TURN_KEY_ID: z.string().min(1), + TURN_KEY_SECRET: z.string().min(1) +}); + +export const config = envSchema.parse(process.env); +``` + +## wrangler.jsonc + +```jsonc +{ + "name": "turn-credentials-api", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", + "vars": { + "TURN_KEY_ID": "your-turn-key-id" // Non-sensitive, can be in vars + }, + "env": { + "production": { + "kv_namespaces": [ + { + "binding": "CREDENTIALS_CACHE", + "id": "your-kv-namespace-id" + } + ] + } + } +} +``` + +**Store secrets separately**: +```bash +wrangler secret put TURN_KEY_SECRET +``` + +## Cloudflare Worker Integration + +### Worker Binding Types + +```typescript +interface Env { + TURN_KEY_ID: string; + TURN_KEY_SECRET: string; + CREDENTIALS_CACHE?: KVNamespace; +} + +export default { + async fetch(request: Request, env: Env): Promise { + // See patterns.md for implementation + } +} +``` + +### Basic Worker Example + +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + if (request.url.endsWith('/turn-credentials')) { + // Validate client auth + const authHeader = request.headers.get('Authorization'); + if (!authHeader) { + return new Response('Unauthorized', { status: 401 }); + } + + const response = await fetch( + `https://rtc.live.cloudflare.com/v1/turn/keys/${env.TURN_KEY_ID}/credentials/generate`, + { + method: 'POST', + headers: { + 'Authorization': `Bearer ${env.TURN_KEY_SECRET}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ ttl: 3600 }) + } + ); + + if (!response.ok) { + return new Response('Failed to generate credentials', { status: 500 }); + } + + const data = await response.json(); + + // Filter port 53 for browser clients + const filteredUrls = data.iceServers.urls.filter( + (url: string) => !url.includes(':53') + ); + + return Response.json({ + iceServers: [ + { urls: 'stun:stun.cloudflare.com:3478' }, + { + urls: filteredUrls, + username: data.iceServers.username, + credential: data.iceServers.credential + } + ] + }); + } + + return new Response('Not found', { status: 404 }); + } +}; +``` + +## IP Allowlisting (Enterprise/Firewall) + +For strict firewalls, allowlist these IPs for `turn.cloudflare.com`: + +| Type | Address | Protocol | +|------|---------|----------| +| IPv4 | 141.101.90.1/32 | All | +| IPv4 | 162.159.207.1/32 | All | +| IPv6 | 2a06:98c1:3200::1/128 | All | +| IPv6 | 2606:4700:48::1/128 | All | + +**IMPORTANT**: These IPs may change with 14-day notice. Monitor DNS: + +```bash +# Check A and AAAA records +dig turn.cloudflare.com A +dig turn.cloudflare.com AAAA +``` + +Set up automated monitoring to detect IP changes and update allowlists within 14 days. + +## IPv6 Support + +- **Client-to-TURN**: Both IPv4 and IPv6 supported +- **Relay addresses**: IPv4 only (no RFC 6156 support) +- **TCP relaying**: Not supported (RFC 6062) + +Clients can connect via IPv6, but relayed traffic uses IPv4 addresses. + +## TLS Configuration + +### Supported TLS Versions +- TLS 1.1 +- TLS 1.2 +- TLS 1.3 + +### Recommended Ciphers (TLS 1.3) +- AEAD-AES128-GCM-SHA256 +- AEAD-AES256-GCM-SHA384 +- AEAD-CHACHA20-POLY1305-SHA256 + +### Recommended Ciphers (TLS 1.2) +- ECDHE-ECDSA-AES128-GCM-SHA256 +- ECDHE-RSA-AES128-GCM-SHA256 +- ECDHE-RSA-AES128-SHA (also TLS 1.1) +- AES128-GCM-SHA256 + +## See Also + +- [api.md](./api.md) - TURN key creation, credential generation API +- [patterns.md](./patterns.md) - Full Worker implementation patterns +- [gotchas.md](./gotchas.md) - Security best practices, troubleshooting diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..e72395d28fdc06ba47565e2e3f86b8592767fdc5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/gotchas.md @@ -0,0 +1,231 @@ +# TURN Gotchas & Troubleshooting + +Common mistakes, security best practices, and troubleshooting for Cloudflare TURN. + +## Quick Reference + +| Issue | Solution | Details | +|-------|----------|---------| +| Credentials not working | Check TTL ≤ 48hrs | [See Troubleshooting](#issue-turn-credentials-not-working) | +| Connection drops after ~48hrs | Implement credential refresh | [See Connection Drops](#issue-connection-drops-after-48-hours) | +| Port 53 fails in browser | Filter server-side | [See Port 53](#using-port-53-in-browsers) | +| High packet loss | Check rate limits | [See Rate Limits](#limits-per-turn-allocation) | +| Connection fails after maintenance | Implement ICE restart | [See ICE Restart](#ice-restart-required-scenarios) | + +## Critical Constraints + +| Constraint | Value | Consequence if Violated | +|------------|-------|-------------------------| +| Max credential TTL | 48 hours (172800s) | API rejects request | +| Credential revocation delay | ~seconds | Billing stops immediately, connection drops shortly | +| IP allowlist update window | 14 days (if IPs change) | Connection fails if IPs change | +| Packet rate | 5-10k pps per allocation | Packet drops | +| Data rate | 50-100 Mbps per allocation | Packet drops | +| Unique IP rate | >5 new IPs/sec | Packet drops | + +## Limits Per TURN Allocation + +**Per user** (not account-wide): + +- **IP addresses**: >5 new unique IPs per second +- **Packet rate**: 5-10k packets per second (inbound/outbound) +- **Data rate**: 50-100 Mbps (inbound/outbound) +- **MTU**: No specific limit +- **Burst rates**: Higher than documented + +Exceeding limits results in **packet drops**. + +## Common Mistakes + +### Setting TTL > 48 hours + +```typescript +// ❌ BAD: API will reject +const creds = await generate({ ttl: 604800 }); // 7 days + +// ✅ GOOD: +const creds = await generate({ ttl: 86400 }); // 24 hours +``` + +### Hardcoding IPs without monitoring + +```typescript +// ❌ BAD: IPs can change with 14-day notice +const iceServers = [{ urls: 'turn:141.101.90.1:3478' }]; + +// ✅ GOOD: Use DNS +const iceServers = [{ urls: 'turn:turn.cloudflare.com:3478' }]; +``` + +### Using port 53 in browsers + +```typescript +// ❌ BAD: Blocked by Chrome/Firefox +urls: ['turn:turn.cloudflare.com:53'] + +// ✅ GOOD: Filter port 53 +urls: urls.filter(url => !url.includes(':53')) +``` + +### Not handling credential expiry + +```typescript +// ❌ BAD: Credentials expire but call continues → connection drops +const creds = await fetchCreds(); +const pc = new RTCPeerConnection({ iceServers: creds }); + +// ✅ GOOD: Refresh before expiry +setInterval(() => refreshCredentials(pc), 3000000); // 50 min +``` + +### Missing ICE restart support + +```typescript +// ❌ BAD: No recovery from TURN maintenance +pc.addEventListener('iceconnectionstatechange', () => { + console.log('State changed:', pc.iceConnectionState); +}); + +// ✅ GOOD: Implement ICE restart +pc.addEventListener('iceconnectionstatechange', async () => { + if (pc.iceConnectionState === 'failed') { + await refreshCredentials(pc); + pc.restartIce(); + } +}); +``` + +### Exposing TURN key secret client-side + +```typescript +// ❌ BAD: Secret exposed to client +const secret = 'your-turn-key-secret'; +const response = await fetch(`https://rtc.live.cloudflare.com/v1/turn/...`, { + headers: { 'Authorization': `Bearer ${secret}` } +}); + +// ✅ GOOD: Generate credentials server-side +const response = await fetch('/api/turn-credentials'); +``` + +## ICE Restart Required Scenarios + +These events require ICE restart (see [patterns.md](./patterns.md#ice-restart-pattern)): + +1. **TURN server maintenance** (occasional on Cloudflare's network) +2. **Network topology changes** (anycast routing changes) +3. **Credential refresh** during long sessions (>1 hour) +4. **Connection failure** (iceConnectionState === 'failed') + +Implement in all production apps: + +```typescript +pc.addEventListener('iceconnectionstatechange', async () => { + if (pc.iceConnectionState === 'failed' || + pc.iceConnectionState === 'disconnected') { + await refreshTURNCredentials(pc); + pc.restartIce(); + const offer = await pc.createOffer({ iceRestart: true }); + await pc.setLocalDescription(offer); + // Send offer to peer via signaling... + } +}); +``` + +Reference: [RFC 8445 Section 2.4](https://datatracker.ietf.org/doc/html/rfc8445#section-2.4) + +## Security Checklist + +- [ ] Credentials generated server-side only (never client-side) +- [ ] TURN_KEY_SECRET in wrangler secrets, not vars +- [ ] TTL ≤ expected session duration (and ≤ 48 hours) +- [ ] Rate limiting on credential generation endpoint +- [ ] Client authentication before issuing credentials +- [ ] Credential revocation API for compromised sessions +- [ ] No hardcoded IPs (or DNS monitoring in place) +- [ ] Port 53 filtered for browser clients + +## Troubleshooting + +### Issue: TURN credentials not working + +**Check:** +- Key ID and secret are correct +- Credentials haven't expired (check TTL) +- TTL doesn't exceed 172800 seconds (48 hours) +- Server can reach rtc.live.cloudflare.com +- Network allows outbound HTTPS + +**Solution:** +```typescript +// Validate before using +if (ttl > 172800) { + throw new Error('TTL cannot exceed 48 hours'); +} +``` + +### Issue: Slow connection establishment + +**Solutions:** +- Ensure proper ICE candidate gathering +- Check network latency to Cloudflare edge +- Verify firewall allows WebRTC ports (3478, 5349, 443) +- Consider using TURN over TLS (port 443) for corporate networks + +### Issue: High packet loss + +**Check:** +- Not exceeding rate limits (5-10k pps) +- Not exceeding bandwidth limits (50-100 Mbps) +- Not connecting to too many unique IPs (>5/sec) +- Client network quality + +### Issue: Connection drops after ~48 hours + +**Cause**: Credentials expired (48hr max) + +**Solution**: +- Set TTL to expected session duration +- Implement credential refresh with setConfiguration() +- Use ICE restart if connection fails + +```typescript +// Refresh credentials before expiry +const refreshInterval = ttl * 1000 - 60000; // 1 min early +setInterval(async () => { + await refreshTURNCredentials(pc); +}, refreshInterval); +``` + +### Issue: Port 53 URLs in browser fail silently + +**Cause**: Chrome/Firefox block port 53 + +**Solution**: Filter port 53 URLs server-side: + +```typescript +const filtered = urls.filter(url => !url.includes(':53')); +``` + +### Issue: Hardcoded IPs stop working + +**Cause**: Cloudflare changed IP addresses (14-day notice) + +**Solution**: +- Use DNS hostnames (`turn.cloudflare.com`) +- Monitor DNS changes with automated alerts +- Update allowlists within 14 days if using IP allowlisting + +## Cost Optimization + +1. Use appropriate TTLs (don't over-provision) +2. Implement credential caching +3. Set `iceTransportPolicy: 'all'` to try direct first (use `'relay'` only when necessary) +4. Monitor bandwidth usage +5. Free when used with Cloudflare Calls SFU + +## See Also + +- [api.md](./api.md) - Credential generation API, revocation +- [configuration.md](./configuration.md) - IP allowlisting, monitoring +- [patterns.md](./patterns.md) - ICE restart, credential refresh patterns diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..54fd364d5c4e5062966a2489a6f25f5ddcc7e456 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turn/patterns.md @@ -0,0 +1,213 @@ +# TURN Implementation Patterns + +Production-ready patterns for implementing Cloudflare TURN in WebRTC applications. + +## Prerequisites + +Before implementing these patterns, ensure you have: +- TURN key created: see [api.md#create-turn-key](./api.md#create-turn-key) +- Worker configured: see [configuration.md#cloudflare-worker-integration](./configuration.md#cloudflare-worker-integration) + +## Basic TURN Configuration (Browser) + +```typescript +interface RTCIceServer { + urls: string | string[]; + username?: string; + credential?: string; + credentialType?: "password" | "oauth"; +} + +async function getTURNConfig(): Promise { + const response = await fetch('/api/turn-credentials'); + const data = await response.json(); + + return [ + { + urls: 'stun:stun.cloudflare.com:3478' + }, + { + urls: [ + 'turn:turn.cloudflare.com:3478?transport=udp', + 'turn:turn.cloudflare.com:3478?transport=tcp', + 'turns:turn.cloudflare.com:5349?transport=tcp', + 'turns:turn.cloudflare.com:443?transport=tcp' + ], + username: data.username, + credential: data.credential, + credentialType: 'password' + } + ]; +} + +// Use in RTCPeerConnection +const iceServers = await getTURNConfig(); +const peerConnection = new RTCPeerConnection({ iceServers }); +``` + +## Port Selection Strategy + +Recommended order for browser clients: + +1. **3478/udp** (primary, lowest latency) +2. **3478/tcp** (fallback for UDP-blocked networks) +3. **5349/tls** (corporate firewalls, most reliable) +4. **443/tls** (alternate TLS port, firewall-friendly) + +**Avoid port 53**—blocked by Chrome and Firefox. + +```typescript +function filterICEServersForBrowser(urls: string[]): string[] { + return urls + .filter(url => !url.includes(':53')) // Remove port 53 + .sort((a, b) => { + // Prioritize UDP over TCP over TLS + if (a.includes('transport=udp')) return -1; + if (b.includes('transport=udp')) return 1; + if (a.includes('transport=tcp') && !a.startsWith('turns:')) return -1; + if (b.includes('transport=tcp') && !b.startsWith('turns:')) return 1; + return 0; + }); +} +``` + +## Credential Refresh (Mid-Session) + +When credentials expire during long calls: + +```typescript +async function refreshTURNCredentials(pc: RTCPeerConnection): Promise { + const newCreds = await fetch('/turn-credentials').then(r => r.json()); + const config = pc.getConfiguration(); + config.iceServers = newCreds.iceServers; + pc.setConfiguration(config); + // Note: setConfiguration() does NOT trigger ICE restart + // Combine with restartIce() if connection fails +} + +// Auto-refresh before expiry +setInterval(async () => { + await refreshTURNCredentials(peerConnection); +}, 3000000); // 50 minutes if TTL is 1 hour +``` + +## ICE Restart Pattern + +After network change, TURN server maintenance, or credential expiry: + +```typescript +pc.addEventListener('iceconnectionstatechange', async () => { + if (pc.iceConnectionState === 'failed') { + console.warn('ICE connection failed, restarting...'); + + // Refresh credentials + await refreshTURNCredentials(pc); + + // Trigger ICE restart + pc.restartIce(); + const offer = await pc.createOffer({ iceRestart: true }); + await pc.setLocalDescription(offer); + + // Send offer to peer via signaling channel... + } +}); +``` + +## Credentials Caching Pattern + +```typescript +class TURNCredentialsManager { + private creds: { username: string; credential: string; urls: string[]; expiresAt: number; } | null = null; + + async getCredentials(keyId: string, keySecret: string): Promise { + const now = Date.now(); + + if (this.creds && this.creds.expiresAt > now) { + return this.buildIceServers(this.creds); + } + + const ttl = 3600; + if (ttl > 172800) throw new Error('TTL max 48hrs'); + + const res = await fetch( + `https://rtc.live.cloudflare.com/v1/turn/keys/${keyId}/credentials/generate`, + { + method: 'POST', + headers: { 'Authorization': `Bearer ${keySecret}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ ttl }) + } + ); + + const data = await res.json(); + const filteredUrls = data.iceServers.urls.filter((url: string) => !url.includes(':53')); + + this.creds = { + username: data.iceServers.username, + credential: data.iceServers.credential, + urls: filteredUrls, + expiresAt: now + (ttl * 1000) - 60000 + }; + + return this.buildIceServers(this.creds); + } + + private buildIceServers(c: { username: string; credential: string; urls: string[] }): RTCIceServer[] { + return [ + { urls: 'stun:stun.cloudflare.com:3478' }, + { urls: c.urls, username: c.username, credential: c.credential, credentialType: 'password' as const } + ]; + } +} +``` + +## Common Use Cases + +```typescript +// Video conferencing: TURN as fallback +const config = { iceServers: await getTURNConfig(), iceTransportPolicy: 'all' }; + +// IoT/predictable connectivity: force TURN +const config = { iceServers: await getTURNConfig(), iceTransportPolicy: 'relay' }; + +// Screen sharing: reduce overhead +const pc = new RTCPeerConnection({ iceServers: await getTURNConfig(), bundlePolicy: 'max-bundle' }); +``` + +## Integration with Cloudflare Calls SFU + +```typescript +// TURN is automatically used when needed +// Cloudflare Calls handles TURN + SFU coordination +const session = await callsClient.createSession({ + appId: 'your-app-id', + sessionId: 'meeting-123' +}); +``` + +## Debugging ICE Connectivity + +```typescript +pc.addEventListener('icecandidate', (event) => { + if (event.candidate) { + console.log('ICE candidate:', event.candidate.type, event.candidate.protocol); + } +}); + +pc.addEventListener('iceconnectionstatechange', () => { + console.log('ICE state:', pc.iceConnectionState); +}); + +// Check selected candidate pair +const stats = await pc.getStats(); +stats.forEach(report => { + if (report.type === 'candidate-pair' && report.selected) { + console.log('Selected:', report); + } +}); +``` + +## See Also + +- [api.md](./api.md) - Credential generation API, types +- [configuration.md](./configuration.md) - Worker setup, environment variables +- [gotchas.md](./gotchas.md) - Common mistakes, troubleshooting diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/README.md new file mode 100644 index 0000000000000000000000000000000000000000..409039b7af4ffe583630ed55138ea344c051cf5e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/README.md @@ -0,0 +1,99 @@ +# Cloudflare Turnstile Implementation Skill Reference + +Expert guidance for implementing Cloudflare Turnstile - a smart CAPTCHA alternative that protects websites from bots without showing traditional CAPTCHA puzzles. + +## Overview + +Turnstile is a user-friendly CAPTCHA alternative that runs challenges in the background without user interaction. It validates visitors automatically using signals like browser behavior, device fingerprinting, and machine learning. + +## Widget Types + +| Type | Interaction | Use Case | +|------|-------------|----------| +| **Managed** (default) | Shows checkbox when needed | Forms, logins - balance UX and security | +| **Non-Interactive** | Invisible, runs automatically | Frictionless UX, low-risk actions | +| **Invisible** | Hidden, triggered programmatically | Pre-clearance, API calls, headless | + +## Quick Start + +### Implicit Rendering (HTML-based) +```html + + + + +
+
+ +
+``` + +### Explicit Rendering (JavaScript-based) +```html +
+ + +``` + +### Server Validation (Required) +```javascript +// Cloudflare Workers +export default { + async fetch(request) { + const formData = await request.formData(); + const token = formData.get('cf-turnstile-response'); + + const result = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + secret: env.TURNSTILE_SECRET, + response: token, + remoteip: request.headers.get('CF-Connecting-IP') + }) + }); + + const validation = await result.json(); + if (!validation.success) { + return new Response('Invalid CAPTCHA', { status: 400 }); + } + // Process form... + } +} +``` + +## Testing Keys + +**Critical for development/testing:** + +| Type | Key | Behavior | +|------|-----|----------| +| **Site Key (Always Passes)** | `1x00000000000000000000AA` | Widget succeeds, token validates | +| **Site Key (Always Blocks)** | `2x00000000000000000000AB` | Widget fails visibly | +| **Site Key (Force Challenge)** | `3x00000000000000000000FF` | Always shows interactive challenge | +| **Secret Key (Testing)** | `1x0000000000000000000000000000000AA` | Validates test tokens | + +**Note:** Test keys work on `localhost` and any domain. Do NOT use in production. + +## Key Constraints + +- **Token expiry:** 5 minutes after generation +- **Single-use:** Each token can only be validated once +- **Server validation required:** Client-side checks are insufficient + +## Reading Order + +1. **[configuration.md](configuration.md)** - Setup, widget options, script loading +2. **[api.md](api.md)** - JavaScript API, siteverify endpoints, TypeScript types +3. **[patterns.md](patterns.md)** - Form integration, framework examples, validation patterns +4. **[gotchas.md](gotchas.md)** - Common errors, debugging, limitations + +## See Also + +- [Cloudflare Turnstile Docs](https://developers.cloudflare.com/turnstile/) +- [Dashboard](https://dash.cloudflare.com/?to=/:account/turnstile) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/api.md new file mode 100644 index 0000000000000000000000000000000000000000..23cfefb15bac701c2cbbdbf2c0c595dfc25e4f72 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/api.md @@ -0,0 +1,240 @@ +# API Reference + +## Client-Side JavaScript API + +The Turnstile JavaScript API is available at `window.turnstile` after loading the script. + +### `turnstile.render(container, options)` + +Renders a Turnstile widget into a container element. + +**Parameters:** +- `container` (string | HTMLElement): CSS selector or DOM element +- `options` (TurnstileOptions): Configuration object (see [configuration.md](configuration.md)) + +**Returns:** `string` - Widget ID for use with other API methods + +**Example:** +```javascript +const widgetId = window.turnstile.render('#my-container', { + sitekey: 'YOUR_SITE_KEY', + callback: (token) => console.log('Success:', token), + 'error-callback': (code) => console.error('Error:', code) +}); +``` + +### `turnstile.reset(widgetId)` + +Resets a widget (clears token, resets challenge state). Useful when form validation fails. + +**Parameters:** +- `widgetId` (string): Widget ID from `render()`, or container element + +**Returns:** `void` + +**Example:** +```javascript +// Reset on form error +if (!validateForm()) { + window.turnstile.reset(widgetId); +} +``` + +### `turnstile.remove(widgetId)` + +Removes a widget from the DOM completely. + +**Parameters:** +- `widgetId` (string): Widget ID from `render()` + +**Returns:** `void` + +**Example:** +```javascript +// Cleanup on navigation +window.turnstile.remove(widgetId); +``` + +### `turnstile.getResponse(widgetId)` + +Gets the current token from a widget (if challenge completed). + +**Parameters:** +- `widgetId` (string): Widget ID from `render()`, or container element + +**Returns:** `string | undefined` - Token string, or undefined if not ready + +**Example:** +```javascript +const token = window.turnstile.getResponse(widgetId); +if (token) { + submitForm(token); +} +``` + +### `turnstile.isExpired(widgetId)` + +Checks if a widget's token has expired (>5 minutes old). + +**Parameters:** +- `widgetId` (string): Widget ID from `render()` + +**Returns:** `boolean` - True if expired + +**Example:** +```javascript +if (window.turnstile.isExpired(widgetId)) { + window.turnstile.reset(widgetId); +} +``` + +## Callback Signatures + +```typescript +type TurnstileCallback = (token: string) => void; +type ErrorCallback = (errorCode: string) => void; +type TimeoutCallback = () => void; +type ExpiredCallback = () => void; +type BeforeInteractiveCallback = () => void; +type AfterInteractiveCallback = () => void; +type UnsupportedCallback = () => void; +``` + +## Siteverify API (Server-Side) + +**Endpoint:** `https://challenges.cloudflare.com/turnstile/v0/siteverify` + +### Request + +**Method:** POST +**Content-Type:** `application/json` or `application/x-www-form-urlencoded` + +```typescript +interface SiteverifyRequest { + secret: string; // Your secret key (never expose client-side) + response: string; // Token from cf-turnstile-response + remoteip?: string; // User's IP (optional but recommended) + idempotency_key?: string; // Unique key for idempotent validation +} +``` + +**Example:** +```javascript +// Cloudflare Workers +const result = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + secret: env.TURNSTILE_SECRET, + response: token, + remoteip: request.headers.get('CF-Connecting-IP') + }) +}); +const data = await result.json(); +``` + +### Response + +```typescript +interface SiteverifyResponse { + success: boolean; // Validation result + challenge_ts?: string; // ISO timestamp of challenge + hostname?: string; // Hostname where widget was solved + 'error-codes'?: string[]; // Error codes if success=false + action?: string; // Action name from widget config + cdata?: string; // Custom data from widget config +} +``` + +**Example Success:** +```json +{ + "success": true, + "challenge_ts": "2024-01-15T10:30:00Z", + "hostname": "example.com", + "action": "login", + "cdata": "user123" +} +``` + +**Example Failure:** +```json +{ + "success": false, + "error-codes": ["timeout-or-duplicate"] +} +``` + +## Error Codes + +| Code | Cause | Solution | +|------|-------|----------| +| `missing-input-secret` | Secret key not provided | Include `secret` in request | +| `invalid-input-secret` | Secret key is wrong | Check secret key in dashboard | +| `missing-input-response` | Token not provided | Include `response` token | +| `invalid-input-response` | Token is invalid/malformed | Verify token from widget | +| `timeout-or-duplicate` | Token expired (>5min) or reused | Generate new token, validate once | +| `internal-error` | Cloudflare server error | Retry with exponential backoff | +| `bad-request` | Malformed request | Check JSON/form encoding | + +## TypeScript Types + +```typescript +interface TurnstileOptions { + sitekey: string; + action?: string; + cData?: string; + callback?: (token: string) => void; + 'error-callback'?: (errorCode: string) => void; + 'expired-callback'?: () => void; + 'timeout-callback'?: () => void; + 'before-interactive-callback'?: () => void; + 'after-interactive-callback'?: () => void; + 'unsupported-callback'?: () => void; + theme?: 'light' | 'dark' | 'auto'; + size?: 'normal' | 'compact' | 'flexible'; + tabindex?: number; + 'response-field'?: boolean; + 'response-field-name'?: string; + retry?: 'auto' | 'never'; + 'retry-interval'?: number; + language?: string; + execution?: 'render' | 'execute'; + appearance?: 'always' | 'execute' | 'interaction-only'; + 'refresh-expired'?: 'auto' | 'manual' | 'never'; +} + +interface Turnstile { + render(container: string | HTMLElement, options: TurnstileOptions): string; + reset(widgetId: string): void; + remove(widgetId: string): void; + getResponse(widgetId: string): string | undefined; + isExpired(widgetId: string): boolean; + execute(container?: string | HTMLElement, options?: TurnstileOptions): void; +} + +declare global { + interface Window { + turnstile: Turnstile; + onloadTurnstileCallback?: () => void; + } +} +``` + +## Script Loading + +```html + + + + + + + + + +``` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..14a0377b6d1115589ad1917b39f661307f7f928f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/configuration.md @@ -0,0 +1,222 @@ +# Configuration + +## Script Loading + +### Basic (Implicit Rendering) +```html + +``` +Automatically renders widgets with `class="cf-turnstile"` on page load. + +### Explicit Rendering +```html + +``` +Manual control over when/where widgets render via `window.turnstile.render()`. + +### With Load Callback +```html + + +``` + +### Compatibility Mode +```html + +``` +Provides `grecaptcha` API for Google reCAPTCHA drop-in replacement. + +## Widget Configuration + +### Complete Options Object + +```javascript +{ + // Required + sitekey: 'YOUR_SITE_KEY', // Widget sitekey from dashboard + + // Callbacks + callback: (token) => {}, // Success - token ready + 'error-callback': (code) => {}, // Error occurred + 'expired-callback': () => {}, // Token expired (>5min) + 'timeout-callback': () => {}, // Challenge timeout + 'before-interactive-callback': () => {}, // Before showing checkbox + 'after-interactive-callback': () => {}, // After user interacts + 'unsupported-callback': () => {}, // Browser doesn't support Turnstile + + // Appearance + theme: 'auto', // 'light' | 'dark' | 'auto' + size: 'normal', // 'normal' | 'compact' | 'flexible' + tabindex: 0, // Tab order (accessibility) + language: 'auto', // ISO 639-1 code or 'auto' + + // Behavior + execution: 'render', // 'render' (auto) | 'execute' (manual) + appearance: 'always', // 'always' | 'execute' | 'interaction-only' + retry: 'auto', // 'auto' | 'never' + 'retry-interval': 8000, // Retry interval (ms), default 8000 + 'refresh-expired': 'auto', // 'auto' | 'manual' | 'never' + + // Form Integration + 'response-field': true, // Add hidden input (default: true) + 'response-field-name': 'cf-turnstile-response', // Hidden input name + + // Analytics & Data + action: 'login', // Action name (for analytics) + cData: 'user-session-123', // Custom data (returned in siteverify) +} +``` + +### Key Options Explained + +**`execution`:** +- `'render'` (default): Challenge starts immediately on render +- `'execute'`: Wait for `turnstile.execute()` call + +**`appearance`:** +- `'always'` (default): Widget always visible +- `'execute'`: Hidden until `execute()` called +- `'interaction-only'`: Hidden until user interaction needed + +**`refresh-expired`:** +- `'auto'` (default): Auto-refresh expired tokens +- `'manual'`: App must call `reset()` after expiry +- `'never'`: No refresh, expired-callback triggered + +**`retry`:** +- `'auto'` (default): Auto-retry failed challenges +- `'never'`: Don't retry, trigger error-callback + +## HTML Data Attributes + +For implicit rendering, use data attributes on `
`: + +| JavaScript Property | HTML Data Attribute | Example | +|---------------------|---------------------|---------| +| `sitekey` | `data-sitekey` | `data-sitekey="YOUR_KEY"` | +| `action` | `data-action` | `data-action="login"` | +| `cData` | `data-cdata` | `data-cdata="session-123"` | +| `callback` | `data-callback` | `data-callback="onSuccess"` | +| `error-callback` | `data-error-callback` | `data-error-callback="onError"` | +| `expired-callback` | `data-expired-callback` | `data-expired-callback="onExpired"` | +| `timeout-callback` | `data-timeout-callback` | `data-timeout-callback="onTimeout"` | +| `theme` | `data-theme` | `data-theme="dark"` | +| `size` | `data-size` | `data-size="compact"` | +| `tabindex` | `data-tabindex` | `data-tabindex="0"` | +| `response-field` | `data-response-field` | `data-response-field="false"` | +| `response-field-name` | `data-response-field-name` | `data-response-field-name="token"` | +| `retry` | `data-retry` | `data-retry="never"` | +| `retry-interval` | `data-retry-interval` | `data-retry-interval="5000"` | +| `language` | `data-language` | `data-language="en"` | +| `execution` | `data-execution` | `data-execution="execute"` | +| `appearance` | `data-appearance` | `data-appearance="interaction-only"` | +| `refresh-expired` | `data-refresh-expired` | `data-refresh-expired="manual"` | + +**Example:** +```html +
+``` + +## Content Security Policy + +Add these directives to CSP header/meta tag: + +``` +script-src https://challenges.cloudflare.com; +frame-src https://challenges.cloudflare.com; +``` + +**Full Example:** +```html + +``` + +## Framework-Specific Setup + +### React +```bash +npm install @marsidev/react-turnstile +``` +```jsx +import Turnstile from '@marsidev/react-turnstile'; + + console.log(token)} +/> +``` + +### Vue +```bash +npm install vue-turnstile +``` +```vue + + +``` + +### Svelte +```bash +npm install svelte-turnstile +``` +```svelte + + +``` + +### Next.js (App Router) +```tsx +// app/components/TurnstileWidget.tsx +'use client'; +import { useEffect, useRef } from 'react'; + +export default function TurnstileWidget({ sitekey, onSuccess }) { + const ref = useRef(null); + + useEffect(() => { + if (ref.current && window.turnstile) { + const widgetId = window.turnstile.render(ref.current, { + sitekey, + callback: onSuccess + }); + return () => window.turnstile.remove(widgetId); + } + }, [sitekey, onSuccess]); + + return
; +} +``` + +## Cloudflare Pages Plugin + +```bash +npm install @cloudflare/pages-plugin-turnstile +``` + +```typescript +// functions/_middleware.ts +import turnstilePlugin from '@cloudflare/pages-plugin-turnstile'; + +export const onRequest = turnstilePlugin({ + secret: 'YOUR_SECRET_KEY', + onError: () => new Response('CAPTCHA failed', { status: 403 }) +}); +``` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..35cc1e3f62a48097d55ad1943fd1f76771c750d3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/gotchas.md @@ -0,0 +1,218 @@ +# Troubleshooting & Gotchas + +## Critical Rules + +### ❌ Skipping Server-Side Validation +**Problem:** Client-only validation is easily bypassed. + +**Solution:** Always validate on server. +```javascript +// CORRECT - Server validates token +app.post('/submit', async (req, res) => { + const token = req.body['cf-turnstile-response']; + const validation = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { + method: 'POST', + body: JSON.stringify({ secret: SECRET, response: token }) + }).then(r => r.json()); + + if (!validation.success) return res.status(403).json({ error: 'CAPTCHA failed' }); +}); +``` + +### ❌ Exposing Secret Key +**Problem:** Secret key leaked in client-side code. + +**Solution:** Server-side validation only. Never send secret to client. + +### ❌ Reusing Tokens (Single-Use Rule) +**Problem:** Tokens are single-use. Revalidation fails with `timeout-or-duplicate`. + +**Solution:** Generate new token for each submission. Reset widget on error. +```javascript +if (!response.ok) window.turnstile.reset(widgetId); +``` + +### ❌ Not Handling Token Expiry +**Problem:** Tokens expire after 5 minutes. + +**Solution:** Handle expiry callback or use auto-refresh. +```javascript +window.turnstile.render('#container', { + sitekey: 'YOUR_SITE_KEY', + 'refresh-expired': 'auto', // or 'manual' with expired-callback + 'expired-callback': () => window.turnstile.reset(widgetId) +}); +``` + +## Common Errors + +| Error | Cause | Solution | +|-------|-------|----------| +| **Widget not rendering** | Incorrect sitekey, CSP blocking, file:// protocol | Check sitekey, add CSP for challenges.cloudflare.com, use http:// | +| **timeout-or-duplicate** | Token expired (>5min) or reused | Generate fresh token, don't cache >5min | +| **invalid-input-secret** | Wrong secret key | Verify secret from dashboard, check env vars | +| **missing-input-response** | Token not sent | Check form field name is 'cf-turnstile-response' | + +## Framework Gotchas + +### React: Widget Re-mounting +**Problem:** Widget re-renders on state change, losing token. + +**Solution:** Control lifecycle with useRef. +```tsx +function TurnstileWidget({ onToken }) { + const containerRef = useRef(null); + const widgetIdRef = useRef(null); + + useEffect(() => { + if (containerRef.current && !widgetIdRef.current) { + widgetIdRef.current = window.turnstile.render(containerRef.current, { + sitekey: 'YOUR_SITE_KEY', + callback: onToken + }); + } + return () => { + if (widgetIdRef.current) { + window.turnstile.remove(widgetIdRef.current); + widgetIdRef.current = null; + } + }; + }, []); + + return
; +} +``` + +### React StrictMode: Double Render +**Problem:** Widget renders twice in dev due to StrictMode. + +**Solution:** Use cleanup function. +```tsx +useEffect(() => { + const widgetId = window.turnstile.render('#container', { sitekey }); + return () => window.turnstile.remove(widgetId); +}, []); +``` + +### Next.js: SSR Hydration +**Problem:** `window.turnstile` undefined during SSR. + +**Solution:** Use `'use client'` or dynamic import with `ssr: false`. +```tsx +'use client'; +export default function Turnstile() { /* component */ } +``` + +### SPA: Navigation Without Cleanup +**Problem:** Navigating leaves orphaned widgets. + +**Solution:** Remove widget in cleanup. +```javascript +// Vue +onBeforeUnmount(() => window.turnstile.remove(widgetId)); + +// React +useEffect(() => () => window.turnstile.remove(widgetId), []); +``` + +## Network & Security + +### CSP Blocking +**Problem:** Content Security Policy blocks script/iframe. + +**Solution:** Add CSP directives. +```html + +``` + +### IP Address Forwarding +**Problem:** Server receives proxy IP instead of client IP. + +**Solution:** Use correct header. +```javascript +// Cloudflare Workers +const ip = request.headers.get('CF-Connecting-IP'); + +// Behind proxy +const ip = request.headers.get('X-Forwarded-For')?.split(',')[0]; +``` + +### CORS (Siteverify) +**Problem:** CORS error calling siteverify from browser. + +**Solution:** Never call siteverify client-side. Call your backend, backend calls siteverify. + +## Limits & Constraints + +| Limit | Value | Impact | +|-------|-------|--------| +| Token validity | 5 minutes | Must regenerate after expiry | +| Token use | Single-use | Cannot revalidate same token | +| Widget size | 300x65px (normal), 130x120px (compact) | Plan layout | + +## Debugging + +### Console Logging +```javascript +window.turnstile.render('#container', { + sitekey: 'YOUR_SITE_KEY', + callback: (token) => console.log('✓ Token:', token), + 'error-callback': (code) => console.error('✗ Error:', code), + 'expired-callback': () => console.warn('⏱ Expired'), + 'timeout-callback': () => console.warn('⏱ Timeout') +}); +``` + +### Check Token State +```javascript +const token = window.turnstile.getResponse(widgetId); +console.log('Token:', token || 'NOT READY'); +console.log('Expired:', window.turnstile.isExpired(widgetId)); +``` + +### Test Keys (Use First) +Always develop with test keys before production: +- Site: `1x00000000000000000000AA` +- Secret: `1x0000000000000000000000000000000AA` + +### Network Tab +- Verify `api.js` loads (200 OK) +- Check siteverify request/response +- Look for 4xx/5xx errors + +## Misconfigurations + +### Wrong Key Pairing +**Problem:** Site key from one widget, secret from another. + +**Solution:** Verify site key and secret are from same widget in dashboard. + +### Test Keys in Production +**Problem:** Using test keys in production. + +**Solution:** Environment-based keys. +```javascript +const SITE_KEY = process.env.NODE_ENV === 'production' + ? process.env.TURNSTILE_SITE_KEY + : '1x00000000000000000000AA'; +``` + +### Missing Environment Variables +**Problem:** Secret undefined on server. + +**Solution:** Check .env and verify loading. +```bash +# .env +TURNSTILE_SECRET=your_secret_here + +# Verify +console.log('Secret loaded:', !!process.env.TURNSTILE_SECRET); +``` + +## Reference + +- [Turnstile Docs](https://developers.cloudflare.com/turnstile/) +- [Dashboard](https://dash.cloudflare.com/?to=/:account/turnstile) +- [Error Codes](https://developers.cloudflare.com/turnstile/troubleshooting/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..52b3bc740b854d9a614ff436647f4b23b92fc84a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/turnstile/patterns.md @@ -0,0 +1,193 @@ +# Common Patterns + +## Form Integration + +### Basic Form (Implicit Rendering) + +```html + + + + + + +
+ +
+ +
+ + +``` + +### Controlled Form (Explicit Rendering) + +```javascript + + +``` + +## Framework Patterns + +### React + +```tsx +import { useState } from 'react'; +import Turnstile from '@marsidev/react-turnstile'; + +export default function Form() { + const [token, setToken] = useState(null); + + return ( +
{ + e.preventDefault(); + if (!token) return; + await fetch('/api/submit', { + method: 'POST', + body: JSON.stringify({ 'cf-turnstile-response': token }) + }); + }}> + + + + ); +} +``` + +### Vue / Svelte + +```vue + + + + + token = e.detail.token} /> +``` + +## Server Validation + +### Cloudflare Workers + +```typescript +interface Env { + TURNSTILE_SECRET: string; +} + +export default { + async fetch(request: Request, env: Env): Promise { + if (request.method !== 'POST') { + return new Response('Method not allowed', { status: 405 }); + } + + const formData = await request.formData(); + const token = formData.get('cf-turnstile-response'); + + if (!token) { + return new Response('Missing token', { status: 400 }); + } + + // Validate token + const ip = request.headers.get('CF-Connecting-IP'); + const result = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + secret: env.TURNSTILE_SECRET, + response: token, + remoteip: ip + }) + }); + + const validation = await result.json(); + + if (!validation.success) { + return new Response('CAPTCHA validation failed', { status: 403 }); + } + + // Process form... + return new Response('Success'); + } +}; +``` + +### Pages Functions + +```typescript +// functions/submit.ts - same pattern as Workers, use ctx.env and ctx.request +export const onRequestPost: PagesFunction<{ TURNSTILE_SECRET: string }> = async (ctx) => { + const token = (await ctx.request.formData()).get('cf-turnstile-response'); + // Validate with ctx.env.TURNSTILE_SECRET (same as Workers pattern above) +}; +``` + +## Advanced Patterns + +### Pre-Clearance (Invisible) + +```html +
+ + + + +``` + +### Token Refresh on Expiry + +```javascript +let widgetId = window.turnstile.render('#container', { + sitekey: 'YOUR_SITE_KEY', + 'refresh-expired': 'manual', + 'expired-callback': () => { + console.log('Token expired, refreshing...'); + window.turnstile.reset(widgetId); + } +}); +``` + +## Testing + +### Environment-Based Keys + +```javascript +const SITE_KEY = process.env.NODE_ENV === 'production' + ? 'YOUR_PRODUCTION_SITE_KEY' + : '1x00000000000000000000AA'; // Always passes + +const SECRET_KEY = process.env.NODE_ENV === 'production' + ? process.env.TURNSTILE_SECRET + : '1x0000000000000000000000000000000AA'; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1031c84d7f246254b6492ef11919661924df0a63 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/README.md @@ -0,0 +1,113 @@ +# Cloudflare WAF Expert Skill Reference + +**Expertise**: Cloudflare Web Application Firewall (WAF) configuration, custom rules, managed rulesets, rate limiting, attack detection, and API integration + +## Overview + +Cloudflare WAF protects web applications from attacks through managed rulesets and custom rules. + +**Detection (Managed Rulesets)** +- Pre-configured rules maintained by Cloudflare +- CVE-based rules, OWASP Top 10 coverage +- Three main rulesets: Cloudflare Managed, OWASP CRS, Exposed Credentials +- Actions: log, block, challenge, js_challenge, managed_challenge + +**Mitigation (Custom Rules & Rate Limiting)** +- Custom expressions using Wirefilter syntax +- Attack score-based blocking (`cf.waf.score`) +- Rate limiting with per-IP, per-user, or custom characteristics +- Actions: block, challenge, js_challenge, managed_challenge, log, skip + +## Quick Start + +### Deploy Cloudflare Managed Ruleset +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ apiToken: process.env.CF_API_TOKEN }); + +// Deploy managed ruleset to zone +await client.rulesets.create({ + zone_id: 'zone_id', + kind: 'zone', + phase: 'http_request_firewall_managed', + name: 'Deploy Cloudflare Managed Ruleset', + rules: [{ + action: 'execute', + action_parameters: { + id: 'efb7b8c949ac4650a09736fc376e9aee', // Cloudflare Managed Ruleset + }, + expression: 'true', + enabled: true, + }], +}); +``` + +### Create Custom Rule +```typescript +// Block requests with attack score >= 40 +await client.rulesets.create({ + zone_id: 'zone_id', + kind: 'zone', + phase: 'http_request_firewall_custom', + name: 'Custom WAF Rules', + rules: [{ + action: 'block', + expression: 'cf.waf.score gt 40', + description: 'Block high attack scores', + enabled: true, + }], +}); +``` + +### Create Rate Limit +```typescript +await client.rulesets.create({ + zone_id: 'zone_id', + kind: 'zone', + phase: 'http_ratelimit', + name: 'API Rate Limits', + rules: [{ + action: 'block', + expression: 'http.request.uri.path eq "/api/login"', + action_parameters: { + ratelimit: { + characteristics: ['cf.colo.id', 'ip.src'], + period: 60, + requests_per_period: 10, + mitigation_timeout: 600, + }, + }, + enabled: true, + }], +}); +``` + +## Managed Ruleset Quick Reference + +| Ruleset Name | ID | Coverage | +|--------------|----|---------| +| Cloudflare Managed | `efb7b8c949ac4650a09736fc376e9aee` | OWASP Top 10, CVEs | +| OWASP Core Ruleset | `4814384a9e5d4991b9815dcfc25d2f1f` | OWASP ModSecurity CRS | +| Exposed Credentials Check | `c2e184081120413c86c3ab7e14069605` | Credential stuffing | + +## Phases + +WAF rules execute in specific phases: +- `http_request_firewall_managed` - Managed rulesets +- `http_request_firewall_custom` - Custom rules +- `http_ratelimit` - Rate limiting rules +- `http_request_sbfm` - Super Bot Fight Mode (Pro+) + +## Reading Order + +1. **[api.md](api.md)** - SDK methods, expressions, actions, parameters +2. **[configuration.md](configuration.md)** - Setup with Wrangler, Terraform, Pulumi +3. **[patterns.md](patterns.md)** - Common patterns: deploy managed, rate limiting, skip, override +4. **[gotchas.md](gotchas.md)** - Execution order, limits, expression errors + +## See Also + +- [Cloudflare WAF Docs](https://developers.cloudflare.com/waf/) +- [Ruleset Engine](https://developers.cloudflare.com/ruleset-engine/) +- [Expression Reference](https://developers.cloudflare.com/ruleset-engine/rules-language/) \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/api.md new file mode 100644 index 0000000000000000000000000000000000000000..d867b9b87e09943b8351590ad4a22bc8aa0ed352 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/api.md @@ -0,0 +1,202 @@ +# API Reference + +## SDK Setup + +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ + apiToken: process.env.CF_API_TOKEN, +}); +``` + +## Core Methods + +```typescript +// List rulesets +await client.rulesets.list({ zone_id: 'zone_id', phase: 'http_request_firewall_managed' }); + +// Get ruleset +await client.rulesets.get({ zone_id: 'zone_id', ruleset_id: 'ruleset_id' }); + +// Create ruleset +await client.rulesets.create({ + zone_id: 'zone_id', + kind: 'zone', + phase: 'http_request_firewall_custom', + name: 'Custom WAF Rules', + rules: [{ action: 'block', expression: 'cf.waf.score gt 40', enabled: true }], +}); + +// Update ruleset (include rule id to keep existing, omit id for new rules) +await client.rulesets.update({ + zone_id: 'zone_id', + ruleset_id: 'ruleset_id', + rules: [ + { id: 'rule_id', action: 'block', expression: 'cf.waf.score gt 40', enabled: true }, + { action: 'challenge', expression: 'http.request.uri.path contains "/admin"', enabled: true }, + ], +}); + +// Delete ruleset +await client.rulesets.delete({ zone_id: 'zone_id', ruleset_id: 'ruleset_id' }); +``` + +## Actions & Phases + +### Actions by Phase + +| Action | Custom | Managed | Rate Limit | Description | +|--------|--------|---------|------------|-------------| +| `block` | ✅ | ❌ | ✅ | Block request with 403 | +| `challenge` | ✅ | ❌ | ✅ | Show CAPTCHA challenge | +| `js_challenge` | ✅ | ❌ | ✅ | JS-based challenge | +| `managed_challenge` | ✅ | ❌ | ✅ | Smart challenge (recommended) | +| `log` | ✅ | ❌ | ✅ | Log only, don't block | +| `skip` | ✅ | ❌ | ❌ | Skip rule evaluation | +| `execute` | ❌ | ✅ | ❌ | Deploy managed ruleset | + +### Phases (Execution Order) + +1. `http_request_firewall_custom` - Custom rules (first line of defense) +2. `http_request_firewall_managed` - Managed rulesets (pre-configured protection) +3. `http_ratelimit` - Rate limiting (request throttling) +4. `http_request_sbfm` - Super Bot Fight Mode (Pro+ only) + +## Expression Syntax + +### Fields + +```typescript +// Request properties +http.request.method // GET, POST, etc. +http.request.uri.path // /api/users +http.host // example.com + +// IP and Geolocation +ip.src // 192.0.2.1 +ip.geoip.country // US, GB, etc. +ip.geoip.continent // NA, EU, etc. + +// Attack detection +cf.waf.score // 0-100 attack score +cf.waf.score.sqli // SQL injection score +cf.waf.score.xss // XSS score + +// Headers & Cookies +http.request.headers["authorization"][0] +http.request.cookies["session"][0] +lower(http.user_agent) // Lowercase user agent +``` + +### Operators + +```typescript +// Comparison +eq // Equal +ne // Not equal +lt // Less than +le // Less than or equal +gt // Greater than +ge // Greater than or equal + +// String matching +contains // Substring match +matches // Regex match (use carefully) +starts_with // Prefix match +ends_with // Suffix match + +// List operations +in // Value in list +not // Logical NOT +and // Logical AND +or // Logical OR +``` + +### Expression Examples + +```typescript +'cf.waf.score gt 40' // Attack score +'http.request.uri.path eq "/api/login" and http.request.method eq "POST"' // Path + method +'ip.src in {192.0.2.0/24 203.0.113.0/24}' // IP blocking +'ip.geoip.country in {"CN" "RU" "KP"}' // Country blocking +'http.user_agent contains "bot"' // User agent +'not http.request.headers["authorization"][0]' // Header check +'(cf.waf.score.sqli gt 20 or cf.waf.score.xss gt 20) and http.request.uri.path starts_with "/api"' // Complex +``` + +## Rate Limiting Configuration + +```typescript +{ + action: 'block', + expression: 'http.request.uri.path starts_with "/api"', + action_parameters: { + ratelimit: { + // Characteristics define uniqueness: 'ip.src', 'cf.colo.id', + // 'http.request.headers["key"][0]', 'http.request.cookies["session"][0]' + characteristics: ['cf.colo.id', 'ip.src'], // Recommended: per-IP per-datacenter + period: 60, // Time window in seconds + requests_per_period: 100, // Max requests in period + mitigation_timeout: 600, // Block duration in seconds + counting_expression: 'http.request.method ne "GET"', // Optional: filter counted requests + requests_to_origin: false, // Count all requests (not just origin hits) + }, + }, + enabled: true, +} +``` + +## Managed Ruleset Deployment + +```typescript +{ + action: 'execute', + action_parameters: { + id: 'efb7b8c949ac4650a09736fc376e9aee', // Cloudflare Managed + overrides: { + // Override specific rules + rules: [ + { id: '5de7edfa648c4d6891dc3e7f84534ffa', action: 'log', enabled: true }, + ], + // Override categories: 'wordpress', 'sqli', 'xss', 'rce', etc. + categories: [ + { category: 'wordpress', enabled: false }, + { category: 'sqli', action: 'log' }, + ], + }, + }, + expression: 'true', + enabled: true, +} +``` + +## Skip Rules + +Skip rules bypass subsequent rule evaluation. Two skip types: + +**Skip current ruleset**: Skip remaining rules in current phase only +```typescript +{ + action: 'skip', + action_parameters: { + ruleset: 'current', // Skip rest of current ruleset + }, + expression: 'http.request.uri.path ends_with ".jpg" or http.request.uri.path ends_with ".css"', + enabled: true, +} +``` + +**Skip entire phases**: Skip one or more phases completely +```typescript +{ + action: 'skip', + action_parameters: { + phases: ['http_request_firewall_managed', 'http_ratelimit'], // Skip multiple phases + }, + expression: 'ip.src in {192.0.2.0/24 203.0.113.0/24}', + enabled: true, +} +``` + +**Note**: Skip rules in custom phase can skip managed/ratelimit phases, but not vice versa (execution order). \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..796a2910312e3f07475e7518edf47b8302fd2cfc --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/configuration.md @@ -0,0 +1,203 @@ +# Configuration + +## Prerequisites + +**API Token**: Create at https://dash.cloudflare.com/profile/api-tokens +- Permission: `Zone.WAF Edit` or `Zone.Firewall Services Edit` +- Zone Resources: Include specific zones or all zones + +**Zone ID**: Found in dashboard > Overview > API section (right sidebar) + +```bash +# Set environment variables +export CF_API_TOKEN="your_api_token_here" +export ZONE_ID="your_zone_id_here" +``` + +## TypeScript SDK Usage + +```bash +npm install cloudflare +``` + +```typescript +import Cloudflare from 'cloudflare'; + +const client = new Cloudflare({ apiToken: process.env.CF_API_TOKEN }); + +// Custom rules +await client.rulesets.create({ + zone_id: process.env.ZONE_ID, + kind: 'zone', + phase: 'http_request_firewall_custom', + name: 'Custom WAF', + rules: [ + { action: 'block', expression: 'cf.waf.score gt 50', enabled: true }, + { action: 'challenge', expression: 'http.request.uri.path eq "/admin"', enabled: true }, + ], +}); + +// Managed ruleset +await client.rulesets.create({ + zone_id: process.env.ZONE_ID, + phase: 'http_request_firewall_managed', + rules: [{ + action: 'execute', + action_parameters: { id: 'efb7b8c949ac4650a09736fc376e9aee' }, + expression: 'true', + }], +}); + +// Rate limiting +await client.rulesets.create({ + zone_id: process.env.ZONE_ID, + phase: 'http_ratelimit', + rules: [{ + action: 'block', + expression: 'http.request.uri.path starts_with "/api"', + action_parameters: { + ratelimit: { + characteristics: ['cf.colo.id', 'ip.src'], + period: 60, + requests_per_period: 100, + mitigation_timeout: 600, + }, + }, + }], +}); +``` + +## Terraform Configuration + +```hcl +provider "cloudflare" { + api_token = var.cloudflare_api_token +} + +resource "cloudflare_ruleset" "waf_custom" { + zone_id = var.zone_id + kind = "zone" + phase = "http_request_firewall_custom" + + rules { + action = "block" + expression = "cf.waf.score gt 50" + } +} +``` + +**Managed Ruleset & Rate Limiting**: +```hcl +resource "cloudflare_ruleset" "waf_managed" { + zone_id = var.zone_id + name = "Managed Ruleset" + kind = "zone" + phase = "http_request_firewall_managed" + + rules { + action = "execute" + action_parameters { + id = "efb7b8c949ac4650a09736fc376e9aee" + overrides { + rules { + id = "5de7edfa648c4d6891dc3e7f84534ffa" + action = "log" + } + } + } + expression = "true" + } +} + +resource "cloudflare_ruleset" "rate_limiting" { + zone_id = var.zone_id + phase = "http_ratelimit" + + rules { + action = "block" + expression = "http.request.uri.path starts_with \"/api\"" + ratelimit { + characteristics = ["cf.colo.id", "ip.src"] + period = 60 + requests_per_period = 100 + mitigation_timeout = 600 + } + } +} +``` + +## Pulumi Configuration + +```typescript +import * as cloudflare from '@pulumi/cloudflare'; + +const zoneId = 'zone_id'; + +// Custom rules +const wafCustom = new cloudflare.Ruleset('waf-custom', { + zoneId, + phase: 'http_request_firewall_custom', + rules: [ + { action: 'block', expression: 'cf.waf.score gt 50', enabled: true }, + { action: 'challenge', expression: 'http.request.uri.path eq "/admin"', enabled: true }, + ], +}); + +// Managed ruleset +const wafManaged = new cloudflare.Ruleset('waf-managed', { + zoneId, + phase: 'http_request_firewall_managed', + rules: [{ + action: 'execute', + actionParameters: { id: 'efb7b8c949ac4650a09736fc376e9aee' }, + expression: 'true', + }], +}); + +// Rate limiting +const rateLimiting = new cloudflare.Ruleset('rate-limiting', { + zoneId, + phase: 'http_ratelimit', + rules: [{ + action: 'block', + expression: 'http.request.uri.path starts_with "/api"', + ratelimit: { + characteristics: ['cf.colo.id', 'ip.src'], + period: 60, + requestsPerPeriod: 100, + mitigationTimeout: 600, + }, + }], +}); +``` + +## Dashboard Configuration + +1. Navigate to: **Security** > **WAF** +2. Select tab: + - **Managed rules** - Deploy/configure managed rulesets + - **Custom rules** - Create custom rules + - **Rate limiting rules** - Configure rate limits +3. Click **Deploy** or **Create rule** + +**Testing**: Use Security Events to test expressions before deploying. + +## Wrangler Integration + +WAF configuration is zone-level (not Worker-specific). Configuration methods: +- Dashboard UI +- Cloudflare API via SDK +- Terraform/Pulumi (IaC) + +**Workers benefit from WAF automatically** - no Worker code changes needed. + +**Example: Query WAF API from Worker**: +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + return fetch(`https://api.cloudflare.com/client/v4/zones/${env.ZONE_ID}/rulesets`, { + headers: { 'Authorization': `Bearer ${env.CF_API_TOKEN}` }, + }); + }, +}; +``` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..44f33d8f2718220c76af60e97746b8aa03d91133 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/gotchas.md @@ -0,0 +1,204 @@ +# Gotchas & Troubleshooting + +## Execution Order + +**Problem:** Rules execute in unexpected order +**Cause:** Misunderstanding phase execution +**Solution:** + +Phases execute sequentially (can't be changed): +1. `http_request_firewall_custom` - Custom rules +2. `http_request_firewall_managed` - Managed rulesets +3. `http_ratelimit` - Rate limiting + +Within phase: top-to-bottom, first match wins (unless `skip`) + +```typescript +// WRONG: Can't mix phase-specific actions +await client.rulesets.create({ + phase: 'http_request_firewall_custom', + rules: [ + { action: 'block', expression: 'cf.waf.score gt 50' }, + { action: 'execute', action_parameters: { id: 'managed_id' } }, // WRONG + ], +}); + +// CORRECT: Separate rulesets per phase +await client.rulesets.create({ phase: 'http_request_firewall_custom', rules: [...] }); +await client.rulesets.create({ phase: 'http_request_firewall_managed', rules: [...] }); +``` + +## Expression Errors + +**Problem:** Syntax errors prevent deployment +**Cause:** Invalid field/operator/syntax +**Solution:** + +```typescript +// Common mistakes +'http.request.path' → 'http.request.uri.path' // Correct field +'ip.geoip.country eq US' → 'ip.geoip.country eq "US"' // Quote strings +'http.user_agent eq "Mozilla"' → 'lower(http.user_agent) contains "mozilla"' // Case sensitivity +'matches ".*[.jpg"' → 'matches ".*\\.jpg$"' // Valid regex +``` + +Test expressions in Security Events before deploying. + +## Skip Rule Pitfalls + +**Problem:** Skip rules don't work as expected +**Cause:** Misunderstanding skip scope +**Solution:** + +Skip types: +- `ruleset: 'current'` - Skip remaining rules in current ruleset only +- `phases: ['phase_name']` - Skip entire phases + +```typescript +// WRONG: Trying to skip managed rules from custom phase +// In http_request_firewall_custom: +{ + action: 'skip', + action_parameters: { ruleset: 'current' }, + expression: 'ip.src in {192.0.2.0/24}', +} +// This only skips remaining custom rules, not managed rules + +// CORRECT: Skip specific phases +{ + action: 'skip', + action_parameters: { + phases: ['http_request_firewall_managed', 'http_ratelimit'], + }, + expression: 'ip.src in {192.0.2.0/24}', +} +``` + +## Update Replaces All Rules + +**Problem:** Updating ruleset deletes other rules +**Cause:** `update()` replaces entire rule list +**Solution:** + +```typescript +// WRONG: This deletes all existing rules! +await client.rulesets.update({ + zone_id: 'zone_id', + ruleset_id: 'ruleset_id', + rules: [{ action: 'block', expression: 'cf.waf.score gt 50' }], +}); + +// CORRECT: Get existing rules first +const ruleset = await client.rulesets.get({ zone_id: 'zone_id', ruleset_id: 'ruleset_id' }); +await client.rulesets.update({ + zone_id: 'zone_id', + ruleset_id: 'ruleset_id', + rules: [...ruleset.rules, { action: 'block', expression: 'cf.waf.score gt 50' }], +}); +``` + +## Override Conflicts + +**Problem:** Managed ruleset overrides don't apply +**Cause:** Rule ID doesn't exist or category name incorrect +**Solution:** + +```typescript +// List managed ruleset rules to find IDs +const ruleset = await client.rulesets.get({ + zone_id: 'zone_id', + ruleset_id: 'efb7b8c949ac4650a09736fc376e9aee', +}); +console.log(ruleset.rules.map(r => ({ id: r.id, description: r.description }))); + +// Use correct IDs in overrides +{ action: 'execute', action_parameters: { id: 'efb7b8c949ac4650a09736fc376e9aee', + overrides: { rules: [{ id: '5de7edfa648c4d6891dc3e7f84534ffa', action: 'log' }] } } } +``` + +## False Positives + +**Problem:** Legitimate traffic blocked +**Cause:** Aggressive rules/thresholds +**Solution:** + +1. Start with log mode: `overrides: { action: 'log' }` +2. Review Security Events to identify false positives +3. Override specific rules: `overrides: { rules: [{ id: 'rule_id', action: 'log' }] }` + +## Rate Limiting NAT Issues + +**Problem:** Users behind NAT hit rate limits too quickly +**Cause:** Multiple users sharing single IP +**Solution:** + +Add more characteristics: User-Agent, session cookie, or authorization header +```typescript +{ + action: 'block', + expression: 'http.request.uri.path starts_with "/api"', + action_parameters: { + ratelimit: { + characteristics: ['cf.colo.id', 'ip.src', 'http.request.cookies["session"][0]'], + period: 60, + requests_per_period: 100, + }, + }, +} +``` + +## Performance Issues + +**Problem:** Increased latency +**Cause:** Complex expressions, excessive rules +**Solution:** + +1. Skip static assets early: `action: 'skip'` for `\\.(jpg|css|js)$` +2. Path-based deployment: Only run managed on `/api` or `/admin` +3. Disable unused categories: `{ category: 'wordpress', enabled: false }` +4. Prefer string operators over regex: `starts_with` vs `matches` + +## Limits & Quotas + +| Resource | Free | Pro | Business | Enterprise | +|----------|------|-----|----------|------------| +| Custom rules | 5 | 20 | 100 | 1000 | +| Rate limiting rules | 1 | 10 | 25 | 100 | +| Rule expression length | 4096 chars | 4096 chars | 4096 chars | 4096 chars | +| Rules per ruleset | 75 | 75 | 400 | 1000 | +| Managed rulesets | Yes | Yes | Yes | Yes | +| Rate limit characteristics | 2 | 3 | 5 | 5 | + +**Important Notes:** +- Rules execute in order; first match wins (except skip rules) +- Expression evaluation stops at first `false` in AND chains +- `matches` regex operator is slower than string operators +- Rate limit counting happens before mitigation + +## API Errors + +**Problem:** API calls fail with cryptic errors +**Cause:** Invalid parameters or permissions +**Solution:** + +```typescript +// Error: "Invalid phase" → Use exact phase name +phase: 'http_request_firewall_custom' + +// Error: "Ruleset already exists" → Use update() or list first +const rulesets = await client.rulesets.list({ zone_id, phase: 'http_request_firewall_custom' }); +if (rulesets.result.length > 0) { + await client.rulesets.update({ zone_id, ruleset_id: rulesets.result[0].id, rules: [...] }); +} + +// Error: "Action not supported" → Check phase/action compatibility +// 'execute' only in http_request_firewall_managed +// Rate limit config only in http_ratelimit phase + +// Error: "Expression parse error" → Common fixes: +'ip.geoip.country eq "US"' // Quote strings +'cf.waf.score gt 40' // Use 'gt' not '>' +'http.request.uri.path' // Not 'http.request.path' +``` + +**Tip**: Test expressions in dashboard Security Events before deploying. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..30829a588857f6616ea47761e08803cfc86915b8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/waf/patterns.md @@ -0,0 +1,197 @@ +# Common Patterns + +## Deploy Managed Rulesets + +```typescript +// Deploy Cloudflare Managed Ruleset (default) +await client.rulesets.create({ + zone_id: 'zone_id', + kind: 'zone', + phase: 'http_request_firewall_managed', + name: 'Cloudflare Managed Ruleset', + rules: [{ + action: 'execute', + action_parameters: { + id: 'efb7b8c949ac4650a09736fc376e9aee', // Cloudflare Managed + // Or: '4814384a9e5d4991b9815dcfc25d2f1f' for OWASP CRS + // Or: 'c2e184081120413c86c3ab7e14069605' for Exposed Credentials + }, + expression: 'true', // All requests + // Or: 'http.request.uri.path starts_with "/api"' for specific paths + enabled: true, + }], +}); +``` + +## Override Managed Ruleset + +```typescript +await client.rulesets.create({ + zone_id: 'zone_id', + phase: 'http_request_firewall_managed', + rules: [{ + action: 'execute', + action_parameters: { + id: 'efb7b8c949ac4650a09736fc376e9aee', + overrides: { + // Override specific rules + rules: [ + { id: '5de7edfa648c4d6891dc3e7f84534ffa', action: 'log' }, + { id: '75a0060762034b9dad4e883afc121b4c', enabled: false }, + ], + // Override categories: wordpress, sqli, xss, rce, etc. + categories: [ + { category: 'wordpress', enabled: false }, + { category: 'sqli', action: 'log' }, + ], + }, + }, + expression: 'true', + }], +}); +``` + +## Custom Rules + +```typescript +await client.rulesets.create({ + zone_id: 'zone_id', + kind: 'zone', + phase: 'http_request_firewall_custom', + name: 'Custom WAF Rules', + rules: [ + // Attack score-based + { action: 'block', expression: 'cf.waf.score gt 50', enabled: true }, + { action: 'challenge', expression: 'cf.waf.score gt 20', enabled: true }, + + // Specific attack types + { action: 'block', expression: 'cf.waf.score.sqli gt 30 or cf.waf.score.xss gt 30', enabled: true }, + + // Geographic blocking + { action: 'block', expression: 'ip.geoip.country in {"CN" "RU"}', enabled: true }, + ], +}); +``` + +## Rate Limiting + +```typescript +await client.rulesets.create({ + zone_id: 'zone_id', + kind: 'zone', + phase: 'http_ratelimit', + name: 'Rate Limits', + rules: [ + // Per-IP global limit + { + action: 'block', + expression: 'true', + action_parameters: { + ratelimit: { + characteristics: ['cf.colo.id', 'ip.src'], + period: 60, + requests_per_period: 100, + mitigation_timeout: 600, + }, + }, + }, + + // Login endpoint (stricter) + { + action: 'block', + expression: 'http.request.uri.path eq "/api/login"', + action_parameters: { + ratelimit: { + characteristics: ['ip.src'], + period: 60, + requests_per_period: 5, + mitigation_timeout: 600, + }, + }, + }, + + // API writes only (using counting_expression) + { + action: 'block', + expression: 'http.request.uri.path starts_with "/api"', + action_parameters: { + ratelimit: { + characteristics: ['cf.colo.id', 'ip.src'], + period: 60, + requests_per_period: 50, + counting_expression: 'http.request.method ne "GET"', + }, + }, + }, + ], +}); +``` + +## Skip Rules + +```typescript +await client.rulesets.create({ + zone_id: 'zone_id', + kind: 'zone', + phase: 'http_request_firewall_custom', + name: 'Skip Rules', + rules: [ + // Skip static assets (current ruleset only) + { + action: 'skip', + action_parameters: { ruleset: 'current' }, + expression: 'http.request.uri.path matches "\\.(jpg|css|js|woff2?)$"', + }, + + // Skip all WAF phases for trusted IPs + { + action: 'skip', + action_parameters: { + phases: ['http_request_firewall_managed', 'http_ratelimit'], + }, + expression: 'ip.src in {192.0.2.0/24}', + }, + ], +}); +``` + +## Complete Setup Example + +Combine all three phases for comprehensive protection: + +```typescript +const client = new Cloudflare({ apiToken: process.env.CF_API_TOKEN }); +const zoneId = process.env.ZONE_ID; + +// 1. Custom rules (execute first) +await client.rulesets.create({ + zone_id: zoneId, + phase: 'http_request_firewall_custom', + rules: [ + { action: 'skip', action_parameters: { phases: ['http_request_firewall_managed', 'http_ratelimit'] }, expression: 'ip.src in {192.0.2.0/24}' }, + { action: 'block', expression: 'cf.waf.score gt 50' }, + { action: 'managed_challenge', expression: 'cf.waf.score gt 20' }, + ], +}); + +// 2. Managed ruleset (execute second) +await client.rulesets.create({ + zone_id: zoneId, + phase: 'http_request_firewall_managed', + rules: [{ + action: 'execute', + action_parameters: { id: 'efb7b8c949ac4650a09736fc376e9aee', overrides: { categories: [{ category: 'wordpress', enabled: false }] } }, + expression: 'true', + }], +}); + +// 3. Rate limiting (execute third) +await client.rulesets.create({ + zone_id: zoneId, + phase: 'http_ratelimit', + rules: [ + { action: 'block', expression: 'true', action_parameters: { ratelimit: { characteristics: ['cf.colo.id', 'ip.src'], period: 60, requests_per_period: 100, mitigation_timeout: 600 } } }, + { action: 'block', expression: 'http.request.uri.path eq "/api/login"', action_parameters: { ratelimit: { characteristics: ['ip.src'], period: 60, requests_per_period: 5, mitigation_timeout: 600 } } }, + ], +}); +``` \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fcc19385986c0736385be8863fabca2b3fa29f44 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/README.md @@ -0,0 +1,140 @@ +# Cloudflare Web Analytics + +Privacy-first web analytics providing Core Web Vitals, traffic metrics, and user insights without compromising visitor privacy. + +## Overview + +Cloudflare Web Analytics provides: +- **Core Web Vitals** - LCP, FID, CLS, INP, TTFB monitoring +- **Page views & visits** - Traffic patterns without cookies +- **Referrers & paths** - Traffic sources and popular pages +- **Device & browser data** - User agent breakdown +- **Geographic data** - Country-level visitor distribution +- **Privacy-first** - No cookies, fingerprinting, or PII collection +- **Free** - No cost, unlimited pageviews + +**Important:** Web Analytics is **dashboard-only**. No API exists for programmatic data access. + +## Quick Start Decision Tree + +``` +Is your site proxied through Cloudflare? +├─ YES → Use automatic injection (configuration.md) +│ ├─ Enable auto-injection in dashboard +│ └─ No code changes needed (unless Cache-Control: no-transform) +│ +└─ NO → Use manual beacon integration (integration.md) + ├─ Add JS snippet to HTML + ├─ Use spa: true for React/Vue/Next.js + └─ Configure CSP if needed +``` + +## Reading Order + +1. **[configuration.md](configuration.md)** - Setup for proxied vs non-proxied sites +2. **[integration.md](integration.md)** - Framework-specific beacon integration (React, Next.js, Vue, Nuxt, etc.) +3. **[patterns.md](patterns.md)** - Common use cases (performance monitoring, GDPR consent, multi-site tracking) +4. **[gotchas.md](gotchas.md)** - Troubleshooting (SPA tracking, CSP issues, hash routing limitations) + +## When to Use Each File + +- **Setting up for first time?** → Start with configuration.md +- **Using React/Next.js/Vue/Nuxt?** → Go to integration.md for framework code +- **Need GDPR consent loading?** → See patterns.md +- **Beacon not loading or no data?** → Check gotchas.md +- **SPA not tracking navigation?** → See integration.md for `spa: true` config + +## Key Concepts + +### Proxied vs Non-Proxied Sites + +| Type | Description | Beacon Injection | Limit | +|------|-------------|------------------|-------| +| **Proxied** | DNS through Cloudflare (orange cloud) | Automatic or manual | Unlimited | +| **Non-proxied** | External hosting, manual beacon | Manual only | 10 sites max | + +### SPA Mode + +**Critical for modern frameworks:** +```json +{"token": "YOUR_TOKEN", "spa": true} +``` + +Without `spa: true`, client-side navigation (React Router, Vue Router, Next.js routing) will NOT be tracked. Only initial page loads will register. + +### CSP Requirements + +If using Content Security Policy, allow both domains: +``` +script-src https://static.cloudflareinsights.com https://cloudflareinsights.com; +``` + +## Features + +### Core Web Vitals Debugging +- **LCP (Largest Contentful Paint)** - Identifies slow-loading hero images/elements +- **FID (First Input Delay)** - Interaction responsiveness (legacy metric) +- **INP (Interaction to Next Paint)** - Modern interaction responsiveness metric +- **CLS (Cumulative Layout Shift)** - Visual stability issues +- **TTFB (Time to First Byte)** - Server response performance + +Dashboard shows top 5 problematic elements with CSS selectors for debugging. + +### Traffic Filters +- **Bot filtering** - Exclude automated traffic from metrics +- **Date ranges** - Custom time period analysis +- **Geographic** - Country-level filtering +- **Device type** - Desktop, mobile, tablet breakdown +- **Browser/OS** - User agent filtering + +### Rules (Advanced - Plan-dependent) + +Create custom tracking rules for advanced configurations: + +**Sample Rate Rules:** +- Reduce data collection percentage for high-traffic sites +- Example: Track only 50% of visitors to reduce volume + +**Path-Based Rules:** +- Different behavior per route +- Example: Exclude `/admin/*` or `/internal/*` from tracking + +**Host-Based Rules:** +- Multi-domain configurations +- Example: Separate tracking for staging vs production subdomains + +**Availability:** Rules feature depends on your Cloudflare plan. Check dashboard under Web Analytics → Rules to see if available. Free plans may have limited or no access. + +## Plan Limits + +| Feature | Free | Notes | +|---------|------|-------| +| Proxied sites | Unlimited | DNS through Cloudflare | +| Non-proxied sites | 10 | External hosting | +| Pageviews | Unlimited | No volume limits | +| Data retention | 6 months | Rolling window | +| Rules | Plan-dependent | Check dashboard | + +## Privacy & Compliance + +- **No cookies** - Zero client-side storage +- **No fingerprinting** - No tracking across sites +- **No PII** - IP addresses not stored +- **GDPR-friendly** - Minimal data collection +- **CCPA-compliant** - No personal data sale + +**EU opt-out:** Dashboard option to exclude EU visitor data entirely. + +## Limitations + +- **Dashboard-only** - No API for programmatic access +- **No real-time** - 5-10 minute data delay +- **No custom events** - Automatic pageview/navigation tracking only +- **History API only** - Hash-based routing (`#/path`) not supported +- **No session replay** - Metrics only, no user recordings +- **No form tracking** - Page navigation tracking only + +## See Also + +- [Cloudflare Web Analytics Docs](https://developers.cloudflare.com/analytics/web-analytics/) +- [Core Web Vitals Guide](https://web.dev/vitals/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..c324267979b121055447d539f784ff0645367c4a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/configuration.md @@ -0,0 +1,76 @@ +# Configuration + +## Setup Methods + +### Proxied Sites (Automatic) + +Dashboard → Web Analytics → Add site → Select hostname → Done + +| Injection Option | Description | +|------------------|-------------| +| Enable | Auto-inject for all visitors (default) | +| Enable, excluding EU | No injection for EU (GDPR) | +| Enable with manual snippet | You add beacon manually | +| Disable | Pause tracking | + +**Fails if response has:** `Cache-Control: public, no-transform` + +**CSP required:** +``` +script-src https://static.cloudflareinsights.com https://cloudflareinsights.com; +``` + +### Non-Proxied Sites (Manual) + +Dashboard → Web Analytics → Add site → Enter hostname → Copy snippet + +```html + +``` + +**Limits:** 10 non-proxied sites per account + +## SPA Mode + +**Enable `spa: true` for:** React Router, Next.js, Vue Router, Nuxt, SvelteKit, Angular + +**Keep `spa: false` for:** Traditional multi-page apps, static sites, WordPress + +**Hash routing (`#/path`) NOT supported** - use History API routing. + +## Token Management + +- Found in: Dashboard → Web Analytics → Manage site +- **Not secrets** - domain-locked, safe to expose in HTML +- Each site gets unique token + +## Environment Config + +```typescript +// Only load in production +if (process.env.NODE_ENV === 'production') { + // Load beacon +} +``` + +Or use environment-specific tokens via env vars. + +## Verify Installation + +1. DevTools Network → filter `cloudflareinsights` → see `beacon.min.js` + data request +2. No CSP/CORS errors in console +3. Dashboard shows pageviews after 5-10 min delay + +## Rules (Plan-dependent) + +Configure in dashboard for: +- **Sample rate** - reduce collection % for high-traffic +- **Path-based** - different behavior per route +- **Host-based** - separate tracking per domain + +## Data Retention + +- 6 months rolling window +- 1-hour bucket granularity +- No raw export, dashboard only diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..9b1587124c944f7dc0fdeb567d55c693015e30bb --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/web-analytics/gotchas.md @@ -0,0 +1,82 @@ +# Web Analytics Gotchas + +## Critical Issues + +### SPA Navigation Not Tracked + +**Symptom:** Only initial pageload counted +**Fix:** Add `spa: true`: +```html + +``` + +### CSP Blocking Beacon + +**Symptom:** Console error "Refused to load script" +**Fix:** Allow both domains: +``` +script-src 'self' https://static.cloudflareinsights.com https://cloudflareinsights.com; +``` + +### Hash-Based Routing Unsupported + +**Symptom:** `#/path` URLs not tracked +**Fix:** Migrate to History API (`BrowserRouter`, not `HashRouter`). No workaround for hash routing. + +### No Data Appearing + +**Causes & Fixes:** +1. **Delay** - Wait 5-15 minutes +2. **Wrong token** - Verify matches dashboard exactly +3. **Script blocked** - Check DevTools Network tab for beacon.min.js +4. **Domain mismatch** - Dashboard site must match actual URL + +### Auto-Injection Fails + +**Cause:** `Cache-Control: no-transform` header +**Fix:** Remove `no-transform` or install beacon manually + +### Duplicate Pageviews + +**Cause:** Multiple beacon scripts +**Fix:** Keep only one beacon per page + +## Configuration Issues + +| Issue | Fix | +|-------|-----| +| 10-site limit reached | Delete old sites or proxy through CF (unlimited) | +| Token not recognized | Use exact alphanumeric token from dashboard | + +## Framework-Specific + +### Next.js Hydration Warning + +```tsx + +``` + +Place before closing `` tag. + +## Framework Examples + +| Framework | Location | Notes | +|-----------|----------|-------| +| React/Vite | `public/index.html` | Add `spa: true` | +| Next.js App Router | `app/layout.tsx` | Use ` +``` + +Without `spa: true`: only initial pageload tracked. + +## Staging/Production Separation + +```typescript +// Use env-specific tokens +const token = process.env.NEXT_PUBLIC_CF_ANALYTICS_TOKEN; +// .env.production: production token +// .env.staging: staging token (or empty to disable) +``` + +## Bot Filtering + +Dashboard → Filters → "Exclude Bot Traffic" + +Filters: Search crawlers, monitoring services, known bots. +Not filtered: Headless browsers (Playwright/Puppeteer). + +## Ad-Blocker Impact + +~25-40% of users may block `cloudflareinsights.com`. No official workaround. +Dashboard shows minimum baseline; use server logs for complete picture. + +## Limitations + +- No UTM parameter tracking +- No webhooks/alerts/API +- No custom beacon domains +- Max 10 non-proxied sites diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/README.md new file mode 100644 index 0000000000000000000000000000000000000000..34069946c91a66b296fab1941b10abb230d41172 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/README.md @@ -0,0 +1,197 @@ +# Cloudflare Workers AI + +Expert guidance for Cloudflare Workers AI - serverless GPU-powered AI inference at the edge. + +## Overview + +Workers AI provides: +- 50+ pre-trained models (LLMs, embeddings, image generation, speech-to-text, translation) +- Native Workers binding (no external API calls) +- Pay-per-use pricing (neurons consumed per inference) +- OpenAI-compatible REST API +- Streaming support for text generation +- Function calling with compatible models + +**Architecture**: Inference runs on Cloudflare's GPU network. Models load on first request (cold start 1-3s), subsequent requests are faster. + +## Quick Start + +```typescript +interface Env { + AI: Ai; +} + +export default { + async fetch(request: Request, env: Env) { + const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [{ role: 'user', content: 'What is Cloudflare?' }] + }); + return Response.json(response); + } +}; +``` + +```bash +# Setup - add binding to wrangler.jsonc +wrangler dev --remote # Must use --remote for AI +wrangler deploy +``` + +## Model Selection Decision Tree + +### Text Generation (Chat/Completion) + +**Quality Priority**: +- **Best quality**: `@cf/meta/llama-3.1-70b-instruct` (expensive, ~2000 neurons) +- **Balanced**: `@cf/meta/llama-3.1-8b-instruct` (good quality, ~200 neurons) +- **Fastest/cheapest**: `@cf/mistral/mistral-7b-instruct-v0.1` (~50 neurons) + +**Function Calling**: +- Use `@cf/meta/llama-3.1-8b-instruct` or `@cf/meta/llama-3.1-70b-instruct` (native tool support) + +**Code Generation**: +- Use `@cf/deepseek-ai/deepseek-coder-6.7b-instruct` (specialized for code) + +### Embeddings (Semantic Search/RAG) + +**English text**: +- **Best**: `@cf/baai/bge-large-en-v1.5` (1024 dims, highest quality) +- **Balanced**: `@cf/baai/bge-base-en-v1.5` (768 dims, good quality) +- **Fast**: `@cf/baai/bge-small-en-v1.5` (384 dims, lower quality but fast) + +**Multilingual**: +- Use `@hf/sentence-transformers/paraphrase-multilingual-minilm-l12-v2` + +### Image Generation + +- **Stable Diffusion**: `@cf/stabilityai/stable-diffusion-xl-base-1.0` (~10,000 neurons) +- **Portraits**: `@cf/lykon/dreamshaper-8-lcm` (optimized for faces) + +### Other Tasks + +- **Speech-to-text**: `@cf/openai/whisper` +- **Translation**: `@cf/meta/m2m100-1.2b` (100 languages) +- **Image classification**: `@cf/microsoft/resnet-50` + +## SDK Approach Decision Tree + +### Native Binding (Recommended) + +**When**: Building Workers/Pages with TypeScript +**Why**: Zero external dependencies, best performance, native types + +```typescript +await env.AI.run(model, input); +``` + +### REST API + +**When**: External services, non-Workers environments, testing +**Why**: Standard HTTP, works anywhere + +```bash +curl https://api.cloudflare.com/client/v4/accounts//ai/run/@cf/meta/llama-3.1-8b-instruct \ + -H "Authorization: Bearer " \ + -d '{"messages":[{"role":"user","content":"Hello"}]}' +``` + +### Vercel AI SDK Integration + +**When**: Using Vercel AI SDK features (streaming UI, tool calling abstractions) +**Why**: Unified interface across providers + +```typescript +import { openai } from '@ai-sdk/openai'; + +const model = openai('model-name', { + baseURL: 'https://api.cloudflare.com/client/v4/accounts//ai/v1', + headers: { Authorization: 'Bearer ' } +}); +``` + +## RAG vs Direct Generation + +### Use RAG (Vectorize + Workers AI) When: +- Answering questions about specific documents/data +- Need factual accuracy from known corpus +- Context exceeds model's window (>4K tokens) +- Building knowledge base chat + +### Use Direct Generation When: +- Creative writing, brainstorming +- General knowledge questions +- Small context fits in prompt (<4K tokens) +- Cost optimization (RAG adds embedding + vector search costs) + +## Platform Limits + +| Limit | Free Tier | Paid Plans | +|-------|-----------|------------| +| Neurons/day | 10,000 | Pay per use | +| Rate limit | Varies by model | Higher (contact support) | +| Context window | Model dependent (2K-8K) | Same | +| Streaming | ✅ Supported | ✅ Supported | +| Function calling | ✅ Supported (select models) | ✅ Supported | + +**Pricing**: Free 10K neurons/day, then pay per neuron consumed (varies by model) + +## Common Tasks + +```typescript +// Streaming text generation +const stream = await env.AI.run(model, { messages, stream: true }); +for await (const chunk of stream) { + console.log(chunk.response); +} + +// Embeddings for RAG +const { data } = await env.AI.run('@cf/baai/bge-base-en-v1.5', { + text: ['Query text', 'Document 1', 'Document 2'] +}); + +// Function calling +const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [{ role: 'user', content: 'What is the weather?' }], + tools: [{ + type: 'function', + function: { name: 'getWeather', parameters: { ... } } + }] +}); +``` + +## Development Workflow + +```bash +# Always use --remote for AI (local doesn't have models) +wrangler dev --remote + +# Deploy to production +wrangler deploy + +# View model catalog +# https://developers.cloudflare.com/workers-ai/models/ +``` + +## Reading Order + +**Start here**: Quick Start above → configuration.md (setup) + +**Common tasks**: +- First time setup: configuration.md → Add binding + deploy +- Choose model: Model Selection Decision Tree (above) → api.md +- Build RAG: patterns.md → Vectorize integration +- Optimize costs: Model Selection + gotchas.md (rate limits) +- Debugging: gotchas.md → Common errors + +## In This Reference + +- [configuration.md](./configuration.md) - wrangler.jsonc setup, TypeScript types, bindings, environment variables +- [api.md](./api.md) - env.AI.run(), streaming, function calling, REST API, response types +- [patterns.md](./patterns.md) - RAG with Vectorize, prompt engineering, batching, error handling, caching +- [gotchas.md](./gotchas.md) - Deprecated @cloudflare/ai package, rate limits, pricing, common errors + +## See Also + +- [vectorize](../vectorize/) - Vector database for RAG patterns +- [ai-gateway](../ai-gateway/) - Caching, rate limiting, analytics for AI requests +- [workers](../workers/) - Worker runtime and fetch handler patterns diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/api.md new file mode 100644 index 0000000000000000000000000000000000000000..e65f97aefbdea5f2d21ec3934783bc6d9c96392e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/api.md @@ -0,0 +1,112 @@ +# Workers AI API Reference + +## Core Method + +```typescript +const response = await env.AI.run(model, input); +``` + +## Text Generation + +```typescript +const result = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [ + { role: 'system', content: 'You are helpful' }, + { role: 'user', content: 'Hello' } + ], + temperature: 0.7, // 0-1 + max_tokens: 100 +}); +console.log(result.response); +``` + +**Streaming:** +```typescript +const stream = await env.AI.run(model, { messages, stream: true }); +return new Response(stream, { headers: { 'Content-Type': 'text/event-stream' } }); +``` + +## Embeddings + +```typescript +const result = await env.AI.run('@cf/baai/bge-base-en-v1.5', { + text: ['Query', 'Doc 1', 'Doc 2'] // Batch for efficiency +}); +const [queryEmbed, doc1Embed, doc2Embed] = result.data; // 768-dim vectors +``` + +## Function Calling + +```typescript +const tools = [{ + type: 'function', + function: { + name: 'getWeather', + description: 'Get weather for location', + parameters: { + type: 'object', + properties: { location: { type: 'string' } }, + required: ['location'] + } + } +}]; + +const response = await env.AI.run(model, { messages, tools }); +if (response.tool_calls) { + const args = JSON.parse(response.tool_calls[0].function.arguments); + // Execute function, send result back +} +``` + +## Image Generation + +```typescript +const image = await env.AI.run('@cf/stabilityai/stable-diffusion-xl-base-1.0', { + prompt: 'Mountain sunset', + num_steps: 20, // 1-20 + guidance: 7.5 // 1-20 +}); +return new Response(image, { headers: { 'Content-Type': 'image/png' } }); +``` + +## Speech Recognition + +```typescript +const audioArray = Array.from(new Uint8Array(await request.arrayBuffer())); +const result = await env.AI.run('@cf/openai/whisper', { audio: audioArray }); +console.log(result.text); +``` + +## Translation + +```typescript +const result = await env.AI.run('@cf/meta/m2m100-1.2b', { + text: 'Hello', + source_lang: 'en', + target_lang: 'es' +}); +console.log(result.translated_text); +``` + +## REST API + +```bash +curl https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/@cf/meta/llama-3.1-8b-instruct \ + -H "Authorization: Bearer $TOKEN" \ + -d '{"messages":[{"role":"user","content":"Hello"}]}' +``` + +## Error Codes + +| Code | Meaning | Fix | +|------|---------|-----| +| 7502 | Model not found | Check spelling | +| 7504 | Validation failed | Verify input schema | +| 7505 | Rate limited | Reduce rate or upgrade | +| 7506 | Context exceeded | Reduce input size | + +## Performance Tips + +1. **Batch embeddings** - single request for multiple texts +2. **Stream long responses** - reduce perceived latency +3. **Accept cold starts** - first request ~1-3s, subsequent ~100-500ms diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..f5563b3a5bc499439dbb74ae2564a4a799899ed7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/configuration.md @@ -0,0 +1,97 @@ +# Workers AI Configuration + +## wrangler.jsonc + +```jsonc +{ + "name": "my-ai-worker", + "main": "src/index.ts", + "compatibility_date": "2024-01-01", + "ai": { + "binding": "AI" + } +} +``` + +## TypeScript + +```bash +npm install --save-dev @cloudflare/workers-types +``` + +```typescript +interface Env { + AI: Ai; +} + +export default { + async fetch(request: Request, env: Env) { + const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [{ role: 'user', content: 'Hello' }] + }); + return Response.json(response); + } +}; +``` + +## Local Development + +```bash +wrangler dev --remote # Required for AI - no local inference +``` + +## REST API + +```typescript +const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/run/@cf/meta/llama-3.1-8b-instruct`, + { + method: 'POST', + headers: { 'Authorization': `Bearer ${API_TOKEN}` }, + body: JSON.stringify({ messages: [{ role: 'user', content: 'Hello' }] }) + } +); +``` + +Create API token at: dash.cloudflare.com/profile/api-tokens (Workers AI - Read permission) + +## SDK Compatibility + +**OpenAI SDK:** +```typescript +import OpenAI from 'openai'; +const client = new OpenAI({ + apiKey: env.CLOUDFLARE_API_TOKEN, + baseURL: `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/ai/v1` +}); +``` + +## Multi-Model Setup + +```typescript +const MODELS = { + chat: '@cf/meta/llama-3.1-8b-instruct', + embed: '@cf/baai/bge-base-en-v1.5', + image: '@cf/stabilityai/stable-diffusion-xl-base-1.0' +}; +``` + +## RAG Setup (with Vectorize) + +```jsonc +{ + "ai": { "binding": "AI" }, + "vectorize": { + "bindings": [{ "binding": "VECTORIZE", "index_name": "embeddings-index" }] + } +} +``` + +## Troubleshooting + +| Error | Fix | +|-------|-----| +| `env.AI is undefined` | Check `ai` binding in wrangler.jsonc | +| Local AI doesn't work | Use `wrangler dev --remote` | +| Type 'Ai' not found | Install `@cloudflare/workers-types` | +| @cloudflare/ai package error | Don't install - use native binding | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..c69255f54bac0e95b64710327289c2cb77d29f85 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/gotchas.md @@ -0,0 +1,114 @@ +# Workers AI Gotchas + +## Critical: @cloudflare/ai is DEPRECATED + +```typescript +// ❌ WRONG - Don't install @cloudflare/ai +import Ai from '@cloudflare/ai'; + +// ✅ CORRECT - Use native binding +export default { + async fetch(request: Request, env: Env) { + await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { messages: [...] }); + } +} +``` + +## Development + +### "AI inference doesn't work locally" +```bash +# ❌ Local AI doesn't work +wrangler dev +# ✅ Use remote +wrangler dev --remote +``` + +### "env.AI is undefined" +Add binding to wrangler.jsonc: +```jsonc +{ "ai": { "binding": "AI" } } +``` + +## API Responses + +### Embedding response shape varies +```typescript +// @cf/baai/bge-base-en-v1.5 returns: { data: [[0.1, 0.2, ...]] } +const embedding = response.data[0]; // Get first element +``` + +### Stream returns ReadableStream +```typescript +const stream = await env.AI.run(model, { messages: [...], stream: true }); +for await (const chunk of stream) { console.log(chunk.response); } +``` + +## Rate Limits & Pricing + +| Model Type | Neurons/Request | +|------------|-----------------| +| Small text (7B) | ~50-200 | +| Large text (70B) | ~500-2000 | +| Embeddings | ~5-20 | +| Image gen | ~10,000+ | + +**Free tier**: 10,000 neurons/day + +```typescript +// ❌ EXPENSIVE - 70B model +await env.AI.run('@cf/meta/llama-3.1-70b-instruct', ...); +// ✅ CHEAPER - Use smallest that works +await env.AI.run('@cf/meta/llama-3.1-8b-instruct', ...); +``` + +## Model-Specific + +### Function calling +Only `@cf/meta/llama-3.1-*` and `mistral-7b-instruct-v0.2` support tools. + +### Empty response +Check context limits (2K-8K tokens). Validate input structure. + +### Inconsistent responses +Set `temperature: 0` for deterministic outputs. + +### Cold start latency +First request: 1-3s. Use AI Gateway caching for frequent prompts. + +## TypeScript + +```typescript +interface Env { + AI: Ai; // From @cloudflare/workers-types +} + +interface TextGenerationResponse { response: string; } +interface EmbeddingResponse { data: number[][]; shape: number[]; } +``` + +## Common Errors + +### 7502: Model not found +Check exact model name at developers.cloudflare.com/workers-ai/models/ + +### 7504: Input validation failed +```typescript +// Text gen requires messages array +await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [{ role: 'user', content: 'Hello' }] // ✅ +}); + +// Embeddings require text +await env.AI.run('@cf/baai/bge-base-en-v1.5', { text: 'Hello' }); // ✅ +``` + +## Vercel AI SDK Integration + +```typescript +import { openai } from '@ai-sdk/openai'; +const model = openai('gpt-3.5-turbo', { + baseURL: 'https://api.cloudflare.com/client/v4/accounts//ai/v1', + headers: { Authorization: 'Bearer ' } +}); +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..8295a5bfdd35424b36a405e145f60652ad24d587 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-ai/patterns.md @@ -0,0 +1,120 @@ +# Workers AI Patterns + +## RAG (Retrieval-Augmented Generation) + +```typescript +// 1. Embed query +const embedding = await env.AI.run('@cf/baai/bge-base-en-v1.5', { text: query }); + +// 2. Search vectors +const results = await env.VECTORIZE.query(embedding.data[0], { + topK: 5, returnMetadata: true +}); + +// 3. Build context +const context = results.matches.map(m => m.metadata?.text).join('\n\n'); + +// 4. Generate with context +const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [ + { role: 'system', content: `Answer based on:\n\n${context}` }, + { role: 'user', content: query } + ] +}); +``` + +## Streaming (SSE) + +```typescript +const stream = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages, stream: true +}); + +const { readable, writable } = new TransformStream(); +const writer = writable.getWriter(); + +(async () => { + for await (const chunk of stream) { + await writer.write(new TextEncoder().encode(`data: ${JSON.stringify(chunk)}\n\n`)); + } + await writer.write(new TextEncoder().encode('data: [DONE]\n\n')); + await writer.close(); +})(); + +return new Response(readable, { + headers: { 'Content-Type': 'text/event-stream' } +}); +``` + +## Error Handling & Retry + +```typescript +async function runWithRetry(env, model, input, maxRetries = 3) { + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + return await env.AI.run(model, input); + } catch (error) { + if (error.message?.includes('7505') && attempt < maxRetries - 1) { + await new Promise(r => setTimeout(r, Math.pow(2, attempt) * 1000)); + continue; + } + throw error; + } + } +} +``` + +## Model Fallback + +```typescript +try { + return await env.AI.run('@cf/meta/llama-3.1-70b-instruct', { messages }); +} catch { + return await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { messages }); +} +``` + +## Prompt Patterns + +```typescript +// System prompts +const PROMPTS = { + json: 'Respond with valid JSON only.', + concise: 'Keep responses brief.', + cot: 'Think step by step before answering.' +}; + +// Few-shot +messages: [ + { role: 'system', content: 'Extract as JSON' }, + { role: 'user', content: 'John bought 3 apples for $5' }, + { role: 'assistant', content: '{"name":"John","item":"apples","qty":3}' }, + { role: 'user', content: actualInput } +] +``` + +## Parallel Execution + +```typescript +const [sentiment, summary, embedding] = await Promise.all([ + env.AI.run('@cf/mistral/mistral-7b-instruct-v0.1', { messages: sentimentPrompt }), + env.AI.run('@cf/meta/llama-3.1-8b-instruct', { messages: summaryPrompt }), + env.AI.run('@cf/baai/bge-base-en-v1.5', { text }) +]); +``` + +## Cost Optimization + +| Task | Model | Neurons | +|------|-------|---------| +| Classify | `@cf/mistral/mistral-7b-instruct-v0.1` | ~50 | +| Chat | `@cf/meta/llama-3.1-8b-instruct` | ~200 | +| Complex | `@cf/meta/llama-3.1-70b-instruct` | ~2000 | +| Embed | `@cf/baai/bge-base-en-v1.5` | ~10 | + +```typescript +// Batch embeddings +const response = await env.AI.run('@cf/baai/bge-base-en-v1.5', { + text: textsArray // Process multiple at once +}); +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6dee4f974d634b36daa312c7d1e79ea483dd07ca --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/README.md @@ -0,0 +1,127 @@ +# Cloudflare Workers Playground Skill Reference + +## Overview + +Cloudflare Workers Playground is a browser-based sandbox for instantly experimenting with, testing, and deploying Cloudflare Workers without authentication or setup. This skill provides patterns, APIs, and best practices specifically for Workers Playground development. + +**URL:** [workers.cloudflare.com/playground](https://workers.cloudflare.com/playground) + +## ⚠️ Playground Constraints + +**Playground is NOT production-equivalent:** +- ✅ Real Workers runtime, instant testing, shareable URLs +- ❌ No TypeScript (JavaScript only) +- ❌ No bindings (KV, D1, R2, Durable Objects) +- ❌ No environment variables or secrets +- ❌ ES modules only (no Service Worker format) +- ⚠️ Safari broken (use Chrome/Firefox) + +**For production:** Use `wrangler` CLI. Playground is for rapid prototyping. + +## Quick Start + +Minimal Worker: + +```javascript +export default { + async fetch(request, env, ctx) { + return new Response('Hello World'); + } +}; +``` + +JSON API: + +```javascript +export default { + async fetch(request, env, ctx) { + const data = { message: 'Hello', timestamp: Date.now() }; + return Response.json(data); + } +}; +``` + +Proxy with modification: + +```javascript +export default { + async fetch(request, env, ctx) { + const response = await fetch('https://example.com'); + const modified = new Response(response.body, response); + modified.headers.set('X-Custom-Header', 'added-by-worker'); + return modified; + } +}; +``` + +Import from CDN: + +```javascript +import { Hono } from 'https://esm.sh/hono@3'; + +export default { + async fetch(request) { + const app = new Hono(); + app.get('/', (c) => c.text('Hello Hono!')); + return app.fetch(request); + } +}; +``` + +## Reading Order + +1. **[configuration.md](configuration.md)** - Start here: playground setup, constraints, deployment +2. **[api.md](api.md)** - Core APIs: Request, Response, ExecutionContext, fetch, Cache +3. **[patterns.md](patterns.md)** - Common use cases: routing, proxying, A/B testing, multi-module code +4. **[gotchas.md](gotchas.md)** - Troubleshooting: errors, browser issues, limits, best practices + +## In This Reference + +- **[configuration.md](configuration.md)** - Setup, deployment, configuration +- **[api.md](api.md)** - API endpoints, methods, interfaces +- **[patterns.md](patterns.md)** - Common patterns, use cases, examples +- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations + +## Key Features + +**No Setup Required:** +- Open URL and start coding +- No CLI, no account, no config files +- Code executes in real Cloudflare Workers runtime + +**Instant Preview:** +- Live preview pane with browser tab or HTTP tester +- Auto-reload on code changes +- DevTools integration (right-click → Inspect) + +**Share & Deploy:** +- Copy Link generates permanent shareable URL +- Deploy button publishes to production in ~30 seconds +- Get `*.workers.dev` subdomain immediately + +## Common Use Cases + +- **API development:** Test endpoints before wrangler setup +- **Learning Workers:** Experiment with APIs without local environment +- **Prototyping:** Quick POCs for edge logic +- **Sharing examples:** Generate shareable links for bug reports or demos +- **Framework testing:** Import from CDN (Hono, itty-router, etc.) + +## Limitations vs Production + +| Feature | Playground | Production (wrangler) | +|---------|------------|----------------------| +| Language | JavaScript only | JS + TypeScript | +| Bindings | None | KV, D1, R2, DO, AI, etc. | +| Environment vars | None | Full support | +| Module format | ES only | ES + Service Worker | +| CPU time | 10ms (Free plan) | 10ms Free / 50ms Paid | +| Custom domains | No | Yes | +| Analytics | No | Yes | + +## See Also + +- [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/) +- [Workers Examples](https://developers.cloudflare.com/workers/examples/) +- [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) +- [Workers API Reference](https://developers.cloudflare.com/workers/runtime-apis/) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/api.md new file mode 100644 index 0000000000000000000000000000000000000000..1382ab4b58e35842ecba1a1a66f0f9ce386b68f4 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/api.md @@ -0,0 +1,101 @@ +# Workers Playground API + +## Handler + +```javascript +export default { + async fetch(request, env, ctx) { + // request: Request, env: {} (empty in playground), ctx: ExecutionContext + return new Response('Hello'); + } +}; +``` + +## Request + +```javascript +const method = request.method; // "GET", "POST" +const url = new URL(request.url); // Parse URL +const headers = request.headers; // Headers object +const body = await request.json(); // Read body (consumes stream) +const clone = request.clone(); // Clone before reading body + +// Query params +url.searchParams.get('page'); // Single value +url.searchParams.getAll('tag'); // Array + +// Cloudflare metadata +request.cf.country; // "US" +request.cf.colo; // "SFO" +``` + +## Response + +```javascript +// Text +return new Response('Hello', { status: 200 }); + +// JSON +return Response.json({ data }, { status: 200, headers: {...} }); + +// Redirect +return Response.redirect('/new-path', 301); + +// Modify existing +const modified = new Response(response.body, response); +modified.headers.set('X-Custom', 'value'); +``` + +## ExecutionContext + +```javascript +// Background work (after response sent) +ctx.waitUntil(fetch('https://logs.example.com', { method: 'POST', body: '...' })); +return new Response('OK'); // Returns immediately +``` + +## Fetch + +```javascript +const response = await fetch('https://api.example.com'); +const data = await response.json(); + +// With options +await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: 'Alice' }) +}); +``` + +## Cache + +```javascript +const cache = caches.default; + +// Check cache +let response = await cache.match(request); +if (!response) { + response = await fetch(origin); + await cache.put(request, response.clone()); // Clone before put! +} +return response; +``` + +## Crypto + +```javascript +crypto.randomUUID(); // UUID v4 +crypto.getRandomValues(new Uint8Array(16)); + +// SHA-256 hash +const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data)); +``` + +## Limits (Playground = Free Plan) + +| Resource | Limit | +|----------|-------| +| CPU time | 10ms | +| Subrequests | 50 | +| Memory | 128 MB | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..7d747aceec7879b1a84ceaed858baa5756728a97 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/configuration.md @@ -0,0 +1,163 @@ +# Configuration + +## Getting Started + +Navigate to [workers.cloudflare.com/playground](https://workers.cloudflare.com/playground) + +- **No account required** for testing +- **No CLI or local setup** needed +- Code executes in real Cloudflare Workers runtime +- Share code via URL (never expires) + +## Playground Constraints + +⚠️ **Important Limitations** + +| Constraint | Playground | Production Workers | +|------------|------------|-------------------| +| **Module Format** | ES modules only | ES modules or Service Worker | +| **TypeScript** | Not supported (JS only) | Supported via build step | +| **Bindings** | Not available | KV, D1, R2, Durable Objects, etc. | +| **wrangler.toml** | Not used | Required for config | +| **Environment Variables** | Not available | Full support | +| **Secrets** | Not available | Full support | +| **Custom Domains** | Not available | Full support | + +**Playground is for rapid prototyping only.** For production apps, use `wrangler` CLI. + +## Code Editor + +### Syntax Requirements + +Must export default object with `fetch` handler: + +```javascript +export default { + async fetch(request, env, ctx) { + return new Response('Hello World'); + } +}; +``` + +**Key Points:** +- Must use ES modules (`export default`) +- `fetch` method receives `(request, env, ctx)` +- Must return `Response` object +- TypeScript not supported (use plain JavaScript) + +### Multi-Module Code + +Import from external URLs or inline modules: + +```javascript +// Import from CDN +import { Hono } from 'https://esm.sh/hono@3'; + +// Or paste library code and import relatively +// (See patterns.md for multi-module examples) + +export default { + async fetch(request) { + const app = new Hono(); + app.get('/', (c) => c.text('Hello')); + return app.fetch(request); + } +}; +``` + +## Preview Panel + +### Browser Tab + +Default interactive preview with address bar: +- Enter custom URL paths +- Automatic reload on code changes +- DevTools available (right-click → Inspect) + +### HTTP Test Panel + +Switch to **HTTP** tab for raw HTTP testing: +- Change HTTP method (GET, POST, PUT, DELETE, PATCH, etc.) +- Add/edit request headers +- Modify request body (JSON, form data, text) +- View response headers and body +- Test different content types + +Example HTTP test: +``` +Method: POST +URL: /api/users +Headers: + Content-Type: application/json + Authorization: Bearer token123 +Body: +{ + "name": "Alice", + "email": "alice@example.com" +} +``` + +## Sharing Code + +**Copy Link** button generates shareable URL: +- Code embedded in URL fragment +- Links never expire +- No account required +- Can be bookmarked for later + +Example: `https://workers.cloudflare.com/playground#abc123...` + +## Deploying from Playground + +Click **Deploy** button to move code to production: + +1. **Log in** to Cloudflare account (creates free account if needed) +2. **Review** Worker name and code +3. **Deploy** to global network (takes ~30 seconds) +4. **Get URL**: Deployed to `.workers.dev` subdomain +5. **Manage** from dashboard: add bindings, custom domains, analytics + +**After deploy:** +- Code runs on Cloudflare's global network (300+ cities) +- Can add KV, D1, R2, Durable Objects bindings +- Configure custom domains and routes +- View analytics and logs +- Set environment variables and secrets + +**Note:** Deployed Workers are production-ready but start on Free plan (100k requests/day). + +## Browser Compatibility + +| Browser | Status | Notes | +|---------|--------|-------| +| Chrome/Edge | ✅ Full support | Recommended | +| Firefox | ✅ Full support | Works well | +| Safari | ⚠️ Broken | Preview fails with "PreviewRequestFailed" | + +**Safari users:** Use Chrome, Firefox, or Edge for Workers Playground. + +## DevTools Integration + +1. **Open preview** in browser tab +2. **Right-click** → Inspect Element +3. **Console tab** shows Worker logs: + - `console.log()` output + - Uncaught errors + - Network requests (subrequests) + +**Note:** DevTools show client-side console, not Worker execution logs. For production logging, use Logpush or Tail Workers. + +## Limits in Playground + +Same as production Free plan: + +| Resource | Limit | Notes | +|----------|-------|-------| +| CPU time | 10ms | Per request | +| Memory | 128 MB | Per request | +| Script size | 1 MB | After compression | +| Subrequests | 50 | Outbound fetch calls | +| Request size | 100 MB | Incoming | +| Response size | Unlimited | Outgoing (streamed) | + +**Exceeding CPU time** throws error immediately. Optimize hot paths or upgrade to Paid plan (50ms CPU). diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..9271dc435482a37c94c74ba5526be1495c3d85a8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/gotchas.md @@ -0,0 +1,88 @@ +# Workers Playground Gotchas + +## Platform Limitations + +| Limitation | Impact | Workaround | +|------------|--------|------------| +| Safari broken | Preview fails | Use Chrome/Firefox/Edge | +| TypeScript unsupported | TS syntax errors | Write plain JS or use JSDoc | +| No bindings | `env` always `{}` | Mock data or use external APIs | +| No env vars | Can't access secrets | Hardcode for testing | + +## Common Runtime Errors + +### "Response body already read" + +```javascript +// ❌ Body consumed twice +const body = await request.text(); +await fetch(url, { body: request.body }); // Error! + +// ✅ Clone first +const clone = request.clone(); +const body = await request.text(); +await fetch(url, { body: clone.body }); +``` + +### "Worker exceeded CPU time" + +**Limit:** 10ms (free), 50ms (paid) + +```javascript +// ✅ Move slow work to background +ctx.waitUntil(fetch('https://analytics.example.com', {...})); +return new Response('OK'); // Return immediately +``` + +### "Too many subrequests" + +**Limit:** 50 (free), 1000 (paid) + +```javascript +// ❌ 100 individual fetches +// ✅ Batch into single API call +await fetch('https://api.example.com/batch', { + body: JSON.stringify({ ids: [...] }) +}); +``` + +## Best Practices + +```javascript +// Clone before caching +await cache.put(request, response.clone()); +return response; + +// Validate input early +if (request.method !== 'POST') return new Response('', { status: 405 }); + +// Handle errors +try { ... } catch (e) { + return Response.json({ error: e.message }, { status: 500 }); +} +``` + +## Limits + +| Resource | Free | Paid | +|----------|------|------| +| CPU time | 10ms | 50ms | +| Memory | 128 MB | 128 MB | +| Subrequests | 50 | 1000 | + +## Browser Support + +| Browser | Status | +|---------|--------| +| Chrome | ✅ Recommended | +| Firefox | ✅ Works | +| Edge | ✅ Works | +| Safari | ❌ Broken | + +## Debugging + +```javascript +console.log('URL:', request.url); // View in browser DevTools Console +``` + +**Note:** `console.log` works in playground. For production, use Logpush or Tail Workers. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..4af891c532aef30a3453d2fb499b729f098525bc --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workers-playground/patterns.md @@ -0,0 +1,132 @@ +# Workers Playground Patterns + +## JSON API + +```javascript +export default { + async fetch(request) { + const url = new URL(request.url); + if (url.pathname === '/api/hello') return Response.json({ message: 'Hello' }); + if (url.pathname === '/api/echo' && request.method === 'POST') { + return Response.json({ received: await request.json() }); + } + return Response.json({ error: 'Not found' }, { status: 404 }); + } +}; +``` + +## Router Pattern + +```javascript +const routes = { + '/': () => new Response('Home'), + '/api/users': () => Response.json([{ id: 1, name: 'Alice' }]) +}; + +export default { + async fetch(request) { + const handler = routes[new URL(request.url).pathname]; + return handler ? handler() : new Response('Not Found', { status: 404 }); + } +}; +``` + +## Proxy Pattern + +```javascript +export default { + async fetch(request) { + const url = new URL(request.url); + url.hostname = 'api.example.com'; + return fetch(url.toString(), { + method: request.method, headers: request.headers, body: request.body + }); + } +}; +``` + +## CORS Handling + +```javascript +export default { + async fetch(request) { + if (request.method === 'OPTIONS') { + return new Response(null, { + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization' + } + }); + } + const response = await fetch('https://api.example.com', request); + const modified = new Response(response.body, response); + modified.headers.set('Access-Control-Allow-Origin', '*'); + return modified; + } +}; +``` + +## Caching + +```javascript +export default { + async fetch(request) { + if (request.method !== 'GET') return fetch(request); + const cache = caches.default; + let response = await cache.match(request); + if (!response) { + response = await fetch('https://api.example.com'); + if (response.status === 200) await cache.put(request, response.clone()); + } + return response; + } +}; +``` + +## Hono Framework + +```javascript +import { Hono } from 'https://esm.sh/hono@3'; +const app = new Hono(); +app.get('/', (c) => c.text('Hello')); +app.get('/api/users/:id', (c) => c.json({ id: c.req.param('id') })); +app.notFound((c) => c.json({ error: 'Not found' }, 404)); +export default app; +``` + +## Authentication + +```javascript +export default { + async fetch(request) { + const auth = request.headers.get('Authorization'); + if (!auth?.startsWith('Bearer ')) { + return Response.json({ error: 'Unauthorized' }, { status: 401 }); + } + const token = auth.substring(7); + if (token !== 'secret-token') { + return Response.json({ error: 'Invalid token' }, { status: 403 }); + } + return Response.json({ message: 'Authenticated' }); + } +}; +``` + +## Error Handling + +```javascript +export default { + async fetch(request) { + try { + const response = await fetch('https://api.example.com'); + if (!response.ok) throw new Error(`API returned ${response.status}`); + return response; + } catch (error) { + return Response.json({ error: error.message }, { status: 500 }); + } + } +}; +``` + +**Note:** In-memory state (Maps, variables) resets on Worker cold start. Use Durable Objects or KV for persistence. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/README.md new file mode 100644 index 0000000000000000000000000000000000000000..08a5eaf93ee57a9be3e5f3c1f3e147a81bb5df97 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/README.md @@ -0,0 +1,69 @@ +# Cloudflare Workflows + +Durable multi-step applications with automatic retries, state persistence, and long-running execution. + +## What It Does + +- Chain steps with automatic retry logic +- Persist state between steps (minutes → weeks) +- Handle failures without losing progress +- Wait for external events/approvals +- Sleep without consuming resources + +**Available:** Free & Paid Workers plans + +## Core Concepts + +**Workflow**: Class extending `WorkflowEntrypoint` with `run` method +**Instance**: Single execution with unique ID & independent state +**Steps**: Independently retriable units via `step.do()` - API calls, DB queries, AI invocations +**State**: Persisted from step returns; step name = cache key + +## Quick Start + +```typescript +import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers'; + +type Env = { MY_WORKFLOW: Workflow; DB: D1Database }; +type Params = { userId: string }; + +export class MyWorkflow extends WorkflowEntrypoint { + async run(event: WorkflowEvent, step: WorkflowStep) { + const user = await step.do('fetch user', async () => { + return await this.env.DB.prepare('SELECT * FROM users WHERE id = ?') + .bind(event.params.userId).first(); + }); + + await step.sleep('wait 7 days', '7 days'); + + await step.do('send reminder', async () => { + await sendEmail(user.email, 'Reminder!'); + }); + } +} +``` + +## Key Features + +- **Durability**: Failed steps don't re-run successful ones +- **Retries**: Configurable backoff (constant/linear/exponential) +- **Events**: `waitForEvent()` for webhooks/approvals (timeout: 1h → 365d) +- **Sleep**: `sleep()` / `sleepUntil()` for scheduling (max 365d) +- **Parallel**: `Promise.all()` for concurrent steps +- **Idempotency**: Check-then-execute patterns + +## Reading Order + +**Getting Started:** configuration.md → api.md → patterns.md +**Troubleshooting:** gotchas.md + +## In This Reference +- [configuration.md](./configuration.md) - wrangler.jsonc setup, step config, bindings +- [api.md](./api.md) - Step APIs, instance management, sleep/parameters +- [patterns.md](./patterns.md) - Common workflows, testing, orchestration +- [gotchas.md](./gotchas.md) - Timeouts, limits, debugging strategies + +## See Also +- [durable-objects](../durable-objects/) - Alternative stateful approach +- [queues](../queues/) - Message-driven workflows +- [workers](../workers/) - Entry point for workflow instances diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/api.md new file mode 100644 index 0000000000000000000000000000000000000000..7ac5625789451403da5d844564dcec232d5856b9 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/api.md @@ -0,0 +1,185 @@ +# Workflow APIs + +## Step APIs + +```typescript +// step.do() +const result = await step.do('step name', async () => { /* logic */ }); +const result = await step.do('step name', { retries, timeout }, async () => {}); + +// step.sleep() +await step.sleep('description', '1 hour'); +await step.sleep('description', 5000); // ms + +// step.sleepUntil() +await step.sleepUntil('description', Date.parse('2024-12-31')); + +// step.waitForEvent() +const data = await step.waitForEvent('wait', {event: 'webhook-type', timeout: '24h'}); // Default 24h, max 365d +try { const event = await step.waitForEvent('wait', { event: 'approval', timeout: '1h' }); } catch (e) { /* Timeout */ } +``` + +## Instance Management + +```typescript +// Create single +const instance = await env.MY_WORKFLOW.create({id: crypto.randomUUID(), params: { userId: 'user123' }}); // id optional, auto-generated if omitted + +// Create with custom retention (default: 3 days free, 30 days paid) +const instance = await env.MY_WORKFLOW.create({ + id: crypto.randomUUID(), + params: { userId: 'user123' }, + retention: '30 days' // Override default retention period +}); + +// Batch (max 100, idempotent: skips existing IDs) +const instances = await env.MY_WORKFLOW.createBatch([{id: 'user1', params: {name: 'John'}}, {id: 'user2', params: {name: 'Jane'}}]); + +// Get & Status +const instance = await env.MY_WORKFLOW.get('instance-id'); +const status = await instance.status(); // {status: 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown', error?, output?} + +// Control +await instance.pause(); await instance.resume(); await instance.terminate(); await instance.restart(); + +// Send Events +await instance.sendEvent({type: 'approval', payload: { approved: true }}); // Must match waitForEvent type +``` + +## Triggering Workflows + +```typescript +// From Worker +export default { async fetch(req, env) { const instance = await env.MY_WORKFLOW.create({id: crypto.randomUUID(), params: { userId: 'user123' }}); return Response.json({ id: instance.id }); }}; + +// From Queue +export default { async queue(batch, env) { for (const msg of batch.messages) { await env.MY_WORKFLOW.create({id: `job-${msg.id}`, params: msg.body}); } }}; + +// From Cron +export default { async scheduled(event, env) { await env.CLEANUP_WORKFLOW.create({id: `cleanup-${Date.now()}`, params: { timestamp: event.scheduledTime }}); }}; + +// From Another Workflow (non-blocking) +export class ParentWorkflow extends WorkflowEntrypoint { + async run(event, step) { + const child = await step.do('start child', async () => await this.env.CHILD_WORKFLOW.create({id: `child-${event.instanceId}`, params: {}})); + } +} +``` + +## Error Handling + +```typescript +import { NonRetryableError } from 'cloudflare:workers'; + +// NonRetryableError +await step.do('validate', async () => { + if (!event.params.paymentMethod) throw new NonRetryableError('Payment method required'); + const res = await fetch('https://api.example.com/charge', { method: 'POST' }); + if (res.status === 401) throw new NonRetryableError('Invalid credentials'); // Don't retry + if (!res.ok) throw new Error('Retryable failure'); // Will retry + return res.json(); +}); + +// Catching Errors +try { await step.do('risky op', async () => { throw new NonRetryableError('Failed'); }); } catch (e) { await step.do('cleanup', async () => {}); } + +// Idempotency +await step.do('charge', async () => { + const sub = await fetch(`https://api/subscriptions/${id}`).then(r => r.json()); + if (sub.charged) return sub; // Already done + return await fetch(`https://api/subscriptions/${id}`, {method: 'POST', body: JSON.stringify({ amount: 10.0 })}).then(r => r.json()); +}); +``` + +## Type Constraints + +Params and step returns must be `Rpc.Serializable`: + +```typescript +// ✅ Valid types +type ValidParams = { + userId: string; + count: number; + tags: string[]; + metadata: Record; +}; + +// ❌ Invalid types +type InvalidParams = { + callback: () => void; // Functions not serializable + symbol: symbol; // Symbols not serializable + circular: any; // Circular references not allowed +}; + +// Step returns follow same rules +const result = await step.do('fetch', async () => { + return { userId: '123', data: [1, 2, 3] }; // ✅ Plain object +}); +``` + +## Sleep & Scheduling + +```typescript +// Relative +await step.sleep('wait 1 hour', '1 hour'); +await step.sleep('wait 30 days', '30 days'); +await step.sleep('wait 5s', 5000); // ms + +// Absolute +await step.sleepUntil('launch date', Date.parse('24 Oct 2024 13:00:00 UTC')); +await step.sleepUntil('deadline', new Date('2024-12-31T23:59:59Z')); +``` + +Units: second, minute, hour, day, week, month, year. Max: 365 days. +Sleeping instances don't count toward concurrency. + +## Parameters + +**Pass from Worker:** +```typescript +const instance = await env.MY_WORKFLOW.create({ + id: crypto.randomUUID(), + params: { userId: 'user123', email: 'user@example.com' } +}); +``` + +**Access in Workflow:** +```typescript +async run(event: WorkflowEvent, step: WorkflowStep) { + const userId = event.params.userId; + const instanceId = event.instanceId; + const createdAt = event.timestamp; +} +``` + +**CLI Trigger:** +```bash +npx wrangler workflows trigger my-workflow '{"userId":"user123"}' +``` + +## Wrangler CLI + +```bash +npm create cloudflare@latest my-workflow -- --template "cloudflare/workflows-starter" +npx wrangler deploy +npx wrangler workflows list +npx wrangler workflows trigger my-workflow '{"userId":"user123"}' +npx wrangler workflows instances list my-workflow +npx wrangler workflows instances describe my-workflow instance-id +npx wrangler workflows instances pause/resume/terminate my-workflow instance-id +``` + +## REST API + +```bash +# Create +curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/workflows/{workflow_name}/instances" -H "Authorization: Bearer {token}" -d '{"id":"custom-id","params":{"userId":"user123"}}' + +# Status +curl "https://api.cloudflare.com/client/v4/accounts/{account_id}/workflows/{workflow_name}/instances/{instance_id}/status" -H "Authorization: Bearer {token}" + +# Send Event +curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/workflows/{workflow_name}/instances/{instance_id}/events" -H "Authorization: Bearer {token}" -d '{"type":"approval","payload":{"approved":true}}' +``` + +See: [configuration.md](./configuration.md), [patterns.md](./patterns.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..14516e4872613bf8e657e15e9ca6008e9bc5b07c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/configuration.md @@ -0,0 +1,151 @@ +# Workflow Configuration + +## wrangler.jsonc Setup + +```jsonc +{ + "name": "my-worker", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", // Use current date for new projects + "observability": { + "enabled": true // Enables Workflows dashboard + structured logs + }, + "workflows": [ + { + "name": "my-workflow", // Workflow name + "binding": "MY_WORKFLOW", // Env binding + "class_name": "MyWorkflow" // TS class name + // "script_name": "other-worker" // For cross-script calls + } + ], + "limits": { + "cpu_ms": 300000 // 5 min max (default 30s) + } +} +``` + +## Step Configuration + +```typescript +// Basic step +const data = await step.do('step name', async () => ({ result: 'value' })); + +// With retry config +await step.do('api call', { + retries: { + limit: 10, // Default: 5, or Infinity + delay: '10 seconds', // Default: 10000ms + backoff: 'exponential' // constant | linear | exponential + }, + timeout: '30 minutes' // Per-attempt timeout (default: 10min) +}, async () => { + const res = await fetch('https://api.example.com/data'); + if (!res.ok) throw new Error('Failed'); + return res.json(); +}); +``` + +### Parallel Steps +```typescript +const [user, settings] = await Promise.all([ + step.do('fetch user', async () => this.env.KV.get(`user:${id}`)), + step.do('fetch settings', async () => this.env.KV.get(`settings:${id}`)) +]); +``` + +### Conditional Steps +```typescript +const config = await step.do('fetch config', async () => + this.env.KV.get('flags', { type: 'json' }) +); + +// ✅ Deterministic (based on step output) +if (config.enableEmail) { + await step.do('send email', async () => sendEmail()); +} + +// ❌ Non-deterministic (Date.now outside step) +if (Date.now() > deadline) { /* BAD */ } +``` + +### Dynamic Steps (Loops) +```typescript +const files = await step.do('list files', async () => + this.env.BUCKET.list() +); + +for (const file of files.objects) { + await step.do(`process ${file.key}`, async () => { + const obj = await this.env.BUCKET.get(file.key); + return processData(await obj.arrayBuffer()); + }); +} +``` + +## Multiple Workflows + +```jsonc +{ + "workflows": [ + {"name": "user-onboarding", "binding": "USER_ONBOARDING", "class_name": "UserOnboarding"}, + {"name": "data-processing", "binding": "DATA_PROCESSING", "class_name": "DataProcessing"} + ] +} +``` + +Each class extends `WorkflowEntrypoint` with its own `Params` type. + +## Cross-Script Bindings + +Worker A defines workflow. Worker B calls it by adding `script_name`: + +```jsonc +// Worker B (caller) +{ + "workflows": [{ + "name": "billing-workflow", + "binding": "BILLING", + "script_name": "billing-worker" // Points to Worker A + }] +} +``` + +## Bindings + +Workflows access Cloudflare bindings via `this.env`: + +```typescript +type Env = { + MY_WORKFLOW: Workflow; + KV: KVNamespace; + DB: D1Database; + BUCKET: R2Bucket; + AI: Ai; + VECTORIZE: VectorizeIndex; +}; + +await step.do('use bindings', async () => { + const kv = await this.env.KV.get('key'); + const db = await this.env.DB.prepare('SELECT * FROM users').first(); + const file = await this.env.BUCKET.get('file.txt'); + const ai = await this.env.AI.run('@cf/meta/llama-2-7b-chat-int8', { prompt: 'Hi' }); +}); +``` + +## Pages Functions Binding + +Pages Functions can trigger Workflows via service bindings: + +```typescript +// functions/_middleware.ts +export const onRequest: PagesFunction = async ({ env, request }) => { + const instance = await env.MY_WORKFLOW.create({ + params: { url: request.url } + }); + return new Response(`Started ${instance.id}`); +}; +``` + +Configure in wrangler.jsonc under `service_bindings`. + +See: [api.md](./api.md), [patterns.md](./patterns.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..06465601ef4a28151032704498f71e8b82b42b6e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/gotchas.md @@ -0,0 +1,97 @@ +# Gotchas & Debugging + +## Common Errors + +### "Step Timeout" + +**Cause:** Step execution exceeding 10 minute default timeout or configured timeout +**Solution:** Set custom timeout with `step.do('long operation', {timeout: '30 minutes'}, async () => {...})` or increase CPU limit in wrangler.jsonc (max 5min CPU time) + +### "waitForEvent Timeout" + +**Cause:** Event not received within timeout period (default 24h, max 365d) +**Solution:** Wrap in try-catch to handle timeout gracefully and proceed with default behavior + +### "Non-Deterministic Step Names" + +**Cause:** Using dynamic values like `Date.now()` in step names causes replay issues +**Solution:** Use deterministic values like `event.instanceId` for step names + +### "State Lost in Variables" + +**Cause:** Using module-level or local variables to store state which is lost on hibernation +**Solution:** Return values from `step.do()` which are automatically persisted: `const total = await step.do('step 1', async () => 10)` + +### "Non-Deterministic Conditionals" + +**Cause:** Using non-deterministic logic (like `Date.now()`) outside steps in conditionals +**Solution:** Move non-deterministic operations inside steps: `const isLate = await step.do('check', async () => Date.now() > deadline)` + +### "Large Step Returns Exceeding Limit" + +**Cause:** Returning data >1 MiB from step +**Solution:** Store large data in R2 and return only reference: `{ key: 'r2-object-key' }` + +### "Step Exceeded CPU Limit But Ran for < 30s" + +**Cause:** Confusion between CPU time (active compute) and wall-clock time (includes I/O waits) +**Solution:** Network requests, database queries, and sleeps don't count toward CPU. 30s limit = 30s of active processing + +### "Idempotency Violation" + +**Cause:** Step operations not idempotent, causing duplicate charges or actions on retry +**Solution:** Check if operation already completed before executing (e.g., check if customer already charged) + +### "Instance ID Collision" + +**Cause:** Reusing instance IDs causing conflicts +**Solution:** Use unique IDs with timestamp: `await env.MY_WORKFLOW.create({ id: \`${userId}-${Date.now()}\`, params: {} })` + +### "Instance Data Disappeared After Completion" + +**Cause:** Completed/errored instances are automatically deleted after retention period (3 days free / 30 days paid) +**Solution:** Export critical data to KV/R2/D1 before workflow completes + +### "Missing await on step.do" + +**Cause:** Forgetting to await step.do() causing fire-and-forget behavior +**Solution:** Always await step operations: `await step.do('task', ...)` + +## Limits + +| Limit | Free | Paid | Notes | +|-------|------|------|-------| +| CPU per step | 10ms | 30s (default), 5min (max) | Set via `limits.cpu_ms` in wrangler.jsonc | +| Step state | 1 MiB | 1 MiB | Per step return value | +| Instance state | 100 MB | 1 GB | Total state per workflow instance | +| Steps per workflow | 1,024 | 1,024 | `step.sleep()` doesn't count | +| Executions per day | 100k | Unlimited | Daily execution limit | +| Concurrent instances | 25 | 10k | Maximum concurrent workflows; waiting state excluded | +| Queued instances | 100k | 1M | Maximum queued workflow instances | +| Subrequests per step | 50 | 1,000 | Maximum outbound requests per step | +| State retention | 3 days | 30 days | How long completed instances kept | +| Step timeout default | 10 min | 10 min | Per attempt | +| waitForEvent timeout default | 24h | 24h | Maximum 365 days | +| waitForEvent timeout max | 365 days | 365 days | Maximum wait time | + +**Note:** Instances in `waiting` state (from `step.sleep` or `step.waitForEvent`) don't count toward concurrent instance limit, allowing millions of sleeping workflows. + +## Pricing + +| Metric | Free | Paid | Notes | +|--------|------|------|-------| +| Requests | 100k/day | 10M/mo + $0.30/M | Workflow invocations | +| CPU time | 10ms/invoke | 30M CPU-ms/mo + $0.02/M CPU-ms | Actual CPU usage | +| Storage | 1 GB | 1 GB/mo + $0.20/GB-mo | All instances (running/errored/sleeping/completed) | + +## References + +- [Official Docs](https://developers.cloudflare.com/workflows/) +- [Get Started Guide](https://developers.cloudflare.com/workflows/get-started/guide/) +- [Workers API](https://developers.cloudflare.com/workflows/build/workers-api/) +- [REST API](https://developers.cloudflare.com/api/resources/workflows/) +- [Examples](https://developers.cloudflare.com/workflows/examples/) +- [Limits](https://developers.cloudflare.com/workflows/reference/limits/) +- [Pricing](https://developers.cloudflare.com/workflows/reference/pricing/) + +See: [README.md](./README.md), [configuration.md](./configuration.md), [api.md](./api.md), [patterns.md](./patterns.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..86e7b3c9c41bfa7efa93b147d3d0ffe31e6e0c12 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/workflows/patterns.md @@ -0,0 +1,175 @@ +# Workflow Patterns + +## Image Processing Pipeline + +```typescript +export class ImageProcessingWorkflow extends WorkflowEntrypoint { + async run(event, step) { + const imageData = await step.do('fetch', async () => (await this.env.BUCKET.get(event.params.imageKey)).arrayBuffer()); + const description = await step.do('generate description', async () => + await this.env.AI.run('@cf/llava-hf/llava-1.5-7b-hf', {image: Array.from(new Uint8Array(imageData)), prompt: 'Describe this image', max_tokens: 50}) + ); + await step.waitForEvent('await approval', { event: 'approved', timeout: '24h' }); + await step.do('publish', async () => await this.env.BUCKET.put(`public/${event.params.imageKey}`, imageData)); + } +} +``` + +## User Lifecycle + +```typescript +export class UserLifecycleWorkflow extends WorkflowEntrypoint { + async run(event, step) { + await step.do('welcome email', async () => await sendEmail(event.params.email, 'Welcome!')); + await step.sleep('trial period', '7 days'); + const hasConverted = await step.do('check conversion', async () => { + const user = await this.env.DB.prepare('SELECT subscription_status FROM users WHERE id = ?').bind(event.params.userId).first(); + return user.subscription_status === 'active'; + }); + if (!hasConverted) await step.do('trial expiration email', async () => await sendEmail(event.params.email, 'Trial ending')); + } +} +``` + +## Data Pipeline + +```typescript +export class DataPipelineWorkflow extends WorkflowEntrypoint { + async run(event, step) { + const rawData = await step.do('extract', {retries: { limit: 10, delay: '30s', backoff: 'exponential' }}, async () => { + const res = await fetch(event.params.sourceUrl); + if (!res.ok) throw new Error('Fetch failed'); + return res.json(); + }); + const transformed = await step.do('transform', async () => + rawData.map(item => ({ id: item.id, normalized: normalizeData(item) })) + ); + const dataRef = await step.do('store', async () => { + const key = `processed/${Date.now()}.json`; + await this.env.BUCKET.put(key, JSON.stringify(transformed)); + return { key }; + }); + await step.do('load', async () => { + const data = await (await this.env.BUCKET.get(dataRef.key)).json(); + for (let i = 0; i < data.length; i += 100) { + await this.env.DB.batch(data.slice(i, i + 100).map(item => + this.env.DB.prepare('INSERT INTO records VALUES (?, ?)').bind(item.id, item.normalized) + )); + } + }); + } +} +``` + +## Human-in-the-Loop Approval + +```typescript +export class ApprovalWorkflow extends WorkflowEntrypoint { + async run(event, step) { + await step.do('create approval', async () => await this.env.DB.prepare('INSERT INTO approvals (id, user_id, status) VALUES (?, ?, ?)').bind(event.instanceId, event.params.userId, 'pending').run()); + try { + const approval = await step.waitForEvent<{ approved: boolean }>('wait for approval', { event: 'approval-response', timeout: '48h' }); + if (approval.approved) { await step.do('process approval', async () => {}); } + else { await step.do('handle rejection', async () => {}); } + } catch (e) { + await step.do('auto reject', async () => await this.env.DB.prepare('UPDATE approvals SET status = ? WHERE id = ?').bind('auto-rejected', event.instanceId).run()); + } + } +} +``` + +## Testing Workflows + +### Setup + +```typescript +// vitest.config.ts +import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config'; + +export default defineWorkersConfig({ + test: { + poolOptions: { + workers: { + wrangler: { configPath: './wrangler.jsonc' } + } + } + } +}); +``` + +### Introspection API + +```typescript +import { introspectWorkflowInstance } from 'cloudflare:test'; + +const instance = await env.MY_WORKFLOW.create({ params: { userId: '123' } }); +const introspector = await introspectWorkflowInstance(env.MY_WORKFLOW, instance.id); + +// Wait for step completion +const result = await introspector.waitForStepResult({ name: 'fetch user', index: 0 }); + +// Mock step behavior +await introspector.modify(async (m) => { + await m.mockStepResult({ name: 'api call' }, { mocked: true }); +}); +``` + +## Best Practices + +### ✅ DO + +1. **Granular steps**: One API call per step (unless proving idempotency) +2. **Idempotency**: Check-then-execute; use idempotency keys +3. **Deterministic names**: Use static or step-output-based names +4. **Return state**: Persist via step returns, not variables +5. **Always await**: `await step.do()`, avoid dangling promises +6. **Deterministic conditionals**: Base on `event.payload` or step outputs +7. **Store large data externally**: R2/KV for >1 MiB, return refs +8. **Batch creation**: `createBatch()` for multiple instances + +### ❌ DON'T + +1. **One giant step**: Breaks durability & retry control +2. **State outside steps**: Lost on hibernation +3. **Mutate events**: Events immutable, return new state +4. **Non-deterministic logic outside steps**: `Math.random()`, `Date.now()` must be in steps +5. **Side effects outside steps**: May duplicate on restart +6. **Non-deterministic step names**: Prevents caching +7. **Ignore timeouts**: `waitForEvent` throws, use try-catch +8. **Reuse instance IDs**: Must be unique within retention + +## Orchestration Patterns + +### Fan-Out (Parallel Processing) +```typescript +const files = await step.do('list', async () => this.env.BUCKET.list()); +await Promise.all(files.objects.map((file, i) => step.do(`process ${i}`, async () => processFile(await (await this.env.BUCKET.get(file.key)).arrayBuffer())))); +``` + +### Parent-Child Workflows +```typescript +const child = await step.do('start child', async () => await this.env.CHILD_WORKFLOW.create({id: `child-${event.instanceId}`, params: { data: result.data }})); +await step.do('other work', async () => console.log(`Child started: ${child.id}`)); +``` + +### Race Pattern +```typescript +const winner = await Promise.race([ + step.do('option A', async () => slowOperation()), + step.do('option B', async () => fastOperation()) +]); +``` + +### Scheduled Workflow Chain +```typescript +export default { async scheduled(event, env) { await env.DAILY_WORKFLOW.create({id: `daily-${event.scheduledTime}`, params: { timestamp: event.scheduledTime }}); }}; +export class DailyWorkflow extends WorkflowEntrypoint { + async run(event, step) { + await step.do('daily task', async () => {}); + await step.sleep('wait 7 days', '7 days'); + await step.do('weekly followup', async () => {}); + } +} +``` + +See: [configuration.md](./configuration.md), [api.md](./api.md), [gotchas.md](./gotchas.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/wrangler/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/wrangler/api.md new file mode 100644 index 0000000000000000000000000000000000000000..63bd9d05dc94f209007bf8d62ff11b8380a20431 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/wrangler/api.md @@ -0,0 +1,188 @@ +# Wrangler Programmatic API + +Node.js APIs for testing and development. + +## startWorker (Testing) + +Starts Worker with real local bindings for integration tests. Stable API (replaces `unstable_startWorker`). + +```typescript +import { startWorker } from "wrangler"; +import { describe, it, before, after } from "node:test"; +import assert from "node:assert"; + +describe("worker", () => { + let worker; + + before(async () => { + worker = await startWorker({ + config: "wrangler.jsonc", + environment: "development" + }); + }); + + after(async () => { + await worker.dispose(); + }); + + it("responds with 200", async () => { + const response = await worker.fetch("http://example.com"); + assert.strictEqual(response.status, 200); + }); +}); +``` + +### Options + +| Option | Type | Description | +|--------|------|-------------| +| `config` | `string` | Path to wrangler.jsonc | +| `environment` | `string` | Environment name from config | +| `persist` | `boolean \| { path: string }` | Enable persistent state | +| `bundle` | `boolean` | Enable bundling (default: true) | +| `remote` | `false \| true \| "minimal"` | Remote mode: `false` (local), `true` (full remote), `"minimal"` (remote bindings only) | + +### Remote Mode + +```typescript +// Local mode (default) - fast, simulated +const worker = await startWorker({ config: "wrangler.jsonc" }); + +// Full remote mode - production-like, slower +const worker = await startWorker({ + config: "wrangler.jsonc", + remote: true +}); + +// Minimal remote mode - remote bindings, local Worker +const worker = await startWorker({ + config: "wrangler.jsonc", + remote: "minimal" +}); +``` + +## getPlatformProxy + +Emulate bindings in Node.js without starting Worker. + +```typescript +import { getPlatformProxy } from "wrangler"; + +const { env, dispose, caches } = await getPlatformProxy({ + configPath: "wrangler.jsonc", + environment: "production", + persist: { path: ".wrangler/state" } +}); + +// Use bindings +const value = await env.MY_KV.get("key"); +await env.DB.prepare("SELECT * FROM users").all(); +await env.ASSETS.put("file.txt", "content"); + +// Platform APIs +await caches.default.put("https://example.com", new Response("cached")); + +await dispose(); +``` + +Use for unit tests (test functions, not full Worker) or scripts that need bindings. + +## Type Generation + +Generate types from config: `wrangler types` → creates `worker-configuration.d.ts` + +## Event System + +Listen to Worker lifecycle events for advanced workflows. + +```typescript +import { startWorker } from "wrangler"; + +const worker = await startWorker({ + config: "wrangler.jsonc", + bundle: true +}); + +// Bundle events +worker.on("bundleStart", (details) => { + console.log("Bundling started:", details.config); +}); + +worker.on("bundleComplete", (details) => { + console.log("Bundle ready:", details.duration); +}); + +// Reconfiguration events +worker.on("reloadStart", () => { + console.log("Worker reloading..."); +}); + +worker.on("reloadComplete", () => { + console.log("Worker reloaded"); +}); + +await worker.dispose(); +``` + +### Dynamic Reconfiguration + +```typescript +import { startWorker } from "wrangler"; + +const worker = await startWorker({ config: "wrangler.jsonc" }); + +// Replace entire config +await worker.setConfig({ + config: "wrangler.staging.jsonc", + environment: "staging" +}); + +// Patch specific fields +await worker.patchConfig({ + vars: { DEBUG: "true" } +}); + +await worker.dispose(); +``` + +## unstable_dev (Deprecated) + +Use `startWorker` instead. + +## Multi-Worker Registry + +Test multiple Workers with service bindings. + +```typescript +import { startWorker } from "wrangler"; + +const auth = await startWorker({ config: "./auth/wrangler.jsonc" }); +const api = await startWorker({ + config: "./api/wrangler.jsonc", + bindings: { AUTH: auth } // Service binding +}); + +const response = await api.fetch("http://example.com/api/login"); +// API Worker calls AUTH Worker via env.AUTH.fetch() + +await api.dispose(); +await auth.dispose(); +``` + +## Best Practices + +- Use `startWorker` for integration tests (tests full Worker) +- Use `getPlatformProxy` for unit tests (tests individual functions) +- Use `remote: true` when debugging production-specific issues +- Use `remote: "minimal"` for faster tests with real bindings +- Enable `persist: true` for debugging (state survives runs) +- Run `wrangler types` after config changes +- Always `dispose()` to prevent resource leaks +- Listen to bundle events for build monitoring +- Use multi-worker registry for testing service bindings + +## See Also + +- [README.md](./README.md) - CLI commands +- [configuration.md](./configuration.md) - Config +- [patterns.md](./patterns.md) - Testing patterns diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/wrangler/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/wrangler/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..dcf936b16ba129960e70f911ae60b3790dff3c08 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/wrangler/configuration.md @@ -0,0 +1,197 @@ +# Wrangler Configuration + +Configuration reference for wrangler.jsonc (recommended). + +## Config Format + +**wrangler.jsonc recommended** (v3.91.0+) - provides schema validation. + +```jsonc +{ + "$schema": "./node_modules/wrangler/config-schema.json", + "name": "my-worker", + "main": "src/index.ts", + "compatibility_date": "2025-01-01", // Use current date + "vars": { "API_KEY": "dev-key" }, + "kv_namespaces": [{ "binding": "MY_KV", "id": "abc123" }] +} +``` + +## Field Inheritance + +Inheritable: `name`, `main`, `compatibility_date`, `routes`, `triggers` +Non-inheritable (define per env): `vars`, bindings (KV, D1, R2, etc.) + +## Environments + +```jsonc +{ + "name": "my-worker", + "vars": { "ENV": "dev" }, + "env": { + "production": { + "name": "my-worker-prod", + "vars": { "ENV": "prod" }, + "route": { "pattern": "example.com/*", "zone_name": "example.com" } + } + } +} +``` + +Deploy: `wrangler deploy --env production` + +## Routing + +```jsonc +// Custom domain (recommended) +{ "routes": [{ "pattern": "api.example.com", "custom_domain": true }] } + +// Zone-based +{ "routes": [{ "pattern": "api.example.com/*", "zone_name": "example.com" }] } + +// workers.dev +{ "workers_dev": true } +``` + +## Bindings + +```jsonc +// Variables +{ "vars": { "API_URL": "https://api.example.com" } } + +// KV +{ "kv_namespaces": [{ "binding": "CACHE", "id": "abc123" }] } + +// D1 +{ "d1_databases": [{ "binding": "DB", "database_id": "abc-123" }] } + +// R2 +{ "r2_buckets": [{ "binding": "ASSETS", "bucket_name": "my-assets" }] } + +// Durable Objects +{ "durable_objects": { + "bindings": [{ + "name": "COUNTER", + "class_name": "Counter", + "script_name": "my-worker" // Required for external DOs + }] +} } +{ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Counter"] }] } + +// Service Bindings +{ "services": [{ "binding": "AUTH", "service": "auth-worker" }] } + +// Queues +{ "queues": { + "producers": [{ "binding": "TASKS", "queue": "task-queue" }], + "consumers": [{ "queue": "task-queue", "max_batch_size": 10 }] +} } + +// Vectorize +{ "vectorize": [{ "binding": "VECTORS", "index_name": "embeddings" }] } + +// Hyperdrive (requires nodejs_compat_v2 for pg/postgres) +{ "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "hyper-id" }] } +{ "compatibility_flags": ["nodejs_compat_v2"] } // For pg/postgres + +// Workers AI +{ "ai": { "binding": "AI" } } + +// Workflows +{ "workflows": [{ "binding": "WORKFLOW", "name": "my-workflow", "class_name": "MyWorkflow" }] } + +// Secrets Store (centralized secrets) +{ "secrets_store": [{ "binding": "SECRETS", "id": "store-id" }] } + +// Constellation (AI inference) +{ "constellation": [{ "binding": "MODEL", "project_id": "proj-id" }] } +``` + +## Workers Assets (Static Files) + +Recommended for serving static files (replaces old `site` config). + +```jsonc +{ + "assets": { + "directory": "./public", + "binding": "ASSETS", + "html_handling": "auto-trailing-slash", // or "none", "force-trailing-slash" + "not_found_handling": "single-page-application" // or "404-page", "none" + } +} +``` + +Access in Worker: +```typescript +export default { + async fetch(request, env) { + // Try serving static asset first + const asset = await env.ASSETS.fetch(request); + if (asset.status !== 404) return asset; + + // Custom logic for non-assets + return new Response("API response"); + } +} +``` + +## Placement + +Control where Workers run geographically. + +```jsonc +{ + "placement": { + "mode": "smart" // or "off" + } +} +``` + +- `"smart"`: Run Worker near data sources (D1, Durable Objects) to reduce latency +- `"off"`: Default distribution (run everywhere) + +## Auto-Provisioning (Beta) + +Omit resource IDs - Wrangler creates them and writes back to config on deploy. + +```jsonc +{ "kv_namespaces": [{ "binding": "MY_KV" }] } // No id - auto-provisioned +``` + +After deploy, ID is added to config automatically. + +## Advanced + +```jsonc +// Cron Triggers +{ "triggers": { "crons": ["0 0 * * *"] } } + +// Observability (tracing) +{ "observability": { "enabled": true, "head_sampling_rate": 0.1 } } + +// Runtime Limits +{ "limits": { "cpu_ms": 100 } } + +// Browser Rendering +{ "browser": { "binding": "BROWSER" } } + +// mTLS Certificates +{ "mtls_certificates": [{ "binding": "CERT", "certificate_id": "cert-uuid" }] } + +// Logpush (stream logs to R2/S3) +{ "logpush": true } + +// Tail Consumers (process logs with another Worker) +{ "tail_consumers": [{ "service": "log-worker" }] } + +// Unsafe bindings (access to arbitrary bindings) +{ "unsafe": { "bindings": [{ "name": "MY_BINDING", "type": "plain_text", "text": "value" }] } } +``` + +## See Also + +- [README.md](./README.md) - Overview and commands +- [api.md](./api.md) - Programmatic API +- [patterns.md](./patterns.md) - Workflows +- [gotchas.md](./gotchas.md) - Common issues diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/IMPLEMENTATION_SUMMARY.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/IMPLEMENTATION_SUMMARY.md new file mode 100644 index 0000000000000000000000000000000000000000..dd8da196be21fd7855fbe93502223f195c3a3842 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/IMPLEMENTATION_SUMMARY.md @@ -0,0 +1,121 @@ +# Zaraz Reference Implementation Summary + +## Files Created + +| File | Lines | Purpose | +|------|-------|---------| +| README.md | 111 | Navigation, decision tree, quick start | +| api.md | 287 | Web API reference, Zaraz Context | +| configuration.md | 307 | Dashboard setup, triggers, tools, consent | +| patterns.md | 430 | SPA, e-commerce, Worker integration | +| gotchas.md | 317 | Troubleshooting, limits, tool-specific issues | +| **Total** | **1,452** | **vs 366 original** | + +## Key Improvements Applied + +### Structure +- ✅ Created 5-file progressive disclosure system +- ✅ Added navigation table in README +- ✅ Added decision tree for routing +- ✅ Added "Reading Order by Task" guide +- ✅ Cross-referenced files throughout + +### New Content Added +- ✅ Zaraz Context (system/client properties) +- ✅ History Change trigger for SPA tracking +- ✅ Context Enrichers pattern +- ✅ Worker Variables pattern +- ✅ Consent management deep dive +- ✅ Tool-specific quirks (GA4, Facebook, Google Ads) +- ✅ GTM migration guide +- ✅ Comprehensive troubleshooting +- ✅ "When NOT to use Zaraz" section +- ✅ TypeScript type definitions + +### Preserved Content +- ✅ All original API methods +- ✅ E-commerce tracking examples +- ✅ Consent management +- ✅ Workers integration (expanded) +- ✅ Common patterns (expanded) +- ✅ Debugging tools +- ✅ Reference links + +## Progressive Disclosure Impact + +### Before (Monolithic) +All tasks loaded 366 lines regardless of need. + +### After (Progressive) +- **Track event task**: README (111) + api.md (287) = 398 lines +- **Debug issue**: gotchas.md (317) = 317 lines (13% reduction) +- **Configure tool**: configuration.md (307) = 307 lines (16% reduction) +- **SPA tracking**: README + patterns.md (SPA section) ~180 lines (51% reduction) + +**Net effect:** Task-specific loading reduces unnecessary content by 13-51% depending on use case. + +## File Summary + +### README.md (111 lines) +- Overview and core concepts +- Quick start guide +- When to use Zaraz vs Workers +- Navigation table +- Reading order by task +- Decision tree + +### api.md (287 lines) +- zaraz.track() +- zaraz.set() +- zaraz.ecommerce() +- Zaraz Context (system/client properties) +- zaraz.consent API +- zaraz.debug +- Cookie methods +- TypeScript definitions + +### configuration.md (307 lines) +- Dashboard setup flow +- Trigger types (including History Change) +- Tool configuration (GA4, Facebook, Google Ads) +- Actions and action rules +- Selective loading +- Consent management setup +- Privacy features +- Testing workflow + +### patterns.md (430 lines) +- SPA tracking (React, Vue, Next.js) +- User identification flows +- Complete e-commerce funnel +- A/B testing +- Worker integration (Context Enrichers, Worker Variables, HTML injection) +- Multi-tool coordination +- GTM migration +- Best practices + +### gotchas.md (317 lines) +- Events not firing (5-step debug process) +- Consent issues +- SPA tracking pitfalls +- Performance issues +- Tool-specific quirks +- Data layer issues +- Limits table +- When NOT to use Zaraz +- Debug checklist + +## Quality Metrics + +- ✅ All files use consistent markdown formatting +- ✅ Code examples include language tags +- ✅ Tables for structured data (limits, parameters, comparisons) +- ✅ Problem → Cause → Solution format in gotchas +- ✅ Cross-references between files +- ✅ No "see documentation" placeholders +- ✅ Real, actionable examples throughout +- ✅ Verified API syntax for Workers + +## Original Backup + +Original SKILL.md preserved as `_SKILL_old.md` for reference. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/README.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0e28155858ad77f0345536fbe758d296bd15c9d2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/README.md @@ -0,0 +1,111 @@ +# Cloudflare Zaraz + +Expert guidance for Cloudflare Zaraz - server-side tag manager for loading third-party tools at the edge. + +## What is Zaraz? + +Zaraz offloads third-party scripts (analytics, ads, chat, marketing) to Cloudflare's edge, improving site speed, privacy, and security. Zero client-side performance impact. + +**Core Concepts:** +- **Server-side execution** - Scripts run on Cloudflare, not user's browser +- **Single HTTP request** - All tools loaded via one endpoint +- **Privacy-first** - Control data sent to third parties +- **No client-side JS overhead** - Minimal browser impact + +## Quick Start + +1. Navigate to domain > Zaraz in Cloudflare dashboard +2. Click "Start setup" +3. Add tools (Google Analytics, Facebook Pixel, etc.) +4. Configure triggers (when tools fire) +5. Add tracking code to your site: + +```javascript +// Track page view +zaraz.track('page_view'); + +// Track custom event +zaraz.track('button_click', { button_id: 'cta' }); + +// Set user properties +zaraz.set('userId', 'user_123'); +``` + +## When to Use Zaraz + +**Use Zaraz when:** +- Adding multiple third-party tools (analytics, ads, marketing) +- Site performance is critical (no client-side JS overhead) +- Privacy compliance required (GDPR, CCPA) +- Non-technical teams need to manage tools + +**Use Workers directly when:** +- Building custom server-side tracking logic +- Need full control over data processing +- Integrating with complex backend systems +- Zaraz's tool library doesn't meet needs + +## In This Reference + +| File | Purpose | When to Read | +|------|---------|--------------| +| [api.md](./api.md) | Web API, zaraz object, consent methods | Implementing tracking calls | +| [configuration.md](./configuration.md) | Dashboard setup, triggers, tools | Initial setup, adding tools | +| [patterns.md](./patterns.md) | SPA, e-commerce, Worker integration | Best practices, common scenarios | +| [gotchas.md](./gotchas.md) | Troubleshooting, limits, pitfalls | Debugging issues | + +## Reading Order by Task + +| Task | Files to Read | +|------|---------------| +| Add analytics to site | README → configuration.md | +| Track custom events | README → api.md | +| Debug tracking issues | gotchas.md | +| SPA tracking | api.md → patterns.md (SPA section) | +| E-commerce tracking | api.md#ecommerce → patterns.md#ecommerce | +| Worker integration | patterns.md#worker-integration | +| GDPR compliance | api.md#consent → configuration.md#consent | + +## Decision Tree + +``` +What do you need? + +├─ Track events in browser → api.md +│ ├─ Page views, clicks → zaraz.track() +│ ├─ User properties → zaraz.set() +│ └─ E-commerce → zaraz.ecommerce() +│ +├─ Configure Zaraz → configuration.md +│ ├─ Add GA4/Facebook → tools setup +│ ├─ When tools fire → triggers +│ └─ GDPR consent → consent purposes +│ +├─ Integrate with Workers → patterns.md#worker-integration +│ ├─ Enrich context → Context Enrichers +│ └─ Inject tracking → HTML rewriting +│ +└─ Debug issues → gotchas.md + ├─ Events not firing → troubleshooting + ├─ Consent issues → consent debugging + └─ Performance → debugging tools +``` + +## Key Features + +- **100+ Pre-built Tools** - GA4, Facebook, Google Ads, TikTok, etc. +- **Zero Client Impact** - Runs at Cloudflare's edge, not browser +- **Privacy Controls** - Consent management, data filtering +- **Custom Tools** - Build Managed Components for proprietary systems +- **Worker Integration** - Enrich context, compute dynamic values +- **Debug Mode** - Real-time event inspection + +## Reference + +- [Zaraz Docs](https://developers.cloudflare.com/zaraz/) +- [Web API](https://developers.cloudflare.com/zaraz/web-api/) +- [Managed Components](https://developers.cloudflare.com/zaraz/advanced/load-custom-managed-component/) + +--- + +This skill focuses exclusively on Zaraz. For Workers development, see `cloudflare-workers` skill. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/api.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/api.md new file mode 100644 index 0000000000000000000000000000000000000000..5d8e1cc8c1f11e550c261a501033e57bc7c7b1b5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/api.md @@ -0,0 +1,112 @@ +# Zaraz Web API + +Client-side JavaScript API for tracking events, setting properties, and managing consent. + +## zaraz.track() + +```javascript +zaraz.track('button_click'); +zaraz.track('purchase', { value: 99.99, currency: 'USD', item_id: '12345' }); +zaraz.track('pageview', { page_path: '/products', page_title: 'Products' }); // SPA +``` + +**Params:** `eventName` (string), `properties` (object, optional). Fire-and-forget. + +## zaraz.set() + +```javascript +zaraz.set('userId', 'user_12345'); +zaraz.set({ email: '[email protected]', plan: 'premium', country: 'US' }); +``` + +Properties persist for page session. Use for user identification and segmentation. + +## zaraz.ecommerce() + +```javascript +zaraz.ecommerce('Product Viewed', { product_id: 'SKU123', name: 'Widget', price: 49.99 }); +zaraz.ecommerce('Product Added', { product_id: 'SKU123', quantity: 2, price: 49.99 }); +zaraz.ecommerce('Order Completed', { + order_id: 'ORD-789', total: 149.98, currency: 'USD', + products: [{ product_id: 'SKU123', quantity: 2, price: 49.99 }] +}); +``` + +**Events:** `Product Viewed`, `Product Added`, `Product Removed`, `Cart Viewed`, `Checkout Started`, `Order Completed` + +Tools auto-map to GA4, Facebook CAPI, etc. + +## System Properties (Triggers) + +``` +{{system.page.url}} {{system.page.title}} {{system.page.referrer}} +{{system.device.ip}} {{system.device.userAgent}} {{system.device.language}} +{{system.cookies.name}} {{client.__zarazTrack.userId}} +``` + +## zaraz.consent + +```javascript +// Check +const purposes = zaraz.consent.getAll(); // { analytics: true, marketing: false } + +// Set +zaraz.consent.modal = true; // Show modal +zaraz.consent.setAll({ analytics: true, marketing: false }); +zaraz.consent.set('marketing', true); + +// Listen +zaraz.consent.addEventListener('consentChanged', () => { + if (zaraz.consent.getAll().marketing) zaraz.track('marketing_consent_granted'); +}); +``` + +**Flow:** Configure purposes in dashboard → Map tools to purposes → Show modal/set programmatically → Tools fire when allowed + +## zaraz.debug + +```javascript +zaraz.debug = true; +zaraz.track('test_event'); +console.log(zaraz.tools); // View loaded tools +``` + +## Cookie Methods + +```javascript +zaraz.getCookie('session_id'); // Zaraz namespace +zaraz.readCookie('_ga'); // Any cookie +``` + +## Async Behavior + +All methods fire-and-forget. Events batched and sent asynchronously: + +```javascript +zaraz.track('event1'); +zaraz.set('prop', 'value'); +zaraz.track('event2'); // All batched +``` + +## TypeScript Types + +```typescript +interface Zaraz { + track(event: string, properties?: Record): void; + set(key: string, value: unknown): void; + set(properties: Record): void; + ecommerce(event: string, properties: Record): void; + consent: { + getAll(): Record; + setAll(purposes: Record): void; + set(purpose: string, value: boolean): void; + addEventListener(event: 'consentChanged', callback: () => void): void; + modal: boolean; + }; + debug: boolean; + tools?: string[]; + getCookie(name: string): string | undefined; + readCookie(name: string): string | undefined; +} +declare global { interface Window { zaraz: Zaraz; } } +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/configuration.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..e2e534ce66ec646f62edd15b5abd59100a87e240 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/configuration.md @@ -0,0 +1,90 @@ +# Zaraz Configuration + +## Dashboard Setup + +1. Domain → Zaraz → Start setup +2. Add tool (e.g., Google Analytics 4) +3. Enter credentials (GA4: `G-XXXXXXXXXX`) +4. Configure triggers +5. Save and Publish + +## Triggers + +| Type | When | Use Case | +|------|------|----------| +| Pageview | Page load | Track page views | +| Click | Element clicked | Button tracking | +| Form Submission | Form submitted | Lead capture | +| History Change | URL changes (SPA) | React/Vue routing | +| Variable Match | Custom condition | Conditional firing | + +### History Change (SPA) + +``` +Type: History Change +Event: pageview +``` + +Fires on `pushState`, `replaceState`, hash changes. **No manual tracking needed.** + +### Click Trigger + +``` +Type: Click +CSS Selector: .buy-button +Event: purchase_intent +Properties: + button_text: {{system.clickElement.text}} +``` + +## Tool Configuration + +**GA4:** +``` +Measurement ID: G-XXXXXXXXXX +Events: page_view, purchase, user_engagement +``` + +**Facebook Pixel:** +``` +Pixel ID: 1234567890123456 +Events: PageView, Purchase, AddToCart +``` + +**Google Ads:** +``` +Conversion ID: AW-XXXXXXXXX +Conversion Label: YYYYYYYYYY +``` + +## Consent Management + +1. Settings → Consent → Create purposes (analytics, marketing) +2. Map tools to purposes +3. Set behavior: "Do not load until consent granted" + +**Programmatic consent:** +```javascript +zaraz.consent.setAll({ analytics: true, marketing: true }); +``` + +## Privacy Features + +| Feature | Default | +|---------|---------| +| IP Anonymization | Enabled | +| Cookie Control | Via consent purposes | +| GDPR/CCPA | Consent modal | + +## Testing + +1. **Preview Mode** - test without publishing +2. **Debug Mode** - `zaraz.debug = true` +3. **Network tab** - filter "zaraz" + +## Limits + +| Resource | Limit | +|----------|-------| +| Event properties | 100KB | +| Consent purposes | 20 | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/gotchas.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/gotchas.md new file mode 100644 index 0000000000000000000000000000000000000000..eaa6b4917ab5c77bcfd0494598e887030390537e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/gotchas.md @@ -0,0 +1,81 @@ +# Zaraz Gotchas + +## Events Not Firing + +**Check:** +1. Tool enabled in dashboard (green dot) +2. Trigger conditions met +3. Consent granted for tool's purpose +4. Tool credentials correct (GA4: `G-XXXXXXXXXX`, FB: numeric only) + +**Debug:** +```javascript +zaraz.debug = true; +console.log('Tools:', zaraz.tools); +console.log('Consent:', zaraz.consent.getAll()); +``` + +## Consent Issues + +**Modal not showing:** +```javascript +// Clear consent cookie +document.cookie = 'zaraz-consent=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; +location.reload(); +``` + +**Tools firing before consent:** Map tool to consent purpose with "Do not load until consent granted". + +## SPA Tracking + +**Route changes not tracked:** +1. Configure History Change trigger in dashboard +2. Hash routing (`#/path`) requires manual tracking: +```javascript +window.addEventListener('hashchange', () => { + zaraz.track('pageview', { page_path: location.pathname + location.hash }); +}); +``` + +**React fix:** +```javascript +const location = useLocation(); +useEffect(() => { + zaraz.track('pageview', { page_path: location.pathname }); +}, [location]); // Include dependency +``` + +## Performance + +**Slow page load:** +- Audit tool count (50+ degrades performance) +- Disable blocking triggers unless required +- Reduce event payload size (<100KB) + +## Tool-Specific Issues + +| Tool | Issue | Fix | +|------|-------|-----| +| GA4 | Events not in real-time | Wait 5-10 min, use DebugView | +| Facebook | Invalid Pixel ID | Use numeric only (no `fbpx_` prefix) | +| Google Ads | Conversions not attributed | Include `send_to: 'AW-XXX/LABEL'` | + +## Data Layer + +- Properties persist per page only - set on each page load +- Nested access: `{{client.__zarazTrack.user.plan}}` + +## Limits + +| Resource | Limit | +|----------|-------| +| Request size | 100KB | +| Consent purposes | 20 | +| API rate | 1000 req/sec | + +## When NOT to Use Zaraz + +- Server-to-server tracking (use Workers) +- Real-time bidirectional communication +- Binary data transmission +- Authentication flows diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..c5ef967eddb2e6685b543830244e3eea55f58397 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/cloudflare/references/zaraz/patterns.md @@ -0,0 +1,74 @@ +# Zaraz Patterns + +## SPA Tracking + +**History Change Trigger (Recommended):** Configure in dashboard - no code needed, Zaraz auto-detects route changes. + +**Manual tracking (React/Vue/Next.js):** +```javascript +// On route change +zaraz.track('pageview', { page_path: pathname, page_title: document.title }); +``` + +## User Identification + +```javascript +// Login +zaraz.set({ userId: user.id, email: user.email, plan: user.plan }); +zaraz.track('login', { method: 'oauth' }); + +// Logout - set to null (cannot clear) +zaraz.set('userId', null); +``` + +## E-commerce Funnel + +| Event | Method | +|-------|--------| +| View | `zaraz.ecommerce('Product Viewed', { product_id, name, price })` | +| Add to cart | `zaraz.ecommerce('Product Added', { product_id, quantity })` | +| Checkout | `zaraz.ecommerce('Checkout Started', { cart_id, products: [...] })` | +| Purchase | `zaraz.ecommerce('Order Completed', { order_id, total, products })` | + +## A/B Testing + +```javascript +zaraz.set('experiment_checkout', variant); +zaraz.track('experiment_viewed', { experiment_id: 'checkout', variant }); +// On conversion +zaraz.track('experiment_conversion', { experiment_id, variant, value }); +``` + +## Worker Integration + +**Context Enricher** - Modify context before tools execute: +```typescript +export default { + async fetch(request, env) { + const body = await request.json(); + body.system.userRegion = request.cf?.region; + return Response.json(body); + } +}; +``` +Configure: Zaraz > Settings > Context Enrichers + +**Worker Variables** - Compute dynamic values server-side, use as `{{worker.variable_name}}`. + +## GTM Migration + +| GTM | Zaraz | +|-----|-------| +| `dataLayer.push({event: 'purchase'})` | `zaraz.ecommerce('Order Completed', {...})` | +| `{{Page URL}}` | `{{system.page.url}}` | +| `{{Page Title}}` | `{{system.page.title}}` | +| Page View trigger | Pageview trigger | +| Click trigger | Click (selector: `*`) | + +## Best Practices + +1. Use dashboard triggers over inline code +2. Enable History Change for SPAs (no manual code) +3. Debug with `zaraz.debug = true` +4. Implement consent early (GDPR/CCPA) +5. Use Context Enrichers for sensitive/server data diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b595f1c2182f3b7d6f944d7ba0ac59667fba78aa --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/SKILL.md @@ -0,0 +1,186 @@ +--- +name: durable-objects +description: Create and review Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC methods, SQLite storage, alarms, WebSockets, or reviewing DO code for best practices. Covers Workers integration, wrangler config, and testing with Vitest. Biases towards retrieval from Cloudflare docs over pre-trained knowledge. +--- + +# Durable Objects + +Build stateful, coordinated applications on Cloudflare's edge using Durable Objects. + +## Retrieval Sources + +Your knowledge of Durable Objects APIs and configuration may be outdated. **Prefer retrieval over pre-training** for any Durable Objects task. + +| Resource | URL | +|----------|-----| +| Docs | https://developers.cloudflare.com/durable-objects/ | +| API Reference | https://developers.cloudflare.com/durable-objects/api/ | +| Best Practices | https://developers.cloudflare.com/durable-objects/best-practices/ | +| Examples | https://developers.cloudflare.com/durable-objects/examples/ | + +Fetch the relevant doc page when implementing features. + +## When to Use + +- Creating new Durable Object classes for stateful coordination +- Implementing RPC methods, alarms, or WebSocket handlers +- Reviewing existing DO code for best practices +- Configuring wrangler.jsonc/toml for DO bindings and migrations +- Writing tests with `@cloudflare/vitest-pool-workers` +- Designing sharding strategies and parent-child relationships + +## Reference Documentation + +- `./references/rules.md` - Core rules, storage, concurrency, RPC, alarms +- `./references/testing.md` - Vitest setup, unit/integration tests, alarm testing +- `./references/workers.md` - Workers handlers, types, wrangler config, observability + +Search: `blockConcurrencyWhile`, `idFromName`, `getByName`, `setAlarm`, `sql.exec` + +## Core Principles + +### Use Durable Objects For + +| Need | Example | +|------|---------| +| Coordination | Chat rooms, multiplayer games, collaborative docs | +| Strong consistency | Inventory, booking systems, turn-based games | +| Per-entity storage | Multi-tenant SaaS, per-user data | +| Persistent connections | WebSockets, real-time notifications | +| Scheduled work per entity | Subscription renewals, game timeouts | + +### Do NOT Use For + +- Stateless request handling (use plain Workers) +- Maximum global distribution needs +- High fan-out independent requests + +## Quick Reference + +### Wrangler Configuration + +```jsonc +// wrangler.jsonc +{ + "durable_objects": { + "bindings": [{ "name": "MY_DO", "class_name": "MyDurableObject" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDurableObject"] }] +} +``` + +### Basic Durable Object Pattern + +```typescript +import { DurableObject } from "cloudflare:workers"; + +export interface Env { + MY_DO: DurableObjectNamespace; +} + +export class MyDurableObject extends DurableObject { + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + ctx.blockConcurrencyWhile(async () => { + this.ctx.storage.sql.exec(` + CREATE TABLE IF NOT EXISTS items ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + data TEXT NOT NULL + ) + `); + }); + } + + async addItem(data: string): Promise { + const result = this.ctx.storage.sql.exec<{ id: number }>( + "INSERT INTO items (data) VALUES (?) RETURNING id", + data + ); + return result.one().id; + } +} + +export default { + async fetch(request: Request, env: Env): Promise { + const stub = env.MY_DO.getByName("my-instance"); + const id = await stub.addItem("hello"); + return Response.json({ id }); + }, +}; +``` + +## Critical Rules + +1. **Model around coordination atoms** - One DO per chat room/game/user, not one global DO +2. **Use `getByName()` for deterministic routing** - Same input = same DO instance +3. **Use SQLite storage** - Configure `new_sqlite_classes` in migrations +4. **Initialize in constructor** - Use `blockConcurrencyWhile()` for schema setup only +5. **Use RPC methods** - Not fetch() handler (compatibility date >= 2024-04-03) +6. **Persist first, cache second** - Always write to storage before updating in-memory state +7. **One alarm per DO** - `setAlarm()` replaces any existing alarm + +## Anti-Patterns (NEVER) + +- Single global DO handling all requests (bottleneck) +- Using `blockConcurrencyWhile()` on every request (kills throughput) +- Storing critical state only in memory (lost on eviction/crash) +- Using `await` between related storage writes (breaks atomicity) +- Holding `blockConcurrencyWhile()` across `fetch()` or external I/O + +## Stub Creation + +```typescript +// Deterministic - preferred for most cases +const stub = env.MY_DO.getByName("room-123"); + +// From existing ID string +const id = env.MY_DO.idFromString(storedIdString); +const stub = env.MY_DO.get(id); + +// New unique ID - store mapping externally +const id = env.MY_DO.newUniqueId(); +const stub = env.MY_DO.get(id); +``` + +## Storage Operations + +```typescript +// SQL (synchronous, recommended) +this.ctx.storage.sql.exec("INSERT INTO t (c) VALUES (?)", value); +const rows = this.ctx.storage.sql.exec("SELECT * FROM t").toArray(); + +// KV (async) +await this.ctx.storage.put("key", value); +const val = await this.ctx.storage.get("key"); +``` + +## Alarms + +```typescript +// Schedule (replaces existing) +await this.ctx.storage.setAlarm(Date.now() + 60_000); + +// Handler +async alarm(): Promise { + // Process scheduled work + // Optionally reschedule: await this.ctx.storage.setAlarm(...) +} + +// Cancel +await this.ctx.storage.deleteAlarm(); +``` + +## Testing Quick Start + +```typescript +import { env } from "cloudflare:test"; +import { describe, it, expect } from "vitest"; + +describe("MyDO", () => { + it("should work", async () => { + const stub = env.MY_DO.getByName("test"); + const result = await stub.addItem("test"); + expect(result).toBe(1); + }); +}); +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d0cf1c8b80d69a3a4c0213ac9c4ee3fbb471c484 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Durable Objects" + short_description: "Build stateful coordination on Cloudflare Workers" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/rules.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/rules.md new file mode 100644 index 0000000000000000000000000000000000000000..4ab2ea0965928b37be8f5deba3ebd8e625d2ada8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/rules.md @@ -0,0 +1,295 @@ +# Durable Objects Rules & Best Practices + +## Design & Sharding + +### Model Around Coordination Atoms + +Create one DO per logical unit needing coordination: chat room, game session, document, user, tenant. + +```typescript +// ✅ Good: One DO per chat room +const stub = env.CHAT_ROOM.getByName(roomId); + +// ❌ Bad: Single global DO +const stub = env.CHAT_ROOM.getByName("global"); // Bottleneck! +``` + +### Parent-Child Relationships + +For hierarchical data, create separate child DOs. Parent tracks references, children handle own state. + +```typescript +// Parent: GameServer tracks match references +// Children: GameMatch handles individual match state +async createMatch(name: string): Promise { + const matchId = crypto.randomUUID(); + this.ctx.storage.sql.exec( + "INSERT INTO matches (id, name) VALUES (?, ?)", + matchId, name + ); + const child = this.env.GAME_MATCH.getByName(matchId); + await child.init(matchId, name); + return matchId; +} +``` + +### Location Hints + +Influence DO creation location for latency-sensitive apps: + +```typescript +const id = env.GAME.idFromName(gameId, { locationHint: "wnam" }); +``` + +Available hints: `wnam`, `enam`, `sam`, `weur`, `eeur`, `apac`, `oc`, `afr`, `me`. + +## Storage + +### SQLite (Recommended) + +Configure in wrangler: +```jsonc +{ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDO"] }] } +``` + +SQL API is synchronous: +```typescript +// Write +this.ctx.storage.sql.exec( + "INSERT INTO items (name, value) VALUES (?, ?)", + name, value +); + +// Read +const rows = this.ctx.storage.sql.exec<{ id: number; name: string }>( + "SELECT * FROM items WHERE name = ?", name +).toArray(); + +// Single row +const row = this.ctx.storage.sql.exec<{ count: number }>( + "SELECT COUNT(*) as count FROM items" +).one(); +``` + +### Migrations + +**Note:** `PRAGMA user_version` is **not supported** in Durable Objects SQLite storage. Use a `_sql_schema_migrations` table instead: + +```typescript +constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + ctx.blockConcurrencyWhile(async () => this.migrate()); +} + +private migrate() { + this.ctx.storage.sql.exec(` + CREATE TABLE IF NOT EXISTS _sql_schema_migrations ( + id INTEGER PRIMARY KEY, + applied_at TEXT NOT NULL DEFAULT (datetime('now')) + ) + `); + + const currentVersion = this.ctx.storage.sql + .exec<{ version: number }>("SELECT COALESCE(MAX(id), 0) as version FROM _sql_schema_migrations") + .one().version; + + if (currentVersion < 1) { + this.ctx.storage.sql.exec(` + CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, data TEXT); + CREATE INDEX IF NOT EXISTS idx_items_data ON items(data); + INSERT INTO _sql_schema_migrations (id) VALUES (1); + `); + } + if (currentVersion < 2) { + this.ctx.storage.sql.exec(` + ALTER TABLE items ADD COLUMN created_at INTEGER; + INSERT INTO _sql_schema_migrations (id) VALUES (2); + `); + } +} +``` + +For production apps, consider [`durable-utils`](https://github.com/lambrospetrou/durable-utils#sqlite-schema-migrations) — provides a `SQLSchemaMigrations` class that tracks executed migrations both in memory and in storage. Also see [`@cloudflare/actors` storage utilities](https://github.com/cloudflare/actors/blob/main/packages/storage/src/sql-schema-migrations.ts) — a reference implementation of the same pattern used by the Cloudflare Actors framework. + +### State Types + +| Type | Speed | Persistence | Use Case | +|------|-------|-------------|----------| +| Class properties | Fastest | Lost on eviction | Caching, active connections | +| SQLite storage | Fast | Durable | Primary data | +| External (R2, D1) | Variable | Durable, cross-DO | Large files, shared data | + +**Rule**: Always persist critical state to SQLite first, then update in-memory cache. + +## Concurrency + +### Input/Output Gates + +Storage operations automatically block other requests (input gates). Responses wait for writes (output gates). + +```typescript +async increment(): Promise { + // Safe: input gates block interleaving during storage ops + const val = (await this.ctx.storage.get("count")) ?? 0; + await this.ctx.storage.put("count", val + 1); + return val + 1; +} +``` + +### Write Coalescing + +Multiple writes without `await` between them are batched atomically: + +```typescript +// ✅ Good: All three writes commit atomically +this.ctx.storage.sql.exec("UPDATE accounts SET balance = balance - ? WHERE id = ?", amount, fromId); +this.ctx.storage.sql.exec("UPDATE accounts SET balance = balance + ? WHERE id = ?", amount, toId); +this.ctx.storage.sql.exec("INSERT INTO transfers (from_id, to_id, amount) VALUES (?, ?, ?)", fromId, toId, amount); + +// ❌ Bad: await breaks coalescing +await this.ctx.storage.put("key1", val1); +await this.ctx.storage.put("key2", val2); // Separate transaction! +``` + +### Race Conditions with External I/O + +`fetch()` and other non-storage I/O allows interleaving: + +```typescript +// ⚠️ Race condition possible +async processItem(id: string) { + const item = await this.ctx.storage.get(`item:${id}`); + if (item?.status === "pending") { + await fetch("https://api.example.com/process"); // Other requests can run here! + await this.ctx.storage.put(`item:${id}`, { status: "completed" }); + } +} +``` + +**Solution**: Use optimistic locking (version numbers) or `transaction()`. + +### blockConcurrencyWhile() + +Blocks ALL concurrency. Use sparingly - only for initialization: + +```typescript +// ✅ Good: One-time init +constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + ctx.blockConcurrencyWhile(async () => this.migrate()); +} + +// ❌ Bad: On every request (kills throughput) +async handleRequest() { + await this.ctx.blockConcurrencyWhile(async () => { + // ~5ms = max 200 req/sec + }); +} +``` + +**Never** hold across external I/O (fetch, R2, KV). + +## RPC Methods + +Use RPC (compatibility date >= 2024-04-03) instead of fetch() handler: + +```typescript +export class ChatRoom extends DurableObject { + async sendMessage(userId: string, content: string): Promise { + // Public methods are RPC endpoints + const result = this.ctx.storage.sql.exec<{ id: number }>( + "INSERT INTO messages (user_id, content) VALUES (?, ?) RETURNING id", + userId, content + ); + return { id: result.one().id, userId, content }; + } +} + +// Caller +const stub = env.CHAT_ROOM.getByName(roomId); +const msg = await stub.sendMessage("user-123", "Hello!"); // Typed! +``` + +### Explicit init() Method + +DOs don't know their own ID. Pass identity explicitly: + +```typescript +async init(entityId: string, metadata: Metadata): Promise { + await this.ctx.storage.put("entityId", entityId); + await this.ctx.storage.put("metadata", metadata); +} +``` + +## Alarms + +One alarm per DO. `setAlarm()` replaces existing. + +```typescript +// Schedule +await this.ctx.storage.setAlarm(Date.now() + 60_000); + +// Handler +async alarm(): Promise { + const tasks = this.ctx.storage.sql.exec( + "SELECT * FROM tasks WHERE due_at <= ?", Date.now() + ).toArray(); + + for (const task of tasks) { + await this.processTask(task); + } + + // Reschedule if more work + const next = this.ctx.storage.sql.exec<{ due_at: number }>( + "SELECT MIN(due_at) as due_at FROM tasks WHERE due_at > ?", Date.now() + ).one(); + if (next?.due_at) { + await this.ctx.storage.setAlarm(next.due_at); + } +} + +// Get/Delete +const alarm = await this.ctx.storage.getAlarm(); +await this.ctx.storage.deleteAlarm(); +``` + +**Retry**: Alarms auto-retry on failure. Use idempotent handlers. + +## WebSockets (Hibernation API) + +```typescript +async fetch(request: Request): Promise { + const pair = new WebSocketPair(); + this.ctx.acceptWebSocket(pair[1]); + return new Response(null, { status: 101, webSocket: pair[0] }); +} + +async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) { + const data = JSON.parse(message as string); + // Handle message + ws.send(JSON.stringify({ type: "ack" })); +} + +async webSocketClose(ws: WebSocket, code: number, reason: string) { + // Cleanup +} + +// Broadcast +getWebSockets().forEach(ws => ws.send(JSON.stringify(payload))); +``` + +## Error Handling + +```typescript +async safeOperation(): Promise { + try { + return await this.riskyOperation(); + } catch (error) { + console.error("Operation failed:", error); + // Log to external service if needed + throw error; // Re-throw to signal failure to caller + } +} +``` + +**Note**: Uncaught exceptions may terminate the DO instance. In-memory state is lost, but SQLite storage persists. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/testing.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/testing.md new file mode 100644 index 0000000000000000000000000000000000000000..c4fb7e9491173760117e2bce01431bb88fa7cdbe --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/testing.md @@ -0,0 +1,264 @@ +# Testing Durable Objects + +Use `@cloudflare/vitest-pool-workers` to test DOs inside the Workers runtime. + +## Setup + +### Install Dependencies + +```bash +npm i -D vitest@~3.2.0 @cloudflare/vitest-pool-workers +``` + +### vitest.config.ts + +```typescript +import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; + +export default defineWorkersConfig({ + test: { + poolOptions: { + workers: { + wrangler: { configPath: "./wrangler.toml" }, + }, + }, + }, +}); +``` + +### TypeScript Config (test/tsconfig.json) + +```jsonc +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "moduleResolution": "bundler", + "types": ["@cloudflare/vitest-pool-workers"] + }, + "include": ["./**/*.ts", "../src/worker-configuration.d.ts"] +} +``` + +### Environment Types (env.d.ts) + +```typescript +declare module "cloudflare:test" { + interface ProvidedEnv extends Env {} +} +``` + +## Unit Tests (Direct DO Access) + +```typescript +import { env } from "cloudflare:test"; +import { describe, it, expect } from "vitest"; + +describe("Counter DO", () => { + it("should increment", async () => { + const stub = env.COUNTER.getByName("test-counter"); + + expect(await stub.increment()).toBe(1); + expect(await stub.increment()).toBe(2); + expect(await stub.getCount()).toBe(2); + }); + + it("isolates different instances", async () => { + const stub1 = env.COUNTER.getByName("counter-1"); + const stub2 = env.COUNTER.getByName("counter-2"); + + await stub1.increment(); + await stub1.increment(); + await stub2.increment(); + + expect(await stub1.getCount()).toBe(2); + expect(await stub2.getCount()).toBe(1); + }); +}); +``` + +## Integration Tests (HTTP via SELF) + +```typescript +import { SELF } from "cloudflare:test"; +import { describe, it, expect } from "vitest"; + +describe("Worker HTTP", () => { + it("should increment via POST", async () => { + const res = await SELF.fetch("http://example.com?id=test", { + method: "POST", + }); + + expect(res.status).toBe(200); + const data = await res.json<{ count: number }>(); + expect(data.count).toBe(1); + }); + + it("should get count via GET", async () => { + await SELF.fetch("http://example.com?id=get-test", { method: "POST" }); + await SELF.fetch("http://example.com?id=get-test", { method: "POST" }); + + const res = await SELF.fetch("http://example.com?id=get-test"); + const data = await res.json<{ count: number }>(); + expect(data.count).toBe(2); + }); +}); +``` + +## Direct Internal Access + +Use `runInDurableObject()` to access instance internals and storage: + +```typescript +import { env, runInDurableObject } from "cloudflare:test"; +import { describe, it, expect } from "vitest"; +import { Counter } from "../src"; + +describe("DO internals", () => { + it("can verify storage directly", async () => { + const stub = env.COUNTER.getByName("direct-test"); + await stub.increment(); + await stub.increment(); + + await runInDurableObject(stub, async (instance: Counter, state) => { + expect(instance).toBeInstanceOf(Counter); + + const result = state.storage.sql + .exec<{ value: number }>( + "SELECT value FROM counters WHERE name = ?", + "default" + ) + .one(); + expect(result.value).toBe(2); + }); + }); +}); +``` + +## List DO IDs + +```typescript +import { env, listDurableObjectIds } from "cloudflare:test"; +import { describe, it, expect } from "vitest"; + +describe("DO listing", () => { + it("can list all IDs in namespace", async () => { + const id1 = env.COUNTER.idFromName("list-1"); + const id2 = env.COUNTER.idFromName("list-2"); + + await env.COUNTER.get(id1).increment(); + await env.COUNTER.get(id2).increment(); + + const ids = await listDurableObjectIds(env.COUNTER); + expect(ids.length).toBe(2); + expect(ids.some(id => id.equals(id1))).toBe(true); + expect(ids.some(id => id.equals(id2))).toBe(true); + }); +}); +``` + +## Testing Alarms + +Use `runDurableObjectAlarm()` to trigger alarms immediately: + +```typescript +import { env, runInDurableObject, runDurableObjectAlarm } from "cloudflare:test"; +import { describe, it, expect } from "vitest"; + +describe("DO alarms", () => { + it("can trigger alarms immediately", async () => { + const stub = env.COUNTER.getByName("alarm-test"); + await stub.increment(); + await stub.increment(); + expect(await stub.getCount()).toBe(2); + + // Schedule alarm + await runInDurableObject(stub, async (instance, state) => { + await state.storage.setAlarm(Date.now() + 60_000); + }); + + // Execute immediately without waiting + const ran = await runDurableObjectAlarm(stub); + expect(ran).toBe(true); + + // Verify alarm handler ran (if it resets counter) + expect(await stub.getCount()).toBe(0); + + // No alarm scheduled now + const ranAgain = await runDurableObjectAlarm(stub); + expect(ranAgain).toBe(false); + }); +}); +``` + +Example alarm handler: +```typescript +async alarm(): Promise { + this.ctx.storage.sql.exec("DELETE FROM counters"); +} +``` + +## Test Isolation + +Each test gets isolated storage automatically. DOs from one test don't affect others: + +```typescript +describe("Isolation", () => { + it("first test creates DO", async () => { + const stub = env.COUNTER.getByName("isolated"); + await stub.increment(); + expect(await stub.getCount()).toBe(1); + }); + + it("second test has fresh state", async () => { + const ids = await listDurableObjectIds(env.COUNTER); + expect(ids.length).toBe(0); // Previous test's DO is gone + + const stub = env.COUNTER.getByName("isolated"); + expect(await stub.getCount()).toBe(0); // Fresh instance + }); +}); +``` + +## SQLite Storage Testing + +```typescript +describe("SQLite", () => { + it("can verify SQL storage", async () => { + const stub = env.COUNTER.getByName("sqlite-test"); + await stub.increment("page-views"); + await stub.increment("page-views"); + await stub.increment("api-calls"); + + await runInDurableObject(stub, async (instance, state) => { + const rows = state.storage.sql + .exec<{ name: string; value: number }>( + "SELECT name, value FROM counters ORDER BY name" + ) + .toArray(); + + expect(rows).toEqual([ + { name: "api-calls", value: 1 }, + { name: "page-views", value: 2 }, + ]); + + expect(state.storage.sql.databaseSize).toBeGreaterThan(0); + }); + }); +}); +``` + +## Running Tests + +```bash +npx vitest # Watch mode +npx vitest run # Single run +``` + +package.json: +```json +{ + "scripts": { + "test": "vitest" + } +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/workers.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/workers.md new file mode 100644 index 0000000000000000000000000000000000000000..bd115a5954e402c75de17058e8ab2bc0ae4d4a4f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/durable-objects/references/workers.md @@ -0,0 +1,346 @@ +# Cloudflare Workers Best Practices + +High-level guidance for Workers that invoke Durable Objects. + +## Wrangler Configuration + +### wrangler.jsonc (Recommended) + +```jsonc +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "my-worker", + "main": "src/index.ts", + "compatibility_date": "2024-12-01", + "compatibility_flags": ["nodejs_compat"], + + "durable_objects": { + "bindings": [ + { "name": "CHAT_ROOM", "class_name": "ChatRoom" }, + { "name": "USER_SESSION", "class_name": "UserSession" } + ] + }, + + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["ChatRoom", "UserSession"] } + ], + + // Environment variables + "vars": { + "ENVIRONMENT": "production" + }, + + // KV namespaces + "kv_namespaces": [ + { "binding": "CONFIG", "id": "abc123" } + ], + + // R2 buckets + "r2_buckets": [ + { "binding": "UPLOADS", "bucket_name": "my-uploads" } + ], + + // D1 databases + "d1_databases": [ + { "binding": "DB", "database_id": "xyz789" } + ] +} +``` + +### wrangler.toml (Alternative) + +```toml +name = "my-worker" +main = "src/index.ts" +compatibility_date = "2024-12-01" +compatibility_flags = ["nodejs_compat"] + +[[durable_objects.bindings]] +name = "CHAT_ROOM" +class_name = "ChatRoom" + +[[migrations]] +tag = "v1" +new_sqlite_classes = ["ChatRoom"] + +[vars] +ENVIRONMENT = "production" +``` + +## TypeScript Types + +### Environment Interface + +```typescript +// src/types.ts +import { ChatRoom } from "./durable-objects/chat-room"; +import { UserSession } from "./durable-objects/user-session"; + +export interface Env { + // Durable Objects + CHAT_ROOM: DurableObjectNamespace; + USER_SESSION: DurableObjectNamespace; + + // KV + CONFIG: KVNamespace; + + // R2 + UPLOADS: R2Bucket; + + // D1 + DB: D1Database; + + // Environment variables + ENVIRONMENT: string; + API_KEY: string; // From secrets +} +``` + +### Export Durable Object Classes + +```typescript +// src/index.ts +export { ChatRoom } from "./durable-objects/chat-room"; +export { UserSession } from "./durable-objects/user-session"; + +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + // Worker handler + }, +}; +``` + +## Worker Handler Pattern + +```typescript +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const url = new URL(request.url); + + try { + // Route to appropriate handler + if (url.pathname.startsWith("/api/rooms")) { + return handleRooms(request, env); + } + if (url.pathname.startsWith("/api/users")) { + return handleUsers(request, env); + } + + return new Response("Not Found", { status: 404 }); + } catch (error) { + console.error("Request failed:", error); + return new Response("Internal Server Error", { status: 500 }); + } + }, +}; + +async function handleRooms(request: Request, env: Env): Promise { + const url = new URL(request.url); + const roomId = url.searchParams.get("room"); + + if (!roomId) { + return Response.json({ error: "Missing room parameter" }, { status: 400 }); + } + + const stub = env.CHAT_ROOM.getByName(roomId); + + if (request.method === "POST") { + const body = await request.json<{ userId: string; message: string }>(); + const result = await stub.sendMessage(body.userId, body.message); + return Response.json(result); + } + + const messages = await stub.getMessages(); + return Response.json(messages); +} +``` + +## Request Validation + +```typescript +import { z } from "zod"; + +const SendMessageSchema = z.object({ + userId: z.string().min(1), + message: z.string().min(1).max(1000), +}); + +async function handleSendMessage(request: Request, env: Env): Promise { + const body = await request.json(); + const result = SendMessageSchema.safeParse(body); + + if (!result.success) { + return Response.json( + { error: "Validation failed", details: result.error.issues }, + { status: 400 } + ); + } + + const stub = env.CHAT_ROOM.getByName(result.data.userId); + const message = await stub.sendMessage(result.data.userId, result.data.message); + return Response.json(message); +} +``` + +## Observability & Logging + +### Structured Logging + +```typescript +function log(level: "info" | "warn" | "error", message: string, data?: Record) { + console.log(JSON.stringify({ + level, + message, + timestamp: new Date().toISOString(), + ...data, + })); +} + +// Usage +log("info", "Request received", { path: url.pathname, method: request.method }); +log("error", "DO call failed", { roomId, error: String(error) }); +``` + +### Request Tracing + +```typescript +async function handleRequest(request: Request, env: Env): Promise { + const requestId = crypto.randomUUID(); + const startTime = Date.now(); + + try { + const response = await processRequest(request, env); + + log("info", "Request completed", { + requestId, + duration: Date.now() - startTime, + status: response.status, + }); + + return response; + } catch (error) { + log("error", "Request failed", { + requestId, + duration: Date.now() - startTime, + error: String(error), + }); + throw error; + } +} +``` + +### Tail Workers (Production) + +For production logging, use Tail Workers to forward logs: + +```jsonc +// wrangler.jsonc +{ + "tail_consumers": [ + { "service": "log-collector" } + ] +} +``` + +## Error Handling + +### Graceful DO Errors + +```typescript +async function callDO(stub: DurableObjectStub, method: string): Promise { + try { + const result = await stub.getMessages(); + return Response.json(result); + } catch (error) { + if (error instanceof Error) { + // DO threw an error + log("error", "DO operation failed", { error: error.message }); + return Response.json( + { error: "Service temporarily unavailable" }, + { status: 503 } + ); + } + throw error; + } +} +``` + +### Timeout Handling + +```typescript +async function withTimeout(promise: Promise, ms: number): Promise { + const timeout = new Promise((_, reject) => + setTimeout(() => reject(new Error("Timeout")), ms) + ); + return Promise.race([promise, timeout]); +} + +// Usage +const result = await withTimeout(stub.processData(data), 5000); +``` + +## CORS Handling + +```typescript +function corsHeaders(): HeadersInit { + return { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type, Authorization", + }; +} + +export default { + async fetch(request: Request, env: Env): Promise { + if (request.method === "OPTIONS") { + return new Response(null, { headers: corsHeaders() }); + } + + const response = await handleRequest(request, env); + + // Add CORS headers to response + const newHeaders = new Headers(response.headers); + Object.entries(corsHeaders()).forEach(([k, v]) => newHeaders.set(k, v)); + + return new Response(response.body, { + status: response.status, + headers: newHeaders, + }); + }, +}; +``` + +## Secrets Management + +Set secrets via wrangler CLI (not in config files): + +```bash +wrangler secret put API_KEY +wrangler secret put DATABASE_URL +``` + +Access in code: +```typescript +export default { + async fetch(request: Request, env: Env): Promise { + const apiKey = env.API_KEY; // From secret + // ... + }, +}; +``` + +## Development Commands + +```bash +# Local development +wrangler dev + +# Deploy +wrangler deploy + +# Tail logs +wrangler tail + +# List DOs +wrangler d1 execute DB --command "SELECT * FROM _cf_DO" +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..2e7e0c38772df151e186373dab43f09a5e9c18fc --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/SKILL.md @@ -0,0 +1,177 @@ +--- +name: sandbox-sdk +description: Build sandboxed applications for secure code execution. Load when building AI code execution, code interpreters, CI/CD systems, interactive dev environments, or executing untrusted code. Covers Sandbox SDK lifecycle, commands, files, code interpreter, and preview URLs. Biases towards retrieval from Cloudflare docs over pre-trained knowledge. +--- + +# Cloudflare Sandbox SDK + +Build secure, isolated code execution environments on Cloudflare Workers. + +## FIRST: Verify Installation + +```bash +npm install @cloudflare/sandbox +docker info # Must succeed - Docker required for local dev +``` + +## Retrieval Sources + +Your knowledge of the Sandbox SDK may be outdated. **Prefer retrieval over pre-training** for any Sandbox SDK task. + +| Resource | URL | +|----------|-----| +| Docs | https://developers.cloudflare.com/sandbox/ | +| API Reference | https://developers.cloudflare.com/sandbox/api/ | +| Examples | https://github.com/cloudflare/sandbox-sdk/tree/main/examples | +| Get Started | https://developers.cloudflare.com/sandbox/get-started/ | + +When implementing features, fetch the relevant doc page or example first. + +## Required Configuration + +**wrangler.jsonc** (exact - do not modify structure): + +```jsonc +{ + "containers": [{ + "class_name": "Sandbox", + "image": "./Dockerfile", + "instance_type": "lite", + "max_instances": 1 + }], + "durable_objects": { + "bindings": [{ "class_name": "Sandbox", "name": "Sandbox" }] + }, + "migrations": [{ "new_sqlite_classes": ["Sandbox"], "tag": "v1" }] +} +``` + +**Worker entry** - must re-export Sandbox class: + +```typescript +import { getSandbox } from '@cloudflare/sandbox'; +export { Sandbox } from '@cloudflare/sandbox'; // Required export +``` + +## Quick Reference + +| Task | Method | +|------|--------| +| Get sandbox | `getSandbox(env.Sandbox, 'user-123')` | +| Run command | `await sandbox.exec('python script.py')` | +| Run code (interpreter) | `await sandbox.runCode(code, { language: 'python' })` | +| Write file | `await sandbox.writeFile('/workspace/app.py', content)` | +| Read file | `await sandbox.readFile('/workspace/app.py')` | +| Create directory | `await sandbox.mkdir('/workspace/src', { recursive: true })` | +| List files | `await sandbox.listFiles('/workspace')` | +| Expose port | `await sandbox.exposePort(8080)` | +| Destroy | `await sandbox.destroy()` | + +## Core Patterns + +### Execute Commands + +```typescript +const sandbox = getSandbox(env.Sandbox, 'user-123'); +const result = await sandbox.exec('python --version'); +// result: { stdout, stderr, exitCode, success } +``` + +### Code Interpreter (Recommended for AI) + +Use `runCode()` for executing LLM-generated code with rich outputs: + +```typescript +const ctx = await sandbox.createCodeContext({ language: 'python' }); + +await sandbox.runCode('import pandas as pd; data = [1,2,3]', { context: ctx }); +const result = await sandbox.runCode('sum(data)', { context: ctx }); +// result.results[0].text = "6" +``` + +**Languages**: `python`, `javascript`, `typescript` + +State persists within context. Create explicit contexts for production. + +### File Operations + +```typescript +await sandbox.mkdir('/workspace/project', { recursive: true }); +await sandbox.writeFile('/workspace/project/main.py', code); +const file = await sandbox.readFile('/workspace/project/main.py'); +const files = await sandbox.listFiles('/workspace/project'); +``` + +## When to Use What + +| Need | Use | Why | +|------|-----|-----| +| Shell commands, scripts | `exec()` | Direct control, streaming | +| LLM-generated code | `runCode()` | Rich outputs, state persistence | +| Build/test pipelines | `exec()` | Exit codes, stderr capture | +| Data analysis | `runCode()` | Charts, tables, pandas | + +## Extending the Dockerfile + +Base image (`docker.io/cloudflare/sandbox:0.7.0`) includes Python 3.11, Node.js 20, and common tools. + +Add dependencies by extending the Dockerfile: + +```dockerfile +FROM docker.io/cloudflare/sandbox:0.7.0 + +# Python packages +RUN pip install requests beautifulsoup4 + +# Node packages (global) +RUN npm install -g typescript + +# System packages +RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/* + +EXPOSE 8080 # Required for local dev port exposure +``` + +Keep images lean - affects cold start time. + +## Preview URLs (Port Exposure) + +Expose HTTP services running in sandboxes: + +```typescript +const { url } = await sandbox.exposePort(8080); +// Returns preview URL for the service +``` + +**Production requirement**: Preview URLs need a custom domain with wildcard DNS (`*.yourdomain.com`). The `.workers.dev` domain does not support preview URL subdomains. + +See: https://developers.cloudflare.com/sandbox/guides/expose-services/ + +## OpenAI Agents SDK Integration + +The SDK provides helpers for OpenAI Agents at `@cloudflare/sandbox/openai`: + +```typescript +import { Shell, Editor } from '@cloudflare/sandbox/openai'; +``` + +See `examples/openai-agents` for complete integration pattern. + +## Sandbox Lifecycle + +- `getSandbox()` returns immediately - container starts lazily on first operation +- Containers sleep after 10 minutes of inactivity (configurable via `sleepAfter`) +- Use `destroy()` to immediately free resources +- Same `sandboxId` always returns same sandbox instance + +## Anti-Patterns + +- **Don't use internal clients** (`CommandClient`, `FileClient`) - use `sandbox.*` methods +- **Don't skip the Sandbox export** - Worker won't deploy without `export { Sandbox }` +- **Don't hardcode sandbox IDs for multi-user** - use user/session identifiers +- **Don't forget cleanup** - call `destroy()` for temporary sandboxes + +## Detailed References + +- **[references/api-quick-ref.md](references/api-quick-ref.md)** - Full API with options and return types +- **[references/examples.md](references/examples.md)** - Example index with use cases diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c1b829d63342a215ccac48a06ea42f3e03cddf4d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Sandbox SDK" + short_description: "Build secure sandboxed code execution" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/references/api-quick-ref.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/references/api-quick-ref.md new file mode 100644 index 0000000000000000000000000000000000000000..1b4b386a7b448302c322c670dcd941daac68b4cf --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/references/api-quick-ref.md @@ -0,0 +1,113 @@ +# Sandbox SDK API Reference + +Detailed API for `@cloudflare/sandbox`. For full docs: https://developers.cloudflare.com/sandbox/api/ + +## Lifecycle + +```typescript +getSandbox(binding: DurableObjectNamespace, sandboxId: string, options?: SandboxOptions): Sandbox + +interface SandboxOptions { + sleepAfter?: string; // Duration before auto-sleep (default: "10m") + keepAlive?: boolean; // Prevent auto-sleep (default: false) + normalizeId?: boolean; // Lowercase IDs for preview URLs (default: false) +} + +await sandbox.destroy(): Promise // Immediately terminate and delete all state +``` + +## Commands + +```typescript +await sandbox.exec(command: string, options?: ExecOptions): Promise + +interface ExecOptions { + cwd?: string; // Working directory + env?: Record; // Environment variables + timeout?: number; // Timeout in ms (default: 60000) + stdin?: string; // Input to command +} + +interface ExecResult { + stdout: string; + stderr: string; + exitCode: number; + success: boolean; // exitCode === 0 +} +``` + +## Code Interpreter + +```typescript +await sandbox.createCodeContext(options?: CreateContextOptions): Promise + +interface CreateContextOptions { + language?: 'python' | 'javascript' | 'typescript'; // default: 'python' + cwd?: string; // Working directory (default: '/workspace') + envVars?: Record; + timeout?: number; // Request timeout in ms (default: 30000) +} + +await sandbox.runCode(code: string, options?: RunCodeOptions): Promise + +interface RunCodeOptions { + context?: CodeContext; // Reuse context for state persistence + language?: 'python' | 'javascript' | 'typescript'; + timeout?: number; // Execution timeout in ms (default: 60000) +} + +interface ExecutionResult { + code: string; + logs: { stdout: string[]; stderr: string[] }; + results: RichOutput[]; // text, html, png, json, etc. + error?: { name: string; value: string; traceback: string[] }; + executionCount: number; +} +``` + +## Files + +```typescript +await sandbox.writeFile(path: string, content: string | Uint8Array): Promise +await sandbox.readFile(path: string): Promise<{ content: string }> +await sandbox.mkdir(path: string, options?: { recursive?: boolean }): Promise +await sandbox.listFiles(path: string): Promise +await sandbox.deleteFile(path: string): Promise + +interface FileMetadata { + name: string; + path: string; + isDirectory: boolean; + size: number; + modifiedAt: string; +} +``` + +## Ports + +```typescript +await sandbox.exposePort(port: number): Promise<{ url: string; token: string }> +await sandbox.unexposePort(port: number): Promise +await sandbox.listPorts(): Promise +``` + +## Error Handling + +Errors include context about the operation: + +```typescript +try { + await sandbox.exec('invalid-command'); +} catch (error) { + // error.message includes command and sandbox context +} +``` + +For `runCode()`, check `result.error` instead of catching: + +```typescript +const result = await sandbox.runCode('1/0', { language: 'python' }); +if (result.error) { + console.error(result.error.name); // "ZeroDivisionError" +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/references/examples.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/references/examples.md new file mode 100644 index 0000000000000000000000000000000000000000..78d8edd713c0980a28cda59f3c13b301044def95 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/sandbox-sdk/references/examples.md @@ -0,0 +1,49 @@ +# Sandbox SDK Examples + +All examples: https://github.com/cloudflare/sandbox-sdk/tree/main/examples + +## Example Index + +| Example | Use Case | Key File | +|---------|----------|----------| +| `minimal` | Basic setup, exec, file ops | `src/index.ts` | +| `code-interpreter` | AI code execution with Workers AI | `src/index.ts` | +| `openai-agents` | OpenAI Agents SDK integration | `src/index.ts` | +| `opencode` | OpenCode agent integration | `src/index.ts` | +| `codex-app-server` | Codex app server integration | `src/index.ts` | +| `typescript-validator` | TypeScript compilation/validation | `src/index.ts` | +| `authentication` | Auth patterns for sandboxes | `src/index.ts` | + +## When to Use Which Example + +| Building | Start With | +|----------|------------| +| AI code execution | `code-interpreter` | +| Agent with shell + file editing | `openai-agents` | +| Basic command execution | `minimal` | +| Code validation service | `typescript-validator` | +| Multi-user sandboxes | `authentication` | + +## Common Patterns from Examples + +**Sandbox per user/session** (from `openai-agents`): +```typescript +const sandbox = getSandbox(env.Sandbox, `session-${sessionId}`); +``` + +**Code context reuse** (from `code-interpreter`): +```typescript +const pythonCtx = await sandbox.createCodeContext({ language: 'python' }); +const result = await sandbox.runCode(code, { context: pythonCtx }); +``` + +**Resource cleanup** (from `code-interpreter`): +```typescript +try { + // ... use sandbox +} finally { + await sandbox.destroy(); +} +``` + +Fetch the full example source when implementing similar patterns. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/web-perf/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/web-perf/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..9bc2e1d1f3ca5e91833f44e2855302b27e0c822d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/web-perf/SKILL.md @@ -0,0 +1,201 @@ +--- +name: web-perf +description: Analyzes web performance using Chrome DevTools MCP. Measures Core Web Vitals (FCP, LCP, TBT, CLS, Speed Index), identifies render-blocking resources, network dependency chains, layout shifts, caching issues, and accessibility gaps. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed. Biases towards retrieval from current documentation over pre-trained knowledge. +--- + +# Web Performance Audit + +Your knowledge of web performance metrics, thresholds, and tooling APIs may be outdated. **Prefer retrieval over pre-training** when citing specific numbers or recommendations. + +## Retrieval Sources + +| Source | How to retrieve | Use for | +|--------|----------------|---------| +| web.dev | `https://web.dev/articles/vitals` | Core Web Vitals thresholds, definitions | +| Chrome DevTools docs | `https://developer.chrome.com/docs/devtools/performance` | Tooling APIs, trace analysis | +| Lighthouse scoring | `https://developer.chrome.com/docs/lighthouse/performance/performance-scoring` | Score weights, metric thresholds | + +## FIRST: Verify MCP Tools Available + +**Run this before starting.** Try calling `navigate_page` or `performance_start_trace`. If unavailable, STOP—the chrome-devtools MCP server isn't configured. + +Ask the user to add this to their MCP config: + +```json +"chrome-devtools": { + "type": "local", + "command": ["npx", "-y", "chrome-devtools-mcp@latest"] +} +``` + +## Key Guidelines + +- **Be assertive**: Verify claims by checking network requests, DOM, or codebase—then state findings definitively. +- **Verify before recommending**: Confirm something is unused before suggesting removal. +- **Quantify impact**: Use estimated savings from insights. Don't prioritize changes with 0ms impact. +- **Skip non-issues**: If render-blocking resources have 0ms estimated impact, note but don't recommend action. +- **Be specific**: Say "compress hero.png (450KB) to WebP" not "optimize images". +- **Prioritize ruthlessly**: A site with 200ms LCP and 0 CLS is already excellent—say so. + +## Quick Reference + +| Task | Tool Call | +|------|-----------| +| Load page | `navigate_page(url: "...")` | +| Start trace | `performance_start_trace(autoStop: true, reload: true)` | +| Analyze insight | `performance_analyze_insight(insightSetId: "...", insightName: "...")` | +| List requests | `list_network_requests(resourceTypes: ["Script", "Stylesheet", ...])` | +| Request details | `get_network_request(reqid: )` | +| A11y snapshot | `take_snapshot(verbose: true)` | + +## Workflow + +Copy this checklist to track progress: + +``` +Audit Progress: +- [ ] Phase 1: Performance trace (navigate + record) +- [ ] Phase 2: Core Web Vitals analysis (includes CLS culprits) +- [ ] Phase 3: Network analysis +- [ ] Phase 4: Accessibility snapshot +- [ ] Phase 5: Codebase analysis (skip if third-party site) +``` + +### Phase 1: Performance Trace + +1. Navigate to the target URL: + ``` + navigate_page(url: "") + ``` + +2. Start a performance trace with reload to capture cold-load metrics: + ``` + performance_start_trace(autoStop: true, reload: true) + ``` + +3. Wait for trace completion, then retrieve results. + +**Troubleshooting:** +- If trace returns empty or fails, verify the page loaded correctly with `navigate_page` first +- If insight names don't match, inspect the trace response to list available insights + +### Phase 2: Core Web Vitals Analysis + +Use `performance_analyze_insight` to extract key metrics. + +**Note:** Insight names may vary across Chrome DevTools versions. If an insight name doesn't work, check the `insightSetId` from the trace response to discover available insights. + +Common insight names: + +| Metric | Insight Name | What to Look For | +|--------|--------------|------------------| +| LCP | `LCPBreakdown` | Time to largest contentful paint; breakdown of TTFB, resource load, render delay | +| CLS | `CLSCulprits` | Elements causing layout shifts (images without dimensions, injected content, font swaps) | +| Render Blocking | `RenderBlocking` | CSS/JS blocking first paint | +| Document Latency | `DocumentLatency` | Server response time issues | +| Network Dependencies | `NetworkRequestsDepGraph` | Request chains delaying critical resources | + +Example: +``` +performance_analyze_insight(insightSetId: "", insightName: "LCPBreakdown") +``` + +**Key thresholds (good/needs-improvement/poor):** +- TTFB: < 800ms / < 1.8s / > 1.8s +- FCP: < 1.8s / < 3s / > 3s +- LCP: < 2.5s / < 4s / > 4s +- INP: < 200ms / < 500ms / > 500ms +- TBT: < 200ms / < 600ms / > 600ms +- CLS: < 0.1 / < 0.25 / > 0.25 +- Speed Index: < 3.4s / < 5.8s / > 5.8s + +### Phase 3: Network Analysis + +List all network requests to identify optimization opportunities: +``` +list_network_requests(resourceTypes: ["Script", "Stylesheet", "Document", "Font", "Image"]) +``` + +**Look for:** + +1. **Render-blocking resources**: JS/CSS in `` without `async`/`defer`/`media` attributes +2. **Network chains**: Resources discovered late because they depend on other resources loading first (e.g., CSS imports, JS-loaded fonts) +3. **Missing preloads**: Critical resources (fonts, hero images, key scripts) not preloaded +4. **Caching issues**: Missing or weak `Cache-Control`, `ETag`, or `Last-Modified` headers +5. **Large payloads**: Uncompressed or oversized JS/CSS bundles +6. **Unused preconnects**: If flagged, verify by checking if ANY requests went to that origin. If zero requests, it's definitively unused—recommend removal. If requests exist but loaded late, the preconnect may still be valuable. + +For detailed request info: +``` +get_network_request(reqid: ) +``` + +### Phase 4: Accessibility Snapshot + +Take an accessibility tree snapshot: +``` +take_snapshot(verbose: true) +``` + +**Flag high-level gaps:** +- Missing or duplicate ARIA IDs +- Elements with poor contrast ratios (check against WCAG AA: 4.5:1 for normal text, 3:1 for large text) +- Focus traps or missing focus indicators +- Interactive elements without accessible names + +## Phase 5: Codebase Analysis + +**Skip if auditing a third-party site without codebase access.** + +Analyze the codebase to understand where improvements can be made. + +### Detect Framework & Bundler + +Search for configuration files to identify the stack: + +| Tool | Config Files | +|------|--------------| +| Webpack | `webpack.config.js`, `webpack.*.js` | +| Vite | `vite.config.js`, `vite.config.ts` | +| Rollup | `rollup.config.js`, `rollup.config.mjs` | +| esbuild | `esbuild.config.js`, build scripts with `esbuild` | +| Parcel | `.parcelrc`, `package.json` (parcel field) | +| Next.js | `next.config.js`, `next.config.mjs` | +| Nuxt | `nuxt.config.js`, `nuxt.config.ts` | +| SvelteKit | `svelte.config.js` | +| Astro | `astro.config.mjs` | + +Also check `package.json` for framework dependencies and build scripts. + +### Tree-Shaking & Dead Code + +- **Webpack**: Check for `mode: 'production'`, `sideEffects` in package.json, `usedExports` optimization +- **Vite/Rollup**: Tree-shaking enabled by default; check for `treeshake` options +- **Look for**: Barrel files (`index.js` re-exports), large utility libraries imported wholesale (lodash, moment) + +### Unused JS/CSS + +- Check for CSS-in-JS vs. static CSS extraction +- Look for PurgeCSS/UnCSS configuration (Tailwind's `content` config) +- Identify dynamic imports vs. eager loading + +### Polyfills + +- Check for `@babel/preset-env` targets and `useBuiltIns` setting +- Look for `core-js` imports (often oversized) +- Check `browserslist` config for overly broad targeting + +### Compression & Minification + +- Check for `terser`, `esbuild`, or `swc` minification +- Look for gzip/brotli compression in build output or server config +- Check for source maps in production builds (should be external or disabled) + +## Output Format + +Present findings as: + +1. **Core Web Vitals Summary** - Table with metric, value, and rating (good/needs-improvement/poor) +2. **Top Issues** - Prioritized list of problems with estimated impact (high/medium/low) +3. **Recommendations** - Specific, actionable fixes with code snippets or config changes +4. **Codebase Findings** - Framework/bundler detected, optimization opportunities (omit if no codebase access) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/web-perf/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/web-perf/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb632a6c1f5674f05caf03ba98325f36dae76b3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/web-perf/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Web Performance" + short_description: "Audit page performance with Chrome DevTools MCP" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..bebd018cdcae1771eacdee30cfb96af3ad3bd936 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/SKILL.md @@ -0,0 +1,127 @@ +--- +name: workers-best-practices +description: Reviews and authors Cloudflare Workers code against production best practices. Load when writing new Workers, reviewing Worker code, configuring wrangler.jsonc, or checking for common Workers anti-patterns (streaming, floating promises, global state, secrets, bindings, observability). Biases towards retrieval from Cloudflare docs over pre-trained knowledge. +--- + +Your knowledge of Cloudflare Workers APIs, types, and configuration may be outdated. **Prefer retrieval over pre-training** for any Workers code task — writing or reviewing. + +## Retrieval Sources + +Fetch the **latest** versions before writing or reviewing Workers code. Do not rely on baked-in knowledge for API signatures, config fields, or binding shapes. + +| Source | How to retrieve | Use for | +|--------|----------------|---------| +| Workers best practices | Fetch `https://developers.cloudflare.com/workers/best-practices/workers-best-practices/` | Canonical rules, patterns, anti-patterns | +| Workers types | See `references/review.md` for retrieval steps | API signatures, handler types, binding types | +| Wrangler config schema | `node_modules/wrangler/config-schema.json` | Config fields, binding shapes, allowed values | +| Cloudflare docs | Search tool or `https://developers.cloudflare.com/workers/` | API reference, compatibility dates/flags | + +## FIRST: Fetch Latest References + +Before reviewing or writing Workers code, retrieve the current best practices page and relevant type definitions. If the project's `node_modules` has an older version, **prefer the latest published version**. + +```bash +# Fetch latest workers types +mkdir -p /tmp/workers-types-latest && \ + npm pack @cloudflare/workers-types --pack-destination /tmp/workers-types-latest && \ + tar -xzf /tmp/workers-types-latest/cloudflare-workers-types-*.tgz -C /tmp/workers-types-latest +# Types at /tmp/workers-types-latest/package/index.d.ts +``` + +## Reference Documentation + +- `references/rules.md` — all best practice rules with code examples and anti-patterns +- `references/review.md` — type validation, config validation, binding access patterns, review process + +## Rules Quick Reference + +### Configuration + +| Rule | Summary | +|------|---------| +| Compatibility date | Set `compatibility_date` to today on new projects; update periodically on existing ones | +| nodejs_compat | Enable the `nodejs_compat` flag — many libraries depend on Node.js built-ins | +| wrangler types | Run `wrangler types` to generate `Env` — never hand-write binding interfaces | +| Secrets | Use `wrangler secret put`, never hardcode secrets in config or source | +| wrangler.jsonc | Use JSONC config for non-secret settings — newer features are JSON-only | + +### Request & Response Handling + +| Rule | Summary | +|------|---------| +| Streaming | Stream large/unknown payloads — never `await response.text()` on unbounded data | +| waitUntil | Use `ctx.waitUntil()` for post-response work; do not destructure `ctx` | + +### Architecture + +| Rule | Summary | +|------|---------| +| Bindings over REST | Use in-process bindings (KV, R2, D1, Queues) — not the Cloudflare REST API | +| Queues & Workflows | Move async/background work off the critical path | +| Service bindings | Use service bindings for Worker-to-Worker calls — not public HTTP | +| Hyperdrive | Always use Hyperdrive for external PostgreSQL/MySQL connections | + +### Observability + +| Rule | Summary | +|------|---------| +| Logs & Traces | Enable `observability` in config with `head_sampling_rate`; use structured JSON logging | + +### Code Patterns + +| Rule | Summary | +|------|---------| +| No global request state | Never store request-scoped data in module-level variables | +| Floating promises | Every Promise must be `await`ed, `return`ed, `void`ed, or passed to `ctx.waitUntil()` | + +### Security + +| Rule | Summary | +|------|---------| +| Web Crypto | Use `crypto.randomUUID()` / `crypto.getRandomValues()` — never `Math.random()` for security | +| No passThroughOnException | Use explicit try/catch with structured error responses | + +## Anti-Patterns to Flag + +| Anti-pattern | Why it matters | +|-------------|----------------| +| `await response.text()` on unbounded data | Memory exhaustion — 128 MB limit | +| Hardcoded secrets in source or config | Credential leak via version control | +| `Math.random()` for tokens/IDs | Predictable, not cryptographically secure | +| Bare `fetch()` without `await` or `waitUntil` | Floating promise — dropped result, swallowed error | +| Module-level mutable variables for request state | Cross-request data leaks, stale state, I/O errors | +| Cloudflare REST API from inside a Worker | Unnecessary network hop, auth overhead, added latency | +| `ctx.passThroughOnException()` as error handling | Hides bugs, makes debugging impossible | +| Hand-written `Env` interface | Drifts from actual wrangler config bindings | +| Direct string comparison for secret values | Timing side-channel — use `crypto.subtle.timingSafeEqual` | +| Destructuring `ctx` (`const { waitUntil } = ctx`) | Loses `this` binding — throws "Illegal invocation" at runtime | +| `any` on `Env` or handler params | Defeats type safety for all binding access | +| `as unknown as T` double-cast | Hides real type incompatibilities — fix the design | +| `implements` on platform base classes (instead of `extends`) | Legacy — loses `this.ctx`, `this.env`. Applies to DurableObject, WorkerEntrypoint, Workflow | +| `env.X` inside platform base class | Should be `this.env.X` in classes extending DurableObject, WorkerEntrypoint, etc. | + +## Review Workflow + +1. **Retrieve** — fetch latest best practices page, workers types, and wrangler schema +2. **Read full files** — not just diffs; context matters for binding access patterns +3. **Check types** — binding access, handler signatures, no `any`, no unsafe casts (see `references/review.md`) +4. **Check config** — compatibility_date, nodejs_compat, observability, secrets, binding-code consistency +5. **Check patterns** — streaming, floating promises, global state, serialization boundaries +6. **Check security** — crypto usage, secret handling, timing-safe comparisons, error handling +7. **Validate with tools** — `npx tsc --noEmit`, lint for `no-floating-promises` +8. **Reference rules** — see `references/rules.md` for each rule's correct pattern + +## Scope + +This skill covers Workers-specific best practices and code review. For related topics: + +- **Durable Objects**: load the `durable-objects` skill +- **Workflows**: see [Rules of Workflows](https://developers.cloudflare.com/workflows/build/rules-of-workflows/) +- **Wrangler CLI commands**: load the `wrangler` skill + +## Principles + +- **Be certain.** Retrieve before flagging. If unsure about an API, config field, or pattern, fetch the docs first. +- **Provide evidence.** Reference line numbers, tool output, or docs links. +- **Focus on what developers will copy.** Workers code in examples and docs gets pasted into production. +- **Correctness over completeness.** A concise example that works beats a comprehensive one with errors. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c5f663cbe59ff03612c84addce3ede543ad20cb --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Workers Best Practices" + short_description: "Write and review production-grade Workers code" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/references/review.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/references/review.md new file mode 100644 index 0000000000000000000000000000000000000000..24c70e02ea9d4c718ae276a9f796afe74fb6b33a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/references/review.md @@ -0,0 +1,174 @@ +# Code Review — Workers + +How to review Workers code for type correctness, API usage, config validity, and best practices. This is self-contained — do not assume access to other skills. + +## Retrieval + +Prefer retrieval over pre-training. Types, config schemas, and APIs change with compatibility dates and new bindings. + +### Workers types + +Fetch the latest `@cloudflare/workers-types` before reviewing. The project may have an older version installed. + +```bash +mkdir -p /tmp/workers-types-latest && \ + npm pack @cloudflare/workers-types --pack-destination /tmp/workers-types-latest && \ + tar -xzf /tmp/workers-types-latest/cloudflare-workers-types-*.tgz -C /tmp/workers-types-latest +# Types are at /tmp/workers-types-latest/package/index.d.ts +``` + +Search this file for the specific type, class, or interface under review. Do not guess type names. + +Alternative: `npx wrangler types` generates a typed `Env` interface from the local wrangler config. + +Fallback: read `node_modules/@cloudflare/workers-types/index.d.ts`. Note the installed version. + +### Wrangler config schema + +The authoritative schema is bundled with wrangler as `config-schema.json` (JSON Schema draft-07). + +```bash +# Read from local node_modules +cat node_modules/wrangler/config-schema.json +``` + +Do not guess field names or structures — look them up. + +### Cloudflare docs + +Use the Cloudflare docs search tool if available, or fetch from `https://developers.cloudflare.com/workers/`. The best practices page lives at `/workers/best-practices/workers-best-practices/`. + +--- + +## Type Validation + +### Env interface + +- Every binding must have a specific type. Flag `any`, `unknown`, `object`, or `Record` on bindings. +- Binding types that accept generic parameters (Durable Object namespaces, Queues, Service bindings for RPC) must include them. Read the type definition to confirm which types are generic. +- Binding names must match the wrangler config exactly. +- Prefer generated types from `wrangler types` over hand-written interfaces. + +### Handler and class signatures + +Verify against current type definitions — do not assume signatures are stable. + +- Correct import path (most Workers platform classes import from `"cloudflare:workers"`) +- Generic type parameter on base classes (e.g., `DurableObject`) +- Binding access pattern: `env.X` in module export handlers, `this.env.X` in classes extending platform base classes +- `ExecutionContext` as the third param in module export handlers (needed for `ctx.waitUntil()`) +- `fetch()` handlers must return `Promise` + +### Binding access — the most common error + +- **Module export handlers** (`fetch`, `scheduled`, `queue`, `email`): bindings via `env.X` parameter +- **Platform base classes** (`WorkerEntrypoint`, `DurableObject`, `Workflow`, `Agent`): bindings via `this.env.X` + +Flag `env.X` inside a class extending a platform base class. Flag `this.env.X` inside a module export handler. + +### Type integrity rules + +| Rule | Detail | +|------|--------| +| No `any` | Never on binding types, handler params, or API responses | +| No double-casting | `as unknown as T` hides real incompatibilities — fix the underlying design | +| Justify suppressions | `@ts-ignore`/`@ts-expect-error` must include a comment explaining why | +| Prefer `satisfies` | Use `satisfies ExportedHandler` over `as` — validates without widening | +| Validate, do not assert | Schema or type guard for untyped data (JSON, parsed bodies), not `as` | + +### Stale class patterns + +Old patterns survive in codebases long after APIs change. + +- **`extends` vs `implements`**: platform classes use `extends`, not `implements`. The `implements` pattern is legacy and loses `this.ctx`, `this.env`. +- **Import paths**: verify module specifiers match what types actually export. Common mistake: wrong path for `"cloudflare:workers"` vs `"cloudflare:workflows"`. +- **Renamed properties**: e.g., `this.state` to `this.ctx` in Durable Objects. Search types to confirm. +- **Constructor signatures**: base class constructors change. Verify expected parameters. + +--- + +## Config Validation + +### Required fields + +For executable examples, verify: `name`, `compatibility_date`, `main`. Check the schema for current required fields. + +### Config format + +- **JSONC** (`wrangler.jsonc`) — preferred for new projects +- **JSON** (`wrangler.json`) — valid but no comments +- **TOML** (`wrangler.toml`) — legacy; acceptable in existing content, flag in new projects + +### Binding-code consistency + +1. Every `env.X` reference in code has a corresponding binding declaration in config +2. Every binding in config is referenced in code (warn on unused) +3. Names match exactly (case-sensitive) +4. For Durable Objects: `class_name` matches the exported class name + +### Common config mistakes + +| Check | What to look for | +|-------|-----------------| +| Stale `compatibility_date` | Should be recent; use `$today` placeholder in docs | +| Missing DO migrations | Every new DO class needs a migration entry | +| Binding name mismatch | Config `binding`/`name` must match `env.X` in code | +| Secrets in config | Never in `vars` — use `wrangler secret put` | +| Wrong binding key | Verify top-level key name against the schema | +| Missing entrypoint | `main` required for executable Workers | + +--- + +## Anti-Patterns to Flag + +See the full anti-patterns table in `SKILL.md`. The type-specific ones to watch for during review: + +- **`any` on `Env` or handler params** — defeats type safety for all downstream binding access +- **`as unknown as T`** — hides real type incompatibilities; fix the underlying design +- **`@ts-ignore`/`@ts-expect-error` without explanation** — masks errors silently; require a justifying comment +- **`implements` instead of `extends` on platform base classes** — legacy pattern; loses `this.ctx`, `this.env` +- **`env.X` inside class body** — should be `this.env.X` in platform base classes +- **`this.env.X` in module export handler** — should be `env.X` parameter +- **Non-serializable values across boundaries** — `Response`, `Error` in step/queue compiles but fails at runtime + +--- + +## Serialization Boundaries + +Data crossing these boundaries must be structured-clone serializable: + +- **Queue messages**: body passed to `.send()` or `.sendBatch()` +- **Workflow step return values**: persisted to durable storage +- **DO storage**: values in `storage.put()` or SQL +- **`postMessage()`**: WebSocket messages + +Non-serializable types to flag: `Response`, `Request`, `Error`, functions, class instances with methods, `Map`/`Set`, `Symbol`. + +Valid: plain objects, arrays, strings, numbers, booleans, null, `ArrayBuffer`, `Date`. + +--- + +## Review Process + +1. **Retrieve** — fetch latest workers types, wrangler schema, and best practices page +2. **Read full files** — not just diffs; context matters for binding access patterns +3. **Categorize code** — determines what to check: + - **Illustrative** (concept demo, comments for most logic): verify correct API names and realistic signatures + - **Demonstrative** (functional snippet, would work in context): verify syntax, correct APIs, correct binding access + - **Executable** (standalone, runs without modification): verify compiles, runs, includes imports and config +4. **Check types** — binding access pattern, handler signatures, no `any`, no unsafe casts +5. **Check config** — compatibility_date, nodejs_compat, observability, secrets, binding-code consistency +6. **Check patterns** — streaming, floating promises, global state, serialization boundaries +7. **Check security** — crypto usage, secret handling, timing-safe comparisons, error handling +8. **Validate with tools** — `npx tsc --noEmit`, lint for `no-floating-promises` +9. **Assess risk** — HIGH (auth, crypto, bindings), MEDIUM (business logic, config), LOW (style, comments) + +### Output format + +``` +**[SEVERITY]** Brief description +`file.ts:42` — explanation with evidence +Suggested fix: `code` +``` + +Severity: **CRITICAL** (security, data loss, crash) | **HIGH** (type error, wrong API, broken config) | **MEDIUM** (missing validation, edge case) | **LOW** (style, minor improvement) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/references/rules.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/references/rules.md new file mode 100644 index 0000000000000000000000000000000000000000..2ac2df70f696ae585063b305adfe582b220f6011 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/workers-best-practices/references/rules.md @@ -0,0 +1,463 @@ +# Workers Best Practices — Rules + +Each rule has an imperative summary, what to check, the correct pattern, and an anti-pattern where applicable. Code examples are plain TypeScript — no MDX components. + +When a rule involves config fields or API signatures that may evolve, a **Retrieve** callout reminds you to check the latest docs or types before flagging. All doc paths are relative to `https://developers.cloudflare.com`. + +--- + +## Configuration + +### Keep compatibility_date current + +Set `compatibility_date` to today on new projects. Update periodically on existing ones to access new APIs and fixes. + +**Check**: `compatibility_date` exists. Flag if older than 6 months. + +```jsonc +// wrangler.jsonc +{ + "compatibility_date": "$today", // Replace with today's date (YYYY-MM-DD) + "compatibility_flags": ["nodejs_compat"] +} +``` + +**Retrieve**: current compatibility dates at `/workers/configuration/compatibility-dates/`. + +### Enable nodejs_compat + +The `nodejs_compat` flag enables Node.js built-in modules (`node:crypto`, `node:buffer`, `node:stream`). Many libraries require it. Missing this flag causes cryptic import errors at runtime. + +**Check**: `compatibility_flags` includes `"nodejs_compat"`. + +```jsonc +{ + "compatibility_flags": ["nodejs_compat"] +} +``` + +### Generate binding types with wrangler types + +Never hand-write the `Env` interface. Run `wrangler types` to generate it from the wrangler config. Re-run after adding or renaming any binding. + +**Check**: no manually defined `Env` or `interface Env` that duplicates wrangler config bindings. Look for `satisfies ExportedHandler` pattern on the default export. + +```ts +// Generated by wrangler types — always matches actual config +export default { + async fetch(request: Request, env: Env): Promise { + const value = await env.MY_KV.get("key"); + return new Response(value); + }, +} satisfies ExportedHandler; +``` + +Anti-pattern: +```ts +// Hand-written Env that drifts from actual bindings +interface Env { + MY_KV: KVNamespace; // What if the binding name changed? +} +``` + +### Store secrets with wrangler secret + +Secrets must never appear in wrangler config or source code. Use `wrangler secret put` and access via `env` at runtime. Non-secret config goes in `vars`. + +**Check**: no string literals that look like API keys, tokens, or credentials. Verify `.env` is in `.gitignore` for local dev. + +```jsonc +{ + "vars": { + "API_BASE_URL": "https://api.example.com" // Non-secret: OK in config + } + // Secrets set via: wrangler secret put API_KEY +} +``` + +Anti-pattern: +```jsonc +{ + "vars": { + "API_KEY": "sk-live-abc123..." // Secret in version control + } +} +``` + +### Use wrangler.jsonc for config + +Prefer `wrangler.jsonc` over `wrangler.toml`. Newer features are JSON-only. JSONC supports comments for documenting config decisions. + +**Check**: project uses `wrangler.jsonc` (or `wrangler.json`). Flag `wrangler.toml` in new projects. + +--- + +## Request & Response Handling + +### Stream request and response bodies + +Workers have a 128 MB memory limit. Buffering entire bodies with `await response.text()` or `await request.arrayBuffer()` crashes on large payloads. Stream data through using `TransformStream` or pass `response.body` directly. + +**Check**: any `await response.text()`, `await response.json()`, or `await response.arrayBuffer()` on data that could be large or unbounded. Small, bounded payloads (known-size JSON, config files) are fine to buffer. + +Correct — stream through: +```ts +async fetch(request: Request, env: Env): Promise { + const response = await fetch("https://api.example.com/large-dataset"); + return new Response(response.body, response); +} +``` + +Correct — concatenate multiple streams: +```ts +async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const urls = ["https://api.example.com/part-1", "https://api.example.com/part-2"]; + const { readable, writable } = new TransformStream(); + + // Track the pipeline promise — don't let it float + ctx.waitUntil((async () => { + for (const url of urls) { + const response = await fetch(url); + if (response.body) { + await response.body.pipeTo(writable, { preventClose: true }); + } + } + await writable.close(); + })()); + + return new Response(readable, { + headers: { "Content-Type": "application/octet-stream" }, + }); +} +``` + +Anti-pattern: +```ts +// Buffers entire body — crashes on large payloads +const response = await fetch("https://api.example.com/large-dataset"); +const text = await response.text(); +return new Response(text); +``` + +**Retrieve**: streaming APIs at `/workers/runtime-apis/streams/`. + +### Use waitUntil for work after the response + +`ctx.waitUntil()` performs background work (analytics, cache writes, webhooks) after the response is sent. Keeps response fast. 30-second time limit after response. + +**Check**: background work uses `ctx.waitUntil()`, not inline `await`. Do not destructure `ctx` — it loses the `this` binding and throws "Illegal invocation". + +```ts +async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const data = await processRequest(request); + + ctx.waitUntil(logToAnalytics(env, data)); + ctx.waitUntil(updateCache(env, data)); + + return Response.json(data); +} +``` + +Anti-pattern: +```ts +// Destructuring ctx loses the this binding +const { waitUntil } = ctx; // "Illegal invocation" at runtime +waitUntil(somePromise); +``` + +--- + +## Architecture + +### Use bindings for Cloudflare services, not REST APIs + +Bindings (KV, R2, D1, Queues, Workflows) are direct, in-process references — no network hop, no authentication, no extra latency. Using the Cloudflare REST API from a Worker wastes time and adds complexity. + +**Check**: no `fetch("https://api.cloudflare.com/client/v4/...")` calls for services available as bindings. + +```ts +// Binding — direct, zero-cost +const object = await env.MY_BUCKET.get("my-file"); +``` + +Anti-pattern: +```ts +// REST API from inside a Worker — unnecessary overhead +const response = await fetch( + "https://api.cloudflare.com/client/v4/accounts/.../r2/buckets/.../objects/my-file", + { headers: { Authorization: `Bearer ${env.CF_API_TOKEN}` } } +); +``` + +### Use Queues and Workflows for async and background work + +Long-running, retriable, or non-urgent tasks should not block a request. + +- **Queues**: decouple producer from consumer. Fan-out, buffering/batching, simple single-step background jobs. At-least-once delivery. +- **Workflows**: multi-step durable execution. Each step's return value is persisted; only failed steps retry. Can run for hours/days/weeks. +- **Both together**: Queue buffers high-throughput entry, consumer creates Workflow instances for complex processing. + +**Check**: long-running work (email sends, webhooks, multi-step processes) is offloaded to Queues or Workflows, not done inline in the fetch handler. + +```ts +async fetch(request: Request, env: Env): Promise { + const order = await request.json<{ id: string; type: string }>(); + + if (order.type === "simple") { + await env.ORDER_QUEUE.send({ orderId: order.id, action: "send-email" }); + } else { + await env.FULFILLMENT_WORKFLOW.create({ params: { orderId: order.id } }); + } + + return Response.json({ status: "accepted" }, { status: 202 }); +} +``` + +**Retrieve**: `/queues/` and `/workflows/` for current APIs. For Workflow-specific rules, see [Rules of Workflows](https://developers.cloudflare.com/workflows/build/rules-of-workflows/). + +### Use service bindings for Worker-to-Worker communication + +Service bindings are zero-cost, bypass the public internet, and support type-safe RPC. Do not call another Worker via its public URL. + +**Check**: Worker-to-Worker calls use `env.SERVICE_NAME.method()` (RPC) or `env.SERVICE_NAME.fetch()`, not `fetch("https://my-other-worker.example.com/...")`. + +```ts +import { WorkerEntrypoint } from "cloudflare:workers"; + +export class AuthService extends WorkerEntrypoint { + async verifyToken(token: string): Promise<{ userId: string; valid: boolean }> { + return { userId: "user-123", valid: true }; + } +} + +// Caller Worker +const auth = await env.AUTH_SERVICE.verifyToken(token); +``` + +**Retrieve**: verify `WorkerEntrypoint` import path and signature against latest `@cloudflare/workers-types`. + +### Use Hyperdrive for external database connections + +Hyperdrive maintains a regional connection pool, eliminating per-request TCP + TLS + auth cost (often 300-500ms). Create a new `Client` per request — Hyperdrive manages the underlying pool. Requires `nodejs_compat`. + +**Check**: any `new Client()` or database connection that uses a direct connection string instead of `env.HYPERDRIVE.connectionString`. + +```jsonc +{ + "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "" }] +} +``` + +```ts +import { Client } from "pg"; + +async fetch(request: Request, env: Env): Promise { + const client = new Client({ connectionString: env.HYPERDRIVE.connectionString }); + await client.connect(); + const result = await client.query("SELECT id, name FROM users LIMIT 10"); + return Response.json(result.rows); +} +``` + +**Retrieve**: `/hyperdrive/` for current configuration and supported databases. + +--- + +## Observability + +### Enable Workers Logs and Traces + +Enable `observability` in wrangler config before deploying to production. Use `head_sampling_rate` to control volume and cost. Use structured JSON logging — `console.log(JSON.stringify({...}))` — so logs are searchable. Use `console.error` for errors (appears at error severity in the dashboard). + +**Check**: `observability.enabled` is `true` in config. Logging uses structured JSON, not string concatenation. + +```jsonc +{ + "observability": { + "enabled": true, + "logs": { "head_sampling_rate": 1 }, + "traces": { "enabled": true, "head_sampling_rate": 0.01 } + } +} +``` + +```ts +// Structured JSON — searchable and filterable +console.log(JSON.stringify({ message: "incoming request", method: request.method, path: url.pathname })); + +// Error severity +console.error(JSON.stringify({ message: "request failed", error: e instanceof Error ? e.message : String(e) })); +``` + +Anti-pattern: +```ts +// Unstructured string logs — hard to query +console.log("Got a request to " + url.pathname); +``` + +**Retrieve**: `/workers/observability/logs/workers-logs/` and `/workers/observability/traces/` for current config options. + +--- + +## Code Patterns + +### Do not store request-scoped state in global scope + +Workers reuse isolates across requests. Module-level mutable variables cause cross-request data leaks, stale state, and "Cannot perform I/O on behalf of a different request" errors. + +**Check**: no mutable `let`/`var` at module scope that gets assigned inside a handler. Pass state through function arguments. + +```ts +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const userId = request.headers.get("X-User-Id"); + const result = await handleRequest(userId, env); + return Response.json(result); + }, +} satisfies ExportedHandler; +``` + +Anti-pattern: +```ts +// Module-level mutable state — leaks between requests +let currentUser: string | null = null; + +export default { + async fetch(request: Request, env: Env): Promise { + currentUser = request.headers.get("X-User-Id"); // Visible to next request + // ... + }, +}; +``` + +### Always await or waitUntil Promises + +A Promise that is not `await`ed, `return`ed, or passed to `ctx.waitUntil()` is a floating promise. Causes: dropped results, swallowed errors, unfinished work. The runtime may terminate the isolate before it completes. + +**Check**: every `fetch()`, `env.*.put()`, `env.*.send()`, and any other async call is handled. Enable `no-floating-promises` lint rule. + +```bash +# ESLint +npx eslint --rule '{"@typescript-eslint/no-floating-promises": "error"}' src/ + +# oxlint +npx oxlint --deny typescript/no-floating-promises src/ +``` + +```ts +// Correct: await when you need the result +const response = await fetch("https://api.example.com/process", { method: "POST", body: JSON.stringify(data) }); + +// Correct: waitUntil when you don't need the result before responding +ctx.waitUntil(fetch("https://api.example.com/webhook", { method: "POST", body: JSON.stringify(data) })); +``` + +Anti-pattern: +```ts +// Floating promise — result dropped, error swallowed +fetch("https://api.example.com/webhook", { method: "POST", body: JSON.stringify(data) }); +``` + +### Be aware of platform limits + +Workers have a 10ms CPU time limit (Bundled) or 30s (Standard/Unbound). Heavy synchronous work — tight loops, large JSON parsing, compute-intensive crypto — can hit the CPU limit and terminate the request. + +**Check**: compute-heavy operations that run synchronously. Consider breaking work into smaller chunks, offloading to Queues/Workflows, or using WebAssembly for CPU-intensive tasks. + +**Retrieve**: current limits at `/workers/platform/limits/`. + +--- + +## Security + +### Use Web Crypto for secure token generation + +Use `crypto.randomUUID()` for unique IDs and `crypto.getRandomValues()` for random bytes. `Math.random()` is not cryptographically secure. + +For comparing secrets (API keys, HMAC signatures), use `crypto.subtle.timingSafeEqual()`. Hash both values to a fixed size first — do not short-circuit on length mismatch (leaks length via timing). + +**Check**: no `Math.random()` for security-sensitive values. Secret comparisons use `timingSafeEqual` with fixed-size hashing. + +```ts +// Secure random UUID +const sessionId = crypto.randomUUID(); + +// Secure random bytes +const tokenBytes = new Uint8Array(32); +crypto.getRandomValues(tokenBytes); +const token = Array.from(tokenBytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +``` + +```ts +// Constant-time comparison — hash first to avoid length leak +async function verifyToken(provided: string, expected: string): Promise { + const encoder = new TextEncoder(); + const [providedHash, expectedHash] = await Promise.all([ + crypto.subtle.digest("SHA-256", encoder.encode(provided)), + crypto.subtle.digest("SHA-256", encoder.encode(expected)), + ]); + return crypto.subtle.timingSafeEqual(providedHash, expectedHash); +} +``` + +Anti-pattern: +```ts +// Predictable — not cryptographically secure +const token = Math.random().toString(36).substring(2); + +// Timing side-channel — leaks information about the expected value +return provided === expected; +``` + +**Retrieve**: `/workers/runtime-apis/web-crypto/` for current API surface. + +### Explicit error handling over passThroughOnException + +`passThroughOnException()` is a fail-open mechanism that sends requests to the origin when the Worker throws. It hides bugs and makes debugging difficult. Use explicit try/catch with structured error responses. + +**Check**: no `ctx.passThroughOnException()` calls. Error handling uses try/catch with structured JSON error responses and `console.error`. + +```ts +async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + try { + const result = await handleRequest(request, env); + return Response.json(result); + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + console.error(JSON.stringify({ message: "unhandled error", error: message, path: new URL(request.url).pathname })); + return Response.json({ error: "Internal server error" }, { status: 500 }); + } +} +``` + +--- + +## Development & Testing + +### Test with @cloudflare/vitest-pool-workers + +Runs tests inside the Workers runtime with real bindings. Catches issues that Node.js-based tests miss. + +**Known pitfall**: the Vitest pool auto-injects `nodejs_compat`, so tests pass even if your wrangler config is missing the flag. Always confirm your `wrangler.jsonc` includes `nodejs_compat` if your code depends on Node.js built-ins. + +**Check**: test setup uses `@cloudflare/vitest-pool-workers`. Tests cover nullable returns (e.g., KV `.get()` returning `null`). + +```ts +import { describe, it, expect } from "vitest"; +import { env } from "cloudflare:test"; + +describe("KV operations", () => { + it("should store and retrieve a value", async () => { + await env.MY_KV.put("key", "value"); + const result = await env.MY_KV.get("key"); + expect(result).toBe("value"); + }); + + it("should return null for missing keys", async () => { + const result = await env.MY_KV.get("nonexistent"); + expect(result).toBeNull(); + }); +}); +``` + +**Retrieve**: `/workers/testing/vitest-integration/` for current setup and configuration. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/LICENSE.txt b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..13e25df86ce06eb6488e6a6bc5c5847f5dedc352 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/LICENSE.txt @@ -0,0 +1,201 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf of + any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don\'t include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..41564a021862eb1efe28e18140a42daaa75163ab --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/SKILL.md @@ -0,0 +1,897 @@ +--- +name: wrangler +description: Cloudflare Workers CLI for deploying, developing, and managing Workers, KV, R2, D1, Vectorize, Hyperdrive, Workers AI, Containers, Queues, Workflows, Pipelines, and Secrets Store. Load before running wrangler commands to ensure correct syntax and best practices. Biases towards retrieval from Cloudflare docs over pre-trained knowledge. +--- + +# Wrangler CLI + +Your knowledge of Wrangler CLI flags, config fields, and subcommands may be outdated. **Prefer retrieval over pre-training** for any Wrangler task. + +## Retrieval Sources + +Fetch the **latest** information before writing or reviewing Wrangler commands and config. Do not rely on baked-in knowledge for CLI flags, config fields, or binding shapes. + +| Source | How to retrieve | Use for | +|--------|----------------|---------| +| Wrangler docs | `https://developers.cloudflare.com/workers/wrangler/` | CLI commands, flags, config reference | +| Wrangler config schema | `node_modules/wrangler/config-schema.json` | Config fields, binding shapes, allowed values | +| Cloudflare docs | Search tool or `https://developers.cloudflare.com/workers/` | API reference, compatibility dates/flags | + +## FIRST: Verify Wrangler Installation + +```bash +wrangler --version # Requires v4.x+ +``` + +If not installed: +```bash +npm install -D wrangler@latest +``` + +## Key Guidelines + +- **Use `wrangler.jsonc`**: Prefer JSON config over TOML. Newer features are JSON-only. +- **Set `compatibility_date`**: Use a recent date (within 30 days). Check https://developers.cloudflare.com/workers/configuration/compatibility-dates/ +- **Generate types after config changes**: Run `wrangler types` to update TypeScript bindings. +- **Local dev defaults to local storage**: Bindings use local simulation unless `remote: true`. +- **Validate config before deploy**: Run `wrangler check` to catch errors early. +- **Use environments for staging/prod**: Define `env.staging` and `env.production` in config. + +## Quick Start: New Worker + +```bash +# Initialize new project +npx wrangler init my-worker + +# Or with a framework +npx create-cloudflare@latest my-app +``` + +## Quick Reference: Core Commands + +| Task | Command | +|------|---------| +| Start local dev server | `wrangler dev` | +| Deploy to Cloudflare | `wrangler deploy` | +| Deploy dry run | `wrangler deploy --dry-run` | +| Generate TypeScript types | `wrangler types` | +| Validate configuration | `wrangler check` | +| View live logs | `wrangler tail` | +| Delete Worker | `wrangler delete` | +| Auth status | `wrangler whoami` | + +--- + +## Configuration (wrangler.jsonc) + +### Minimal Config + +```jsonc +{ + "$schema": "./node_modules/wrangler/config-schema.json", + "name": "my-worker", + "main": "src/index.ts", + "compatibility_date": "2026-03-18" +} +``` + +### Full Config with Bindings + +```jsonc +{ + "$schema": "./node_modules/wrangler/config-schema.json", + "name": "my-worker", + "main": "src/index.ts", + "compatibility_date": "2026-03-18", + "compatibility_flags": ["nodejs_compat_v2"], + + // Environment variables + "vars": { + "ENVIRONMENT": "production" + }, + + // KV Namespace + "kv_namespaces": [ + { "binding": "KV", "id": "" } + ], + + // R2 Bucket + "r2_buckets": [ + { "binding": "BUCKET", "bucket_name": "my-bucket" } + ], + + // D1 Database + "d1_databases": [ + { "binding": "DB", "database_name": "my-db", "database_id": "" } + ], + + // Workers AI (always remote) + "ai": { "binding": "AI" }, + + // Vectorize + "vectorize": [ + { "binding": "VECTOR_INDEX", "index_name": "my-index" } + ], + + // Hyperdrive + "hyperdrive": [ + { "binding": "HYPERDRIVE", "id": "" } + ], + + // Durable Objects + "durable_objects": { + "bindings": [ + { "name": "COUNTER", "class_name": "Counter" } + ] + }, + + // Cron triggers + "triggers": { + "crons": ["0 * * * *"] + }, + + // Environments + "env": { + "staging": { + "name": "my-worker-staging", + "vars": { "ENVIRONMENT": "staging" } + } + } +} +``` + +### Generate Types from Config + +```bash +# Generate worker-configuration.d.ts +wrangler types + +# Custom output path +wrangler types ./src/env.d.ts + +# Check types are up to date (CI) +wrangler types --check +``` + +--- + +## Local Development + +### Start Dev Server + +```bash +# Local mode (default) - uses local storage simulation +wrangler dev + +# With specific environment +wrangler dev --env staging + +# Force local-only (disable remote bindings) +wrangler dev --local + +# Remote mode - runs on Cloudflare edge (legacy) +wrangler dev --remote + +# Custom port +wrangler dev --port 8787 + +# Live reload for HTML changes +wrangler dev --live-reload + +# Test scheduled/cron handlers +wrangler dev --test-scheduled +# Then visit: http://localhost:8787/__scheduled +``` + +### Remote Bindings for Local Dev + +Use `remote: true` in binding config to connect to real resources while running locally: + +```jsonc +{ + "r2_buckets": [ + { "binding": "BUCKET", "bucket_name": "my-bucket", "remote": true } + ], + "ai": { "binding": "AI", "remote": true }, + "vectorize": [ + { "binding": "INDEX", "index_name": "my-index", "remote": true } + ] +} +``` + +**Recommended remote bindings**: AI (required), Vectorize, Browser Rendering, mTLS, Images. + +### Local Secrets + +Create `.dev.vars` for local development secrets: + +``` +API_KEY=local-dev-key +DATABASE_URL=postgres://localhost:5432/dev +``` + +--- + +## Deployment + +### Deploy Worker + +```bash +# Deploy to production +wrangler deploy + +# Deploy specific environment +wrangler deploy --env staging + +# Dry run (validate without deploying) +wrangler deploy --dry-run + +# Keep dashboard-set variables +wrangler deploy --keep-vars + +# Minify code +wrangler deploy --minify +``` + +### Manage Secrets + +```bash +# Set secret interactively +wrangler secret put API_KEY + +# Set from stdin +echo "secret-value" | wrangler secret put API_KEY + +# List secrets +wrangler secret list + +# Delete secret +wrangler secret delete API_KEY + +# Bulk secrets from JSON file +wrangler secret bulk secrets.json +``` + +### Versions and Rollback + +```bash +# List recent versions +wrangler versions list + +# View specific version +wrangler versions view + +# Rollback to previous version +wrangler rollback + +# Rollback to specific version +wrangler rollback +``` + +--- + +## KV (Key-Value Store) + +### Manage Namespaces + +```bash +# Create namespace +wrangler kv namespace create MY_KV + +# List namespaces +wrangler kv namespace list + +# Delete namespace +wrangler kv namespace delete --namespace-id +``` + +### Manage Keys + +```bash +# Put value +wrangler kv key put --namespace-id "key" "value" + +# Put with expiration (seconds) +wrangler kv key put --namespace-id "key" "value" --expiration-ttl 3600 + +# Get value +wrangler kv key get --namespace-id "key" + +# List keys +wrangler kv key list --namespace-id + +# Delete key +wrangler kv key delete --namespace-id "key" + +# Bulk put from JSON +wrangler kv bulk put --namespace-id data.json +``` + +### Config Binding + +```jsonc +{ + "kv_namespaces": [ + { "binding": "CACHE", "id": "" } + ] +} +``` + +--- + +## R2 (Object Storage) + +### Manage Buckets + +```bash +# Create bucket +wrangler r2 bucket create my-bucket + +# Create with location hint +wrangler r2 bucket create my-bucket --location wnam + +# List buckets +wrangler r2 bucket list + +# Get bucket info +wrangler r2 bucket info my-bucket + +# Delete bucket +wrangler r2 bucket delete my-bucket +``` + +### Manage Objects + +```bash +# Upload object +wrangler r2 object put my-bucket/path/file.txt --file ./local-file.txt + +# Download object +wrangler r2 object get my-bucket/path/file.txt + +# Delete object +wrangler r2 object delete my-bucket/path/file.txt +``` + +### Config Binding + +```jsonc +{ + "r2_buckets": [ + { "binding": "ASSETS", "bucket_name": "my-bucket" } + ] +} +``` + +--- + +## D1 (SQL Database) + +### Manage Databases + +```bash +# Create database +wrangler d1 create my-database + +# Create with location +wrangler d1 create my-database --location wnam + +# List databases +wrangler d1 list + +# Get database info +wrangler d1 info my-database + +# Delete database +wrangler d1 delete my-database +``` + +### Execute SQL + +```bash +# Execute SQL command (remote) +wrangler d1 execute my-database --remote --command "SELECT * FROM users" + +# Execute SQL file (remote) +wrangler d1 execute my-database --remote --file ./schema.sql + +# Execute locally +wrangler d1 execute my-database --local --command "SELECT * FROM users" +``` + +### Migrations + +```bash +# Create migration +wrangler d1 migrations create my-database create_users_table + +# List pending migrations +wrangler d1 migrations list my-database --local + +# Apply migrations locally +wrangler d1 migrations apply my-database --local + +# Apply migrations to remote +wrangler d1 migrations apply my-database --remote +``` + +### Export/Backup + +```bash +# Export schema and data +wrangler d1 export my-database --remote --output backup.sql + +# Export schema only +wrangler d1 export my-database --remote --output schema.sql --no-data +``` + +### Config Binding + +```jsonc +{ + "d1_databases": [ + { + "binding": "DB", + "database_name": "my-database", + "database_id": "", + "migrations_dir": "./migrations" + } + ] +} +``` + +--- + +## Vectorize (Vector Database) + +### Manage Indexes + +```bash +# Create index with dimensions +wrangler vectorize create my-index --dimensions 768 --metric cosine + +# Create with preset (auto-configures dimensions/metric) +wrangler vectorize create my-index --preset @cf/baai/bge-base-en-v1.5 + +# List indexes +wrangler vectorize list + +# Get index info +wrangler vectorize get my-index + +# Delete index +wrangler vectorize delete my-index +``` + +### Manage Vectors + +```bash +# Insert vectors from NDJSON file +wrangler vectorize insert my-index --file vectors.ndjson + +# Query vectors +wrangler vectorize query my-index --vector "[0.1, 0.2, ...]" --top-k 10 +``` + +### Config Binding + +```jsonc +{ + "vectorize": [ + { "binding": "SEARCH_INDEX", "index_name": "my-index" } + ] +} +``` + +--- + +## Hyperdrive (Database Accelerator) + +### Manage Configs + +```bash +# Create config +wrangler hyperdrive create my-hyperdrive \ + --connection-string "postgres://user:pass@host:5432/database" + +# List configs +wrangler hyperdrive list + +# Get config details +wrangler hyperdrive get + +# Update config +wrangler hyperdrive update --origin-password "new-password" + +# Delete config +wrangler hyperdrive delete +``` + +### Config Binding + +```jsonc +{ + "compatibility_flags": ["nodejs_compat_v2"], + "hyperdrive": [ + { "binding": "HYPERDRIVE", "id": "" } + ] +} +``` + +--- + +## Workers AI + +### List Models + +```bash +# List available models +wrangler ai models + +# List finetunes +wrangler ai finetune list +``` + +### Config Binding + +```jsonc +{ + "ai": { "binding": "AI" } +} +``` + +**Note**: Workers AI always runs remotely and incurs usage charges even in local dev. + +--- + +## Queues + +### Manage Queues + +```bash +# Create queue +wrangler queues create my-queue + +# List queues +wrangler queues list + +# Delete queue +wrangler queues delete my-queue + +# Add consumer to queue +wrangler queues consumer add my-queue my-worker + +# Remove consumer +wrangler queues consumer remove my-queue my-worker +``` + +### Config Binding + +```jsonc +{ + "queues": { + "producers": [ + { "binding": "MY_QUEUE", "queue": "my-queue" } + ], + "consumers": [ + { + "queue": "my-queue", + "max_batch_size": 10, + "max_batch_timeout": 30 + } + ] + } +} +``` + +--- + +## Containers + +### Build and Push Images + +```bash +# Build container image +wrangler containers build -t my-app:latest . + +# Build and push in one command +wrangler containers build -t my-app:latest . --push + +# Push existing image to Cloudflare registry +wrangler containers push my-app:latest +``` + +### Manage Containers + +```bash +# List containers +wrangler containers list + +# Get container info +wrangler containers info + +# Delete container +wrangler containers delete +``` + +### Manage Images + +```bash +# List images in registry +wrangler containers images list + +# Delete image +wrangler containers images delete my-app:latest +``` + +### Manage External Registries + +```bash +# List configured registries +wrangler containers registries list + +# Configure external registry (e.g., ECR) +wrangler containers registries configure \ + --public-credential + +# Delete registry configuration +wrangler containers registries delete +``` + +--- + +## Workflows + +### Manage Workflows + +```bash +# List workflows +wrangler workflows list + +# Describe workflow +wrangler workflows describe my-workflow + +# Trigger workflow instance +wrangler workflows trigger my-workflow + +# Trigger with parameters +wrangler workflows trigger my-workflow --params '{"key": "value"}' + +# Delete workflow +wrangler workflows delete my-workflow +``` + +### Manage Workflow Instances + +```bash +# List instances +wrangler workflows instances list my-workflow + +# Describe instance +wrangler workflows instances describe my-workflow + +# Terminate instance +wrangler workflows instances terminate my-workflow +``` + +### Config Binding + +```jsonc +{ + "workflows": [ + { + "binding": "MY_WORKFLOW", + "name": "my-workflow", + "class_name": "MyWorkflow" + } + ] +} +``` + +--- + +## Pipelines + +### Manage Pipelines + +```bash +# Create pipeline +wrangler pipelines create my-pipeline --r2 my-bucket + +# List pipelines +wrangler pipelines list + +# Show pipeline details +wrangler pipelines show my-pipeline + +# Update pipeline +wrangler pipelines update my-pipeline --batch-max-mb 100 + +# Delete pipeline +wrangler pipelines delete my-pipeline +``` + +### Config Binding + +```jsonc +{ + "pipelines": [ + { "binding": "MY_PIPELINE", "pipeline": "my-pipeline" } + ] +} +``` + +--- + +## Secrets Store + +### Manage Stores + +```bash +# Create store +wrangler secrets-store store create my-store + +# List stores +wrangler secrets-store store list + +# Delete store +wrangler secrets-store store delete +``` + +### Manage Secrets in Store + +```bash +# Add secret to store +wrangler secrets-store secret put my-secret + +# List secrets in store +wrangler secrets-store secret list + +# Get secret +wrangler secrets-store secret get my-secret + +# Delete secret from store +wrangler secrets-store secret delete my-secret +``` + +### Config Binding + +```jsonc +{ + "secrets_store_secrets": [ + { + "binding": "MY_SECRET", + "store_id": "", + "secret_name": "my-secret" + } + ] +} +``` + +--- + +## Pages (Frontend Deployment) + +```bash +# Create Pages project +wrangler pages project create my-site + +# Deploy directory to Pages +wrangler pages deploy ./dist + +# Deploy with specific branch +wrangler pages deploy ./dist --branch main + +# List deployments +wrangler pages deployment list --project-name my-site +``` + +--- + +## Observability + +### Tail Logs + +```bash +# Stream live logs +wrangler tail + +# Tail specific Worker +wrangler tail my-worker + +# Filter by status +wrangler tail --status error + +# Filter by search term +wrangler tail --search "error" + +# JSON output +wrangler tail --format json +``` + +### Config Logging + +```jsonc +{ + "observability": { + "enabled": true, + "head_sampling_rate": 1 + } +} +``` + +--- + +## Testing + +### Local Testing with Vitest + +```bash +npm install -D @cloudflare/vitest-pool-workers vitest +``` + +`vitest.config.ts`: +```typescript +import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; + +export default defineWorkersConfig({ + test: { + poolOptions: { + workers: { + wrangler: { configPath: "./wrangler.jsonc" }, + }, + }, + }, +}); +``` + +### Test Scheduled Events + +```bash +# Enable in dev +wrangler dev --test-scheduled + +# Trigger via HTTP +curl http://localhost:8787/__scheduled +``` + +--- + +## Troubleshooting + +### Common Issues + +| Issue | Solution | +|-------|----------| +| `command not found: wrangler` | Install: `npm install -D wrangler` | +| Auth errors | Run `wrangler login` | +| Config validation errors | Run `wrangler check` | +| Type errors after config change | Run `wrangler types` | +| Local storage not persisting | Check `.wrangler/state` directory | +| Binding undefined in Worker | Verify binding name matches config exactly | + +### Debug Commands + +```bash +# Check auth status +wrangler whoami + +# Validate config +wrangler check + +# View config schema +wrangler docs configuration +``` + +--- + +## Best Practices + +1. **Version control `wrangler.jsonc`**: Treat as source of truth for Worker config. +2. **Use automatic provisioning**: Omit resource IDs for auto-creation on deploy. +3. **Run `wrangler types` in CI**: Add to build step to catch binding mismatches. +4. **Use environments**: Separate staging/production with `env.staging`, `env.production`. +5. **Set `compatibility_date`**: Update quarterly to get new runtime features. +6. **Use `.dev.vars` for local secrets**: Never commit secrets to config. +7. **Test locally first**: `wrangler dev` with local bindings before deploying. +8. **Use `--dry-run` before major deploys**: Validate changes without deployment. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8532697e5c8ef1452d08db2da0a0cc3b98970f6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/agents/openai.yaml @@ -0,0 +1,6 @@ +interface: + display_name: "Wrangler" + short_description: "Use the Cloudflare Workers CLI safely" + icon_small: "./assets/cloudflare-small.svg" + icon_large: "./assets/cloudflare.png" + default_prompt: "Use Wrangler to set up, review, or fix this Cloudflare Worker config and deployment flow without guessing CLI flags." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/assets/cloudflare-small.svg b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/assets/cloudflare-small.svg new file mode 100644 index 0000000000000000000000000000000000000000..7feedbc2b37ff9f28f81d30aff52e605090bee86 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/wrangler/assets/cloudflare-small.svg @@ -0,0 +1,3 @@ + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..d1093a10047acf2fd80ecc03d71d20d45f0bcaf1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/.codex-plugin/plugin.json @@ -0,0 +1,43 @@ +{ + "name": "hugging-face", + "version": "1.0.3", + "description": "Inspect models, datasets, Spaces, and research", + "author": { + "name": "Hugging Face", + "url": "https://huggingface.co" + }, + "homepage": "https://huggingface.co", + "repository": "https://github.com/openai/plugins", + "license": "MIT", + "keywords": [ + "hugging-face", + "models", + "datasets", + "spaces", + "machine-learning" + ], + "skills": "./skills/", + "apps": "./.app.json", + "interface": { + "displayName": "Hugging Face", + "shortDescription": "Inspect models, datasets, Spaces, and research", + "longDescription": "Connect to the Hugging Face Hub to explore Models and Datasets, access SDK Documentation and more. Manage Machine Learning Jobs and connect to thousands of AI applications via Spaces.", + "developerName": "Hugging Face", + "category": "Developer Tools", + "capabilities": [ + "Interactive", + "Read", + "Write" + ], + "websiteURL": "https://huggingface.co", + "privacyPolicyURL": "https://huggingface.co/privacy", + "termsOfServiceURL": "https://huggingface.co/terms-of-service", + "defaultPrompt": [ + "Generate a realistic farm using FLUX.1" + ], + "brandColor": "#FFD21E", + "screenshots": [], + "composerIcon": "./assets/logo.png", + "logo": "./assets/logo.png" + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/cli/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/cli/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..88b00dbe7f28aec8a094d8b1bdb110b49bad8da2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/cli/SKILL.md @@ -0,0 +1,172 @@ +--- +name: hf-cli +description: "Hugging Face Hub CLI (`hf`) for downloading, uploading, and managing repositories, models, datasets, and Spaces on the Hugging Face Hub. Replaces now deprecated `huggingface-cli` command." +--- + +Install: `curl -LsSf https://hf.co/cli/install.sh | bash -s`. + +The Hugging Face Hub CLI tool `hf` is available. IMPORTANT: The `hf` command replaces the deprecated `huggingface-cli` command. + +Use `hf --help` to view available functions. Note that auth commands are now all under `hf auth` e.g. `hf auth whoami`. + +## Commands + +- `hf download REPO_ID` — Download files from the Hub. `[--type CHOICE --revision TEXT --include TEXT --exclude TEXT --cache-dir TEXT --local-dir TEXT --force-download --dry-run --quiet --max-workers INTEGER]` +- `hf env` — Print information about the environment. +- `hf sync` — Sync files between local directory and a bucket. `[--delete --ignore-times --ignore-sizes --plan TEXT --apply TEXT --dry-run --include TEXT --exclude TEXT --filter-from TEXT --existing --ignore-existing --verbose --quiet]` +- `hf upload REPO_ID` — Upload a file or a folder to the Hub. Recommended for single-commit uploads. `[--type CHOICE --revision TEXT --private --include TEXT --exclude TEXT --delete TEXT --commit-message TEXT --commit-description TEXT --create-pr --every FLOAT --quiet]` +- `hf upload-large-folder REPO_ID LOCAL_PATH` — Upload a large folder to the Hub. Recommended for resumable uploads. `[--type CHOICE --revision TEXT --private --include TEXT --exclude TEXT --num-workers INTEGER --no-report --no-bars]` +- `hf version` — Print information about the hf version. + +### `hf auth` — Manage authentication (login, logout, etc.). + +- `hf auth list` — List all stored access tokens. +- `hf auth login` — Login using a token from huggingface.co/settings/tokens. `[--add-to-git-credential --force]` +- `hf auth logout` — Logout from a specific token. `[--token-name TEXT]` +- `hf auth switch` — Switch between access tokens. `[--token-name TEXT --add-to-git-credential]` +- `hf auth whoami` — Find out which huggingface.co account you are logged in as. `[--format CHOICE]` + +### `hf buckets` — Commands to interact with buckets. + +- `hf buckets cp SRC` — Copy a single file to or from a bucket. `[--quiet]` +- `hf buckets create BUCKET_ID` — Create a new bucket. `[--private --exist-ok --quiet]` +- `hf buckets delete BUCKET_ID` — Delete a bucket. `[--yes --missing-ok --quiet]` +- `hf buckets info BUCKET_ID` — Get info about a bucket. `[--quiet]` +- `hf buckets list` — List buckets or files in a bucket. `[--human-readable --tree --recursive --format CHOICE --quiet]` +- `hf buckets move FROM_ID TO_ID` — Move (rename) a bucket to a new name or namespace. +- `hf buckets remove ARGUMENT` — Remove files from a bucket. `[--recursive --yes --dry-run --include TEXT --exclude TEXT --quiet]` +- `hf buckets sync` — Sync files between local directory and a bucket. `[--delete --ignore-times --ignore-sizes --plan TEXT --apply TEXT --dry-run --include TEXT --exclude TEXT --filter-from TEXT --existing --ignore-existing --verbose --quiet]` + +### `hf cache` — Manage local cache directory. + +- `hf cache list` — List cached repositories or revisions. `[--cache-dir TEXT --revisions --filter TEXT --format CHOICE --quiet --sort CHOICE --limit INTEGER]` +- `hf cache prune` — Remove detached revisions from the cache. `[--cache-dir TEXT --yes --dry-run]` +- `hf cache rm TARGETS` — Remove cached repositories or revisions. `[--cache-dir TEXT --yes --dry-run]` +- `hf cache verify REPO_ID` — Verify checksums for a single repo revision from cache or a local directory. `[--type CHOICE --revision TEXT --cache-dir TEXT --local-dir TEXT --fail-on-missing-files --fail-on-extra-files]` + +### `hf collections` — Interact with collections on the Hub. + +- `hf collections add-item COLLECTION_SLUG ITEM_ID ITEM_TYPE` — Add an item to a collection. `[--note TEXT --exists-ok]` +- `hf collections create TITLE` — Create a new collection on the Hub. `[--namespace TEXT --description TEXT --private --exists-ok]` +- `hf collections delete COLLECTION_SLUG` — Delete a collection from the Hub. `[--missing-ok]` +- `hf collections delete-item COLLECTION_SLUG ITEM_OBJECT_ID` — Delete an item from a collection. `[--missing-ok]` +- `hf collections info COLLECTION_SLUG` — Get info about a collection on the Hub. Output is in JSON format. +- `hf collections list` — List collections on the Hub. `[--owner TEXT --item TEXT --sort CHOICE --limit INTEGER --format CHOICE --quiet]` +- `hf collections update COLLECTION_SLUG` — Update a collection's metadata on the Hub. `[--title TEXT --description TEXT --position INTEGER --private --theme TEXT]` +- `hf collections update-item COLLECTION_SLUG ITEM_OBJECT_ID` — Update an item in a collection. `[--note TEXT --position INTEGER]` + +### `hf datasets` — Interact with datasets on the Hub. + +- `hf datasets info DATASET_ID` — Get info about a dataset on the Hub. Output is in JSON format. `[--revision TEXT --expand TEXT]` +- `hf datasets list` — List datasets on the Hub. `[--search TEXT --author TEXT --filter TEXT --sort CHOICE --limit INTEGER --expand TEXT --format CHOICE --quiet]` +- `hf datasets parquet DATASET_ID` — List parquet file URLs available for a dataset. `[--subset TEXT --split TEXT --format CHOICE --quiet]` +- `hf datasets sql SQL` — Execute a raw SQL query with DuckDB against dataset parquet URLs. `[--format CHOICE]` + +### `hf discussions` — Manage discussions and pull requests on the Hub. + +- `hf discussions close REPO_ID NUM` — Close a discussion or pull request. `[--comment TEXT --yes --type CHOICE]` +- `hf discussions comment REPO_ID NUM` — Comment on a discussion or pull request. `[--body TEXT --body-file PATH --type CHOICE]` +- `hf discussions create REPO_ID --title TEXT` — Create a new discussion or pull request on a repo. `[--body TEXT --body-file PATH --pull-request --type CHOICE]` +- `hf discussions diff REPO_ID NUM` — Show the diff of a pull request. `[--type CHOICE]` +- `hf discussions info REPO_ID NUM` — Get info about a discussion or pull request. `[--comments --diff --no-color --type CHOICE --format CHOICE]` +- `hf discussions list REPO_ID` — List discussions and pull requests on a repo. `[--status CHOICE --kind CHOICE --author TEXT --limit INTEGER --type CHOICE --format CHOICE --quiet]` +- `hf discussions merge REPO_ID NUM` — Merge a pull request. `[--comment TEXT --yes --type CHOICE]` +- `hf discussions rename REPO_ID NUM NEW_TITLE` — Rename a discussion or pull request. `[--type CHOICE]` +- `hf discussions reopen REPO_ID NUM` — Reopen a closed discussion or pull request. `[--comment TEXT --yes --type CHOICE]` + +### `hf endpoints` — Manage Hugging Face Inference Endpoints. + +- `hf endpoints catalog deploy --repo TEXT` — Deploy an Inference Endpoint from the Model Catalog. `[--name TEXT --accelerator TEXT --namespace TEXT]` +- `hf endpoints catalog list` — List available Catalog models. +- `hf endpoints delete NAME` — Delete an Inference Endpoint permanently. `[--namespace TEXT --yes]` +- `hf endpoints deploy NAME --repo TEXT --framework TEXT --accelerator TEXT --instance-size TEXT --instance-type TEXT --region TEXT --vendor TEXT` — Deploy an Inference Endpoint from a Hub repository. `[--namespace TEXT --task TEXT --min-replica INTEGER --max-replica INTEGER --scale-to-zero-timeout INTEGER --scaling-metric CHOICE --scaling-threshold FLOAT]` +- `hf endpoints describe NAME` — Get information about an existing endpoint. `[--namespace TEXT]` +- `hf endpoints list` — Lists all Inference Endpoints for the given namespace. `[--namespace TEXT --format CHOICE --quiet]` +- `hf endpoints pause NAME` — Pause an Inference Endpoint. `[--namespace TEXT]` +- `hf endpoints resume NAME` — Resume an Inference Endpoint. `[--namespace TEXT --fail-if-already-running]` +- `hf endpoints scale-to-zero NAME` — Scale an Inference Endpoint to zero. `[--namespace TEXT]` +- `hf endpoints update NAME` — Update an existing endpoint. `[--namespace TEXT --repo TEXT --accelerator TEXT --instance-size TEXT --instance-type TEXT --framework TEXT --revision TEXT --task TEXT --min-replica INTEGER --max-replica INTEGER --scale-to-zero-timeout INTEGER --scaling-metric CHOICE --scaling-threshold FLOAT]` + +### `hf extensions` — Manage hf CLI extensions. + +- `hf extensions exec NAME` — Execute an installed extension. +- `hf extensions install REPO_ID` — Install an extension from a public GitHub repository. `[--force]` +- `hf extensions list` — List installed extension commands. `[--format CHOICE --quiet]` +- `hf extensions remove NAME` — Remove an installed extension. +- `hf extensions search` — Search extensions available on GitHub (tagged with 'hf-extension' topic). `[--format CHOICE --quiet]` + +### `hf jobs` — Run and manage Jobs on the Hub. + +- `hf jobs cancel JOB_ID` — Cancel a Job `[--namespace TEXT]` +- `hf jobs hardware` — List available hardware options for Jobs +- `hf jobs inspect JOB_IDS` — Display detailed information on one or more Jobs `[--namespace TEXT]` +- `hf jobs logs JOB_ID` — Fetch the logs of a Job. `[--follow --tail INTEGER --namespace TEXT]` +- `hf jobs ps` — List Jobs. `[--all --namespace TEXT --filter TEXT --format TEXT --quiet]` +- `hf jobs run IMAGE COMMAND` — Run a Job. `[--env TEXT --secrets TEXT --label TEXT --env-file TEXT --secrets-file TEXT --flavor CHOICE --timeout TEXT --detach --namespace TEXT]` +- `hf jobs scheduled delete SCHEDULED_JOB_ID` — Delete a scheduled Job. `[--namespace TEXT]` +- `hf jobs scheduled inspect SCHEDULED_JOB_IDS` — Display detailed information on one or more scheduled Jobs `[--namespace TEXT]` +- `hf jobs scheduled ps` — List scheduled Jobs `[--all --namespace TEXT --filter TEXT --format TEXT --quiet]` +- `hf jobs scheduled resume SCHEDULED_JOB_ID` — Resume (unpause) a scheduled Job. `[--namespace TEXT]` +- `hf jobs scheduled run SCHEDULE IMAGE COMMAND` — Schedule a Job. `[--suspend --concurrency --env TEXT --secrets TEXT --label TEXT --env-file TEXT --secrets-file TEXT --flavor CHOICE --timeout TEXT --namespace TEXT]` +- `hf jobs scheduled suspend SCHEDULED_JOB_ID` — Suspend (pause) a scheduled Job. `[--namespace TEXT]` +- `hf jobs scheduled uv run SCHEDULE SCRIPT` — Run a UV script (local file or URL) on HF infrastructure `[--suspend --concurrency --image TEXT --flavor CHOICE --env TEXT --secrets TEXT --label TEXT --env-file TEXT --secrets-file TEXT --timeout TEXT --namespace TEXT --with TEXT --python TEXT]` +- `hf jobs stats` — Fetch the resource usage statistics and metrics of Jobs `[--namespace TEXT]` +- `hf jobs uv run SCRIPT` — Run a UV script (local file or URL) on HF infrastructure `[--image TEXT --flavor CHOICE --env TEXT --secrets TEXT --label TEXT --env-file TEXT --secrets-file TEXT --timeout TEXT --detach --namespace TEXT --with TEXT --python TEXT]` + +### `hf models` — Interact with models on the Hub. + +- `hf models info MODEL_ID` — Get info about a model on the Hub. Output is in JSON format. `[--revision TEXT --expand TEXT]` +- `hf models list` — List models on the Hub. `[--search TEXT --author TEXT --filter TEXT --num-parameters TEXT --sort CHOICE --limit INTEGER --expand TEXT --format CHOICE --quiet]` + +### `hf papers` — Interact with papers on the Hub. + +- `hf papers list` — List daily papers on the Hub. `[--date TEXT --sort CHOICE --limit INTEGER --format CHOICE --quiet]` + +### `hf repos` — Manage repos on the Hub. + +- `hf repos branch create REPO_ID BRANCH` — Create a new branch for a repo on the Hub. `[--revision TEXT --type CHOICE --exist-ok]` +- `hf repos branch delete REPO_ID BRANCH` — Delete a branch from a repo on the Hub. `[--type CHOICE]` +- `hf repos create REPO_ID` — Create a new repo on the Hub. `[--type CHOICE --space-sdk TEXT --private --exist-ok --resource-group-id TEXT]` +- `hf repos delete REPO_ID` — Delete a repo from the Hub. This is an irreversible operation. `[--type CHOICE --missing-ok]` +- `hf repos delete-files REPO_ID PATTERNS` — Delete files from a repo on the Hub. `[--type CHOICE --revision TEXT --commit-message TEXT --commit-description TEXT --create-pr]` +- `hf repos duplicate FROM_ID` — Duplicate a repo on the Hub (model, dataset, or Space). `[--type CHOICE --private --exist-ok]` +- `hf repos move FROM_ID TO_ID` — Move a repository from a namespace to another namespace. `[--type CHOICE]` +- `hf repos settings REPO_ID` — Update the settings of a repository. `[--gated CHOICE --private --type CHOICE]` +- `hf repos tag create REPO_ID TAG` — Create a tag for a repo. `[--message TEXT --revision TEXT --type CHOICE]` +- `hf repos tag delete REPO_ID TAG` — Delete a tag for a repo. `[--yes --type CHOICE]` +- `hf repos tag list REPO_ID` — List tags for a repo. `[--type CHOICE]` + +### `hf skills` — Manage skills for AI assistants. + +- `hf skills add` — Download a skill and install it for an AI assistant. `[--claude --codex --cursor --opencode --global --dest PATH --force]` +- `hf skills preview` — Print the generated SKILL.md to stdout. + +### `hf spaces` — Interact with spaces on the Hub. + +- `hf spaces dev-mode SPACE_ID` — Enable or disable dev mode on a Space. `[--stop]` +- `hf spaces hot-reload SPACE_ID` — Hot-reload any Python file of a Space without a full rebuild + restart. `[--local-file TEXT --skip-checks --skip-summary]` +- `hf spaces info SPACE_ID` — Get info about a space on the Hub. Output is in JSON format. `[--revision TEXT --expand TEXT]` +- `hf spaces list` — List spaces on the Hub. `[--search TEXT --author TEXT --filter TEXT --sort CHOICE --limit INTEGER --expand TEXT --format CHOICE --quiet]` + +### `hf webhooks` — Manage webhooks on the Hub. + +- `hf webhooks create --watch TEXT` — Create a new webhook. `[--url TEXT --job-id TEXT --domain CHOICE --secret TEXT]` +- `hf webhooks delete WEBHOOK_ID` — Delete a webhook permanently. `[--yes]` +- `hf webhooks disable WEBHOOK_ID` — Disable an active webhook. +- `hf webhooks enable WEBHOOK_ID` — Enable a disabled webhook. +- `hf webhooks info WEBHOOK_ID` — Show full details for a single webhook as JSON. +- `hf webhooks list` — List all webhooks for the current user. `[--format CHOICE --quiet]` +- `hf webhooks update WEBHOOK_ID` — Update an existing webhook. Only provided options are changed. `[--url TEXT --watch TEXT --domain CHOICE --secret TEXT]` + +## Common options + +- `--format` — Output format: `--format json` (or `--json`) or `--format table` (default). +- `-q / --quiet` — Minimal output. +- `--revision` — Git revision id which can be a branch name, a tag, or a commit hash. +- `--token` — Use a User Access Token. Prefer setting `HF_TOKEN` env var instead of passing `--token`. +- `--type` — The type of repository (model, dataset, or space). + +## Tips + +- Use `hf --help` for full options, descriptions, usage, and real-world examples +- Authenticate with `HF_TOKEN` env var (recommended) or with `--token` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/cli/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/cli/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2d49d5f04c59085139308d26a02b44fba0c2d791 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/cli/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "HF CLI" + short_description: "Manage Hub repos, models, datasets, and Spaces with the Hugging Face CLI" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..a68b2e79958930b3913cb8e7667e07000031e40b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/SKILL.md @@ -0,0 +1,207 @@ +--- +name: huggingface-community-evals +description: Run evaluations for Hugging Face Hub models using inspect-ai and lighteval on local hardware. Use for backend selection, local GPU evals, and choosing between vLLM / Transformers / accelerate. Not for HF Jobs orchestration, model-card PRs, .eval_results publication, or community-evals automation. +--- + +# Overview + +This skill is for **running evaluations against models on the Hugging Face Hub on local hardware**. + +It covers: +- `inspect-ai` with local inference +- `lighteval` with local inference +- choosing between `vllm`, Hugging Face Transformers, and `accelerate` +- smoke tests, task selection, and backend fallback strategy + +It does **not** cover: +- Hugging Face Jobs orchestration +- model-card or `model-index` edits +- README table extraction +- Artificial Analysis imports +- `.eval_results` generation or publishing +- PR creation or community-evals automation + +If the user wants to **run the same eval remotely on Hugging Face Jobs**, hand off to the `hugging-face-jobs` skill and pass it one of the local scripts in this skill. + +If the user wants to **publish results into the community evals workflow**, stop after generating the evaluation run and hand off that publishing step to `~/code/community-evals`. + +> All paths below are relative to the directory containing this `SKILL.md`. + +# When To Use Which Script + +| Use case | Script | +|---|---| +| Local `inspect-ai` eval on a Hub model via inference providers | `scripts/inspect_eval_uv.py` | +| Local GPU eval with `inspect-ai` using `vllm` or Transformers | `scripts/inspect_vllm_uv.py` | +| Local GPU eval with `lighteval` using `vllm` or `accelerate` | `scripts/lighteval_vllm_uv.py` | +| Extra command patterns | `examples/USAGE_EXAMPLES.md` | + +# Prerequisites + +- Prefer `uv run` for local execution. +- Set `HF_TOKEN` for gated/private models. +- For local GPU runs, verify GPU access before starting: + +```bash +uv --version +printenv HF_TOKEN >/dev/null +nvidia-smi +``` + +If `nvidia-smi` is unavailable, either: +- use `scripts/inspect_eval_uv.py` for lighter provider-backed evaluation, or +- hand off to the `hugging-face-jobs` skill if the user wants remote compute. + +# Core Workflow + +1. Choose the evaluation framework. + - Use `inspect-ai` when you want explicit task control and inspect-native flows. + - Use `lighteval` when the benchmark is naturally expressed as a lighteval task string, especially leaderboard-style tasks. +2. Choose the inference backend. + - Prefer `vllm` for throughput on supported architectures. + - Use Hugging Face Transformers (`--backend hf`) or `accelerate` as compatibility fallbacks. +3. Start with a smoke test. + - `inspect-ai`: add `--limit 10` or similar. + - `lighteval`: add `--max-samples 10`. +4. Scale up only after the smoke test passes. +5. If the user wants remote execution, hand off to `hugging-face-jobs` with the same script + args. + +# Quick Start + +## Option A: inspect-ai with local inference providers path + +Best when the model is already supported by Hugging Face Inference Providers and you want the lowest local setup overhead. + +```bash +uv run scripts/inspect_eval_uv.py \ + --model meta-llama/Llama-3.2-1B \ + --task mmlu \ + --limit 20 +``` + +Use this path when: +- you want a quick local smoke test +- you do not need direct GPU control +- the task already exists in `inspect-evals` + +## Option B: inspect-ai on Local GPU + +Best when you need to load the Hub model directly, use `vllm`, or fall back to Transformers for unsupported architectures. + +Local GPU: + +```bash +uv run scripts/inspect_vllm_uv.py \ + --model meta-llama/Llama-3.2-1B \ + --task gsm8k \ + --limit 20 +``` + +Transformers fallback: + +```bash +uv run scripts/inspect_vllm_uv.py \ + --model microsoft/phi-2 \ + --task mmlu \ + --backend hf \ + --trust-remote-code \ + --limit 20 +``` + +## Option C: lighteval on Local GPU + +Best when the task is naturally expressed as a `lighteval` task string, especially Open LLM Leaderboard style benchmarks. + +Local GPU: + +```bash +uv run scripts/lighteval_vllm_uv.py \ + --model meta-llama/Llama-3.2-3B-Instruct \ + --tasks "leaderboard|mmlu|5,leaderboard|gsm8k|5" \ + --max-samples 20 \ + --use-chat-template +``` + +`accelerate` fallback: + +```bash +uv run scripts/lighteval_vllm_uv.py \ + --model microsoft/phi-2 \ + --tasks "leaderboard|mmlu|5" \ + --backend accelerate \ + --trust-remote-code \ + --max-samples 20 +``` + +# Remote Execution Boundary + +This skill intentionally stops at **local execution and backend selection**. + +If the user wants to: +- run these scripts on Hugging Face Jobs +- pick remote hardware +- pass secrets to remote jobs +- schedule recurring runs +- inspect / cancel / monitor jobs + +then switch to the **`hugging-face-jobs`** skill and pass it one of these scripts plus the chosen arguments. + +# Task Selection + +`inspect-ai` examples: +- `mmlu` +- `gsm8k` +- `hellaswag` +- `arc_challenge` +- `truthfulqa` +- `winogrande` +- `humaneval` + +`lighteval` task strings use `suite|task|num_fewshot`: +- `leaderboard|mmlu|5` +- `leaderboard|gsm8k|5` +- `leaderboard|arc_challenge|25` +- `lighteval|hellaswag|0` + +Multiple `lighteval` tasks can be comma-separated in `--tasks`. + +# Backend Selection + +- Prefer `inspect_vllm_uv.py --backend vllm` for fast GPU inference on supported architectures. +- Use `inspect_vllm_uv.py --backend hf` when `vllm` does not support the model. +- Prefer `lighteval_vllm_uv.py --backend vllm` for throughput on supported models. +- Use `lighteval_vllm_uv.py --backend accelerate` as the compatibility fallback. +- Use `inspect_eval_uv.py` when Inference Providers already cover the model and you do not need direct GPU control. + +# Hardware Guidance + +| Model size | Suggested local hardware | +|---|---| +| `< 3B` | consumer GPU / Apple Silicon / small dev GPU | +| `3B - 13B` | stronger local GPU | +| `13B+` | high-memory local GPU or hand off to `hugging-face-jobs` | + +For smoke tests, prefer cheaper local runs plus `--limit` or `--max-samples`. + +# Troubleshooting + +- CUDA or vLLM OOM: + - reduce `--batch-size` + - reduce `--gpu-memory-utilization` + - switch to a smaller model for the smoke test + - if necessary, hand off to `hugging-face-jobs` +- Model unsupported by `vllm`: + - switch to `--backend hf` for `inspect-ai` + - switch to `--backend accelerate` for `lighteval` +- Gated/private repo access fails: + - verify `HF_TOKEN` +- Custom model code required: + - add `--trust-remote-code` + +# Examples + +See: +- `examples/USAGE_EXAMPLES.md` for local command patterns +- `scripts/inspect_eval_uv.py` +- `scripts/inspect_vllm_uv.py` +- `scripts/lighteval_vllm_uv.py` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8600a9702ff69700295451c467a216649167db26 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Community Evals" + short_description: "Run local evaluations for Hugging Face Hub models" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/examples/.env.example b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/examples/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..26d9b9b4b284d58add70f2ed2d581a1ab503fa67 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/examples/.env.example @@ -0,0 +1,3 @@ +# Hugging Face Token (required for gated/private models) +# Get your token at: https://huggingface.co/settings/tokens +HF_TOKEN=hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxx diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/examples/USAGE_EXAMPLES.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/examples/USAGE_EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..ca42fd37226f36c36043f5d5a122f586d7432506 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/examples/USAGE_EXAMPLES.md @@ -0,0 +1,101 @@ +# Usage Examples + +This document provides practical examples for **running evaluations locally** against Hugging Face Hub models. + +## What this skill covers + +- `inspect-ai` local runs +- `inspect-ai` with `vllm` or Transformers backends +- `lighteval` local runs with `vllm` or `accelerate` +- smoke tests and backend fallback patterns + +## What this skill does NOT cover + +- `model-index` +- `.eval_results` +- community eval publication workflows +- model-card PR creation +- Hugging Face Jobs orchestration + +If you want to run these same scripts remotely, use the `hugging-face-jobs` skill and pass one of the scripts in `scripts/`. + +## Setup + +```bash +cd skills/community-evals +export HF_TOKEN=hf_xxx +uv --version +``` + +For local GPU runs: + +```bash +nvidia-smi +``` + +## inspect-ai examples + +### Quick smoke test + +```bash +uv run scripts/inspect_eval_uv.py \ + --model meta-llama/Llama-3.2-1B \ + --task mmlu \ + --limit 10 +``` + +### Local GPU with vLLM + +```bash +uv run scripts/inspect_vllm_uv.py \ + --model meta-llama/Llama-3.2-8B-Instruct \ + --task gsm8k \ + --limit 20 +``` + +### Transformers fallback + +```bash +uv run scripts/inspect_vllm_uv.py \ + --model microsoft/phi-2 \ + --task mmlu \ + --backend hf \ + --trust-remote-code \ + --limit 20 +``` + +## lighteval examples + +### Single task + +```bash +uv run scripts/lighteval_vllm_uv.py \ + --model meta-llama/Llama-3.2-3B-Instruct \ + --tasks "leaderboard|mmlu|5" \ + --max-samples 20 +``` + +### Multiple tasks + +```bash +uv run scripts/lighteval_vllm_uv.py \ + --model meta-llama/Llama-3.2-3B-Instruct \ + --tasks "leaderboard|mmlu|5,leaderboard|gsm8k|5" \ + --max-samples 20 \ + --use-chat-template +``` + +### accelerate fallback + +```bash +uv run scripts/lighteval_vllm_uv.py \ + --model microsoft/phi-2 \ + --tasks "leaderboard|mmlu|5" \ + --backend accelerate \ + --trust-remote-code \ + --max-samples 20 +``` + +## Hand-off to Hugging Face Jobs + +When local hardware is not enough, switch to the `hugging-face-jobs` skill and run one of these scripts remotely. Keep the script path and args; move the orchestration there. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/inspect_eval_uv.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/inspect_eval_uv.py new file mode 100644 index 0000000000000000000000000000000000000000..d398bc60b0bf4dcb5571ae144ce5fef5226d2467 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/inspect_eval_uv.py @@ -0,0 +1,104 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = [ +# "inspect-ai>=0.3.0", +# "inspect-evals", +# "openai", +# ] +# /// + +""" +Entry point script for running inspect-ai evaluations against Hugging Face inference providers. +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +import sys +from pathlib import Path +from typing import Optional + + +def _inspect_evals_tasks_root() -> Optional[Path]: + """Return the installed inspect_evals package path if available.""" + try: + import inspect_evals + + return Path(inspect_evals.__file__).parent + except Exception: + return None + + +def _normalize_task(task: str) -> str: + """Allow lighteval-style `suite|task|shots` strings by keeping the task name.""" + if "|" in task: + parts = task.split("|") + if len(parts) >= 2 and parts[1]: + return parts[1] + return task + + +def main() -> None: + parser = argparse.ArgumentParser(description="Inspect-ai job runner") + parser.add_argument("--model", required=True, help="Model ID on Hugging Face Hub") + parser.add_argument("--task", required=True, help="inspect-ai task to execute") + parser.add_argument("--limit", type=int, default=None, help="Limit number of samples to evaluate") + parser.add_argument( + "--tasks-root", + default=None, + help="Optional path to inspect task files. Defaults to the installed inspect_evals package.", + ) + parser.add_argument( + "--sandbox", + default="local", + help="Sandbox backend to use (default: local for HF jobs without Docker).", + ) + args = parser.parse_args() + + # Ensure downstream libraries can read the token passed as a secret + hf_token = os.getenv("HF_TOKEN") + if hf_token: + os.environ.setdefault("HUGGING_FACE_HUB_TOKEN", hf_token) + os.environ.setdefault("HF_HUB_TOKEN", hf_token) + + task = _normalize_task(args.task) + tasks_root = Path(args.tasks_root) if args.tasks_root else _inspect_evals_tasks_root() + if tasks_root and not tasks_root.exists(): + tasks_root = None + + cmd = [ + "inspect", + "eval", + task, + "--model", + f"hf-inference-providers/{args.model}", + "--log-level", + "info", + # Reduce batch size to avoid OOM errors (default is 32) + "--max-connections", + "1", + # Set a small positive temperature (HF doesn't allow temperature=0) + "--temperature", + "0.001", + ] + + if args.sandbox: + cmd.extend(["--sandbox", args.sandbox]) + + if args.limit: + cmd.extend(["--limit", str(args.limit)]) + + try: + subprocess.run(cmd, check=True, cwd=tasks_root) + print("Evaluation complete.") + except subprocess.CalledProcessError as exc: + location = f" (cwd={tasks_root})" if tasks_root else "" + print(f"Evaluation failed with exit code {exc.returncode}{location}", file=sys.stderr) + raise + + +if __name__ == "__main__": + main() + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/inspect_vllm_uv.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/inspect_vllm_uv.py new file mode 100644 index 0000000000000000000000000000000000000000..f1454c5a6e2cd2934a60eeab8d5826f6075e102a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/inspect_vllm_uv.py @@ -0,0 +1,306 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = [ +# "inspect-ai>=0.3.0", +# "inspect-evals", +# "vllm>=0.4.0", +# "torch>=2.0.0", +# "transformers>=4.40.0", +# ] +# /// + +""" +Entry point script for running inspect-ai evaluations with vLLM or HuggingFace Transformers backend. + +This script runs evaluations on custom HuggingFace models using local GPU inference, +separate from inference provider scripts (which use external APIs). + +Usage (standalone): + uv run scripts/inspect_vllm_uv.py --model "meta-llama/Llama-3.2-1B" --task "mmlu" + +Model backends: + - vllm: Fast inference with vLLM (recommended for large models) + - hf: HuggingFace Transformers backend (broader model compatibility) +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +import sys +from typing import Optional + + +def setup_environment() -> None: + """Configure environment variables for HuggingFace authentication.""" + hf_token = os.getenv("HF_TOKEN") + if hf_token: + os.environ.setdefault("HUGGING_FACE_HUB_TOKEN", hf_token) + os.environ.setdefault("HF_HUB_TOKEN", hf_token) + + +def run_inspect_vllm( + model_id: str, + task: str, + limit: Optional[int] = None, + max_connections: int = 4, + temperature: float = 0.0, + tensor_parallel_size: int = 1, + gpu_memory_utilization: float = 0.8, + dtype: str = "auto", + trust_remote_code: bool = False, + log_level: str = "info", +) -> None: + """ + Run inspect-ai evaluation with vLLM backend. + + Args: + model_id: HuggingFace model ID + task: inspect-ai task to execute (e.g., "mmlu", "gsm8k") + limit: Limit number of samples to evaluate + max_connections: Maximum concurrent connections + temperature: Sampling temperature + tensor_parallel_size: Number of GPUs for tensor parallelism + gpu_memory_utilization: GPU memory fraction + dtype: Data type (auto, float16, bfloat16) + trust_remote_code: Allow remote code execution + log_level: Logging level + """ + setup_environment() + + model_spec = f"vllm/{model_id}" + cmd = [ + "inspect", + "eval", + task, + "--model", + model_spec, + "--log-level", + log_level, + "--max-connections", + str(max_connections), + ] + + # vLLM supports temperature=0 unlike HF inference providers + cmd.extend(["--temperature", str(temperature)]) + + # Older inspect-ai CLI versions do not support --model-args; rely on defaults + # and let vLLM choose sensible settings for small models. + if tensor_parallel_size != 1: + cmd.extend(["--tensor-parallel-size", str(tensor_parallel_size)]) + if gpu_memory_utilization != 0.8: + cmd.extend(["--gpu-memory-utilization", str(gpu_memory_utilization)]) + if dtype != "auto": + cmd.extend(["--dtype", dtype]) + if trust_remote_code: + cmd.append("--trust-remote-code") + + if limit: + cmd.extend(["--limit", str(limit)]) + + print(f"Running: {' '.join(cmd)}") + + try: + subprocess.run(cmd, check=True) + print("Evaluation complete.") + except subprocess.CalledProcessError as exc: + print(f"Evaluation failed with exit code {exc.returncode}", file=sys.stderr) + sys.exit(exc.returncode) + + +def run_inspect_hf( + model_id: str, + task: str, + limit: Optional[int] = None, + max_connections: int = 1, + temperature: float = 0.001, + device: str = "auto", + dtype: str = "auto", + trust_remote_code: bool = False, + log_level: str = "info", +) -> None: + """ + Run inspect-ai evaluation with HuggingFace Transformers backend. + + Use this when vLLM doesn't support the model architecture. + + Args: + model_id: HuggingFace model ID + task: inspect-ai task to execute + limit: Limit number of samples + max_connections: Maximum concurrent connections (keep low for memory) + temperature: Sampling temperature + device: Device to use (auto, cuda, cpu) + dtype: Data type + trust_remote_code: Allow remote code execution + log_level: Logging level + """ + setup_environment() + + model_spec = f"hf/{model_id}" + + cmd = [ + "inspect", + "eval", + task, + "--model", + model_spec, + "--log-level", + log_level, + "--max-connections", + str(max_connections), + "--temperature", + str(temperature), + ] + + if device != "auto": + cmd.extend(["--device", device]) + if dtype != "auto": + cmd.extend(["--dtype", dtype]) + if trust_remote_code: + cmd.append("--trust-remote-code") + + if limit: + cmd.extend(["--limit", str(limit)]) + + print(f"Running: {' '.join(cmd)}") + + try: + subprocess.run(cmd, check=True) + print("Evaluation complete.") + except subprocess.CalledProcessError as exc: + print(f"Evaluation failed with exit code {exc.returncode}", file=sys.stderr) + sys.exit(exc.returncode) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Run inspect-ai evaluations with vLLM or HuggingFace Transformers on custom models", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Run MMLU with vLLM backend + uv run scripts/inspect_vllm_uv.py --model meta-llama/Llama-3.2-1B --task mmlu + + # Run with HuggingFace Transformers backend + uv run scripts/inspect_vllm_uv.py --model meta-llama/Llama-3.2-1B --task mmlu --backend hf + + # Run with limited samples for testing + uv run scripts/inspect_vllm_uv.py --model meta-llama/Llama-3.2-1B --task mmlu --limit 10 + + # Run on multiple GPUs with tensor parallelism + uv run scripts/inspect_vllm_uv.py --model meta-llama/Llama-3.2-70B --task mmlu --tensor-parallel-size 4 + +Available tasks (from inspect-evals): + - mmlu: Massive Multitask Language Understanding + - gsm8k: Grade School Math + - hellaswag: Common sense reasoning + - arc_challenge: AI2 Reasoning Challenge + - truthfulqa: TruthfulQA benchmark + - winogrande: Winograd Schema Challenge + - humaneval: Code generation (HumanEval) + + """, + ) + + parser.add_argument( + "--model", + required=True, + help="HuggingFace model ID (e.g., meta-llama/Llama-3.2-1B)", + ) + parser.add_argument( + "--task", + required=True, + help="inspect-ai task to execute (e.g., mmlu, gsm8k)", + ) + parser.add_argument( + "--backend", + choices=["vllm", "hf"], + default="vllm", + help="Model backend (default: vllm)", + ) + parser.add_argument( + "--limit", + type=int, + default=None, + help="Limit number of samples to evaluate", + ) + parser.add_argument( + "--max-connections", + type=int, + default=None, + help="Maximum concurrent connections (default: 4 for vllm, 1 for hf)", + ) + parser.add_argument( + "--temperature", + type=float, + default=None, + help="Sampling temperature (default: 0.0 for vllm, 0.001 for hf)", + ) + parser.add_argument( + "--tensor-parallel-size", + type=int, + default=1, + help="Number of GPUs for tensor parallelism (vLLM only, default: 1)", + ) + parser.add_argument( + "--gpu-memory-utilization", + type=float, + default=0.8, + help="GPU memory fraction to use (vLLM only, default: 0.8)", + ) + parser.add_argument( + "--dtype", + default="auto", + choices=["auto", "float16", "bfloat16", "float32"], + help="Data type for model weights (default: auto)", + ) + parser.add_argument( + "--device", + default="auto", + help="Device for HF backend (auto, cuda, cpu)", + ) + parser.add_argument( + "--trust-remote-code", + action="store_true", + help="Allow executing remote code from model repository", + ) + parser.add_argument( + "--log-level", + default="info", + choices=["debug", "info", "warning", "error"], + help="Logging level (default: info)", + ) + + args = parser.parse_args() + + if args.backend == "vllm": + run_inspect_vllm( + model_id=args.model, + task=args.task, + limit=args.limit, + max_connections=args.max_connections or 4, + temperature=args.temperature if args.temperature is not None else 0.0, + tensor_parallel_size=args.tensor_parallel_size, + gpu_memory_utilization=args.gpu_memory_utilization, + dtype=args.dtype, + trust_remote_code=args.trust_remote_code, + log_level=args.log_level, + ) + else: + run_inspect_hf( + model_id=args.model, + task=args.task, + limit=args.limit, + max_connections=args.max_connections or 1, + temperature=args.temperature if args.temperature is not None else 0.001, + device=args.device, + dtype=args.dtype, + trust_remote_code=args.trust_remote_code, + log_level=args.log_level, + ) + + +if __name__ == "__main__": + main() diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/lighteval_vllm_uv.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/lighteval_vllm_uv.py new file mode 100644 index 0000000000000000000000000000000000000000..91ba83b33f68d8b0705c6f9abe089ecf97cbb9d5 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/community-evals/scripts/lighteval_vllm_uv.py @@ -0,0 +1,297 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = [ +# "lighteval[accelerate,vllm]>=0.6.0", +# "torch>=2.0.0", +# "transformers>=4.40.0", +# "accelerate>=0.30.0", +# "vllm>=0.4.0", +# ] +# /// + +""" +Entry point script for running lighteval evaluations with local GPU backends. + +This script runs evaluations using vLLM or accelerate on custom HuggingFace models. +It is separate from inference provider scripts and evaluates models directly on local hardware. + +Usage (standalone): + uv run scripts/lighteval_vllm_uv.py --model "meta-llama/Llama-3.2-1B" --tasks "leaderboard|mmlu|5" + +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +import sys +from typing import Optional + + +def setup_environment() -> None: + """Configure environment variables for HuggingFace authentication.""" + hf_token = os.getenv("HF_TOKEN") + if hf_token: + os.environ.setdefault("HUGGING_FACE_HUB_TOKEN", hf_token) + os.environ.setdefault("HF_HUB_TOKEN", hf_token) + + +def run_lighteval_vllm( + model_id: str, + tasks: str, + output_dir: Optional[str] = None, + max_samples: Optional[int] = None, + batch_size: int = 1, + tensor_parallel_size: int = 1, + gpu_memory_utilization: float = 0.8, + dtype: str = "auto", + trust_remote_code: bool = False, + use_chat_template: bool = False, + system_prompt: Optional[str] = None, +) -> None: + """ + Run lighteval with vLLM backend for efficient GPU inference. + + Args: + model_id: HuggingFace model ID (e.g., "meta-llama/Llama-3.2-1B") + tasks: Task specification (e.g., "leaderboard|mmlu|5" or "lighteval|hellaswag|0") + output_dir: Directory for evaluation results + max_samples: Limit number of samples per task + batch_size: Batch size for evaluation + tensor_parallel_size: Number of GPUs for tensor parallelism + gpu_memory_utilization: GPU memory fraction to use (0.0-1.0) + dtype: Data type for model weights (auto, float16, bfloat16) + trust_remote_code: Allow executing remote code from model repo + use_chat_template: Apply chat template for conversational models + system_prompt: System prompt for chat models + """ + setup_environment() + + # Build lighteval vllm command + cmd = [ + "lighteval", + "vllm", + model_id, + tasks, + "--batch-size", str(batch_size), + "--tensor-parallel-size", str(tensor_parallel_size), + "--gpu-memory-utilization", str(gpu_memory_utilization), + "--dtype", dtype, + ] + + if output_dir: + cmd.extend(["--output-dir", output_dir]) + + if max_samples: + cmd.extend(["--max-samples", str(max_samples)]) + + if trust_remote_code: + cmd.append("--trust-remote-code") + + if use_chat_template: + cmd.append("--use-chat-template") + + if system_prompt: + cmd.extend(["--system-prompt", system_prompt]) + + print(f"Running: {' '.join(cmd)}") + + try: + subprocess.run(cmd, check=True) + print("Evaluation complete.") + except subprocess.CalledProcessError as exc: + print(f"Evaluation failed with exit code {exc.returncode}", file=sys.stderr) + sys.exit(exc.returncode) + + +def run_lighteval_accelerate( + model_id: str, + tasks: str, + output_dir: Optional[str] = None, + max_samples: Optional[int] = None, + batch_size: int = 1, + dtype: str = "bfloat16", + trust_remote_code: bool = False, + use_chat_template: bool = False, + system_prompt: Optional[str] = None, +) -> None: + """ + Run lighteval with accelerate backend for multi-GPU distributed inference. + + Use this backend when vLLM is not available or for models not supported by vLLM. + + Args: + model_id: HuggingFace model ID + tasks: Task specification + output_dir: Directory for evaluation results + max_samples: Limit number of samples per task + batch_size: Batch size for evaluation + dtype: Data type for model weights + trust_remote_code: Allow executing remote code + use_chat_template: Apply chat template + system_prompt: System prompt for chat models + """ + setup_environment() + + # Build lighteval accelerate command + cmd = [ + "lighteval", + "accelerate", + model_id, + tasks, + "--batch-size", str(batch_size), + "--dtype", dtype, + ] + + if output_dir: + cmd.extend(["--output-dir", output_dir]) + + if max_samples: + cmd.extend(["--max-samples", str(max_samples)]) + + if trust_remote_code: + cmd.append("--trust-remote-code") + + if use_chat_template: + cmd.append("--use-chat-template") + + if system_prompt: + cmd.extend(["--system-prompt", system_prompt]) + + print(f"Running: {' '.join(cmd)}") + + try: + subprocess.run(cmd, check=True) + print("Evaluation complete.") + except subprocess.CalledProcessError as exc: + print(f"Evaluation failed with exit code {exc.returncode}", file=sys.stderr) + sys.exit(exc.returncode) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Run lighteval evaluations with vLLM or accelerate backend on custom HuggingFace models", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Run MMLU evaluation with vLLM + uv run scripts/lighteval_vllm_uv.py --model meta-llama/Llama-3.2-1B --tasks "leaderboard|mmlu|5" + + # Run with accelerate backend instead of vLLM + uv run scripts/lighteval_vllm_uv.py --model meta-llama/Llama-3.2-1B --tasks "leaderboard|mmlu|5" --backend accelerate + + # Run with chat template for instruction-tuned models + uv run scripts/lighteval_vllm_uv.py --model meta-llama/Llama-3.2-1B-Instruct --tasks "leaderboard|mmlu|5" --use-chat-template + + # Run with limited samples for testing + uv run scripts/lighteval_vllm_uv.py --model meta-llama/Llama-3.2-1B --tasks "leaderboard|mmlu|5" --max-samples 10 + +Task format: + Tasks use the format: "suite|task|num_fewshot" + - leaderboard|mmlu|5 (MMLU with 5-shot) + - lighteval|hellaswag|0 (HellaSwag zero-shot) + - leaderboard|gsm8k|5 (GSM8K with 5-shot) + - Multiple tasks: "leaderboard|mmlu|5,leaderboard|gsm8k|5" + """, + ) + + parser.add_argument( + "--model", + required=True, + help="HuggingFace model ID (e.g., meta-llama/Llama-3.2-1B)", + ) + parser.add_argument( + "--tasks", + required=True, + help="Task specification (e.g., 'leaderboard|mmlu|5')", + ) + parser.add_argument( + "--backend", + choices=["vllm", "accelerate"], + default="vllm", + help="Inference backend to use (default: vllm)", + ) + parser.add_argument( + "--output-dir", + default=None, + help="Directory for evaluation results", + ) + parser.add_argument( + "--max-samples", + type=int, + default=None, + help="Limit number of samples per task (useful for testing)", + ) + parser.add_argument( + "--batch-size", + type=int, + default=1, + help="Batch size for evaluation (default: 1)", + ) + parser.add_argument( + "--tensor-parallel-size", + type=int, + default=1, + help="Number of GPUs for tensor parallelism (vLLM only, default: 1)", + ) + parser.add_argument( + "--gpu-memory-utilization", + type=float, + default=0.8, + help="GPU memory fraction to use (vLLM only, default: 0.8)", + ) + parser.add_argument( + "--dtype", + default="auto", + choices=["auto", "float16", "bfloat16", "float32"], + help="Data type for model weights (default: auto)", + ) + parser.add_argument( + "--trust-remote-code", + action="store_true", + help="Allow executing remote code from model repository", + ) + parser.add_argument( + "--use-chat-template", + action="store_true", + help="Apply chat template for instruction-tuned/chat models", + ) + parser.add_argument( + "--system-prompt", + default=None, + help="System prompt for chat models", + ) + + args = parser.parse_args() + + if args.backend == "vllm": + run_lighteval_vllm( + model_id=args.model, + tasks=args.tasks, + output_dir=args.output_dir, + max_samples=args.max_samples, + batch_size=args.batch_size, + tensor_parallel_size=args.tensor_parallel_size, + gpu_memory_utilization=args.gpu_memory_utilization, + dtype=args.dtype, + trust_remote_code=args.trust_remote_code, + use_chat_template=args.use_chat_template, + system_prompt=args.system_prompt, + ) + else: + run_lighteval_accelerate( + model_id=args.model, + tasks=args.tasks, + output_dir=args.output_dir, + max_samples=args.max_samples, + batch_size=args.batch_size, + dtype=args.dtype if args.dtype != "auto" else "bfloat16", + trust_remote_code=args.trust_remote_code, + use_chat_template=args.use_chat_template, + system_prompt=args.system_prompt, + ) + + +if __name__ == "__main__": + main() diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/datasets/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/datasets/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..16ff9665c71bd7d7a3cd4e5eaa67078a41cad750 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/datasets/SKILL.md @@ -0,0 +1,121 @@ +--- +name: huggingface-datasets +description: Use this skill for Hugging Face Dataset Viewer API workflows that fetch subset/split metadata, paginate rows, search text, apply filters, download parquet URLs, and read size or statistics. +--- + +# Hugging Face Dataset Viewer + +Use this skill to execute read-only Dataset Viewer API calls for dataset exploration and extraction. + +## Core workflow + +1. Optionally validate dataset availability with `/is-valid`. +2. Resolve `config` + `split` with `/splits`. +3. Preview with `/first-rows`. +4. Paginate content with `/rows` using `offset` and `length` (max 100). +5. Use `/search` for text matching and `/filter` for row predicates. +6. Retrieve parquet links via `/parquet` and totals/metadata via `/size` and `/statistics`. + +## Defaults + +- Base URL: `https://datasets-server.huggingface.co` +- Default API method: `GET` +- Query params should be URL-encoded. +- `offset` is 0-based. +- `length` max is usually `100` for row-like endpoints. +- Gated/private datasets require `Authorization: Bearer `. + +## Dataset Viewer + +- `Validate dataset`: `/is-valid?dataset=` +- `List subsets and splits`: `/splits?dataset=` +- `Preview first rows`: `/first-rows?dataset=&config=&split=` +- `Paginate rows`: `/rows?dataset=&config=&split=&offset=&length=` +- `Search text`: `/search?dataset=&config=&split=&query=&offset=&length=` +- `Filter with predicates`: `/filter?dataset=&config=&split=&where=&orderby=&offset=&length=` +- `List parquet shards`: `/parquet?dataset=` +- `Get size totals`: `/size?dataset=` +- `Get column statistics`: `/statistics?dataset=&config=&split=` +- `Get Croissant metadata (if available)`: `/croissant?dataset=` + +Pagination pattern: + +```bash +curl "https://datasets-server.huggingface.co/rows?dataset=stanfordnlp/imdb&config=plain_text&split=train&offset=0&length=100" +curl "https://datasets-server.huggingface.co/rows?dataset=stanfordnlp/imdb&config=plain_text&split=train&offset=100&length=100" +``` + +When pagination is partial, use response fields such as `num_rows_total`, `num_rows_per_page`, and `partial` to drive continuation logic. + +Search/filter notes: + +- `/search` matches string columns (full-text style behavior is internal to the API). +- `/filter` requires predicate syntax in `where` and optional sort in `orderby`. +- Keep filtering and searches read-only and side-effect free. + +## Querying Datasets + +Use `npx parquetlens` with Hub parquet alias paths for SQL querying. + +Parquet alias shape: + +```text +hf://datasets//@~parquet///.parquet +``` + +Derive ``, ``, and `` from Dataset Viewer `/parquet`: + +```bash +curl -s "https://datasets-server.huggingface.co/parquet?dataset=cfahlgren1/hub-stats" \ + | jq -r '.parquet_files[] | "hf://datasets/\(.dataset)@~parquet/\(.config)/\(.split)/\(.filename)"' +``` + +Run SQL query: + +```bash +npx -y -p parquetlens -p @parquetlens/sql parquetlens \ + "hf://datasets//@~parquet///.parquet" \ + --sql "SELECT * FROM data LIMIT 20" +``` + +### SQL export + +- CSV: `--sql "COPY (SELECT * FROM data LIMIT 1000) TO 'export.csv' (FORMAT CSV, HEADER, DELIMITER ',')"` +- JSON: `--sql "COPY (SELECT * FROM data LIMIT 1000) TO 'export.json' (FORMAT JSON)"` +- Parquet: `--sql "COPY (SELECT * FROM data LIMIT 1000) TO 'export.parquet' (FORMAT PARQUET)"` + +## Creating and Uploading Datasets + +Use one of these flows depending on dependency constraints. + +Zero local dependencies (Hub UI): + +- Create dataset repo in browser: `https://huggingface.co/new-dataset` +- Upload parquet files in the repo "Files and versions" page. +- Verify shards appear in Dataset Viewer: + +```bash +curl -s "https://datasets-server.huggingface.co/parquet?dataset=/" +``` + +Low dependency CLI flow (`npx @huggingface/hub` / `hfjs`): + +- Set auth token: + +```bash +export HF_TOKEN= +``` + +- Upload parquet folder to a dataset repo (auto-creates repo if missing): + +```bash +npx -y @huggingface/hub upload datasets// ./local/parquet-folder data +``` + +- Upload as private repo on creation: + +```bash +npx -y @huggingface/hub upload datasets// ./local/parquet-folder data --private +``` + +After upload, call `/parquet` to discover `//` values for querying with `@~parquet`. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/datasets/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/datasets/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2c270fd1577ba4967d43264ab4e31a8ecae9a5b6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/datasets/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Datasets" + short_description: "Work with Hugging Face Dataset Viewer API metadata, rows, and filters" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..08c453550081fb35ba2bff8b84c54923a356c15a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/SKILL.md @@ -0,0 +1,245 @@ +--- +name: huggingface-gradio +description: Build Gradio web UIs and demos in Python. Use when creating or editing Gradio apps, components, event listeners, layouts, or chatbots. +--- + +# Gradio + +Gradio is a Python library for building interactive web UIs and ML demos. This skill covers the core API, patterns, and examples. + +## Guides + +Detailed guides on specific topics (read these when relevant): + +- [Quickstart](https://www.gradio.app/guides/quickstart) +- [The Interface Class](https://www.gradio.app/guides/the-interface-class) +- [Blocks and Event Listeners](https://www.gradio.app/guides/blocks-and-event-listeners) +- [Controlling Layout](https://www.gradio.app/guides/controlling-layout) +- [More Blocks Features](https://www.gradio.app/guides/more-blocks-features) +- [Custom CSS and JS](https://www.gradio.app/guides/custom-CSS-and-JS) +- [Streaming Outputs](https://www.gradio.app/guides/streaming-outputs) +- [Streaming Inputs](https://www.gradio.app/guides/streaming-inputs) +- [Sharing Your App](https://www.gradio.app/guides/sharing-your-app) +- [Custom HTML Components](https://www.gradio.app/guides/custom-HTML-components) +- [Getting Started with the Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) +- [Getting Started with the JS Client](https://www.gradio.app/guides/getting-started-with-the-js-client) + +## Core Patterns + +**Interface** (high-level): wraps a function with input/output components. + +```python +import gradio as gr + +def greet(name): + return f"Hello {name}!" + +gr.Interface(fn=greet, inputs="text", outputs="text").launch() +``` + +**Blocks** (low-level): flexible layout with explicit event wiring. + +```python +import gradio as gr + +with gr.Blocks() as demo: + name = gr.Textbox(label="Name") + output = gr.Textbox(label="Greeting") + btn = gr.Button("Greet") + btn.click(fn=lambda n: f"Hello {n}!", inputs=name, outputs=output) + +demo.launch() +``` + +**ChatInterface**: high-level wrapper for chatbot UIs. + +```python +import gradio as gr + +def respond(message, history): + return f"You said: {message}" + +gr.ChatInterface(fn=respond).launch() +``` + +## Key Component Signatures + +### `Textbox(value: str | I18nData | Callable | None = None, type: Literal['text', 'password', 'email'] = "text", lines: int = 1, max_lines: int | None = None, placeholder: str | I18nData | None = None, label: str | I18nData | None = None, info: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, autofocus: bool = False, autoscroll: bool = True, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", text_align: Literal['left', 'right'] | None = None, rtl: bool = False, buttons: list[Literal['copy'] | Button] | None = None, max_length: int | None = None, submit_btn: str | bool | None = False, stop_btn: str | bool | None = False, html_attributes: InputHTMLAttributes | None = None)` +Creates a textarea for user to enter string input or display string output.. + +### `Number(value: float | Callable | None = None, label: str | I18nData | None = None, placeholder: str | I18nData | None = None, info: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", buttons: list[Button] | None = None, precision: int | None = None, minimum: float | None = None, maximum: float | None = None, step: float = 1)` +Creates a numeric field for user to enter numbers as input or display numeric output.. + +### `Slider(minimum: float = 0, maximum: float = 100, value: float | Callable | None = None, step: float | None = None, precision: int | None = None, label: str | I18nData | None = None, info: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", randomize: bool = False, buttons: list[Literal['reset']] | None = None)` +Creates a slider that ranges from {minimum} to {maximum} with a step size of {step}.. + +### `Checkbox(value: bool | Callable = False, label: str | I18nData | None = None, info: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", buttons: list[Button] | None = None)` +Creates a checkbox that can be set to `True` or `False`. + +### `Dropdown(choices: Sequence[str | int | float | tuple[str, str | int | float]] | None = None, value: str | int | float | Sequence[str | int | float] | Callable | DefaultValue | None = DefaultValue(), type: Literal['value', 'index'] = "value", multiselect: bool | None = None, allow_custom_value: bool = False, max_choices: int | None = None, filterable: bool = True, label: str | I18nData | None = None, info: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", buttons: list[Button] | None = None)` +Creates a dropdown of choices from which a single entry or multiple entries can be selected (as an input component) or displayed (as an output component).. + +### `Radio(choices: Sequence[str | int | float | tuple[str, str | int | float]] | None = None, value: str | int | float | Callable | None = None, type: Literal['value', 'index'] = "value", label: str | I18nData | None = None, info: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", rtl: bool = False, buttons: list[Button] | None = None)` +Creates a set of (string or numeric type) radio buttons of which only one can be selected.. + +### `Image(value: str | PIL.Image.Image | np.ndarray | Callable | None = None, format: str = "webp", height: int | str | None = None, width: int | str | None = None, image_mode: Literal['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | None = "RGB", sources: list[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboard'] | None = None, type: Literal['numpy', 'pil', 'filepath'] = "numpy", label: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, buttons: list[Literal['download', 'share', 'fullscreen'] | Button] | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, streaming: bool = False, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", webcam_options: WebcamOptions | None = None, placeholder: str | None = None, watermark: WatermarkOptions | None = None)` +Creates an image component that can be used to upload images (as an input) or display images (as an output).. + +### `Audio(value: str | Path | tuple[int, np.ndarray] | Callable | None = None, sources: list[Literal['upload', 'microphone']] | Literal['upload', 'microphone'] | None = None, type: Literal['numpy', 'filepath'] = "numpy", label: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, streaming: bool = False, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", format: Literal['wav', 'mp3'] | None = None, autoplay: bool = False, editable: bool = True, buttons: list[Literal['download', 'share'] | Button] | None = None, waveform_options: WaveformOptions | dict | None = None, loop: bool = False, recording: bool = False, subtitles: str | Path | list[dict[str, Any]] | None = None, playback_position: float = 0)` +Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output).. + +### `Video(value: str | Path | Callable | None = None, format: str | None = None, sources: list[Literal['upload', 'webcam']] | Literal['upload', 'webcam'] | None = None, height: int | str | None = None, width: int | str | None = None, label: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", webcam_options: WebcamOptions | None = None, include_audio: bool | None = None, autoplay: bool = False, buttons: list[Literal['download', 'share'] | Button] | None = None, loop: bool = False, streaming: bool = False, watermark: WatermarkOptions | None = None, subtitles: str | Path | list[dict[str, Any]] | None = None, playback_position: float = 0)` +Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output). + +### `File(value: str | list[str] | Callable | None = None, file_count: Literal['single', 'multiple', 'directory'] = "single", file_types: list[str] | None = None, type: Literal['filepath', 'binary'] = "filepath", label: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, height: int | str | float | None = None, interactive: bool | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", allow_reordering: bool = False, buttons: list[Button] | None = None)` +Creates a file component that allows uploading one or more generic files (when used as an input) or displaying generic files or URLs for download (as output). + +### `Chatbot(value: list[MessageDict | Message] | Callable | None = None, label: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, autoscroll: bool = True, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", height: int | str | None = 400, resizable: bool = False, max_height: int | str | None = None, min_height: int | str | None = None, editable: Literal['user', 'all'] | None = None, latex_delimiters: list[dict[str, str | bool]] | None = None, rtl: bool = False, buttons: list[Literal['share', 'copy', 'copy_all'] | Button] | None = None, watermark: str | None = None, avatar_images: tuple[str | Path | None, str | Path | None] | None = None, sanitize_html: bool = True, render_markdown: bool = True, feedback_options: list[str] | tuple[str, ...] | None = ('Like', 'Dislike'), feedback_value: Sequence[str | None] | None = None, line_breaks: bool = True, layout: Literal['panel', 'bubble'] | None = None, placeholder: str | None = None, examples: list[ExampleMessage] | None = None, allow_file_downloads: = True, group_consecutive_messages: bool = True, allow_tags: list[str] | bool = True, reasoning_tags: list[tuple[str, str]] | None = None, like_user_message: bool = False)` +Creates a chatbot that displays user-submitted messages and responses. + +### `Button(value: str | I18nData | Callable = "Run", every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, variant: Literal['primary', 'secondary', 'stop', 'huggingface'] = "secondary", size: Literal['sm', 'md', 'lg'] = "lg", icon: str | Path | None = None, link: str | None = None, link_target: Literal['_self', '_blank', '_parent', '_top'] = "_self", visible: bool | Literal['hidden'] = True, interactive: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", scale: int | None = None, min_width: int | None = None)` +Creates a button that can be assigned arbitrary .click() events. + +### `Markdown(value: str | I18nData | Callable | None = None, label: str | I18nData | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, rtl: bool = False, latex_delimiters: list[dict[str, str | bool]] | None = None, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", sanitize_html: bool = True, line_breaks: bool = False, header_links: bool = False, height: int | str | None = None, max_height: int | str | None = None, min_height: int | str | None = None, buttons: list[Literal['copy']] | None = None, container: bool = False, padding: bool = False)` +Used to render arbitrary Markdown output. + +### `HTML(value: Any | Callable | None = None, label: str | I18nData | None = None, html_template: str = "${value}", css_template: str = "", js_on_load: str | None = "element.addEventListener('click', function() { trigger('click') });", apply_default_css: bool = True, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool = False, visible: bool | Literal['hidden'] = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | tuple[int | str, ...] | None = None, preserved_by_key: list[str] | str | None = "value", min_height: int | None = None, max_height: int | None = None, container: bool = False, padding: bool = False, autoscroll: bool = False, buttons: list[Button] | None = None, props: Any)` +Creates a component with arbitrary HTML. + + +## Custom HTML Components + +If a task requires significant customization of an existing component or a component that doesn't exist in Gradio, you can create one with `gr.HTML`. It supports `html_template` (with `${}` JS expressions and `{{}}` Handlebars syntax), `css_template` for scoped styles, and `js_on_load` for interactivity — where `props.value` updates the component value and `trigger('event_name')` fires Gradio events. For reuse, subclass `gr.HTML` and define `api_info()` for API/MCP support. See the [full guide](https://www.gradio.app/guides/custom-HTML-components). + +Here's an example that shows how to create and use these kinds of components: + +```python +import gradio as gr + +class StarRating(gr.HTML): + def __init__(self, label, value=0, **kwargs): + html_template = """ +

${label} rating:

+ ${Array.from({length: 5}, (_, i) => ``).join('')} + """ + css_template = """ + img { height: 50px; display: inline-block; cursor: pointer; } + .faded { filter: grayscale(100%); opacity: 0.3; } + """ + js_on_load = """ + const imgs = element.querySelectorAll('img'); + imgs.forEach((img, index) => { + img.addEventListener('click', () => { + props.value = index + 1; + }); + }); + """ + super().__init__(value=value, label=label, html_template=html_template, css_template=css_template, js_on_load=js_on_load, **kwargs) + + def api_info(self): + return {"type": "integer", "minimum": 0, "maximum": 5} + + +with gr.Blocks() as demo: + gr.Markdown("# Restaurant Review") + food_rating = StarRating(label="Food", value=3) + service_rating = StarRating(label="Service", value=3) + ambience_rating = StarRating(label="Ambience", value=3) + average_btn = gr.Button("Calculate Average Rating") + rating_output = StarRating(label="Average", value=3) + def calculate_average(food, service, ambience): + return round((food + service + ambience) / 3) + average_btn.click( + fn=calculate_average, + inputs=[food_rating, service_rating, ambience_rating], + outputs=rating_output + ) + +demo.launch() +``` + +## Event Listeners + +All event listeners share the same signature: + +```python +component.event_name( + fn: Callable | None | Literal["decorator"] = "decorator", + inputs: Component | Sequence[Component] | set[Component] | None = None, + outputs: Component | Sequence[Component] | set[Component] | None = None, + api_name: str | None = None, + api_description: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + show_progress_on: Component | Sequence[Component] | None = None, + queue: bool = True, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | Literal[True] | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + api_visibility: Literal["public", "private", "undocumented"] = "public", + time_limit: int | None = None, + stream_every: float = 0.5, + key: int | str | tuple[int | str, ...] | None = None, + validator: Callable | None = None, +) -> Dependency +``` + +Supported events per component: + +- **AnnotatedImage**: select +- **Audio**: stream, change, clear, play, pause, stop, pause, start_recording, pause_recording, stop_recording, upload, input +- **BarPlot**: select, double_click +- **BrowserState**: change +- **Button**: click +- **Chatbot**: change, select, like, retry, undo, example_select, option_select, clear, copy, edit +- **Checkbox**: change, input, select +- **CheckboxGroup**: change, input, select +- **ClearButton**: click +- **Code**: change, input, focus, blur +- **ColorPicker**: change, input, submit, focus, blur +- **Dataframe**: change, input, select, edit +- **Dataset**: click, select +- **DateTime**: change, submit +- **DeepLinkButton**: click +- **Dialogue**: change, input, submit +- **DownloadButton**: click +- **Dropdown**: change, input, select, focus, blur, key_up +- **DuplicateButton**: click +- **File**: change, select, clear, upload, delete, download +- **FileExplorer**: change, input, select +- **Gallery**: select, upload, change, delete, preview_close, preview_open +- **HTML**: change, input, click, double_click, submit, stop, edit, clear, play, pause, end, start_recording, pause_recording, stop_recording, focus, blur, upload, release, select, stream, like, example_select, option_select, load, key_up, apply, delete, tick, undo, retry, expand, collapse, download, copy +- **HighlightedText**: change, select +- **Image**: clear, change, stream, select, upload, input +- **ImageEditor**: clear, change, input, select, upload, apply +- **ImageSlider**: clear, change, stream, select, upload, input +- **JSON**: change +- **Label**: change, select +- **LinePlot**: select, double_click +- **LoginButton**: click +- **Markdown**: change, copy +- **Model3D**: change, upload, edit, clear +- **MultimodalTextbox**: change, input, select, submit, focus, blur, stop +- **Navbar**: change +- **Number**: change, input, submit, focus, blur +- **ParamViewer**: change, upload +- **Plot**: change +- **Radio**: select, change, input +- **ScatterPlot**: select, double_click +- **SimpleImage**: clear, change, upload +- **Slider**: change, input, release +- **State**: change +- **Textbox**: change, input, select, submit, focus, blur, stop, copy +- **Timer**: tick +- **UploadButton**: click, upload +- **Video**: change, clear, start_recording, stop_recording, stop, play, pause, end, upload, input + +## Additional Reference + +- [End-to-End Examples](examples.md) — complete working apps diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..714928efb9bda35408b5c763bae44c47e7949c46 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Gradio" + short_description: "Build and edit Gradio apps, components, and chatbots" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/examples.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/examples.md new file mode 100644 index 0000000000000000000000000000000000000000..b48c4cdc6dddbef128d026c1ec47442ebca51788 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/gradio/examples.md @@ -0,0 +1,613 @@ +# Gradio End-to-End Examples + +Complete working Gradio apps for reference. + +## Blocks Essay Simple + +```python +import gradio as gr + +def change_textbox(choice): + if choice == "short": + return gr.Textbox(lines=2, visible=True) + elif choice == "long": + return gr.Textbox(lines=8, visible=True, value="Lorem ipsum dolor sit amet") + else: + return gr.Textbox(visible=False) + +with gr.Blocks() as demo: + radio = gr.Radio( + ["short", "long", "none"], label="What kind of essay would you like to write?" + ) + text = gr.Textbox(lines=2, interactive=True, buttons=["copy"]) + radio.change(fn=change_textbox, inputs=radio, outputs=text) + +demo.launch() +``` + +## Blocks Flipper + +```python +import numpy as np +import gradio as gr + +def flip_text(x): + return x[::-1] + +def flip_image(x): + return np.fliplr(x) + +with gr.Blocks() as demo: + gr.Markdown("Flip text or image files using this demo.") + with gr.Tab("Flip Text"): + text_input = gr.Textbox() + text_output = gr.Textbox() + text_button = gr.Button("Flip") + with gr.Tab("Flip Image"): + with gr.Row(): + image_input = gr.Image() + image_output = gr.Image() + image_button = gr.Button("Flip") + + with gr.Accordion("Open for More!", open=False): + gr.Markdown("Look at me...") + temp_slider = gr.Slider( + 0, 1, + value=0.1, + step=0.1, + interactive=True, + label="Slide me", + ) + + text_button.click(flip_text, inputs=text_input, outputs=text_output) + image_button.click(flip_image, inputs=image_input, outputs=image_output) + +demo.launch() +``` + +## Blocks Form + +```python +import gradio as gr + +with gr.Blocks() as demo: + name_box = gr.Textbox(label="Name") + age_box = gr.Number(label="Age", minimum=0, maximum=100) + symptoms_box = gr.CheckboxGroup(["Cough", "Fever", "Runny Nose"]) + submit_btn = gr.Button("Submit") + + with gr.Column(visible=False) as output_col: + diagnosis_box = gr.Textbox(label="Diagnosis") + patient_summary_box = gr.Textbox(label="Patient Summary") + + def submit(name, age, symptoms): + return { + submit_btn: gr.Button(visible=False), + output_col: gr.Column(visible=True), + diagnosis_box: "covid" if "Cough" in symptoms else "flu", + patient_summary_box: f"{name}, {age} y/o", + } + + submit_btn.click( + submit, + [name_box, age_box, symptoms_box], + [submit_btn, diagnosis_box, patient_summary_box, output_col], + ) + +demo.launch() +``` + +## Blocks Hello + +```python +import gradio as gr + +def welcome(name): + return f"Welcome to Gradio, {name}!" + +with gr.Blocks() as demo: + gr.Markdown( + """ + # Hello World! + Start typing below to see the output. + """) + inp = gr.Textbox(placeholder="What is your name?") + out = gr.Textbox() + inp.change(welcome, inp, out) + +demo.launch() +``` + +## Blocks Layout + +```python +import gradio as gr + +demo = gr.Blocks() + +with demo: + with gr.Row(): + gr.Image(interactive=True, scale=2) + gr.Image() + with gr.Row(): + gr.Textbox(label="Text") + gr.Number(label="Count", scale=2) + gr.Radio(choices=["One", "Two"]) + with gr.Row(): + gr.Button("500", scale=0, min_width=500) + gr.Button("A", scale=0) + gr.Button("grow") + with gr.Row(): + gr.Textbox() + gr.Textbox() + gr.Button() + with gr.Row(): + with gr.Row(): + with gr.Column(): + gr.Textbox(label="Text") + gr.Number(label="Count") + gr.Radio(choices=["One", "Two"]) + gr.Image() + with gr.Column(): + gr.Image(interactive=True) + gr.Image() + gr.Image() + gr.Textbox(label="Text") + gr.Number(label="Count") + gr.Radio(choices=["One", "Two"]) + +demo.launch() +``` + +## Calculator + +```python +import gradio as gr + +def calculator(num1, operation, num2): + if operation == "add": + return num1 + num2 + elif operation == "subtract": + return num1 - num2 + elif operation == "multiply": + return num1 * num2 + elif operation == "divide": + if num2 == 0: + raise gr.Error("Cannot divide by zero!") + return num1 / num2 + +demo = gr.Interface( + calculator, + [ + "number", + gr.Radio(["add", "subtract", "multiply", "divide"]), + "number" + ], + "number", + examples=[ + [45, "add", 3], + [3.14, "divide", 2], + [144, "multiply", 2.5], + [0, "subtract", 1.2], + ], + title="Toy Calculator", + description="Here's a sample toy calculator.", + api_name="predict" +) + +demo.launch() +``` + +## Chatbot Simple + +```python +import gradio as gr +import random +import time + +with gr.Blocks() as demo: + chatbot = gr.Chatbot() + msg = gr.Textbox() + clear = gr.ClearButton([msg, chatbot]) + + def respond(message, chat_history): + bot_message = random.choice(["How are you?", "Today is a great day", "I'm very hungry"]) + chat_history.append({"role": "user", "content": message}) + chat_history.append({"role": "assistant", "content": bot_message}) + time.sleep(2) + return "", chat_history + + msg.submit(respond, [msg, chatbot], [msg, chatbot]) + +demo.launch() +``` + +## Chatbot Streaming + +```python +import gradio as gr +import random +import time + +with gr.Blocks() as demo: + chatbot = gr.Chatbot() + msg = gr.Textbox() + clear = gr.Button("Clear") + + def user(user_message, history: list): + return "", history + [{"role": "user", "content": user_message}] + + def bot(history: list): + bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"]) + history.append({"role": "assistant", "content": ""}) + for character in bot_message: + history[-1]['content'] += character + time.sleep(0.05) + yield history + + msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then( + bot, chatbot, chatbot + ) + clear.click(lambda: None, None, chatbot, queue=False) + +demo.launch() +``` + +## Custom Css + +```python +import gradio as gr + +with gr.Blocks() as demo: + with gr.Column(elem_classes="cool-col"): + gr.Markdown("### Gradio Demo with Custom CSS", elem_classes="darktest") + gr.Markdown( + elem_classes="markdown", + value="Resize the browser window to see the CSS media query in action.", + ) + +if __name__ == "__main__": + demo.launch(css_paths=["demo/custom_css/custom_css.css"]) +``` + +## Fake Diffusion + +```python +import gradio as gr +import numpy as np +import time + +def fake_diffusion(steps): + rng = np.random.default_rng() + for i in range(steps): + time.sleep(1) + image = rng.random(size=(600, 600, 3)) + yield image + image = np.ones((1000,1000,3), np.uint8) + image[:] = [255, 124, 0] + yield image + +demo = gr.Interface(fake_diffusion, + inputs=gr.Slider(1, 10, 3, step=1), + outputs="image", + api_name="predict") + +demo.launch() +``` + +## Hello World + +```python +import gradio as gr + + +def greet(name): + return "Hello " + name + "!" + + +demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox", api_name="predict") + +demo.launch() +``` + +## Image Editor + +```python +import gradio as gr +import time + + +def sleep(im): + time.sleep(5) + return [im["background"], im["layers"][0], im["layers"][1], im["composite"]] + + +def predict(im): + return im["composite"] + + +with gr.Blocks() as demo: + with gr.Row(): + im = gr.ImageEditor( + type="numpy", + ) + im_preview = gr.Image() + n_upload = gr.Number(0, label="Number of upload events", step=1) + n_change = gr.Number(0, label="Number of change events", step=1) + n_input = gr.Number(0, label="Number of input events", step=1) + + im.upload(lambda x: x + 1, outputs=n_upload, inputs=n_upload) + im.change(lambda x: x + 1, outputs=n_change, inputs=n_change) + im.input(lambda x: x + 1, outputs=n_input, inputs=n_input) + im.change(predict, outputs=im_preview, inputs=im, show_progress="hidden") + +demo.launch() +``` + +## On Listener Decorator + +```python +import gradio as gr + +with gr.Blocks() as demo: + name = gr.Textbox(label="Name") + output = gr.Textbox(label="Output Box") + greet_btn = gr.Button("Greet") + + @gr.on(triggers=[name.submit, greet_btn.click], inputs=name, outputs=output) + def greet(name): + return "Hello " + name + "!" + +demo.launch() +``` + +## Render Merge + +```python +import gradio as gr +import time + +with gr.Blocks() as demo: + text_count = gr.Slider(1, 5, value=1, step=1, label="Textbox Count") + + @gr.render(inputs=text_count) + def render_count(count): + boxes = [] + for i in range(count): + box = gr.Textbox(label=f"Box {i}") + boxes.append(box) + + def merge(*args): + time.sleep(0.2) # simulate a delay + return " ".join(args) + + merge_btn.click(merge, boxes, output) + + def clear(): + time.sleep(0.2) # simulate a delay + return [" "] * count + + clear_btn.click(clear, None, boxes) + + def countup(): + time.sleep(0.2) # simulate a delay + return list(range(count)) + + count_btn.click(countup, None, boxes, queue=False) + + with gr.Row(): + merge_btn = gr.Button("Merge") + clear_btn = gr.Button("Clear") + count_btn = gr.Button("Count") + + output = gr.Textbox() + +demo.launch() +``` + +## Reverse Audio 2 + +```python +import gradio as gr +import numpy as np + +def reverse_audio(audio): + sr, data = audio + return (sr, np.flipud(data)) + +demo = gr.Interface(fn=reverse_audio, + inputs="microphone", + outputs="audio", api_name="predict") + +demo.launch() +``` + +## Sepia Filter + +```python +import numpy as np +import gradio as gr + +def sepia(input_img): + sepia_filter = np.array([ + [0.393, 0.769, 0.189], + [0.349, 0.686, 0.168], + [0.272, 0.534, 0.131] + ]) + sepia_img = input_img.dot(sepia_filter.T) + sepia_img /= sepia_img.max() + return sepia_img + +demo = gr.Interface(sepia, gr.Image(), "image", api_name="predict") +demo.launch() +``` + +## Sort Records + +```python +import gradio as gr + +def sort_records(records): + return records.sort("Quantity") + +demo = gr.Interface( + sort_records, + gr.Dataframe( + headers=["Item", "Quantity"], + datatype=["str", "number"], + row_count=3, + column_count=2, + column_limits=(2, 2), + type="polars" + ), + "dataframe", + description="Sort by Quantity" +) + +demo.launch() +``` + +## Streaming Simple + +```python +import gradio as gr + +with gr.Blocks() as demo: + with gr.Row(): + with gr.Column(): + input_img = gr.Image(label="Input", sources="webcam") + with gr.Column(): + output_img = gr.Image(label="Output") + input_img.stream(lambda s: s, input_img, output_img, time_limit=15, stream_every=0.1, concurrency_limit=30) + +if __name__ == "__main__": + + demo.launch() +``` + +## Tabbed Interface Lite + +```python +import gradio as gr + +hello_world = gr.Interface(lambda name: "Hello " + name, "text", "text", api_name="predict") +bye_world = gr.Interface(lambda name: "Bye " + name, "text", "text", api_name="predict") +chat = gr.ChatInterface(lambda *args: "Hello " + args[0], api_name="chat") + +demo = gr.TabbedInterface([hello_world, bye_world, chat], ["Hello World", "Bye World", "Chat"]) + +demo.launch() +``` + +## Tax Calculator + +```python +import gradio as gr + +def tax_calculator(income, marital_status, assets): + tax_brackets = [(10, 0), (25, 8), (60, 12), (120, 20), (250, 30)] + total_deductible = sum(cost for cost, deductible in zip(assets["Cost"], assets["Deductible"]) if deductible) + taxable_income = income - total_deductible + + total_tax = 0 + for bracket, rate in tax_brackets: + if taxable_income > bracket: + total_tax += (taxable_income - bracket) * rate / 100 + + if marital_status == "Married": + total_tax *= 0.75 + elif marital_status == "Divorced": + total_tax *= 0.8 + + return round(total_tax) + +demo = gr.Interface( + tax_calculator, + [ + "number", + gr.Radio(["Single", "Married", "Divorced"]), + gr.Dataframe( + headers=["Item", "Cost", "Deductible"], + datatype=["str", "number", "bool"], + label="Assets Purchased this Year", + ), + ], + gr.Number(label="Tax due"), + examples=[ + [10000, "Married", [["Suit", 5000, True], ["Laptop (for work)", 800, False], ["Car", 1800, True]]], + [80000, "Single", [["Suit", 800, True], ["Watch", 1800, True], ["Food", 800, True]]], + ], + live=True, + api_name="predict" +) + +demo.launch() +``` + +## Timer Simple + +```python +import gradio as gr +import random +import time + +with gr.Blocks() as demo: + timer = gr.Timer(1) + timestamp = gr.Number(label="Time") + timer.tick(lambda: round(time.time()), outputs=timestamp, api_name="timestamp") + + number = gr.Number(lambda: random.randint(1, 10), every=timer, label="Random Number") + with gr.Row(): + gr.Button("Start").click(lambda: gr.Timer(active=True), None, timer) + gr.Button("Stop").click(lambda: gr.Timer(active=False), None, timer) + gr.Button("Go Fast").click(lambda: 0.2, None, timer) + +if __name__ == "__main__": + demo.launch() +``` + +## Variable Outputs + +```python +import gradio as gr + +max_textboxes = 10 + +def variable_outputs(k): + k = int(k) + return [gr.Textbox(visible=True)]*k + [gr.Textbox(visible=False)]*(max_textboxes-k) + +with gr.Blocks() as demo: + s = gr.Slider(1, max_textboxes, value=max_textboxes, step=1, label="How many textboxes to show:") + textboxes = [] + for i in range(max_textboxes): + t = gr.Textbox(f"Textbox {i}") + textboxes.append(t) + + s.change(variable_outputs, s, textboxes) + +if __name__ == "__main__": + demo.launch() +``` + +## Video Identity + +```python +import gradio as gr +from gradio.media import get_video + +def video_identity(video): + return video + +# get_video() returns file paths to sample media included with Gradio +demo = gr.Interface(video_identity, + gr.Video(), + "playable_video", + examples=[ + get_video("world.mp4") + ], + cache_examples=True, + api_name="predict",) + +demo.launch() +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..30a49c199ecfd898b9178ae3dab6d2597d247247 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/SKILL.md @@ -0,0 +1,1042 @@ +--- +name: huggingface-jobs +description: This skill should be used when users want to run any workload on Hugging Face Jobs infrastructure. Covers UV scripts, Docker-based jobs, hardware selection, cost estimation, authentication with tokens, secrets management, timeout configuration, and result persistence. Designed for general-purpose compute workloads including data processing, inference, experiments, batch jobs, and any Python-based tasks. Should be invoked for tasks involving cloud compute, GPU workloads, or when users mention running jobs on Hugging Face infrastructure without local setup. +--- + +# Running Workloads on Hugging Face Jobs + +## Overview + +Run any workload on fully managed Hugging Face infrastructure. No local setup required—jobs run on cloud CPUs, GPUs, or TPUs and can persist results to the Hugging Face Hub. + +**Common use cases:** +- **Data Processing** - Transform, filter, or analyze large datasets +- **Batch Inference** - Run inference on thousands of samples +- **Experiments & Benchmarks** - Reproducible ML experiments +- **Model Training** - Fine-tune models (see `model-trainer` skill for TRL-specific training) +- **Synthetic Data Generation** - Generate datasets using LLMs +- **Development & Testing** - Test code without local GPU setup +- **Scheduled Jobs** - Automate recurring tasks + +**For model training specifically:** See the `model-trainer` skill for TRL-based training workflows. + +## When to Use This Skill + +Use this skill when users want to: +- Run Python workloads on cloud infrastructure +- Execute jobs without local GPU/TPU setup +- Process data at scale +- Run batch inference or experiments +- Schedule recurring tasks +- Use GPUs/TPUs for any workload +- Persist results to the Hugging Face Hub + +## Key Directives + +When assisting with jobs: + +1. **ALWAYS use `hf_jobs()` MCP tool** - Submit jobs using `hf_jobs("uv", {...})` or `hf_jobs("run", {...})`. The `script` parameter accepts Python code directly. Do NOT save to local files unless the user explicitly requests it. Pass the script content as a string to `hf_jobs()`. + +2. **Always handle authentication** - Jobs that interact with the Hub require `HF_TOKEN` via secrets. See Token Usage section below. + +3. **Provide job details after submission** - After submitting, provide job ID, monitoring URL, estimated time, and note that the user can request status checks later. + +4. **Set appropriate timeouts** - Default 30min may be insufficient for long-running tasks. + +## Prerequisites Checklist + +Before starting any job, verify: + +### ✅ **Account & Authentication** +- Hugging Face Account with [Pro](https://hf.co/pro), [Team](https://hf.co/enterprise), or [Enterprise](https://hf.co/enterprise) plan (Jobs require paid plan) +- Authenticated login: Check with `hf_whoami()` +- **HF_TOKEN for Hub Access** ⚠️ CRITICAL - Required for any Hub operations (push models/datasets, download private repos, etc.) +- Token must have appropriate permissions (read for downloads, write for uploads) + +### ✅ **Token Usage** (See Token Usage section for details) + +**When tokens are required:** +- Pushing models/datasets to Hub +- Accessing private repositories +- Using Hub APIs in scripts +- Any authenticated Hub operations + +**How to provide tokens:** +```python +# hf_jobs MCP tool — $HF_TOKEN is auto-replaced with real token: +{"secrets": {"HF_TOKEN": "$HF_TOKEN"}} + +# HfApi().run_uv_job() — MUST pass actual token: +from huggingface_hub import get_token +secrets={"HF_TOKEN": get_token()} +``` + +**⚠️ CRITICAL:** The `$HF_TOKEN` placeholder is ONLY auto-replaced by the `hf_jobs` MCP tool. When using `HfApi().run_uv_job()`, you MUST pass the real token via `get_token()`. Passing the literal string `"$HF_TOKEN"` results in a 9-character invalid token and 401 errors. + +## Token Usage Guide + +### Understanding Tokens + +**What are HF Tokens?** +- Authentication credentials for Hugging Face Hub +- Required for authenticated operations (push, private repos, API access) +- Stored securely on your machine after `hf auth login` + +**Token Types:** +- **Read Token** - Can download models/datasets, read private repos +- **Write Token** - Can push models/datasets, create repos, modify content +- **Organization Token** - Can act on behalf of an organization + +### When Tokens Are Required + +**Always Required:** +- Pushing models/datasets to Hub +- Accessing private repositories +- Creating new repositories +- Modifying existing repositories +- Using Hub APIs programmatically + +**Not Required:** +- Downloading public models/datasets +- Running jobs that don't interact with Hub +- Reading public repository information + +### How to Provide Tokens to Jobs + +#### Method 1: Automatic Token (Recommended) + +```python +hf_jobs("uv", { + "script": "your_script.py", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Automatic replacement +}) +``` + +**How it works:** +- `$HF_TOKEN` is a placeholder that gets replaced with your actual token +- Uses the token from your logged-in session (`hf auth login`) +- Most secure and convenient method +- Token is encrypted server-side when passed as a secret + +**Benefits:** +- No token exposure in code +- Uses your current login session +- Automatically updated if you re-login +- Works seamlessly with MCP tools + +#### Method 2: Explicit Token (Not Recommended) + +```python +hf_jobs("uv", { + "script": "your_script.py", + "secrets": {"HF_TOKEN": "hf_abc123..."} # ⚠️ Hardcoded token +}) +``` + +**When to use:** +- Only if automatic token doesn't work +- Testing with a specific token +- Organization tokens (use with caution) + +**Security concerns:** +- Token visible in code/logs +- Must manually update if token rotates +- Risk of token exposure + +#### Method 3: Environment Variable (Less Secure) + +```python +hf_jobs("uv", { + "script": "your_script.py", + "env": {"HF_TOKEN": "hf_abc123..."} # ⚠️ Less secure than secrets +}) +``` + +**Difference from secrets:** +- `env` variables are visible in job logs +- `secrets` are encrypted server-side +- Always prefer `secrets` for tokens + +### Using Tokens in Scripts + +**In your Python script, tokens are available as environment variables:** + +```python +# /// script +# dependencies = ["huggingface-hub"] +# /// + +import os +from huggingface_hub import HfApi + +# Token is automatically available if passed via secrets +token = os.environ.get("HF_TOKEN") + +# Use with Hub API +api = HfApi(token=token) + +# Or let huggingface_hub auto-detect +api = HfApi() # Automatically uses HF_TOKEN env var +``` + +**Best practices:** +- Don't hardcode tokens in scripts +- Use `os.environ.get("HF_TOKEN")` to access +- Let `huggingface_hub` auto-detect when possible +- Verify token exists before Hub operations + +### Token Verification + +**Check if you're logged in:** +```python +from huggingface_hub import whoami +user_info = whoami() # Returns your username if authenticated +``` + +**Verify token in job:** +```python +import os +assert "HF_TOKEN" in os.environ, "HF_TOKEN not found!" +token = os.environ["HF_TOKEN"] +print(f"Token starts with: {token[:7]}...") # Should start with "hf_" +``` + +### Common Token Issues + +**Error: 401 Unauthorized** +- **Cause:** Token missing or invalid +- **Fix:** Add `secrets={"HF_TOKEN": "$HF_TOKEN"}` to job config +- **Verify:** Check `hf_whoami()` works locally + +**Error: 403 Forbidden** +- **Cause:** Token lacks required permissions +- **Fix:** Ensure token has write permissions for push operations +- **Check:** Token type at https://huggingface.co/settings/tokens + +**Error: Token not found in environment** +- **Cause:** `secrets` not passed or wrong key name +- **Fix:** Use `secrets={"HF_TOKEN": "$HF_TOKEN"}` (not `env`) +- **Verify:** Script checks `os.environ.get("HF_TOKEN")` + +**Error: Repository access denied** +- **Cause:** Token doesn't have access to private repo +- **Fix:** Use token from account with access +- **Check:** Verify repo visibility and your permissions + +### Token Security Best Practices + +1. **Never commit tokens** - Use `$HF_TOKEN` placeholder or environment variables +2. **Use secrets, not env** - Secrets are encrypted server-side +3. **Rotate tokens regularly** - Generate new tokens periodically +4. **Use minimal permissions** - Create tokens with only needed permissions +5. **Don't share tokens** - Each user should use their own token +6. **Monitor token usage** - Check token activity in Hub settings + +### Complete Token Example + +```python +# Example: Push results to Hub +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["huggingface-hub", "datasets"] +# /// + +import os +from huggingface_hub import HfApi +from datasets import Dataset + +# Verify token is available +assert "HF_TOKEN" in os.environ, "HF_TOKEN required!" + +# Use token for Hub operations +api = HfApi(token=os.environ["HF_TOKEN"]) + +# Create and push dataset +data = {"text": ["Hello", "World"]} +dataset = Dataset.from_dict(data) +dataset.push_to_hub("username/my-dataset", token=os.environ["HF_TOKEN"]) + +print("✅ Dataset pushed successfully!") +""", + "flavor": "cpu-basic", + "timeout": "30m", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Token provided securely +}) +``` + +## Quick Start: Two Approaches + +### Approach 1: UV Scripts (Recommended) + +UV scripts use PEP 723 inline dependencies for clean, self-contained workloads. + +**MCP Tool:** +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["transformers", "torch"] +# /// + +from transformers import pipeline +import torch + +# Your workload here +classifier = pipeline("sentiment-analysis") +result = classifier("I love Hugging Face!") +print(result) +""", + "flavor": "cpu-basic", + "timeout": "30m" +}) +``` + +**CLI Equivalent:** +```bash +hf jobs uv run my_script.py --flavor cpu-basic --timeout 30m +``` + +**Python API:** +```python +from huggingface_hub import run_uv_job +run_uv_job("my_script.py", flavor="cpu-basic", timeout="30m") +``` + +**Benefits:** Direct MCP tool usage, clean code, dependencies declared inline, no file saving required + +**When to use:** Default choice for all workloads, custom logic, any scenario requiring `hf_jobs()` + +#### Custom Docker Images for UV Scripts + +By default, UV scripts use `ghcr.io/astral-sh/uv:python3.12-bookworm-slim`. For ML workloads with complex dependencies, use pre-built images: + +```python +hf_jobs("uv", { + "script": "inference.py", + "image": "vllm/vllm-openai:latest", # Pre-built image with vLLM + "flavor": "a10g-large" +}) +``` + +**CLI:** +```bash +hf jobs uv run --image vllm/vllm-openai:latest --flavor a10g-large inference.py +``` + +**Benefits:** Faster startup, pre-installed dependencies, optimized for specific frameworks + +#### Python Version + +By default, UV scripts use Python 3.12. Specify a different version: + +```python +hf_jobs("uv", { + "script": "my_script.py", + "python": "3.11", # Use Python 3.11 + "flavor": "cpu-basic" +}) +``` + +**Python API:** +```python +from huggingface_hub import run_uv_job +run_uv_job("my_script.py", python="3.11") +``` + +#### Working with Scripts + +⚠️ **Important:** There are *two* "script path" stories depending on how you run Jobs: + +- **Using the `hf_jobs()` MCP tool (recommended in this repo)**: the `script` value must be **inline code** (a string) or a **URL**. A local filesystem path (like `"./scripts/foo.py"`) won't exist inside the remote container. +- **Using the `hf jobs uv run` CLI**: local file paths **do work** (the CLI uploads your script). + +**Common mistake with `hf_jobs()` MCP tool:** + +```python +# ❌ Will fail (remote container can't see your local path) +hf_jobs("uv", {"script": "./scripts/foo.py"}) +``` + +**Correct patterns with `hf_jobs()` MCP tool:** + +```python +# ✅ Inline: read the local script file and pass its *contents* +from pathlib import Path +script = Path("jobs/scripts/foo.py").read_text() +hf_jobs("uv", {"script": script}) + +# ✅ URL: host the script somewhere reachable +hf_jobs("uv", {"script": "https://huggingface.co/datasets/uv-scripts/.../raw/main/foo.py"}) + +# ✅ URL from GitHub +hf_jobs("uv", {"script": "https://raw.githubusercontent.com/huggingface/trl/main/trl/scripts/sft.py"}) +``` + +**CLI equivalent (local paths supported):** + +```bash +hf jobs uv run ./scripts/foo.py -- --your --args +``` + +#### Adding Dependencies at Runtime + +Add extra dependencies beyond what's in the PEP 723 header: + +```python +hf_jobs("uv", { + "script": "inference.py", + "dependencies": ["transformers", "torch>=2.0"], # Extra deps + "flavor": "a10g-small" +}) +``` + +**Python API:** +```python +from huggingface_hub import run_uv_job +run_uv_job("inference.py", dependencies=["transformers", "torch>=2.0"]) +``` + +### Approach 2: Docker-Based Jobs + +Run jobs with custom Docker images and commands. + +**MCP Tool:** +```python +hf_jobs("run", { + "image": "python:3.12", + "command": ["python", "-c", "print('Hello from HF Jobs!')"], + "flavor": "cpu-basic", + "timeout": "30m" +}) +``` + +**CLI Equivalent:** +```bash +hf jobs run python:3.12 python -c "print('Hello from HF Jobs!')" +``` + +**Python API:** +```python +from huggingface_hub import run_job +run_job(image="python:3.12", command=["python", "-c", "print('Hello!')"], flavor="cpu-basic") +``` + +**Benefits:** Full Docker control, use pre-built images, run any command +**When to use:** Need specific Docker images, non-Python workloads, complex environments + +**Example with GPU:** +```python +hf_jobs("run", { + "image": "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel", + "command": ["python", "-c", "import torch; print(torch.cuda.get_device_name())"], + "flavor": "a10g-small", + "timeout": "1h" +}) +``` + +**Using Hugging Face Spaces as Images:** + +You can use Docker images from HF Spaces: +```python +hf_jobs("run", { + "image": "hf.co/spaces/lhoestq/duckdb", # Space as Docker image + "command": ["duckdb", "-c", "SELECT 'Hello from DuckDB!'"], + "flavor": "cpu-basic" +}) +``` + +**CLI:** +```bash +hf jobs run hf.co/spaces/lhoestq/duckdb duckdb -c "SELECT 'Hello!'" +``` + +### Finding More UV Scripts on Hub + +The `uv-scripts` organization provides ready-to-use UV scripts stored as datasets on Hugging Face Hub: + +```python +# Discover available UV script collections +dataset_search({"author": "uv-scripts", "sort": "downloads", "limit": 20}) + +# Explore a specific collection +hub_repo_details(["uv-scripts/classification"], repo_type="dataset", include_readme=True) +``` + +**Popular collections:** OCR, classification, synthetic-data, vLLM, dataset-creation + +## Hardware Selection + +> **Reference:** [HF Jobs Hardware Docs](https://huggingface.co/docs/hub/en/spaces-config-reference) (updated 07/2025) + +| Workload Type | Recommended Hardware | Use Case | +|---------------|---------------------|----------| +| Data processing, testing | `cpu-basic`, `cpu-upgrade` | Lightweight tasks | +| Small models, demos | `t4-small` | <1B models, quick tests | +| Medium models | `t4-medium`, `l4x1` | 1-7B models | +| Large models, production | `a10g-small`, `a10g-large` | 7-13B models | +| Very large models | `a100-large` | 13B+ models | +| Batch inference | `a10g-large`, `a100-large` | High-throughput | +| Multi-GPU workloads | `l4x4`, `a10g-largex2`, `a10g-largex4` | Parallel/large models | +| TPU workloads | `v5e-1x1`, `v5e-2x2`, `v5e-2x4` | JAX/Flax, TPU-optimized | + +**All Available Flavors:** +- **CPU:** `cpu-basic`, `cpu-upgrade` +- **GPU:** `t4-small`, `t4-medium`, `l4x1`, `l4x4`, `a10g-small`, `a10g-large`, `a10g-largex2`, `a10g-largex4`, `a100-large` +- **TPU:** `v5e-1x1`, `v5e-2x2`, `v5e-2x4` + +**Guidelines:** +- Start with smaller hardware for testing +- Scale up based on actual needs +- Use multi-GPU for parallel workloads or large models +- Use TPUs for JAX/Flax workloads +- See `references/hardware_guide.md` for detailed specifications + +## Critical: Saving Results + +**⚠️ EPHEMERAL ENVIRONMENT—MUST PERSIST RESULTS** + +The Jobs environment is temporary. All files are deleted when the job ends. If results aren't persisted, **ALL WORK IS LOST**. + +### Persistence Options + +**1. Push to Hugging Face Hub (Recommended)** + +```python +# Push models +model.push_to_hub("username/model-name", token=os.environ["HF_TOKEN"]) + +# Push datasets +dataset.push_to_hub("username/dataset-name", token=os.environ["HF_TOKEN"]) + +# Push artifacts +api.upload_file( + path_or_fileobj="results.json", + path_in_repo="results.json", + repo_id="username/results", + token=os.environ["HF_TOKEN"] +) +``` + +**2. Use External Storage** + +```python +# Upload to S3, GCS, etc. +import boto3 +s3 = boto3.client('s3') +s3.upload_file('results.json', 'my-bucket', 'results.json') +``` + +**3. Send Results via API** + +```python +# POST results to your API +import requests +requests.post("https://your-api.com/results", json=results) +``` + +### Required Configuration for Hub Push + +**In job submission:** +```python +# hf_jobs MCP tool: +{"secrets": {"HF_TOKEN": "$HF_TOKEN"}} # auto-replaced + +# HfApi().run_uv_job(): +from huggingface_hub import get_token +secrets={"HF_TOKEN": get_token()} # must pass real token +``` + +**In script:** +```python +import os +from huggingface_hub import HfApi + +# Token automatically available from secrets +api = HfApi(token=os.environ.get("HF_TOKEN")) + +# Push your results +api.upload_file(...) +``` + +### Verification Checklist + +Before submitting: +- [ ] Results persistence method chosen +- [ ] Token in secrets if using Hub (MCP: `"$HF_TOKEN"`, Python API: `get_token()`) +- [ ] Script handles missing token gracefully +- [ ] Test persistence path works + +**See:** `references/hub_saving.md` for detailed Hub persistence guide + +## Timeout Management + +**⚠️ DEFAULT: 30 MINUTES** + +Jobs automatically stop after the timeout. For long-running tasks like training, always set a custom timeout. + +### Setting Timeouts + +**MCP Tool:** +```python +{ + "timeout": "2h" # 2 hours +} +``` + +**Supported formats:** +- Integer/float: seconds (e.g., `300` = 5 minutes) +- String with suffix: `"5m"` (minutes), `"2h"` (hours), `"1d"` (days) +- Examples: `"90m"`, `"2h"`, `"1.5h"`, `300`, `"1d"` + +**Python API:** +```python +from huggingface_hub import run_job, run_uv_job + +run_job(image="python:3.12", command=[...], timeout="2h") +run_uv_job("script.py", timeout=7200) # 2 hours in seconds +``` + +### Timeout Guidelines + +| Scenario | Recommended | Notes | +|----------|-------------|-------| +| Quick test | 10-30 min | Verify setup | +| Data processing | 1-2 hours | Depends on data size | +| Batch inference | 2-4 hours | Large batches | +| Experiments | 4-8 hours | Multiple runs | +| Long-running | 8-24 hours | Production workloads | + +**Always add 20-30% buffer** for setup, network delays, and cleanup. + +**On timeout:** Job killed immediately, all unsaved progress lost + +## Cost Estimation + +**General guidelines:** + +``` +Total Cost = (Hours of runtime) × (Cost per hour) +``` + +**Example calculations:** + +**Quick test:** +- Hardware: cpu-basic ($0.10/hour) +- Time: 15 minutes (0.25 hours) +- Cost: $0.03 + +**Data processing:** +- Hardware: l4x1 ($2.50/hour) +- Time: 2 hours +- Cost: $5.00 + +**Batch inference:** +- Hardware: a10g-large ($5/hour) +- Time: 4 hours +- Cost: $20.00 + +**Cost optimization tips:** +1. Start small - Test on cpu-basic or t4-small +2. Monitor runtime - Set appropriate timeouts +3. Use checkpoints - Resume if job fails +4. Optimize code - Reduce unnecessary compute +5. Choose right hardware - Don't over-provision + +## Monitoring and Tracking + +### Check Job Status + +**MCP Tool:** +```python +# List all jobs +hf_jobs("ps") + +# Inspect specific job +hf_jobs("inspect", {"job_id": "your-job-id"}) + +# View logs +hf_jobs("logs", {"job_id": "your-job-id"}) + +# Cancel a job +hf_jobs("cancel", {"job_id": "your-job-id"}) +``` + +**Python API:** +```python +from huggingface_hub import list_jobs, inspect_job, fetch_job_logs, cancel_job + +# List your jobs +jobs = list_jobs() + +# List running jobs only +running = [j for j in list_jobs() if j.status.stage == "RUNNING"] + +# Inspect specific job +job_info = inspect_job(job_id="your-job-id") + +# View logs +for log in fetch_job_logs(job_id="your-job-id"): + print(log) + +# Cancel a job +cancel_job(job_id="your-job-id") +``` + +**CLI:** +```bash +hf jobs ps # List jobs +hf jobs logs # View logs +hf jobs cancel # Cancel job +``` + +**Remember:** Wait for user to request status checks. Avoid polling repeatedly. + +### Job URLs + +After submission, jobs have monitoring URLs: +``` +https://huggingface.co/jobs/username/job-id +``` + +View logs, status, and details in the browser. + +### Wait for Multiple Jobs + +```python +import time +from huggingface_hub import inspect_job, run_job + +# Run multiple jobs +jobs = [run_job(image=img, command=cmd) for img, cmd in workloads] + +# Wait for all to complete +for job in jobs: + while inspect_job(job_id=job.id).status.stage not in ("COMPLETED", "ERROR"): + time.sleep(10) +``` + +## Scheduled Jobs + +Run jobs on a schedule using CRON expressions or predefined schedules. + +**MCP Tool:** +```python +# Schedule a UV script that runs every hour +hf_jobs("scheduled uv", { + "script": "your_script.py", + "schedule": "@hourly", + "flavor": "cpu-basic" +}) + +# Schedule with CRON syntax +hf_jobs("scheduled uv", { + "script": "your_script.py", + "schedule": "0 9 * * 1", # 9 AM every Monday + "flavor": "cpu-basic" +}) + +# Schedule a Docker-based job +hf_jobs("scheduled run", { + "image": "python:3.12", + "command": ["python", "-c", "print('Scheduled!')"], + "schedule": "@daily", + "flavor": "cpu-basic" +}) +``` + +**Python API:** +```python +from huggingface_hub import create_scheduled_job, create_scheduled_uv_job + +# Schedule a Docker job +create_scheduled_job( + image="python:3.12", + command=["python", "-c", "print('Running on schedule!')"], + schedule="@hourly" +) + +# Schedule a UV script +create_scheduled_uv_job("my_script.py", schedule="@daily", flavor="cpu-basic") + +# Schedule with GPU +create_scheduled_uv_job( + "ml_inference.py", + schedule="0 */6 * * *", # Every 6 hours + flavor="a10g-small" +) +``` + +**Available schedules:** +- `@annually`, `@yearly` - Once per year +- `@monthly` - Once per month +- `@weekly` - Once per week +- `@daily` - Once per day +- `@hourly` - Once per hour +- CRON expression - Custom schedule (e.g., `"*/5 * * * *"` for every 5 minutes) + +**Manage scheduled jobs:** +```python +# MCP Tool +hf_jobs("scheduled ps") # List scheduled jobs +hf_jobs("scheduled inspect", {"job_id": "..."}) # Inspect details +hf_jobs("scheduled suspend", {"job_id": "..."}) # Pause +hf_jobs("scheduled resume", {"job_id": "..."}) # Resume +hf_jobs("scheduled delete", {"job_id": "..."}) # Delete +``` + +**Python API for management:** +```python +from huggingface_hub import ( + list_scheduled_jobs, + inspect_scheduled_job, + suspend_scheduled_job, + resume_scheduled_job, + delete_scheduled_job +) + +# List all scheduled jobs +scheduled = list_scheduled_jobs() + +# Inspect a scheduled job +info = inspect_scheduled_job(scheduled_job_id) + +# Suspend (pause) a scheduled job +suspend_scheduled_job(scheduled_job_id) + +# Resume a scheduled job +resume_scheduled_job(scheduled_job_id) + +# Delete a scheduled job +delete_scheduled_job(scheduled_job_id) +``` + +## Webhooks: Trigger Jobs on Events + +Trigger jobs automatically when changes happen in Hugging Face repositories. + +**Python API:** +```python +from huggingface_hub import create_webhook + +# Create webhook that triggers a job when a repo changes +webhook = create_webhook( + job_id=job.id, + watched=[ + {"type": "user", "name": "your-username"}, + {"type": "org", "name": "your-org-name"} + ], + domains=["repo", "discussion"], + secret="your-secret" +) +``` + +**How it works:** +1. Webhook listens for changes in watched repositories +2. When triggered, the job runs with `WEBHOOK_PAYLOAD` environment variable +3. Your script can parse the payload to understand what changed + +**Use cases:** +- Auto-process new datasets when uploaded +- Trigger inference when models are updated +- Run tests when code changes +- Generate reports on repository activity + +**Access webhook payload in script:** +```python +import os +import json + +payload = json.loads(os.environ.get("WEBHOOK_PAYLOAD", "{}")) +print(f"Event type: {payload.get('event', {}).get('action')}") +``` + +See [Webhooks Documentation](https://huggingface.co/docs/huggingface_hub/guides/webhooks) for more details. + +## Common Workload Patterns + +This repository ships ready-to-run UV scripts in `jobs/scripts/`. Prefer using them instead of inventing new templates. + +### Pattern 1: Dataset → Model Responses (vLLM) — `scripts/generate-responses.py` + +**What it does:** loads a Hub dataset (chat `messages` or a `prompt` column), applies a model chat template, generates responses with vLLM, and **pushes** the output dataset + dataset card back to the Hub. + +**Requires:** GPU + **write** token (it pushes a dataset). + +```python +from pathlib import Path + +script = Path("jobs/scripts/generate-responses.py").read_text() +hf_jobs("uv", { + "script": script, + "script_args": [ + "username/input-dataset", + "username/output-dataset", + "--messages-column", "messages", + "--model-id", "Qwen/Qwen3-30B-A3B-Instruct-2507", + "--temperature", "0.7", + "--top-p", "0.8", + "--max-tokens", "2048", + ], + "flavor": "a10g-large", + "timeout": "4h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"}, +}) +``` + +### Pattern 2: CoT Self-Instruct Synthetic Data — `scripts/cot-self-instruct.py` + +**What it does:** generates synthetic prompts/answers via CoT Self-Instruct, optionally filters outputs (answer-consistency / RIP), then **pushes** the generated dataset + dataset card to the Hub. + +**Requires:** GPU + **write** token (it pushes a dataset). + +```python +from pathlib import Path + +script = Path("jobs/scripts/cot-self-instruct.py").read_text() +hf_jobs("uv", { + "script": script, + "script_args": [ + "--seed-dataset", "davanstrien/s1k-reasoning", + "--output-dataset", "username/synthetic-math", + "--task-type", "reasoning", + "--num-samples", "5000", + "--filter-method", "answer-consistency", + ], + "flavor": "l4x4", + "timeout": "8h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"}, +}) +``` + +### Pattern 3: Streaming Dataset Stats (Polars + HF Hub) — `scripts/finepdfs-stats.py` + +**What it does:** scans parquet directly from Hub (no 300GB download), computes temporal stats, and (optionally) uploads results to a Hub dataset repo. + +**Requires:** CPU is often enough; token needed **only** if you pass `--output-repo` (upload). + +```python +from pathlib import Path + +script = Path("jobs/scripts/finepdfs-stats.py").read_text() +hf_jobs("uv", { + "script": script, + "script_args": [ + "--limit", "10000", + "--show-plan", + "--output-repo", "username/finepdfs-temporal-stats", + ], + "flavor": "cpu-upgrade", + "timeout": "2h", + "env": {"HF_XET_HIGH_PERFORMANCE": "1"}, + "secrets": {"HF_TOKEN": "$HF_TOKEN"}, +}) +``` + +## Common Failure Modes + +### Out of Memory (OOM) + +**Fix:** +1. Reduce batch size or data chunk size +2. Process data in smaller batches +3. Upgrade hardware: cpu → t4 → a10g → a100 + +### Job Timeout + +**Fix:** +1. Check logs for actual runtime +2. Increase timeout with buffer: `"timeout": "3h"` +3. Optimize code for faster execution +4. Process data in chunks + +### Hub Push Failures + +**Fix:** +1. Add token to secrets: MCP uses `"$HF_TOKEN"` (auto-replaced), Python API uses `get_token()` (must pass real token) +2. Verify token in script: `assert "HF_TOKEN" in os.environ` +3. Check token permissions +4. Verify repo exists or can be created + +### Missing Dependencies + +**Fix:** +Add to PEP 723 header: +```python +# /// script +# dependencies = ["package1", "package2>=1.0.0"] +# /// +``` + +### Authentication Errors + +**Fix:** +1. Check `hf_whoami()` works locally +2. Verify token in secrets — MCP: `"$HF_TOKEN"`, Python API: `get_token()` (NOT `"$HF_TOKEN"`) +3. Re-login: `hf auth login` +4. Check token has required permissions + +## Troubleshooting + +**Common issues:** +- Job times out → Increase timeout, optimize code +- Results not saved → Check persistence method, verify HF_TOKEN +- Out of Memory → Reduce batch size, upgrade hardware +- Import errors → Add dependencies to PEP 723 header +- Authentication errors → Check token, verify secrets parameter + +**See:** `references/troubleshooting.md` for complete troubleshooting guide + +## Resources + +### References (In This Skill) +- `references/token_usage.md` - Complete token usage guide +- `references/hardware_guide.md` - Hardware specs and selection +- `references/hub_saving.md` - Hub persistence guide +- `references/troubleshooting.md` - Common issues and solutions + +### Scripts (In This Skill) +- `scripts/generate-responses.py` - vLLM batch generation: dataset → responses → push to Hub +- `scripts/cot-self-instruct.py` - CoT Self-Instruct synthetic data generation + filtering → push to Hub +- `scripts/finepdfs-stats.py` - Polars streaming stats over `finepdfs-edu` parquet on Hub (optional push) + +### External Links + +**Official Documentation:** +- [HF Jobs Guide](https://huggingface.co/docs/huggingface_hub/guides/jobs) - Main documentation +- [HF Jobs CLI Reference](https://huggingface.co/docs/huggingface_hub/guides/cli#hf-jobs) - Command line interface +- [HF Jobs API Reference](https://huggingface.co/docs/huggingface_hub/package_reference/hf_api) - Python API details +- [Hardware Flavors Reference](https://huggingface.co/docs/hub/en/spaces-config-reference) - Available hardware + +**Related Tools:** +- [UV Scripts Guide](https://docs.astral.sh/uv/guides/scripts/) - PEP 723 inline dependencies +- [UV Scripts Organization](https://huggingface.co/uv-scripts) - Community UV script collection +- [HF Hub Authentication](https://huggingface.co/docs/huggingface_hub/quick-start#authentication) - Token setup +- [Webhooks Documentation](https://huggingface.co/docs/huggingface_hub/guides/webhooks) - Event triggers + +## Key Takeaways + +1. **Submit scripts inline** - The `script` parameter accepts Python code directly; no file saving required unless user requests +2. **Jobs are asynchronous** - Don't wait/poll; let user check when ready +3. **Always set timeout** - Default 30 min may be insufficient; set appropriate timeout +4. **Always persist results** - Environment is ephemeral; without persistence, all work is lost +5. **Use tokens securely** - MCP: `secrets={"HF_TOKEN": "$HF_TOKEN"}`, Python API: `secrets={"HF_TOKEN": get_token()}` — `"$HF_TOKEN"` only works with MCP tool +6. **Choose appropriate hardware** - Start small, scale up based on needs (see hardware guide) +7. **Use UV scripts** - Default to `hf_jobs("uv", {...})` with inline scripts for Python workloads +8. **Handle authentication** - Verify tokens are available before Hub operations +9. **Monitor jobs** - Provide job URLs and status check commands +10. **Optimize costs** - Choose right hardware, set appropriate timeouts + +## Quick Reference: MCP Tool vs CLI vs Python API + +| Operation | MCP Tool | CLI | Python API | +|-----------|----------|-----|------------| +| Run UV script | `hf_jobs("uv", {...})` | `hf jobs uv run script.py` | `run_uv_job("script.py")` | +| Run Docker job | `hf_jobs("run", {...})` | `hf jobs run image cmd` | `run_job(image, command)` | +| List jobs | `hf_jobs("ps")` | `hf jobs ps` | `list_jobs()` | +| View logs | `hf_jobs("logs", {...})` | `hf jobs logs ` | `fetch_job_logs(job_id)` | +| Cancel job | `hf_jobs("cancel", {...})` | `hf jobs cancel ` | `cancel_job(job_id)` | +| Schedule UV | `hf_jobs("scheduled uv", {...})` | `hf jobs scheduled uv run SCHEDULE script.py` | `create_scheduled_uv_job()` | +| Schedule Docker | `hf_jobs("scheduled run", {...})` | `hf jobs scheduled run SCHEDULE image cmd` | `create_scheduled_job()` | +| List scheduled | `hf_jobs("scheduled ps")` | `hf jobs scheduled ps` | `list_scheduled_jobs()` | +| Delete scheduled | `hf_jobs("scheduled delete", {...})` | `hf jobs scheduled delete ` | `delete_scheduled_job()` | diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..67a7078c0a34fe78758d885aab49475b3958ddec --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Jobs" + short_description: "Run workloads on Hugging Face Jobs infrastructure" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/index.html b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/index.html new file mode 100644 index 0000000000000000000000000000000000000000..8c2f58be2bd860a5c7f5da711da2b1ee4388ac09 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/index.html @@ -0,0 +1,215 @@ + + + + + + hf-jobs - Run Workloads on Hugging Face Jobs + + + +
+

Agent Skill : hf-jobs

+ +
+

Run any workload on Hugging Face Jobs.

+

Use this skill when you want to run GPU/CPU workloads (batch inference, synthetic data generation, dataset stats, experiments) on Hugging Face Jobs, with correct token handling and result persistence back to the Hub.

+
+ + + +
+

Overview

+

This skill focuses on running real workloads via Hugging Face Jobs. It includes ready-to-run UV scripts and guides for authentication (HF tokens), secrets vs env vars, timeouts, hardware selection, and pushing results to the Hub.

+
+ +
+

Core Documentation

+
    +
  • + SKILL.md +
    jobs/SKILL.md
    +
    Complete skill documentation (how to submit jobs, tokens/secrets, timeouts, persistence, and how to use the bundled scripts)
    +
  • +
+
+ +
+

References

+
    +
  • + token_usage.md +
    jobs/references/token_usage.md
    +
    Token best practices: secrets vs env, permissions, common errors (401/403), and secure patterns
    +
  • +
  • + hub_saving.md +
    jobs/references/hub_saving.md
    +
    How to persist results: push datasets/models/files to the Hub (ephemeral job filesystem)
    +
  • +
  • + hardware_guide.md +
    jobs/references/hardware_guide.md
    +
    Flavor selection guidance for CPU/GPU/TPU workloads
    +
  • +
  • + troubleshooting.md +
    jobs/references/troubleshooting.md
    +
    Common failure modes (timeouts, missing deps, OOM, auth) and fixes
    +
  • +
+
+ +
+

Scripts

+
    +
  • + generate-responses.py +
    jobs/scripts/generate-responses.py
    +
    vLLM batch generation: load prompts/messages from a dataset, generate responses, push dataset + card to Hub
    +
  • +
  • + cot-self-instruct.py +
    jobs/scripts/cot-self-instruct.py
    +
    CoT Self-Instruct synthetic data generation (reasoning/instruction) + optional filtering, pushes dataset + card
    +
  • +
  • + finepdfs-stats.py +
    jobs/scripts/finepdfs-stats.py
    +
    Polars streaming stats over Hub parquet (finepdfs-edu); optional upload of computed stats to a dataset repo
    +
  • +
+
+
+ + + + + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/hardware_guide.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/hardware_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..0a8463382f22e6aa82494b7a7019546e02e4b73b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/hardware_guide.md @@ -0,0 +1,336 @@ +# Hardware Selection Guide + +Choosing the right hardware (flavor) is critical for cost-effective workloads. + +> **Reference:** [HF Jobs Hardware Documentation](https://huggingface.co/docs/hub/en/spaces-config-reference) (updated 07/2025) + +## Available Hardware + +### CPU Flavors +| Flavor | Description | Use Case | +|--------|-------------|----------| +| `cpu-basic` | Basic CPU instance | Testing, lightweight scripts | +| `cpu-upgrade` | Enhanced CPU instance | Data processing, parallel workloads | + +**Use cases:** Data processing, testing scripts, lightweight workloads +**Not recommended for:** Model training, GPU-accelerated workloads + +### GPU Flavors + +| Flavor | GPU | VRAM | Use Case | +|--------|-----|------|----------| +| `t4-small` | NVIDIA T4 | 16GB | <1B models, demos, quick tests | +| `t4-medium` | NVIDIA T4 | 16GB | 1-3B models, development | +| `l4x1` | NVIDIA L4 | 24GB | 3-7B models, efficient workloads | +| `l4x4` | 4x NVIDIA L4 | 96GB | Multi-GPU, parallel workloads | +| `a10g-small` | NVIDIA A10G | 24GB | 3-7B models, production | +| `a10g-large` | NVIDIA A10G | 24GB | 7-13B models, batch inference | +| `a10g-largex2` | 2x NVIDIA A10G | 48GB | Multi-GPU, large models | +| `a10g-largex4` | 4x NVIDIA A10G | 96GB | Multi-GPU, very large models | +| `a100-large` | NVIDIA A100 | 40GB | 13B+ models, fastest GPU option | + +### TPU Flavors + +| Flavor | Configuration | Use Case | +|--------|---------------|----------| +| `v5e-1x1` | TPU v5e (1x1) | Small TPU workloads | +| `v5e-2x2` | TPU v5e (2x2) | Medium TPU workloads | +| `v5e-2x4` | TPU v5e (2x4) | Large TPU workloads | + +**TPU Use Cases:** +- JAX/Flax model training +- Large-scale inference +- TPU-optimized workloads + +## Selection Guidelines + +### By Workload Type + +**Data Processing** +- **Recommended:** `cpu-upgrade` or `l4x1` +- **Use case:** Transform, filter, analyze datasets +- **Batch size:** Depends on data size +- **Time:** Varies by dataset size + +**Batch Inference** +- **Recommended:** `a10g-large` or `a100-large` +- **Use case:** Run inference on thousands of samples +- **Batch size:** 8-32 depending on model +- **Time:** Depends on number of samples + +**Experiments & Benchmarks** +- **Recommended:** `a10g-small` or `a10g-large` +- **Use case:** Reproducible ML experiments +- **Batch size:** Varies +- **Time:** Depends on experiment complexity + +**Model Training** (see `model-trainer` skill for details) +- **Recommended:** See model-trainer skill +- **Use case:** Fine-tuning models +- **Batch size:** Depends on model size +- **Time:** Hours to days + +**Synthetic Data Generation** +- **Recommended:** `a10g-large` or `a100-large` +- **Use case:** Generate datasets using LLMs +- **Batch size:** Depends on generation method +- **Time:** Hours for large datasets + +### By Budget + +**Minimal Budget (<$5 total)** +- Use `cpu-basic` or `t4-small` +- Process small datasets +- Quick tests and demos + +**Small Budget ($5-20)** +- Use `t4-medium` or `a10g-small` +- Process medium datasets +- Run experiments + +**Medium Budget ($20-50)** +- Use `a10g-small` or `a10g-large` +- Process large datasets +- Production workloads + +**Large Budget ($50-200)** +- Use `a10g-large` or `a100-large` +- Large-scale processing +- Multiple experiments + +### By Model Size (for inference/processing) + +**Tiny Models (<1B parameters)** +- **Recommended:** `t4-small` +- **Example:** Qwen2.5-0.5B, TinyLlama +- **Batch size:** 8-16 + +**Small Models (1-3B parameters)** +- **Recommended:** `t4-medium` or `a10g-small` +- **Example:** Qwen2.5-1.5B, Phi-2 +- **Batch size:** 4-8 + +**Medium Models (3-7B parameters)** +- **Recommended:** `a10g-small` or `a10g-large` +- **Example:** Qwen2.5-7B, Mistral-7B +- **Batch size:** 2-4 + +**Large Models (7-13B parameters)** +- **Recommended:** `a10g-large` or `a100-large` +- **Example:** Llama-3-8B +- **Batch size:** 1-2 + +**Very Large Models (13B+ parameters)** +- **Recommended:** `a100-large` +- **Example:** Llama-3-13B, Llama-3-70B +- **Batch size:** 1 + +## Memory Considerations + +### Estimating Memory Requirements + +**For inference:** +``` +Memory (GB) ≈ (Model params in billions) × 2-4 +``` + +**For training:** +``` +Memory (GB) ≈ (Model params in billions) × 20 (full) or × 4 (LoRA) +``` + +**Examples:** +- Qwen2.5-0.5B inference: ~1-2GB ✅ fits t4-small +- Qwen2.5-7B inference: ~14-28GB ✅ fits a10g-large +- Qwen2.5-7B training: ~140GB ❌ not feasible without LoRA + +### Memory Optimization + +If hitting memory limits: + +1. **Reduce batch size** + ```python + batch_size = 1 + ``` + +2. **Process in chunks** + ```python + for chunk in chunks: + process(chunk) + ``` + +3. **Use smaller models** + - Use quantized models + - Use LoRA adapters + +4. **Upgrade hardware** + - cpu → t4 → a10g → a100 + +## Cost Estimation + +### Formula + +``` +Total Cost = (Hours of runtime) × (Cost per hour) +``` + +### Example Calculations + +**Data processing:** +- Hardware: cpu-upgrade ($0.50/hour) +- Time: 1 hour +- Cost: $0.50 + +**Batch inference:** +- Hardware: a10g-large ($5/hour) +- Time: 2 hours +- Cost: $10.00 + +**Experiments:** +- Hardware: a10g-small ($3.50/hour) +- Time: 4 hours +- Cost: $14.00 + +### Cost Optimization Tips + +1. **Start small:** Test on cpu-basic or t4-small +2. **Monitor runtime:** Set appropriate timeouts +3. **Optimize code:** Reduce unnecessary compute +4. **Choose right hardware:** Don't over-provision +5. **Use checkpoints:** Resume if job fails +6. **Monitor costs:** Check running jobs regularly + +## Multi-GPU Workloads + +Multi-GPU flavors automatically distribute workloads: + +**Multi-GPU flavors:** +- `l4x4` - 4x L4 GPUs (96GB total VRAM) +- `a10g-largex2` - 2x A10G GPUs (48GB total VRAM) +- `a10g-largex4` - 4x A10G GPUs (96GB total VRAM) + +**When to use:** +- Large models (>13B parameters) +- Need faster processing (linear speedup) +- Large datasets (>100K samples) +- Parallel workloads +- Tensor parallelism for inference + +**MCP Tool Example:** +```python +hf_jobs("uv", { + "script": "process.py", + "flavor": "a10g-largex2", # 2 GPUs + "timeout": "4h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +**CLI Equivalent:** +```bash +hf jobs uv run process.py --flavor a10g-largex2 --timeout 4h +``` + +## Choosing Between Options + +### CPU vs GPU + +**Choose CPU when:** +- No GPU acceleration needed +- Data processing only +- Budget constrained +- Simple workloads + +**Choose GPU when:** +- Model inference/training +- GPU-accelerated libraries +- Need faster processing +- Large models + +### a10g vs a100 + +**Choose a10g when:** +- Model <13B parameters +- Budget conscious +- Processing time not critical + +**Choose a100 when:** +- Model 13B+ parameters +- Need fastest processing +- Memory requirements high +- Budget allows + +### Single vs Multi-GPU + +**Choose single GPU when:** +- Model <7B parameters +- Budget constrained +- Simpler debugging + +**Choose multi-GPU when:** +- Model >13B parameters +- Need faster processing +- Large batch sizes required +- Cost-effective for large jobs + +## Quick Reference + +### All Available Flavors + +```python +# Official flavor list (updated 07/2025) +FLAVORS = { + # CPU + "cpu-basic", # Testing, lightweight + "cpu-upgrade", # Data processing + + # GPU - Single + "t4-small", # 16GB - <1B models + "t4-medium", # 16GB - 1-3B models + "l4x1", # 24GB - 3-7B models + "a10g-small", # 24GB - 3-7B production + "a10g-large", # 24GB - 7-13B models + "a100-large", # 40GB - 13B+ models + + # GPU - Multi + "l4x4", # 4x L4 (96GB total) + "a10g-largex2", # 2x A10G (48GB total) + "a10g-largex4", # 4x A10G (96GB total) + + # TPU + "v5e-1x1", # TPU v5e 1x1 + "v5e-2x2", # TPU v5e 2x2 + "v5e-2x4", # TPU v5e 2x4 +} +``` + +### Workload → Hardware Mapping + +```python +HARDWARE_MAP = { + "data_processing": "cpu-upgrade", + "batch_inference_small": "t4-small", + "batch_inference_medium": "a10g-large", + "batch_inference_large": "a100-large", + "experiments": "a10g-small", + "tpu_workloads": "v5e-1x1", + "training": "see model-trainer skill" +} +``` + +### CLI Examples + +```bash +# CPU job +hf jobs run python:3.12 python script.py + +# GPU job +hf jobs run --flavor a10g-large pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel python script.py + +# TPU job +hf jobs run --flavor v5e-1x1 your-tpu-image python script.py + +# UV script with GPU +hf jobs uv run --flavor a10g-small my_script.py +``` + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/hub_saving.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/hub_saving.md new file mode 100644 index 0000000000000000000000000000000000000000..e2af02834385783d75c97cd260dfa6c7b5c3ce37 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/hub_saving.md @@ -0,0 +1,352 @@ +# Saving Results to Hugging Face Hub + +**⚠️ CRITICAL:** Job environments are ephemeral. ALL results are lost when a job completes unless persisted to the Hub or external storage. + +## Why Persistence is Required + +When running on Hugging Face Jobs: +- Environment is temporary +- All files deleted on job completion +- No local disk persistence +- Cannot access results after job ends + +**Without persistence, all work is permanently lost.** + +## Persistence Options + +### Option 1: Push to Hugging Face Hub (Recommended) + +**For models:** +```python +from transformers import AutoModel +model.push_to_hub("username/model-name", token=os.environ.get("HF_TOKEN")) +``` + +**For datasets:** +```python +from datasets import Dataset +dataset.push_to_hub("username/dataset-name", token=os.environ.get("HF_TOKEN")) +``` + +**For files/artifacts:** +```python +from huggingface_hub import HfApi +api = HfApi(token=os.environ.get("HF_TOKEN")) +api.upload_file( + path_or_fileobj="results.json", + path_in_repo="results.json", + repo_id="username/results", + repo_type="dataset" +) +``` + +### Option 2: External Storage + +**S3:** +```python +import boto3 +s3 = boto3.client('s3') +s3.upload_file('results.json', 'my-bucket', 'results.json') +``` + +**Google Cloud Storage:** +```python +from google.cloud import storage +client = storage.Client() +bucket = client.bucket('my-bucket') +blob = bucket.blob('results.json') +blob.upload_from_filename('results.json') +``` + +### Option 3: API Endpoint + +```python +import requests +requests.post("https://your-api.com/results", json=results) +``` + +## Required Configuration for Hub Push + +### Job Configuration + +**Always include HF_TOKEN:** +```python +hf_jobs("uv", { + "script": "your_script.py", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Required for Hub operations +}) +``` + +### Script Configuration + +**Verify token exists:** +```python +import os +assert "HF_TOKEN" in os.environ, "HF_TOKEN required for Hub operations!" +``` + +**Use token for Hub operations:** +```python +from huggingface_hub import HfApi + +# Auto-detects HF_TOKEN from environment +api = HfApi() + +# Or explicitly pass token +api = HfApi(token=os.environ.get("HF_TOKEN")) +``` + +## Complete Examples + +### Example 1: Push Dataset + +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["datasets", "huggingface-hub"] +# /// + +import os +from datasets import Dataset +from huggingface_hub import HfApi + +# Verify token +assert "HF_TOKEN" in os.environ, "HF_TOKEN required!" + +# Process data +data = {"text": ["Sample 1", "Sample 2"]} +dataset = Dataset.from_dict(data) + +# Push to Hub +dataset.push_to_hub("username/my-dataset") +print("✅ Dataset pushed!") +""", + "flavor": "cpu-basic", + "timeout": "30m", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +### Example 2: Push Model + +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["transformers"] +# /// + +import os +from transformers import AutoModel, AutoTokenizer + +# Verify token +assert "HF_TOKEN" in os.environ, "HF_TOKEN required!" + +# Load and process model +model = AutoModel.from_pretrained("base-model") +tokenizer = AutoTokenizer.from_pretrained("base-model") +# ... process model ... + +# Push to Hub +model.push_to_hub("username/my-model") +tokenizer.push_to_hub("username/my-model") +print("✅ Model pushed!") +""", + "flavor": "a10g-large", + "timeout": "2h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +### Example 3: Push Artifacts + +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["huggingface-hub", "pandas"] +# /// + +import os +import json +import pandas as pd +from huggingface_hub import HfApi + +# Verify token +assert "HF_TOKEN" in os.environ, "HF_TOKEN required!" + +# Generate results +results = {"accuracy": 0.95, "loss": 0.05} +df = pd.DataFrame([results]) + +# Save files +with open("results.json", "w") as f: + json.dump(results, f) +df.to_csv("results.csv", index=False) + +# Push to Hub +api = HfApi() +api.upload_file("results.json", "results.json", "username/results", repo_type="dataset") +api.upload_file("results.csv", "results.csv", "username/results", repo_type="dataset") +print("✅ Results pushed!") +""", + "flavor": "cpu-basic", + "timeout": "30m", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +## Authentication Methods + +### Method 1: Automatic Token (Recommended) + +```python +"secrets": {"HF_TOKEN": "$HF_TOKEN"} +``` + +Uses your logged-in Hugging Face token automatically. + +### Method 2: Explicit Token + +```python +"secrets": {"HF_TOKEN": "hf_abc123..."} +``` + +Provide token explicitly (not recommended for security). + +### Method 3: Environment Variable + +```python +"env": {"HF_TOKEN": "hf_abc123..."} +``` + +Pass as regular environment variable (less secure than secrets). + +**Always prefer Method 1** for security and convenience. + +## Verification Checklist + +Before submitting any job that saves to Hub, verify: + +- [ ] `secrets={"HF_TOKEN": "$HF_TOKEN"}` in job config +- [ ] Script checks for token: `assert "HF_TOKEN" in os.environ` +- [ ] Hub push code included in script +- [ ] Repository name doesn't conflict with existing repos +- [ ] You have write access to the target namespace + +## Repository Setup + +### Automatic Creation + +If repository doesn't exist, it's created automatically when first pushing (if token has write permissions). + +### Manual Creation + +Create repository before pushing: + +```python +from huggingface_hub import HfApi + +api = HfApi() +api.create_repo( + repo_id="username/repo-name", + repo_type="model", # or "dataset" + private=False, # or True for private repo +) +``` + +### Repository Naming + +**Valid names:** +- `username/my-model` +- `username/model-name` +- `organization/model-name` + +**Invalid names:** +- `model-name` (missing username) +- `username/model name` (spaces not allowed) +- `username/MODEL` (uppercase discouraged) + +## Troubleshooting + +### Error: 401 Unauthorized + +**Cause:** HF_TOKEN not provided or invalid + +**Solutions:** +1. Verify `secrets={"HF_TOKEN": "$HF_TOKEN"}` in job config +2. Check you're logged in: `hf_whoami()` +3. Re-login: `hf auth login` + +### Error: 403 Forbidden + +**Cause:** No write access to repository + +**Solutions:** +1. Check repository namespace matches your username +2. Verify you're a member of organization (if using org namespace) +3. Check token has write permissions + +### Error: Repository not found + +**Cause:** Repository doesn't exist and auto-creation failed + +**Solutions:** +1. Manually create repository first +2. Check repository name format +3. Verify namespace exists + +### Error: Push failed + +**Cause:** Network issues or Hub unavailable + +**Solutions:** +1. Check logs for specific error +2. Verify token is valid +3. Retry push operation + +## Best Practices + +1. **Always verify token exists** before Hub operations +2. **Use descriptive repo names** (e.g., `my-experiment-results` not `results`) +3. **Push incrementally** for large results (use checkpoints) +4. **Verify push success** in logs before job completes +5. **Use appropriate repo types** (model vs dataset) +6. **Add README** with result descriptions +7. **Tag repos** with relevant tags + +## Monitoring Push Progress + +Check logs for push progress: + +**MCP Tool:** +```python +hf_jobs("logs", {"job_id": "your-job-id"}) +``` + +**CLI:** +```bash +hf jobs logs +``` + +**Python API:** +```python +from huggingface_hub import fetch_job_logs +for log in fetch_job_logs(job_id="your-job-id"): + print(log) +``` + +**Look for:** +``` +Pushing to username/repo-name... +Upload file results.json: 100% +✅ Push successful +``` + +## Key Takeaway + +**Without `secrets={"HF_TOKEN": "$HF_TOKEN"}` and persistence code, all results are permanently lost.** + +Always verify both are configured before submitting any job that produces results. + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/token_usage.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/token_usage.md new file mode 100644 index 0000000000000000000000000000000000000000..89d675d4e5ec5b369471d941e74f7009aee6c234 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/token_usage.md @@ -0,0 +1,570 @@ +# Token Usage Guide for Hugging Face Jobs + +**⚠️ CRITICAL:** Proper token usage is essential for any job that interacts with the Hugging Face Hub. + +## Overview + +Hugging Face tokens are authentication credentials that allow your jobs to interact with the Hub. They're required for: +- Pushing models/datasets to Hub +- Accessing private repositories +- Creating new repositories +- Using Hub APIs programmatically +- Any authenticated Hub operations + +## Token Types + +### Read Token +- **Permissions:** Download models/datasets, read private repos +- **Use case:** Jobs that only need to download/read content +- **Creation:** https://huggingface.co/settings/tokens + +### Write Token +- **Permissions:** Push models/datasets, create repos, modify content +- **Use case:** Jobs that need to upload results (most common) +- **Creation:** https://huggingface.co/settings/tokens +- **⚠️ Required for:** Pushing models, datasets, or any uploads + +### Organization Token +- **Permissions:** Act on behalf of an organization +- **Use case:** Jobs running under organization namespace +- **Creation:** Organization settings → Tokens + +## Providing Tokens to Jobs + +### Method 1: `hf_jobs` MCP tool with `$HF_TOKEN` (Recommended) ⭐ + +```python +hf_jobs("uv", { + "script": "your_script.py", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Automatic replacement +}) +``` + +**How it works:** +1. `$HF_TOKEN` is a placeholder that gets replaced with your actual token +2. Uses the token from your logged-in session (`hf auth login`) +3. Token is encrypted server-side when passed as a secret +4. Most secure and convenient method + +**Benefits:** +- ✅ No token exposure in code +- ✅ Uses your current login session +- ✅ Automatically updated if you re-login +- ✅ Works seamlessly with MCP tools +- ✅ Token encrypted server-side + +**Requirements:** +- Must be logged in: `hf auth login` or `hf_whoami()` works +- Token must have required permissions + +**⚠️ CRITICAL:** `$HF_TOKEN` auto-replacement is an `hf_jobs` MCP tool feature ONLY. It does NOT work with `HfApi().run_uv_job()` — see Method 1b below. + +### Method 1b: `HfApi().run_uv_job()` with `get_token()` (Required for Python API) + +```python +from huggingface_hub import HfApi, get_token +api = HfApi() +api.run_uv_job( + script="your_script.py", + secrets={"HF_TOKEN": get_token()}, # ✅ Passes actual token value +) +``` + +**How it works:** +1. `get_token()` retrieves the token from your logged-in session +2. The actual token value is passed to the `secrets` parameter +3. Token is encrypted server-side + +**Why `"$HF_TOKEN"` fails with `HfApi().run_uv_job()`:** +- The Python API passes the literal string `"$HF_TOKEN"` (9 characters) as the token +- The Jobs server receives this invalid string instead of a real token +- Result: `401 Unauthorized` errors when the script tries to authenticate +- You MUST use `get_token()` from `huggingface_hub` to get the real token + +### Method 2: Explicit Token (Not Recommended) + +```python +hf_jobs("uv", { + "script": "your_script.py", + "secrets": {"HF_TOKEN": "hf_abc123..."} # ⚠️ Hardcoded token +}) +``` + +**When to use:** +- Only if automatic token doesn't work +- Testing with a specific token +- Organization tokens (use with caution) + +**Security concerns:** +- ❌ Token visible in code/logs +- ❌ Must manually update if token rotates +- ❌ Risk of token exposure +- ❌ Not recommended for production + +### Method 3: Environment Variable (Less Secure) + +```python +hf_jobs("uv", { + "script": "your_script.py", + "env": {"HF_TOKEN": "hf_abc123..."} # ⚠️ Less secure than secrets +}) +``` + +**Difference from secrets:** +- `env` variables are visible in job logs +- `secrets` are encrypted server-side +- Always prefer `secrets` for tokens + +**When to use:** +- Only for non-sensitive configuration +- Never use for tokens (use `secrets` instead) + +## Using Tokens in Scripts + +### Accessing Tokens + +Tokens passed via `secrets` are available as environment variables in your script: + +```python +import os + +# Get token from environment +token = os.environ.get("HF_TOKEN") + +# Verify token exists +if not token: + raise ValueError("HF_TOKEN not found in environment!") +``` + +### Using with Hugging Face Hub + +**Option 1: Explicit token parameter** +```python +from huggingface_hub import HfApi + +api = HfApi(token=os.environ.get("HF_TOKEN")) +api.upload_file(...) +``` + +**Option 2: Auto-detection (Recommended)** +```python +from huggingface_hub import HfApi + +# Automatically uses HF_TOKEN env var +api = HfApi() # ✅ Simpler, uses token from environment +api.upload_file(...) +``` + +**Option 3: With transformers/datasets** +```python +from transformers import AutoModel +from datasets import load_dataset + +# Auto-detects HF_TOKEN from environment +model = AutoModel.from_pretrained("username/model") +dataset = load_dataset("username/dataset") + +# For push operations, token is auto-detected +model.push_to_hub("username/new-model") +dataset.push_to_hub("username/new-dataset") +``` + +### Complete Example + +```python +# /// script +# dependencies = ["huggingface-hub", "datasets"] +# /// + +import os +from huggingface_hub import HfApi +from datasets import Dataset + +# Verify token is available +assert "HF_TOKEN" in os.environ, "HF_TOKEN required for Hub operations!" + +# Use token for Hub operations +api = HfApi() # Auto-detects HF_TOKEN + +# Create and push dataset +data = {"text": ["Hello", "World"]} +dataset = Dataset.from_dict(data) + +# Push to Hub (token auto-detected) +dataset.push_to_hub("username/my-dataset") + +print("✅ Dataset pushed successfully!") +``` + +## Token Verification + +### Check Authentication Locally + +```python +from huggingface_hub import whoami + +try: + user_info = whoami() + print(f"✅ Logged in as: {user_info['name']}") +except Exception as e: + print(f"❌ Not authenticated: {e}") +``` + +### Verify Token in Job + +```python +import os + +# Check token exists +if "HF_TOKEN" not in os.environ: + raise ValueError("HF_TOKEN not found in environment!") + +token = os.environ["HF_TOKEN"] + +# Verify token format (should start with "hf_") +if not token.startswith("hf_"): + raise ValueError(f"Invalid token format: {token[:10]}...") + +# Test token works +from huggingface_hub import whoami +try: + user_info = whoami(token=token) + print(f"✅ Token valid for user: {user_info['name']}") +except Exception as e: + raise ValueError(f"Token validation failed: {e}") +``` + +## Common Token Issues + +### Error: 401 Unauthorized + +**Symptoms:** +``` +401 Client Error: Unauthorized for url: https://huggingface.co/api/... +``` + +**Causes:** +1. Token missing from job +2. Token invalid or expired +3. Token not passed correctly + +**Solutions:** +1. Add `secrets={"HF_TOKEN": "$HF_TOKEN"}` to job config +2. Verify `hf_whoami()` works locally +3. Re-login: `hf auth login` +4. Check token hasn't expired + +**Verification:** +```python +# In your script +import os +assert "HF_TOKEN" in os.environ, "HF_TOKEN missing!" +``` + +### Error: 403 Forbidden + +**Symptoms:** +``` +403 Client Error: Forbidden for url: https://huggingface.co/api/... +``` + +**Causes:** +1. Token lacks required permissions (read-only token used for write) +2. No access to private repository +3. Organization permissions insufficient + +**Solutions:** +1. Ensure token has write permissions +2. Check token type at https://huggingface.co/settings/tokens +3. Verify access to target repository +4. Use organization token if needed + +**Check token permissions:** +```python +from huggingface_hub import whoami + +user_info = whoami() +print(f"User: {user_info['name']}") +print(f"Type: {user_info.get('type', 'user')}") +``` + +### Error: Token not found in environment + +**Symptoms:** +``` +KeyError: 'HF_TOKEN' +ValueError: HF_TOKEN not found +``` + +**Causes:** +1. `secrets` not passed in job config +2. Wrong key name (should be `HF_TOKEN`) +3. Using `env` instead of `secrets` + +**Solutions:** +1. Use `secrets={"HF_TOKEN": "$HF_TOKEN"}` (not `env`) +2. Verify key name is exactly `HF_TOKEN` +3. Check job config syntax + +**Correct configuration:** +```python +# ✅ Correct +hf_jobs("uv", { + "script": "...", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) + +# ❌ Wrong - using env instead of secrets +hf_jobs("uv", { + "script": "...", + "env": {"HF_TOKEN": "$HF_TOKEN"} # Less secure +}) + +# ❌ Wrong - wrong key name +hf_jobs("uv", { + "script": "...", + "secrets": {"TOKEN": "$HF_TOKEN"} # Wrong key +}) +``` + +### Error: Repository access denied + +**Symptoms:** +``` +403 Client Error: Forbidden +Repository not found or access denied +``` + +**Causes:** +1. Token doesn't have access to private repo +2. Repository doesn't exist and can't be created +3. Wrong namespace + +**Solutions:** +1. Use token from account with access +2. Verify repo visibility (public vs private) +3. Check namespace matches token owner +4. Create repo first if needed + +**Check repository access:** +```python +from huggingface_hub import HfApi + +api = HfApi() +try: + repo_info = api.repo_info("username/repo-name") + print(f"✅ Access granted: {repo_info.id}") +except Exception as e: + print(f"❌ Access denied: {e}") +``` + +## Token Security Best Practices + +### 1. Never Commit Tokens + +**❌ Bad:** +```python +# Never do this! +token = "hf_abc123xyz..." +api = HfApi(token=token) +``` + +**✅ Good:** +```python +# Use environment variable +token = os.environ.get("HF_TOKEN") +api = HfApi(token=token) +``` + +### 2. Use Secrets, Not Environment Variables + +**❌ Bad:** +```python +hf_jobs("uv", { + "script": "...", + "env": {"HF_TOKEN": "$HF_TOKEN"} # Visible in logs +}) +``` + +**✅ Good:** +```python +hf_jobs("uv", { + "script": "...", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # Encrypted server-side +}) +``` + +### 3. Use Automatic Token Replacement + +**❌ Bad:** +```python +hf_jobs("uv", { + "script": "...", + "secrets": {"HF_TOKEN": "hf_abc123..."} # Hardcoded +}) +``` + +**✅ Good:** +```python +hf_jobs("uv", { + "script": "...", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # Automatic +}) +``` + +### 4. Rotate Tokens Regularly + +- Generate new tokens periodically +- Revoke old tokens +- Update job configurations +- Monitor token usage + +### 5. Use Minimal Permissions + +- Create tokens with only needed permissions +- Use read tokens when write isn't needed +- Don't use admin tokens for regular jobs + +### 6. Don't Share Tokens + +- Each user should use their own token +- Don't commit tokens to repositories +- Don't share tokens in logs or messages + +### 7. Monitor Token Usage + +- Check token activity in Hub settings +- Review job logs for token issues +- Set up alerts for unauthorized access + +## Token Workflow Examples + +### Example 1: Push Model to Hub + +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["transformers"] +# /// + +import os +from transformers import AutoModel, AutoTokenizer + +# Verify token +assert "HF_TOKEN" in os.environ, "HF_TOKEN required!" + +# Load and process model +model = AutoModel.from_pretrained("base-model") +# ... process model ... + +# Push to Hub (token auto-detected) +model.push_to_hub("username/my-model") +print("✅ Model pushed!") +""", + "flavor": "a10g-large", + "timeout": "2h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Token provided +}) +``` + +### Example 2: Access Private Dataset + +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["datasets"] +# /// + +import os +from datasets import load_dataset + +# Verify token +assert "HF_TOKEN" in os.environ, "HF_TOKEN required!" + +# Load private dataset (token auto-detected) +dataset = load_dataset("private-org/private-dataset") +print(f"✅ Loaded {len(dataset)} examples") +""", + "flavor": "cpu-basic", + "timeout": "30m", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Token provided +}) +``` + +### Example 3: Create and Push Dataset + +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["datasets", "huggingface-hub"] +# /// + +import os +from datasets import Dataset +from huggingface_hub import HfApi + +# Verify token +assert "HF_TOKEN" in os.environ, "HF_TOKEN required!" + +# Create dataset +data = {"text": ["Sample 1", "Sample 2"]} +dataset = Dataset.from_dict(data) + +# Push to Hub +api = HfApi() # Auto-detects HF_TOKEN +dataset.push_to_hub("username/my-dataset") +print("✅ Dataset pushed!") +""", + "flavor": "cpu-basic", + "timeout": "30m", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Token provided +}) +``` + +## Quick Reference + +### Token Checklist + +Before submitting a job that uses Hub: + +- [ ] Job includes `secrets={"HF_TOKEN": "$HF_TOKEN"}` +- [ ] Script checks for token: `assert "HF_TOKEN" in os.environ` +- [ ] Token has required permissions (read/write) +- [ ] User is logged in: `hf_whoami()` works +- [ ] Token not hardcoded in script +- [ ] Using `secrets` not `env` for token + +### Common Patterns + +**Pattern 1: Auto-detect token** +```python +from huggingface_hub import HfApi +api = HfApi() # Uses HF_TOKEN from environment +``` + +**Pattern 2: Explicit token** +```python +import os +from huggingface_hub import HfApi +api = HfApi(token=os.environ.get("HF_TOKEN")) +``` + +**Pattern 3: Verify token** +```python +import os +assert "HF_TOKEN" in os.environ, "HF_TOKEN required!" +``` + +## Key Takeaways + +1. **Always use `secrets={"HF_TOKEN": "$HF_TOKEN"}`** for Hub operations +2. **Never hardcode tokens** in scripts or job configs +3. **Verify token exists** in script before Hub operations +4. **Use auto-detection** when possible (`HfApi()` without token parameter) +5. **Check permissions** - ensure token has required access +6. **Monitor token usage** - review activity regularly +7. **Rotate tokens** - generate new tokens periodically + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/troubleshooting.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..338b68949d63b1f3f1b46aab77b4c94cbd9eddde --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/references/troubleshooting.md @@ -0,0 +1,475 @@ +# Troubleshooting Guide + +Common issues and solutions for Hugging Face Jobs. + +## Authentication Issues + +### Error: 401 Unauthorized + +**Symptoms:** +``` +401 Client Error: Unauthorized for url: https://huggingface.co/api/... +``` + +**Causes:** +- Token missing from job +- Token invalid or expired +- Token not passed correctly + +**Solutions:** +1. Add token to secrets: `hf_jobs` MCP uses `"$HF_TOKEN"` (auto-replaced); `HfApi().run_uv_job()` MUST use `get_token()` from `huggingface_hub` (the literal string `"$HF_TOKEN"` will NOT work with the Python API) +2. Verify `hf_whoami()` works locally +3. Re-login: `hf auth login` +4. Check token hasn't expired + +**Verification:** +```python +# In your script +import os +assert "HF_TOKEN" in os.environ, "HF_TOKEN missing!" +``` + +### Error: 403 Forbidden + +**Symptoms:** +``` +403 Client Error: Forbidden for url: https://huggingface.co/api/... +``` + +**Causes:** +- Token lacks required permissions +- No access to private repository +- Organization permissions insufficient + +**Solutions:** +1. Ensure token has write permissions +2. Check token type at https://huggingface.co/settings/tokens +3. Verify access to target repository +4. Use organization token if needed + +### Error: Token not found in environment + +**Symptoms:** +``` +KeyError: 'HF_TOKEN' +ValueError: HF_TOKEN not found +``` + +**Causes:** +- `secrets` not passed in job config +- Wrong key name (should be `HF_TOKEN`) +- Using `env` instead of `secrets` + +**Solutions:** +1. Use `secrets` (not `env`) — with `hf_jobs` MCP: `"$HF_TOKEN"`; with `HfApi().run_uv_job()`: `get_token()` +2. Verify key name is exactly `HF_TOKEN` +3. Check job config syntax + +## Job Execution Issues + +### Error: Job Timeout + +**Symptoms:** +- Job stops unexpectedly +- Status shows "TIMEOUT" +- Partial results only + +**Causes:** +- Default 30min timeout exceeded +- Job takes longer than expected +- No timeout specified + +**Solutions:** +1. Check logs for actual runtime +2. Increase timeout with buffer: `"timeout": "3h"` +3. Optimize code for faster execution +4. Process data in chunks +5. Add 20-30% buffer to estimated time + +**MCP Tool Example:** +```python +hf_jobs("uv", { + "script": "...", + "timeout": "2h" # Set appropriate timeout +}) +``` + +**Python API Example:** +```python +from huggingface_hub import run_uv_job, inspect_job, fetch_job_logs + +job = run_uv_job("script.py", timeout="4h") + +# Check if job failed +job_info = inspect_job(job_id=job.id) +if job_info.status.stage == "ERROR": + print(f"Job failed: {job_info.status.message}") + # Check logs for details + for log in fetch_job_logs(job_id=job.id): + print(log) +``` + +### Error: Out of Memory (OOM) + +**Symptoms:** +``` +RuntimeError: CUDA out of memory +MemoryError: Unable to allocate array +``` + +**Causes:** +- Batch size too large +- Model too large for hardware +- Insufficient GPU memory + +**Solutions:** +1. Reduce batch size +2. Process data in smaller chunks +3. Upgrade hardware: cpu → t4 → a10g → a100 +4. Use smaller models or quantization +5. Enable gradient checkpointing (for training) + +**Example:** +```python +# Reduce batch size +batch_size = 1 + +# Process in chunks +for chunk in chunks: + process(chunk) +``` + +### Error: Missing Dependencies + +**Symptoms:** +``` +ModuleNotFoundError: No module named 'package_name' +ImportError: cannot import name 'X' +``` + +**Causes:** +- Package not in dependencies +- Wrong package name +- Version mismatch + +**Solutions:** +1. Add to PEP 723 header: + ```python + # /// script + # dependencies = ["package-name>=1.0.0"] + # /// + ``` +2. Check package name spelling +3. Specify version if needed +4. Check package availability + +### Error: Script Not Found + +**Symptoms:** +``` +FileNotFoundError: script.py not found +``` + +**Causes:** +- Local file path used (not supported) +- URL incorrect +- Script not accessible + +**Solutions:** +1. Use inline script (recommended) +2. Use publicly accessible URL +3. Upload script to Hub first +4. Check URL is correct + +**Correct approaches:** +```python +# ✅ Inline code +hf_jobs("uv", {"script": "# /// script\n# dependencies = [...]\n# ///\n\n"}) + +# ✅ From URL +hf_jobs("uv", {"script": "https://huggingface.co/user/repo/resolve/main/script.py"}) +``` + +## Hub Push Issues + +### Error: Push Failed + +**Symptoms:** +``` +Error pushing to Hub +Upload failed +``` + +**Causes:** +- Network issues +- Token missing or invalid +- Repository access denied +- File too large + +**Solutions:** +1. Check token: `assert "HF_TOKEN" in os.environ` +2. Verify repository exists or can be created +3. Check network connectivity in logs +4. Retry push operation +5. Split large files into chunks + +### Error: Repository Not Found + +**Symptoms:** +``` +404 Client Error: Not Found +Repository not found +``` + +**Causes:** +- Repository doesn't exist +- Wrong repository name +- No access to private repo + +**Solutions:** +1. Create repository first: + ```python + from huggingface_hub import HfApi + api = HfApi() + api.create_repo("username/repo-name", repo_type="dataset") + ``` +2. Check repository name format +3. Verify namespace exists +4. Check repository visibility + +### Error: Results Not Saved + +**Symptoms:** +- Job completes successfully +- No results visible on Hub +- Files not persisted + +**Causes:** +- No persistence code in script +- Push code not executed +- Push failed silently + +**Solutions:** +1. Add persistence code to script +2. Verify push executes successfully +3. Check logs for push errors +4. Add error handling around push + +**Example:** +```python +try: + dataset.push_to_hub("username/dataset") + print("✅ Push successful") +except Exception as e: + print(f"❌ Push failed: {e}") + raise +``` + +## Hardware Issues + +### Error: GPU Not Available + +**Symptoms:** +``` +CUDA not available +No GPU found +``` + +**Causes:** +- CPU flavor used instead of GPU +- GPU not requested +- CUDA not installed in image + +**Solutions:** +1. Use GPU flavor: `"flavor": "a10g-large"` +2. Check image has CUDA support +3. Verify GPU availability in logs + +### Error: Slow Performance + +**Symptoms:** +- Job takes longer than expected +- Low GPU utilization +- CPU bottleneck + +**Causes:** +- Wrong hardware selected +- Inefficient code +- Data loading bottleneck + +**Solutions:** +1. Upgrade hardware +2. Optimize code +3. Use batch processing +4. Profile code to find bottlenecks + +## General Issues + +### Error: Job Status Unknown + +**Symptoms:** +- Can't check job status +- Status API returns error + +**Solutions:** +1. Use job URL: `https://huggingface.co/jobs/username/job-id` +2. Check logs: `hf_jobs("logs", {"job_id": "..."})` +3. Inspect job: `hf_jobs("inspect", {"job_id": "..."})` + +### Error: Logs Not Available + +**Symptoms:** +- No logs visible +- Logs delayed + +**Causes:** +- Job just started (logs delayed 30-60s) +- Job failed before logging +- Logs not yet generated + +**Solutions:** +1. Wait 30-60 seconds after job start +2. Check job status first +3. Use job URL for web interface + +### Error: Cost Unexpectedly High + +**Symptoms:** +- Job costs more than expected +- Longer runtime than estimated + +**Causes:** +- Job ran longer than timeout +- Wrong hardware selected +- Inefficient code + +**Solutions:** +1. Monitor job runtime +2. Set appropriate timeout +3. Optimize code +4. Choose right hardware +5. Check cost estimates before running + +## Debugging Tips + +### 1. Add Logging + +```python +import logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +logger.info("Starting processing...") +logger.info(f"Processed {count} items") +``` + +### 2. Verify Environment + +```python +import os +print(f"Python version: {os.sys.version}") +print(f"CUDA available: {torch.cuda.is_available()}") +print(f"HF_TOKEN present: {'HF_TOKEN' in os.environ}") +``` + +### 3. Test Locally First + +Run script locally before submitting to catch errors early: +```bash +python script.py +# Or with uv +uv run script.py +``` + +### 4. Check Job Logs + +**MCP Tool:** +```python +# View logs +hf_jobs("logs", {"job_id": "your-job-id"}) +``` + +**CLI:** +```bash +hf jobs logs +``` + +**Python API:** +```python +from huggingface_hub import fetch_job_logs +for log in fetch_job_logs(job_id="your-job-id"): + print(log) +``` + +**Or use job URL:** `https://huggingface.co/jobs/username/job-id` + +### 5. Add Error Handling + +```python +try: + # Your code + process_data() +except Exception as e: + print(f"Error: {e}") + import traceback + traceback.print_exc() + raise +``` + +### 6. Check Job Status Programmatically + +```python +from huggingface_hub import inspect_job, fetch_job_logs + +job_info = inspect_job(job_id="your-job-id") +print(f"Status: {job_info.status.stage}") +print(f"Message: {job_info.status.message}") + +if job_info.status.stage == "ERROR": + print("Job failed! Logs:") + for log in fetch_job_logs(job_id="your-job-id"): + print(log) +``` + +## Quick Reference + +### Common Error Codes + +| Code | Meaning | Solution | +|------|---------|----------| +| 401 | Unauthorized | Add token to secrets: MCP uses `"$HF_TOKEN"`, Python API uses `get_token()` | +| 403 | Forbidden | Check token permissions | +| 404 | Not Found | Verify repository exists | +| 500 | Server Error | Retry or contact support | + +### Checklist Before Submitting + +- [ ] Token configured: MCP uses `secrets={"HF_TOKEN": "$HF_TOKEN"}`, Python API uses `secrets={"HF_TOKEN": get_token()}` +- [ ] Script checks for token: `assert "HF_TOKEN" in os.environ` +- [ ] Timeout set appropriately +- [ ] Hardware selected correctly +- [ ] Dependencies listed in PEP 723 header +- [ ] Persistence code included +- [ ] Error handling added +- [ ] Logging added for debugging + +## Getting Help + +If issues persist: + +1. **Check logs** - Most errors include detailed messages +2. **Review documentation** - See main SKILL.md +3. **Check Hub status** - https://status.huggingface.co +4. **Community forums** - https://discuss.huggingface.co +5. **GitHub issues** - For bugs in huggingface_hub + +## Key Takeaways + +1. **Always include token** - MCP: `secrets={"HF_TOKEN": "$HF_TOKEN"}`, Python API: `secrets={"HF_TOKEN": get_token()}` +2. **Set appropriate timeout** - Default 30min may be insufficient +3. **Verify persistence** - Results won't persist without code +4. **Check logs** - Most issues visible in job logs +5. **Test locally** - Catch errors before submitting +6. **Add error handling** - Better debugging information +7. **Monitor costs** - Set timeouts to avoid unexpected charges + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/cot-self-instruct.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/cot-self-instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..5388438ba8998378662ec6e6b930717ae436b745 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/cot-self-instruct.py @@ -0,0 +1,718 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = [ +# "datasets", +# "transformers", +# "vllm>=0.6.5", +# "huggingface-hub[hf_transfer]", +# "torch", +# "numpy", +# "tqdm", +# "scikit-learn", +# ] +# /// +""" +Generate high-quality synthetic data using Chain-of-Thought Self-Instruct methodology. + +This script implements the CoT-Self-Instruct approach from the paper "CoT-Self-Instruct: +Building high-quality synthetic prompts for reasoning and non-reasoning tasks" (2025). + +It supports two modes: +1. Reasoning tasks: Generates both questions and answers with Chain-of-Thought +2. Instruction tasks: Generates diverse prompts for general instruction following + +Example usage: + # Reasoning tasks with Answer-Consistency filtering + uv run cot-self-instruct.py \\ + --seed-dataset davanstrien/s1k-reasoning \\ + --output-dataset username/synthetic-math \\ + --task-type reasoning \\ + --num-samples 5000 \\ + --filter-method answer-consistency + + # Instruction tasks with RIP filtering + uv run cot-self-instruct.py \\ + --seed-dataset wildchat-filtered \\ + --output-dataset username/synthetic-prompts \\ + --task-type instruction \\ + --filter-method rip \\ + --reward-model Nexusflow/Athene-RM-8B + + # HF Jobs execution + hf jobs uv run --flavor l4x4 \\ + --image vllm/vllm-openai \\ + -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\ + https://huggingface.co/datasets/uv-scripts/synthetic-data/raw/main/cot-self-instruct.py \\ + [args...] +""" + +import argparse +import json +import logging +import os +import random +import re +import sys +from collections import Counter +from datetime import datetime +from typing import Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +from datasets import Dataset, load_dataset +from huggingface_hub import DatasetCard, login +from sklearn.cluster import KMeans +from tqdm.auto import tqdm +from transformers import AutoTokenizer +from vllm import LLM, SamplingParams + +# Enable HF Transfer for faster downloads +os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" + +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger(__name__) + +# Prompt templates from the paper +REASONING_PROMPT_TEMPLATE = """You are a reasoning question generator assistant. Your goal is to create a novel, and challenging reasoning question. You are provided the following seed questions: +Seed Question 1: {seed1} +Seed Question 2: {seed2} +Your task is to: +1. Write a brand-new, self-contained reasoning question that meets the following requirements: +(a) The question draws inspiration from the seed question without copying it verbatim, remaining novel and of comparable difficulty. +(b) The question's final answer should be a single, unambiguous scalar value (e.g., an integer, reduced fraction, exact radical), or another answer type that can be verified in one step (e.g., 'yes/no,' a choice from A to D). +2. Then reason step by step, solve the new question and format your output as follows: +[New Question Begin]{{your_generated_question}}[New Question End] +[Final Answer to New Question Begin]\\boxed{{your_final_answer}}[Final Answer to New Question End]""" + +INSTRUCTION_PROMPT_TEMPLATE = """You are a prompt generator assistant. Your goal is to create diverse and creative synthetic prompts. +Please follow the steps below to create synthetic prompts. +Step 1: Carefully read #Prompt 1# and #Prompt 2#. Identify and list all the common elements between these two prompts. If no common elements are found, list the main elements from each prompt. +Step 2: Develop a comprehensive plan based on the #Common Elements List# or #Main Elements List# from Step 1. This plan will guide the generation of new synthetic prompts that are similar to the original prompts. +Step 3: Execute the plan step by step and provide one #Synthetic Prompt#. +Please reply strictly in the following format: +- Step 1 #Common Elements List# or #Main Elements List#: +- Step 2 #Plan#: +- Step 3 #Synthetic Prompt#: +#Prompt 1#: +{prompt1} +#Prompt 2#: +{prompt2}""" + + +def check_gpu_availability() -> int: + """Check if CUDA is available and return the number of GPUs.""" + if not torch.cuda.is_available(): + logger.error("CUDA is not available. This script requires a GPU.") + logger.error( + "Please run on a machine with NVIDIA GPU or use HF Jobs with GPU flavor." + ) + sys.exit(1) + + num_gpus = torch.cuda.device_count() + for i in range(num_gpus): + gpu_name = torch.cuda.get_device_name(i) + gpu_memory = torch.cuda.get_device_properties(i).total_memory / 1024**3 + logger.info(f"GPU {i}: {gpu_name} with {gpu_memory:.1f} GB memory") + + return num_gpus + + +def parse_thinking_output(text: str) -> str: + """Remove thinking tokens from model output.""" + # Remove ... blocks + text = re.sub(r'.*?', '', text, flags=re.DOTALL) + return text.strip() + + +def extract_reasoning_output(text: str) -> Tuple[Optional[str], Optional[str]]: + """Extract question and answer from reasoning task output.""" + text = parse_thinking_output(text) + + # Extract question + question_match = re.search(r'\[New Question Begin\](.*?)\[New Question End\]', text, re.DOTALL) + if not question_match: + return None, None + question = question_match.group(1).strip() + + # Extract answer + answer_match = re.search(r'\[Final Answer to New Question Begin\]\\?boxed\{(.*?)\}\[Final Answer to New Question End\]', text, re.DOTALL) + if not answer_match: + # Try without \boxed + answer_match = re.search(r'\[Final Answer to New Question Begin\](.*?)\[Final Answer to New Question End\]', text, re.DOTALL) + + if not answer_match: + return question, None + + answer = answer_match.group(1).strip() + return question, answer + + +def extract_instruction_output(text: str) -> Optional[str]: + """Extract synthetic prompt from instruction task output.""" + text = parse_thinking_output(text) + + # Look for the synthetic prompt after "Step 3 #Synthetic Prompt#:" + match = re.search(r'Step 3 #Synthetic Prompt#:\s*(.+)', text, re.DOTALL) + if match: + return match.group(1).strip() + return None + + +def categorize_prompts(prompts: List[str], num_categories: int = 8) -> Dict[int, List[int]]: + """Categorize prompts using clustering for instruction tasks.""" + from transformers import AutoModel + + logger.info(f"Categorizing {len(prompts)} prompts into {num_categories} categories...") + + # Use a small model for embeddings + tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") + model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") + + # Get embeddings + embeddings = [] + for prompt in tqdm(prompts, desc="Computing embeddings"): + inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512) + with torch.no_grad(): + outputs = model(**inputs) + embedding = outputs.last_hidden_state.mean(dim=1).numpy() + embeddings.append(embedding[0]) + + # Cluster + kmeans = KMeans(n_clusters=num_categories, random_state=42) + labels = kmeans.fit_predict(embeddings) + + # Group by category + categories = {} + for idx, label in enumerate(labels): + if label not in categories: + categories[label] = [] + categories[label].append(idx) + + return categories + + +def generate_synthetic_data( + llm: LLM, + seed_data: List[Dict], + task_type: str, + num_samples: int, + categories: Optional[Dict[int, List[int]]] = None, +) -> List[Dict]: + """Generate synthetic data using CoT-Self-Instruct.""" + synthetic_data = [] + + # Set up progress bar + pbar = tqdm(total=num_samples, desc="Generating synthetic data") + + while len(synthetic_data) < num_samples: + # Sample seed data + if task_type == "reasoning": + # Random sampling for reasoning tasks + seeds = random.sample(seed_data, min(2, len(seed_data))) + prompt = REASONING_PROMPT_TEMPLATE.format( + seed1=seeds[0].get("question", seeds[0].get("prompt", "")), + seed2=seeds[1].get("question", seeds[1].get("prompt", "")) if len(seeds) > 1 else seeds[0].get("question", seeds[0].get("prompt", "")) + ) + else: + # Category-aware sampling for instruction tasks + if categories: + # Pick a random category + category = random.choice(list(categories.keys())) + category_indices = categories[category] + indices = random.sample(category_indices, min(2, len(category_indices))) + seeds = [seed_data[i] for i in indices] + else: + seeds = random.sample(seed_data, min(2, len(seed_data))) + + prompt = INSTRUCTION_PROMPT_TEMPLATE.format( + prompt1=seeds[0].get("prompt", seeds[0].get("question", "")), + prompt2=seeds[1].get("prompt", seeds[1].get("question", "")) if len(seeds) > 1 else seeds[0].get("prompt", seeds[0].get("question", "")) + ) + + # Generate + sampling_params = SamplingParams( + temperature=0.7 if task_type == "reasoning" else 0.8, + top_p=0.95 if task_type == "reasoning" else 0.9, + max_tokens=2048, + ) + + outputs = llm.generate([prompt], sampling_params) + output_text = outputs[0].outputs[0].text + + # Parse output + if task_type == "reasoning": + question, answer = extract_reasoning_output(output_text) + if question and answer: + synthetic_data.append({ + "question": question, + "answer": answer, + "seed_indices": [seed_data.index(s) for s in seeds], + }) + pbar.update(1) + else: + synthetic_prompt = extract_instruction_output(output_text) + if synthetic_prompt: + synthetic_data.append({ + "prompt": synthetic_prompt, + "seed_indices": [seed_data.index(s) for s in seeds], + }) + pbar.update(1) + + pbar.close() + return synthetic_data + + +def answer_consistency_filter( + llm: LLM, + synthetic_data: List[Dict], + k_responses: int = 16, + threshold: float = 0.5, +) -> List[Dict]: + """Filter reasoning tasks using Answer-Consistency.""" + logger.info(f"Applying Answer-Consistency filter with K={k_responses}") + + filtered_data = [] + + for item in tqdm(synthetic_data, desc="Answer-Consistency filtering"): + question = item["question"] + original_answer = item["answer"] + + # Generate K responses + prompts = [question] * k_responses + sampling_params = SamplingParams( + temperature=0.6, + top_p=0.95, + max_tokens=1024, + ) + + outputs = llm.generate(prompts, sampling_params) + + # Extract answers + answers = [] + for output in outputs: + text = output.outputs[0].text + # Try to extract boxed answer + match = re.search(r'\\boxed\{(.*?)\}', text) + if match: + answers.append(match.group(1).strip()) + + if not answers: + continue + + # Get majority answer + answer_counts = Counter(answers) + if answer_counts: + majority_answer, count = answer_counts.most_common(1)[0] + + # Check if majority answer matches original and meets threshold + if (majority_answer == original_answer and + count / len(answers) >= threshold): + item["consistency_score"] = count / len(answers) + filtered_data.append(item) + + logger.info(f"Answer-Consistency: kept {len(filtered_data)}/{len(synthetic_data)} examples") + return filtered_data + + +def rip_filter( + llm: LLM, + synthetic_data: List[Dict], + reward_model_id: str, + k_responses: int = 32, + threshold: float = 0.5, +) -> List[Dict]: + """Filter using Rejecting Instruction Preferences (RIP).""" + logger.info(f"Applying RIP filter with K={k_responses} and reward model {reward_model_id}") + + # Note: In a full implementation, you would load and use the actual reward model + # For this example, we'll use a placeholder scoring mechanism + logger.warning("RIP filtering requires a reward model implementation - using placeholder") + + filtered_data = [] + + for item in tqdm(synthetic_data, desc="RIP filtering"): + prompt = item.get("prompt", item.get("question", "")) + + # Generate K responses + prompts = [prompt] * k_responses + sampling_params = SamplingParams( + temperature=1.0, + top_p=1.0, + max_tokens=1024, + ) + + outputs = llm.generate(prompts, sampling_params) + + # In real implementation: score each response with reward model + # For now, use length as a proxy (longer responses often score higher) + scores = [len(output.outputs[0].text) for output in outputs] + + # Use minimum score as quality indicator + min_score = min(scores) if scores else 0 + normalized_score = min_score / 1000 # Normalize to 0-1 range + + if normalized_score >= threshold: + item["rip_score"] = normalized_score + filtered_data.append(item) + + logger.info(f"RIP filter: kept {len(filtered_data)}/{len(synthetic_data)} examples") + return filtered_data + + +def create_dataset_card( + task_type: str, + source_dataset: str, + generation_model: str, + filter_method: str, + num_generated: int, + num_filtered: int, + generation_time: str, + additional_info: Dict = None, +) -> str: + """Create a comprehensive dataset card.""" + filter_info = "" + if filter_method == "answer-consistency": + filter_info = """ +### Answer-Consistency Filtering + +This dataset was filtered using Answer-Consistency: +- Generated K responses for each synthetic question +- Kept only examples where majority answer matched the generated answer +- Ensures high-quality, correctly solved problems""" + elif filter_method == "rip": + filter_info = """ +### RIP (Rejecting Instruction Preferences) Filtering + +This dataset was filtered using RIP: +- Generated K responses for each synthetic prompt +- Scored responses using a reward model +- Kept only prompts with high minimum scores""" + + return f"""--- +tags: +- synthetic-data +- cot-self-instruct +- {task_type} +- uv-script +--- + +# CoT-Self-Instruct Synthetic Data + +This dataset contains synthetic {task_type} data generated using the Chain-of-Thought Self-Instruct methodology. + +## Generation Details + +- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) +- **Generation Model**: [{generation_model}](https://huggingface.co/{generation_model}) +- **Task Type**: {task_type} +- **Filter Method**: {filter_method} +- **Generated Examples**: {num_generated:,} +- **After Filtering**: {num_filtered:,} ({(num_filtered/num_generated)*100:.1f}% acceptance rate) +- **Generation Date**: {generation_time} +{filter_info} + +## Methodology + +Generated using CoT-Self-Instruct, which: +1. Uses Chain-of-Thought reasoning to analyze seed examples +2. Generates new synthetic examples of similar quality and complexity +3. Applies quality filtering to ensure high-quality outputs + +Based on the paper: "CoT-Self-Instruct: Building high-quality synthetic prompts for reasoning and non-reasoning tasks" (2025) + +## Generation Script + +Generated using the CoT-Self-Instruct script from [uv-scripts/synthetic-data](https://huggingface.co/datasets/uv-scripts/synthetic-data). + +To reproduce: +```bash +uv run https://huggingface.co/datasets/uv-scripts/synthetic-data/raw/main/cot-self-instruct.py \\ + --seed-dataset {source_dataset} \\ + --output-dataset \\ + --task-type {task_type} \\ + --generation-model {generation_model} \\ + --filter-method {filter_method} +``` +""" + + +def main(): + parser = argparse.ArgumentParser( + description="Generate synthetic data using CoT-Self-Instruct", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=__doc__, + ) + + # Dataset arguments + parser.add_argument( + "--seed-dataset", + type=str, + required=True, + help="HuggingFace dataset ID containing seed examples", + ) + parser.add_argument( + "--output-dataset", + type=str, + required=True, + help="HuggingFace dataset ID for output", + ) + + # Task configuration + parser.add_argument( + "--task-type", + type=str, + choices=["reasoning", "instruction", "auto"], + default="auto", + help="Type of task (reasoning generates Q&A, instruction generates prompts)", + ) + parser.add_argument( + "--task-column", + type=str, + default=None, + help="Column name containing tasks (auto-detected if not specified)", + ) + + # Model configuration + parser.add_argument( + "--generation-model", + type=str, + default="Qwen/Qwen3-30B-A3B-Thinking-2507", + help="Model for synthetic data generation", + ) + parser.add_argument( + "--filter-model", + type=str, + default=None, + help="Model for filtering (defaults to generation model)", + ) + parser.add_argument( + "--reward-model", + type=str, + default="Nexusflow/Athene-RM-8B", + help="Reward model for RIP filtering", + ) + + # Generation parameters + parser.add_argument( + "--num-samples", + type=int, + default=5000, + help="Number of synthetic examples to generate", + ) + parser.add_argument( + "--batch-size", + type=int, + default=1, + help="Batch size for generation", + ) + + # Filtering parameters + parser.add_argument( + "--filter-method", + type=str, + choices=["answer-consistency", "rip", "both", "none"], + default="answer-consistency", + help="Quality filtering method", + ) + parser.add_argument( + "--k-responses", + type=int, + default=16, + help="Number of responses for filtering", + ) + parser.add_argument( + "--quality-threshold", + type=float, + default=0.5, + help="Minimum quality threshold for filtering", + ) + + # GPU configuration + parser.add_argument( + "--tensor-parallel-size", + type=int, + default=None, + help="Number of GPUs for tensor parallelism (auto-detected if not set)", + ) + parser.add_argument( + "--gpu-memory-utilization", + type=float, + default=0.9, + help="GPU memory utilization", + ) + + # Other arguments + parser.add_argument( + "--hf-token", + type=str, + default=None, + help="HuggingFace API token", + ) + parser.add_argument( + "--seed", + type=int, + default=42, + help="Random seed", + ) + + args = parser.parse_args() + + # Set random seeds + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + + # Check GPU + num_gpus = check_gpu_availability() + tensor_parallel_size = args.tensor_parallel_size or num_gpus + + # Authentication + hf_token = args.hf_token or os.environ.get("HF_TOKEN") + if hf_token: + login(token=hf_token) + + # Load seed dataset + logger.info(f"Loading seed dataset: {args.seed_dataset}") + seed_dataset = load_dataset(args.seed_dataset, split="train") + + # Auto-detect task type and column if needed + if args.task_type == "auto": + columns = seed_dataset.column_names + if "question" in columns and "answer" in columns: + args.task_type = "reasoning" + logger.info("Auto-detected task type: reasoning") + else: + args.task_type = "instruction" + logger.info("Auto-detected task type: instruction") + + if not args.task_column: + if args.task_type == "reasoning": + args.task_column = "question" + else: + # Try to find prompt column + for col in ["prompt", "instruction", "text", "input"]: + if col in seed_dataset.column_names: + args.task_column = col + break + + logger.info(f"Using task column: {args.task_column}") + + # Convert to list of dicts + seed_data = seed_dataset.to_list() + + # Categorize prompts for instruction tasks + categories = None + if args.task_type == "instruction" and len(seed_data) > 100: + prompts = [item.get(args.task_column, "") for item in seed_data] + categories = categorize_prompts(prompts) + + # Initialize generation model + logger.info(f"Loading generation model: {args.generation_model}") + generation_llm = LLM( + model=args.generation_model, + tensor_parallel_size=tensor_parallel_size, + gpu_memory_utilization=args.gpu_memory_utilization, + ) + + # Generate synthetic data + start_time = datetime.now() + synthetic_data = generate_synthetic_data( + generation_llm, + seed_data, + args.task_type, + args.num_samples, + categories, + ) + + # Apply filtering + filter_llm = generation_llm + if args.filter_model and args.filter_model != args.generation_model: + logger.info(f"Loading filter model: {args.filter_model}") + # Clean up generation model + del generation_llm + torch.cuda.empty_cache() + + filter_llm = LLM( + model=args.filter_model, + tensor_parallel_size=tensor_parallel_size, + gpu_memory_utilization=args.gpu_memory_utilization, + ) + + filtered_data = synthetic_data + if args.filter_method != "none": + if args.filter_method == "answer-consistency" and args.task_type == "reasoning": + filtered_data = answer_consistency_filter( + filter_llm, + synthetic_data, + args.k_responses, + args.quality_threshold, + ) + elif args.filter_method == "rip": + filtered_data = rip_filter( + filter_llm, + synthetic_data, + args.reward_model, + args.k_responses, + args.quality_threshold, + ) + elif args.filter_method == "both": + if args.task_type == "reasoning": + filtered_data = answer_consistency_filter( + filter_llm, + synthetic_data, + args.k_responses, + args.quality_threshold, + ) + filtered_data = rip_filter( + filter_llm, + filtered_data, + args.reward_model, + args.k_responses, + args.quality_threshold, + ) + + # Create HuggingFace dataset + logger.info(f"Creating dataset with {len(filtered_data)} examples") + dataset = Dataset.from_list(filtered_data) + + # Create dataset card + generation_time = start_time.strftime("%Y-%m-%d %H:%M:%S UTC") + dataset_card = create_dataset_card( + args.task_type, + args.seed_dataset, + args.generation_model, + args.filter_method, + len(synthetic_data), + len(filtered_data), + generation_time, + ) + + # Push to hub + logger.info(f"Pushing dataset to: {args.output_dataset}") + # Create dataset card + card = DatasetCard(dataset_card) + dataset.push_to_hub(args.output_dataset) + # Push card separately + card.push_to_hub(args.output_dataset) + + logger.info("Done! Dataset available at: https://huggingface.co/datasets/" + args.output_dataset) + + # Print example HF Jobs command if running locally + if len(sys.argv) > 1: + print("\nTo run on HF Jobs:") + print(f"""hf jobs uv run --flavor l4x4 \\ + --image vllm/vllm-openai \\ + -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\ + https://huggingface.co/datasets/uv-scripts/synthetic-data/raw/main/cot-self-instruct.py \\ + --seed-dataset {args.seed_dataset} \\ + --output-dataset {args.output_dataset} \\ + --task-type {args.task_type} \\ + --generation-model {args.generation_model} \\ + --filter-method {args.filter_method} \\ + --num-samples {args.num_samples}""") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/finepdfs-stats.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/finepdfs-stats.py new file mode 100644 index 0000000000000000000000000000000000000000..989732b64f8906d6f8fd474ac44b08beb0910127 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/finepdfs-stats.py @@ -0,0 +1,546 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "polars>=1.31.0", +# "huggingface-hub", +# "datasets", +# "ascii-graph", +# ] +# /// +""" +Analyze educational quality trends across CommonCrawl dumps using Polars streaming. + +Answers: "Is the web getting more educational over time?" + +Demonstrates Polars HF Hub integration - process 50M+ docs without downloading 300GB+. + +Example usage: + # Analyze English PDFs (default) + uv run finepdfs-stats.py + + # Analyze all 70+ languages + uv run finepdfs-stats.py --all-languages + + # Quick test + uv run finepdfs-stats.py --limit 10000 --show-plan + + # Save results to HF Hub + uv run finepdfs-stats.py --output-repo username/finepdfs-temporal-stats + + # Run on HF Jobs + hf jobs uv run \\ + -s HF_TOKEN \\ + -e HF_XET_HIGH_PERFORMANCE=1 \\ + https://huggingface.co/datasets/uv-scripts/dataset-stats/raw/main/finepdfs-stats.py \\ + -- --output-repo username/stats +""" + +import argparse +import logging +import os +import sys +import time +from pathlib import Path + +import polars as pl +from ascii_graph import Pyasciigraph +from datasets import Dataset +from huggingface_hub import HfApi, create_repo, list_repo_tree, login + +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger(__name__) + +# Common language+script codes for finepdfs-edu +COMMON_LANGUAGES = { + "eng_Latn": "English (Latin script)", + "fra_Latn": "French (Latin script)", + "deu_Latn": "German (Latin script)", + "spa_Latn": "Spanish (Latin script)", + "por_Latn": "Portuguese (Latin script)", + "ita_Latn": "Italian (Latin script)", + "nld_Latn": "Dutch (Latin script)", + "pol_Latn": "Polish (Latin script)", + "rus_Cyrl": "Russian (Cyrillic script)", + "zho_Hans": "Chinese (Simplified)", + "zho_Hant": "Chinese (Traditional)", + "jpn_Jpan": "Japanese", + "kor_Hang": "Korean", + "ara_Arab": "Arabic", + "hin_Deva": "Hindi (Devanagari)", +} + + +def list_available_languages(dataset_id: str) -> list[str]: + """List available language subsets in the dataset.""" + try: + tree = list_repo_tree(dataset_id, path_in_repo="data", repo_type="dataset") + languages = [ + item.path.replace("data/", "") + for item in tree + if item.path.startswith("data/") + and "/" not in item.path.replace("data/", "") + ] + return sorted(languages) + except Exception as e: + logger.warning(f"Could not list languages: {e}") + return list(COMMON_LANGUAGES.keys()) + + +def compute_temporal_stats(df: pl.LazyFrame, output_path: Path) -> pl.DataFrame: + """Single scan: compute stats grouped by dump for temporal analysis.""" + query = df.group_by("dump").agg( + pl.len().alias("doc_count"), + pl.col("token_count").sum().alias("total_tokens"), + pl.col("fw_edu_scores").list.mean().mean().alias("avg_edu_score"), + (pl.col("fw_edu_scores").list.mean() >= 3).sum().alias("high_edu_count"), + ) + query.sink_parquet(output_path, engine="streaming") + return pl.read_parquet(output_path) + + +def compute_global_stats(temporal: pl.DataFrame) -> pl.DataFrame: + """Compute global stats from temporal breakdown.""" + total = temporal["doc_count"].sum() + return pl.DataFrame( + { + "total_docs": [total], + "total_tokens": [temporal["total_tokens"].sum()], + "avg_edu_score": [ + (temporal["avg_edu_score"] * temporal["doc_count"]).sum() / total + ], + "high_edu_rate": [temporal["high_edu_count"].sum() / total], + "num_dumps": [len(temporal)], + } + ) + + +def format_temporal_stats(temporal: pl.DataFrame) -> pl.DataFrame: + """Format temporal stats with high_edu_rate, sorted chronologically.""" + return ( + temporal.with_columns( + (pl.col("high_edu_count") / pl.col("doc_count")).alias("high_edu_rate") + ) + .select(["dump", "doc_count", "avg_edu_score", "high_edu_rate"]) + .sort( + "dump" + ) # Chronological order (CC-MAIN-2017-xx comes before CC-MAIN-2024-xx) + ) + + +def create_ascii_charts(temporal_stats: pl.DataFrame) -> str: + """Create ASCII bar charts showing temporal trends.""" + # Extract year from dump name (CC-MAIN-2024-42 -> 2024) + # Group by year and average the values for cleaner display + yearly = ( + temporal_stats.with_columns( + pl.col("dump").str.extract(r"CC-MAIN-(\d{4})", 1).alias("year") + ) + .group_by("year") + .agg( + pl.col("doc_count").sum(), + pl.col("avg_edu_score").mean(), + pl.col("high_edu_rate").mean(), + ) + .sort("year") + ) + + lines = [] + + # High edu rate chart (more dramatic differences) + data_rate = [ + (row["year"], row["high_edu_rate"] * 100) + for row in yearly.iter_rows(named=True) + ] + graph = Pyasciigraph(line_length=60, float_format="{0:.1f}%") + lines.extend(graph.graph("High Educational Content (edu >= 3)", data_rate)) + + lines.append("") + + # Avg edu score chart + data_score = [ + (row["year"], row["avg_edu_score"]) for row in yearly.iter_rows(named=True) + ] + graph2 = Pyasciigraph(line_length=60, float_format="{0:.2f}") + lines.extend(graph2.graph("Average Educational Score", data_score)) + + return "\n".join(lines) + + +def create_readme( + args, + global_stats: pl.DataFrame, + temporal_stats: pl.DataFrame, + scan_time: float, + ascii_charts: str, +) -> str: + """Create README content for the stats dataset.""" + stats = global_stats.to_dicts()[0] + total_docs = stats.get("total_docs", 0) + docs_per_sec = total_docs / scan_time if scan_time > 0 else 0 + + # Get first and last year averages for trend (more representative than single dumps) + yearly = ( + temporal_stats.with_columns( + pl.col("dump").str.extract(r"CC-MAIN-(\d{4})", 1).alias("year") + ) + .group_by("year") + .agg( + pl.col("doc_count").sum(), + pl.col("avg_edu_score").mean(), + pl.col("high_edu_rate").mean(), + ) + .sort("year") + ) + first_year = yearly.head(1).to_dicts()[0] + last_year = yearly.tail(1).to_dicts()[0] + + scope = ( + "all languages" + if args.all_languages + else COMMON_LANGUAGES.get(args.lang, args.lang) + ) + + return f"""--- +tags: + - uv-script + - statistics + - polars + - finepdfs-edu + - temporal-analysis +license: odc-by +configs: + - config_name: global_stats + data_files: global_stats/train-*.parquet + - config_name: temporal_stats + data_files: temporal_stats/train-*.parquet +default_viewer_config: temporal_stats +--- + +# Is the Web Getting More Educational? + +Temporal analysis of educational quality in **{scope}** across {stats.get("num_dumps", 0)} CommonCrawl dumps. + +## Trend + +``` +{ascii_charts} +``` + +## Key Finding + +| Year | Avg Edu Score | High Edu Rate | +|------|---------------|---------------| +| {first_year["year"]} | {first_year["avg_edu_score"]:.2f} | {first_year["high_edu_rate"] * 100:.1f}% | +| {last_year["year"]} | {last_year["avg_edu_score"]:.2f} | {last_year["high_edu_rate"] * 100:.1f}% | + +## Performance + +- **{total_docs:,} documents** processed in **{scan_time:.0f} seconds** +- **{docs_per_sec:,.0f} docs/sec** using Polars streaming +- Single scan, no full dataset download required + +## Summary + +| Metric | Value | +|--------|-------| +| Scope | {scope} | +| Total Documents | {total_docs:,} | +| Total Tokens | {stats.get("total_tokens", 0):,} | +| Avg Edu Score | {stats.get("avg_edu_score", 0):.3f} | +| High Edu Rate | {stats.get("high_edu_rate", 0) * 100:.1f}% | +| CommonCrawl Dumps | {stats.get("num_dumps", 0)} | + +## Files + +- `global_stats` - Overall summary +- `temporal_stats` - Per-dump breakdown (sorted chronologically) + +## Reproduce + +```bash +uv run https://huggingface.co/datasets/uv-scripts/dataset-stats/raw/main/finepdfs-stats.py \\ + {"--all-languages" if args.all_languages else f"--lang {args.lang}"} --output-repo your-username/stats +``` + +## Source + +- **Dataset**: [{args.source_dataset}](https://huggingface.co/datasets/{args.source_dataset}) +- **Script**: [uv-scripts/dataset-stats](https://huggingface.co/datasets/uv-scripts/dataset-stats) +""" + + +def main(): + parser = argparse.ArgumentParser( + description="Analyze educational quality trends across CommonCrawl dumps", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=__doc__, + ) + + parser.add_argument( + "--source-dataset", + type=str, + default="HuggingFaceFW/finepdfs-edu", + help="Source dataset (default: HuggingFaceFW/finepdfs-edu)", + ) + + parser.add_argument( + "--lang", + type=str, + default="eng_Latn", + help="Language+script code (default: eng_Latn)", + ) + + parser.add_argument( + "--all-languages", + action="store_true", + help="Analyze all languages (70+) instead of single language", + ) + + parser.add_argument( + "--show-plan", + action="store_true", + help="Show Polars query plan (demonstrates optimization)", + ) + + parser.add_argument( + "--list-languages", + action="store_true", + help="List available languages and exit", + ) + + parser.add_argument( + "--limit", + type=int, + help="Limit to first N rows (for testing)", + ) + + parser.add_argument( + "--output-repo", + type=str, + help="HuggingFace dataset repository to upload results", + ) + + parser.add_argument( + "--output-dir", + type=str, + default="./stats_output", + help="Local directory for output files", + ) + + parser.add_argument( + "--hf-token", + type=str, + help="HuggingFace API token (or set HF_TOKEN env var)", + ) + + parser.add_argument( + "--private", + action="store_true", + help="Make the output dataset private", + ) + + args = parser.parse_args() + + # Check for high-performance mode + if os.environ.get("HF_XET_HIGH_PERFORMANCE"): + logger.info("High-performance mode enabled (HF_XET_HIGH_PERFORMANCE=1)") + + # List languages mode + if args.list_languages: + print(f"Available language+script codes for {args.source_dataset}:\n") + print("Common languages:") + for code, name in COMMON_LANGUAGES.items(): + print(f" {code:12} - {name}") + print("\nFetching full list from HF Hub...") + all_langs = list_available_languages(args.source_dataset) + print(f"\nAll available ({len(all_langs)} total):") + for lang in all_langs[:30]: # Show first 30 + name = COMMON_LANGUAGES.get(lang, "") + print(f" {lang:12} {name}") + if len(all_langs) > 30: + print(f" ... and {len(all_langs) - 30} more") + sys.exit(0) + + # Build the parquet path + if args.all_languages: + source_path = f"hf://datasets/{args.source_dataset}/data/*/train/*.parquet" + scope_desc = "all languages" + else: + source_path = ( + f"hf://datasets/{args.source_dataset}/data/{args.lang}/train/*.parquet" + ) + scope_desc = f"{args.lang} ({COMMON_LANGUAGES.get(args.lang, 'unknown')})" + + logger.info(f"Scanning: {source_path}") + logger.info(f"Scope: {scope_desc}") + + # Create lazy frame - this doesn't load any data yet! + logger.info("Creating lazy query plan...") + df = pl.scan_parquet(source_path) + + # Apply limit if specified + if args.limit: + logger.info(f"Limiting to first {args.limit:,} rows") + df = df.head(args.limit) + + # Show query plan if requested + if args.show_plan: + # Build a sample query to show the plan + sample_query = df.select( + pl.len(), + pl.col("token_count").sum(), + pl.col("language").n_unique(), + ) + print("\nQuery Plan (showing Polars optimization):") + print("=" * 60) + print(sample_query.explain()) + print("=" * 60) + print("\nNote: Polars uses projection pushdown - only reads columns needed!") + print("The 'text' column is never loaded, making this very fast.\n") + + # Create output directory + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + # Single scan: compute temporal stats + logger.info("Computing temporal stats (single scan)...") + start = time.perf_counter() + temporal_path = output_dir / "temporal_stats.parquet" + temporal_raw = compute_temporal_stats(df, temporal_path) + scan_time = time.perf_counter() - start + logger.info(f"Scan complete in {scan_time:.2f}s - {len(temporal_raw)} dumps") + + # Compute stats + global_stats = compute_global_stats(temporal_raw) + temporal_stats = format_temporal_stats(temporal_raw) + + # Save + global_stats.write_parquet(output_dir / "global_stats.parquet") + temporal_stats.write_parquet(output_dir / "temporal_stats.parquet") + + # Print results + total_docs = global_stats["total_docs"][0] + docs_per_sec = total_docs / scan_time if scan_time > 0 else 0 + + print("\n" + "=" * 70) + print("IS THE WEB GETTING MORE EDUCATIONAL?") + print("=" * 70) + + print(f"\nScope: {scope_desc}") + print(f"Dataset: {args.source_dataset}") + + print("\n" + "-" * 70) + print("GLOBAL STATS") + print("-" * 70) + print(global_stats) + + print("\n" + "-" * 70) + print(f"TEMPORAL TREND ({len(temporal_stats)} CommonCrawl dumps)") + print("-" * 70) + # Show first 5 and last 5 + if len(temporal_stats) > 10: + print("Earliest dumps:") + print(temporal_stats.head(5)) + print("\n...") + print("\nLatest dumps:") + print(temporal_stats.tail(5)) + else: + print(temporal_stats) + + # Create ASCII charts + ascii_charts = create_ascii_charts(temporal_stats) + print("\n" + "-" * 70) + print("TREND VISUALIZATION") + print("-" * 70) + print(ascii_charts) + + print("\n" + "-" * 70) + print("PERFORMANCE") + print("-" * 70) + print(f"Scan time: {scan_time:.2f}s") + print(f"Documents: {total_docs:,}") + print(f"Throughput: {docs_per_sec:,.0f} docs/sec") + + logger.info(f"Results saved to: {output_dir}") + + # Upload to HF Hub if requested + if args.output_repo: + hf_token = args.hf_token or os.environ.get("HF_TOKEN") + if hf_token: + login(token=hf_token) + + api = HfApi(token=hf_token) + + logger.info(f"Creating/updating dataset repository: {args.output_repo}") + create_repo( + args.output_repo, + repo_type="dataset", + private=args.private, + token=hf_token, + exist_ok=True, + ) + + # Upload each as a dataset config + configs = [ + ("global_stats", global_stats), + ("temporal_stats", temporal_stats), + ] + + for config_name, stats_df in configs: + logger.info(f"Uploading {config_name}...") + ds = Dataset.from_polars(stats_df) + ds.push_to_hub( + args.output_repo, + config_name=config_name, + token=hf_token, + private=args.private, + ) + time.sleep(1) # Avoid 409 conflicts + + # Upload README + readme_content = create_readme( + args, global_stats, temporal_stats, scan_time, ascii_charts + ) + api.upload_file( + path_or_fileobj=readme_content.encode(), + path_in_repo="README.md", + repo_id=args.output_repo, + repo_type="dataset", + token=hf_token, + ) + + dataset_url = f"https://huggingface.co/datasets/{args.output_repo}" + logger.info(f"Dataset uploaded: {dataset_url}") + print(f"\nResults uploaded to: {dataset_url}") + + +if __name__ == "__main__": + if len(sys.argv) == 1: + print("Is the Web Getting More Educational?") + print("=" * 40) + print("\nAnalyze educational quality trends across CommonCrawl dumps") + print("using Polars streaming - no download needed!\n") + print("Example commands:\n") + print("# Quick test:") + print("uv run finepdfs-stats.py --limit 10000\n") + print("# Analyze English PDFs:") + print("uv run finepdfs-stats.py\n") + print("# Analyze ALL 70+ languages:") + print("uv run finepdfs-stats.py --all-languages\n") + print("# Show query plan (see Polars optimization):") + print("uv run finepdfs-stats.py --show-plan --limit 1000\n") + print("# Save results to HF Hub:") + print("uv run finepdfs-stats.py --output-repo username/temporal-stats\n") + print("# Run on HF Jobs:") + print("hf jobs uv run \\") + print(" -s HF_TOKEN \\") + print(" -e HF_XET_HIGH_PERFORMANCE=1 \\") + print( + " https://huggingface.co/datasets/uv-scripts/dataset-stats/raw/main/finepdfs-stats.py \\" + ) + print(" -- --output-repo username/stats") + sys.exit(0) + + main() diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/generate-responses.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/generate-responses.py new file mode 100644 index 0000000000000000000000000000000000000000..1496f4494b32c5aac4f88429abe3926f93462ff3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/jobs/scripts/generate-responses.py @@ -0,0 +1,587 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = [ +# "datasets", +# "flashinfer-python", +# "huggingface-hub[hf_transfer]", +# "hf-xet>= 1.1.7", +# "torch", +# "transformers", +# "vllm>=0.8.5", +# ] +# +# /// +""" +Generate responses for prompts in a dataset using vLLM for efficient GPU inference. + +This script loads a dataset from Hugging Face Hub containing chat-formatted messages, +applies the model's chat template, generates responses using vLLM, and saves the +results back to the Hub with a comprehensive dataset card. + +Example usage: + # Local execution with auto GPU detection + uv run generate-responses.py \\ + username/input-dataset \\ + username/output-dataset \\ + --messages-column messages + + # With custom model and sampling parameters + uv run generate-responses.py \\ + username/input-dataset \\ + username/output-dataset \\ + --model-id meta-llama/Llama-3.1-8B-Instruct \\ + --temperature 0.9 \\ + --top-p 0.95 \\ + --max-tokens 2048 + + # HF Jobs execution (see script output for full command) + hf jobs uv run --flavor a100x4 ... +""" + +import argparse +import logging +import os +import sys +from datetime import datetime +from typing import Optional + +from datasets import load_dataset +from huggingface_hub import DatasetCard, get_token, login +from torch import cuda +from tqdm.auto import tqdm +from transformers import AutoTokenizer +from vllm import LLM, SamplingParams + +# Enable HF Transfer for faster downloads +os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" + +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger(__name__) + + +def check_gpu_availability() -> int: + """Check if CUDA is available and return the number of GPUs.""" + if not cuda.is_available(): + logger.error("CUDA is not available. This script requires a GPU.") + logger.error( + "Please run on a machine with NVIDIA GPU or use HF Jobs with GPU flavor." + ) + sys.exit(1) + + num_gpus = cuda.device_count() + for i in range(num_gpus): + gpu_name = cuda.get_device_name(i) + gpu_memory = cuda.get_device_properties(i).total_memory / 1024**3 + logger.info(f"GPU {i}: {gpu_name} with {gpu_memory:.1f} GB memory") + + return num_gpus + + +def create_dataset_card( + source_dataset: str, + model_id: str, + messages_column: str, + prompt_column: Optional[str], + sampling_params: SamplingParams, + tensor_parallel_size: int, + num_examples: int, + generation_time: str, + num_skipped: int = 0, + max_model_len_used: Optional[int] = None, +) -> str: + """Create a comprehensive dataset card documenting the generation process.""" + filtering_section = "" + if num_skipped > 0: + skip_percentage = (num_skipped / num_examples) * 100 + processed = num_examples - num_skipped + filtering_section = f""" + +### Filtering Statistics + +- **Total Examples**: {num_examples:,} +- **Processed**: {processed:,} ({100 - skip_percentage:.1f}%) +- **Skipped (too long)**: {num_skipped:,} ({skip_percentage:.1f}%) +- **Max Model Length Used**: {max_model_len_used:,} tokens + +Note: Prompts exceeding the maximum model length were skipped and have empty responses.""" + + return f"""--- +tags: +- generated +- vllm +- uv-script +--- + +# Generated Responses Dataset + +This dataset contains generated responses for prompts from [{source_dataset}](https://huggingface.co/datasets/{source_dataset}). + +## Generation Details + +- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) +- **Input Column**: `{prompt_column if prompt_column else messages_column}` ({"plain text prompts" if prompt_column else "chat messages"}) +- **Model**: [{model_id}](https://huggingface.co/{model_id}) +- **Number of Examples**: {num_examples:,} +- **Generation Date**: {generation_time}{filtering_section} + +### Sampling Parameters + +- **Temperature**: {sampling_params.temperature} +- **Top P**: {sampling_params.top_p} +- **Top K**: {sampling_params.top_k} +- **Min P**: {sampling_params.min_p} +- **Max Tokens**: {sampling_params.max_tokens} +- **Repetition Penalty**: {sampling_params.repetition_penalty} + +### Hardware Configuration + +- **Tensor Parallel Size**: {tensor_parallel_size} +- **GPU Configuration**: {tensor_parallel_size} GPU(s) + +## Dataset Structure + +The dataset contains all columns from the source dataset plus: +- `response`: The generated response from the model + +## Generation Script + +Generated using the vLLM inference script from [uv-scripts/vllm](https://huggingface.co/datasets/uv-scripts/vllm). + +To reproduce this generation: + +```bash +uv run https://huggingface.co/datasets/uv-scripts/vllm/raw/main/generate-responses.py \\ + {source_dataset} \\ + \\ + --model-id {model_id} \\ + {"--prompt-column " + prompt_column if prompt_column else "--messages-column " + messages_column} \\ + --temperature {sampling_params.temperature} \\ + --top-p {sampling_params.top_p} \\ + --top-k {sampling_params.top_k} \\ + --max-tokens {sampling_params.max_tokens}{f" \\\\\\n --max-model-len {max_model_len_used}" if max_model_len_used else ""} +``` +""" + + +def main( + src_dataset_hub_id: str, + output_dataset_hub_id: str, + model_id: str = "Qwen/Qwen3-30B-A3B-Instruct-2507", + messages_column: str = "messages", + prompt_column: Optional[str] = None, + output_column: str = "response", + temperature: float = 0.7, + top_p: float = 0.8, + top_k: int = 20, + min_p: float = 0.0, + max_tokens: int = 16384, + repetition_penalty: float = 1.0, + gpu_memory_utilization: float = 0.90, + max_model_len: Optional[int] = None, + tensor_parallel_size: Optional[int] = None, + skip_long_prompts: bool = True, + max_samples: Optional[int] = None, + hf_token: Optional[str] = None, +): + """ + Main generation pipeline. + + Args: + src_dataset_hub_id: Input dataset on Hugging Face Hub + output_dataset_hub_id: Where to save results on Hugging Face Hub + model_id: Hugging Face model ID for generation + messages_column: Column name containing chat messages + prompt_column: Column name containing plain text prompts (alternative to messages_column) + output_column: Column name for generated responses + temperature: Sampling temperature + top_p: Top-p sampling parameter + top_k: Top-k sampling parameter + min_p: Minimum probability threshold + max_tokens: Maximum tokens to generate + repetition_penalty: Repetition penalty parameter + gpu_memory_utilization: GPU memory utilization factor + max_model_len: Maximum model context length (None uses model default) + tensor_parallel_size: Number of GPUs to use (auto-detect if None) + skip_long_prompts: Skip prompts exceeding max_model_len instead of failing + max_samples: Maximum number of samples to process (None for all) + hf_token: Hugging Face authentication token + """ + generation_start_time = datetime.now().isoformat() + + # GPU check and configuration + num_gpus = check_gpu_availability() + if tensor_parallel_size is None: + tensor_parallel_size = num_gpus + logger.info( + f"Auto-detected {num_gpus} GPU(s), using tensor_parallel_size={tensor_parallel_size}" + ) + else: + logger.info(f"Using specified tensor_parallel_size={tensor_parallel_size}") + if tensor_parallel_size > num_gpus: + logger.warning( + f"Requested {tensor_parallel_size} GPUs but only {num_gpus} available" + ) + + # Authentication - try multiple methods + HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") or get_token() + + if not HF_TOKEN: + logger.error("No HuggingFace token found. Please provide token via:") + logger.error(" 1. --hf-token argument") + logger.error(" 2. HF_TOKEN environment variable") + logger.error(" 3. Run 'hf auth login' or use login() in Python") + sys.exit(1) + + logger.info("HuggingFace token found, authenticating...") + login(token=HF_TOKEN) + + # Initialize vLLM + logger.info(f"Loading model: {model_id}") + vllm_kwargs = { + "model": model_id, + "tensor_parallel_size": tensor_parallel_size, + "gpu_memory_utilization": gpu_memory_utilization, + } + if max_model_len is not None: + vllm_kwargs["max_model_len"] = max_model_len + logger.info(f"Using max_model_len={max_model_len}") + + llm = LLM(**vllm_kwargs) + + # Load tokenizer for chat template + logger.info("Loading tokenizer...") + tokenizer = AutoTokenizer.from_pretrained(model_id) + + # Create sampling parameters + sampling_params = SamplingParams( + temperature=temperature, + top_p=top_p, + top_k=top_k, + min_p=min_p, + max_tokens=max_tokens, + repetition_penalty=repetition_penalty, + ) + + # Load dataset + logger.info(f"Loading dataset: {src_dataset_hub_id}") + dataset = load_dataset(src_dataset_hub_id, split="train") + + # Apply max_samples if specified + if max_samples is not None and max_samples < len(dataset): + logger.info(f"Limiting dataset to {max_samples} samples") + dataset = dataset.select(range(max_samples)) + + total_examples = len(dataset) + logger.info(f"Dataset loaded with {total_examples:,} examples") + + # Determine which column to use and validate + if prompt_column: + # Use prompt column mode + if prompt_column not in dataset.column_names: + logger.error( + f"Column '{prompt_column}' not found. Available columns: {dataset.column_names}" + ) + sys.exit(1) + logger.info(f"Using prompt column mode with column: '{prompt_column}'") + use_messages = False + else: + # Use messages column mode + if messages_column not in dataset.column_names: + logger.error( + f"Column '{messages_column}' not found. Available columns: {dataset.column_names}" + ) + sys.exit(1) + logger.info(f"Using messages column mode with column: '{messages_column}'") + use_messages = True + + # Get effective max length for filtering + if max_model_len is not None: + effective_max_len = max_model_len + else: + # Get model's default max length + effective_max_len = llm.llm_engine.model_config.max_model_len + logger.info(f"Using effective max model length: {effective_max_len}") + + # Process messages and apply chat template + logger.info("Preparing prompts...") + all_prompts = [] + valid_prompts = [] + valid_indices = [] + skipped_info = [] + + for i, example in enumerate(tqdm(dataset, desc="Processing prompts")): + if use_messages: + # Messages mode: use existing chat messages + messages = example[messages_column] + # Apply chat template + prompt = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True + ) + else: + # Prompt mode: convert plain text to messages format + user_prompt = example[prompt_column] + messages = [{"role": "user", "content": user_prompt}] + # Apply chat template + prompt = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True + ) + + all_prompts.append(prompt) + + # Count tokens if filtering is enabled + if skip_long_prompts: + tokens = tokenizer.encode(prompt) + if len(tokens) <= effective_max_len: + valid_prompts.append(prompt) + valid_indices.append(i) + else: + skipped_info.append((i, len(tokens))) + else: + valid_prompts.append(prompt) + valid_indices.append(i) + + # Log filtering results + if skip_long_prompts and skipped_info: + logger.warning( + f"Skipped {len(skipped_info)} prompts that exceed max_model_len ({effective_max_len} tokens)" + ) + logger.info("Skipped prompt details (first 10):") + for idx, (prompt_idx, token_count) in enumerate(skipped_info[:10]): + logger.info( + f" - Example {prompt_idx}: {token_count} tokens (exceeds by {token_count - effective_max_len})" + ) + if len(skipped_info) > 10: + logger.info(f" ... and {len(skipped_info) - 10} more") + + skip_percentage = (len(skipped_info) / total_examples) * 100 + if skip_percentage > 10: + logger.warning(f"WARNING: {skip_percentage:.1f}% of prompts were skipped!") + + if not valid_prompts: + logger.error("No valid prompts to process after filtering!") + sys.exit(1) + + # Generate responses - vLLM handles batching internally + logger.info(f"Starting generation for {len(valid_prompts):,} valid prompts...") + logger.info("vLLM will handle batching and scheduling automatically") + + outputs = llm.generate(valid_prompts, sampling_params) + + # Extract generated text and create full response list + logger.info("Extracting generated responses...") + responses = [""] * total_examples # Initialize with empty strings + + for idx, output in enumerate(outputs): + original_idx = valid_indices[idx] + response = output.outputs[0].text.strip() + responses[original_idx] = response + + # Add responses to dataset + logger.info("Adding responses to dataset...") + dataset = dataset.add_column(output_column, responses) + + # Create dataset card + logger.info("Creating dataset card...") + card_content = create_dataset_card( + source_dataset=src_dataset_hub_id, + model_id=model_id, + messages_column=messages_column, + prompt_column=prompt_column, + sampling_params=sampling_params, + tensor_parallel_size=tensor_parallel_size, + num_examples=total_examples, + generation_time=generation_start_time, + num_skipped=len(skipped_info) if skip_long_prompts else 0, + max_model_len_used=effective_max_len if skip_long_prompts else None, + ) + + # Push dataset to hub + logger.info(f"Pushing dataset to: {output_dataset_hub_id}") + dataset.push_to_hub(output_dataset_hub_id, token=HF_TOKEN) + + # Push dataset card + card = DatasetCard(card_content) + card.push_to_hub(output_dataset_hub_id, token=HF_TOKEN) + + logger.info("✅ Generation complete!") + logger.info( + f"Dataset available at: https://huggingface.co/datasets/{output_dataset_hub_id}" + ) + + +if __name__ == "__main__": + if len(sys.argv) > 1: + parser = argparse.ArgumentParser( + description="Generate responses for dataset prompts using vLLM", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Basic usage with default Qwen model + uv run generate-responses.py input-dataset output-dataset + + # With custom model and parameters + uv run generate-responses.py input-dataset output-dataset \\ + --model-id meta-llama/Llama-3.1-8B-Instruct \\ + --temperature 0.9 \\ + --max-tokens 2048 + + # Force specific GPU configuration + uv run generate-responses.py input-dataset output-dataset \\ + --tensor-parallel-size 2 \\ + --gpu-memory-utilization 0.95 + + # Using environment variable for token + HF_TOKEN=hf_xxx uv run generate-responses.py input-dataset output-dataset + """, + ) + + parser.add_argument( + "src_dataset_hub_id", + help="Input dataset on Hugging Face Hub (e.g., username/dataset-name)", + ) + parser.add_argument( + "output_dataset_hub_id", help="Output dataset name on Hugging Face Hub" + ) + parser.add_argument( + "--model-id", + type=str, + default="Qwen/Qwen3-30B-A3B-Instruct-2507", + help="Model to use for generation (default: Qwen3-30B-A3B-Instruct-2507)", + ) + parser.add_argument( + "--messages-column", + type=str, + default="messages", + help="Column containing chat messages (default: messages)", + ) + parser.add_argument( + "--prompt-column", + type=str, + help="Column containing plain text prompts (alternative to --messages-column)", + ) + parser.add_argument( + "--output-column", + type=str, + default="response", + help="Column name for generated responses (default: response)", + ) + parser.add_argument( + "--max-samples", + type=int, + help="Maximum number of samples to process (default: all)", + ) + parser.add_argument( + "--temperature", + type=float, + default=0.7, + help="Sampling temperature (default: 0.7)", + ) + parser.add_argument( + "--top-p", + type=float, + default=0.8, + help="Top-p sampling parameter (default: 0.8)", + ) + parser.add_argument( + "--top-k", + type=int, + default=20, + help="Top-k sampling parameter (default: 20)", + ) + parser.add_argument( + "--min-p", + type=float, + default=0.0, + help="Minimum probability threshold (default: 0.0)", + ) + parser.add_argument( + "--max-tokens", + type=int, + default=16384, + help="Maximum tokens to generate (default: 16384)", + ) + parser.add_argument( + "--repetition-penalty", + type=float, + default=1.0, + help="Repetition penalty (default: 1.0)", + ) + parser.add_argument( + "--gpu-memory-utilization", + type=float, + default=0.90, + help="GPU memory utilization factor (default: 0.90)", + ) + parser.add_argument( + "--max-model-len", + type=int, + help="Maximum model context length (default: model's default)", + ) + parser.add_argument( + "--tensor-parallel-size", + type=int, + help="Number of GPUs to use (default: auto-detect)", + ) + parser.add_argument( + "--hf-token", + type=str, + help="Hugging Face token (can also use HF_TOKEN env var)", + ) + parser.add_argument( + "--skip-long-prompts", + action="store_true", + default=True, + help="Skip prompts that exceed max_model_len instead of failing (default: True)", + ) + parser.add_argument( + "--no-skip-long-prompts", + dest="skip_long_prompts", + action="store_false", + help="Fail on prompts that exceed max_model_len", + ) + + args = parser.parse_args() + + main( + src_dataset_hub_id=args.src_dataset_hub_id, + output_dataset_hub_id=args.output_dataset_hub_id, + model_id=args.model_id, + messages_column=args.messages_column, + prompt_column=args.prompt_column, + output_column=args.output_column, + temperature=args.temperature, + top_p=args.top_p, + top_k=args.top_k, + min_p=args.min_p, + max_tokens=args.max_tokens, + repetition_penalty=args.repetition_penalty, + gpu_memory_utilization=args.gpu_memory_utilization, + max_model_len=args.max_model_len, + tensor_parallel_size=args.tensor_parallel_size, + skip_long_prompts=args.skip_long_prompts, + max_samples=args.max_samples, + hf_token=args.hf_token, + ) + else: + # Show HF Jobs example when run without arguments + print(""" +vLLM Response Generation Script +============================== + +This script requires arguments. For usage information: + uv run generate-responses.py --help + +Example HF Jobs command with multi-GPU: + # If you're logged in with hf auth, token will be auto-detected + hf jobs uv run \\ + --flavor l4x4 \\ + https://huggingface.co/datasets/uv-scripts/vllm/raw/main/generate-responses.py \\ + username/input-dataset \\ + username/output-dataset \\ + --messages-column messages \\ + --model-id Qwen/Qwen3-30B-A3B-Instruct-2507 \\ + --temperature 0.7 \\ + --max-tokens 16384 + """) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..eaba5091eac079712cfbd9b0d35f27c677854083 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/SKILL.md @@ -0,0 +1,716 @@ +--- +name: huggingface-llm-trainer +description: This skill should be used when users want to train or fine-tune language models using TRL (Transformer Reinforcement Learning) on Hugging Face Jobs infrastructure. Covers SFT, DPO, GRPO and reward modeling training methods, plus GGUF conversion for local deployment. Includes guidance on the TRL Jobs package, UV scripts with PEP 723 format, dataset preparation and validation, hardware selection, cost estimation, Trackio monitoring, Hub authentication, and model persistence. Should be invoked for tasks involving cloud GPU training, GGUF conversion, or when users mention training on Hugging Face Jobs without local GPU setup. +--- + +# TRL Training on Hugging Face Jobs + +## Overview + +Train language models using TRL (Transformer Reinforcement Learning) on fully managed Hugging Face infrastructure. No local GPU setup required—models train on cloud GPUs and results are automatically saved to the Hugging Face Hub. + +**TRL provides multiple training methods:** +- **SFT** (Supervised Fine-Tuning) - Standard instruction tuning +- **DPO** (Direct Preference Optimization) - Alignment from preference data +- **GRPO** (Group Relative Policy Optimization) - Online RL training +- **Reward Modeling** - Train reward models for RLHF + +**For detailed TRL method documentation:** +```python +hf_doc_search("your query", product="trl") +hf_doc_fetch("https://huggingface.co/docs/trl/sft_trainer") # SFT +hf_doc_fetch("https://huggingface.co/docs/trl/dpo_trainer") # DPO +# etc. +``` + +**See also:** `references/training_methods.md` for method overviews and selection guidance + +## When to Use This Skill + +Use this skill when users want to: +- Fine-tune language models on cloud GPUs without local infrastructure +- Train with TRL methods (SFT, DPO, GRPO, etc.) +- Run training jobs on Hugging Face Jobs infrastructure +- Convert trained models to GGUF for local deployment (Ollama, LM Studio, llama.cpp) +- Ensure trained models are permanently saved to the Hub +- Use modern workflows with optimized defaults + +### When to Use Unsloth + +Use **Unsloth** (`references/unsloth.md`) instead of standard TRL when: +- **Limited GPU memory** - Unsloth uses ~60% less VRAM +- **Speed matters** - Unsloth is ~2x faster +- Training **large models (>13B)** - memory efficiency is critical +- Training **Vision-Language Models (VLMs)** - Unsloth has `FastVisionModel` support + +See `references/unsloth.md` for complete Unsloth documentation and `scripts/unsloth_sft_example.py` for a production-ready training script. + +## Key Directives + +When assisting with training jobs: + +1. **ALWAYS use `hf_jobs()` MCP tool** - Submit jobs using `hf_jobs("uv", {...})`, NOT bash `trl-jobs` commands. The `script` parameter accepts Python code directly. Do NOT save to local files unless the user explicitly requests it. Pass the script content as a string to `hf_jobs()`. If user asks to "train a model", "fine-tune", or similar requests, you MUST create the training script AND submit the job immediately using `hf_jobs()`. + +2. **Always include Trackio** - Every training script should include Trackio for real-time monitoring. Use example scripts in `scripts/` as templates. + +3. **Provide job details after submission** - After submitting, provide job ID, monitoring URL, estimated time, and note that the user can request status checks later. + +4. **Use example scripts as templates** - Reference `scripts/train_sft_example.py`, `scripts/train_dpo_example.py`, etc. as starting points. + +## Local Script Execution + +Repository scripts use PEP 723 inline dependencies. Run them with `uv run`: +```bash +uv run scripts/estimate_cost.py --help +uv run scripts/dataset_inspector.py --help +``` + +## Prerequisites Checklist + +Before starting any training job, verify: + +### ✅ **Account & Authentication** +- Hugging Face Account with [Pro](https://hf.co/pro), [Team](https://hf.co/enterprise), or [Enterprise](https://hf.co/enterprise) plan (Jobs require paid plan) +- Authenticated login: Check with `hf_whoami()` +- **HF_TOKEN for Hub Push** ⚠️ CRITICAL - Training environment is ephemeral, must push to Hub or ALL training results are lost +- Token must have write permissions +- **MUST pass `secrets={"HF_TOKEN": "$HF_TOKEN"}` in job config** to make token available (the `$HF_TOKEN` syntax + references your actual token value) + +### ✅ **Dataset Requirements** +- Dataset must exist on Hub or be loadable via `datasets.load_dataset()` +- Format must match training method (SFT: "messages"/text/prompt-completion; DPO: chosen/rejected; GRPO: prompt-only) +- **ALWAYS validate unknown datasets** before GPU training to prevent format failures (see Dataset Validation section below) +- Size appropriate for hardware (Demo: 50-100 examples on t4-small; Production: 1K-10K+ on a10g-large/a100-large) + +### ⚠️ **Critical Settings** +- **Timeout must exceed expected training time** - Default 30min is TOO SHORT for most training. Minimum recommended: 1-2 hours. Job fails and loses all progress if timeout is exceeded. +- **Hub push must be enabled** - Config: `push_to_hub=True`, `hub_model_id="username/model-name"`; Job: `secrets={"HF_TOKEN": "$HF_TOKEN"}` + +## Asynchronous Job Guidelines + +**⚠️ IMPORTANT: Training jobs run asynchronously and can take hours** + +### Action Required + +**When user requests training:** +1. **Create the training script** with Trackio included (use `scripts/train_sft_example.py` as template) +2. **Submit immediately** using `hf_jobs()` MCP tool with script content inline - don't save to file unless user requests +3. **Report submission** with job ID, monitoring URL, and estimated time +4. **Wait for user** to request status checks - don't poll automatically + +### Ground Rules +- **Jobs run in background** - Submission returns immediately; training continues independently +- **Initial logs delayed** - Can take 30-60 seconds for logs to appear +- **User checks status** - Wait for user to request status updates +- **Avoid polling** - Check logs only on user request; provide monitoring links instead + +### After Submission + +**Provide to user:** +- ✅ Job ID and monitoring URL +- ✅ Expected completion time +- ✅ Trackio dashboard URL +- ✅ Note that user can request status checks later + +**Example Response:** +``` +✅ Job submitted successfully! + +Job ID: abc123xyz +Monitor: https://huggingface.co/jobs/username/abc123xyz + +Expected time: ~2 hours +Estimated cost: ~$10 + +The job is running in the background. Ask me to check status/logs when ready! +``` + +## Quick Start: Three Approaches + +**💡 Tip for Demos:** For quick demos on smaller GPUs (t4-small), omit `eval_dataset` and `eval_strategy` to save ~40% memory. You'll still see training loss and learning progress. + +### Sequence Length Configuration + +**TRL config classes use `max_length` (not `max_seq_length`)** to control tokenized sequence length: + +```python +# ✅ CORRECT - If you need to set sequence length +SFTConfig(max_length=512) # Truncate sequences to 512 tokens +DPOConfig(max_length=2048) # Longer context (2048 tokens) + +# ❌ WRONG - This parameter doesn't exist +SFTConfig(max_seq_length=512) # TypeError! +``` + +**Default behavior:** `max_length=1024` (truncates from right). This works well for most training. + +**When to override:** +- **Longer context**: Set higher (e.g., `max_length=2048`) +- **Memory constraints**: Set lower (e.g., `max_length=512`) +- **Vision models**: Set `max_length=None` (prevents cutting image tokens) + +**Usually you don't need to set this parameter at all** - the examples below use the sensible default. + +### Approach 1: UV Scripts (Recommended—Default Choice) + +UV scripts use PEP 723 inline dependencies for clean, self-contained training. **This is the primary approach for Codex.** + +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["trl>=0.12.0", "peft>=0.7.0", "trackio"] +# /// + +from datasets import load_dataset +from peft import LoraConfig +from trl import SFTTrainer, SFTConfig +import trackio + +dataset = load_dataset("trl-lib/Capybara", split="train") + +# Create train/eval split for monitoring +dataset_split = dataset.train_test_split(test_size=0.1, seed=42) + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset_split["train"], + eval_dataset=dataset_split["test"], + peft_config=LoraConfig(r=16, lora_alpha=32), + args=SFTConfig( + output_dir="my-model", + push_to_hub=True, + hub_model_id="username/my-model", + num_train_epochs=3, + eval_strategy="steps", + eval_steps=50, + report_to="trackio", + project="meaningful_prject_name", # project name for the training name (trackio) + run_name="meaningful_run_name", # descriptive name for the specific training run (trackio) + ) +) + +trainer.train() +trainer.push_to_hub() +""", + "flavor": "a10g-large", + "timeout": "2h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +**Benefits:** Direct MCP tool usage, clean code, dependencies declared inline (PEP 723), no file saving required, full control +**When to use:** Default choice for all training tasks in Codex, custom training logic, any scenario requiring `hf_jobs()` + +#### Working with Scripts + +⚠️ **Important:** The `script` parameter accepts either inline code (as shown above) OR a URL. **Local file paths do NOT work.** + +**Why local paths don't work:** +Jobs run in isolated Docker containers without access to your local filesystem. Scripts must be: +- Inline code (recommended for custom training) +- Publicly accessible URLs +- Private repo URLs (with HF_TOKEN) + +**Common mistakes:** +```python +# ❌ These will all fail +hf_jobs("uv", {"script": "train.py"}) +hf_jobs("uv", {"script": "./scripts/train.py"}) +hf_jobs("uv", {"script": "/path/to/train.py"}) +``` + +**Correct approaches:** +```python +# ✅ Inline code (recommended) +hf_jobs("uv", {"script": "# /// script\n# dependencies = [...]\n# ///\n\n"}) + +# ✅ From Hugging Face Hub +hf_jobs("uv", {"script": "https://huggingface.co/user/repo/resolve/main/train.py"}) + +# ✅ From GitHub +hf_jobs("uv", {"script": "https://raw.githubusercontent.com/user/repo/main/train.py"}) + +# ✅ From Gist +hf_jobs("uv", {"script": "https://gist.githubusercontent.com/user/id/raw/train.py"}) +``` + +**To use local scripts:** Upload to HF Hub first: +```bash +hf repos create my-training-scripts --type model +hf upload my-training-scripts ./train.py train.py +# Use: https://huggingface.co/USERNAME/my-training-scripts/resolve/main/train.py +``` + +### Approach 2: TRL Maintained Scripts (Official Examples) + +TRL provides battle-tested scripts for all methods. Can be run from URLs: + +```python +hf_jobs("uv", { + "script": "https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py", + "script_args": [ + "--model_name_or_path", "Qwen/Qwen2.5-0.5B", + "--dataset_name", "trl-lib/Capybara", + "--output_dir", "my-model", + "--push_to_hub", + "--hub_model_id", "username/my-model" + ], + "flavor": "a10g-large", + "timeout": "2h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +**Benefits:** No code to write, maintained by TRL team, production-tested +**When to use:** Standard TRL training, quick experiments, don't need custom code +**Available:** Scripts are available from https://github.com/huggingface/trl/tree/main/examples/scripts + +### Finding More UV Scripts on Hub + +The `uv-scripts` organization provides ready-to-use UV scripts stored as datasets on Hugging Face Hub: + +```python +# Discover available UV script collections +dataset_search({"author": "uv-scripts", "sort": "downloads", "limit": 20}) + +# Explore a specific collection +hub_repo_details(["uv-scripts/classification"], repo_type="dataset", include_readme=True) +``` + +**Popular collections:** ocr, classification, synthetic-data, vllm, dataset-creation + +### Approach 3: HF Jobs CLI (Direct Terminal Commands) + +When the `hf_jobs()` MCP tool is unavailable, use the `hf jobs` CLI directly. + +**⚠️ CRITICAL: CLI Syntax Rules** + +```bash +# ✅ CORRECT syntax - flags BEFORE script URL +hf jobs uv run --flavor a10g-large --timeout 2h --secrets HF_TOKEN "https://example.com/train.py" + +# ❌ WRONG - "run uv" instead of "uv run" +hf jobs run uv "https://example.com/train.py" --flavor a10g-large + +# ❌ WRONG - flags AFTER script URL (will be ignored!) +hf jobs uv run "https://example.com/train.py" --flavor a10g-large + +# ❌ WRONG - "--secret" instead of "--secrets" (plural) +hf jobs uv run --secret HF_TOKEN "https://example.com/train.py" +``` + +**Key syntax rules:** +1. Command order is `hf jobs uv run` (NOT `hf jobs run uv`) +2. All flags (`--flavor`, `--timeout`, `--secrets`) must come BEFORE the script URL +3. Use `--secrets` (plural), not `--secret` +4. Script URL must be the last positional argument + +**Complete CLI example:** +```bash +hf jobs uv run \ + --flavor a10g-large \ + --timeout 2h \ + --secrets HF_TOKEN \ + "https://huggingface.co/user/repo/resolve/main/train.py" +``` + +**Check job status via CLI:** +```bash +hf jobs ps # List all jobs +hf jobs logs # View logs +hf jobs inspect # Job details +hf jobs cancel # Cancel a job +``` + +### Approach 4: TRL Jobs Package (Simplified Training) + +The `trl-jobs` package provides optimized defaults and one-liner training. + +```bash +uvx trl-jobs sft \ + --model_name Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/Capybara + +``` + +**Benefits:** Pre-configured settings, automatic Trackio integration, automatic Hub push, one-line commands +**When to use:** User working in terminal directly (not Codex context), quick local experimentation +**Repository:** https://github.com/huggingface/trl-jobs + +⚠️ **In Codex context, prefer using `hf_jobs()` MCP tool (Approach 1) when available.** + +## Hardware Selection + +| Model Size | Recommended Hardware | Cost (approx/hr) | Use Case | +|------------|---------------------|------------------|----------| +| <1B params | `t4-small` | ~$0.75 | Demos, quick tests only without eval steps | +| 1-3B params | `t4-medium`, `l4x1` | ~$1.50-2.50 | Development | +| 3-7B params | `a10g-small`, `a10g-large` | ~$3.50-5.00 | Production training | +| 7-13B params | `a10g-large`, `a100-large` | ~$5-10 | Large models (use LoRA) | +| 13B+ params | `a100-large`, `a10g-largex2` | ~$10-20 | Very large (use LoRA) | + +**GPU Flavors:** cpu-basic/upgrade/performance/xl, t4-small/medium, l4x1/x4, a10g-small/large/largex2/largex4, a100-large, h100/h100x8 + +**Guidelines:** +- Use **LoRA/PEFT** for models >7B to reduce memory +- Multi-GPU automatically handled by TRL/Accelerate +- Start with smaller hardware for testing + +**See:** `references/hardware_guide.md` for detailed specifications + +## Critical: Saving Results to Hub + +**⚠️ EPHEMERAL ENVIRONMENT—MUST PUSH TO HUB** + +The Jobs environment is temporary. All files are deleted when the job ends. If the model isn't pushed to Hub, **ALL TRAINING IS LOST**. + +### Required Configuration + +**In training script/config:** +```python +SFTConfig( + push_to_hub=True, + hub_model_id="username/model-name", # MUST specify + hub_strategy="every_save", # Optional: push checkpoints +) +``` + +**In job submission:** +```python +{ + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # Enables authentication +} +``` + +### Verification Checklist + +Before submitting: +- [ ] `push_to_hub=True` set in config +- [ ] `hub_model_id` includes username/repo-name +- [ ] `secrets` parameter includes HF_TOKEN +- [ ] User has write access to target repo + +**See:** `references/hub_saving.md` for detailed troubleshooting + +## Timeout Management + +**⚠️ DEFAULT: 30 MINUTES—TOO SHORT FOR TRAINING** + +### Setting Timeouts + +```python +{ + "timeout": "2h" # 2 hours (formats: "90m", "2h", "1.5h", or seconds as integer) +} +``` + +### Timeout Guidelines + +| Scenario | Recommended | Notes | +|----------|-------------|-------| +| Quick demo (50-100 examples) | 10-30 min | Verify setup | +| Development training | 1-2 hours | Small datasets | +| Production (3-7B model) | 4-6 hours | Full datasets | +| Large model with LoRA | 3-6 hours | Depends on dataset | + +**Always add 20-30% buffer** for model/dataset loading, checkpoint saving, Hub push operations, and network delays. + +**On timeout:** Job killed immediately, all unsaved progress lost, must restart from beginning + +## Cost Estimation + +**Offer to estimate cost when planning jobs with known parameters.** Use `scripts/estimate_cost.py`: + +```bash +uv run scripts/estimate_cost.py \ + --model meta-llama/Llama-2-7b-hf \ + --dataset trl-lib/Capybara \ + --hardware a10g-large \ + --dataset-size 16000 \ + --epochs 3 +``` + +Output includes estimated time, cost, recommended timeout (with buffer), and optimization suggestions. + +**When to offer:** User planning a job, asks about cost/time, choosing hardware, job will run >1 hour or cost >$5 + +## Example Training Scripts + +**Production-ready templates with all best practices:** + +Load these scripts for correctly: + +- **`scripts/train_sft_example.py`** - Complete SFT training with Trackio, LoRA, checkpoints +- **`scripts/train_dpo_example.py`** - DPO training for preference learning +- **`scripts/train_grpo_example.py`** - GRPO training for online RL + +These scripts demonstrate proper Hub saving, Trackio integration, checkpoint management, and optimized parameters. Pass their content inline to `hf_jobs()` or use as templates for custom scripts. + +## Monitoring and Tracking + +**Trackio** provides real-time metrics visualization. See `references/trackio_guide.md` for complete setup guide. + +**Key points:** +- Add `trackio` to dependencies +- Configure trainer with `report_to="trackio" and run_name="meaningful_name"` + +### Trackio Configuration Defaults + +**Use sensible defaults unless user specifies otherwise.** When generating training scripts with Trackio: + +**Default Configuration:** +- **Space ID**: `{username}/trackio` (use "trackio" as default space name) +- **Run naming**: Unless otherwise specified, name the run in a way the user will recognize (e.g., descriptive of the task, model, or purpose) +- **Config**: Keep minimal - only include hyperparameters and model/dataset info +- **Project Name**: Use a Project Name to associate runs with a particular Project + +**User overrides:** If user requests specific trackio configuration (custom space, run naming, grouping, or additional config), apply their preferences instead of defaults. + + +This is useful for managing multiple jobs with the same configuration or keeping training scripts portable. + +See `references/trackio_guide.md` for complete documentation including grouping runs for experiments. + +### Check Job Status + +```python +# List all jobs +hf_jobs("ps") + +# Inspect specific job +hf_jobs("inspect", {"job_id": "your-job-id"}) + +# View logs +hf_jobs("logs", {"job_id": "your-job-id"}) +``` + +**Remember:** Wait for user to request status checks. Avoid polling repeatedly. + +## Dataset Validation + +**Validate dataset format BEFORE launching GPU training to prevent the #1 cause of training failures: format mismatches.** + +### Why Validate + +- 50%+ of training failures are due to dataset format issues +- DPO especially strict: requires exact column names (`prompt`, `chosen`, `rejected`) +- Failed GPU jobs waste $1-10 and 30-60 minutes +- Validation on CPU costs ~$0.01 and takes <1 minute + +### When to Validate + +**ALWAYS validate for:** +- Unknown or custom datasets +- DPO training (CRITICAL - 90% of datasets need mapping) +- Any dataset not explicitly TRL-compatible + +**Skip validation for known TRL datasets:** +- `trl-lib/ultrachat_200k`, `trl-lib/Capybara`, `HuggingFaceH4/ultrachat_200k`, etc. + +### Usage + +```python +hf_jobs("uv", { + "script": "https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py", + "script_args": ["--dataset", "username/dataset-name", "--split", "train"] +}) +``` + +The script is fast, and will usually complete synchronously. + +### Reading Results + +The output shows compatibility for each training method: + +- **`✓ READY`** - Dataset is compatible, use directly +- **`✗ NEEDS MAPPING`** - Compatible but needs preprocessing (mapping code provided) +- **`✗ INCOMPATIBLE`** - Cannot be used for this method + +When mapping is needed, the output includes a **"MAPPING CODE"** section with copy-paste ready Python code. + +### Example Workflow + +```python +# 1. Inspect dataset (costs ~$0.01, <1 min on CPU) +hf_jobs("uv", { + "script": "https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py", + "script_args": ["--dataset", "argilla/distilabel-math-preference-dpo", "--split", "train"] +}) + +# 2. Check output markers: +# ✓ READY → proceed with training +# ✗ NEEDS MAPPING → apply mapping code below +# ✗ INCOMPATIBLE → choose different method/dataset + +# 3. If mapping needed, apply before training: +def format_for_dpo(example): + return { + 'prompt': example['instruction'], + 'chosen': example['chosen_response'], + 'rejected': example['rejected_response'], + } +dataset = dataset.map(format_for_dpo, remove_columns=dataset.column_names) + +# 4. Launch training job with confidence +``` + +### Common Scenario: DPO Format Mismatch + +Most DPO datasets use non-standard column names. Example: + +``` +Dataset has: instruction, chosen_response, rejected_response +DPO expects: prompt, chosen, rejected +``` + +The validator detects this and provides exact mapping code to fix it. + +## Converting Models to GGUF + +After training, convert models to **GGUF format** for use with llama.cpp, Ollama, LM Studio, and other local inference tools. + +**What is GGUF:** +- Optimized for CPU/GPU inference with llama.cpp +- Supports quantization (4-bit, 5-bit, 8-bit) to reduce model size +- Compatible with Ollama, LM Studio, Jan, GPT4All, llama.cpp +- Typically 2-8GB for 7B models (vs 14GB unquantized) + +**When to convert:** +- Running models locally with Ollama or LM Studio +- Reducing model size with quantization +- Deploying to edge devices +- Sharing models for local-first use + +**See:** `references/gguf_conversion.md` for complete conversion guide, including production-ready conversion script, quantization options, hardware requirements, usage examples, and troubleshooting. + +**Quick conversion:** +```python +hf_jobs("uv", { + "script": "", + "flavor": "a10g-large", + "timeout": "45m", + "secrets": {"HF_TOKEN": "$HF_TOKEN"}, + "env": { + "ADAPTER_MODEL": "username/my-finetuned-model", + "BASE_MODEL": "Qwen/Qwen2.5-0.5B", + "OUTPUT_REPO": "username/my-model-gguf" + } +}) +``` + +## Common Training Patterns + +See `references/training_patterns.md` for detailed examples including: +- Quick demo (5-10 minutes) +- Production with checkpoints +- Multi-GPU training +- DPO training (preference learning) +- GRPO training (online RL) + +## Common Failure Modes + +### Out of Memory (OOM) + +**Fix (try in order):** +1. Reduce batch size: `per_device_train_batch_size=1`, increase `gradient_accumulation_steps=8`. Effective batch size is `per_device_train_batch_size` x `gradient_accumulation_steps`. For best performance keep effective batch size close to 128. +2. Enable: `gradient_checkpointing=True` +3. Upgrade hardware: t4-small → l4x1, a10g-small → a10g-large etc. + +### Dataset Misformatted + +**Fix:** +1. Validate first with dataset inspector: + ```bash + uv run https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py \ + --dataset name --split train + ``` +2. Check output for compatibility markers (✓ READY, ✗ NEEDS MAPPING, ✗ INCOMPATIBLE) +3. Apply mapping code from inspector output if needed + +### Job Timeout + +**Fix:** +1. Check logs for actual runtime: `hf_jobs("logs", {"job_id": "..."})` +2. Increase timeout with buffer: `"timeout": "3h"` (add 30% to estimated time) +3. Or reduce training: lower `num_train_epochs`, use smaller dataset, enable `max_steps` +4. Save checkpoints: `save_strategy="steps"`, `save_steps=500`, `hub_strategy="every_save"` + +**Note:** Default 30min is insufficient for real training. Minimum 1-2 hours. + +### Hub Push Failures + +**Fix:** +1. Add to job: `secrets={"HF_TOKEN": "$HF_TOKEN"}` +2. Add to config: `push_to_hub=True`, `hub_model_id="username/model-name"` +3. Verify auth: `hf_whoami()` +4. Check token has write permissions and repo exists (or set `hub_private_repo=True`) + +### Missing Dependencies + +**Fix:** +Add to PEP 723 header: +```python +# /// script +# dependencies = ["trl>=0.12.0", "peft>=0.7.0", "trackio", "missing-package"] +# /// +``` + +## Troubleshooting + +**Common issues:** +- Job times out → Increase timeout, reduce epochs/dataset, use smaller model/LoRA +- Model not saved to Hub → Check push_to_hub=True, hub_model_id, secrets=HF_TOKEN +- Out of Memory (OOM) → Reduce batch size, increase gradient accumulation, enable LoRA, use larger GPU +- Dataset format error → Validate with dataset inspector (see Dataset Validation section) +- Import/module errors → Add PEP 723 header with dependencies, verify format +- Authentication errors → Check `hf_whoami()`, token permissions, secrets parameter + +**See:** `references/troubleshooting.md` for complete troubleshooting guide + +## Resources + +### References (In This Skill) +- `references/training_methods.md` - Overview of SFT, DPO, GRPO, KTO, PPO, Reward Modeling +- `references/training_patterns.md` - Common training patterns and examples +- `references/unsloth.md` - Unsloth for fast VLM training (~2x speed, 60% less VRAM) +- `references/gguf_conversion.md` - Complete GGUF conversion guide +- `references/trackio_guide.md` - Trackio monitoring setup +- `references/hardware_guide.md` - Hardware specs and selection +- `references/hub_saving.md` - Hub authentication troubleshooting +- `references/troubleshooting.md` - Common issues and solutions +- `references/local_training_macos.md` - Local training on macOS + +### Scripts (In This Skill) +- `scripts/train_sft_example.py` - Production SFT template +- `scripts/train_dpo_example.py` - Production DPO template +- `scripts/train_grpo_example.py` - Production GRPO template +- `scripts/unsloth_sft_example.py` - Unsloth text LLM training template (faster, less VRAM) +- `scripts/estimate_cost.py` - Estimate time and cost (offer when appropriate) +- `scripts/convert_to_gguf.py` - Complete GGUF conversion script + +### External Scripts +- [Dataset Inspector](https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py) - Validate dataset format before training (use via `uv run` or `hf_jobs`) + +### External Links +- [TRL Documentation](https://huggingface.co/docs/trl) +- [TRL Jobs Training Guide](https://huggingface.co/docs/trl/en/jobs_training) +- [TRL Jobs Package](https://github.com/huggingface/trl-jobs) +- [HF Jobs Documentation](https://huggingface.co/docs/huggingface_hub/guides/jobs) +- [TRL Example Scripts](https://github.com/huggingface/trl/tree/main/examples/scripts) +- [UV Scripts Guide](https://docs.astral.sh/uv/guides/scripts/) +- [UV Scripts Organization](https://huggingface.co/uv-scripts) + +## Key Takeaways + +1. **Submit scripts inline** - The `script` parameter accepts Python code directly; no file saving required unless user requests +2. **Jobs are asynchronous** - Don't wait/poll; let user check when ready +3. **Always set timeout** - Default 30 min is insufficient; minimum 1-2 hours recommended +4. **Always enable Hub push** - Environment is ephemeral; without push, all results lost +5. **Include Trackio** - Use example scripts as templates for real-time monitoring +6. **Offer cost estimation** - When parameters are known, use `scripts/estimate_cost.py` +7. **Use UV scripts (Approach 1)** - Default to `hf_jobs("uv", {...})` with inline scripts; TRL maintained scripts for standard training; avoid bash `trl-jobs` commands in Codex +8. **Use hf_doc_fetch/hf_doc_search** for latest TRL documentation +9. **Validate dataset format** before training with dataset inspector (see Dataset Validation section) +10. **Choose appropriate hardware** for model size; use LoRA for models >7B diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5fec60abd02da36262de4f69c9e1e6e34b8d6c77 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "LLM Trainer" + short_description: "Train and fine-tune language models on Hugging Face Jobs" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/gguf_conversion.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/gguf_conversion.md new file mode 100644 index 0000000000000000000000000000000000000000..a99ea0e888a24895ab2017bc8fdab3d809f66f88 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/gguf_conversion.md @@ -0,0 +1,296 @@ +# GGUF Conversion Guide + +After training models with TRL on Hugging Face Jobs, convert them to **GGUF format** for use with llama.cpp, Ollama, LM Studio, and other local inference tools. + +**This guide provides production-ready, tested code based on successful conversions.** All critical dependencies and build steps are included. + +## What is GGUF? + +**GGUF** (GPT-Generated Unified Format): +- Optimized format for CPU/GPU inference with llama.cpp +- Supports quantization (4-bit, 5-bit, 8-bit) to reduce model size +- Compatible with: Ollama, LM Studio, Jan, GPT4All, llama.cpp +- Typically 2-8GB for 7B models (vs 14GB unquantized) + +## When to Convert to GGUF + +**Convert when:** +- Running models locally with Ollama or LM Studio +- Using CPU-optimized inference +- Reducing model size with quantization +- Deploying to edge devices +- Sharing models for local-first use + +## Critical Success Factors + +Based on production testing, these are **essential** for reliable conversion: + +### 1. ✅ Install Build Tools FIRST +**Before cloning llama.cpp**, install build dependencies: +```python +subprocess.run(["apt-get", "update", "-qq"], check=True, capture_output=True) +subprocess.run(["apt-get", "install", "-y", "-qq", "build-essential", "cmake"], check=True, capture_output=True) +``` + +**Why:** The quantization tool requires gcc and cmake. Installing after cloning doesn't help. + +### 2. ✅ Use CMake (Not Make) +**Build the quantize tool with CMake:** +```python +# Create build directory +os.makedirs("/tmp/llama.cpp/build", exist_ok=True) + +# Configure +subprocess.run([ + "cmake", "-B", "/tmp/llama.cpp/build", "-S", "/tmp/llama.cpp", + "-DGGML_CUDA=OFF" # Faster build, CUDA not needed for quantization +], check=True, capture_output=True, text=True) + +# Build +subprocess.run([ + "cmake", "--build", "/tmp/llama.cpp/build", + "--target", "llama-quantize", "-j", "4" +], check=True, capture_output=True, text=True) + +# Binary path +quantize_bin = "/tmp/llama.cpp/build/bin/llama-quantize" +``` + +**Why:** CMake is more reliable than `make` and produces consistent binary paths. + +### 3. ✅ Include All Dependencies +**PEP 723 header must include:** +```python +# /// script +# dependencies = [ +# "transformers>=4.36.0", +# "peft>=0.7.0", +# "torch>=2.0.0", +# "accelerate>=0.24.0", +# "huggingface_hub>=0.20.0", +# "sentencepiece>=0.1.99", # Required for tokenizer +# "protobuf>=3.20.0", # Required for tokenizer +# "numpy", +# "gguf", +# ] +# /// +``` + +**Why:** `sentencepiece` and `protobuf` are critical for tokenizer conversion. Missing them causes silent failures. + +### 4. ✅ Verify Names Before Use +**Always verify repos exist:** +```python +# Before submitting job, verify: +hub_repo_details([ADAPTER_MODEL], repo_type="model") +hub_repo_details([BASE_MODEL], repo_type="model") +``` + +**Why:** Non-existent dataset/model names cause job failures that could be caught in seconds. + +## Complete Conversion Script + +See `scripts/convert_to_gguf.py` for the complete, production-ready script. + +**Key features:** +- ✅ All dependencies in PEP 723 header +- ✅ Build tools installed automatically +- ✅ CMake build process (reliable) +- ✅ Comprehensive error handling +- ✅ Environment variable configuration +- ✅ Automatic README generation + +## Quick Conversion Job + +```python +# Before submitting: VERIFY MODELS EXIST +hub_repo_details(["username/my-finetuned-model"], repo_type="model") +hub_repo_details(["Qwen/Qwen2.5-0.5B"], repo_type="model") + +# Submit conversion job +hf_jobs("uv", { + "script": open("trl/scripts/convert_to_gguf.py").read(), # Or inline the script + "flavor": "a10g-large", + "timeout": "45m", + "secrets": {"HF_TOKEN": "$HF_TOKEN"}, + "env": { + "ADAPTER_MODEL": "username/my-finetuned-model", + "BASE_MODEL": "Qwen/Qwen2.5-0.5B", + "OUTPUT_REPO": "username/my-model-gguf", + "HF_USERNAME": "username" # Optional, for README + } +}) +``` + +## Conversion Process + +The script performs these steps: + +1. **Load and Merge** - Load base model and LoRA adapter, merge them +2. **Install Build Tools** - Install gcc, cmake (CRITICAL: before cloning llama.cpp) +3. **Setup llama.cpp** - Clone repo, install Python dependencies +4. **Convert to GGUF** - Create FP16 GGUF using llama.cpp converter +5. **Build Quantize Tool** - Use CMake to build `llama-quantize` +6. **Quantize** - Create Q4_K_M, Q5_K_M, Q8_0 versions +7. **Upload** - Upload all versions + README to Hub + +## Quantization Options + +Common quantization formats (from smallest to largest): + +| Format | Size | Quality | Use Case | +|--------|------|---------|----------| +| **Q4_K_M** | ~300MB | Good | **Recommended** - best balance of size/quality | +| **Q5_K_M** | ~350MB | Better | Higher quality, slightly larger | +| **Q8_0** | ~500MB | Very High | Near-original quality | +| **F16** | ~1GB | Original | Full precision, largest file | + +**Recommendation:** Create Q4_K_M, Q5_K_M, and Q8_0 versions to give users options. + +## Hardware Requirements + +**For conversion:** +- Small models (<1B): CPU-basic works, but slow +- Medium models (1-7B): a10g-large recommended +- Large models (7B+): a10g-large or a100-large + +**Time estimates:** +- 0.5B model: ~15-25 minutes on A10G +- 3B model: ~30-45 minutes on A10G +- 7B model: ~45-60 minutes on A10G + +## Using GGUF Models + +**GGUF models work on both CPU and GPU.** They're optimized for CPU inference but can also leverage GPU acceleration when available. + +### With Ollama (auto-detects GPU) +```bash +# Download GGUF +hf download username/my-model-gguf model-q4_k_m.gguf + +# Create Modelfile +echo "FROM ./model-q4_k_m.gguf" > Modelfile + +# Create and run (uses GPU automatically if available) +ollama create my-model -f Modelfile +ollama run my-model +``` + +### With llama.cpp +```bash +# CPU only +./llama-cli -m model-q4_k_m.gguf -p "Your prompt" + +# With GPU acceleration (offload 32 layers to GPU) +./llama-cli -m model-q4_k_m.gguf -ngl 32 -p "Your prompt" +``` + +### With LM Studio +1. Download the `.gguf` file +2. Import into LM Studio +3. Start chatting + +## Best Practices + +### ✅ DO: +1. **Verify repos exist** before submitting jobs (use `hub_repo_details`) +2. **Install build tools FIRST** before cloning llama.cpp +3. **Use CMake** for building quantize tool (not make) +4. **Include all dependencies** in PEP 723 header (especially sentencepiece, protobuf) +5. **Create multiple quantizations** - Give users choice +6. **Test on known models** before production use +7. **Use A10G GPU** for faster conversion + +### ❌ DON'T: +1. **Assume repos exist** - Always verify with hub tools +2. **Use make** instead of CMake - Less reliable +3. **Remove dependencies** to "simplify" - They're all needed +4. **Skip build tools** - Quantization will fail silently +5. **Use default paths** - CMake puts binaries in build/bin/ + +## Common Issues + +### Out of memory during merge +**Fix:** +- Use larger GPU (a10g-large or a100-large) +- Ensure `device_map="auto"` for automatic placement +- Use `dtype=torch.float16` or `torch.bfloat16` + +### Conversion fails with architecture error +**Fix:** +- Ensure llama.cpp supports the model architecture +- Check for standard architecture (Qwen, Llama, Mistral, etc.) +- Update llama.cpp to latest: `git clone --depth 1 https://github.com/ggerganov/llama.cpp.git` +- Check llama.cpp documentation for model support + +### Quantization fails +**Fix:** +- Verify build tools installed: `apt-get install build-essential cmake` +- Use CMake (not make) to build quantize tool +- Check binary path: `/tmp/llama.cpp/build/bin/llama-quantize` +- Verify FP16 GGUF exists before quantizing + +### Missing sentencepiece error +**Fix:** +- Add to PEP 723 header: `"sentencepiece>=0.1.99", "protobuf>=3.20.0"` +- Don't remove dependencies to "simplify" - all are required + +### Upload fails or times out +**Fix:** +- Large models (>2GB) need longer timeout: `"timeout": "1h"` +- Upload quantized versions separately if needed +- Check network/Hub status + +## Lessons Learned + +These are from production testing and real failures: + +### 1. Always Verify Before Use +**Lesson:** Don't assume repos/datasets exist. Check first. +```python +# BEFORE submitting job +hub_repo_details(["trl-lib/argilla-dpo-mix-7k"], repo_type="dataset") # Would catch error +``` +**Prevented failures:** Non-existent dataset names, typos in model names + +### 2. Prioritize Reliability Over Performance +**Lesson:** Default to what's most likely to succeed. +- Use CMake (not make) - more reliable +- Disable CUDA in build - faster, not needed +- Include all dependencies - don't "simplify" + +**Prevented failures:** Build failures, missing binaries + +### 3. Create Atomic, Self-Contained Scripts +**Lesson:** Don't remove dependencies or steps. Scripts should work as a unit. +- All dependencies in PEP 723 header +- All build steps included +- Clear error messages + +**Prevented failures:** Missing tokenizer libraries, build tool failures + +## References + +**In this skill:** +- `scripts/convert_to_gguf.py` - Complete, production-ready script + +**External:** +- [llama.cpp Repository](https://github.com/ggerganov/llama.cpp) +- [GGUF Specification](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md) +- [Ollama Documentation](https://ollama.ai) +- [LM Studio](https://lmstudio.ai) + +## Summary + +**Critical checklist for GGUF conversion:** +- [ ] Verify adapter and base models exist on Hub +- [ ] Use production script from `scripts/convert_to_gguf.py` +- [ ] All dependencies in PEP 723 header (including sentencepiece, protobuf) +- [ ] Build tools installed before cloning llama.cpp +- [ ] CMake used for building quantize tool (not make) +- [ ] Correct binary path: `/tmp/llama.cpp/build/bin/llama-quantize` +- [ ] A10G GPU selected for reasonable conversion time +- [ ] Timeout set to 45m minimum +- [ ] HF_TOKEN in secrets for Hub upload + +**The script in `scripts/convert_to_gguf.py` incorporates all these lessons and has been tested successfully in production.** diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/hardware_guide.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/hardware_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..22eba945ad61b93725d547a94bd130c422f98b27 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/hardware_guide.md @@ -0,0 +1,283 @@ +# Hardware Selection Guide + +Choosing the right hardware (flavor) is critical for cost-effective training. + +## Available Hardware + +### CPU +- `cpu-basic` - Basic CPU, testing only +- `cpu-upgrade` - Enhanced CPU + +**Use cases:** Dataset validation, preprocessing, testing scripts +**Not recommended for training:** Too slow for any meaningful training + +### GPU Options + +| Flavor | GPU | Memory | Use Case | Cost/hour | +|--------|-----|--------|----------|-----------| +| `t4-small` | NVIDIA T4 | 16GB | <1B models, demos | ~$0.50-1 | +| `t4-medium` | NVIDIA T4 | 16GB | 1-3B models, development | ~$1-2 | +| `l4x1` | NVIDIA L4 | 24GB | 3-7B models, efficient training | ~$2-3 | +| `l4x4` | 4x NVIDIA L4 | 96GB | Multi-GPU training | ~$8-12 | +| `a10g-small` | NVIDIA A10G | 24GB | 3-7B models, production | ~$3-4 | +| `a10g-large` | NVIDIA A10G | 24GB | 7-13B models | ~$4-6 | +| `a10g-largex2` | 2x NVIDIA A10G | 48GB | Multi-GPU, large models | ~$8-12 | +| `a10g-largex4` | 4x NVIDIA A10G | 96GB | Multi-GPU, very large models | ~$16-24 | +| `a100-large` | NVIDIA A100 | 40GB | 13B+ models, fast training | ~$8-12 | + +### TPU Options + +| Flavor | Type | Use Case | +|--------|------|----------| +| `v5e-1x1` | TPU v5e | Small TPU workloads | +| `v5e-2x2` | 4x TPU v5e | Medium TPU workloads | +| `v5e-2x4` | 8x TPU v5e | Large TPU workloads | + +**Note:** TPUs require TPU-optimized code. Most TRL training uses GPUs. + +## Selection Guidelines + +### By Model Size + +**Tiny Models (<1B parameters)** +- **Recommended:** `t4-small` +- **Example:** Qwen2.5-0.5B, TinyLlama +- **Batch size:** 4-8 +- **Training time:** 1-2 hours for 1K examples + +**Small Models (1-3B parameters)** +- **Recommended:** `t4-medium` or `a10g-small` +- **Example:** Qwen2.5-1.5B, Phi-2 +- **Batch size:** 2-4 +- **Training time:** 2-4 hours for 10K examples + +**Medium Models (3-7B parameters)** +- **Recommended:** `a10g-small` or `a10g-large` +- **Example:** Qwen2.5-7B, Mistral-7B +- **Batch size:** 1-2 (or LoRA with 4-8) +- **Training time:** 4-8 hours for 10K examples + +**Large Models (7-13B parameters)** +- **Recommended:** `a10g-large` or `a100-large` +- **Example:** Llama-3-8B, Mixtral-8x7B (with LoRA) +- **Batch size:** 1 (full fine-tuning) or 2-4 (LoRA) +- **Training time:** 6-12 hours for 10K examples +- **Note:** Always use LoRA/PEFT + +**Very Large Models (13B+ parameters)** +- **Recommended:** `a100-large` with LoRA +- **Example:** Llama-3-13B, Llama-3-70B (LoRA only) +- **Batch size:** 1-2 with LoRA +- **Training time:** 8-24 hours for 10K examples +- **Note:** Full fine-tuning not feasible, use LoRA/PEFT + +### By Budget + +**Minimal Budget (<$5 total)** +- Use `t4-small` +- Train on subset of data (100-500 examples) +- Limit to 1-2 epochs +- Use small model (<1B) + +**Small Budget ($5-20)** +- Use `t4-medium` or `a10g-small` +- Train on 1K-5K examples +- 2-3 epochs +- Model up to 3B parameters + +**Medium Budget ($20-50)** +- Use `a10g-small` or `a10g-large` +- Train on 5K-20K examples +- 3-5 epochs +- Model up to 7B parameters + +**Large Budget ($50-200)** +- Use `a10g-large` or `a100-large` +- Full dataset training +- Multiple epochs +- Model up to 13B parameters with LoRA + +### By Training Type + +**Quick Demo/Experiment** +- `t4-small` +- 50-100 examples +- 5-10 steps +- ~10-15 minutes + +**Development/Iteration** +- `t4-medium` or `a10g-small` +- 1K examples +- 1 epoch +- ~30-60 minutes + +**Production Training** +- `a10g-large` or `a100-large` +- Full dataset +- 3-5 epochs +- 4-12 hours + +**Research/Experimentation** +- `a100-large` +- Multiple runs +- Various hyperparameters +- Budget for 20-50 hours + +## Memory Considerations + +### Estimating Memory Requirements + +**Full fine-tuning:** +``` +Memory (GB) ≈ (Model params in billions) × 20 +``` + +**LoRA fine-tuning:** +``` +Memory (GB) ≈ (Model params in billions) × 4 +``` + +**Examples:** +- Qwen2.5-0.5B full: ~10GB ✅ fits t4-small +- Qwen2.5-1.5B full: ~30GB ❌ exceeds most GPUs +- Qwen2.5-1.5B LoRA: ~6GB ✅ fits t4-small +- Qwen2.5-7B full: ~140GB ❌ not feasible +- Qwen2.5-7B LoRA: ~28GB ✅ fits a10g-large + +### Memory Optimization + +If hitting memory limits: + +1. **Use LoRA/PEFT** + ```python + peft_config=LoraConfig(r=16, lora_alpha=32) + ``` + +2. **Reduce batch size** + ```python + per_device_train_batch_size=1 + ``` + +3. **Increase gradient accumulation** + ```python + gradient_accumulation_steps=8 # Effective batch size = 1×8 + ``` + +4. **Enable gradient checkpointing** + ```python + gradient_checkpointing=True + ``` + +5. **Use mixed precision** + ```python + bf16=True # or fp16=True + ``` + +6. **Upgrade to larger GPU** + - t4 → a10g → a100 + +## Cost Estimation + +### Formula + +``` +Total Cost = (Hours of training) × (Cost per hour) +``` + +### Example Calculations + +**Quick demo:** +- Hardware: t4-small ($0.75/hour) +- Time: 15 minutes (0.25 hours) +- Cost: $0.19 + +**Development training:** +- Hardware: a10g-small ($3.50/hour) +- Time: 2 hours +- Cost: $7.00 + +**Production training:** +- Hardware: a10g-large ($5/hour) +- Time: 6 hours +- Cost: $30.00 + +**Large model with LoRA:** +- Hardware: a100-large ($10/hour) +- Time: 8 hours +- Cost: $80.00 + +### Cost Optimization Tips + +1. **Start small:** Test on t4-small with subset +2. **Use LoRA:** 4-5x cheaper than full fine-tuning +3. **Optimize hyperparameters:** Fewer epochs if possible +4. **Set appropriate timeout:** Don't waste compute on stalled jobs +5. **Use checkpointing:** Resume if job fails +6. **Monitor costs:** Check running jobs regularly + +## Multi-GPU Training + +TRL automatically handles multi-GPU training with Accelerate when using multi-GPU flavors. + +**Multi-GPU flavors:** +- `l4x4` - 4x L4 GPUs +- `a10g-largex2` - 2x A10G GPUs +- `a10g-largex4` - 4x A10G GPUs + +**When to use:** +- Models >13B parameters +- Need faster training (linear speedup) +- Large datasets (>50K examples) + +**Example:** +```python +hf_jobs("uv", { + "script": "train.py", + "flavor": "a10g-largex2", # 2 GPUs + "timeout": "4h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +No code changes needed—TRL/Accelerate handles distribution automatically. + +## Choosing Between Options + +### a10g vs a100 + +**Choose a10g when:** +- Model <13B parameters +- Budget conscious +- Training time not critical + +**Choose a100 when:** +- Model 13B+ parameters +- Need fastest training +- Memory requirements high +- Budget allows + +### Single vs Multi-GPU + +**Choose single GPU when:** +- Model <7B parameters +- Budget constrained +- Simpler debugging + +**Choose multi-GPU when:** +- Model >13B parameters +- Need faster training +- Large batch sizes required +- Cost-effective for large jobs + +## Quick Reference + +```python +# Model size → Hardware selection +HARDWARE_MAP = { + "<1B": "t4-small", + "1-3B": "a10g-small", + "3-7B": "a10g-large", + "7-13B": "a10g-large (LoRA) or a100-large", + ">13B": "a100-large (LoRA required)" +} +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/hub_saving.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/hub_saving.md new file mode 100644 index 0000000000000000000000000000000000000000..734e49b51de8b0224a3e2ee91084432a2fdb5a76 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/hub_saving.md @@ -0,0 +1,364 @@ +# Saving Training Results to Hugging Face Hub + +**⚠️ CRITICAL:** Training environments are ephemeral. ALL results are lost when a job completes unless pushed to the Hub. + +## Why Hub Push is Required + +When running on Hugging Face Jobs: +- Environment is temporary +- All files deleted on job completion +- No local disk persistence +- Cannot access results after job ends + +**Without Hub push, training is completely wasted.** + +## Required Configuration + +### 1. Training Configuration + +In your SFTConfig or trainer config: + +```python +SFTConfig( + push_to_hub=True, # Enable Hub push + hub_model_id="username/model-name", # Target repository +) +``` + +### 2. Job Configuration + +When submitting the job: + +```python +hf_jobs("uv", { + "script": "train.py", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # Provide authentication +}) +``` + +**The `$HF_TOKEN` placeholder is automatically replaced with your Hugging Face token.** + +## Complete Example + +```python +# train.py +# /// script +# dependencies = ["trl"] +# /// + +from trl import SFTTrainer, SFTConfig +from datasets import load_dataset + +dataset = load_dataset("trl-lib/Capybara", split="train") + +# Configure with Hub push +config = SFTConfig( + output_dir="my-model", + num_train_epochs=3, + + # ✅ CRITICAL: Hub push configuration + push_to_hub=True, + hub_model_id="myusername/my-trained-model", + + # Optional: Push strategy + push_to_hub_model_id="myusername/my-trained-model", + push_to_hub_organization=None, + push_to_hub_token=None, # Uses environment token +) + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, + args=config, +) + +trainer.train() + +# ✅ Push final model +trainer.push_to_hub() + +print("✅ Model saved to: https://huggingface.co/myusername/my-trained-model") +``` + +**Submit with authentication:** + +```python +hf_jobs("uv", { + "script": "train.py", + "flavor": "a10g-large", + "timeout": "2h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Required! +}) +``` + +## What Gets Saved + +When `push_to_hub=True`: + +1. **Model weights** - Final trained parameters +2. **Tokenizer** - Associated tokenizer +3. **Configuration** - Model config (config.json) +4. **Training arguments** - Hyperparameters used +5. **Model card** - Auto-generated documentation +6. **Checkpoints** - If `save_strategy="steps"` enabled + +## Checkpoint Saving + +Save intermediate checkpoints during training: + +```python +SFTConfig( + output_dir="my-model", + push_to_hub=True, + hub_model_id="username/my-model", + + # Checkpoint configuration + save_strategy="steps", + save_steps=100, # Save every 100 steps + save_total_limit=3, # Keep only last 3 checkpoints +) +``` + +**Benefits:** +- Resume training if job fails +- Compare checkpoint performance +- Use intermediate models + +**Checkpoints are pushed to:** `username/my-model` (same repo) + +## Authentication Methods + +### Method 1: Automatic Token (Recommended) + +```python +"secrets": {"HF_TOKEN": "$HF_TOKEN"} +``` + +Uses your logged-in Hugging Face token automatically. + +### Method 2: Explicit Token + +```python +"secrets": {"HF_TOKEN": "hf_abc123..."} +``` + +Provide token explicitly (not recommended for security). + +### Method 3: Environment Variable + +```python +"env": {"HF_TOKEN": "hf_abc123..."} +``` + +Pass as regular environment variable (less secure than secrets). + +**Always prefer Method 1** for security and convenience. + +## Verification Checklist + +Before submitting any training job, verify: + +- [ ] `push_to_hub=True` in training config +- [ ] `hub_model_id` is specified (format: `username/model-name`) +- [ ] `secrets={"HF_TOKEN": "$HF_TOKEN"}` in job config +- [ ] Repository name doesn't conflict with existing repos +- [ ] You have write access to the target namespace + +## Repository Setup + +### Automatic Creation + +If repository doesn't exist, it's created automatically when first pushing. + +### Manual Creation + +Create repository before training: + +```python +from huggingface_hub import HfApi + +api = HfApi() +api.create_repo( + repo_id="username/model-name", + repo_type="model", + private=False, # or True for private repo +) +``` + +### Repository Naming + +**Valid names:** +- `username/my-model` +- `username/model-name` +- `organization/model-name` + +**Invalid names:** +- `model-name` (missing username) +- `username/model name` (spaces not allowed) +- `username/MODEL` (uppercase discouraged) + +## Troubleshooting + +### Error: 401 Unauthorized + +**Cause:** HF_TOKEN not provided or invalid + +**Solutions:** +1. Verify `secrets={"HF_TOKEN": "$HF_TOKEN"}` in job config +2. Check you're logged in: `hf auth whoami` +3. Re-login: `hf auth login` + +### Error: 403 Forbidden + +**Cause:** No write access to repository + +**Solutions:** +1. Check repository namespace matches your username +2. Verify you're a member of organization (if using org namespace) +3. Check repository isn't private (if accessing org repo) + +### Error: Repository not found + +**Cause:** Repository doesn't exist and auto-creation failed + +**Solutions:** +1. Manually create repository first +2. Check repository name format +3. Verify namespace exists + +### Error: Push failed during training + +**Cause:** Network issues or Hub unavailable + +**Solutions:** +1. Training continues but final push fails +2. Checkpoints may be saved +3. Re-run push manually after job completes + +### Issue: Model saved but not visible + +**Possible causes:** +1. Repository is private—check https://huggingface.co/username +2. Wrong namespace—verify `hub_model_id` matches login +3. Push still in progress—wait a few minutes + +## Manual Push After Training + +If training completes but push fails, push manually: + +```python +from transformers import AutoModel, AutoTokenizer + +# Load from local checkpoint +model = AutoModel.from_pretrained("./output_dir") +tokenizer = AutoTokenizer.from_pretrained("./output_dir") + +# Push to Hub +model.push_to_hub("username/model-name", token="hf_abc123...") +tokenizer.push_to_hub("username/model-name", token="hf_abc123...") +``` + +**Note:** Only possible if job hasn't completed (files still exist). + +## Best Practices + +1. **Always enable `push_to_hub=True`** +2. **Use checkpoint saving** for long training runs +3. **Verify Hub push** in logs before job completes +4. **Set appropriate `save_total_limit`** to avoid excessive checkpoints +5. **Use descriptive repo names** (e.g., `qwen-capybara-sft` not `model1`) +6. **Add model card** with training details +7. **Tag models** with relevant tags (e.g., `text-generation`, `fine-tuned`) + +## Monitoring Push Progress + +Check logs for push progress: + +```python +hf_jobs("logs", {"job_id": "your-job-id"}) +``` + +**Look for:** +``` +Pushing model to username/model-name... +Upload file pytorch_model.bin: 100% +✅ Model pushed successfully +``` + +## Example: Full Production Setup + +```python +# production_train.py +# /// script +# dependencies = ["trl>=0.12.0", "peft>=0.7.0"] +# /// + +from datasets import load_dataset +from peft import LoraConfig +from trl import SFTTrainer, SFTConfig +import os + +# Verify token is available +assert "HF_TOKEN" in os.environ, "HF_TOKEN not found in environment!" + +# Load dataset +dataset = load_dataset("trl-lib/Capybara", split="train") +print(f"✅ Dataset loaded: {len(dataset)} examples") + +# Configure with comprehensive Hub settings +config = SFTConfig( + output_dir="qwen-capybara-sft", + + # Hub configuration + push_to_hub=True, + hub_model_id="myusername/qwen-capybara-sft", + hub_strategy="checkpoint", # Push checkpoints + + # Checkpoint configuration + save_strategy="steps", + save_steps=100, + save_total_limit=3, + + # Training settings + num_train_epochs=3, + per_device_train_batch_size=4, + + # Logging + logging_steps=10, + logging_first_step=True, +) + +# Train with LoRA +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, + args=config, + peft_config=LoraConfig(r=16, lora_alpha=32), +) + +print("🚀 Starting training...") +trainer.train() + +print("💾 Pushing final model to Hub...") +trainer.push_to_hub() + +print("✅ Training complete!") +print(f"Model available at: https://huggingface.co/myusername/qwen-capybara-sft") +``` + +**Submit:** + +```python +hf_jobs("uv", { + "script": "production_train.py", + "flavor": "a10g-large", + "timeout": "6h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +## Key Takeaway + +**Without `push_to_hub=True` and `secrets={"HF_TOKEN": "$HF_TOKEN"}`, all training results are permanently lost.** + +Always verify both are configured before submitting any training job. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/local_training_macos.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/local_training_macos.md new file mode 100644 index 0000000000000000000000000000000000000000..fdf5dede51aaf47c3bd31cc9b45fd36e3a8faa24 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/local_training_macos.md @@ -0,0 +1,231 @@ +# Local Training on macOS (Apple Silicon) + +Run small LoRA fine-tuning jobs locally on Mac for smoke tests and quick iteration before submitting to HF Jobs. + +## When to Use Local Mac vs HF Jobs + +| Local Mac | HF Jobs / Cloud GPU | +|-----------|-------------------| +| Model ≤3B, text-only | Model 7B+ | +| LoRA/PEFT only | QLoRA 4-bit (CUDA/bitsandbytes) | +| Short context (≤1024) | Long context / full fine-tuning | +| Smoke tests, dataset validation | Production runs, VLMs | + +**Typical workflow:** local smoke test → HF Jobs with same config → export/quantize ([gguf_conversion.md](gguf_conversion.md)) + +## Recommended Defaults + +| Setting | Value | Notes | +|---------|-------|-------| +| Model size | 0.5B–1.5B first run | Scale up after verifying | +| Max seq length | 512–1024 | Lower = less memory | +| Batch size | 1 | Scale via gradient accumulation | +| Gradient accumulation | 8–16 | Effective batch = 8–16 | +| LoRA rank (r) | 8–16 | alpha = 2×r | +| Dtype | float32 | fp16 causes NaN on MPS; bf16 only on M1 Pro+ and M2/M3/M4 | + +### Memory by hardware + +| Unified RAM | Max Model Size | +|-------------|---------------| +| 16 GB | ~0.5B–1.5B | +| 32 GB | ~1.5B–3B | +| 64 GB | ~3B (short context) | + +## Setup + +```bash +xcode-select --install +python3 -m venv .venv && source .venv/bin/activate +pip install -U "torch>=2.2" "transformers>=4.40" "trl>=0.12" "peft>=0.10" \ + datasets accelerate safetensors huggingface_hub +``` + +Verify MPS: +```bash +python -c "import torch; print(torch.__version__, '| MPS:', torch.backends.mps.is_available())" +``` + +Optional — configure Accelerate for local Mac (no distributed, no mixed precision, MPS device): +```bash +accelerate config +``` + +## Training Script + +
+train_lora_sft.py + +```python +import os +from dataclasses import dataclass +from typing import Optional +import torch +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed +from peft import LoraConfig +from trl import SFTTrainer, SFTConfig + +set_seed(42) + +@dataclass +class Cfg: + model_id: str = os.environ.get("MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct") + dataset_id: str = os.environ.get("DATASET_ID", "HuggingFaceH4/ultrachat_200k") + dataset_split: str = os.environ.get("DATASET_SPLIT", "train_sft[:500]") + data_files: Optional[str] = os.environ.get("DATA_FILES", None) + text_field: str = os.environ.get("TEXT_FIELD", "") + messages_field: str = os.environ.get("MESSAGES_FIELD", "messages") + out_dir: str = os.environ.get("OUT_DIR", "outputs/local-lora") + max_seq_length: int = int(os.environ.get("MAX_SEQ_LENGTH", "512")) + max_steps: int = int(os.environ.get("MAX_STEPS", "-1")) + +cfg = Cfg() +device = "mps" if torch.backends.mps.is_available() else "cpu" + +tokenizer = AutoTokenizer.from_pretrained(cfg.model_id, use_fast=True) +if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token +tokenizer.padding_side = "right" + +model = AutoModelForCausalLM.from_pretrained(cfg.model_id, torch_dtype=torch.float32) +model.to(device) +model.config.use_cache = False + +if cfg.data_files: + ds = load_dataset("json", data_files=cfg.data_files, split="train") +else: + ds = load_dataset(cfg.dataset_id, split=cfg.dataset_split) + +def format_example(ex): + if cfg.text_field and isinstance(ex.get(cfg.text_field), str): + ex["text"] = ex[cfg.text_field] + return ex + msgs = ex.get(cfg.messages_field) + if isinstance(msgs, list): + if hasattr(tokenizer, "apply_chat_template"): + try: + ex["text"] = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=False) + return ex + except Exception: + pass + ex["text"] = "\n".join([str(m) for m in msgs]) + return ex + ex["text"] = str(ex) + return ex + +ds = ds.map(format_example) +ds = ds.remove_columns([c for c in ds.column_names if c != "text"]) + +lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", + task_type="CAUSAL_LM", target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]) + +sft_kwargs = dict( + output_dir=cfg.out_dir, per_device_train_batch_size=1, gradient_accumulation_steps=8, + learning_rate=2e-4, logging_steps=10, save_steps=200, save_total_limit=2, + gradient_checkpointing=True, report_to="none", fp16=False, bf16=False, + max_seq_length=cfg.max_seq_length, dataset_text_field="text", +) +if cfg.max_steps > 0: + sft_kwargs["max_steps"] = cfg.max_steps +else: + sft_kwargs["num_train_epochs"] = 1 + +trainer = SFTTrainer(model=model, train_dataset=ds, peft_config=lora, + args=SFTConfig(**sft_kwargs), processing_class=tokenizer) +trainer.train() +trainer.save_model(cfg.out_dir) +print(f"✅ Saved to: {cfg.out_dir}") +``` + +
+ +### Run + +```bash +python train_lora_sft.py +``` + +**Env overrides:** + +```bash +MODEL_ID="Qwen/Qwen2.5-1.5B-Instruct" python train_lora_sft.py # different model +MAX_STEPS=50 python train_lora_sft.py # quick 50-step test +DATA_FILES="my_data.jsonl" python train_lora_sft.py # local JSONL file +PYTORCH_ENABLE_MPS_FALLBACK=1 python train_lora_sft.py # MPS op fallback to CPU +PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0 python train_lora_sft.py # disable MPS memory limit (use with caution) +``` + +**Local JSONL format** — chat messages or plain text: +```jsonl +{"messages": [{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi!"}]} +``` +```jsonl +{"text": "User: Hello\nAssistant: Hi!"} +``` +For plain text: `DATA_FILES="file.jsonl" TEXT_FIELD="text" MESSAGES_FIELD="" python train_lora_sft.py` + +### Verify Success + +- Loss decreases over steps +- `outputs/local-lora/` contains `adapter_config.json` + `*.safetensors` + +## Quick Evaluation + +
+eval_generate.py + +```python +import os, torch +from transformers import AutoTokenizer, AutoModelForCausalLM +from peft import PeftModel + +BASE = os.environ.get("MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct") +ADAPTER = os.environ.get("ADAPTER_DIR", "outputs/local-lora") +device = "mps" if torch.backends.mps.is_available() else "cpu" + +tokenizer = AutoTokenizer.from_pretrained(BASE, use_fast=True) +model = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.float32) +model.to(device) +model = PeftModel.from_pretrained(model, ADAPTER) + +prompt = os.environ.get("PROMPT", "Explain gradient accumulation in 3 bullet points.") +inputs = tokenizer(prompt, return_tensors="pt").to(model.device) +with torch.no_grad(): + out = model.generate(**inputs, max_new_tokens=120, do_sample=True, temperature=0.7, top_p=0.9) +print(tokenizer.decode(out[0], skip_special_tokens=True)) +``` + +
+ +## Troubleshooting (macOS-Specific) + +For general training issues, see [troubleshooting.md](troubleshooting.md). + +| Problem | Fix | +|---------|-----| +| MPS unsupported op / crash | `PYTORCH_ENABLE_MPS_FALLBACK=1` | +| OOM / system instability | Reduce `MAX_SEQ_LENGTH`, use smaller model, set `PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0` (caution) | +| fp16 NaN / loss explosion | Keep `fp16=False` (default), lower learning rate | +| LoRA "module not found" | Print `model.named_modules()` to find correct target names | +| TRL TypeError on args | Check TRL version; script uses `SFTConfig` + `processing_class` (TRL ≥0.12) | +| Intel Mac | No MPS — use HF Jobs instead | + +**Common LoRA target modules by architecture:** + +| Architecture | target_modules | +|-------------|---------------| +| Llama/Qwen/Mistral | `q_proj`, `k_proj`, `v_proj`, `o_proj` | +| GPT-2/GPT-J | `c_attn`, `c_proj` | +| BLOOM | `query_key_value`, `dense` | + +## MLX Alternative + +[MLX](https://github.com/ml-explore/mlx) offers tighter Apple Silicon integration but has a smaller ecosystem and less mature training APIs. For this skill's workflow (local validation → HF Jobs), PyTorch + MPS is recommended for consistency. See [mlx-lm](https://github.com/ml-explore/mlx-lm) for MLX-based fine-tuning. + +## See Also + +- [troubleshooting.md](troubleshooting.md) — General TRL troubleshooting +- [hardware_guide.md](hardware_guide.md) — GPU selection for HF Jobs +- [gguf_conversion.md](gguf_conversion.md) — Export for on-device inference +- [training_methods.md](training_methods.md) — SFT, DPO, GRPO overview diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/reliability_principles.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/reliability_principles.md new file mode 100644 index 0000000000000000000000000000000000000000..bf2f745878edd6a4a7b51b68e806b43ac6e6d856 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/reliability_principles.md @@ -0,0 +1,371 @@ +# Reliability Principles for Training Jobs + +These principles are derived from real production failures and successful fixes. Following them prevents common failure modes and ensures reliable job execution. + +## Principle 1: Always Verify Before Use + +**Rule:** Never assume repos, datasets, or resources exist. Verify with tools first. + +### What It Prevents + +- **Non-existent datasets** - Jobs fail immediately when dataset doesn't exist +- **Typos in names** - Simple mistakes like "argilla-dpo-mix-7k" vs "ultrafeedback_binarized" +- **Incorrect paths** - Old or moved repos, renamed files +- **Missing dependencies** - Undocumented requirements + +### How to Apply + +**Before submitting ANY job:** + +```python +# Verify dataset exists +dataset_search({"query": "dataset-name", "author": "author-name", "limit": 5}) +hub_repo_details(["author/dataset-name"], repo_type="dataset") + +# Verify model exists +hub_repo_details(["org/model-name"], repo_type="model") + +# Check script/file paths (for URL-based scripts) +# Verify before using: https://github.com/user/repo/blob/main/script.py +``` + +**Examples that would have caught errors:** + +```python +# ❌ WRONG: Assumed dataset exists +hf_jobs("uv", { + "script": """...""", + "env": {"DATASET": "trl-lib/argilla-dpo-mix-7k"} # Doesn't exist! +}) + +# ✅ CORRECT: Verify first +dataset_search({"query": "argilla dpo", "author": "trl-lib"}) +# Would show: "trl-lib/ultrafeedback_binarized" is the correct name + +hub_repo_details(["trl-lib/ultrafeedback_binarized"], repo_type="dataset") +# Confirms it exists before using +``` + +### Implementation Checklist + +- [ ] Check dataset exists before training +- [ ] Verify base model exists before fine-tuning +- [ ] Confirm adapter model exists before GGUF conversion +- [ ] Test script URLs are valid before submitting +- [ ] Validate file paths in repositories +- [ ] Check for recent updates/renames of resources + +**Time cost:** 5-10 seconds +**Time saved:** Hours of failed job time + debugging + +--- + +## Principle 2: Prioritize Reliability Over Performance + +**Rule:** Default to what is most likely to succeed, not what is theoretically fastest. + +### What It Prevents + +- **Hardware incompatibilities** - Features that fail on certain GPUs +- **Unstable optimizations** - Speed-ups that cause crashes +- **Complex configurations** - More failure points +- **Build system issues** - Unreliable compilation methods + +### How to Apply + +**Choose reliability:** + +```python +# ❌ RISKY: Aggressive optimization that may fail +SFTConfig( + torch_compile=True, # Can fail on T4, A10G GPUs + optim="adamw_bnb_8bit", # Requires specific setup + fp16=False, # May cause training instability + ... +) + +# ✅ SAFE: Proven defaults +SFTConfig( + # torch_compile=True, # Commented with note: "Enable on H100 for 20% speedup" + optim="adamw_torch", # Standard, always works + fp16=True, # Stable and fast + ... +) +``` + +**For build processes:** + +```python +# ❌ UNRELIABLE: Uses make (platform-dependent) +subprocess.run(["make", "-C", "/tmp/llama.cpp", "llama-quantize"], check=True) + +# ✅ RELIABLE: Uses CMake (consistent, documented) +subprocess.run([ + "cmake", "-B", "/tmp/llama.cpp/build", "-S", "/tmp/llama.cpp", + "-DGGML_CUDA=OFF" # Disable CUDA for faster, more reliable build +], check=True) + +subprocess.run([ + "cmake", "--build", "/tmp/llama.cpp/build", + "--target", "llama-quantize", "-j", "4" +], check=True) +``` + +### Real-World Example + +**The `torch.compile` failure:** +- Added for "20% speedup" on H100 +- **Failed fatally on T4-medium** with cryptic error +- Misdiagnosed as dataset issue (cost hours) +- **Fix:** Disable by default, add as optional comment + +**Result:** Reliability > 20% performance gain + +### Implementation Checklist + +- [ ] Use proven, standard configurations by default +- [ ] Comment out performance optimizations with hardware notes +- [ ] Use stable build systems (CMake > make) +- [ ] Test on target hardware before production +- [ ] Document known incompatibilities +- [ ] Provide "safe" and "fast" variants when needed + +**Performance loss:** 10-20% in best case +**Reliability gain:** 95%+ success rate vs 60-70% + +--- + +## Principle 3: Create Atomic, Self-Contained Scripts + +**Rule:** Scripts should work as complete, independent units. Don't remove parts to "simplify." + +### What It Prevents + +- **Missing dependencies** - Removed "unnecessary" packages that are actually required +- **Incomplete processes** - Skipped steps that seem redundant +- **Environment assumptions** - Scripts that need pre-setup +- **Partial failures** - Some parts work, others fail silently + +### How to Apply + +**Complete dependency specifications:** + +```python +# ❌ INCOMPLETE: "Simplified" by removing dependencies +# /// script +# dependencies = [ +# "transformers", +# "peft", +# "torch", +# ] +# /// + +# ✅ COMPLETE: All dependencies explicit +# /// script +# dependencies = [ +# "transformers>=4.36.0", +# "peft>=0.7.0", +# "torch>=2.0.0", +# "accelerate>=0.24.0", +# "huggingface_hub>=0.20.0", +# "sentencepiece>=0.1.99", # Required for tokenizers +# "protobuf>=3.20.0", # Required for tokenizers +# "numpy", +# "gguf", +# ] +# /// +``` + +**Complete build processes:** + +```python +# ❌ INCOMPLETE: Assumes build tools exist +subprocess.run(["git", "clone", "https://github.com/ggerganov/llama.cpp.git", "/tmp/llama.cpp"]) +subprocess.run(["make", "-C", "/tmp/llama.cpp", "llama-quantize"]) # FAILS: no gcc/make + +# ✅ COMPLETE: Installs all requirements +subprocess.run(["apt-get", "update", "-qq"], check=True) +subprocess.run(["apt-get", "install", "-y", "-qq", "build-essential", "cmake"], check=True) +subprocess.run(["git", "clone", "https://github.com/ggerganov/llama.cpp.git", "/tmp/llama.cpp"]) +# ... then build +``` + +### Real-World Example + +**The `sentencepiece` failure:** +- Original script had it: worked fine +- "Simplified" version removed it: "doesn't look necessary" +- **GGUF conversion failed silently** - tokenizer couldn't convert +- Hard to debug: no obvious error message +- **Fix:** Restore all original dependencies + +**Result:** Don't remove dependencies without thorough testing + +### Implementation Checklist + +- [ ] All dependencies in PEP 723 header with version pins +- [ ] All system packages installed by script +- [ ] No assumptions about pre-existing environment +- [ ] No "optional" steps that are actually required +- [ ] Test scripts in clean environment +- [ ] Document why each dependency is needed + +**Complexity:** Slightly longer scripts +**Reliability:** Scripts "just work" every time + +--- + +## Principle 4: Provide Clear Error Context + +**Rule:** When things fail, make it obvious what went wrong and how to fix it. + +### How to Apply + +**Wrap subprocess calls:** + +```python +# ❌ UNCLEAR: Silent failure +subprocess.run([...], check=True, capture_output=True) + +# ✅ CLEAR: Shows what failed +try: + result = subprocess.run( + [...], + check=True, + capture_output=True, + text=True + ) + print(result.stdout) + if result.stderr: + print("Warnings:", result.stderr) +except subprocess.CalledProcessError as e: + print(f"❌ Command failed!") + print("STDOUT:", e.stdout) + print("STDERR:", e.stderr) + raise +``` + +**Validate inputs:** + +```python +# ❌ UNCLEAR: Fails later with cryptic error +model = load_model(MODEL_NAME) + +# ✅ CLEAR: Fails fast with clear message +if not MODEL_NAME: + raise ValueError("MODEL_NAME environment variable not set!") + +print(f"Loading model: {MODEL_NAME}") +try: + model = load_model(MODEL_NAME) + print(f"✅ Model loaded successfully") +except Exception as e: + print(f"❌ Failed to load model: {MODEL_NAME}") + print(f"Error: {e}") + print("Hint: Check that model exists on Hub") + raise +``` + +### Implementation Checklist + +- [ ] Wrap external calls with try/except +- [ ] Print stdout/stderr on failure +- [ ] Validate environment variables early +- [ ] Add progress indicators (✅, ❌, 🔄) +- [ ] Include hints for common failures +- [ ] Log configuration at start + +--- + +## Principle 5: Test the Happy Path on Known-Good Inputs + +**Rule:** Before using new code in production, test with inputs you know work. + +### How to Apply + +**Known-good test inputs:** + +```python +# For training +TEST_DATASET = "trl-lib/Capybara" # Small, well-formatted, widely used +TEST_MODEL = "Qwen/Qwen2.5-0.5B" # Small, fast, reliable + +# For GGUF conversion +TEST_ADAPTER = "evalstate/qwen-capybara-medium" # Known working model +TEST_BASE = "Qwen/Qwen2.5-0.5B" # Compatible base +``` + +**Testing workflow:** + +1. Test with known-good inputs first +2. If that works, try production inputs +3. If production fails, you know it's the inputs (not code) +4. Isolate the difference + +### Implementation Checklist + +- [ ] Maintain list of known-good test models/datasets +- [ ] Test new scripts with test inputs first +- [ ] Document what makes inputs "good" +- [ ] Keep test jobs cheap (small models, short timeouts) +- [ ] Only move to production after test succeeds + +**Time cost:** 5-10 minutes for test run +**Debugging time saved:** Hours + +--- + +## Summary: The Reliability Checklist + +Before submitting ANY job: + +### Pre-Flight Checks +- [ ] **Verified** all repos/datasets exist (hub_repo_details) +- [ ] **Tested** with known-good inputs if new code +- [ ] **Using** proven hardware/configuration +- [ ] **Included** all dependencies in PEP 723 header +- [ ] **Installed** system requirements (build tools, etc.) +- [ ] **Set** appropriate timeout (not default 30m) +- [ ] **Configured** Hub push with HF_TOKEN +- [ ] **Added** clear error handling + +### Script Quality +- [ ] Self-contained (no external setup needed) +- [ ] Complete dependencies listed +- [ ] Build tools installed by script +- [ ] Progress indicators included +- [ ] Error messages are clear +- [ ] Configuration logged at start + +### Job Configuration +- [ ] Timeout > expected runtime + 30% buffer +- [ ] Hardware appropriate for model size +- [ ] Secrets include HF_TOKEN +- [ ] Environment variables set correctly +- [ ] Cost estimated and acceptable + +**Following these principles transforms job success rate from ~60-70% to ~95%+** + +--- + +## When Principles Conflict + +Sometimes reliability and performance conflict. Here's how to choose: + +| Scenario | Choose | Rationale | +|----------|--------|-----------| +| Demo/test | Reliability | Fast failure is worse than slow success | +| Production (first run) | Reliability | Prove it works before optimizing | +| Production (proven) | Performance | Safe to optimize after validation | +| Time-critical | Reliability | Failures cause more delay than slow runs | +| Cost-critical | Balanced | Test with small model, then optimize | + +**General rule:** Reliability first, optimize second. + +--- + +## Further Reading + +- `troubleshooting.md` - Common issues and fixes +- `training_patterns.md` - Proven training configurations +- `gguf_conversion.md` - Production GGUF workflow diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/trackio_guide.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/trackio_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..342045ee8ba34d05e3d777b17aec54eb69523668 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/trackio_guide.md @@ -0,0 +1,189 @@ +# Trackio Integration for TRL Training + +**Trackio** is an experiment tracking library that provides real-time metrics visualization for remote training on Hugging Face Jobs infrastructure. + +⚠️ **IMPORTANT**: For Jobs training (remote cloud GPUs): +- Training happens on ephemeral cloud runners (not your local machine) +- Trackio syncs metrics to a Hugging Face Space for real-time monitoring +- Without a Space, metrics are lost when the job completes +- The Space dashboard persists your training metrics permanently + +## Setting Up Trackio for Jobs + +**Step 1: Add trackio dependency** +```python +# /// script +# dependencies = [ +# "trl>=0.12.0", +# "trackio", # Required! +# ] +# /// +``` + +**Step 2: Create a Trackio Space (one-time setup)** + +**Option A: Let Trackio auto-create (Recommended)** +Pass a `space_id` to `trackio.init()` and Trackio will automatically create the Space if it doesn't exist. + +**Option B: Create manually** +- Create Space via Hub UI at https://huggingface.co/new-space +- Select Gradio SDK +- OR use command: `hf repos create my-trackio-dashboard --type space --space-sdk gradio` + +**Step 3: Initialize Trackio with space_id** +```python +import trackio + +trackio.init( + project="my-training", + space_id="username/trackio", # CRITICAL for Jobs! Replace 'username' with your HF username + config={ + "model": "Qwen/Qwen2.5-0.5B", + "dataset": "trl-lib/Capybara", + "learning_rate": 2e-5, + } +) +``` + +**Step 4: Configure TRL to use Trackio** +```python +SFTConfig( + report_to="trackio", + # ... other config +) +``` + +**Step 5: Finish tracking** +```python +trainer.train() +trackio.finish() # Ensures final metrics are synced +``` + +## What Trackio Tracks + +Trackio automatically logs: +- ✅ Training loss +- ✅ Learning rate +- ✅ GPU utilization +- ✅ Memory usage +- ✅ Training throughput +- ✅ Custom metrics + +## How It Works with Jobs + +1. **Training runs** → Metrics logged to local SQLite DB +2. **Every 5 minutes** → Trackio syncs DB to HF Dataset (Parquet) +3. **Space dashboard** → Reads from Dataset, displays metrics in real-time +4. **Job completes** → Final sync ensures all metrics persisted + +## Default Configuration Pattern + +**Use sensible defaults for trackio configuration unless user requests otherwise.** + +### Recommended Defaults + +```python +import trackio + +trackio.init( + project="qwen-capybara-sft", + name="baseline-run", # Descriptive name user will recognize + space_id="username/trackio", # Default space: {username}/trackio + config={ + # Keep config minimal - hyperparameters and model/dataset info only + "model": "Qwen/Qwen2.5-0.5B", + "dataset": "trl-lib/Capybara", + "learning_rate": 2e-5, + "num_epochs": 3, + } +) +``` + +**Key principles:** +- **Space ID**: Use `{username}/trackio` with "trackio" as default space name +- **Run naming**: Unless otherwise specified, name the run in a way the user will recognize +- **Config**: Keep minimal - don't automatically capture job metadata unless requested +- **Grouping**: Optional - only use if user requests organizing related experiments + +## Grouping Runs (Optional) + +The `group` parameter helps organize related runs together in the dashboard sidebar. This is useful when user is running multiple experiments with different configurations but wants to compare them together: + +```python +# Example: Group runs by experiment type +trackio.init(project="my-project", run_name="baseline-run-1", group="baseline") +trackio.init(project="my-project", run_name="augmented-run-1", group="augmented") +trackio.init(project="my-project", run_name="tuned-run-1", group="tuned") +``` + +Runs with the same group name can be grouped together in the sidebar, making it easier to compare related experiments. You can group by any configuration parameter: + +```python +# Hyperparameter sweep - group by learning rate +trackio.init(project="hyperparam-sweep", run_name="lr-0.001-run", group="lr_0.001") +trackio.init(project="hyperparam-sweep", run_name="lr-0.01-run", group="lr_0.01") +``` + +## Environment Variables for Jobs + +You can configure trackio using environment variables instead of passing parameters to `trackio.init()`. This is useful for managing configuration across multiple jobs. + + + +**`HF_TOKEN`** +Required for creating Spaces and writing to datasets (passed via `secrets`): +```python +hf_jobs("uv", { + "script": "...", + "secrets": { + "HF_TOKEN": "$HF_TOKEN" # Enables Space creation and Hub push + } +}) +``` + +### Example with Environment Variables + +```python +hf_jobs("uv", { + "script": """ +# Training script - trackio config from environment +import trackio +from datetime import datetime + +# Auto-generate run name +timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M") +run_name = f"sft_qwen25_{timestamp}" + +# Project and space_id can come from environment variables +trackio.init(run_name=run_name, group="SFT") + +# ... training code ... +trackio.finish() +""", + "flavor": "a10g-large", + "timeout": "2h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +**When to use environment variables:** +- Managing multiple jobs with same configuration +- Keeping training scripts portable across projects +- Separating configuration from code + +**When to use direct parameters:** +- Single job with specific configuration +- When clarity in code is preferred +- When each job has different project/space + +## Viewing the Dashboard + +After starting training: +1. Navigate to the Space: `https://huggingface.co/spaces/username/trackio` +2. The Gradio dashboard shows all tracked experiments +3. Filter by project, compare runs, view charts with smoothing + +## Recommendation + +- **Trackio**: Best for real-time monitoring during long training runs +- **Weights & Biases**: Best for team collaboration, requires account diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/training_methods.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/training_methods.md new file mode 100644 index 0000000000000000000000000000000000000000..2393d7731cb2c9d1b4c3029f5fbc635d3beba49f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/training_methods.md @@ -0,0 +1,150 @@ +# TRL Training Methods Overview + +TRL (Transformer Reinforcement Learning) provides multiple training methods for fine-tuning and aligning language models. This reference provides a brief overview of each method. + +## Supervised Fine-Tuning (SFT) + +**What it is:** Standard instruction tuning with supervised learning on demonstration data. + +**When to use:** +- Initial fine-tuning of base models on task-specific data +- Teaching new capabilities or domains +- Most common starting point for fine-tuning + +**Dataset format:** Conversational format with "messages" field, OR text field, OR prompt/completion pairs + +**Example:** +```python +from trl import SFTTrainer, SFTConfig + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, + args=SFTConfig( + output_dir="my-model", + push_to_hub=True, + hub_model_id="username/my-model", + eval_strategy="no", # Disable eval for simple example + # max_length=1024 is the default - only set if you need different length + ) +) +trainer.train() +``` + +**Note:** For production training with evaluation monitoring, see `scripts/train_sft_example.py` + +**Documentation:** `hf_doc_fetch("https://huggingface.co/docs/trl/sft_trainer")` + +## Direct Preference Optimization (DPO) + +**What it is:** Alignment method that trains directly on preference pairs (chosen vs rejected responses) without requiring a reward model. + +**When to use:** +- Aligning models to human preferences +- Improving response quality after SFT +- Have paired preference data (chosen/rejected responses) + +**Dataset format:** Preference pairs with "chosen" and "rejected" fields + +**Example:** +```python +from trl import DPOTrainer, DPOConfig + +trainer = DPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", # Use instruct model + train_dataset=dataset, + args=DPOConfig( + output_dir="dpo-model", + beta=0.1, # KL penalty coefficient + eval_strategy="no", # Disable eval for simple example + # max_length=1024 is the default - only set if you need different length + ) +) +trainer.train() +``` + +**Note:** For production training with evaluation monitoring, see `scripts/train_dpo_example.py` + +**Documentation:** `hf_doc_fetch("https://huggingface.co/docs/trl/dpo_trainer")` + +## Group Relative Policy Optimization (GRPO) + +**What it is:** Online RL method that optimizes relative to group performance, useful for tasks with verifiable rewards. + +**When to use:** +- Tasks with automatic reward signals (code execution, math verification) +- Online learning scenarios +- When DPO offline data is insufficient + +**Dataset format:** Prompt-only format (model generates responses, reward computed online) + +**Example:** +```python +# Use TRL maintained script +hf_jobs("uv", { + "script": "https://raw.githubusercontent.com/huggingface/trl/main/examples/scripts/grpo.py", + "script_args": [ + "--model_name_or_path", "Qwen/Qwen2.5-0.5B-Instruct", + "--dataset_name", "trl-lib/math_shepherd", + "--output_dir", "grpo-model" + ], + "flavor": "a10g-large", + "timeout": "4h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +**Documentation:** `hf_doc_fetch("https://huggingface.co/docs/trl/grpo_trainer")` + +## Reward Modeling + +**What it is:** Train a reward model to score responses, used as a component in RLHF pipelines. + +**When to use:** +- Building RLHF pipeline +- Need automatic quality scoring +- Creating reward signals for PPO training + +**Dataset format:** Preference pairs with "chosen" and "rejected" responses + +**Documentation:** `hf_doc_fetch("https://huggingface.co/docs/trl/reward_trainer")` + +## Method Selection Guide + +| Method | Complexity | Data Required | Use Case | +|--------|-----------|---------------|----------| +| **SFT** | Low | Demonstrations | Initial fine-tuning | +| **DPO** | Medium | Paired preferences | Post-SFT alignment | +| **GRPO** | Medium | Prompts + reward fn | Online RL with automatic rewards | +| **Reward** | Medium | Paired preferences | Building RLHF pipeline | + +## Recommended Pipeline + +**For most use cases:** +1. **Start with SFT** - Fine-tune base model on task data +2. **Follow with DPO** - Align to preferences using paired data +3. **Optional: GGUF conversion** - Deploy for local inference + +**For advanced RL scenarios:** +1. **Start with SFT** - Fine-tune base model +2. **Train reward model** - On preference data + +## Dataset Format Reference + +For complete dataset format specifications, use: +```python +hf_doc_fetch("https://huggingface.co/docs/trl/dataset_formats") +``` + +Or validate your dataset: +```bash +uv run https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py \ + --dataset your/dataset --split train +``` + +## See Also + +- `references/training_patterns.md` - Common training patterns and examples +- `scripts/train_sft_example.py` - Complete SFT template +- `scripts/train_dpo_example.py` - Complete DPO template +- [Dataset Inspector](https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py) - Dataset format validation tool diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/training_patterns.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/training_patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..2101e12a766ea675ee0577b2c4d46f6b5277f7a7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/training_patterns.md @@ -0,0 +1,203 @@ +# Common Training Patterns + +This guide provides common training patterns and use cases for TRL on Hugging Face Jobs. + +## Multi-GPU Training + +Automatic distributed training across multiple GPUs. TRL/Accelerate handles distribution automatically: + +```python +hf_jobs("uv", { + "script": """ +# Your training script here (same as single GPU) +# No changes needed - Accelerate detects multiple GPUs +""", + "flavor": "a10g-largex2", # 2x A10G GPUs + "timeout": "4h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +**Tips for multi-GPU:** +- No code changes needed +- Use `per_device_train_batch_size` (per GPU, not total) +- Effective batch size = `per_device_train_batch_size` × `num_gpus` × `gradient_accumulation_steps` +- Monitor GPU utilization to ensure both GPUs are being used + +## DPO Training (Preference Learning) + +Train with preference data for alignment: + +```python +hf_jobs("uv", { + "script": """ +# /// script +# dependencies = ["trl>=0.12.0", "trackio"] +# /// + +from datasets import load_dataset +from trl import DPOTrainer, DPOConfig +import trackio + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +# Create train/eval split +dataset_split = dataset.train_test_split(test_size=0.1, seed=42) + +config = DPOConfig( + output_dir="dpo-model", + push_to_hub=True, + hub_model_id="username/dpo-model", + num_train_epochs=1, + beta=0.1, # KL penalty coefficient + eval_strategy="steps", + eval_steps=50, + report_to="trackio", + run_name="baseline_run", # use a meaningful run name + # max_length=1024, # Default - only set if you need different sequence length +) + +trainer = DPOTrainer( + model="Qwen/Qwen2.5-0.5B-Instruct", # Use instruct model as base + train_dataset=dataset_split["train"], + eval_dataset=dataset_split["test"], # IMPORTANT: Provide eval_dataset when eval_strategy is enabled + args=config, +) + +trainer.train() +trainer.push_to_hub() +trackio.finish() +""", + "flavor": "a10g-large", + "timeout": "3h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +**For DPO documentation:** Use `hf_doc_fetch("https://huggingface.co/docs/trl/dpo_trainer")` + +## GRPO Training (Online RL) + +Group Relative Policy Optimization for online reinforcement learning: + +```python +hf_jobs("uv", { + "script": "https://raw.githubusercontent.com/huggingface/trl/main/examples/scripts/grpo.py", + "script_args": [ + "--model_name_or_path", "Qwen/Qwen2.5-0.5B-Instruct", + "--dataset_name", "trl-lib/math_shepherd", + "--output_dir", "grpo-model", + "--push_to_hub", + "--hub_model_id", "username/grpo-model" + ], + "flavor": "a10g-large", + "timeout": "4h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +**For GRPO documentation:** Use `hf_doc_fetch("https://huggingface.co/docs/trl/grpo_trainer")` + +## Trackio Configuration + +**Use sensible defaults for trackio setup.** See `references/trackio_guide.md` for complete documentation including grouping runs for experiments. + +### Basic Pattern + +```python +import trackio + +trackio.init( + project="my-training", + run_name="baseline-run", # Descriptive name user will recognize + space_id="username/trackio", # Default space: {username}/trackio + config={ + # Keep config minimal - hyperparameters and model/dataset info only + "model": "Qwen/Qwen2.5-0.5B", + "dataset": "trl-lib/Capybara", + "learning_rate": 2e-5, + } +) + +# Your training code... + +trackio.finish() +``` + +### Grouping for Experiments (Optional) + +When user wants to compare related runs, use the `group` parameter: + +```python +# Hyperparameter sweep +trackio.init(project="hyperparam-sweep", run_name="lr-0.001", group="lr_0.001") +trackio.init(project="hyperparam-sweep", run_name="lr-0.01", group="lr_0.01") +``` + +## Pattern Selection Guide + +| Use Case | Pattern | Hardware | Time | +|----------|---------|----------|------| +| SFT training | `scripts/train_sft_example.py` | a10g-large | 2-6 hours | +| Large dataset (>10K) | Multi-GPU | a10g-largex2 | 4-12 hours | +| Preference learning | DPO Training | a10g-large | 2-4 hours | +| Online RL | GRPO Training | a10g-large | 3-6 hours | + +## Critical: Evaluation Dataset Requirements + +**⚠️ IMPORTANT**: If you set `eval_strategy="steps"` or `eval_strategy="epoch"`, you **MUST** provide an `eval_dataset` to the trainer, or the training will hang. + +### ✅ CORRECT - With eval dataset: +```python +dataset_split = dataset.train_test_split(test_size=0.1, seed=42) + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset_split["train"], + eval_dataset=dataset_split["test"], # ← MUST provide when eval_strategy is enabled + args=SFTConfig(eval_strategy="steps", ...), +) +``` + +### ❌ WRONG - Will hang: +```python +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, + # NO eval_dataset but eval_strategy="steps" ← WILL HANG + args=SFTConfig(eval_strategy="steps", ...), +) +``` + +### Option: Disable evaluation if no eval dataset +```python +config = SFTConfig( + eval_strategy="no", # ← Explicitly disable evaluation + # ... other config +) + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, + # No eval_dataset needed + args=config, +) +``` + +## Best Practices + +1. **Use train/eval splits** - Create evaluation split for monitoring progress +2. **Enable Trackio** - Monitor progress in real-time +3. **Add 20-30% buffer to timeout** - Account for loading/saving overhead +4. **Test with TRL official scripts first** - Use maintained examples before custom code +5. **Always provide eval_dataset** - When using eval_strategy, or set to "no" +6. **Use multi-GPU for large models** - 7B+ models benefit significantly + +## See Also + +- `scripts/train_sft_example.py` - Complete SFT template with Trackio and eval split +- `scripts/train_dpo_example.py` - Complete DPO template +- `scripts/train_grpo_example.py` - Complete GRPO template +- `references/hardware_guide.md` - Detailed hardware specifications +- `references/training_methods.md` - Overview of all TRL training methods +- `references/troubleshooting.md` - Common issues and solutions diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/troubleshooting.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..fc6ffb9e3ad2fb39e6a9a8177a7107a432b7e4e1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/troubleshooting.md @@ -0,0 +1,282 @@ +# Troubleshooting TRL Training Jobs + +Common issues and solutions when training with TRL on Hugging Face Jobs. + +## Training Hangs at "Starting training..." Step + +**Problem:** Job starts but hangs at the training step - never progresses, never times out, just sits there. + +**Root Cause:** Using `eval_strategy="steps"` or `eval_strategy="epoch"` without providing an `eval_dataset` to the trainer. + +**Solution:** + +**Option A: Provide eval_dataset (recommended)** +```python +# Create train/eval split +dataset_split = dataset.train_test_split(test_size=0.1, seed=42) + +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset_split["train"], + eval_dataset=dataset_split["test"], # ← MUST provide when eval_strategy is enabled + args=SFTConfig( + eval_strategy="steps", + eval_steps=50, + ... + ), +) +``` + +**Option B: Disable evaluation** +```python +trainer = SFTTrainer( + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, + # No eval_dataset + args=SFTConfig( + eval_strategy="no", # ← Explicitly disable + ... + ), +) +``` + +**Prevention:** +- Always create train/eval split for better monitoring +- Use `dataset.train_test_split(test_size=0.1, seed=42)` +- Check example scripts: `scripts/train_sft_example.py` includes proper eval setup + +## Job Times Out + +**Problem:** Job terminates before training completes, all progress lost. + +**Solutions:** +- Increase timeout parameter (e.g., `"timeout": "4h"`) +- Reduce `num_train_epochs` or use smaller dataset slice +- Use smaller model or enable LoRA/PEFT to speed up training +- Add 20-30% buffer to estimated time for loading/saving overhead + +**Prevention:** +- Always start with a quick demo run to estimate timing +- Use `scripts/estimate_cost.py` to get time estimates +- Monitor first runs closely via Trackio or logs + +## Model Not Saved to Hub + +**Problem:** Training completes but model doesn't appear on Hub - all work lost. + +**Check:** +- [ ] `push_to_hub=True` in training config +- [ ] `hub_model_id` specified with username (e.g., `"username/model-name"`) +- [ ] `secrets={"HF_TOKEN": "$HF_TOKEN"}` in job submission +- [ ] User has write access to target repo +- [ ] Token has write permissions (check at https://huggingface.co/settings/tokens) +- [ ] Training script calls `trainer.push_to_hub()` at the end + +**See:** `references/hub_saving.md` for detailed Hub authentication troubleshooting + +## Out of Memory (OOM) + +**Problem:** Job fails with CUDA out of memory error. + +**Solutions (in order of preference):** +1. **Reduce batch size:** Lower `per_device_train_batch_size` (try 4 → 2 → 1) +2. **Increase gradient accumulation:** Raise `gradient_accumulation_steps` to maintain effective batch size +3. **Disable evaluation:** Remove `eval_dataset` and `eval_strategy` (saves ~40% memory, good for demos) +4. **Enable LoRA/PEFT:** Use `peft_config=LoraConfig(r=8, lora_alpha=16)` to train adapters only (smaller rank = less memory) +5. **Use larger GPU:** Switch from `t4-small` → `l4x1` → `a10g-large` → `a100-large` +6. **Enable gradient checkpointing:** Set `gradient_checkpointing=True` in config (slower but saves memory) +7. **Use smaller model:** Try a smaller variant (e.g., 0.5B instead of 3B) + +**Memory guidelines:** +- T4 (16GB): <1B models with LoRA +- A10G (24GB): 1-3B models with LoRA, <1B full fine-tune +- A100 (40GB/80GB): 7B+ models with LoRA, 3B full fine-tune + +## Parameter Naming Issues + +**Problem:** `TypeError: SFTConfig.__init__() got an unexpected keyword argument 'max_seq_length'` + +**Cause:** TRL config classes use `max_length`, not `max_seq_length`. + +**Solution:** +```python +# ✅ CORRECT - TRL uses max_length +SFTConfig(max_length=512) +DPOConfig(max_length=512) + +# ❌ WRONG - This will fail +SFTConfig(max_seq_length=512) +``` + +**Note:** Most TRL configs don't require explicit max_length - the default (1024) works well. Only set if you need a specific value. + +## Dataset Format Error + +**Problem:** Training fails with dataset format errors or missing fields. + +**Solutions:** +1. **Check format documentation:** + ```python + hf_doc_fetch("https://huggingface.co/docs/trl/dataset_formats") + ``` + +2. **Validate dataset before training:** + ```bash + uv run https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py \ + --dataset --split train + ``` + Or via hf_jobs: + ```python + hf_jobs("uv", { + "script": "https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py", + "script_args": ["--dataset", "dataset-name", "--split", "train"] + }) + ``` + +3. **Verify field names:** + - **SFT:** Needs "messages" field (conversational), OR "text" field, OR "prompt"/"completion" + - **DPO:** Needs "chosen" and "rejected" fields + - **GRPO:** Needs prompt-only format + +4. **Check dataset split:** + - Ensure split exists (e.g., `split="train"`) + - Preview dataset: `load_dataset("name", split="train[:5]")` + +## Import/Module Errors + +**Problem:** Job fails with "ModuleNotFoundError" or import errors. + +**Solutions:** +1. **Add PEP 723 header with dependencies:** + ```python + # /// script + # dependencies = [ + # "trl>=0.12.0", + # "peft>=0.7.0", + # "transformers>=4.36.0", + # ] + # /// + ``` + +2. **Verify exact format:** + - Must have `# ///` delimiters (with space after `#`) + - Dependencies must be valid PyPI package names + - Check spelling and version constraints + +3. **Test locally first:** + ```bash + uv run train.py # Tests if dependencies are correct + ``` + +## Authentication Errors + +**Problem:** Job fails with authentication or permission errors when pushing to Hub. + +**Solutions:** +1. **Verify authentication:** + ```python + hf_whoami() # Check who's authenticated + ``` + +2. **Check token permissions:** + - Go to https://huggingface.co/settings/tokens + - Ensure token has "write" permission + - Token must not be "read-only" + +3. **Verify token in job:** + ```python + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # Must be in job config + ``` + +4. **Check repo permissions:** + - User must have write access to target repo + - If org repo, user must be member with write access + - Repo must exist or user must have permission to create + +## Job Stuck or Not Starting + +**Problem:** Job shows "pending" or "starting" for extended period. + +**Solutions:** +- Check Jobs dashboard for status: https://huggingface.co/jobs +- Verify hardware availability (some GPU types may have queues) +- Try different hardware flavor if one is heavily utilized +- Check for account billing issues (Jobs requires paid plan) + +**Typical startup times:** +- CPU jobs: 10-30 seconds +- GPU jobs: 30-90 seconds +- If >3 minutes: likely queued or stuck + +## Training Loss Not Decreasing + +**Problem:** Training runs but loss stays flat or doesn't improve. + +**Solutions:** +1. **Check learning rate:** May be too low (try 2e-5 to 5e-5) or too high (try 1e-6) +2. **Verify dataset quality:** Inspect examples to ensure they're reasonable +3. **Check model size:** Very small models may not have capacity for task +4. **Increase training steps:** May need more epochs or larger dataset +5. **Verify dataset format:** Wrong format may cause degraded training + +## Logs Not Appearing + +**Problem:** Cannot see training logs or progress. + +**Solutions:** +1. **Wait 30-60 seconds:** Initial logs can be delayed +2. **Check logs via MCP tool:** + ```python + hf_jobs("logs", {"job_id": "your-job-id"}) + ``` +3. **Use Trackio for real-time monitoring:** See `references/trackio_guide.md` +4. **Verify job is actually running:** + ```python + hf_jobs("inspect", {"job_id": "your-job-id"}) + ``` + +## Checkpoint/Resume Issues + +**Problem:** Cannot resume from checkpoint or checkpoint not saved. + +**Solutions:** +1. **Enable checkpoint saving:** + ```python + SFTConfig( + save_strategy="steps", + save_steps=100, + hub_strategy="every_save", # Push each checkpoint + ) + ``` + +2. **Verify checkpoints pushed to Hub:** Check model repo for checkpoint folders + +3. **Resume from checkpoint:** + ```python + trainer = SFTTrainer( + model="username/model-name", # Can be checkpoint path + resume_from_checkpoint="username/model-name/checkpoint-1000", + ) + ``` + +## Getting Help + +If issues persist: + +1. **Check TRL documentation:** + ```python + hf_doc_search("your issue", product="trl") + ``` + +2. **Check Jobs documentation:** + ```python + hf_doc_fetch("https://huggingface.co/docs/huggingface_hub/guides/jobs") + ``` + +3. **Review related guides:** + - `references/hub_saving.md` - Hub authentication issues + - `references/hardware_guide.md` - Hardware selection and specs + - `references/training_patterns.md` - Eval dataset requirements + - SKILL.md "Working with Scripts" section - Script format and URL issues + +4. **Ask in HF forums:** https://discuss.huggingface.co/ diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/unsloth.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/unsloth.md new file mode 100644 index 0000000000000000000000000000000000000000..83e1e116e54106709eafc3ff4273419a5512c8a6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/llm-trainer/references/unsloth.md @@ -0,0 +1,313 @@ +# Unsloth: Fast Fine-Tuning with Memory Optimization + +**Unsloth** is a fine-tuning library that provides ~2x faster training and ~60% less VRAM usage for LLM training. It's particularly useful when working with limited GPU memory or when speed is critical. + +- **GitHub**: [unslothai/unsloth](https://github.com/unslothai/unsloth) +- **Docs**: [unsloth.ai/docs](https://unsloth.ai/docs) + +## When to Use Unsloth + +Use Unsloth if instructed to do so, or one of the following use cases applies: + +| Use Case | Recommendation | +|----------|----------------| +| Standard text LLM fine-tuning | TRL is sufficient, but Unsloth is faster | +| Limited GPU memory | **Use Unsloth** - 60% less VRAM | +| Need maximum speed | **Use Unsloth** - 2x faster | +| Large models (>13B) | **Use Unsloth** - memory efficiency critical | + +## Supported Models + +Unsloth supports many popular models including: +- **Text LLMs**: Llama 3/3.1/3.2/3.3, Qwen 2.5/3, Mistral, Phi-4, Gemma 2/3, LFM2/2.5 +- **Vision LLMs**: Qwen3-VL, Gemma 3, Llama 3.2 Vision, Pixtral + +Use Unsloth's pre-optimized model variants when available: +```python +# Unsloth-optimized models load faster and use less memory +model_id = "unsloth/LFM2.5-1.2B-Instruct" # 4-bit quantized +model_id = "unsloth/gemma-3-4b-pt" # Vision model +model_id = "unsloth/Qwen3-VL-8B-Instruct" # Vision model +``` + +## Installation + +```python +# /// script +# dependencies = [ +# "unsloth", +# "trl", +# "datasets", +# "trackio", +# ] +# /// +``` + +## Basic Usage: Text LLM + +```python +from unsloth import FastLanguageModel +from trl import SFTTrainer, SFTConfig +from datasets import load_dataset + +# Load model with Unsloth optimizations +model, tokenizer = FastLanguageModel.from_pretrained( + model_name="LiquidAI/LFM2.5-1.2B-Instruct", + max_seq_length=4096, +) + +# Add LoRA adapters +model = FastLanguageModel.get_peft_model( + model, + r=16, + lora_alpha=16, + target_modules=["q_proj", "k_proj", "v_proj", "out_proj", "in_proj", "w1", "w2", "w3"], + lora_dropout=0, + bias="none", + use_gradient_checkpointing="unsloth", + random_state=3407, +) + +# Load dataset +dataset = load_dataset("trl-lib/Capybara", split="train") + +# Train with TRL +trainer = SFTTrainer( + model=model, + tokenizer=tokenizer, + train_dataset=dataset, + args=SFTConfig( + output_dir="./output", + per_device_train_batch_size=2, + gradient_accumulation_steps=4, + max_steps=500, + learning_rate=2e-4, + report_to="trackio", + ), +) + +trainer.train() +``` + +## LFM2.5 Specific Settings + +For LFM2.5 inference, use these recommended generation parameters: + +**Instruct models:** +```python +temperature = 0.1 +top_k = 50 +top_p = 0.1 +repetition_penalty = 1.05 +``` + +**Thinking models:** +```python +temperature = 0.05 +top_k = 50 +repetition_penalty = 1.05 +``` + +## Vision-Language Models (VLMs) + +Unsloth provides specialized support for VLMs with `FastVisionModel`: + +```python +from unsloth import FastVisionModel, get_chat_template +from unsloth.trainer import UnslothVisionDataCollator +from trl import SFTTrainer, SFTConfig +from datasets import load_dataset + +# Load VLM with Unsloth +model, processor = FastVisionModel.from_pretrained( + "unsloth/gemma-3-4b-pt", # or "unsloth/Qwen3-VL-8B-Instruct" + load_in_4bit=True, + use_gradient_checkpointing="unsloth", +) + +# Add LoRA for all modalities +model = FastVisionModel.get_peft_model( + model, + finetune_vision_layers=True, # Train vision encoder + finetune_language_layers=True, # Train language model + finetune_attention_modules=True, # Train attention + finetune_mlp_modules=True, # Train MLPs + r=16, + lora_alpha=32, + target_modules="all-linear", +) + +# Apply chat template (required for base models) +processor = get_chat_template(processor, "gemma-3") + +# Load VLM dataset (with images and messages) +dataset = load_dataset("your-vlm-dataset", split="train", streaming=True) + +# Enable training mode +FastVisionModel.for_training(model) + +# Train with VLM-specific collator +trainer = SFTTrainer( + model=model, + train_dataset=dataset, + processing_class=processor.tokenizer, + data_collator=UnslothVisionDataCollator(model, processor), + args=SFTConfig( + output_dir="./vlm-output", + per_device_train_batch_size=2, + gradient_accumulation_steps=4, + max_steps=500, + learning_rate=2e-4, + # VLM-specific settings + remove_unused_columns=False, + dataset_text_field="", + dataset_kwargs={"skip_prepare_dataset": True}, + report_to="trackio", + ), +) + +trainer.train() +``` + +## Key Differences from Standard TRL + +| Aspect | Standard TRL | Unsloth | +|--------|--------------|---------| +| Model loading | `AutoModelForCausalLM.from_pretrained()` | `FastLanguageModel.from_pretrained()` | +| LoRA setup | `PeftModel` / `LoraConfig` | `FastLanguageModel.get_peft_model()` | +| VLM loading | Limited support | `FastVisionModel.from_pretrained()` | +| VLM collator | Manual | `UnslothVisionDataCollator` | +| Memory usage | Standard | ~60% less | +| Training speed | Standard | ~2x faster | + +## VLM Dataset Format + +VLM datasets should have: +- `images`: List of PIL images or image paths +- `messages`: Conversation format with image references + +```python +{ + "images": [, ...], + "messages": [ + {"role": "user", "content": [ + {"type": "image"}, + {"type": "text", "text": "Describe this image"} + ]}, + {"role": "assistant", "content": "This image shows..."} + ] +} +``` + +## Streaming Datasets + +For large VLM datasets, use streaming to avoid disk space issues: + +```python +dataset = load_dataset( + "your-vlm-dataset", + split="train", + streaming=True, # Stream from Hub +) + +# Must use max_steps with streaming (no epoch-based training) +SFTConfig(max_steps=500, ...) +``` + +## Saving Models + +### Save LoRA Adapter + +```python +model.save_pretrained("./adapter") +processor.save_pretrained("./adapter") + +# Push to Hub +model.push_to_hub("username/my-vlm-adapter") +processor.push_to_hub("username/my-vlm-adapter") +``` + +### Merge and Save Full Model + +```python +# Merge LoRA weights into base model +model = model.merge_and_unload() + +# Save merged model +model.save_pretrained("./merged") +tokenizer.save_pretrained("./merged") +``` + +### Convert to GGUF + +Unsloth models can be converted to GGUF for llama.cpp/Ollama: + +```python +# Save in 16-bit for GGUF conversion +model.save_pretrained_gguf("./gguf", tokenizer, quantization_method="f16") + +# Or directly quantize +model.save_pretrained_gguf("./gguf", tokenizer, quantization_method="q4_k_m") +``` + +## Qwen3-VL Specific Settings + +For Qwen3-VL models, use these recommended settings: + +**Instruct models:** +```python +temperature = 0.7 +top_p = 0.8 +presence_penalty = 1.5 +``` + +**Thinking models:** +```python +temperature = 1.0 +top_p = 0.95 +presence_penalty = 0.0 +``` + +## Hardware Requirements + +| Model | Min VRAM (Unsloth 4-bit) | Recommended GPU | +|-------|--------------------------|-----------------| +| 2B-4B | 8GB | T4, L4 | +| 7B-8B | 16GB | A10G, L4x4 | +| 13B | 24GB | A10G-large | +| 30B+ | 48GB+ | A100 | + +## Example: Full VLM Training Script + +See `scripts/unsloth_sft_example.py` for a complete production-ready example that includes: +- Unsloth VLM setup +- Streaming dataset support +- Trackio monitoring +- Hub push +- CLI arguments + +Run locally: +```bash +uv run scripts/unsloth_sft_example.py \ + --dataset trl-lib/Capybara \ + --max-steps 500 \ + --output-repo username/my-model +``` + +Run on HF Jobs: +```python +hf_jobs("uv", { + "script": " +``` + +## Core Concepts + +### 1. Pipeline API +The pipeline API is the easiest way to use models. It groups together preprocessing, model inference, and postprocessing: + +```javascript +import { pipeline } from '@huggingface/transformers'; + +// Create a pipeline for a specific task +const pipe = await pipeline('sentiment-analysis'); + +// Use the pipeline +const result = await pipe('I love transformers!'); +// Output: [{ label: 'POSITIVE', score: 0.999817686 }] + +// IMPORTANT: Always dispose when done to free memory +await classifier.dispose(); +``` + +**⚠️ Memory Management:** All pipelines must be disposed with `pipe.dispose()` when finished to prevent memory leaks. See examples in [Code Examples](./references/EXAMPLES.md) for cleanup patterns across different environments. + +### 2. Model Selection +You can specify a custom model as the second argument: + +```javascript +const pipe = await pipeline( + 'sentiment-analysis', + 'Xenova/bert-base-multilingual-uncased-sentiment' +); +``` + +**Finding Models:** + +Browse available Transformers.js models on Hugging Face Hub: +- **All models**: https://huggingface.co/models?library=transformers.js&sort=trending +- **By task**: Add `pipeline_tag` parameter + - Text generation: https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending + - Image classification: https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js&sort=trending + - Speech recognition: https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js&sort=trending + +**Tip:** Filter by task type, sort by trending/downloads, and check model cards for performance metrics and usage examples. + +### 3. Device Selection +Choose where to run the model: + +```javascript +// Run on CPU (default for WASM) +const pipe = await pipeline('sentiment-analysis', 'model-id'); + +// Run on GPU (WebGPU - experimental) +const pipe = await pipeline('sentiment-analysis', 'model-id', { + device: 'webgpu', +}); +``` + +### 4. Quantization Options +Control model precision vs. performance: + +```javascript +// Use quantized model (faster, smaller) +const pipe = await pipeline('sentiment-analysis', 'model-id', { + dtype: 'q4', // Options: 'fp32', 'fp16', 'q8', 'q4' +}); +``` + +## Supported Tasks + +**Note:** All examples below show basic usage. + +### Natural Language Processing + +#### Text Classification +```javascript +const classifier = await pipeline('text-classification'); +const result = await classifier('This movie was amazing!'); +``` + +#### Named Entity Recognition (NER) +```javascript +const ner = await pipeline('token-classification'); +const entities = await ner('My name is John and I live in New York.'); +``` + +#### Question Answering +```javascript +const qa = await pipeline('question-answering'); +const answer = await qa({ + question: 'What is the capital of France?', + context: 'Paris is the capital and largest city of France.' +}); +``` + +#### Text Generation +```javascript +const generator = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX'); +const text = await generator('Once upon a time', { + max_new_tokens: 100, + temperature: 0.7 +}); +``` + +**For streaming and chat:** See **[Text Generation Guide](./references/TEXT_GENERATION.md)** for: +- Streaming token-by-token output with `TextStreamer` +- Chat/conversation format with system/user/assistant roles +- Generation parameters (temperature, top_k, top_p) +- Browser and Node.js examples +- React components and API endpoints + +#### Translation +```javascript +const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M'); +const output = await translator('Hello, how are you?', { + src_lang: 'eng_Latn', + tgt_lang: 'fra_Latn' +}); +``` + +#### Summarization +```javascript +const summarizer = await pipeline('summarization'); +const summary = await summarizer(longText, { + max_length: 100, + min_length: 30 +}); +``` + +#### Zero-Shot Classification +```javascript +const classifier = await pipeline('zero-shot-classification'); +const result = await classifier('This is a story about sports.', ['politics', 'sports', 'technology']); +``` + +### Computer Vision + +#### Image Classification +```javascript +const classifier = await pipeline('image-classification'); +const result = await classifier('https://example.com/image.jpg'); +// Or with local file +const result = await classifier(imageUrl); +``` + +#### Object Detection +```javascript +const detector = await pipeline('object-detection'); +const objects = await detector('https://example.com/image.jpg'); +// Returns: [{ label: 'person', score: 0.95, box: { xmin, ymin, xmax, ymax } }, ...] +``` + +#### Image Segmentation +```javascript +const segmenter = await pipeline('image-segmentation'); +const segments = await segmenter('https://example.com/image.jpg'); +``` + +#### Depth Estimation +```javascript +const depthEstimator = await pipeline('depth-estimation'); +const depth = await depthEstimator('https://example.com/image.jpg'); +``` + +#### Zero-Shot Image Classification +```javascript +const classifier = await pipeline('zero-shot-image-classification'); +const result = await classifier('image.jpg', ['cat', 'dog', 'bird']); +``` + +### Audio Processing + +#### Automatic Speech Recognition +```javascript +const transcriber = await pipeline('automatic-speech-recognition'); +const result = await transcriber('audio.wav'); +// Returns: { text: 'transcribed text here' } +``` + +#### Audio Classification +```javascript +const classifier = await pipeline('audio-classification'); +const result = await classifier('audio.wav'); +``` + +#### Text-to-Speech +```javascript +const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts'); +const audio = await synthesizer('Hello, this is a test.', { + speaker_embeddings: speakerEmbeddings +}); +``` + +### Multimodal + +#### Image-to-Text (Image Captioning) +```javascript +const captioner = await pipeline('image-to-text'); +const caption = await captioner('image.jpg'); +``` + +#### Document Question Answering +```javascript +const docQA = await pipeline('document-question-answering'); +const answer = await docQA('document-image.jpg', 'What is the total amount?'); +``` + +#### Zero-Shot Object Detection +```javascript +const detector = await pipeline('zero-shot-object-detection'); +const objects = await detector('image.jpg', ['person', 'car', 'tree']); +``` + +### Feature Extraction (Embeddings) + +```javascript +const extractor = await pipeline('feature-extraction'); +const embeddings = await extractor('This is a sentence to embed.'); +// Returns: tensor of shape [1, sequence_length, hidden_size] + +// For sentence embeddings (mean pooling) +const extractor = await pipeline('feature-extraction', 'onnx-community/all-MiniLM-L6-v2-ONNX'); +const embeddings = await extractor('Text to embed', { pooling: 'mean', normalize: true }); +``` + +## Finding and Choosing Models + +### Browsing the Hugging Face Hub + +Discover compatible Transformers.js models on Hugging Face Hub: + +**Base URL (all models):** +``` +https://huggingface.co/models?library=transformers.js&sort=trending +``` + +**Filter by task** using the `pipeline_tag` parameter: + +| Task | URL | +|------|-----| +| **Text Generation** | https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending | +| **Text Classification** | https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js&sort=trending | +| **Translation** | https://huggingface.co/models?pipeline_tag=translation&library=transformers.js&sort=trending | +| **Summarization** | https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js&sort=trending | +| **Question Answering** | https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js&sort=trending | +| **Image Classification** | https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js&sort=trending | +| **Object Detection** | https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js&sort=trending | +| **Image Segmentation** | https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js&sort=trending | +| **Speech Recognition** | https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js&sort=trending | +| **Audio Classification** | https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js&sort=trending | +| **Image-to-Text** | https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js&sort=trending | +| **Feature Extraction** | https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js&sort=trending | +| **Zero-Shot Classification** | https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js&sort=trending | + +**Sort options:** +- `&sort=trending` - Most popular recently +- `&sort=downloads` - Most downloaded overall +- `&sort=likes` - Most liked by community +- `&sort=modified` - Recently updated + +### Choosing the Right Model + +Consider these factors when selecting a model: + +**1. Model Size** +- **Small (< 100MB)**: Fast, suitable for browsers, limited accuracy +- **Medium (100MB - 500MB)**: Balanced performance, good for most use cases +- **Large (> 500MB)**: High accuracy, slower, better for Node.js or powerful devices + +**2. Quantization** +Models are often available in different quantization levels: +- `fp32` - Full precision (largest, most accurate) +- `fp16` - Half precision (smaller, still accurate) +- `q8` - 8-bit quantized (much smaller, slight accuracy loss) +- `q4` - 4-bit quantized (smallest, noticeable accuracy loss) + +**3. Task Compatibility** +Check the model card for: +- Supported tasks (some models support multiple tasks) +- Input/output formats +- Language support (multilingual vs. English-only) +- License restrictions + +**4. Performance Metrics** +Model cards typically show: +- Accuracy scores +- Benchmark results +- Inference speed +- Memory requirements + +### Example: Finding a Text Generation Model + +```javascript +// 1. Visit: https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending + +// 2. Browse and select a model (e.g., onnx-community/gemma-3-270m-it-ONNX) + +// 3. Check model card for: +// - Model size: ~270M parameters +// - Quantization: q4 available +// - Language: English +// - Use case: Instruction-following chat + +// 4. Use the model: +import { pipeline } from '@huggingface/transformers'; + +const generator = await pipeline( + 'text-generation', + 'onnx-community/gemma-3-270m-it-ONNX', + { dtype: 'q4' } // Use quantized version for faster inference +); + +const output = await generator('Explain quantum computing in simple terms.', { + max_new_tokens: 100 +}); + +await generator.dispose(); +``` + +### Tips for Model Selection + +1. **Start Small**: Test with a smaller model first, then upgrade if needed +2. **Check ONNX Support**: Ensure the model has ONNX files (look for `onnx` folder in model repo) +3. **Read Model Cards**: Model cards contain usage examples, limitations, and benchmarks +4. **Test Locally**: Benchmark inference speed and memory usage in your environment +5. **Community Models**: Look for models by `Xenova` (Transformers.js maintainer) or `onnx-community` +6. **Version Pin**: Use specific git commits in production for stability: + ```javascript + const pipe = await pipeline('task', 'model-id', { revision: 'abc123' }); + ``` + +## Advanced Configuration + +### Environment Configuration (`env`) + +The `env` object provides comprehensive control over Transformers.js execution, caching, and model loading. + +**Quick Overview:** + +```javascript +import { env } from '@huggingface/transformers'; + +// View version +console.log(env.version); // e.g., '3.8.1' + +// Common settings +env.allowRemoteModels = true; // Load from Hugging Face Hub +env.allowLocalModels = false; // Load from file system +env.localModelPath = '/models/'; // Local model directory +env.useFSCache = true; // Cache models on disk (Node.js) +env.useBrowserCache = true; // Cache models in browser +env.cacheDir = './.cache'; // Cache directory location +``` + +**Configuration Patterns:** + +```javascript +// Development: Fast iteration with remote models +env.allowRemoteModels = true; +env.useFSCache = true; + +// Production: Local models only +env.allowRemoteModels = false; +env.allowLocalModels = true; +env.localModelPath = '/app/models/'; + +// Custom CDN +env.remoteHost = 'https://cdn.example.com/models'; + +// Disable caching (testing) +env.useFSCache = false; +env.useBrowserCache = false; +``` + +For complete documentation on all configuration options, caching strategies, cache management, pre-downloading models, and more, see: + +**→ [Configuration Reference](./references/CONFIGURATION.md)** + +### Working with Tensors + +```javascript +import { AutoTokenizer, AutoModel } from '@huggingface/transformers'; + +// Load tokenizer and model separately for more control +const tokenizer = await AutoTokenizer.from_pretrained('bert-base-uncased'); +const model = await AutoModel.from_pretrained('bert-base-uncased'); + +// Tokenize input +const inputs = await tokenizer('Hello world!'); + +// Run model +const outputs = await model(inputs); +``` + +### Batch Processing + +```javascript +const classifier = await pipeline('sentiment-analysis'); + +// Process multiple texts +const results = await classifier([ + 'I love this!', + 'This is terrible.', + 'It was okay.' +]); +``` + +## Browser-Specific Considerations + +### WebGPU Usage +WebGPU provides GPU acceleration in browsers: + +```javascript +const pipe = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX', { + device: 'webgpu', + dtype: 'fp32' +}); +``` + +**Note**: WebGPU is experimental. Check browser compatibility and file issues if problems occur. + +### WASM Performance +Default browser execution uses WASM: + +```javascript +// Optimized for browsers with quantization +const pipe = await pipeline('sentiment-analysis', 'model-id', { + dtype: 'q8' // or 'q4' for even smaller size +}); +``` + +### Progress Tracking & Loading Indicators + +Models can be large (ranging from a few MB to several GB) and consist of multiple files. Track download progress by passing a callback to the `pipeline()` function: + +```javascript +import { pipeline } from '@huggingface/transformers'; + +// Track progress for each file +const fileProgress = {}; + +function onProgress(info) { + console.log(`${info.status}: ${info.file}`); + + if (info.status === 'progress') { + fileProgress[info.file] = info.progress; + console.log(`${info.file}: ${info.progress.toFixed(1)}%`); + } + + if (info.status === 'done') { + console.log(`✓ ${info.file} complete`); + } +} + +// Pass callback to pipeline +const classifier = await pipeline('sentiment-analysis', null, { + progress_callback: onProgress +}); +``` + +**Progress Info Properties:** + +```typescript +interface ProgressInfo { + status: 'initiate' | 'download' | 'progress' | 'done' | 'ready'; + name: string; // Model id or path + file: string; // File being processed + progress?: number; // Percentage (0-100, only for 'progress' status) + loaded?: number; // Bytes downloaded (only for 'progress' status) + total?: number; // Total bytes (only for 'progress' status) +} +``` + +For complete examples including browser UIs, React components, CLI progress bars, and retry logic, see: + +**→ [Pipeline Options - Progress Callback](./references/PIPELINE_OPTIONS.md#progress-callback)** + +## Error Handling + +```javascript +try { + const pipe = await pipeline('sentiment-analysis', 'model-id'); + const result = await pipe('text to analyze'); +} catch (error) { + if (error.message.includes('fetch')) { + console.error('Model download failed. Check internet connection.'); + } else if (error.message.includes('ONNX')) { + console.error('Model execution failed. Check model compatibility.'); + } else { + console.error('Unknown error:', error); + } +} +``` + +## Performance Tips + +1. **Reuse Pipelines**: Create pipeline once, reuse for multiple inferences +2. **Use Quantization**: Start with `q8` or `q4` for faster inference +3. **Batch Processing**: Process multiple inputs together when possible +4. **Cache Models**: Models are cached automatically (see **[Caching Reference](./references/CACHE.md)** for details on browser Cache API, Node.js filesystem cache, and custom implementations) +5. **WebGPU for Large Models**: Use WebGPU for models that benefit from GPU acceleration +6. **Prune Context**: For text generation, limit `max_new_tokens` to avoid memory issues +7. **Clean Up Resources**: Call `pipe.dispose()` when done to free memory + +## Memory Management + +**IMPORTANT:** Always call `pipe.dispose()` when finished to prevent memory leaks. + +```javascript +const pipe = await pipeline('sentiment-analysis'); +const result = await pipe('Great product!'); +await pipe.dispose(); // ✓ Free memory (100MB - several GB per model) +``` + +**When to dispose:** +- Application shutdown or component unmount +- Before loading a different model +- After batch processing in long-running apps + +Models consume significant memory and hold GPU/CPU resources. Disposal is critical for browser memory limits and server stability. + +For detailed patterns (React cleanup, servers, browser), see **[Code Examples](./references/EXAMPLES.md)** + +## Troubleshooting + +### Model Not Found +- Verify model exists on Hugging Face Hub +- Check model name spelling +- Ensure model has ONNX files (look for `onnx` folder in model repo) + +### Memory Issues +- Use smaller models or quantized versions (`dtype: 'q4'`) +- Reduce batch size +- Limit sequence length with `max_length` + +### WebGPU Errors +- Check browser compatibility (Chrome 113+, Edge 113+) +- Try `dtype: 'fp16'` if `fp32` fails +- Fall back to WASM if WebGPU unavailable + +## Reference Documentation + +### This Skill +- **[Pipeline Options](./references/PIPELINE_OPTIONS.md)** - Configure `pipeline()` with `progress_callback`, `device`, `dtype`, etc. +- **[Configuration Reference](./references/CONFIGURATION.md)** - Global `env` configuration for caching and model loading +- **[Caching Reference](./references/CACHE.md)** - Browser Cache API, Node.js filesystem cache, and custom cache implementations +- **[Text Generation Guide](./references/TEXT_GENERATION.md)** - Streaming, chat format, and generation parameters +- **[Model Architectures](./references/MODEL_ARCHITECTURES.md)** - Supported models and selection tips +- **[Code Examples](./references/EXAMPLES.md)** - Real-world implementations for different runtimes + +### Official Transformers.js +- Official docs: https://huggingface.co/docs/transformers.js +- API reference: https://huggingface.co/docs/transformers.js/api/pipelines +- Model hub: https://huggingface.co/models?library=transformers.js +- GitHub: https://github.com/huggingface/transformers.js +- Examples: https://github.com/huggingface/transformers.js/tree/main/examples + +## Best Practices + +1. **Always Dispose Pipelines**: Call `pipe.dispose()` when done - critical for preventing memory leaks +2. **Start with Pipelines**: Use the pipeline API unless you need fine-grained control +3. **Test Locally First**: Test models with small inputs before deploying +4. **Monitor Model Sizes**: Be aware of model download sizes for web applications +5. **Handle Loading States**: Show progress indicators for better UX +6. **Version Pin**: Pin specific model versions for production stability +7. **Error Boundaries**: Always wrap pipeline calls in try-catch blocks +8. **Progressive Enhancement**: Provide fallbacks for unsupported browsers +9. **Reuse Models**: Load once, use many times - don't recreate pipelines unnecessarily +10. **Graceful Shutdown**: Dispose models on SIGTERM/SIGINT in servers + +## Quick Reference: Task IDs + +| Task | Task ID | +|------|---------| +| Text classification | `text-classification` or `sentiment-analysis` | +| Token classification | `token-classification` or `ner` | +| Question answering | `question-answering` | +| Fill mask | `fill-mask` | +| Summarization | `summarization` | +| Translation | `translation` | +| Text generation | `text-generation` | +| Text-to-text generation | `text2text-generation` | +| Zero-shot classification | `zero-shot-classification` | +| Image classification | `image-classification` | +| Image segmentation | `image-segmentation` | +| Object detection | `object-detection` | +| Depth estimation | `depth-estimation` | +| Image-to-image | `image-to-image` | +| Zero-shot image classification | `zero-shot-image-classification` | +| Zero-shot object detection | `zero-shot-object-detection` | +| Automatic speech recognition | `automatic-speech-recognition` | +| Audio classification | `audio-classification` | +| Text-to-speech | `text-to-speech` or `text-to-audio` | +| Image-to-text | `image-to-text` | +| Document question answering | `document-question-answering` | +| Feature extraction | `feature-extraction` | +| Sentence similarity | `sentence-similarity` | + +--- + +This skill enables you to integrate state-of-the-art machine learning capabilities directly into JavaScript applications without requiring separate ML servers or Python environments. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d358f66717d43033ef83430a01844534f2d29de0 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Transformers.js" + short_description: "Run Hugging Face models directly in JavaScript and TypeScript" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/CACHE.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/CACHE.md new file mode 100644 index 0000000000000000000000000000000000000000..6f97b2cdd54b256df3d874f9372b2890341b44c4 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/CACHE.md @@ -0,0 +1,339 @@ +# Caching Reference + +Complete guide to caching strategies for Transformers.js models across different environments. + +## Table of Contents + +1. [Overview](#overview) +2. [Browser Caching](#browser-caching) +3. [Node.js Caching](#nodejs-caching) +4. [Custom Cache Implementation](#custom-cache-implementation) +5. [Cache Configuration](#cache-configuration) + +## Overview + +Transformers.js models can be large (from a few MB to several GB), so caching is critical for performance. The caching strategy differs based on the environment: + +- **Browser**: Uses the Cache API (browser cache storage) +- **Node.js**: Uses filesystem cache in `~/.cache/huggingface/` +- **Custom**: Implement your own cache (database, cloud storage, etc.) + +### Default Behavior + +```javascript +import { pipeline } from '@huggingface/transformers'; + +// First load: downloads model +const pipe = await pipeline('sentiment-analysis'); + +// Subsequent loads: uses cached model +const pipe2 = await pipeline('sentiment-analysis'); // Fast! +``` + +Caching is **automatic** and enabled by default. Models are cached after the first download. + +## Browser Caching + +### Using the Cache API + +In browser environments, Transformers.js uses the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to store models: + +```javascript +import { env, pipeline } from '@huggingface/transformers'; + +// Browser cache is enabled by default +console.log(env.useBrowserCache); // true + +// Load model (cached automatically) +const classifier = await pipeline('sentiment-analysis'); +``` + +**How it works:** + +1. Model files are downloaded from Hugging Face Hub +2. Files are stored in the browser's Cache Storage +3. Subsequent loads retrieve from cache (no network request) +4. Cache persists across page reloads and browser sessions + +### Cache Location + +Browser caches are stored in: +- **Chrome/Edge**: `Cache Storage` in DevTools → Application tab → Cache storage +- **Firefox**: `about:cache` → Storage +- **Safari**: Web Inspector → Storage tab + +### Disable Browser Cache + +```javascript +import { env } from '@huggingface/transformers'; + +// Disable browser caching (not recommended) +env.useBrowserCache = false; + +// Models will be re-downloaded on every page load +``` + +**Use case:** Testing, development, or debugging cache issues. + +### Browser Storage Limits + +Browsers impose storage quotas: + +- **Chrome**: ~60% of available disk space (but can evict data) +- **Firefox**: ~50% of available disk space +- **Safari**: ~1GB per origin (prompt for more) + +**Tip:** Monitor storage usage with the [Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Storage_API): + +```javascript +if ('storage' in navigator && 'estimate' in navigator.storage) { + const estimate = await navigator.storage.estimate(); + const percentUsed = (estimate.usage / estimate.quota) * 100; + console.log(`Storage: ${percentUsed.toFixed(2)}% used`); + console.log(`Available: ${((estimate.quota - estimate.usage) / 1024 / 1024).toFixed(2)} MB`); +} +``` + +## Node.js Caching + +### Filesystem Cache + +In Node.js, models are cached to the filesystem: + +```javascript +import { env, pipeline } from '@huggingface/transformers'; + +// Default cache directory (Node.js) +console.log(env.cacheDir); // './.cache' (relative to current directory) + +// Filesystem cache is enabled by default +console.log(env.useFSCache); // true + +// Load model (cached to disk) +const classifier = await pipeline('sentiment-analysis'); +``` + +### Default Cache Location + +**Default behavior:** +- Cache directory: `./.cache` (relative to where Node.js process runs) +- Full default path: `~/.cache/huggingface/` when using Hugging Face tools + +**Note:** The statement "Models are cached automatically in `~/.cache/huggingface/`" from performance tips is specific to Hugging Face's Python tooling convention. In Transformers.js for Node.js, the default is `./.cache` unless configured otherwise. + +### Custom Cache Directory + +```javascript +import { env, pipeline } from '@huggingface/transformers'; + +// Set custom cache directory +env.cacheDir = '/var/cache/transformers'; + +// Or use environment variable (Node.js convention) +env.cacheDir = process.env.HF_HOME || '~/.cache/huggingface'; + +// Now load model +const classifier = await pipeline('sentiment-analysis'); +// Cached to: /var/cache/transformers/models--Xenova--distilbert-base-uncased-finetuned-sst-2-english/ +``` + +**Pattern:** `models--{organization}--{model-name}/` + +### Disable Filesystem Cache + +```javascript +import { env } from '@huggingface/transformers'; + +// Disable filesystem caching (not recommended) +env.useFSCache = false; + +// Models will be re-downloaded on every load +``` + +**Use case:** Testing, CI/CD environments, or containers with ephemeral storage. + +## Custom Cache Implementation + +Implement your own cache for specialized storage backends. + +### Custom Cache Interface + +```typescript +interface CacheInterface { + /** + * Check if a URL is cached + */ + match(url: string): Promise; + + /** + * Store a URL and its response + */ + put(url: string, response: Response): Promise; +} +``` + +### Example: Cloud Storage Cache (S3) + +```javascript +import { env, pipeline } from '@huggingface/transformers'; +import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; +import { Readable } from 'stream'; + +class S3Cache { + constructor(bucket, region = 'us-east-1') { + this.bucket = bucket; + this.s3 = new S3Client({ region }); + } + + async match(url) { + const key = this.urlToKey(url); + + try { + const command = new GetObjectCommand({ + Bucket: this.bucket, + Key: key + }); + const response = await this.s3.send(command); + + // Convert stream to buffer + const chunks = []; + for await (const chunk of response.Body) { + chunks.push(chunk); + } + const body = Buffer.concat(chunks); + + return new Response(body, { + status: 200, + headers: JSON.parse(response.Metadata.headers || '{}') + }); + } catch (error) { + if (error.name === 'NoSuchKey') return undefined; + throw error; + } + } + + async put(url, response) { + const key = this.urlToKey(url); + const clonedResponse = response.clone(); + const body = Buffer.from(await clonedResponse.arrayBuffer()); + const headers = JSON.stringify(Object.fromEntries(response.headers.entries())); + + const command = new PutObjectCommand({ + Bucket: this.bucket, + Key: key, + Body: body, + Metadata: { headers } + }); + + await this.s3.send(command); + } + + urlToKey(url) { + // Convert URL to S3 key (remove protocol, replace slashes) + return url.replace(/^https?:\/\//, '').replace(/\//g, '_'); + } +} + +// Configure S3 cache +env.useCustomCache = true; +env.customCache = new S3Cache('my-transformers-cache', 'us-east-1'); +env.useFSCache = false; + +// Use S3 cache +const classifier = await pipeline('sentiment-analysis'); +``` + +## Cache Configuration + +### Environment Variables + +Use environment variables to configure caching: + +```javascript +import { env } from '@huggingface/transformers'; + +// Configure cache directory from environment +env.cacheDir = process.env.TRANSFORMERS_CACHE || './.cache'; + +// Disable caching in CI/CD +if (process.env.CI === 'true') { + env.useFSCache = false; + env.useBrowserCache = false; +} + +// Production: use pre-cached models +if (process.env.NODE_ENV === 'production') { + env.allowRemoteModels = false; + env.allowLocalModels = true; + env.localModelPath = process.env.MODEL_PATH || '/app/models'; +} +``` + +### Configuration Patterns + +#### Development: Enable All Caching + +```javascript +import { env } from '@huggingface/transformers'; + +env.allowRemoteModels = true; +env.useFSCache = true; // Node.js +env.useBrowserCache = true; // Browser +env.cacheDir = './.cache'; +``` + +#### Production: Local Models Only + +```javascript +import { env } from '@huggingface/transformers'; + +env.allowRemoteModels = false; +env.allowLocalModels = true; +env.localModelPath = '/app/models'; +env.useFSCache = true; +``` + +#### Testing: Disable Caching + +```javascript +import { env } from '@huggingface/transformers'; + +env.useFSCache = false; +env.useBrowserCache = false; +env.allowRemoteModels = true; // Download every time +``` + +#### Hybrid: Cache + Remote Fallback + +```javascript +import { env } from '@huggingface/transformers'; + +// Try local cache first, fall back to remote +env.allowRemoteModels = true; +env.allowLocalModels = true; +env.useFSCache = true; +env.localModelPath = './models'; +``` + +--- + +## Summary + +Transformers.js provides flexible caching options: + +- **Browser**: Cache API (automatic, persistent) +- **Node.js**: Filesystem cache (default `./.cache`, configurable) +- **Custom**: Implement your own (database, cloud storage, etc.) + +**Key takeaways:** + +1. Caching is enabled by default and automatic +2. Configure cache **before** loading models +3. Browser uses Cache API, Node.js uses filesystem +4. Custom caches enable advanced storage backends +5. Monitor cache size and implement cleanup strategies +6. Pre-download models for production deployments + +For more configuration options, see: +- [Configuration Reference](./CONFIGURATION.md) +- [Pipeline Options](./PIPELINE_OPTIONS.md) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/CONFIGURATION.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/CONFIGURATION.md new file mode 100644 index 0000000000000000000000000000000000000000..52e18d9665852ad162b96d9b461720aec3e7714a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/CONFIGURATION.md @@ -0,0 +1,390 @@ +# Environment Configuration Reference + +Complete guide to configuring Transformers.js behavior using the `env` object. + +## Table of Contents + +1. [Overview](#overview) +2. [Remote Model Configuration](#remote-model-configuration) +3. [Local Model Configuration](#local-model-configuration) +4. [Cache Configuration](#cache-configuration) +5. [WASM Configuration](#wasm-configuration) +6. [Common Configuration Patterns](#common-configuration-patterns) +7. [Environment Best Practices](#environment-best-practices) + +## Overview + +The `env` object provides comprehensive control over Transformers.js execution, caching, and model loading: + +```javascript +import { env } from '@huggingface/transformers'; + +// View current version +console.log(env.version); // e.g., '3.8.1' +``` + +### Available Properties + +```typescript +interface TransformersEnvironment { + // Version info + version: string; + + // Backend configuration + backends: { + onnx: Partial; + }; + + // Remote model settings + allowRemoteModels: boolean; + remoteHost: string; + remotePathTemplate: string; + + // Local model settings + allowLocalModels: boolean; + localModelPath: string; + useFS: boolean; + + // Cache settings + useBrowserCache: boolean; + useFSCache: boolean; + cacheDir: string | null; + useCustomCache: boolean; + customCache: CacheInterface | null; + useWasmCache: boolean; + cacheKey: string; +} +``` + +## Remote Model Configuration + +Control how models are loaded from remote sources (default: Hugging Face Hub). + +### Disable Remote Loading + +```javascript +import { env } from '@huggingface/transformers'; + +// Force local-only mode (no network requests) +env.allowRemoteModels = false; +``` + +**Use case:** Offline applications, security requirements, or air-gapped environments. + +### Custom Model Host + +```javascript +import { env } from '@huggingface/transformers'; + +// Use your own CDN or model server +env.remoteHost = 'https://cdn.example.com/models'; + +// Customize the URL pattern +// Default: '{model}/resolve/{revision}/{file}' +env.remotePathTemplate = 'custom/{model}/{file}'; +``` + +**Use case:** Self-hosting models, using a CDN for faster downloads, or corporate proxies. + +### Example: Private Model Server + +```javascript +import { env, pipeline } from '@huggingface/transformers'; + +// Configure custom model host +env.remoteHost = 'https://models.mycompany.com'; +env.remotePathTemplate = '{model}/{file}'; + +// Models will be loaded from: +// https://models.mycompany.com/my-model/model.onnx +const pipe = await pipeline('sentiment-analysis', 'my-model'); +``` + +## Local Model Configuration + +Control loading models from the local file system. + +### Enable Local Models + +```javascript +import { env } from '@huggingface/transformers'; + +// Enable local file system loading +env.allowLocalModels = true; + +// Set the base path for local models +env.localModelPath = '/path/to/models/'; +``` + +**Default values:** +- Browser: `allowLocalModels = false`, `localModelPath = '/models/'` +- Node.js: `allowLocalModels = true`, `localModelPath = '/models/'` + +### File System Control + +```javascript +import { env } from '@huggingface/transformers'; + +// Disable file system usage entirely (Node.js only) +env.useFS = false; +``` + +### Example: Local Model Directory Structure + +``` +/app/models/ +├── onnx-community/ +│ ├── Supertonic-TTS-ONNX/ +│ │ ├── config.json +│ │ ├── tokenizer.json +│ │ ├── model.onnx +│ │ └── ... +│ └── yolo26l-pose-ONNX/ +│ ├── config.json +│ ├── preprocessor_config.json +│ ├── model.onnx +│ └── ... +``` + +```javascript +env.allowLocalModels = true; +env.localModelPath = '/app/models/'; +env.allowRemoteModels = false; // Offline mode + +const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english'); +``` + +## Cache Configuration + +Transformers.js supports multiple caching strategies to improve performance and reduce network usage. + +### Quick Configuration + +```javascript +import { env } from '@huggingface/transformers'; + +// Browser cache (Cache API) +env.useBrowserCache = true; // default: true +env.cacheKey = 'my-app-transformers-cache'; // default: 'transformers-cache' + +// Node.js filesystem cache +env.useFSCache = true; // default: true +env.cacheDir = './custom-cache-dir'; // default: './.cache' + +// Custom cache implementation +env.useCustomCache = true; +env.customCache = new CustomCache(); // Implement Cache API interface + +// WASM binary caching +env.useWasmCache = true; // default: true +``` + +### Disable Caching + +```javascript +import { env } from '@huggingface/transformers'; + +// Disable all caching (re-download on every load) +env.useFSCache = false; +env.useBrowserCache = false; +env.useWasmCache = false; +env.cacheDir = null; +``` + +For comprehensive caching documentation including: +- Browser Cache API details and storage limits +- Node.js filesystem cache structure and management +- Custom cache implementations (Redis, database, S3) +- Cache clearing and monitoring strategies +- Best practices and troubleshooting + +See **[Caching Reference](./CACHE.md)** + +## WASM Configuration + +Configure ONNX Runtime Web Assembly backend settings. + +### Basic WASM Settings + +```javascript +import { env } from '@huggingface/transformers'; + +// Set custom WASM paths +env.backends.onnx.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/'; + +// Configure number of threads (Node.js only) +env.backends.onnx.wasm.numThreads = 4; + +// Enable/disable SIMD (single instruction, multiple data) +env.backends.onnx.wasm.simd = true; +``` + +### Proxy Configuration + +```javascript +import { env } from '@huggingface/transformers'; + +// Configure proxy for WASM downloads +env.backends.onnx.wasm.proxy = true; +``` + +### Self-Hosted WASM Files + +```javascript +import { env } from '@huggingface/transformers'; + +// Host WASM files on your own server +env.backends.onnx.wasm.wasmPaths = '/static/wasm/'; +``` + +**Required files:** +- `ort-wasm.wasm` - Main WASM binary +- `ort-wasm-simd.wasm` - SIMD-enabled WASM binary +- `ort-wasm-threaded.wasm` - Multi-threaded WASM binary +- `ort-wasm-simd-threaded.wasm` - SIMD + multi-threaded WASM binary + +## Common Configuration Patterns + +### Development Setup + +```javascript +import { env } from '@huggingface/transformers'; + +// Fast iteration with caching +env.allowRemoteModels = true; +env.useBrowserCache = true; // Browser +env.useFSCache = true; // Node.js +env.cacheDir = './.cache'; +``` + +### Production (Local Models) + +```javascript +import { env } from '@huggingface/transformers'; + +// Secure, offline-capable setup +env.allowRemoteModels = false; +env.allowLocalModels = true; +env.localModelPath = '/app/models/'; +env.useFSCache = false; // Models already local +``` + +### Offline-First Application + +```javascript +import { env } from '@huggingface/transformers'; + +// Try local first, fall back to remote +env.allowLocalModels = true; +env.localModelPath = './models/'; +env.allowRemoteModels = true; +env.useFSCache = true; +env.cacheDir = './cache'; +``` + +### Custom CDN + +```javascript +import { env } from '@huggingface/transformers'; + +// Use your own model hosting +env.remoteHost = 'https://cdn.example.com/ml-models'; +env.remotePathTemplate = '{model}/{file}'; +env.useBrowserCache = true; +``` + +### Memory-Constrained Environment + +```javascript +import { env } from '@huggingface/transformers'; + +// Minimize disk/memory usage +env.useFSCache = false; +env.useBrowserCache = false; +env.useWasmCache = false; +env.cacheDir = null; +``` + +### Testing/CI Environment + +```javascript +import { env } from '@huggingface/transformers'; + +// Predictable, isolated testing +env.allowRemoteModels = false; +env.allowLocalModels = true; +env.localModelPath = './test-fixtures/models/'; +env.useFSCache = false; +``` + + + +## Environment Best Practices + +### 1. Configure Early + +Set `env` properties before loading any models: + +```javascript +import { env, pipeline } from '@huggingface/transformers'; + +// ✓ Good: Configure before loading +env.allowRemoteModels = false; +env.localModelPath = '/app/models/'; +const pipe = await pipeline('sentiment-analysis'); + +// ✗ Bad: Configuring after loading may not take effect +const pipe = await pipeline('sentiment-analysis'); +env.allowRemoteModels = false; // Too late! +``` + +### 2. Use Environment Variables + +```javascript +import { env } from '@huggingface/transformers'; + +// Configure based on environment +env.allowRemoteModels = process.env.NODE_ENV === 'development'; +env.cacheDir = process.env.MODEL_CACHE_DIR || './.cache'; +env.localModelPath = process.env.LOCAL_MODELS_PATH || '/app/models/'; +``` + +### 3. Handle Errors Gracefully + +```javascript +import { pipeline, env } from '@huggingface/transformers'; + +try { + env.allowRemoteModels = false; + const pipe = await pipeline('sentiment-analysis', 'my-model'); +} catch (error) { + if (error.message.includes('not found')) { + console.error('Model not found locally. Enable remote models or download the model.'); + } + throw error; +} +``` + +### 4. Log Configuration + +```javascript +import { env } from '@huggingface/transformers'; + +console.log('Transformers.js Configuration:', { + version: env.version, + allowRemoteModels: env.allowRemoteModels, + allowLocalModels: env.allowLocalModels, + localModelPath: env.localModelPath, + cacheDir: env.cacheDir, + useFSCache: env.useFSCache, + useBrowserCache: env.useBrowserCache +}); +``` + +## Related Documentation + +- **[Caching Reference](./CACHE.md)** - Comprehensive caching guide (browser, Node.js, custom implementations) +- [Pipeline Options](./PIPELINE_OPTIONS.md) - Configure pipeline loading with `progress_callback`, `device`, `dtype`, etc. +- [Model Architectures](./MODEL_ARCHITECTURES.md) - Supported models and architectures +- [Examples](./EXAMPLES.md) - Code examples for different runtimes +- [Main Skill Guide](../SKILL.md) - Getting started and common usage diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/EXAMPLES.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..6a6e9b74293c5460ae967cc491ee76f940e3c58a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/transformers.js/references/EXAMPLES.md @@ -0,0 +1,605 @@ +# Transformers.js Code Examples + +Working examples showing how to use Transformers.js across different runtimes and frameworks. + +All examples use the same task and model for consistency: +- **Task**: `feature-extraction` +- **Model**: `onnx-community/all-MiniLM-L6-v2-ONNX` + +## Table of Contents +1. [Browser (Vanilla JS)](#browser-vanilla-js) +2. [Node.js](#nodejs) +3. [React](#react) +4. [Express API](#express-api) + +## Browser (Vanilla JS) + +### Basic Usage + +```html + + + + Feature Extraction + + +

Text Embedding Generator

+ + +
+ + + + + +``` + +### With Progress Tracking + +```html + + + + Feature Extraction with Progress + + + +

Text Embedding Generator

+
+

Loading model...

+
+
+ + + + + +``` + +## Node.js + +### Basic Script + +```javascript +// embed.js +import { pipeline } from '@huggingface/transformers'; + +async function generateEmbedding(text) { + const extractor = await pipeline( + 'feature-extraction', + 'onnx-community/all-MiniLM-L6-v2-ONNX' + ); + + const output = await extractor(text, { pooling: 'mean', normalize: true }); + + console.log('Text:', text); + console.log('Embedding dimensions:', output.data.length); + console.log('First 5 values:', Array.from(output.data).slice(0, 5)); + + await extractor.dispose(); +} + +generateEmbedding('Hello, world!'); +``` + +### Batch Processing + +```javascript +// batch-embed.js +import { pipeline } from '@huggingface/transformers'; +import fs from 'fs/promises'; + +async function embedDocuments(documents) { + const extractor = await pipeline( + 'feature-extraction', + 'onnx-community/all-MiniLM-L6-v2-ONNX' + ); + + console.log(`Processing ${documents.length} documents...`); + + const embeddings = []; + + for (let i = 0; i < documents.length; i++) { + const output = await extractor(documents[i], { + pooling: 'mean', + normalize: true + }); + + embeddings.push({ + text: documents[i], + embedding: Array.from(output.data) + }); + + console.log(`Processed ${i + 1}/${documents.length}`); + } + + await fs.writeFile( + 'embeddings.json', + JSON.stringify(embeddings, null, 2) + ); + + console.log('Saved to embeddings.json'); + + await extractor.dispose(); +} + +const documents = [ + 'The cat sat on the mat', + 'A dog played in the park', + 'Machine learning is fascinating' +]; + +embedDocuments(documents); +``` + +### CLI with Progress + +```javascript +// cli-embed.js +import { pipeline } from '@huggingface/transformers'; + +async function main() { + const text = process.argv[2] || 'Hello, world!'; + + console.log('Loading model...'); + + const fileProgress = {}; + + const extractor = await pipeline( + 'feature-extraction', + 'onnx-community/all-MiniLM-L6-v2-ONNX', + { + progress_callback: (info) => { + if (info.status === 'progress') { + fileProgress[info.file] = info.progress; + + // Show all files progress + const progressLines = Object.entries(fileProgress) + .map(([file, progress]) => ` ${file}: ${progress.toFixed(1)}%`) + .join('\n'); + + process.stdout.write(`\r\x1b[K${progressLines}`); + } + + if (info.status === 'done') { + console.log(`\n✓ ${info.file} complete`); + } + + if (info.status === 'ready') { + console.log('\nModel ready!'); + } + } + } + ); + + console.log('Generating embedding...'); + const output = await extractor(text, { pooling: 'mean', normalize: true }); + + console.log(`\nText: "${text}"`); + console.log(`Dimensions: ${output.data.length}`); + console.log(`First 5 values: ${Array.from(output.data).slice(0, 5).join(', ')}`); + + await extractor.dispose(); +} + +main(); +``` + +## React + +### Basic Component + +```jsx +// EmbeddingGenerator.jsx +import { useState, useRef, useEffect } from 'react'; +import { pipeline } from '@huggingface/transformers'; + +export function EmbeddingGenerator() { + const extractorRef = useRef(null); + const [text, setText] = useState(''); + const [embedding, setEmbedding] = useState(null); + const [loading, setLoading] = useState(false); + + const generate = async () => { + if (!text) return; + + setLoading(true); + + // Load model on first generate + if (!extractorRef.current) { + extractorRef.current = await pipeline( + 'feature-extraction', + 'onnx-community/all-MiniLM-L6-v2-ONNX' + ); + } + + const output = await extractorRef.current(text, { + pooling: 'mean', + normalize: true + }); + setEmbedding(Array.from(output.data)); + setLoading(false); + }; + + // Cleanup on unmount + useEffect(() => { + return () => { + if (extractorRef.current) { + extractorRef.current.dispose(); + } + }; + }, []); + + return ( +
+

Text Embedding Generator

+ + + +
+ + + + +``` + +### React + +```jsx +import { useState, useRef, useEffect } from 'react'; +import { pipeline, TextStreamer } from '@huggingface/transformers'; + +function StreamingGenerator() { + const generatorRef = useRef(null); + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const handleGenerate = async (prompt) => { + if (!prompt) return; + + setLoading(true); + setOutput(''); + + // Load model on first generate + if (!generatorRef.current) { + generatorRef.current = await pipeline( + 'text-generation', + 'onnx-community/Qwen2.5-0.5B-Instruct', + { dtype: 'q4' } + ); + } + + const streamer = new TextStreamer(generatorRef.current.tokenizer, { + skip_prompt: true, + skip_special_tokens: true, + callback_function: (token) => { + setOutput((prev) => prev + token); + }, + }); + + await generatorRef.current(prompt, { + max_new_tokens: 200, + temperature: 0.7, + streamer, + }); + + setLoading(false); + }; + + // Cleanup on unmount + useEffect(() => { + return () => { + if (generatorRef.current) { + generatorRef.current.dispose(); + } + }; + }, []); + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Chat Format + +Use structured messages for conversations. Works with both basic generation and streaming (just add `streamer` parameter). + +### Single Turn + +```javascript +import { pipeline } from '@huggingface/transformers'; + +const generator = await pipeline( + 'text-generation', + 'onnx-community/Qwen2.5-0.5B-Instruct', + { dtype: 'q4' } +); + +const messages = [ + { role: 'system', content: 'You are a helpful assistant.' }, + { role: 'user', content: 'How do I create an async function?' } +]; + +const result = await generator(messages, { + max_new_tokens: 256, + temperature: 0.7, +}); + +console.log(result[0].generated_text); +``` + +### Multi-turn Conversation + +```javascript +const conversation = [ + { role: 'system', content: 'You are a helpful assistant.' }, + { role: 'user', content: 'What is JavaScript?' }, + { role: 'assistant', content: 'JavaScript is a programming language...' }, + { role: 'user', content: 'Can you show an example?' } +]; + +const result = await generator(conversation, { + max_new_tokens: 200, + temperature: 0.7, +}); + +// To add streaming, just pass a streamer: +// streamer: new TextStreamer(generator.tokenizer, {...}) +``` + +## Generation Parameters + +### Common Parameters + +```javascript +await generator(prompt, { + // Token limits + max_new_tokens: 512, // Maximum tokens to generate + min_new_tokens: 0, // Minimum tokens to generate + + // Sampling + temperature: 0.7, // Randomness (0.0-2.0) + top_k: 50, // Consider top K tokens + top_p: 0.95, // Nucleus sampling + do_sample: true, // Use random sampling (false = always pick most likely token) + + // Repetition control + repetition_penalty: 1.0, // Penalty for repeating (1.0 = no penalty) + no_repeat_ngram_size: 0, // Prevent repeating n-grams + + // Streaming + streamer: streamer, // TextStreamer instance +}); +``` + +### Parameter Effects + +**Temperature:** +- Low (0.1-0.5): More focused and deterministic +- Medium (0.6-0.9): Balanced creativity and coherence +- High (1.0-2.0): More creative and random + +```javascript +// Focused output +await generator(prompt, { temperature: 0.3, max_new_tokens: 100 }); + +// Creative output +await generator(prompt, { temperature: 1.2, max_new_tokens: 100 }); +``` + +**Sampling Methods:** + +```javascript +// Greedy (deterministic) +await generator(prompt, { + do_sample: false, + max_new_tokens: 100 +}); + +// Top-k sampling +await generator(prompt, { + top_k: 50, + temperature: 0.7, + max_new_tokens: 100 +}); + +// Top-p (nucleus) sampling +await generator(prompt, { + top_p: 0.95, + temperature: 0.7, + max_new_tokens: 100 +}); +``` + +## Model Selection + +Browse available text generation models on Hugging Face Hub: + +**https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending** + +### Selection Tips + +- **Small models (< 1B params)**: Fast, browser-friendly, use `dtype: 'q4'` +- **Medium models (1-3B params)**: Balanced quality/speed, use `dtype: 'q4'` or `fp16` +- **Large models (> 3B params)**: High quality, slower, best for Node.js with `dtype: 'fp16'` + +Check model cards for: +- Parameter count and model size +- Supported languages +- Benchmark scores +- License restrictions + +## Best Practices + +1. **Model Size**: Use quantized models (`q4`) for browsers, larger models (`fp16`) for servers +2. **Streaming**: Use streaming for better UX - shows progress and feels responsive +3. **Token Limits**: Set `max_new_tokens` to prevent runaway generation +4. **Temperature**: Tune based on use case (creative: 0.8-1.2, factual: 0.3-0.7) +5. **Memory**: Always call `dispose()` when done +6. **Caching**: Load model once, reuse for multiple requests + +## Related Documentation + +- [Pipeline Options](./PIPELINE_OPTIONS.md) - Configure pipeline loading +- [Configuration Reference](./CONFIGURATION.md) - Environment settings +- [Code Examples](./EXAMPLES.md) - More examples for different runtimes +- [Main Skill Guide](../SKILL.md) - Getting started guide diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..5a2c554b04218a9c411c184fd749ffb6eb0daabe --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/SKILL.md @@ -0,0 +1,593 @@ +--- +name: huggingface-vision-trainer +description: Trains and fine-tunes vision models for object detection (D-FINE, RT-DETR v2, DETR, YOLOS), image classification (timm models — MobileNetV3, MobileViT, ResNet, ViT/DINOv3 — plus any Transformers classifier), and SAM/SAM2 segmentation using Hugging Face Transformers on Hugging Face Jobs cloud GPUs. Covers COCO-format dataset preparation, Albumentations augmentation, mAP/mAR evaluation, accuracy metrics, SAM segmentation with bbox/point prompts, DiceCE loss, hardware selection, cost estimation, Trackio monitoring, and Hub persistence. Use when users mention training object detection, image classification, SAM, SAM2, segmentation, image matting, DETR, D-FINE, RT-DETR, ViT, timm, MobileNet, ResNet, bounding box models, or fine-tuning vision models on Hugging Face Jobs. +--- + +# Vision Model Training on Hugging Face Jobs + +Train object detection, image classification, and SAM/SAM2 segmentation models on managed cloud GPUs. No local GPU setup required—results are automatically saved to the Hugging Face Hub. + +## When to Use This Skill + +Use this skill when users want to: +- Fine-tune object detection models (D-FINE, RT-DETR v2, DETR, YOLOS) on cloud GPUs or local +- Fine-tune image classification models (timm: MobileNetV3, MobileViT, ResNet, ViT/DINOv3, or any Transformers classifier) on cloud GPUs or local +- Fine-tune SAM or SAM2 models for segmentation / image matting using bbox or point prompts +- Train bounding-box detectors on custom datasets +- Train image classifiers on custom datasets +- Train segmentation models on custom mask datasets with prompts +- Run vision training jobs on Hugging Face Jobs infrastructure +- Ensure trained vision models are permanently saved to the Hub + +## Related Skills + +- **`hugging-face-jobs`** — General HF Jobs infrastructure: token authentication, hardware flavors, timeout management, cost estimation, secrets, environment variables, scheduled jobs, and result persistence. **Refer to the Jobs skill for any non-training-specific Jobs questions** (e.g., "how do secrets work?", "what hardware is available?", "how do I pass tokens?"). +- **`hugging-face-model-trainer`** — TRL-based language model training (SFT, DPO, GRPO). Use that skill for text/language model fine-tuning. + +## Local Script Execution + +Helper scripts use PEP 723 inline dependencies. Run them with `uv run`: +```bash +uv run scripts/dataset_inspector.py --dataset username/dataset-name --split train +uv run scripts/estimate_cost.py --help +``` + +## Prerequisites Checklist + +Before starting any training job, verify: + +### Account & Authentication +- Hugging Face Account with [Pro](https://hf.co/pro), [Team](https://hf.co/enterprise), or [Enterprise](https://hf.co/enterprise) plan (Jobs require paid plan) +- Authenticated login: Check with `hf_whoami()` (tool) or `hf auth whoami` (terminal) +- Token has **write** permissions +- **MUST pass token in job secrets** — see directive #3 below for syntax (MCP tool vs Python API) + +### Dataset Requirements — Object Detection +- Dataset must exist on Hub +- Annotations must use the `objects` column with `bbox`, `category` (and optionally `area`) sub-fields +- Bboxes can be in **xywh (COCO)** or **xyxy (Pascal VOC)** format — auto-detected and converted +- Categories can be **integers or strings** — strings are auto-remapped to integer IDs +- `image_id` column is **optional** — generated automatically if missing +- **ALWAYS validate unknown datasets** before GPU training (see Dataset Validation section) + +### Dataset Requirements — Image Classification +- Dataset must exist on Hub +- Must have an **`image` column** (PIL images) and a **`label` column** (integer class IDs or strings) +- The label column can be `ClassLabel` type (with names) or plain integers/strings — strings are auto-remapped +- Common column names auto-detected: `label`, `labels`, `class`, `fine_label` +- **ALWAYS validate unknown datasets** before GPU training (see Dataset Validation section) + +### Dataset Requirements — SAM/SAM2 Segmentation +- Dataset must exist on Hub +- Must have an **`image` column** (PIL images) and a **`mask` column** (binary ground-truth segmentation mask) +- Must have a **prompt** — either: + - A **`prompt` column** with JSON containing `{"bbox": [x0,y0,x1,y1]}` or `{"point": [x,y]}` + - OR a dedicated **`bbox`** column with `[x0,y0,x1,y1]` values + - OR a dedicated **`point`** column with `[x,y]` or `[[x,y],...]` values +- Bboxes should be in **xyxy** format (absolute pixel coordinates) +- Example dataset: `merve/MicroMat-mini` (image matting with bbox prompts) +- **ALWAYS validate unknown datasets** before GPU training (see Dataset Validation section) + +### Critical Settings +- **Timeout must exceed expected training time** — Default 30min is TOO SHORT. See directive #6 for recommended values. +- **Hub push must be enabled** — `push_to_hub=True`, `hub_model_id="username/model-name"`, token in `secrets` + +## Dataset Validation + +**Validate dataset format BEFORE launching GPU training to prevent the #1 cause of training failures: format mismatches.** + +**ALWAYS validate for** unknown/custom datasets or any dataset you haven't trained with before. **Skip for** `cppe-5` (the default in the training script). + +### Running the Inspector + +**Option 1: Via HF Jobs (recommended — avoids local SSL/dependency issues):** +```python +hf_jobs("uv", { + "script": "path/to/dataset_inspector.py", + "script_args": ["--dataset", "username/dataset-name", "--split", "train"] +}) +``` + +**Option 2: Locally:** +```bash +uv run scripts/dataset_inspector.py --dataset username/dataset-name --split train +``` + +**Option 3: Via `HfApi().run_uv_job()` (if hf_jobs MCP unavailable):** +```python +from huggingface_hub import HfApi +api = HfApi() +api.run_uv_job( + script="scripts/dataset_inspector.py", + script_args=["--dataset", "username/dataset-name", "--split", "train"], + flavor="cpu-basic", + timeout=300, +) +``` + +### Reading Results + +- **`✓ READY`** — Dataset is compatible, use directly +- **`✗ NEEDS FORMATTING`** — Needs preprocessing (mapping code provided in output) + +## Automatic Bbox Preprocessing + +The object detection training script (`scripts/object_detection_training.py`) automatically handles bbox format detection (xyxy→xywh conversion), bbox sanitization, `image_id` generation, string category→integer remapping, and dataset truncation. **No manual preprocessing needed** — just ensure the dataset has `objects.bbox` and `objects.category` columns. + +## Training workflow + +Copy this checklist and track progress: + +``` +Training Progress: +- [ ] Step 1: Verify prerequisites (account, token, dataset) +- [ ] Step 2: Validate dataset format (run dataset_inspector.py) +- [ ] Step 3: Ask user about dataset size and validation split +- [ ] Step 4: Prepare training script (OD: scripts/object_detection_training.py, IC: scripts/image_classification_training.py, SAM: scripts/sam_segmentation_training.py) +- [ ] Step 5: Save script locally, submit job, and report details +``` + +**Step 1: Verify prerequisites** + +Follow the Prerequisites Checklist above. + +**Step 2: Validate dataset** + +Run the dataset inspector BEFORE spending GPU time. See "Dataset Validation" section above. + +**Step 3: Ask user preferences** + +ALWAYS use the AskUserQuestion tool with option-style format: + +```python +AskUserQuestion({ + "questions": [ + { + "question": "Do you want to run a quick test with a subset of the data first?", + "header": "Dataset Size", + "options": [ + {"label": "Quick test run (10% of data)", "description": "Faster, cheaper (~30-60 min, ~$2-5) to validate setup"}, + {"label": "Full dataset (Recommended)", "description": "Complete training for best model quality"} + ], + "multiSelect": false + }, + { + "question": "Do you want to create a validation split from the training data?", + "header": "Split data", + "options": [ + {"label": "Yes (Recommended)", "description": "Automatically split 15% of training data for validation"}, + {"label": "No", "description": "Use existing validation split from dataset"} + ], + "multiSelect": false + }, + { + "question": "Which GPU hardware do you want to use?", + "header": "Hardware Flavor", + "options": [ + {"label": "t4-small ($0.40/hr)", "description": "1x T4, 16 GB VRAM — sufficient for all OD models under 100M params"}, + {"label": "l4x1 ($0.80/hr)", "description": "1x L4, 24 GB VRAM — more headroom for large images or batch sizes"}, + {"label": "a10g-large ($1.50/hr)", "description": "1x A10G, 24 GB VRAM — faster training, more CPU/RAM"}, + {"label": "a100-large ($2.50/hr)", "description": "1x A100, 80 GB VRAM — fastest, for very large datasets or image sizes"} + ], + "multiSelect": false + } + ] +}) +``` + +**Step 4: Prepare training script** + +For object detection, use [scripts/object_detection_training.py](scripts/object_detection_training.py) as the production-ready template. For image classification, use [scripts/image_classification_training.py](scripts/image_classification_training.py). For SAM/SAM2 segmentation, use [scripts/sam_segmentation_training.py](scripts/sam_segmentation_training.py). All scripts use `HfArgumentParser` — all configuration is passed via CLI arguments in `script_args`, NOT by editing Python variables. For timm model details, see [references/timm_trainer.md](references/timm_trainer.md). For SAM2 training details, see [references/finetune_sam2_trainer.md](references/finetune_sam2_trainer.md). + +**Step 5: Save script, submit job, and report** + +1. **Save the script locally** to `submitted_jobs/` in the workspace root (create if needed) with a descriptive name like `training__.py`. Tell the user the path. +2. **Submit** using `hf_jobs` MCP tool (preferred) or `HfApi().run_uv_job()` — see directive #1 for both methods. Pass all config via `script_args`. +3. **Report** the job ID (from `.id` attribute), monitoring URL, Trackio dashboard (`https://huggingface.co/spaces/{username}/trackio`), expected time, and estimated cost. +4. **Wait for user** to request status checks — don't poll automatically. Training jobs run asynchronously and can take hours. + +## Critical directives + +These rules prevent common failures. Follow them exactly. + +### 1. Job submission: `hf_jobs` MCP tool vs Python API + +**`hf_jobs()` is an MCP tool, NOT a Python function.** Do NOT try to import it from `huggingface_hub`. Call it as a tool: + +``` +hf_jobs("uv", {"script": training_script_content, "flavor": "a10g-large", "timeout": "4h", "secrets": {"HF_TOKEN": "$HF_TOKEN"}}) +``` + +**If `hf_jobs` MCP tool is unavailable**, use the Python API directly: + +```python +from huggingface_hub import HfApi, get_token +api = HfApi() +job_info = api.run_uv_job( + script="path/to/training_script.py", # file PATH, NOT content + script_args=["--dataset_name", "cppe-5", ...], + flavor="a10g-large", + timeout=14400, # seconds (4 hours) + env={"PYTHONUNBUFFERED": "1"}, + secrets={"HF_TOKEN": get_token()}, # MUST use get_token(), NOT "$HF_TOKEN" +) +print(f"Job ID: {job_info.id}") +``` + +**Critical differences between the two methods:** + +| | `hf_jobs` MCP tool | `HfApi().run_uv_job()` | +|---|---|---| +| `script` param | Python code string or URL (NOT local paths) | File path to `.py` file (NOT content) | +| Token in secrets | `"$HF_TOKEN"` (auto-replaced) | `get_token()` (actual token value) | +| Timeout format | String (`"4h"`) | Seconds (`14400`) | + +**Rules for both methods:** +- The training script MUST include PEP 723 inline metadata with dependencies +- Do NOT use `image` or `command` parameters (those belong to `run_job()`, not `run_uv_job()`) + +### 2. Authentication via job secrets + explicit hub_token injection + +**Job config** MUST include the token in secrets — syntax depends on submission method (see table above). + +**Training script requirement:** The Transformers `Trainer` calls `create_repo(token=self.args.hub_token)` during `__init__()` when `push_to_hub=True`. The training script MUST inject `HF_TOKEN` into `training_args.hub_token` AFTER parsing args but BEFORE creating the `Trainer`. The template `scripts/object_detection_training.py` already includes this: + +```python +hf_token = os.environ.get("HF_TOKEN") +if training_args.push_to_hub and not training_args.hub_token: + if hf_token: + training_args.hub_token = hf_token +``` + +If you write a custom script, you MUST include this token injection before the `Trainer(...)` call. + +- Do NOT call `login()` in custom scripts unless replicating the full pattern from `scripts/object_detection_training.py` +- Do NOT rely on implicit token resolution (`hub_token=None`) — unreliable in Jobs +- See the `hugging-face-jobs` skill → *Token Usage Guide* for full details + +### 3. JobInfo attribute + +Access the job identifier using `.id` (NOT `.job_id` or `.name` — these don't exist): + +```python +job_info = api.run_uv_job(...) # or hf_jobs("uv", {...}) +job_id = job_info.id # Correct -- returns string like "687fb701029421ae5549d998" +``` + +### 4. Required training flags and HfArgumentParser boolean syntax + +`scripts/object_detection_training.py` uses `HfArgumentParser` — all config is passed via `script_args`. Boolean arguments have two syntaxes: + +- **`bool` fields** (e.g., `push_to_hub`, `do_train`): Use as bare flags (`--push_to_hub`) or negate with `--no_` prefix (`--no_remove_unused_columns`) +- **`Optional[bool]` fields** (e.g., `greater_is_better`): MUST pass explicit value (`--greater_is_better True`). Bare `--greater_is_better` causes `error: expected one argument` + +Required flags for object detection: + +``` +--no_remove_unused_columns # MUST: preserves image column for pixel_values +--no_eval_do_concat_batches # MUST: images have different numbers of target boxes +--push_to_hub # MUST: environment is ephemeral +--hub_model_id username/model-name +--metric_for_best_model eval_map +--greater_is_better True # MUST pass "True" explicitly (Optional[bool]) +--do_train +--do_eval +``` + +Required flags for image classification: + +``` +--no_remove_unused_columns # MUST: preserves image column for pixel_values +--push_to_hub # MUST: environment is ephemeral +--hub_model_id username/model-name +--metric_for_best_model eval_accuracy +--greater_is_better True # MUST pass "True" explicitly (Optional[bool]) +--do_train +--do_eval +``` + +Required flags for SAM/SAM2 segmentation: + +``` +--remove_unused_columns False # MUST: preserves input_boxes/input_points +--push_to_hub # MUST: environment is ephemeral +--hub_model_id username/model-name +--do_train +--prompt_type bbox # or "point" +--dataloader_pin_memory False # MUST: avoids pin_memory issues with custom collator +``` + +### 5. Timeout management + +Default 30 min is TOO SHORT for object detection. Set minimum 2-4 hours. Add 30% buffer for model loading, preprocessing, and Hub push. + +| Scenario | Timeout | +|----------|---------| +| Quick test (100-200 images, 5-10 epochs) | 1h | +| Development (500-1K images, 15-20 epochs) | 2-3h | +| Production (1K-5K images, 30 epochs) | 4-6h | +| Large dataset (5K+ images) | 6-12h | + +### 6. Trackio monitoring + +Trackio is **always enabled** in the object detection training script — it calls `trackio.init()` and `trackio.finish()` automatically. No need to pass `--report_to trackio`. The project name is taken from `--output_dir` and the run name from `--run_name`. For image classification, pass `--report_to trackio` in `TrainingArguments`. + +Dashboard at: `https://huggingface.co/spaces/{username}/trackio` + +## Model & hardware selection + +### Recommended object detection models + +| Model | Params | Use case | +|-------|--------|----------| +| `ustc-community/dfine-small-coco` | 10.4M | Best starting point — fast, cheap, SOTA quality | +| `PekingU/rtdetr_v2_r18vd` | 20.2M | Lightweight real-time detector | +| `ustc-community/dfine-large-coco` | 31.4M | Higher accuracy, still efficient | +| `PekingU/rtdetr_v2_r50vd` | 43M | Strong real-time baseline | +| `ustc-community/dfine-xlarge-obj365` | 63.5M | Best accuracy (pretrained on Objects365) | +| `PekingU/rtdetr_v2_r101vd` | 76M | Largest RT-DETR v2 variant | + +Start with `ustc-community/dfine-small-coco` for fast iteration. Move to D-FINE Large or RT-DETR v2 R50 for better accuracy. + +### Recommended image classification models + +All `timm/` models work out of the box via `AutoModelForImageClassification` (loaded as `TimmWrapperForImageClassification`). See [references/timm_trainer.md](references/timm_trainer.md) for details. + +| Model | Params | Use case | +|-------|--------|----------| +| `timm/mobilenetv3_small_100.lamb_in1k` | 2.5M | Ultra-lightweight — mobile/edge, fastest training | +| `timm/mobilevit_s.cvnets_in1k` | 5.6M | Mobile transformer — good accuracy/speed trade-off | +| `timm/resnet50.a1_in1k` | 25.6M | Strong CNN baseline — reliable, well-studied | +| `timm/vit_base_patch16_dinov3.lvd1689m` | 86.6M | Best accuracy — DINOv3 self-supervised ViT | + +Start with `timm/mobilenetv3_small_100.lamb_in1k` for fast iteration. Move to `timm/resnet50.a1_in1k` or `timm/vit_base_patch16_dinov3.lvd1689m` for better accuracy. + +### Recommended SAM/SAM2 segmentation models + +| Model | Params | Use case | +|-------|--------|----------| +| `facebook/sam2.1-hiera-tiny` | 38.9M | Fastest SAM2 — good for quick experiments | +| `facebook/sam2.1-hiera-small` | 46.0M | Best starting point — good quality/speed balance | +| `facebook/sam2.1-hiera-base-plus` | 80.8M | Higher capacity for complex segmentation | +| `facebook/sam2.1-hiera-large` | 224.4M | Best SAM2 accuracy — requires more VRAM | +| `facebook/sam-vit-base` | 93.7M | Original SAM — ViT-B backbone | +| `facebook/sam-vit-large` | 312.3M | Original SAM — ViT-L backbone | +| `facebook/sam-vit-huge` | 641.1M | Original SAM — ViT-H, best SAM v1 accuracy | + +Start with `facebook/sam2.1-hiera-small` for fast iteration. SAM2 models are generally more efficient than SAM v1 at similar quality. Only the mask decoder is trained by default (vision and prompt encoders are frozen). + +### Hardware recommendation + +All recommended OD and IC models are under 100M params — **`t4-small` (16 GB VRAM, $0.40/hr) is sufficient for all of them.** Image classification models are generally smaller and faster than object detection models — `t4-small` handles even ViT-Base comfortably. For SAM2 models up to `hiera-base-plus`, `t4-small` is sufficient since only the mask decoder is trained. For `sam2.1-hiera-large` or SAM v1 models, use `l4x1` or `a10g-large`. Only upgrade if you hit OOM from large batch sizes — reduce batch size first before switching hardware. Common upgrade path: `t4-small` → `l4x1` ($0.80/hr, 24 GB) → `a10g-large` ($1.50/hr, 24 GB). + +For full hardware flavor list: refer to the `hugging-face-jobs` skill. For cost estimation: run `scripts/estimate_cost.py`. + +## Quick start — Object Detection + +The `script_args` below are the same for both submission methods. See directive #1 for the critical differences between them. + +```python +OD_SCRIPT_ARGS = [ + "--model_name_or_path", "ustc-community/dfine-small-coco", + "--dataset_name", "cppe-5", + "--image_square_size", "640", + "--output_dir", "dfine_finetuned", + "--num_train_epochs", "30", + "--per_device_train_batch_size", "8", + "--learning_rate", "5e-5", + "--eval_strategy", "epoch", + "--save_strategy", "epoch", + "--save_total_limit", "2", + "--load_best_model_at_end", + "--metric_for_best_model", "eval_map", + "--greater_is_better", "True", + "--no_remove_unused_columns", + "--no_eval_do_concat_batches", + "--push_to_hub", + "--hub_model_id", "username/model-name", + "--do_train", + "--do_eval", +] +``` + +```python +from huggingface_hub import HfApi, get_token +api = HfApi() +job_info = api.run_uv_job( + script="scripts/object_detection_training.py", + script_args=OD_SCRIPT_ARGS, + flavor="t4-small", + timeout=14400, + env={"PYTHONUNBUFFERED": "1"}, + secrets={"HF_TOKEN": get_token()}, +) +print(f"Job ID: {job_info.id}") +``` + +### Key OD `script_args` + +- `--model_name_or_path` — recommended: `"ustc-community/dfine-small-coco"` (see model table above) +- `--dataset_name` — the Hub dataset ID +- `--image_square_size` — 480 (fast iteration) or 800 (better accuracy) +- `--hub_model_id` — `"username/model-name"` for Hub persistence +- `--num_train_epochs` — 30 typical for convergence +- `--train_val_split` — fraction to split for validation (default 0.15), set if dataset lacks a validation split +- `--max_train_samples` — truncate training set (useful for quick test runs, e.g. `"785"` for ~10% of a 7.8K dataset) +- `--max_eval_samples` — truncate evaluation set + +## Quick start — Image Classification + +```python +IC_SCRIPT_ARGS = [ + "--model_name_or_path", "timm/mobilenetv3_small_100.lamb_in1k", + "--dataset_name", "ethz/food101", + "--output_dir", "food101_classifier", + "--num_train_epochs", "5", + "--per_device_train_batch_size", "32", + "--per_device_eval_batch_size", "32", + "--learning_rate", "5e-5", + "--eval_strategy", "epoch", + "--save_strategy", "epoch", + "--save_total_limit", "2", + "--load_best_model_at_end", + "--metric_for_best_model", "eval_accuracy", + "--greater_is_better", "True", + "--no_remove_unused_columns", + "--push_to_hub", + "--hub_model_id", "username/food101-classifier", + "--do_train", + "--do_eval", +] +``` + +```python +from huggingface_hub import HfApi, get_token +api = HfApi() +job_info = api.run_uv_job( + script="scripts/image_classification_training.py", + script_args=IC_SCRIPT_ARGS, + flavor="t4-small", + timeout=7200, + env={"PYTHONUNBUFFERED": "1"}, + secrets={"HF_TOKEN": get_token()}, +) +print(f"Job ID: {job_info.id}") +``` + +### Key IC `script_args` + +- `--model_name_or_path` — any `timm/` model or Transformers classification model (see model table above) +- `--dataset_name` — the Hub dataset ID +- `--image_column_name` — column containing PIL images (default: `"image"`) +- `--label_column_name` — column containing class labels (default: `"label"`) +- `--hub_model_id` — `"username/model-name"` for Hub persistence +- `--num_train_epochs` — 3-5 typical for classification (fewer than OD) +- `--per_device_train_batch_size` — 16-64 (classification models use less memory than OD) +- `--train_val_split` — fraction to split for validation (default 0.15), set if dataset lacks a validation split +- `--max_train_samples` / `--max_eval_samples` — truncate for quick tests + +## Quick start — SAM/SAM2 Segmentation + +```python +SAM_SCRIPT_ARGS = [ + "--model_name_or_path", "facebook/sam2.1-hiera-small", + "--dataset_name", "merve/MicroMat-mini", + "--prompt_type", "bbox", + "--prompt_column_name", "prompt", + "--output_dir", "sam2-finetuned", + "--num_train_epochs", "30", + "--per_device_train_batch_size", "4", + "--learning_rate", "1e-5", + "--logging_steps", "1", + "--save_strategy", "epoch", + "--save_total_limit", "2", + "--remove_unused_columns", "False", + "--dataloader_pin_memory", "False", + "--push_to_hub", + "--hub_model_id", "username/sam2-finetuned", + "--do_train", + "--report_to", "trackio", +] +``` + +```python +from huggingface_hub import HfApi, get_token +api = HfApi() +job_info = api.run_uv_job( + script="scripts/sam_segmentation_training.py", + script_args=SAM_SCRIPT_ARGS, + flavor="t4-small", + timeout=7200, + env={"PYTHONUNBUFFERED": "1"}, + secrets={"HF_TOKEN": get_token()}, +) +print(f"Job ID: {job_info.id}") +``` + +### Key SAM `script_args` + +- `--model_name_or_path` — SAM or SAM2 model (see model table above); auto-detects SAM vs SAM2 +- `--dataset_name` — the Hub dataset ID (e.g., `"merve/MicroMat-mini"`) +- `--prompt_type` — `"bbox"` or `"point"` — type of prompt in the dataset +- `--prompt_column_name` — column with JSON-encoded prompts (default: `"prompt"`) +- `--bbox_column_name` — dedicated bbox column (alternative to JSON prompt column) +- `--point_column_name` — dedicated point column (alternative to JSON prompt column) +- `--mask_column_name` — column with ground-truth masks (default: `"mask"`) +- `--hub_model_id` — `"username/model-name"` for Hub persistence +- `--num_train_epochs` — 20-30 typical for SAM fine-tuning +- `--per_device_train_batch_size` — 2-4 (SAM models use significant memory) +- `--freeze_vision_encoder` / `--freeze_prompt_encoder` — freeze encoder weights (default: both frozen, only mask decoder trains) +- `--train_val_split` — fraction to split for validation (default 0.1) + +## Checking job status + +**MCP tool (if available):** +``` +hf_jobs("ps") # List all jobs +hf_jobs("logs", {"job_id": "your-job-id"}) # View logs +hf_jobs("inspect", {"job_id": "your-job-id"}) # Job details +``` + +**Python API fallback:** +```python +from huggingface_hub import HfApi +api = HfApi() +api.list_jobs() # List all jobs +api.get_job_logs(job_id="your-job-id") # View logs +api.get_job(job_id="your-job-id") # Job details +``` + +## Common failure modes + +### OOM (CUDA out of memory) +Reduce `per_device_train_batch_size` (try 4, then 2), reduce `IMAGE_SIZE`, or upgrade hardware. + +### Dataset format errors +Run `scripts/dataset_inspector.py` first. The training script auto-detects xyxy vs xywh, converts string categories to integer IDs, and adds `image_id` if missing. Ensure `objects.bbox` contains 4-value coordinate lists in absolute pixels and `objects.category` contains either integer IDs or string labels. + +### Hub push failures (401) +Verify: (1) job secrets include token (see directive #2), (2) script sets `training_args.hub_token` BEFORE creating the `Trainer`, (3) `push_to_hub=True` is set, (4) correct `hub_model_id`, (5) token has write permissions. + +### Job timeout +Increase timeout (see directive #5 table), reduce epochs/dataset, or use checkpoint strategy with `hub_strategy="every_save"`. + +### KeyError: 'test' (missing test split) +The object detection training script handles this gracefully — it falls back to the `validation` split. Ensure you're using the latest `scripts/object_detection_training.py`. + +### Single-class dataset: "iteration over a 0-d tensor" +`torchmetrics.MeanAveragePrecision` returns scalar (0-d) tensors for per-class metrics when there's only one class. The template `scripts/object_detection_training.py` handles this by calling `.unsqueeze(0)` on these tensors. Ensure you're using the latest template. + +### Poor detection performance (mAP < 0.15) +Increase epochs (30-50), ensure 500+ images, check per-class mAP for imbalanced classes, try different learning rates (1e-5 to 1e-4), increase image size. + +For comprehensive troubleshooting: see [references/reliability_principles.md](references/reliability_principles.md) + +## Reference files + +- [scripts/object_detection_training.py](scripts/object_detection_training.py) — Production-ready object detection training script +- [scripts/image_classification_training.py](scripts/image_classification_training.py) — Production-ready image classification training script (supports timm models) +- [scripts/sam_segmentation_training.py](scripts/sam_segmentation_training.py) — Production-ready SAM/SAM2 segmentation training script (bbox & point prompts) +- [scripts/dataset_inspector.py](scripts/dataset_inspector.py) — Validate dataset format for OD, classification, and SAM segmentation +- [scripts/estimate_cost.py](scripts/estimate_cost.py) — Estimate training costs for any vision model (includes SAM/SAM2) +- [references/object_detection_training_notebook.md](references/object_detection_training_notebook.md) — Object detection training workflow, augmentation strategies, and training patterns +- [references/image_classification_training_notebook.md](references/image_classification_training_notebook.md) — Image classification training workflow with ViT, preprocessing, and evaluation +- [references/finetune_sam2_trainer.md](references/finetune_sam2_trainer.md) — SAM2 fine-tuning walkthrough with MicroMat dataset, DiceCE loss, and Trainer integration +- [references/timm_trainer.md](references/timm_trainer.md) — Using timm models with HF Trainer (TimmWrapper, transforms, full example) +- [references/hub_saving.md](references/hub_saving.md) — Detailed Hub persistence guide and verification checklist +- [references/reliability_principles.md](references/reliability_principles.md) — Failure prevention principles from production experience + +## External links + +- [Transformers Object Detection Guide](https://huggingface.co/docs/transformers/tasks/object_detection) +- [Transformers Image Classification Guide](https://huggingface.co/docs/transformers/tasks/image_classification) +- [DETR Model Documentation](https://huggingface.co/docs/transformers/model_doc/detr) +- [ViT Model Documentation](https://huggingface.co/docs/transformers/model_doc/vit) +- [HF Jobs Guide](https://huggingface.co/docs/huggingface_hub/guides/jobs) — Main Jobs documentation +- [HF Jobs Configuration](https://huggingface.co/docs/hub/en/jobs-configuration) — Hardware, secrets, timeouts, namespaces +- [HF Jobs CLI Reference](https://huggingface.co/docs/huggingface_hub/guides/cli#hf-jobs) — Command line interface +- [Object Detection Models](https://huggingface.co/models?pipeline_tag=object-detection) +- [Image Classification Models](https://huggingface.co/models?pipeline_tag=image-classification) +- [SAM2 Model Documentation](https://huggingface.co/docs/transformers/model_doc/sam2) +- [SAM Model Documentation](https://huggingface.co/docs/transformers/model_doc/sam) +- [Object Detection Datasets](https://huggingface.co/datasets?task_categories=task_categories:object-detection) +- [Image Classification Datasets](https://huggingface.co/datasets?task_categories=task_categories:image-classification) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68536939166c3bdf3eaded94d2eca9102f7c7a7f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Vision Trainer" + short_description: "Train and fine-tune vision models on Hugging Face Jobs" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/finetune_sam2_trainer.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/finetune_sam2_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..1cff003682c7fff725dc6cde1be7402b10f0a081 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/finetune_sam2_trainer.md @@ -0,0 +1,254 @@ +# Fine-tuning SAM2 with HF Trainer + +Fine-tune SAM2.1 on a small part of the MicroMat dataset for image matting, +using the Hugging Face Trainer with a custom loss function. + +```python +!pip install -q transformers datasets monai trackio +``` + +## Load and explore the dataset + +```python +from datasets import load_dataset + +dataset = load_dataset("merve/MicroMat-mini", split="train") +dataset +``` + +```python +dataset = dataset.train_test_split(test_size=0.1) +train_ds = dataset["train"] +val_ds = dataset["test"] +``` + +```python +import json + +train_ds[0] +``` + +```python +json.loads(train_ds["prompt"][0])["bbox"] +``` + +## Visualize a sample + +```python +import matplotlib.pyplot as plt +import numpy as np + + +def show_mask(mask, ax, bbox): + color = np.array([0.12, 0.56, 1.0, 0.6]) + mask = np.array(mask) + h, w = mask.shape + mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, 4) + ax.imshow(mask_image) + x0, y0, x1, y1 = bbox + ax.add_patch( + plt.Rectangle( + (x0, y0), x1 - x0, y1 - y0, fill=False, edgecolor="lime", linewidth=2 + ) + ) + + +example = train_ds[0] +image = np.array(example["image"]) +ground_truth_mask = np.array(example["mask"]) + +fig, ax = plt.subplots() +ax.imshow(image) +show_mask(ground_truth_mask, ax, json.loads(example["prompt"])["bbox"]) +ax.set_title("Ground truth mask") +ax.set_axis_off() +plt.show() +``` + +## Build the dataset and collator + +`SAMDataset` wraps each sample into the format expected by the SAM2 processor. +Ground-truth masks are stored under the key `"labels"` so the Trainer +automatically pops them before calling `model.forward()`. + +```python +from torch.utils.data import Dataset +import torch +import torch.nn.functional as F + + +class SAMDataset(Dataset): + def __init__(self, dataset, processor): + self.dataset = dataset + self.processor = processor + + def __len__(self): + return len(self.dataset) + + def __getitem__(self, idx): + item = self.dataset[idx] + image = item["image"] + prompt = json.loads(item["prompt"])["bbox"] + inputs = self.processor(image, input_boxes=[[prompt]], return_tensors="pt") + inputs["labels"] = (np.array(item["mask"]) > 0).astype(np.float32) + inputs["original_image_size"] = torch.tensor(image.size[::-1]) + return inputs + + +def collate_fn(batch): + pixel_values = torch.cat([item["pixel_values"] for item in batch], dim=0) + original_sizes = torch.stack([item["original_sizes"] for item in batch]) + input_boxes = torch.cat([item["input_boxes"] for item in batch], dim=0) + labels = torch.cat( + [ + F.interpolate( + torch.as_tensor(x["labels"]).unsqueeze(0).unsqueeze(0).float(), + size=(256, 256), + mode="nearest", + ) + for x in batch + ], + dim=0, + ).long() + + return { + "pixel_values": pixel_values, + "original_sizes": original_sizes, + "input_boxes": input_boxes, + "labels": labels, + "original_image_size": torch.stack( + [item["original_image_size"] for item in batch] + ), + "multimask_output": False, + } +``` + +```python +from transformers import Sam2Processor + +processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-small") + +train_dataset = SAMDataset(dataset=train_ds, processor=processor) +val_dataset = SAMDataset(dataset=val_ds, processor=processor) +``` + +## Load model and freeze encoder layers + +```python +from transformers import Sam2Model + +model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-small") + +for name, param in model.named_parameters(): + if name.startswith("vision_encoder") or name.startswith("prompt_encoder"): + param.requires_grad_(False) +``` + +## Inference before training + +```python +item = val_ds[1] +img = item["image"] +bbox = json.loads(item["prompt"])["bbox"] +inputs = processor(images=img, input_boxes=[[bbox]], return_tensors="pt").to( + model.device +) + +with torch.no_grad(): + outputs = model(**inputs) + +masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0] +preds = masks.squeeze(0) +mask = (preds[0] > 0).cpu().numpy() + +overlay = np.asarray(img, dtype=np.uint8).copy() +overlay[mask] = 0.55 * overlay[mask] + 0.45 * np.array([0, 255, 0], dtype=np.float32) + +plt.imshow(overlay) +plt.title("Before training") +plt.axis("off") +plt.show() +``` + +## Define custom loss + +SAM2 does not compute loss in its `forward()`, so we provide a +`compute_loss_func` to the Trainer. The Trainer pops `"labels"` from the +batch before calling `model(**inputs)`, then passes `(outputs, labels)` to +this function. + +```python +import monai +from transformers import Trainer, TrainingArguments +import trackio + +seg_loss = monai.losses.DiceCELoss(sigmoid=True, squared_pred=True, reduction="mean") + + +def compute_loss(outputs, labels, num_items_in_batch=None): + predicted_masks = outputs.pred_masks.squeeze(1) + return seg_loss(predicted_masks, labels.float()) +``` + +## Train with Trainer + +Key settings: +- `remove_unused_columns=False`: the Trainer must keep `input_boxes`, + `original_sizes`, etc. that are not in the model's `forward()` signature. +- `compute_loss_func`: our custom DiceCE loss. +- `report_to="trackio"`: logs the training loss to trackio. + +```python +training_args = TrainingArguments( + output_dir="sam2-finetuned", + num_train_epochs=30, + per_device_train_batch_size=4, + learning_rate=1e-5, + weight_decay=0, + logging_steps=1, + save_strategy="epoch", + save_total_limit=2, + remove_unused_columns=False, + dataloader_pin_memory=False, + report_to="trackio", +) + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset, + data_collator=collate_fn, + compute_loss_func=compute_loss, +) + +trainer.train() +``` + +## Inference after training + +```python +item = val_ds[1] +img = item["image"] +bbox = json.loads(item["prompt"])["bbox"] + +inputs = processor(images=img, input_boxes=[[bbox]], return_tensors="pt").to( + model.device +) + +with torch.no_grad(): + outputs = model(**inputs) + +preds = processor.post_process_masks( + outputs.pred_masks.cpu(), inputs["original_sizes"] +)[0] +preds = preds.squeeze(0) +mask = (preds[0] > 0).cpu().numpy() + +overlay = np.asarray(img, dtype=np.uint8).copy() +overlay[mask] = 0.55 * overlay[mask] + 0.45 * np.array([0, 255, 0], dtype=np.float32) + +plt.imshow(overlay) +plt.title("After training") +plt.axis("off") +plt.show() +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/hub_saving.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/hub_saving.md new file mode 100644 index 0000000000000000000000000000000000000000..269a48b403e8c86cf665a098f448d6f390f5847f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/hub_saving.md @@ -0,0 +1,618 @@ +# Saving Vision Models to Hugging Face Hub + +## Contents +- Why Hub Push is Required +- Required Configuration (TrainingArguments, job config) +- Complete Example +- What Gets Saved +- Important: Save Image Processor +- Checkpoint Saving +- Model Card Configuration +- Saving Label Mappings +- Authentication Methods +- Verification Checklist +- Repository Setup (automatic/manual creation, naming) +- Troubleshooting (401, 403, push failures, inference issues) +- Manual Push After Training +- Example: Full Production Setup +- Inference Example + +--- + +**CRITICAL:** Training environments are ephemeral. ALL results are lost when a job completes unless pushed to the Hub. + +## Why Hub Push is Required + +When running on Hugging Face Jobs: +- Environment is temporary +- All files deleted on job completion +- No local disk persistence +- Cannot access results after job ends + +**Without Hub push, training is completely wasted.** + +## Required Configuration + +### 1. Training Configuration + +In your TrainingArguments: + +```python +from transformers import TrainingArguments + +training_args = TrainingArguments( + output_dir="my-object-detector", + push_to_hub=True, # Enable Hub push + hub_model_id="username/model-name", # Target repository +) +``` + +### 2. Job Configuration + +When submitting the job: + +```python +hf_jobs("uv", { + "script": training_script_content, # Pass the Python script content directly as a string + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # Provide authentication +}) +``` + +**The `$HF_TOKEN` syntax references your actual Hugging Face token value.** + +## Complete Example + +```python +# train_detector.py +# /// script +# dependencies = ["transformers", "torch", "torchvision", "datasets"] +# /// + +from transformers import ( + AutoImageProcessor, + AutoModelForObjectDetection, + TrainingArguments, + Trainer +) +from datasets import load_dataset +import os +import torch + +# Load dataset +dataset = load_dataset("cppe-5", split="train") + +# Load model and processor +model_name = "facebook/detr-resnet-50" +image_processor = AutoImageProcessor.from_pretrained(model_name) +model = AutoModelForObjectDetection.from_pretrained( + model_name, + num_labels=5, # Number of classes + ignore_mismatched_sizes=True +) + +# Configure with Hub push +training_args = TrainingArguments( + output_dir="my-detector", + num_train_epochs=10, + per_device_train_batch_size=8, + + # ✅ CRITICAL: Hub push configuration + push_to_hub=True, + hub_model_id="myusername/cppe5-detector", + + # Optional: Push strategy + hub_strategy="checkpoint", # Push checkpoints during training +) + +# ✅ CRITICAL: Authenticate with Hub BEFORE creating Trainer +from huggingface_hub import login +hf_token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob") +if hf_token: + login(token=hf_token) + training_args.hub_token = hf_token +elif training_args.push_to_hub: + raise ValueError("HF_TOKEN not found! Add secrets={'HF_TOKEN': '$HF_TOKEN'} to job config.") + +# Define collate function +def collate_fn(batch): + pixel_values = [item["pixel_values"] for item in batch] + labels = [item["labels"] for item in batch] + encoding = image_processor.pad(pixel_values, return_tensors="pt") + return { + "pixel_values": encoding["pixel_values"], + "labels": labels + } + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset, + data_collator=collate_fn, +) + +trainer.train() + +# ✅ Push final model and processor +trainer.push_to_hub() +image_processor.push_to_hub("myusername/cppe5-detector") + +print("✅ Model saved to: https://huggingface.co/myusername/cppe5-detector") +``` + +**Submit with authentication:** + +```python +hf_jobs("uv", { + "script": training_script_content, # Pass script content as a string, NOT a filename + "flavor": "a10g-large", + "timeout": "4h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Required! +}) +``` + +## What Gets Saved + +When `push_to_hub=True`: + +1. **Model weights** - Final trained parameters +2. **Image processor** - Associated preprocessing configuration +3. **Configuration** - Model config (config.json) including: + - Number of labels/classes + - Architecture details (backbone, num_queries, etc.) + - Label mappings (id2label, label2id) +4. **Training arguments** - Hyperparameters used +5. **Model card** - Auto-generated documentation +6. **Checkpoints** - If `save_strategy="steps"` enabled + +## Important: Save Image Processor + +**Object detection models require the image processor to be saved separately:** + +```python +# After training completes +trainer.push_to_hub() + +# ✅ Also push the image processor +image_processor.push_to_hub( + repo_id="username/model-name", + commit_message="Upload image processor" +) +``` + +**Why this matters:** +- Models need specific image preprocessing (resizing, normalization) +- Image processor contains critical configuration +- Without it, model cannot be used for inference + +## Checkpoint Saving + +Save intermediate checkpoints during training: + +```python +TrainingArguments( + output_dir="my-detector", + push_to_hub=True, + hub_model_id="username/my-detector", + + # Checkpoint configuration + save_strategy="steps", + save_steps=500, # Save every 500 steps + save_total_limit=3, # Keep only last 3 checkpoints + hub_strategy="checkpoint", # Push checkpoints to Hub +) +``` + +**Benefits:** +- Resume training if job fails +- Compare checkpoint performance +- Use intermediate models +- Track training progress + +**Checkpoints are pushed to:** `username/my-detector` (same repo) + +## Model Card Configuration + +Add metadata for better discoverability: + +```python +# At the end of training script +model.push_to_hub( + "username/my-detector", + commit_message="Upload trained object detection model", + tags=["object-detection", "vision", "cppe-5"], + model_card_kwargs={ + "license": "apache-2.0", + "dataset": "cppe-5", + "metrics": ["map", "recall", "precision"], + "pipeline_tag": "object-detection", + } +) +``` + +## Saving Label Mappings + +**Critical for object detection:** Save class labels with the model: + +```python +# Define your label mappings +id2label = {0: "Coverall", 1: "Face_Shield", 2: "Gloves", 3: "Goggles", 4: "Mask"} +label2id = {v: k for k, v in id2label.items()} + +# Update model config before training +model.config.id2label = id2label +model.config.label2id = label2id + +# Now train and push +trainer.train() +trainer.push_to_hub() +``` + +**Without label mappings:** +- Model outputs will be numeric IDs only +- No human-readable class names +- Difficult to interpret results + +## Authentication Methods + +For a complete guide on token types, `$HF_TOKEN` automatic replacement, `secrets` vs `env` differences, and security best practices, see the `hugging-face-jobs` skill → *Token Usage Guide*. + +**Recommended:** Always pass tokens via `secrets` (encrypted server-side): + +```python +"secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Automatic replacement with your logged-in token +``` + +## Verification Checklist + +Before submitting any training job, verify: + +- [ ] `push_to_hub=True` in TrainingArguments +- [ ] `hub_model_id` is specified (format: `username/model-name`) +- [ ] Image processor will be saved separately +- [ ] Label mappings (id2label, label2id) are configured +- [ ] Repository name doesn't conflict with existing repos +- [ ] You have write access to the target namespace + +## Repository Setup + +### Automatic Creation + +If repository doesn't exist, it's created automatically when first pushing. + +### Manual Creation + +Create repository before training: + +```python +from huggingface_hub import HfApi + +api = HfApi() +api.create_repo( + repo_id="username/detector-name", + repo_type="model", + private=False, # or True for private repo +) +``` + +### Repository Naming + +**Valid names:** +- `username/detr-cppe5` +- `username/yolos-object-detector` +- `organization/custom-detector` + +**Invalid names:** +- `detector-name` (missing username) +- `username/detector name` (spaces not allowed) +- `username/DETECTOR` (uppercase discouraged) + +**Recommended naming:** +- Include model architecture: `detr-`, `yolos-`, `deta-` +- Include dataset: `-cppe5`, `-coco`, `-voc` +- Be descriptive: `detr-resnet50-cppe5` > `model1` + +## Troubleshooting + +### Error: 401 Unauthorized + +**Cause:** HF_TOKEN not provided, invalid, or not authenticated before Trainer init + +**Solutions:** +1. Verify `secrets={"HF_TOKEN": "$HF_TOKEN"}` in job config +2. Verify script calls `login(token=hf_token)` AND sets `training_args.hub_token = hf_token` BEFORE creating the `Trainer` +3. Check you're logged in locally: `hf auth whoami` +4. Re-login: `hf auth login` + +**Root cause:** The `Trainer` calls `create_repo(token=self.args.hub_token)` during `__init__()` when `push_to_hub=True`. Relying on implicit env-var token resolution is unreliable in Jobs. Calling `login()` saves the token globally, and setting `training_args.hub_token` ensures the Trainer passes it explicitly to all Hub API calls. + +### Error: 403 Forbidden + +**Cause:** No write access to repository + +**Solutions:** +1. Check repository namespace matches your username +2. Verify you're a member of organization (if using org namespace) +3. Check repository isn't private (if accessing org repo) + +### Error: Repository not found + +**Cause:** Repository doesn't exist and auto-creation failed + +**Solutions:** +1. Manually create repository first +2. Check repository name format +3. Verify namespace exists + +### Error: Push failed during training + +**Cause:** Network issues or Hub unavailable + +**Solutions:** +1. Training continues but final push fails +2. Checkpoints may be saved +3. Re-run push manually after job completes + +### Issue: Model loads but inference fails + +**Possible causes:** +1. Image processor not saved—verify it's pushed separately +2. Label mappings missing—check config.json has id2label +3. Wrong image size—verify image processor matches training config + +### Issue: Model saved but not visible + +**Possible causes:** +1. Repository is private—check https://huggingface.co/username +2. Wrong namespace—verify `hub_model_id` matches login +3. Push still in progress—wait a few minutes + +## Manual Push After Training + +If training completes but push fails, push manually: + +```python +from transformers import AutoModelForObjectDetection, AutoImageProcessor + +# Load from local checkpoint +model = AutoModelForObjectDetection.from_pretrained("./output_dir") +image_processor = AutoImageProcessor.from_pretrained("./output_dir") + +# Push to Hub +model.push_to_hub("username/model-name", token="hf_abc123...") +image_processor.push_to_hub("username/model-name", token="hf_abc123...") +``` + +**Note:** Only possible if job hasn't completed (files still exist). + +## Best Practices + +1. **Always enable `push_to_hub=True`** +2. **Save image processor separately** - critical for inference +3. **Configure label mappings** before training +4. **Use checkpoint saving** for long training runs +5. **Verify Hub push** in logs before job completes +6. **Set appropriate `save_total_limit`** to avoid excessive checkpoints +7. **Use descriptive repo names** (e.g., `detr-cppe5` not `detector1`) +8. **Add model card** with: + - Training dataset + - Evaluation metrics (mAP, IoU) + - Example usage code + - Limitations +9. **Tag models appropriately**: + - `object-detection` + - Architecture: `detr`, `yolos`, `deta` + - Dataset: `coco`, `voc`, `cppe-5` + +## Monitoring Push Progress + +Check logs for push progress: + +```python +hf_jobs("logs", {"job_id": "your-job-id"}) +``` + +**Look for:** +``` +Pushing model to username/detector-name... +Upload file pytorch_model.bin: 100% +✅ Model pushed successfully +Pushing image processor... +✅ Image processor pushed successfully +``` + +## Example: Full Production Setup + +```python +# production_detector.py +# /// script +# dependencies = [ +# "transformers>=4.30.0", +# "torch>=2.0.0", +# "torchvision>=0.15.0", +# "datasets>=2.12.0", +# "evaluate>=0.4.0" +# ] +# /// + +from transformers import ( + AutoImageProcessor, + AutoModelForObjectDetection, + TrainingArguments, + Trainer +) +from datasets import load_dataset +import os +import torch + +# Configuration +MODEL_NAME = "facebook/detr-resnet-50" +DATASET_NAME = "cppe-5" +HUB_MODEL_ID = "myusername/detr-cppe5-detector" +NUM_CLASSES = 5 + +# Class labels +id2label = {0: "Coverall", 1: "Face_Shield", 2: "Gloves", 3: "Goggles", 4: "Mask"} +label2id = {v: k for k, v in id2label.items()} + +print(f"🔧 Loading dataset: {DATASET_NAME}") +dataset = load_dataset(DATASET_NAME, split="train") +print(f"✅ Dataset loaded: {len(dataset)} examples") + +print(f"🔧 Loading model: {MODEL_NAME}") +image_processor = AutoImageProcessor.from_pretrained(MODEL_NAME) +model = AutoModelForObjectDetection.from_pretrained( + MODEL_NAME, + num_labels=NUM_CLASSES, + id2label=id2label, + label2id=label2id, + ignore_mismatched_sizes=True +) +print("✅ Model loaded") + +# Configure with comprehensive Hub settings +training_args = TrainingArguments( + output_dir="detr-cppe5", + + # Hub configuration + push_to_hub=True, + hub_model_id=HUB_MODEL_ID, + hub_strategy="checkpoint", # Push checkpoints + + # Checkpoint configuration + save_strategy="steps", + save_steps=500, + save_total_limit=3, + + # Training settings + num_train_epochs=10, + per_device_train_batch_size=8, + gradient_accumulation_steps=2, + learning_rate=1e-4, + warmup_steps=500, + + # Evaluation + eval_strategy="steps", + eval_steps=500, + + # Logging + logging_steps=50, + logging_first_step=True, + + # Performance + fp16=True, # Mixed precision training + dataloader_num_workers=4, +) + +# ✅ CRITICAL: Authenticate with Hub BEFORE creating Trainer +# login() saves the token globally so ALL hub operations can find it. +from huggingface_hub import login +hf_token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob") +if hf_token: + login(token=hf_token) + training_args.hub_token = hf_token +elif training_args.push_to_hub: + raise ValueError("HF_TOKEN not found! Add secrets={'HF_TOKEN': '$HF_TOKEN'} to job config.") + +# Data collator +def collate_fn(batch): + pixel_values = [item["pixel_values"] for item in batch] + labels = [item["labels"] for item in batch] + encoding = image_processor.pad(pixel_values, return_tensors="pt") + return { + "pixel_values": encoding["pixel_values"], + "labels": labels + } + +# Create trainer +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset, + data_collator=collate_fn, +) + +print("🚀 Starting training...") +trainer.train() + +print("💾 Pushing final model to Hub...") +trainer.push_to_hub( + commit_message="Upload trained DETR model on CPPE-5", + tags=["object-detection", "detr", "cppe-5", "vision"], +) + +print("💾 Pushing image processor to Hub...") +image_processor.push_to_hub( + repo_id=HUB_MODEL_ID, + commit_message="Upload image processor" +) + +print("✅ Training complete!") +print(f"Model available at: https://huggingface.co/{HUB_MODEL_ID}") +print(f"\nTo use your model:") +print(f"```python") +print(f"from transformers import AutoImageProcessor, AutoModelForObjectDetection") +print(f"") +print(f"processor = AutoImageProcessor.from_pretrained('{HUB_MODEL_ID}')") +print(f"model = AutoModelForObjectDetection.from_pretrained('{HUB_MODEL_ID}')") +print(f"```") +``` + +**Submit:** + +```python +hf_jobs("uv", { + "script": training_script_content, # Pass script content as a string, NOT a filename + "flavor": "a10g-large", + "timeout": "8h", + "secrets": {"HF_TOKEN": "$HF_TOKEN"} +}) +``` + +## Inference Example + +After training, use your model: + +```python +from transformers import AutoImageProcessor, AutoModelForObjectDetection +from PIL import Image +import torch + +# Load model from Hub +processor = AutoImageProcessor.from_pretrained("username/detr-cppe5-detector") +model = AutoModelForObjectDetection.from_pretrained("username/detr-cppe5-detector") + +# Load and process image +image = Image.open("test_image.jpg") +inputs = processor(images=image, return_tensors="pt") + +# Run inference +with torch.no_grad(): + outputs = model(**inputs) + +# Post-process results +target_sizes = torch.tensor([image.size[::-1]]) +results = processor.post_process_object_detection( + outputs, + threshold=0.5, + target_sizes=target_sizes +)[0] + +# Print detections +for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): + box = [round(i, 2) for i in box.tolist()] + print( + f"Detected {model.config.id2label[label.item()]} with confidence " + f"{round(score.item(), 3)} at location {box}" + ) +``` + +## Key Takeaway + +**Without `push_to_hub=True` and `secrets={"HF_TOKEN": "$HF_TOKEN"}`, all training results are permanently lost.** + +**For object detection, also remember to:** +1. Save the image processor separately +2. Configure label mappings (id2label, label2id) +3. Include appropriate model card metadata + +Always verify all three are configured before submitting any training job. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/image_classification_training_notebook.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/image_classification_training_notebook.md new file mode 100644 index 0000000000000000000000000000000000000000..04a412802dda1498e5548abea563121aa3a82a32 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/image_classification_training_notebook.md @@ -0,0 +1,279 @@ +# Image classification + +## Contents +- Load Food-101 dataset +- Preprocess (ViT image processor, torchvision transforms) +- Evaluate (accuracy metric, compute_metrics) +- Train (TrainingArguments, Trainer setup, push to Hub) +- Inference (pipeline, manual prediction) + +--- + +Image classification assigns a label or class to an image. Unlike text or audio classification, the inputs are the +pixel values that comprise an image. There are many applications for image classification, such as detecting damage +after a natural disaster, monitoring crop health, or helping screen medical images for signs of disease. + +This guide illustrates how to: + +1. Fine-tune [ViT](../model_doc/vit) on the [Food-101](https://huggingface.co/datasets/ethz/food101) dataset to classify a food item in an image. +2. Use your fine-tuned model for inference. + +To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/image-classification) + +Before you begin, make sure you have all the necessary libraries installed: + +```bash +pip install transformers datasets evaluate accelerate pillow torchvision scikit-learn trackio +``` + +We encourage you to log in to your Hugging Face account to upload and share your model with the community. When prompted, enter your token to log in: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +## Load Food-101 dataset + +Start by loading a smaller subset of the Food-101 dataset from the 🤗 Datasets library. This will give you a chance to +experiment and make sure everything works before spending more time training on the full dataset. + +```py +>>> from datasets import load_dataset + +>>> food = load_dataset("ethz/food101", split="train[:5000]") +``` + +Split the dataset's `train` split into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/v4.5.0/en/package_reference/main_classes#datasets.Dataset.train_test_split) method: + +```py +>>> food = food.train_test_split(test_size=0.2) +``` + +Then take a look at an example: + +```py +>>> food["train"][0] +{'image': , + 'label': 79} +``` + +Each example in the dataset has two fields: + +- `image`: a PIL image of the food item +- `label`: the label class of the food item + +To make it easier for the model to get the label name from the label id, create a dictionary that maps the label name +to an integer and vice versa: + +```py +>>> labels = food["train"].features["label"].names +>>> label2id, id2label = dict(), dict() +>>> for i, label in enumerate(labels): +... label2id[label] = str(i) +... id2label[str(i)] = label +``` + +Now you can convert the label id to a label name: + +```py +>>> id2label[str(79)] +'prime_rib' +``` + +## Preprocess + +The next step is to load a ViT image processor to process the image into a tensor: + +```py +>>> from transformers import AutoImageProcessor + +>>> checkpoint = "google/vit-base-patch16-224-in21k" +>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint) +``` + +Apply some image transformations to the images to make the model more robust against overfitting. Here you'll use torchvision's [`transforms`](https://pytorch.org/vision/stable/transforms.html) module, but you can also use any image library you like. + +Crop a random part of the image, resize it, and normalize it with the image mean and standard deviation: + +```py +>>> from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor + +>>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std) +>>> size = ( +... image_processor.size["shortest_edge"] +... if "shortest_edge" in image_processor.size +... else (image_processor.size["height"], image_processor.size["width"]) +... ) +>>> _transforms = Compose([RandomResizedCrop(size), ToTensor(), normalize]) +``` + +Then create a preprocessing function to apply the transforms and return the `pixel_values` - the inputs to the model - of the image: + +```py +>>> def transforms(examples): +... examples["pixel_values"] = [_transforms(img.convert("RGB")) for img in examples["image"]] +... del examples["image"] +... return examples +``` + +To apply the preprocessing function over the entire dataset, use 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/v4.5.0/en/package_reference/main_classes#datasets.Dataset.with_transform) method. The transforms are applied on the fly when you load an element of the dataset: + +```py +>>> food = food.with_transform(transforms) +``` + +Now create a batch of examples using [DefaultDataCollator](/docs/transformers/v5.2.0/en/main_classes/data_collator#transformers.DefaultDataCollator). Unlike other data collators in 🤗 Transformers, the `DefaultDataCollator` does not apply additional preprocessing such as padding. + +```py +>>> from transformers import DefaultDataCollator + +>>> data_collator = DefaultDataCollator() +``` + +## Evaluate + +Including a metric during training is often helpful for evaluating your model's performance. You can quickly load an +evaluation method with the 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load +the [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) metric (see the 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric): + +```py +>>> import evaluate + +>>> accuracy = evaluate.load("accuracy") +``` + +Then create a function that passes your predictions and labels to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) to calculate the accuracy: + +```py +>>> import numpy as np + +>>> def compute_metrics(eval_pred): +... predictions, labels = eval_pred +... predictions = np.argmax(predictions, axis=1) +... return accuracy.compute(predictions=predictions, references=labels) +``` + +Your `compute_metrics` function is ready to go now, and you'll return to it when you set up your training. + +## Train + +If you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.2.0/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)! + +You're ready to start training your model now! Load ViT with [AutoModelForImageClassification](/docs/transformers/v5.2.0/en/model_doc/auto#transformers.AutoModelForImageClassification). Specify the number of labels along with the number of expected labels, and the label mappings: + +```py +>>> from transformers import AutoModelForImageClassification, TrainingArguments, Trainer + +>>> model = AutoModelForImageClassification.from_pretrained( +... checkpoint, +... num_labels=len(labels), +... id2label=id2label, +... label2id=label2id, +... ) +``` + +At this point, only three steps remain: + +1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.2.0/en/main_classes/trainer#transformers.TrainingArguments). It is important you don't remove unused columns because that'll drop the `image` column. Without the `image` column, you can't create `pixel_values`. Set `remove_unused_columns=False` to prevent this behavior! The only other required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.2.0/en/main_classes/trainer#transformers.Trainer) will evaluate the accuracy and save the training checkpoint. +2. Pass the training arguments to [Trainer](/docs/transformers/v5.2.0/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function. +3. Call [train()](/docs/transformers/v5.2.0/en/main_classes/trainer#transformers.Trainer.train) to finetune your model. + +```py +>>> training_args = TrainingArguments( +... output_dir="my_awesome_food_model", +... remove_unused_columns=False, +... eval_strategy="epoch", +... save_strategy="epoch", +... learning_rate=5e-5, +... per_device_train_batch_size=16, +... gradient_accumulation_steps=4, +... per_device_eval_batch_size=16, +... num_train_epochs=3, +... warmup_steps=0.1, +... logging_steps=10, +... report_to="trackio", +... run_name="food101", +... load_best_model_at_end=True, +... metric_for_best_model="accuracy", +... push_to_hub=True, +... ) + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... data_collator=data_collator, +... train_dataset=food["train"], +... eval_dataset=food["test"], +... processing_class=image_processor, +... compute_metrics=compute_metrics, +... ) + +>>> trainer.train() +``` + +Once training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.2.0/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model: + +```py +>>> trainer.push_to_hub() +``` + +For a more in-depth example of how to finetune a model for image classification, take a look at the corresponding [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). + +## Inference + +Great, now that you've fine-tuned a model, you can use it for inference! + +Load an image you'd like to run inference on: + +```py +>>> ds = load_dataset("ethz/food101", split="validation[:10]") +>>> image = ds["image"][0] +``` + + + +The simplest way to try out your finetuned model for inference is to use it in a [pipeline()](/docs/transformers/v5.2.0/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for image classification with your model, and pass your image to it: + +```py +>>> from transformers import pipeline + +>>> classifier = pipeline("image-classification", model="my_awesome_food_model") +>>> classifier(image) +[{'score': 0.31856709718704224, 'label': 'beignets'}, + {'score': 0.015232225880026817, 'label': 'bruschetta'}, + {'score': 0.01519392803311348, 'label': 'chicken_wings'}, + {'score': 0.013022331520915031, 'label': 'pork_chop'}, + {'score': 0.012728818692266941, 'label': 'prime_rib'}] +``` + +You can also manually replicate the results of the `pipeline` if you'd like: + +Load an image processor to preprocess the image and return the `input` as PyTorch tensors: + +```py +>>> from transformers import AutoImageProcessor +>>> import torch + +>>> image_processor = AutoImageProcessor.from_pretrained("my_awesome_food_model") +>>> inputs = image_processor(image, return_tensors="pt") +``` + +Pass your inputs to the model and return the logits: + +```py +>>> from transformers import AutoModelForImageClassification + +>>> model = AutoModelForImageClassification.from_pretrained("my_awesome_food_model") +>>> with torch.no_grad(): +... logits = model(**inputs).logits +``` + +Get the predicted label with the highest probability, and use the model's `id2label` mapping to convert it to a label: + +```py +>>> predicted_label = logits.argmax(-1).item() +>>> model.config.id2label[predicted_label] +'beignets' +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/object_detection_training_notebook.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/object_detection_training_notebook.md new file mode 100644 index 0000000000000000000000000000000000000000..8f506d07eef1d6b25787a07ecec9eb2805fc5d1c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/object_detection_training_notebook.md @@ -0,0 +1,700 @@ +# Object Detection Training Reference + +## Contents +- Load the CPPE-5 dataset +- Preprocess the data (augmentation with Albumentations, COCO annotation formatting) +- Preparing function to compute mAP +- Training the detection model (TrainingArguments, Trainer setup) +- Evaluate +- Inference (loading from Hub, running predictions, visualizing results) + +--- + +Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output +coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects, +each with its own bounding box and a label (e.g. it can have a car and a building), and each object can +be present in different parts of an image (e.g. the image can have several cars). +This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights. +Other applications include counting objects in images, image search, and more. + +In this guide, you will learn how to: + + 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional + backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5) + dataset. + 2. Use your finetuned model for inference. + +To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/object-detection) + +Before you begin, make sure you have all the necessary libraries installed: + +```bash +pip install -q datasets transformers accelerate timm trackio +pip install -q -U albumentations>=1.4.5 torchmetrics pycocotools +``` + +You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model, +and `albumentations` to augment the data. + +We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub. +When prompted, enter your token to log in: + +```py +>>> from huggingface_hub import notebook_login + +>>> notebook_login() +``` + +To get started, we'll define global constants, namely the model name and image size. For this tutorial, we'll use the conditional DETR model due to its faster convergence. Feel free to select any object detection model available in the `transformers` library. + +```py +>>> MODEL_NAME = "microsoft/conditional-detr-resnet-50" # or "facebook/detr-resnet-50" +>>> IMAGE_SIZE = 480 +``` + +## Load the CPPE-5 dataset + +The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with +annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic. + +Start by loading the dataset and creating a `validation` split from `train`: + +```py +>>> from datasets import load_dataset + +>>> cppe5 = load_dataset("cppe-5") + +>>> if "validation" not in cppe5: +... split = cppe5["train"].train_test_split(0.15, seed=1337) +... cppe5["train"] = split["train"] +... cppe5["validation"] = split["test"] + +>>> cppe5 +DatasetDict({ + train: Dataset({ + features: ['image_id', 'image', 'width', 'height', 'objects'], + num_rows: 850 + }) + test: Dataset({ + features: ['image_id', 'image', 'width', 'height', 'objects'], + num_rows: 29 + }) + validation: Dataset({ + features: ['image_id', 'image', 'width', 'height', 'objects'], + num_rows: 150 + }) +}) +``` + +You'll see that this dataset has 1000 images for train and validation sets and a test set with 29 images. + +To get familiar with the data, explore what the examples look like. + +```py +>>> cppe5["train"][0] +{ + 'image_id': 366, + 'image': , + 'width': 500, + 'height': 500, + 'objects': { + 'id': [1932, 1933, 1934], + 'area': [27063, 34200, 32431], + 'bbox': [[29.0, 11.0, 97.0, 279.0], + [201.0, 1.0, 120.0, 285.0], + [382.0, 0.0, 113.0, 287.0]], + 'category': [0, 0, 0] + } +} +``` + +The examples in the dataset have the following fields: + +- `image_id`: the example image id +- `image`: a `PIL.Image.Image` object containing the image +- `width`: width of the image +- `height`: height of the image +- `objects`: a dictionary containing bounding box metadata for the objects in the image: + - `id`: the annotation id + - `area`: the area of the bounding box + - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) ) + - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)` + +You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects. +However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will +need to apply some preprocessing transformations before using this data for training. + +To get an even better understanding of the data, visualize an example in the dataset. + +```py +>>> import numpy as np +>>> import os +>>> from PIL import Image, ImageDraw + +>>> image = cppe5["train"][2]["image"] +>>> annotations = cppe5["train"][2]["objects"] +>>> draw = ImageDraw.Draw(image) + +>>> categories = cppe5["train"].features["objects"]["category"].feature.names + +>>> id2label = {index: x for index, x in enumerate(categories, start=0)} +>>> label2id = {v: k for k, v in id2label.items()} + +>>> for i in range(len(annotations["id"])): +... box = annotations["bbox"][i] +... class_idx = annotations["category"][i] +... x, y, w, h = tuple(box) +... # Check if coordinates are normalized or not +... if max(box) > 1.0: +... # Coordinates are un-normalized, no need to re-scale them +... x1, y1 = int(x), int(y) +... x2, y2 = int(x + w), int(y + h) +... else: +... # Coordinates are normalized, re-scale them +... x1 = int(x * width) +... y1 = int(y * height) +... x2 = int((x + w) * width) +... y2 = int((y + h) * height) +... draw.rectangle((x, y, x + w, y + h), outline="red", width=1) +... draw.text((x, y), id2label[class_idx], fill="white") + +>>> image +``` + + + +To visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically +the `category` field. +You'll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`). +You can use them later when setting up the model. Including these maps will make your model reusable by others if you share +it on the Hugging Face Hub. Please note that, the part of above code that draws the bounding boxes assume that it is in `COCO` format `(x_min, y_min, width, height)`. It has to be adjusted to work for other formats like `(x_min, y_min, x_max, y_max)`. + +As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for +object detection is bounding boxes that "stretch" beyond the edge of the image. Such "runaway" bounding boxes can raise +errors during training and should be addressed. There are a few examples with this issue in this dataset. +To keep things simple in this guide, we will set `clip=True` for `BboxParams` in transformations below. + +## Preprocess the data + +To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model. +[AutoImageProcessor](/docs/transformers/v5.1.0/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and +`labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about: + +- `image_mean = [0.485, 0.456, 0.406 ]` +- `image_std = [0.229, 0.224, 0.225]` + +These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial +to replicate when doing inference or finetuning a pre-trained image model. + +Instantiate the image processor from the same checkpoint as the model you want to finetune. + +```py +>>> from transformers import AutoImageProcessor + +>>> MAX_SIZE = IMAGE_SIZE + +>>> image_processor = AutoImageProcessor.from_pretrained( +... MODEL_NAME, +... do_resize=True, +... size={"max_height": MAX_SIZE, "max_width": MAX_SIZE}, +... do_pad=True, +... pad_size={"height": MAX_SIZE, "width": MAX_SIZE}, +... ) +``` + +Before passing the images to the `image_processor`, apply two preprocessing transformations to the dataset: + +- Augmenting images +- Reformatting annotations to meet DETR expectations + +First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/). +This library ensures that transformations affect the image and update the bounding boxes accordingly. +The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection), +and it uses the exact same dataset as an example. Apply some geometric and color transformations to the image. For additional augmentation options, explore the [Albumentations Demo Space](https://huggingface.co/spaces/qubvel-hf/albumentations-demo). + +```py +>>> import albumentations as A + +>>> train_augment_and_transform = A.Compose( +... [ +... A.Perspective(p=0.1), +... A.HorizontalFlip(p=0.5), +... A.RandomBrightnessContrast(p=0.5), +... A.HueSaturationValue(p=0.1), +... ], +... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True, min_area=25), +... ) + +>>> validation_transform = A.Compose( +... [A.NoOp()], +... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True), +... ) +``` + +The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': list[Dict]}`, + where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example: + +```py +>>> def format_image_annotations_as_coco(image_id, categories, areas, bboxes): +... """Format one set of image annotations to the COCO format + +... Args: +... image_id (str): image id. e.g. "0001" +... categories (list[int]): list of categories/class labels corresponding to provided bounding boxes +... areas (list[float]): list of corresponding areas to provided bounding boxes +... bboxes (list[tuple[float]]): list of bounding boxes provided in COCO format +... ([center_x, center_y, width, height] in absolute coordinates) + +... Returns: +... dict: { +... "image_id": image id, +... "annotations": list of formatted annotations +... } +... """ +... annotations = [] +... for category, area, bbox in zip(categories, areas, bboxes): +... formatted_annotation = { +... "image_id": image_id, +... "category_id": category, +... "iscrowd": 0, +... "area": area, +... "bbox": list(bbox), +... } +... annotations.append(formatted_annotation) + +... return { +... "image_id": image_id, +... "annotations": annotations, +... } + +``` + +Now you can combine the image and annotation transformations to use on a batch of examples: + +```py +>>> def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False): +... """Apply augmentations and format annotations in COCO format for object detection task""" + +... images = [] +... annotations = [] +... for image_id, image, objects in zip(examples["image_id"], examples["image"], examples["objects"]): +... image = np.array(image.convert("RGB")) + +... # apply augmentations +... output = transform(image=image, bboxes=objects["bbox"], category=objects["category"]) +... images.append(output["image"]) + +... # format annotations in COCO format +... formatted_annotations = format_image_annotations_as_coco( +... image_id, output["category"], objects["area"], output["bboxes"] +... ) +... annotations.append(formatted_annotations) + +... # Apply the image processor transformations: resizing, rescaling, normalization +... result = image_processor(images=images, annotations=annotations, return_tensors="pt") + +... if not return_pixel_mask: +... result.pop("pixel_mask", None) + +... return result +``` + +Apply this preprocessing function to the entire dataset using 🤗 Datasets [with_transform](https://huggingface.co/docs/datasets/v4.5.0/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies +transformations on the fly when you load an element of the dataset. + +At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor +with `pixel_values`, a tensor with `pixel_mask`, and `labels`. + +```py +>>> from functools import partial + +>>> # Make transform functions for batch and apply for dataset splits +>>> train_transform_batch = partial( +... augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor +... ) +>>> validation_transform_batch = partial( +... augment_and_transform_batch, transform=validation_transform, image_processor=image_processor +... ) + +>>> cppe5["train"] = cppe5["train"].with_transform(train_transform_batch) +>>> cppe5["validation"] = cppe5["validation"].with_transform(validation_transform_batch) +>>> cppe5["test"] = cppe5["test"].with_transform(validation_transform_batch) + +>>> cppe5["train"][15] +{'pixel_values': tensor([[[ 1.9235, 1.9407, 1.9749, ..., -0.7822, -0.7479, -0.6965], + [ 1.9578, 1.9749, 1.9920, ..., -0.7993, -0.7650, -0.7308], + [ 2.0092, 2.0092, 2.0263, ..., -0.8507, -0.8164, -0.7822], + ..., + [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741], + [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741], + [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741]], + + [[ 1.6232, 1.6408, 1.6583, ..., 0.8704, 1.0105, 1.1331], + [ 1.6408, 1.6583, 1.6758, ..., 0.8529, 0.9930, 1.0980], + [ 1.6933, 1.6933, 1.7108, ..., 0.8179, 0.9580, 1.0630], + ..., + [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052], + [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052], + [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052]], + + [[ 1.8905, 1.9080, 1.9428, ..., -0.1487, -0.0964, -0.0615], + [ 1.9254, 1.9428, 1.9603, ..., -0.1661, -0.1138, -0.0790], + [ 1.9777, 1.9777, 1.9951, ..., -0.2010, -0.1138, -0.0790], + ..., + [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265], + [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265], + [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265]]]), + 'labels': {'image_id': tensor([688]), 'class_labels': tensor([3, 4, 2, 0, 0]), 'boxes': tensor([[0.4700, 0.1933, 0.1467, 0.0767], + [0.4858, 0.2600, 0.1150, 0.1000], + [0.4042, 0.4517, 0.1217, 0.1300], + [0.4242, 0.3217, 0.3617, 0.5567], + [0.6617, 0.4033, 0.5400, 0.4533]]), 'area': tensor([ 4048., 4140., 5694., 72478., 88128.]), 'iscrowd': tensor([0, 0, 0, 0, 0]), 'orig_size': tensor([480, 480])}} +``` + +You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't +complete yet. In the final step, create a custom `collate_fn` to batch images together. +Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask` +to indicate which pixels are real (1) and which are padding (0). + +```py +>>> import torch + +>>> def collate_fn(batch): +... data = {} +... data["pixel_values"] = torch.stack([x["pixel_values"] for x in batch]) +... data["labels"] = [x["labels"] for x in batch] +... if "pixel_mask" in batch[0]: +... data["pixel_mask"] = torch.stack([x["pixel_mask"] for x in batch]) +... return data + +``` + +## Preparing function to compute mAP + +Object detection models are commonly evaluated with a set of COCO-style metrics. We are going to use `torchmetrics` to compute `mAP` (mean average precision) and `mAR` (mean average recall) metrics and will wrap it to `compute_metrics` function in order to use in [Trainer](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer) for evaluation. + +Intermediate format of boxes used for training is `YOLO` (normalized) but we will compute metrics for boxes in `Pascal VOC` (absolute) format in order to correctly handle box areas. Let's define a function that converts bounding boxes to `Pascal VOC` format: + +```py +>>> from transformers.image_transforms import center_to_corners_format + +>>> def convert_bbox_yolo_to_pascal(boxes, image_size): +... """ +... Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1] +... to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates. + +... Args: +... boxes (torch.Tensor): Bounding boxes in YOLO format +... image_size (tuple[int, int]): Image size in format (height, width) + +... Returns: +... torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max) +... """ +... # convert center to corners format +... boxes = center_to_corners_format(boxes) + +... # convert to absolute coordinates +... height, width = image_size +... boxes = boxes * torch.tensor([[width, height, width, height]]) + +... return boxes +``` + +Then, in `compute_metrics` function we collect `predicted` and `target` bounding boxes, scores and labels from evaluation loop results and pass it to the scoring function. + +```py +>>> import numpy as np +>>> from dataclasses import dataclass +>>> from torchmetrics.detection.mean_ap import MeanAveragePrecision + +>>> @dataclass +>>> class ModelOutput: +... logits: torch.Tensor +... pred_boxes: torch.Tensor + +>>> @torch.no_grad() +>>> def compute_metrics(evaluation_results, image_processor, threshold=0.0, id2label=None): +... """ +... Compute mean average mAP, mAR and their variants for the object detection task. + +... Args: +... evaluation_results (EvalPrediction): Predictions and targets from evaluation. +... threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0. +... id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None. + +... Returns: +... Mapping[str, float]: Metrics in a form of dictionary {: } +... """ + +... predictions, targets = evaluation_results.predictions, evaluation_results.label_ids + +... # For metric computation we need to provide: +... # - targets in a form of list of dictionaries with keys "boxes", "labels" +... # - predictions in a form of list of dictionaries with keys "boxes", "scores", "labels" + +... image_sizes = [] +... post_processed_targets = [] +... post_processed_predictions = [] + +... # Collect targets in the required format for metric computation +... for batch in targets: +... # collect image sizes, we will need them for predictions post processing +... batch_image_sizes = torch.tensor(np.array([x["orig_size"] for x in batch])) +... image_sizes.append(batch_image_sizes) +... # collect targets in the required format for metric computation +... # boxes were converted to YOLO format needed for model training +... # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max) +... for image_target in batch: +... boxes = torch.tensor(image_target["boxes"]) +... boxes = convert_bbox_yolo_to_pascal(boxes, image_target["orig_size"]) +... labels = torch.tensor(image_target["class_labels"]) +... post_processed_targets.append({"boxes": boxes, "labels": labels}) + +... # Collect predictions in the required format for metric computation, +... # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format +... for batch, target_sizes in zip(predictions, image_sizes): +... batch_logits, batch_boxes = batch[1], batch[2] +... output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes)) +... post_processed_output = image_processor.post_process_object_detection( +... output, threshold=threshold, target_sizes=target_sizes +... ) +... post_processed_predictions.extend(post_processed_output) + +... # Compute metrics +... metric = MeanAveragePrecision(box_format="xyxy", class_metrics=True) +... metric.update(post_processed_predictions, post_processed_targets) +... metrics = metric.compute() + +... # Replace list of per class metrics with separate metric for each class +... classes = metrics.pop("classes") +... map_per_class = metrics.pop("map_per_class") +... mar_100_per_class = metrics.pop("mar_100_per_class") +... for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class): +... class_name = id2label[class_id.item()] if id2label is not None else class_id.item() +... metrics[f"map_{class_name}"] = class_map +... metrics[f"mar_100_{class_name}"] = class_mar + +... metrics = {k: round(v.item(), 4) for k, v in metrics.items()} + +... return metrics + +>>> eval_compute_metrics_fn = partial( +... compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0 +... ) +``` + +## Training the detection model + +You have done most of the heavy lifting in the previous sections, so now you are ready to train your model! +The images in this dataset are still quite large, even after resizing. This means that finetuning this model will +require at least one GPU. + +Training involves the following steps: + +1. Load the model with [AutoModelForObjectDetection](/docs/transformers/v5.1.0/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing. +2. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.TrainingArguments). +3. Pass the training arguments to [Trainer](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator. +4. Call [train()](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer.train) to finetune your model. + +When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id` +and `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one. + +```py +>>> from transformers import AutoModelForObjectDetection + +>>> model = AutoModelForObjectDetection.from_pretrained( +... MODEL_NAME, +... id2label=id2label, +... label2id=label2id, +... ignore_mismatched_sizes=True, +... ) +``` + +In the [TrainingArguments](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit. For `num_train_epochs=30` training will take about 35 minutes in Google Colab T4 GPU, increase the number of epoch to get better results. + +Important notes: + +- Set `remove_unused_columns` to `False`. +- Set `eval_do_concat_batches=False` to get proper evaluation results. Images have different number of target boxes, if batches are concatenated we will not be able to determine which boxes belongs to particular image. + +If you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging +Face to upload your model). + +```py +>>> from transformers import TrainingArguments + +>>> training_args = TrainingArguments( +... output_dir="detr_finetuned_cppe5", +... num_train_epochs=30, +... fp16=False, +... per_device_train_batch_size=8, +... dataloader_num_workers=4, +... learning_rate=5e-5, +... lr_scheduler_type="cosine", +... weight_decay=1e-4, +... max_grad_norm=0.01, +... metric_for_best_model="eval_map", +... greater_is_better=True, +... load_best_model_at_end=True, +... eval_strategy="epoch", +... save_strategy="epoch", +... save_total_limit=2, +... remove_unused_columns=False, +... report_to="trackio", +... run_name="cppe", +... eval_do_concat_batches=False, +... push_to_hub=True, +... ) +``` + +Finally, bring everything together, and call [train()](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer.train): + +```py +>>> from transformers import Trainer + +>>> trainer = Trainer( +... model=model, +... args=training_args, +... train_dataset=cppe5["train"], +... eval_dataset=cppe5["validation"], +... processing_class=image_processor, +... data_collator=collate_fn, +... compute_metrics=eval_compute_metrics_fn, +... ) + +>>> trainer.train() +``` + +Training runs for 30 epochs (~26 minutes on a T4 GPU for CPPE-5). Final epoch 30 results: + +| Metric | Value | +|--------|-------| +| Training Loss | 0.994 | +| Validation Loss | 1.346 | +| mAP | 0.277 | +| mAP@50 | 0.555 | +| mAP@75 | 0.253 | +| mAR@100 | 0.443 | + +Per-class mAP at epoch 30: Coverall 0.530, Face Shield 0.276, Gloves 0.175, Goggles 0.157, Mask 0.249. + +Key observations: +- mAP improves rapidly in early epochs (0.009 at epoch 1 → 0.18 by epoch 10), then gradually converges +- Large objects are detected better (mAP_large=0.524) than small objects (mAP_small=0.148) +- Class imbalance visible: Coverall highest mAP (0.530), Goggles lowest (0.157) + + + + +If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the +Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.Trainer.push_to_hub) method. + +```py +>>> trainer.push_to_hub() +``` + +## Evaluate + +```py +>>> from pprint import pprint + +>>> metrics = trainer.evaluate(eval_dataset=cppe5["test"], metric_key_prefix="test") +>>> pprint(metrics) +{'epoch': 30.0, + 'test_loss': 1.0877351760864258, + 'test_map': 0.4116, + 'test_map_50': 0.741, + 'test_map_75': 0.3663, + 'test_map_Coverall': 0.5937, + 'test_map_Face_Shield': 0.5863, + 'test_map_Gloves': 0.3416, + 'test_map_Goggles': 0.1468, + 'test_map_Mask': 0.3894, + 'test_map_large': 0.5637, + 'test_map_medium': 0.3257, + 'test_map_small': 0.3589, + 'test_mar_1': 0.323, + 'test_mar_10': 0.5237, + 'test_mar_100': 0.5587, + 'test_mar_100_Coverall': 0.6756, + 'test_mar_100_Face_Shield': 0.7294, + 'test_mar_100_Gloves': 0.4721, + 'test_mar_100_Goggles': 0.4125, + 'test_mar_100_Mask': 0.5038, + 'test_mar_large': 0.7283, + 'test_mar_medium': 0.4901, + 'test_mar_small': 0.4469, + 'test_runtime': 1.6526, + 'test_samples_per_second': 17.548, + 'test_steps_per_second': 2.42} +``` + +These results can be further improved by adjusting the hyperparameters in [TrainingArguments](/docs/transformers/v5.1.0/en/main_classes/trainer#transformers.TrainingArguments). Give it a go! + +## Inference + +Now that you have finetuned a model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference. + +```py +>>> import torch +>>> import requests + +>>> from PIL import Image, ImageDraw +>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection + +>>> url = "https://images.pexels.com/photos/8413299/pexels-photo-8413299.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2" +>>> image = Image.open(requests.get(url, stream=True).raw) +``` + +Load model and image processor from the Hugging Face Hub (skip to use already trained in this session): + +```py +>>> from accelerate import Accelerator + +>>> device = Accelerator().device +>>> model_repo = "qubvel-hf/detr_finetuned_cppe5" + +>>> image_processor = AutoImageProcessor.from_pretrained(model_repo) +>>> model = AutoModelForObjectDetection.from_pretrained(model_repo) +>>> model = model.to(device) +``` + +And detect bounding boxes: + +```py + +>>> with torch.no_grad(): +... inputs = image_processor(images=[image], return_tensors="pt") +... outputs = model(**inputs.to(device)) +... target_sizes = torch.tensor([[image.size[1], image.size[0]]]) +... results = image_processor.post_process_object_detection(outputs, threshold=0.3, target_sizes=target_sizes)[0] + +>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): +... box = [round(i, 2) for i in box.tolist()] +... print( +... f"Detected {model.config.id2label[label.item()]} with confidence " +... f"{round(score.item(), 3)} at location {box}" +... ) +Detected Gloves with confidence 0.683 at location [244.58, 124.33, 300.35, 185.13] +Detected Mask with confidence 0.517 at location [143.73, 64.58, 219.57, 125.89] +Detected Gloves with confidence 0.425 at location [179.15, 155.57, 262.4, 226.35] +Detected Coverall with confidence 0.407 at location [307.13, -1.18, 477.82, 318.06] +Detected Coverall with confidence 0.391 at location [68.61, 126.66, 309.03, 318.89] +``` + +Let's plot the result: + +```py +>>> draw = ImageDraw.Draw(image) + +>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): +... box = [round(i, 2) for i in box.tolist()] +... x, y, x2, y2 = tuple(box) +... draw.rectangle((x, y, x2, y2), outline="red", width=1) +... draw.text((x, y), model.config.id2label[label.item()], fill="white") + +>>> image +``` + + + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/reliability_principles.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/reliability_principles.md new file mode 100644 index 0000000000000000000000000000000000000000..223d4b6d8e77a8e02b13e5a85eb272b5b7f9ddf1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/reliability_principles.md @@ -0,0 +1,310 @@ +# Reliability Principles for Training Jobs + +## Contents +- Principle 1: Always Verify Before Use +- Principle 2: Prioritize Reliability Over Performance +- Principle 3: Create Atomic, Self-Contained Scripts +- Principle 4: Provide Clear Error Context +- Principle 5: Test the Happy Path on Known-Good Inputs +- Summary: The Reliability Checklist (pre-flight, script quality, job config) +- When Principles Conflict + +--- + +These principles are derived from real production failures and successful fixes. Following them prevents common failure modes and ensures reliable job execution. + +## Principle 1: Always Verify Before Use + +**Rule:** Never assume repos, datasets, or resources exist. Verify with tools first. + +### What It Prevents + +- **Non-existent datasets** - Jobs fail immediately when dataset doesn't exist +- **Typos in names** - Simple mistakes like "argilla-dpo-mix-7k" vs "ultrafeedback_binarized" +- **Incorrect paths** - Old or moved repos, renamed files +- **Missing dependencies** - Undocumented requirements + +### How to Apply + +**Before submitting ANY job:** + +```python +# Verify dataset exists +dataset_search({"query": "dataset-name", "author": "author-name", "limit": 5}) +hub_repo_details(["author/dataset-name"], repo_type="dataset") + +# Verify model exists +hub_repo_details(["org/model-name"], repo_type="model") + +# Check script/file paths (for URL-based scripts) +# Verify before using: https://github.com/user/repo/blob/main/script.py +``` + +**Examples that would have caught errors:** + +```python +# ❌ WRONG: Assumed dataset exists +hf_jobs("uv", { + "script": """...""", + "env": {"DATASET": "trl-lib/argilla-dpo-mix-7k"} # Doesn't exist! +}) + +# ✅ CORRECT: Verify first +dataset_search({"query": "argilla dpo", "author": "trl-lib"}) +# Would show: "trl-lib/ultrafeedback_binarized" is the correct name + +hub_repo_details(["trl-lib/ultrafeedback_binarized"], repo_type="dataset") +# Confirms it exists before using +``` + +### Implementation Checklist + +- [ ] Check dataset exists before training +- [ ] Test script URLs are valid before submitting +- [ ] Check for recent updates/renames of resources +- [ ] Check for dataset format + +**Time cost:** 5-10 seconds +**Time saved:** Hours of failed job time + debugging + +--- + +## Principle 2: Prioritize Reliability Over Performance + +**Rule:** Default to what is most likely to succeed, not what is theoretically fastest. + +### What It Prevents + +- **Hardware incompatibilities** - Features that fail on certain GPUs +- **Unstable optimizations** - Speed-ups that cause crashes +- **Complex configurations** - More failure points +- **Build system issues** - Unreliable compilation methods + +### How to Apply + +**Choose reliability:** + +```python +# ❌ RISKY: Aggressive optimization that may fail +TrainingArguments( + torch_compile=True, # Can fail on T4, A10G GPUs + optim="adamw_bnb_8bit", # Requires specific setup + dataloader_num_workers=8, # May cause OOM on small instances + ... +) + +# ✅ SAFE: Proven defaults +TrainingArguments( + # torch_compile=True, # Commented with note: "Enable on H100 for 20% speedup" + optim="adamw_torch", # Standard, always works + fp16=True, # Stable and fast on T4/A10G + dataloader_num_workers=4, # Conservative, reliable + ... +) +``` + +### Real-World Example + +**The `torch.compile` failure:** +- Added for "20% speedup" on H100 +- **Failed fatally on T4-medium** with cryptic error +- Misdiagnosed as dataset issue (cost hours) +- **Fix:** Disable by default, add as optional comment + +**Result:** Reliability > 20% performance gain + +### Implementation Checklist + +- [ ] Use proven, standard configurations by default +- [ ] Comment out performance optimizations with hardware notes +- [ ] Use stable build systems (CMake > make) +- [ ] Test on target hardware before production +- [ ] Document known incompatibilities +- [ ] Provide "safe" and "fast" variants when needed + +**Performance loss:** 10-20% in best case +**Reliability gain:** 95%+ success rate vs 60-70% + +--- + +## Principle 3: Create Atomic, Self-Contained Scripts + +**Rule:** Scripts should work as complete, independent units. Don't remove parts to "simplify." + +### What It Prevents + +- **Missing dependencies** - Removed "unnecessary" packages that are actually required +- **Incomplete processes** - Skipped steps that seem redundant +- **Environment assumptions** - Scripts that need pre-setup +- **Partial failures** - Some parts work, others fail silently + +### How to Apply + +**Complete dependency specifications:** + +```python +# ❌ INCOMPLETE: "Simplified" by removing dependencies +# /// script +# dependencies = [ +# "transformers", +# "torch", +# "datasets", +# ] +# /// + +# ✅ COMPLETE: All dependencies explicit +# /// script +# dependencies = [ +# "transformers>=5.2.0", +# "accelerate>=1.1.0", +# "albumentations>=1.4.16", # Required for augmentation + bbox handling +# "timm", # Required for vision backbones +# "datasets>=4.0", +# "torchmetrics", # Required for mAP/mAR computation +# "pycocotools", # Required for COCO evaluation +# "trackio", # Required for metrics monitoring +# "huggingface_hub", +# ] +# /// +``` + +### Real-World Example + +**The `albumentations` failure:** +- Original script had it: augmentations and bbox clipping worked fine +- "Simplified" version removed it: "not strictly needed for training" +- **Training crashed on bbox augmentation** — no fallback for COCO-format bbox handling +- Hard to debug: error appeared in data loading, not in augmentation setup +- **Fix:** Restore all original dependencies + +**Result:** Don't remove dependencies without thorough testing + +### Implementation Checklist + +- [ ] All dependencies in PEP 723 header with version pins +- [ ] All system packages installed by script +- [ ] No assumptions about pre-existing environment +- [ ] No "optional" steps that are actually required +- [ ] Test scripts in clean environment +- [ ] Document why each dependency is needed + +**Complexity:** Slightly longer scripts +**Reliability:** Scripts "just work" every time + +--- + +## Principle 4: Provide Clear Error Context + +**Rule:** When things fail, make it obvious what went wrong and how to fix it. + +### How to Apply + +**Wrap subprocess calls:** + +```python +# ❌ UNCLEAR: Silent failure +subprocess.run([...], check=True, capture_output=True) + +# ✅ CLEAR: Shows what failed +try: + result = subprocess.run( + [...], + check=True, + capture_output=True, + text=True + ) + print(result.stdout) + if result.stderr: + print("Warnings:", result.stderr) +except subprocess.CalledProcessError as e: + print(f"❌ Command failed!") + print("STDOUT:", e.stdout) + print("STDERR:", e.stderr) + raise +``` + +**Validate inputs:** + +```python +# ❌ UNCLEAR: Fails later with cryptic error +model = load_model(MODEL_NAME) + +# ✅ CLEAR: Fails fast with clear message +if not MODEL_NAME: + raise ValueError("MODEL_NAME environment variable not set!") + +print(f"Loading model: {MODEL_NAME}") +try: + model = load_model(MODEL_NAME) + print(f"✅ Model loaded successfully") +except Exception as e: + print(f"❌ Failed to load model: {MODEL_NAME}") + print(f"Error: {e}") + print("Hint: Check that model exists on Hub") + raise +``` + +### Implementation Checklist + +- [ ] Wrap external calls with try/except +- [ ] Print stdout/stderr on failure +- [ ] Validate environment variables early +- [ ] Add progress indicators (✅, ❌, 🔄) +- [ ] Include hints for common failures +- [ ] Log configuration at start + +--- + +## Principle 5: Test the Happy Path on Known-Good Inputs + +**Rule:** Before using new code in production, test with inputs you know work. + +## Summary: The Reliability Checklist + +Before submitting ANY job: + +### Pre-Flight Checks +- [ ] **Verified** all repos/datasets exist (hub_repo_details) +- [ ] **Tested** with known-good inputs if new code +- [ ] **Using** proven hardware/configuration +- [ ] **Included** all dependencies in PEP 723 header +- [ ] **Installed** system requirements (build tools, etc.) +- [ ] **Set** appropriate timeout (not default 30m) +- [ ] **Configured** Hub push with HF_TOKEN (login() + hub_token) +- [ ] **Added** clear error handling + +### Script Quality +- [ ] Self-contained (no external setup needed) +- [ ] Complete dependencies listed +- [ ] Build tools installed by script +- [ ] Progress indicators included +- [ ] Error messages are clear +- [ ] Configuration logged at start + +### Job Configuration +- [ ] Timeout > expected runtime + 30% buffer +- [ ] Hardware appropriate for model size +- [ ] Secrets include HF_TOKEN (see SKILL.md directive #2 for syntax) +- [ ] Script calls `login(token=hf_token)` and sets `training_args.hub_token = hf_token` BEFORE `Trainer()` init +- [ ] Environment variables set correctly +- [ ] Cost estimated and acceptable + +**Following these principles transforms job success rate from ~60-70% to ~95%+** + +--- + +## When Principles Conflict + +Sometimes reliability and performance conflict. Here's how to choose: + +| Scenario | Choose | Rationale | +|----------|--------|-----------| +| Demo/test | Reliability | Fast failure is worse than slow success | +| Production (first run) | Reliability | Prove it works before optimizing | +| Production (proven) | Performance | Safe to optimize after validation | +| Time-critical | Reliability | Failures cause more delay than slow runs | +| Cost-critical | Balanced | Test with small model, then optimize | + +**General rule:** Reliability first, optimize second. + +--- diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/timm_trainer.md b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/timm_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..046afc42b972e8dfe9ef193ee8dd3c80e08a46fa --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/references/timm_trainer.md @@ -0,0 +1,91 @@ +# Using timm models with Hugging Face Trainer + +Transformers has first-class support for timm models via the `TimmWrapper` classes. You can load any timm model and use it directly with the `Trainer` API for image classification. Here's how it works: + +## Loading a timm model + +The `TimmWrapperForImageClassification` class (in `transformers/src/transformers/models/timm_wrapper/modeling_timm_wrapper.py`) wraps timm models so they're fully compatible with the Trainer API. You can load them via the `Auto` classes: + +```python +from transformers import AutoModelForImageClassification, AutoImageProcessor, Trainer, TrainingArguments + +# Load a timm model for image classification +checkpoint = "timm/resnet50.a1_in1k" +image_processor = AutoImageProcessor.from_pretrained(checkpoint) +model = AutoModelForImageClassification.from_pretrained( + checkpoint, + num_labels=10, # set to your number of classes + ignore_mismatched_sizes=True, # needed when changing num_labels from pretrained +) +``` + +## Key details + +1. **Image processor**: The `TimmWrapperImageProcessor` automatically resolves the correct transforms from timm's config. It exposes both `val_transforms` and `train_transforms` (with augmentations), as noted in the code: + +```64:65:transformers/src/transformers/models/timm_wrapper/image_processing_timm_wrapper.py + # useful for training, see examples/pytorch/image-classification/run_image_classification.py + self.train_transforms = timm.data.create_transform(**self.data_config, is_training=True) +``` + +2. **Loss computation is built-in**: `TimmWrapperForImageClassification.forward()` accepts a `labels` argument and computes cross-entropy loss automatically, which is exactly what Trainer expects: + +```374:376:transformers/src/transformers/models/timm_wrapper/modeling_timm_wrapper.py + loss = None + if labels is not None: + loss = self.loss_function(labels, logits, self.config) +``` + +3. **Returns `ImageClassifierOutput`**: The output format is the standard transformers output, so Trainer handles it seamlessly. + +## Full training example + +```python +from transformers import AutoModelForImageClassification, AutoImageProcessor, Trainer, TrainingArguments +from datasets import load_dataset + +# Load dataset +dataset = load_dataset("food101", split="train[:5000]") +dataset = dataset.train_test_split(test_size=0.2) + +# Load timm model + processor +checkpoint = "timm/resnet50.a1_in1k" +image_processor = AutoImageProcessor.from_pretrained(checkpoint) +model = AutoModelForImageClassification.from_pretrained( + checkpoint, + num_labels=101, + ignore_mismatched_sizes=True, +) + +# Preprocessing +def transform(batch): + batch["pixel_values"] = [image_processor(img)["pixel_values"][0] for img in batch["image"]] + batch["labels"] = batch["label"] + return batch + +dataset["train"].set_transform(transform) +dataset["test"].set_transform(transform) + +# Train +training_args = TrainingArguments( + output_dir="./timm-finetuned", + num_train_epochs=3, + per_device_train_batch_size=16, + per_device_eval_batch_size=16, + eval_strategy="epoch", + save_strategy="epoch", + logging_steps=50, + remove_unused_columns=False, +) + +trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], +) + +trainer.train() +``` + +Any timm checkpoint on the Hub (prefixed with `timm/`) works out of the box (ResNet, EfficientNet, ViT, ConvNeXt, etc). The wrapper handles all the translation between timm's interface and what Trainer expects. \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/dataset_inspector.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/dataset_inspector.py new file mode 100644 index 0000000000000000000000000000000000000000..b7207b8ee69ece6d88a72f9898bf78a5d4b46837 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/dataset_inspector.py @@ -0,0 +1,814 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.10" +# dependencies = [] +# /// +""" +Dataset Format Inspector for Vision Model Training + +Inspects Hugging Face datasets to determine compatibility with object detection +and image classification training. +Uses Datasets Server API for instant results - no dataset download needed! + +ULTRA-EFFICIENT: Uses HF Datasets Server API - completes in <2 seconds. + +Usage with HF Jobs: + hf_jobs("uv", { + "script": "path/to/dataset_inspector.py", + "script_args": ["--dataset", "your/dataset", "--split", "train"] + }) +""" + +import argparse +import math +import sys +import json +import urllib.request +import urllib.parse +from typing import List, Dict, Any, Tuple + + +def parse_args(): + parser = argparse.ArgumentParser(description="Inspect dataset format for vision model training") + parser.add_argument("--dataset", type=str, required=True, help="Dataset name") + parser.add_argument("--split", type=str, default="train", help="Dataset split (default: train)") + parser.add_argument("--config", type=str, default="default", help="Dataset config name (default: default)") + parser.add_argument("--preview", type=int, default=150, help="Max chars per field preview") + parser.add_argument("--samples", type=int, default=5, help="Number of samples to fetch (default: 5)") + parser.add_argument("--json-output", action="store_true", help="Output as JSON") + return parser.parse_args() + + +def api_request(url: str) -> Dict: + """Make API request to Datasets Server""" + try: + with urllib.request.urlopen(url, timeout=10) as response: + return json.loads(response.read().decode()) + except urllib.error.HTTPError as e: + if e.code == 404: + return None + raise Exception(f"API request failed: {e.code} {e.reason}") + except Exception as e: + raise Exception(f"API request failed: {str(e)}") + + +def get_splits(dataset: str) -> Dict: + """Get available splits for dataset""" + url = f"https://datasets-server.huggingface.co/splits?dataset={urllib.parse.quote(dataset)}" + return api_request(url) + + +def get_rows(dataset: str, config: str, split: str, offset: int = 0, length: int = 5) -> Dict: + """Get rows from dataset""" + url = f"https://datasets-server.huggingface.co/rows?dataset={urllib.parse.quote(dataset)}&config={config}&split={split}&offset={offset}&length={length}" + return api_request(url) + + +def find_columns(columns: List[str], patterns: List[str]) -> List[str]: + """Find columns matching patterns""" + return [c for c in columns if any(p in c.lower() for p in patterns)] + + +def detect_bbox_format(bbox: List[float], image_size: Tuple[int, int] = None) -> str: + """ + Detect bounding box format based on values and optionally image dimensions. + Common formats: + - [x_min, y_min, x_max, y_max] - XYXY (Pascal VOC) + - [x_min, y_min, width, height] - XYWH (COCO) + - [x_center, y_center, width, height] - CXCYWH (YOLO normalized) + """ + if len(bbox) != 4: + return "unknown (not 4 values)" + + a, b, c, d = bbox + + is_normalized = all(0 <= v <= 1 for v in bbox) + + if c < a or d < b: + if is_normalized: + return "xywh_normalized" + return "xywh (COCO style)" + + # c > a and d > b — ambiguous between xyxy and xywh. + # Use image dimensions to disambiguate when available. + if image_size is not None: + img_w, img_h = image_size + # If interpreting as xywh, right edge = a + c; if that overshoots the + # image while c alone fits, the format is more likely xyxy. + xywh_exceeds = (a + c > img_w * 1.05) or (b + d > img_h * 1.05) + xyxy_exceeds = (c > img_w * 1.05) or (d > img_h * 1.05) + if xywh_exceeds and not xyxy_exceeds: + return "xyxy (Pascal VOC style)" + if xyxy_exceeds and not xywh_exceeds: + return "xywh (COCO style)" + + if is_normalized: + return "xyxy_normalized" + return "xyxy (Pascal VOC style)" + + +def _extract_image_size(row: Dict) -> Tuple[int, int] | None: + """Try to extract (width, height) from the image column returned by Datasets Server.""" + for col in ("image", "img", "picture", "photo"): + img = row.get(col) + if isinstance(img, dict): + w = img.get("width") + h = img.get("height") + if isinstance(w, (int, float)) and isinstance(h, (int, float)): + return (int(w), int(h)) + return None + + +def analyze_annotations(sample_rows: List[Dict], annotation_cols: List[str]) -> Dict[str, Any]: + """Analyze annotation structure from sample rows""" + if not annotation_cols: + return {"found": False} + + annotation_col = annotation_cols[0] + annotations_info = { + "found": True, + "column": annotation_col, + "sample_structures": [], + "bbox_formats": [], + "categories_found": [], + "avg_objects_per_image": 0, + "max_objects": 0, + "min_objects": float('inf'), + } + + total_objects = 0 + valid_samples = 0 + + for row in sample_rows: + ann = row["row"].get(annotation_col) + if not ann: + continue + + valid_samples += 1 + image_size = _extract_image_size(row["row"]) + + # Check if it's a list of annotations or a dict + if isinstance(ann, dict): + # COCO-style or structured annotation + sample_structure = { + "type": "dict", + "keys": list(ann.keys()) + } + + # Check for bounding boxes + if "bbox" in ann or "bboxes" in ann: + bbox_key = "bbox" if "bbox" in ann else "bboxes" + bboxes = ann[bbox_key] + if isinstance(bboxes, list) and len(bboxes) > 0: + if isinstance(bboxes[0], list): + # Multiple bboxes + num_objects = len(bboxes) + total_objects += num_objects + annotations_info["max_objects"] = max(annotations_info["max_objects"], num_objects) + annotations_info["min_objects"] = min(annotations_info["min_objects"], num_objects) + + # Analyze first bbox format + bbox_format = detect_bbox_format(bboxes[0], image_size) + annotations_info["bbox_formats"].append(bbox_format) + else: + # Single bbox + total_objects += 1 + annotations_info["max_objects"] = max(annotations_info["max_objects"], 1) + annotations_info["min_objects"] = min(annotations_info["min_objects"], 1) + bbox_format = detect_bbox_format(bboxes, image_size) + annotations_info["bbox_formats"].append(bbox_format) + + # Check for categories/classes + for key in ["category", "categories", "label", "labels", "class", "classes", "category_id"]: + if key in ann: + cats = ann[key] + if isinstance(cats, list): + annotations_info["categories_found"].extend([str(c) for c in cats]) + else: + annotations_info["categories_found"].append(str(cats)) + + annotations_info["sample_structures"].append(sample_structure) + + elif isinstance(ann, list): + # List of annotation dicts + sample_structure = { + "type": "list", + "length": len(ann), + "item_type": type(ann[0]).__name__ if ann else None + } + + if ann and isinstance(ann[0], dict): + sample_structure["item_keys"] = list(ann[0].keys()) + + # Count objects + num_objects = len(ann) + total_objects += num_objects + annotations_info["max_objects"] = max(annotations_info["max_objects"], num_objects) + annotations_info["min_objects"] = min(annotations_info["min_objects"], num_objects) + + # Check first annotation + first_ann = ann[0] + if "bbox" in first_ann: + bbox_format = detect_bbox_format(first_ann["bbox"], image_size) + annotations_info["bbox_formats"].append(bbox_format) + + # Check for categories + for key in ["category", "label", "class", "category_id"]: + if key in first_ann: + for item in ann: + if key in item: + annotations_info["categories_found"].append(str(item[key])) + + annotations_info["sample_structures"].append(sample_structure) + + if valid_samples > 0: + annotations_info["avg_objects_per_image"] = round(total_objects / valid_samples, 2) + + if annotations_info["min_objects"] == float('inf'): + annotations_info["min_objects"] = 0 + + # Get unique categories + annotations_info["categories_found"] = list(set(annotations_info["categories_found"])) + annotations_info["num_classes"] = len(annotations_info["categories_found"]) + + # Get most common bbox format + if annotations_info["bbox_formats"]: + from collections import Counter + format_counts = Counter(annotations_info["bbox_formats"]) + annotations_info["primary_bbox_format"] = format_counts.most_common(1)[0][0] + + return annotations_info + + +def check_image_classification_compatibility(columns: List[str], sample_rows: List[Dict], features: List[Dict]) -> Dict[str, Any]: + """Check image classification dataset compatibility""" + + image_cols = find_columns(columns, ["image", "img", "picture", "photo"]) + has_image = len(image_cols) > 0 + + label_cols = find_columns(columns, ["label", "labels", "class", "fine_label", "coarse_label"]) + has_label = len(label_cols) > 0 + + label_info: Dict[str, Any] = {"found": has_label} + + if has_label: + label_col = label_cols[0] + label_info["column"] = label_col + + # Detect whether label is ClassLabel (int with names) or plain int/string + for f in features: + if f.get("name") == label_col: + ftype = f.get("type", "") + if isinstance(ftype, dict) and ftype.get("_type") == "ClassLabel": + label_info["type"] = "ClassLabel" + names = ftype.get("names", []) + label_info["num_classes"] = len(names) + label_info["class_names"] = names[:20] + if len(names) > 20: + label_info["class_names_truncated"] = True + elif isinstance(ftype, dict) and ftype.get("dtype") in ("int64", "int32", "int8"): + label_info["type"] = "int" + elif isinstance(ftype, dict) and ftype.get("dtype") == "string": + label_info["type"] = "string" + break + + # Discover unique labels from samples if ClassLabel info wasn't in features + if "num_classes" not in label_info: + unique = set() + for row in sample_rows: + val = row["row"].get(label_col) + if val is not None: + unique.add(val) + label_info["sample_unique_labels"] = sorted(unique, key=str)[:20] + label_info["sample_unique_count"] = len(unique) + + ready = has_image and has_label + return { + "ready": ready, + "has_image": has_image, + "image_columns": image_cols, + "has_label": has_label, + "label_columns": label_cols, + "label_info": label_info, + } + + +def check_object_detection_compatibility(columns: List[str], sample_rows: List[Dict]) -> Dict[str, Any]: + """Check object detection dataset compatibility""" + + # Find image column + image_cols = find_columns(columns, ["image", "img", "picture", "photo"]) + has_image = len(image_cols) > 0 + + # Find annotation columns + annotation_cols = find_columns(columns, ["objects", "annotations", "ann", "bbox", "bboxes", "detection"]) + has_annotations = len(annotation_cols) > 0 + + # Analyze annotations + annotations_info = analyze_annotations(sample_rows, annotation_cols) if has_annotations else {"found": False} + + # Check for separate bbox and category columns + bbox_cols = find_columns(columns, ["bbox", "bboxes", "boxes"]) + category_cols = find_columns(columns, ["category", "label", "class", "categories", "labels", "classes"]) + + # Determine readiness + ready = has_image and (has_annotations or (len(bbox_cols) > 0 and len(category_cols) > 0)) + + return { + "ready": ready, + "has_image": has_image, + "image_columns": image_cols, + "has_annotations": has_annotations, + "annotation_columns": annotation_cols, + "separate_bbox_columns": bbox_cols, + "separate_category_columns": category_cols, + "annotations_info": annotations_info, + } + + +def check_sam_segmentation_compatibility(columns: List[str], sample_rows: List[Dict], features: List[Dict]) -> Dict[str, Any]: + """Check SAM/SAM2 segmentation dataset compatibility. + + A valid SAM segmentation dataset needs: + - An image column + - A mask column (binary ground-truth segmentation mask) + - A prompt: either a bbox prompt or point prompt (in a JSON prompt column, or dedicated columns) + """ + + image_cols = find_columns(columns, ["image", "img", "picture", "photo"]) + has_image = len(image_cols) > 0 + + mask_cols = find_columns(columns, ["mask", "segmentation", "alpha", "matte"]) + has_mask = len(mask_cols) > 0 + + prompt_cols = find_columns(columns, ["prompt"]) + bbox_cols = [c for c in columns if c in ("bbox", "bboxes", "box", "boxes")] + point_cols = [c for c in columns if c in ("point", "points", "input_point", "input_points")] + + prompt_info: Dict[str, Any] = { + "has_prompt": False, + "prompt_type": None, + "source": None, + "bbox_valid": None, + } + + # Try JSON prompt column first + if prompt_cols: + for row in sample_rows: + raw = row["row"].get(prompt_cols[0]) + if raw is None: + continue + parsed = raw if isinstance(raw, dict) else _try_json(raw) + if parsed is None: + continue + + if isinstance(parsed, dict): + if "bbox" in parsed or "box" in parsed: + prompt_info["has_prompt"] = True + prompt_info["prompt_type"] = "bbox" + prompt_info["source"] = f"JSON column '{prompt_cols[0]}'" + bbox = parsed.get("bbox") or parsed.get("box") + prompt_info["bbox_valid"] = _validate_bbox(bbox, _extract_image_size(row["row"])) + break + elif "point" in parsed or "points" in parsed: + prompt_info["has_prompt"] = True + prompt_info["prompt_type"] = "point" + prompt_info["source"] = f"JSON column '{prompt_cols[0]}'" + break + + if not prompt_info["has_prompt"] and bbox_cols: + prompt_info["has_prompt"] = True + prompt_info["prompt_type"] = "bbox" + prompt_info["source"] = f"column '{bbox_cols[0]}'" + for row in sample_rows: + bbox = row["row"].get(bbox_cols[0]) + if bbox is not None: + prompt_info["bbox_valid"] = _validate_bbox(bbox, _extract_image_size(row["row"])) + break + + if not prompt_info["has_prompt"] and point_cols: + prompt_info["has_prompt"] = True + prompt_info["prompt_type"] = "point" + prompt_info["source"] = f"column '{point_cols[0]}'" + + ready = has_image and has_mask and prompt_info["has_prompt"] + + return { + "ready": ready, + "has_image": has_image, + "image_columns": image_cols, + "has_mask": has_mask, + "mask_columns": mask_cols, + "prompt_columns": prompt_cols, + "bbox_columns": bbox_cols, + "point_columns": point_cols, + "prompt_info": prompt_info, + } + + +def _try_json(value) -> Any: + if not isinstance(value, str): + return None + try: + return json.loads(value) + except (json.JSONDecodeError, TypeError): + return None + + +def _validate_bbox(bbox, image_size=None) -> Dict[str, Any]: + """Validate a single bounding box and return diagnostics.""" + result: Dict[str, Any] = {"valid": False} + if not isinstance(bbox, (list, tuple)): + result["error"] = "bbox is not a list" + return result + if len(bbox) != 4: + result["error"] = f"expected 4 values, got {len(bbox)}" + return result + try: + vals = [float(v) for v in bbox] + except (TypeError, ValueError): + result["error"] = "non-numeric values" + return result + + if not all(math.isfinite(v) for v in vals): + result["error"] = "contains non-finite values" + return result + + x0, y0, x1, y1 = vals + if x1 <= x0 or y1 <= y0: + if vals[2] > 0 and vals[3] > 0: + result["format_hint"] = "likely xywh" + else: + result["error"] = "degenerate bbox (zero or negative area)" + return result + else: + result["format_hint"] = "likely xyxy" + + if image_size is not None: + img_w, img_h = image_size + if any(v > max(img_w, img_h) * 1.5 for v in vals): + result["warning"] = "coordinates exceed image bounds" + + result["valid"] = True + result["values"] = vals + return result + + +def generate_mapping_code(info: Dict[str, Any]) -> str: + """Generate mapping code if needed""" + if info["ready"]: + ann_info = info["annotations_info"] + if not ann_info.get("found"): + return None + + # Check if format conversion is needed + ann_col = ann_info.get("column") + bbox_format = ann_info.get("primary_bbox_format", "unknown") + + if "coco" in bbox_format.lower() or "xywh" in bbox_format.lower(): + # Already COCO format + return f"""# Dataset appears to be in COCO format (xywh) +# Image column: {info['image_columns'][0] if info['image_columns'] else 'image'} +# Annotation column: {ann_col} +# Use directly with transformers object detection models""" + elif "xyxy" in bbox_format.lower(): + # Need to convert from XYXY to XYWH + return f"""# Convert from XYXY (Pascal VOC) to XYWH (COCO) format +def convert_to_coco_format(example): + annotations = example['{ann_col}'] + if isinstance(annotations, list): + for ann in annotations: + if 'bbox' in ann: + x_min, y_min, x_max, y_max = ann['bbox'] + ann['bbox'] = [x_min, y_min, x_max - x_min, y_max - y_min] + elif isinstance(annotations, dict) and 'bbox' in annotations: + bbox = annotations['bbox'] + if isinstance(bbox, list) and len(bbox) > 0 and isinstance(bbox[0], list): + for i, box in enumerate(bbox): + x_min, y_min, x_max, y_max = box + bbox[i] = [x_min, y_min, x_max - x_min, y_max - y_min] + return example + +dataset = dataset.map(convert_to_coco_format)""" + + elif not info["ready"]: + # Need to create annotations structure + if info["separate_bbox_columns"] and info["separate_category_columns"]: + bbox_col = info["separate_bbox_columns"][0] + cat_col = info["separate_category_columns"][0] + + return f"""# Combine separate bbox and category columns +def create_annotations(example): + bboxes = example['{bbox_col}'] + categories = example['{cat_col}'] + + if not isinstance(bboxes, list): + bboxes = [bboxes] + if not isinstance(categories, list): + categories = [categories] + + annotations = [] + for bbox, cat in zip(bboxes, categories): + annotations.append({{'bbox': bbox, 'category': cat}}) + + example['objects'] = annotations + return example + +dataset = dataset.map(create_annotations)""" + + return None + + +def format_value_preview(value: Any, max_chars: int) -> str: + """Format value for preview""" + if value is None: + return "None" + elif isinstance(value, str): + return value[:max_chars] + ("..." if len(value) > max_chars else "") + elif isinstance(value, dict): + keys = list(value.keys()) + return f"{{dict with {len(keys)} keys: {', '.join(keys[:5])}}}" + elif isinstance(value, list): + if len(value) == 0: + return "[]" + elif isinstance(value[0], dict): + return f"[{len(value)} items] First item keys: {list(value[0].keys())}" + elif isinstance(value[0], list): + return f"[{len(value)} items] First item: {value[0]}" + else: + preview = str(value) + return preview[:max_chars] + ("..." if len(preview) > max_chars else "") + else: + preview = str(value) + return preview[:max_chars] + ("..." if len(preview) > max_chars else "") + + +def main(): + args = parse_args() + + print(f"Fetching dataset info via Datasets Server API...") + + try: + # Get splits info + splits_data = get_splits(args.dataset) + if not splits_data or "splits" not in splits_data: + print(f"ERROR: Could not fetch splits for dataset '{args.dataset}'") + print(f" Dataset may not exist or is not accessible via Datasets Server API") + sys.exit(1) + + # Find the right config + available_configs = set() + split_found = False + config_to_use = args.config + + for split_info in splits_data["splits"]: + available_configs.add(split_info["config"]) + if split_info["config"] == args.config and split_info["split"] == args.split: + split_found = True + + # If default config not found, try first available + if not split_found and available_configs: + config_to_use = list(available_configs)[0] + print(f"Config '{args.config}' not found, trying '{config_to_use}'...") + + # Get rows + rows_data = get_rows(args.dataset, config_to_use, args.split, offset=0, length=args.samples) + + if not rows_data or "rows" not in rows_data: + print(f"ERROR: Could not fetch rows for dataset '{args.dataset}'") + print(f" Split '{args.split}' may not exist") + print(f" Available configs: {', '.join(sorted(available_configs))}") + sys.exit(1) + + rows = rows_data["rows"] + if not rows: + print(f"ERROR: No rows found in split '{args.split}'") + sys.exit(1) + + # Extract column info from first row + first_row = rows[0]["row"] + columns = list(first_row.keys()) + features = rows_data.get("features", []) + + # Get total count if available + total_examples = "Unknown" + for split_info in splits_data["splits"]: + if split_info["config"] == config_to_use and split_info["split"] == args.split: + total_examples = f"{split_info.get('num_examples', 'Unknown'):,}" if isinstance(split_info.get('num_examples'), int) else "Unknown" + break + + except Exception as e: + print(f"ERROR: {str(e)}") + sys.exit(1) + + # Run compatibility checks + od_info = check_object_detection_compatibility(columns, rows) + ic_info = check_image_classification_compatibility(columns, rows, features) + sam_info = check_sam_segmentation_compatibility(columns, rows, features) + + # JSON output mode + if args.json_output: + result = { + "dataset": args.dataset, + "config": config_to_use, + "split": args.split, + "total_examples": total_examples, + "columns": columns, + "features": [{"name": f["name"], "type": f["type"]} for f in features] if features else [], + "object_detection_compatibility": od_info, + "image_classification_compatibility": ic_info, + "sam_segmentation_compatibility": sam_info, + } + print(json.dumps(result, indent=2)) + sys.exit(0) + + # Human-readable output optimized for LLM parsing + print("=" * 80) + print(f"VISION DATASET INSPECTION") + print("=" * 80) + + print(f"\nDataset: {args.dataset}") + print(f"Config: {config_to_use}") + print(f"Split: {args.split}") + print(f"Total examples: {total_examples}") + print(f"Samples fetched: {len(rows)}") + + print(f"\n{'COLUMNS':-<80}") + if features: + for feature in features: + print(f" {feature['name']}: {feature['type']}") + else: + for col in columns: + print(f" {col}: (type info not available)") + + print(f"\n{'EXAMPLE DATA':-<80}") + example = first_row + for col in columns: + value = example.get(col) + display = format_value_preview(value, args.preview) + print(f"\n{col}:") + print(f" {display}") + + # --- Image Classification --- + print(f"\n{'IMAGE CLASSIFICATION COMPATIBILITY':-<80}") + print(f"\n[STATUS] {'✓ READY' if ic_info['ready'] else '✗ NOT COMPATIBLE'}") + + print(f"\nImage Column:") + if ic_info["has_image"]: + print(f" ✓ Found: {', '.join(ic_info['image_columns'])}") + else: + print(f" ✗ No image column detected") + + print(f"\nLabel Column:") + if ic_info["has_label"]: + print(f" ✓ Found: {', '.join(ic_info['label_columns'])}") + li = ic_info["label_info"] + if li.get("type"): + print(f" • Type: {li['type']}") + if li.get("num_classes"): + print(f" • Number of Classes: {li['num_classes']}") + if li.get("class_names"): + names = li["class_names"] + display = ", ".join(str(n) for n in names[:10]) + if len(names) > 10: + display += f" ... ({li['num_classes']} total)" + print(f" • Classes: {display}") + elif li.get("sample_unique_labels"): + labels = li["sample_unique_labels"] + display = ", ".join(str(l) for l in labels[:10]) + if li.get("sample_unique_count", 0) > 10: + display += f" ... ({li['sample_unique_count']}+ from sample)" + print(f" • Sample labels: {display}") + else: + print(f" ✗ No label column detected") + print(f" Expected column names: 'label', 'labels', 'class', 'fine_label'") + + if ic_info["ready"]: + lc = ic_info["label_info"].get("column", "label") + print(f"\n Use with: scripts/image_classification_training.py") + print(f" --image_column_name {ic_info['image_columns'][0]} --label_column_name {lc}") + + # --- Object Detection --- + print(f"\n{'OBJECT DETECTION COMPATIBILITY':-<80}") + print(f"\n[STATUS] {'✓ READY' if od_info['ready'] else '✗ NOT COMPATIBLE'}") + + print(f"\nImage Column:") + if od_info["has_image"]: + print(f" ✓ Found: {', '.join(od_info['image_columns'])}") + else: + print(f" ✗ No image column detected") + print(f" Expected column names: 'image', 'img', 'picture', 'photo'") + + print(f"\nAnnotations:") + if od_info["has_annotations"]: + print(f" ✓ Found: {', '.join(od_info['annotation_columns'])}") + ann_info = od_info["annotations_info"] + if ann_info.get("found"): + print(f"\n Annotation Details:") + print(f" • Column: {ann_info['column']}") + if ann_info.get("primary_bbox_format"): + print(f" • BBox Format: {ann_info['primary_bbox_format']}") + if ann_info.get("num_classes", 0) > 0: + print(f" • Number of Classes: {ann_info['num_classes']}") + print(f" • Classes: {', '.join(ann_info['categories_found'][:10])}") + if len(ann_info['categories_found']) > 10: + print(f" (showing first 10 of {len(ann_info['categories_found'])})") + print(f" • Avg Objects/Image: {ann_info['avg_objects_per_image']}") + print(f" • Min Objects: {ann_info['min_objects']}") + print(f" • Max Objects: {ann_info['max_objects']}") + elif od_info["separate_bbox_columns"] and od_info["separate_category_columns"]: + print(f" ⚠ Separate bbox and category columns found:") + print(f" BBox columns: {', '.join(od_info['separate_bbox_columns'])}") + print(f" Category columns: {', '.join(od_info['separate_category_columns'])}") + print(f" Action: These need to be combined (see mapping code below)") + else: + print(f" ✗ No annotation columns detected") + print(f" Expected: 'objects', 'annotations', 'bbox'/'bboxes' + 'category'/'label'") + + # --- SAM Segmentation --- + print(f"\n{'SAM SEGMENTATION COMPATIBILITY':-<80}") + print(f"\n[STATUS] {'✓ READY' if sam_info['ready'] else '✗ NOT COMPATIBLE'}") + + print(f"\nImage Column:") + if sam_info["has_image"]: + print(f" ✓ Found: {', '.join(sam_info['image_columns'])}") + else: + print(f" ✗ No image column detected") + + print(f"\nMask Column:") + if sam_info["has_mask"]: + print(f" ✓ Found: {', '.join(sam_info['mask_columns'])}") + else: + print(f" ✗ No mask column detected") + print(f" Expected column names: 'mask', 'segmentation', 'alpha', 'matte'") + + print(f"\nPrompt:") + pi = sam_info["prompt_info"] + if pi["has_prompt"]: + print(f" ✓ Type: {pi['prompt_type']} (from {pi['source']})") + if pi.get("bbox_valid"): + bv = pi["bbox_valid"] + if bv["valid"]: + print(f" • BBox values: {bv.get('values')}") + if bv.get("format_hint"): + print(f" • Format: {bv['format_hint']}") + if bv.get("warning"): + print(f" ⚠ {bv['warning']}") + else: + print(f" ✗ Invalid bbox: {bv.get('error', 'unknown error')}") + else: + print(f" ✗ No prompt detected") + print(f" Expected: 'prompt' column (JSON with bbox/point), or 'bbox'/'point' column") + + if sam_info["ready"]: + pc = sam_info["prompt_columns"][0] if sam_info["prompt_columns"] else None + args_hint = f"--prompt_type {pi['prompt_type']}" + if pc: + args_hint += f" --prompt_column_name {pc}" + print(f"\n Use with: scripts/sam_segmentation_training.py") + print(f" {args_hint}") + + # Mapping code (OD only) + mapping_code = generate_mapping_code(od_info) + + if mapping_code: + print(f"\n{'OD PREPROCESSING CODE':-<80}") + print(mapping_code) + elif od_info["ready"]: + print(f"\n ✓ No OD preprocessing needed.") + + # --- Summary --- + print(f"\n{'SUMMARY':-<80}") + if ic_info["ready"]: + num_cls = ic_info["label_info"].get("num_classes") or ic_info["label_info"].get("sample_unique_count", "?") + print(f"✓ Image Classification: READY ({num_cls} classes)") + else: + print(f"✗ Image Classification: not compatible") + + if od_info["ready"]: + ann_info = od_info["annotations_info"] + fmt = ann_info.get("primary_bbox_format", "") + cls = ann_info.get("num_classes", "?") + print(f"✓ Object Detection: READY ({cls} classes, {fmt})") + else: + print(f"✗ Object Detection: not compatible") + + if sam_info["ready"]: + print(f"✓ SAM Segmentation: READY (prompt: {pi['prompt_type']})") + else: + print(f"✗ SAM Segmentation: not compatible") + + print(f"\nNote: Used Datasets Server API (instant, no download required)") + + print("\n" + "=" * 80) + sys.exit(0) + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + sys.exit(0) + except Exception as e: + print(f"ERROR: {e}", file=sys.stderr) + sys.exit(1) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/estimate_cost.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/estimate_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c1a45172c5f686ddeac4e43efb2cded0b85970 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/estimate_cost.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.10" +# dependencies = [] +# /// +""" +Estimate training time and cost for vision model training jobs on Hugging Face Jobs. + +Usage: + uv run estimate_cost.py --model ustc-community/dfine-small-coco --dataset cppe-5 --hardware t4-small + uv run estimate_cost.py --model PekingU/rtdetr_v2_r50vd --dataset-size 5000 --hardware t4-small --epochs 30 + uv run estimate_cost.py --model google/vit-base-patch16-224-in21k --dataset ethz/food101 --hardware t4-small --epochs 3 +""" + +import argparse + +HARDWARE_COSTS = { + "t4-small": 0.40, + "t4-medium": 0.60, + "l4x1": 0.80, + "l4x4": 3.80, + "a10g-small": 1.00, + "a10g-large": 1.50, + "a10g-largex2": 3.00, + "a10g-largex4": 5.00, + "l40sx1": 1.80, + "l40sx4": 8.30, + "a100-large": 2.50, + "a100x4": 10.00, +} + +# Vision model sizes in millions of parameters +MODEL_PARAMS_M = { + # Object detection + "dfine-small": 10.4, + "dfine-large": 31.4, + "dfine-xlarge": 63.5, + "rtdetr_v2_r18vd": 20.2, + "rtdetr_v2_r50vd": 43.0, + "rtdetr_v2_r101vd": 76.0, + "detr-resnet-50": 41.3, + "detr-resnet-101": 60.2, + "yolos-small": 30.7, + "yolos-tiny": 6.5, + # Image classification + "mobilenetv3_small": 2.5, + "mobilevit_s": 5.6, + "resnet50": 25.6, + "vit_base_patch16": 86.6, + # SAM / SAM2 segmentation + "sam-vit-base": 93.7, + "sam-vit-large": 312.3, + "sam-vit-huge": 641.1, + "sam2.1-hiera-tiny": 38.9, + "sam2.1-hiera-small": 46.0, + "sam2.1-hiera-base-plus": 80.8, + "sam2.1-hiera-large": 224.4, +} + +KNOWN_DATASETS = { + # Object detection + "cppe-5": 1000, + "merve/license-plate": 6180, + # Image classification + "ethz/food101": 75750, + # SAM segmentation + "merve/MicroMat-mini": 240, +} + + +def extract_model_params(model_name: str) -> float: + """Extract model size in millions of parameters from the model name.""" + name_lower = model_name.lower() + for key, params in MODEL_PARAMS_M.items(): + if key.lower() in name_lower: + return params + return 30.0 # reasonable default for vision models + + +def estimate_training_time(model_params_m: float, dataset_size: int, epochs: int, + image_size: int, batch_size: int, hardware: str) -> float: + """Estimate training time in hours for vision model training.""" + # Steps per epoch + steps_per_epoch = dataset_size / batch_size + # empirical calibration values + base_secs_per_step = 0.8 + model_factor = (model_params_m / 30.0) ** 0.6 + image_factor = (image_size / 640.0) ** 2 + + + batch_factor = (batch_size / 8.0) ** 0.7 + + secs_per_step = base_secs_per_step * model_factor * image_factor * batch_factor + + hardware_multipliers = { + "t4-small": 2.0, + "t4-medium": 2.0, + "l4x1": 1.2, + "l4x4": 0.5, + "a10g-small": 1.0, + "a10g-large": 1.0, + "a10g-largex2": 0.6, + "a10g-largex4": 0.4, + "l40sx1": 0.7, + "l40sx4": 0.25, + "a100-large": 0.5, + "a100x4": 0.2, + } + + multiplier = hardware_multipliers.get(hardware, 1.0) + total_steps = steps_per_epoch * epochs + total_secs = total_steps * secs_per_step * multiplier + + # Add overhead: model loading (~2 min), eval per epoch (~10% of training), Hub push (~3 min) + eval_overhead = total_secs * 0.10 + fixed_overhead = 5 * 60 # 5 minutes + total_secs += eval_overhead + fixed_overhead + + return total_secs / 3600 + + +def parse_args(): + parser = argparse.ArgumentParser(description="Estimate training cost for vision model training jobs") + parser.add_argument("--model", required=True, + help="Model name (e.g., 'ustc-community/dfine-small-coco' or 'detr-resnet-50')") + parser.add_argument("--dataset", default=None, help="Dataset name (for known size lookup)") + parser.add_argument("--hardware", required=True, choices=HARDWARE_COSTS.keys(), help="Hardware flavor") + parser.add_argument("--dataset-size", type=int, default=None, + help="Number of training images (overrides dataset lookup)") + parser.add_argument("--epochs", type=int, default=30, help="Number of training epochs (default: 30)") + parser.add_argument("--image-size", type=int, default=640, help="Image square size in pixels (default: 640)") + parser.add_argument("--batch-size", type=int, default=8, help="Per-device batch size (default: 8)") + return parser.parse_args() + + +def main(): + args = parse_args() + + model_params = extract_model_params(args.model) + print(f"Model: {args.model} (~{model_params:.1f}M parameters)") + + if args.dataset_size: + dataset_size = args.dataset_size + elif args.dataset and args.dataset in KNOWN_DATASETS: + dataset_size = KNOWN_DATASETS[args.dataset] + elif args.dataset: + print(f"Unknown dataset '{args.dataset}', defaulting to 1000 images.") + print(f"Use --dataset-size to specify the exact count.") + dataset_size = 1000 + else: + dataset_size = 1000 + + print(f"Dataset: {args.dataset or 'custom'} (~{dataset_size} images)") + print(f"Epochs: {args.epochs}") + print(f"Image size: {args.image_size}px") + print(f"Batch size: {args.batch_size}") + print(f"Hardware: {args.hardware} (${HARDWARE_COSTS[args.hardware]:.2f}/hr)") + print() + + estimated_hours = estimate_training_time( + model_params, dataset_size, args.epochs, args.image_size, args.batch_size, args.hardware + ) + estimated_cost = estimated_hours * HARDWARE_COSTS[args.hardware] + recommended_timeout = estimated_hours * 1.3 # 30% buffer + + print(f"Estimated training time: {estimated_hours:.1f} hours") + print(f"Estimated cost: ${estimated_cost:.2f}") + print(f"Recommended timeout: {recommended_timeout:.1f}h (with 30% buffer)") + print() + + if estimated_hours > 6: + print("Warning: Long training time. Consider:") + print(" - Reducing epochs or image size") + print(" - Using --max_train_samples for a test run first") + print(" - Upgrading hardware") + print() + + if model_params > 50 and args.hardware in ("t4-small", "t4-medium"): + print("Warning: Large model on T4. If you hit OOM:") + print(" - Reduce batch size (try 4, then 2)") + print(" - Reduce image size (try 480)") + print(" - Upgrade to l4x1 or a10g-small") + print() + + timeout_str = f"{recommended_timeout:.0f}h" + timeout_secs = int(recommended_timeout * 3600) + print(f"Example job configuration (MCP tool):") + print(f""" +hf_jobs("uv", {{ + "script": "scripts/object_detection_training.py", + "script_args": [ + "--model_name_or_path", "{args.model}", + "--dataset_name", "{args.dataset or 'your-dataset'}", + "--image_square_size", "{args.image_size}", + "--num_train_epochs", "{args.epochs}", + "--per_device_train_batch_size", "{args.batch_size}", + "--push_to_hub", "--do_train", "--do_eval" + ], + "flavor": "{args.hardware}", + "timeout": "{timeout_str}", + "secrets": {{"HF_TOKEN": "$HF_TOKEN"}} +}}) +""") + print(f"Example job configuration (Python API):") + print(f""" +api.run_uv_job( + script="scripts/object_detection_training.py", + script_args=[...], + flavor="{args.hardware}", + timeout={timeout_secs}, + secrets={{"HF_TOKEN": get_token()}}, +) +""") + + +if __name__ == "__main__": + main() diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/image_classification_training.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/image_classification_training.py new file mode 100644 index 0000000000000000000000000000000000000000..df5f913bf6338bff1d0b168b10bf71b13526baee --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/image_classification_training.py @@ -0,0 +1,383 @@ +# /// script +# dependencies = [ +# "transformers>=5.2.0", +# "accelerate>=1.1.0", +# "timm", +# "datasets>=4.0", +# "evaluate", +# "scikit-learn", +# "torchvision", +# "trackio", +# "huggingface_hub", +# ] +# /// + +"""Fine-tuning any Transformers or timm model supported by AutoModelForImageClassification using the Trainer API.""" + +import logging +import os +import sys +from dataclasses import dataclass, field +from functools import partial +from typing import Any + +import evaluate +import numpy as np +import torch +from datasets import load_dataset +from torchvision.transforms import ( + CenterCrop, + Compose, + Normalize, + RandomHorizontalFlip, + RandomResizedCrop, + Resize, + ToTensor, +) + +import trackio + +import transformers +from transformers import ( + AutoConfig, + AutoImageProcessor, + AutoModelForImageClassification, + DefaultDataCollator, + HfArgumentParser, + Trainer, + TrainingArguments, +) +from transformers.trainer import EvalPrediction +from transformers.utils import check_min_version +from transformers.utils.versions import require_version + + +logger = logging.getLogger(__name__) + +check_min_version("4.57.0.dev0") +require_version("datasets>=2.0.0") + + +@dataclass +class DataTrainingArguments: + dataset_name: str = field( + default="ethz/food101", + metadata={"help": "Name of a dataset from the Hub."}, + ) + dataset_config_name: str | None = field( + default=None, + metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}, + ) + train_val_split: float | None = field( + default=0.15, + metadata={"help": "Fraction to split off of train for validation (used only when no validation split exists)."}, + ) + max_train_samples: int | None = field( + default=None, + metadata={"help": "Truncate training set to this many samples (for debugging / quick tests)."}, + ) + max_eval_samples: int | None = field( + default=None, + metadata={"help": "Truncate evaluation set to this many samples."}, + ) + image_column_name: str = field( + default="image", + metadata={"help": "The column name for images in the dataset."}, + ) + label_column_name: str = field( + default="label", + metadata={"help": "The column name for labels in the dataset."}, + ) + + +@dataclass +class ModelArguments: + model_name_or_path: str = field( + default="timm/mobilenetv3_small_100.lamb_in1k", + metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."}, + ) + config_name: str | None = field( + default=None, + metadata={"help": "Pretrained config name or path if not the same as model_name."}, + ) + cache_dir: str | None = field( + default=None, + metadata={"help": "Where to store pretrained models downloaded from the Hub."}, + ) + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (branch, tag, or commit id)."}, + ) + image_processor_name: str | None = field( + default=None, + metadata={"help": "Name or path of image processor config."}, + ) + ignore_mismatched_sizes: bool = field( + default=True, + metadata={"help": "Allow loading weights when num_labels differs from pretrained checkpoint."}, + ) + token: str | None = field( + default=None, + metadata={"help": "Auth token for private models / datasets."}, + ) + trust_remote_code: bool = field( + default=False, + metadata={"help": "Whether to trust remote code from Hub repos."}, + ) + + +def build_transforms(image_processor, is_training: bool): + """Build torchvision transforms from the image processor's config.""" + if hasattr(image_processor, "size"): + size = image_processor.size + if "shortest_edge" in size: + img_size = size["shortest_edge"] + elif "height" in size and "width" in size: + img_size = (size["height"], size["width"]) + else: + img_size = 224 + else: + img_size = 224 + + if hasattr(image_processor, "image_mean") and image_processor.image_mean: + normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std) + else: + normalize = Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) + + if is_training: + return Compose([ + RandomResizedCrop(img_size), + RandomHorizontalFlip(), + ToTensor(), + normalize, + ]) + else: + if isinstance(img_size, int): + resize_size = int(img_size / 0.875) # standard 87.5% center crop ratio + else: + resize_size = tuple(int(s / 0.875) for s in img_size) + return Compose([ + Resize(resize_size), + CenterCrop(img_size), + ToTensor(), + normalize, + ]) + + +def main(): + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + # --- Hub authentication --- + from huggingface_hub import login + hf_token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob") + if hf_token: + login(token=hf_token) + training_args.hub_token = hf_token + logger.info("Logged in to Hugging Face Hub") + elif training_args.push_to_hub: + logger.warning("HF_TOKEN not found in environment. Hub push will likely fail.") + + # --- Trackio --- + trackio.init(project=training_args.output_dir, name=training_args.run_name) + + # --- Logging --- + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + if training_args.should_log: + transformers.utils.logging.set_verbosity_info() + + log_level = training_args.get_process_log_level() + logger.setLevel(log_level) + transformers.utils.logging.set_verbosity(log_level) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + logger.warning( + f"Process rank: {training_args.local_process_index}, device: {training_args.device}, " + f"n_gpu: {training_args.n_gpu}, distributed training: " + f"{training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}" + ) + logger.info(f"Training/evaluation parameters {training_args}") + + # --- Load dataset --- + dataset = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + cache_dir=model_args.cache_dir, + trust_remote_code=model_args.trust_remote_code, + ) + + # --- Resolve label column --- + label_col = data_args.label_column_name + if label_col not in dataset["train"].column_names: + candidates = [c for c in dataset["train"].column_names if c in ("label", "labels", "class", "fine_label")] + if candidates: + label_col = candidates[0] + logger.info(f"Label column '{data_args.label_column_name}' not found, using '{label_col}'") + else: + raise ValueError( + f"Label column '{data_args.label_column_name}' not found. " + f"Available columns: {dataset['train'].column_names}" + ) + + # --- Discover labels --- + label_feature = dataset["train"].features[label_col] + if hasattr(label_feature, "names"): + label_names = label_feature.names + else: + unique_labels = sorted(set(dataset["train"][label_col])) + if all(isinstance(l, str) for l in unique_labels): + label_names = unique_labels + else: + label_names = [str(l) for l in unique_labels] + + num_labels = len(label_names) + id2label = dict(enumerate(label_names)) + label2id = {v: k for k, v in id2label.items()} + logger.info(f"Number of classes: {num_labels}") + + # --- Remap string labels to int if needed --- + sample_label = dataset["train"][0][label_col] + if isinstance(sample_label, str): + logger.info("Remapping string labels to integer IDs") + for split_name in list(dataset.keys()): + dataset[split_name] = dataset[split_name].map( + lambda ex: {label_col: label2id[ex[label_col]]}, + ) + + # --- Shuffle + Train/val split --- + dataset["train"] = dataset["train"].shuffle(seed=training_args.seed) + + data_args.train_val_split = None if "validation" in dataset else data_args.train_val_split + if isinstance(data_args.train_val_split, float) and data_args.train_val_split > 0.0: + split = dataset["train"].train_test_split(data_args.train_val_split, seed=training_args.seed) + dataset["train"] = split["train"] + dataset["validation"] = split["test"] + + # --- Truncate --- + if data_args.max_train_samples is not None: + max_train = min(data_args.max_train_samples, len(dataset["train"])) + dataset["train"] = dataset["train"].select(range(max_train)) + logger.info(f"Truncated training set to {max_train} samples") + if data_args.max_eval_samples is not None and "validation" in dataset: + max_eval = min(data_args.max_eval_samples, len(dataset["validation"])) + dataset["validation"] = dataset["validation"].select(range(max_eval)) + logger.info(f"Truncated validation set to {max_eval} samples") + + # --- Load model & image processor --- + common_pretrained_args = { + "cache_dir": model_args.cache_dir, + "revision": model_args.model_revision, + "token": model_args.token, + "trust_remote_code": model_args.trust_remote_code, + } + + config = AutoConfig.from_pretrained( + model_args.config_name or model_args.model_name_or_path, + num_labels=num_labels, + label2id=label2id, + id2label=id2label, + **common_pretrained_args, + ) + + model = AutoModelForImageClassification.from_pretrained( + model_args.model_name_or_path, + config=config, + ignore_mismatched_sizes=model_args.ignore_mismatched_sizes, + **common_pretrained_args, + ) + + image_processor = AutoImageProcessor.from_pretrained( + model_args.image_processor_name or model_args.model_name_or_path, + **common_pretrained_args, + ) + + # --- Build transforms --- + train_transforms = build_transforms(image_processor, is_training=True) + val_transforms = build_transforms(image_processor, is_training=False) + + image_col = data_args.image_column_name + + def preprocess_train(examples): + return { + "pixel_values": [train_transforms(img.convert("RGB")) for img in examples[image_col]], + "labels": examples[label_col], + } + + def preprocess_val(examples): + return { + "pixel_values": [val_transforms(img.convert("RGB")) for img in examples[image_col]], + "labels": examples[label_col], + } + + dataset["train"].set_transform(preprocess_train) + if "validation" in dataset: + dataset["validation"].set_transform(preprocess_val) + if "test" in dataset: + dataset["test"].set_transform(preprocess_val) + + # --- Metrics --- + accuracy_metric = evaluate.load("accuracy") + + def compute_metrics(eval_pred: EvalPrediction): + predictions = np.argmax(eval_pred.predictions, axis=1) + return accuracy_metric.compute(predictions=predictions, references=eval_pred.label_ids) + + # --- Trainer --- + eval_dataset = None + if training_args.do_eval: + if "validation" in dataset: + eval_dataset = dataset["validation"] + elif "test" in dataset: + eval_dataset = dataset["test"] + + trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"] if training_args.do_train else None, + eval_dataset=eval_dataset, + processing_class=image_processor, + data_collator=DefaultDataCollator(), + compute_metrics=compute_metrics, + ) + + # --- Train --- + if training_args.do_train: + train_result = trainer.train(resume_from_checkpoint=training_args.resume_from_checkpoint) + trainer.save_model() + trainer.log_metrics("train", train_result.metrics) + trainer.save_metrics("train", train_result.metrics) + trainer.save_state() + + # --- Evaluate --- + if training_args.do_eval: + test_dataset = dataset.get("test", dataset.get("validation")) + test_prefix = "test" if "test" in dataset else "eval" + if test_dataset is not None: + metrics = trainer.evaluate(eval_dataset=test_dataset, metric_key_prefix=test_prefix) + trainer.log_metrics(test_prefix, metrics) + trainer.save_metrics(test_prefix, metrics) + + trackio.finish() + + # --- Push to Hub --- + kwargs = { + "finetuned_from": model_args.model_name_or_path, + "dataset": data_args.dataset_name, + "tags": ["image-classification", "vision"], + } + if training_args.push_to_hub: + trainer.push_to_hub(**kwargs) + else: + trainer.create_model_card(**kwargs) + + +if __name__ == "__main__": + main() diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/object_detection_training.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/object_detection_training.py new file mode 100644 index 0000000000000000000000000000000000000000..63345332e8890b00134f48fbb29dc0b37f65290d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/object_detection_training.py @@ -0,0 +1,710 @@ +# /// script +# dependencies = [ +# "transformers>=5.2.0", +# "accelerate>=1.1.0", +# "albumentations >= 1.4.16", +# "timm", +# "datasets>=4.0", +# "torchmetrics", +# "pycocotools", +# "trackio", +# "huggingface_hub", +# ] +# /// + +"""Finetuning any 🤗 Transformers model supported by AutoModelForObjectDetection for object detection leveraging the Trainer API.""" + +import logging +import math +import os +import sys +from collections.abc import Mapping +from dataclasses import dataclass, field +from functools import partial +from typing import Any + +import albumentations as A +import numpy as np +import torch +from datasets import load_dataset +from torchmetrics.detection.mean_ap import MeanAveragePrecision + +import trackio + +import transformers +from transformers import ( + AutoConfig, + AutoImageProcessor, + AutoModelForObjectDetection, + HfArgumentParser, + Trainer, + TrainingArguments, +) +from transformers.image_processing_utils import BatchFeature +from transformers.image_transforms import center_to_corners_format +from transformers.trainer import EvalPrediction +from transformers.utils import check_min_version +from transformers.utils.versions import require_version + + +logger = logging.getLogger(__name__) + +# Will error if the minimal version of Transformers is not installed. Remove at your own risks. +check_min_version("4.57.0.dev0") + +require_version("datasets>=2.0.0", "To fix: pip install -r examples/pytorch/object-detection/requirements.txt") + + +@dataclass +class ModelOutput: + logits: torch.Tensor + pred_boxes: torch.Tensor + + +def format_image_annotations_as_coco( + image_id: str, categories: list[int], areas: list[float], bboxes: list[tuple[float]] +) -> dict: + """Format one set of image annotations to the COCO format + + Args: + image_id (str): image id. e.g. "0001" + categories (list[int]): list of categories/class labels corresponding to provided bounding boxes + areas (list[float]): list of corresponding areas to provided bounding boxes + bboxes (list[tuple[float]]): list of bounding boxes provided in COCO format + ([center_x, center_y, width, height] in absolute coordinates) + + Returns: + dict: { + "image_id": image id, + "annotations": list of formatted annotations + } + """ + annotations = [] + for category, area, bbox in zip(categories, areas, bboxes): + formatted_annotation = { + "image_id": image_id, + "category_id": category, + "iscrowd": 0, + "area": area, + "bbox": list(bbox), + } + annotations.append(formatted_annotation) + + return { + "image_id": image_id, + "annotations": annotations, + } + + +def detect_bbox_format_from_samples(dataset, image_col="image", objects_col="objects", num_samples=50): + """ + Detect whether bboxes are xyxy (Pascal VOC) or xywh (COCO) by checking + bbox coordinates against image dimensions. The correct format interpretation + should keep bboxes within image bounds. + """ + exceeds_if_xywh = 0 + exceeds_if_xyxy = 0 + total = 0 + + for example in dataset.select(range(min(num_samples, len(dataset)))): + img_w, img_h = example[image_col].size + for bbox in example[objects_col]["bbox"]: + if len(bbox) != 4: + continue + a, b, c, d = float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3]) + total += 1 + + # If 3rd < 1st or 4th < 2nd, can't be xyxy (x_max must exceed x_min) + if c < a or d < b: + return "xywh" + + # xywh: right/bottom edge = origin + size; exceeding image → wrong format + if a + c > img_w * 1.05: + exceeds_if_xywh += 1 + if b + d > img_h * 1.05: + exceeds_if_xywh += 1 + # xyxy: right/bottom edge = coordinate itself + if c > img_w * 1.05: + exceeds_if_xyxy += 1 + if d > img_h * 1.05: + exceeds_if_xyxy += 1 + + if total == 0: + return "xywh" + + fmt = "xyxy" if exceeds_if_xywh > exceeds_if_xyxy else "xywh" + logger.info( + f"Detected bbox format: {fmt} (checked {total} bboxes from {min(num_samples, len(dataset))} images)" + ) + return fmt + + +def sanitize_dataset(dataset, bbox_format="xywh", image_col="image", objects_col="objects"): + """ + Validate bboxes, convert xyxy→xywh if needed, clip to image bounds, and remove + entries with non-finite values, non-positive dimensions, or degenerate area (<1 px). + Drops images with no remaining valid bboxes. + """ + convert_xyxy = bbox_format == "xyxy" + + def _validate(example): + img_w, img_h = example[image_col].size + objects = example[objects_col] + bboxes = objects["bbox"] + n = len(bboxes) + + valid_indices = [] + converted_bboxes = [] + + for i, bbox in enumerate(bboxes): + if len(bbox) != 4: + continue + vals = [float(v) for v in bbox] + if not all(math.isfinite(v) for v in vals): + continue + + if convert_xyxy: + x_min, y_min, x_max, y_max = vals + w, h = x_max - x_min, y_max - y_min + else: + x_min, y_min, w, h = vals + + if w <= 0 or h <= 0: + continue + + x_min, y_min = max(0.0, x_min), max(0.0, y_min) + if x_min >= img_w or y_min >= img_h: + continue + w = min(w, img_w - x_min) + h = min(h, img_h - y_min) + + if w * h < 1.0: + continue + + valid_indices.append(i) + converted_bboxes.append([x_min, y_min, w, h]) + + # Rebuild objects dict, filtering all list-valued fields by valid_indices + new_objects = {} + for key, value in objects.items(): + if key == "bbox": + new_objects["bbox"] = converted_bboxes + elif isinstance(value, list) and len(value) == n: + new_objects[key] = [value[j] for j in valid_indices] + else: + new_objects[key] = value + + if "area" not in new_objects or len(new_objects.get("area", [])) != len(converted_bboxes): + new_objects["area"] = [b[2] * b[3] for b in converted_bboxes] + + example[objects_col] = new_objects + return example + + before = len(dataset) + dataset = dataset.map(_validate) + dataset = dataset.filter(lambda ex: len(ex[objects_col]["bbox"]) > 0) + after = len(dataset) + if before != after: + logger.warning(f"Dropped {before - after}/{before} images with no valid bboxes after sanitization") + logger.info(f"Bbox sanitization complete: {after} images with valid bboxes remain") + return dataset + + +def convert_bbox_yolo_to_pascal(boxes: torch.Tensor, image_size: tuple[int, int]) -> torch.Tensor: + """ + Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1] + to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates. + + Args: + boxes (torch.Tensor): Bounding boxes in YOLO format + image_size (tuple[int, int]): Image size in format (height, width) + + Returns: + torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max) + """ + # convert center to corners format + boxes = center_to_corners_format(boxes) + + + if isinstance(image_size, torch.Tensor): + image_size = image_size.tolist() + elif isinstance(image_size, np.ndarray): + image_size = image_size.tolist() + height, width = image_size + boxes = boxes * torch.tensor([[width, height, width, height]]) + + return boxes + + +def augment_and_transform_batch( + examples: Mapping[str, Any], + transform: A.Compose, + image_processor: AutoImageProcessor, + return_pixel_mask: bool = False, +) -> BatchFeature: + """Apply augmentations and format annotations in COCO format for object detection task""" + + images = [] + annotations = [] + image_ids = examples["image_id"] if "image_id" in examples else range(len(examples["image"])) + for image_id, image, objects in zip(image_ids, examples["image"], examples["objects"]): + image = np.array(image.convert("RGB")) + + # Filter invalid bboxes before augmentation (safety net after sanitize_dataset) + bboxes = objects["bbox"] + categories = objects["category"] + areas = objects["area"] + valid = [ + (b, c, a) + for b, c, a in zip(bboxes, categories, areas) + if len(b) == 4 and b[2] > 0 and b[3] > 0 and b[0] >= 0 and b[1] >= 0 + ] + if valid: + bboxes, categories, areas = zip(*valid) + else: + bboxes, categories, areas = [], [], [] + + # apply augmentations + output = transform(image=image, bboxes=list(bboxes), category=list(categories)) + images.append(output["image"]) + + # format annotations in COCO format (recompute areas from post-augmentation bboxes) + post_areas = [b[2] * b[3] for b in output["bboxes"]] if output["bboxes"] else [] + formatted_annotations = format_image_annotations_as_coco( + image_id, output["category"], post_areas, output["bboxes"] + ) + annotations.append(formatted_annotations) + + # Apply the image processor transformations: resizing, rescaling, normalization + result = image_processor(images=images, annotations=annotations, return_tensors="pt") + + if not return_pixel_mask: + result.pop("pixel_mask", None) + + return result + + +def collate_fn(batch: list[BatchFeature]) -> Mapping[str, torch.Tensor | list[Any]]: + data = {} + data["pixel_values"] = torch.stack([x["pixel_values"] for x in batch]) + data["labels"] = [x["labels"] for x in batch] + if "pixel_mask" in batch[0]: + data["pixel_mask"] = torch.stack([x["pixel_mask"] for x in batch]) + return data + + +@torch.no_grad() +def compute_metrics( + evaluation_results: EvalPrediction, + image_processor: AutoImageProcessor, + threshold: float = 0.0, + id2label: Mapping[int, str] | None = None, +) -> Mapping[str, float]: + """ + Compute mean average mAP, mAR and their variants for the object detection task. + + Args: + evaluation_results (EvalPrediction): Predictions and targets from evaluation. + threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0. + id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None. + + Returns: + Mapping[str, float]: Metrics in a form of dictionary {: } + """ + + predictions, targets = evaluation_results.predictions, evaluation_results.label_ids + + # For metric computation we need to provide: + # - targets in a form of list of dictionaries with keys "boxes", "labels" + # - predictions in a form of list of dictionaries with keys "boxes", "scores", "labels" + + image_sizes = [] + post_processed_targets = [] + post_processed_predictions = [] + + # Collect targets in the required format for metric computation + for batch in targets: + # collect image sizes, we will need them for predictions post processing + batch_image_sizes = torch.tensor([x["orig_size"] for x in batch]) + image_sizes.append(batch_image_sizes) + # collect targets in the required format for metric computation + # boxes were converted to YOLO format needed for model training + # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max) + for image_target in batch: + boxes = torch.tensor(image_target["boxes"]) + boxes = convert_bbox_yolo_to_pascal(boxes, image_target["orig_size"]) + labels = torch.tensor(image_target["class_labels"]) + post_processed_targets.append({"boxes": boxes, "labels": labels}) + + # Collect predictions in the required format for metric computation, + # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format + for batch, target_sizes in zip(predictions, image_sizes): + batch_logits, batch_boxes = batch[1], batch[2] + output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes)) + post_processed_output = image_processor.post_process_object_detection( + output, threshold=threshold, target_sizes=target_sizes + ) + post_processed_predictions.extend(post_processed_output) + + # Compute metrics + metric = MeanAveragePrecision(box_format="xyxy", class_metrics=True) + metric.update(post_processed_predictions, post_processed_targets) + metrics = metric.compute() + + # Replace list of per class metrics with separate metric for each class + classes = metrics.pop("classes") + map_per_class = metrics.pop("map_per_class") + mar_100_per_class = metrics.pop("mar_100_per_class") + # Single-class datasets return 0-d scalar tensors; make them iterable + if classes.dim() == 0: + classes = classes.unsqueeze(0) + map_per_class = map_per_class.unsqueeze(0) + mar_100_per_class = mar_100_per_class.unsqueeze(0) + for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class): + class_name = id2label[class_id.item()] if id2label is not None else class_id.item() + metrics[f"map_{class_name}"] = class_map + metrics[f"mar_100_{class_name}"] = class_mar + + metrics = {k: round(v.item(), 4) for k, v in metrics.items()} + + return metrics + + +@dataclass +class DataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify + them on the command line. + """ + + dataset_name: str = field( + default="cppe-5", + metadata={ + "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)." + }, + ) + dataset_config_name: str | None = field( + default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} + ) + train_val_split: float | None = field( + default=0.15, metadata={"help": "Percent to split off of train for validation."} + ) + image_square_size: int | None = field( + default=600, + metadata={"help": "Image longest size will be resized to this value, then image will be padded to square."}, + ) + max_train_samples: int | None = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of training examples to this " + "value if set." + ) + }, + ) + max_eval_samples: int | None = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of evaluation examples to this " + "value if set." + ) + }, + ) + use_fast: bool | None = field( + default=True, + metadata={"help": "Use a fast torchvision-base image processor if it is supported for a given model."}, + ) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. + """ + + model_name_or_path: str = field( + default="facebook/detr-resnet-50", + metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}, + ) + config_name: str | None = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + cache_dir: str | None = field( + default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} + ) + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + ) + image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."}) + ignore_mismatched_sizes: bool = field( + default=True, + metadata={ + "help": "Whether or not to raise an error if some of the weights from the checkpoint do not have the same size as the weights of the model (if for instance, you are instantiating a model with 10 labels from a checkpoint with 3 labels)." + }, + ) + token: str = field( + default=None, + metadata={ + "help": ( + "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token " + "generated when running `hf auth login` (stored in `~/.huggingface`)." + ) + }, + ) + trust_remote_code: bool = field( + default=False, + metadata={ + "help": ( + "Whether to trust the execution of code from datasets/models defined on the Hub." + " This option should only be set to `True` for repositories you trust and in which you have read the" + " code, as it will execute code present on the Hub on your local machine." + ) + }, + ) + + +def main(): + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + + from huggingface_hub import login + hf_token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob") + if hf_token: + login(token=hf_token) + training_args.hub_token = hf_token + logger.info("Logged in to Hugging Face Hub") + elif training_args.push_to_hub: + logger.warning("HF_TOKEN not found in environment. Hub push will likely fail.") + + # Initialize Trackio for real-time experiment tracking + trackio.init(project=training_args.output_dir, name=training_args.run_name) + + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + + if training_args.should_log: + # The default of training_args.log_level is passive, so we set log level at info here to have that default. + transformers.utils.logging.set_verbosity_info() + + log_level = training_args.get_process_log_level() + logger.setLevel(log_level) + transformers.utils.logging.set_verbosity(log_level) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + # Log on each process the small summary: + logger.warning( + f"Process rank: {training_args.local_process_index}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " + + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}" + ) + logger.info(f"Training/evaluation parameters {training_args}") + + dataset = load_dataset( + data_args.dataset_name, cache_dir=model_args.cache_dir, trust_remote_code=model_args.trust_remote_code + ) + + bbox_format = detect_bbox_format_from_samples(dataset["train"]) + if bbox_format == "xyxy": + logger.info("Converting bboxes from xyxy (Pascal VOC) → xywh (COCO) format across all splits") + for split_name in list(dataset.keys()): + dataset[split_name] = sanitize_dataset(dataset[split_name], bbox_format=bbox_format) + + for split_name in list(dataset.keys()): + if "image_id" not in dataset[split_name].column_names: + dataset[split_name] = dataset[split_name].add_column( + "image_id", list(range(len(dataset[split_name]))) + ) + + dataset["train"] = dataset["train"].shuffle(seed=training_args.seed) + + data_args.train_val_split = None if "validation" in dataset else data_args.train_val_split + if isinstance(data_args.train_val_split, float) and data_args.train_val_split > 0.0: + split = dataset["train"].train_test_split(data_args.train_val_split, seed=training_args.seed) + dataset["train"] = split["train"] + dataset["validation"] = split["test"] + + categories = None + try: + if isinstance(dataset["train"].features["objects"], dict): + cat_feature = dataset["train"].features["objects"]["category"].feature + else: + cat_feature = dataset["train"].features["objects"].feature["category"] + + if hasattr(cat_feature, "names"): + categories = cat_feature.names + except (AttributeError, KeyError): + pass + + if categories is None: + # Category is a Value type (not ClassLabel) — scan dataset to discover labels + logger.info("Category feature is not ClassLabel — scanning dataset to discover category labels...") + unique_cats = set() + for example in dataset["train"]: + cats = example["objects"]["category"] + if isinstance(cats, list): + unique_cats.update(cats) + else: + unique_cats.add(cats) + + if all(isinstance(c, int) for c in unique_cats): + max_cat = max(unique_cats) + categories = [f"class_{i}" for i in range(max_cat + 1)] + elif all(isinstance(c, str) for c in unique_cats): + categories = sorted(unique_cats) + else: + categories = [str(c) for c in sorted(unique_cats, key=str)] + logger.info(f"Discovered {len(categories)} categories: {categories}") + + id2label = dict(enumerate(categories)) + label2id = {v: k for k, v in id2label.items()} + + # Remap string categories to integer IDs if needed + sample_cats = dataset["train"][0]["objects"]["category"] + if sample_cats and isinstance(sample_cats[0], str): + logger.info(f"Remapping string categories to integer IDs: {label2id}") + + def _remap_categories(example): + objects = example["objects"] + objects["category"] = [label2id[c] for c in objects["category"]] + example["objects"] = objects + return example + + for split_name in list(dataset.keys()): + dataset[split_name] = dataset[split_name].map(_remap_categories) + logger.info("Category remapping complete") + + if data_args.max_train_samples is not None: + max_train = min(data_args.max_train_samples, len(dataset["train"])) + dataset["train"] = dataset["train"].select(range(max_train)) + logger.info(f"Truncated training set to {max_train} samples") + if data_args.max_eval_samples is not None and "validation" in dataset: + max_eval = min(data_args.max_eval_samples, len(dataset["validation"])) + dataset["validation"] = dataset["validation"].select(range(max_eval)) + logger.info(f"Truncated validation set to {max_eval} samples") + + common_pretrained_args = { + "cache_dir": model_args.cache_dir, + "revision": model_args.model_revision, + "token": model_args.token, + "trust_remote_code": model_args.trust_remote_code, + } + config = AutoConfig.from_pretrained( + model_args.config_name or model_args.model_name_or_path, + label2id=label2id, + id2label=id2label, + **common_pretrained_args, + ) + model = AutoModelForObjectDetection.from_pretrained( + model_args.model_name_or_path, + config=config, + ignore_mismatched_sizes=model_args.ignore_mismatched_sizes, + **common_pretrained_args, + ) + image_processor = AutoImageProcessor.from_pretrained( + model_args.image_processor_name or model_args.model_name_or_path, + do_resize=True, + size={"max_height": data_args.image_square_size, "max_width": data_args.image_square_size}, + do_pad=True, + pad_size={"height": data_args.image_square_size, "width": data_args.image_square_size}, + use_fast=data_args.use_fast, + **common_pretrained_args, + ) + + max_size = data_args.image_square_size + train_augment_and_transform = A.Compose( + [ + A.Compose( + [ + A.SmallestMaxSize(max_size=max_size, p=1.0), + A.RandomSizedBBoxSafeCrop(height=max_size, width=max_size, p=1.0), + ], + p=0.2, + ), + A.OneOf( + [ + A.Blur(blur_limit=7, p=0.5), + A.MotionBlur(blur_limit=7, p=0.5), + A.Defocus(radius=(1, 5), alias_blur=(0.1, 0.25), p=0.1), + ], + p=0.1, + ), + A.Perspective(p=0.1), + A.HorizontalFlip(p=0.5), + A.RandomBrightnessContrast(p=0.5), + A.HueSaturationValue(p=0.1), + ], + bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True, min_area=25), + ) + validation_transform = A.Compose( + [A.NoOp()], + bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True), + ) + + train_transform_batch = partial( + augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor + ) + validation_transform_batch = partial( + augment_and_transform_batch, transform=validation_transform, image_processor=image_processor + ) + + dataset["train"] = dataset["train"].with_transform(train_transform_batch) + dataset["validation"] = dataset["validation"].with_transform(validation_transform_batch) + if "test" in dataset: + dataset["test"] = dataset["test"].with_transform(validation_transform_batch) + + + eval_compute_metrics_fn = partial( + compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0 + ) + + trainer = Trainer( + model=model, + args=training_args, + train_dataset=dataset["train"] if training_args.do_train else None, + eval_dataset=dataset["validation"] if training_args.do_eval else None, + processing_class=image_processor, + data_collator=collate_fn, + compute_metrics=eval_compute_metrics_fn, + ) + + # Training + if training_args.do_train: + train_result = trainer.train(resume_from_checkpoint=training_args.resume_from_checkpoint) + trainer.save_model() + trainer.log_metrics("train", train_result.metrics) + trainer.save_metrics("train", train_result.metrics) + trainer.save_state() + + if training_args.do_eval: + test_dataset = dataset["test"] if "test" in dataset else dataset["validation"] + test_prefix = "test" if "test" in dataset else "eval" + metrics = trainer.evaluate(eval_dataset=test_dataset, metric_key_prefix=test_prefix) + trainer.log_metrics(test_prefix, metrics) + trainer.save_metrics(test_prefix, metrics) + + trackio.finish() + + kwargs = { + "finetuned_from": model_args.model_name_or_path, + "dataset": data_args.dataset_name, + "tags": ["object-detection", "vision"], + } + if training_args.push_to_hub: + trainer.push_to_hub(**kwargs) + else: + trainer.create_model_card(**kwargs) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/sam_segmentation_training.py b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/sam_segmentation_training.py new file mode 100644 index 0000000000000000000000000000000000000000..0b544db52f1b5c31a4c14cfa1b5bbec8e54d2c21 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/hugging-face/skills/vision-trainer/scripts/sam_segmentation_training.py @@ -0,0 +1,382 @@ +# /// script +# dependencies = [ +# "transformers>=5.2.0", +# "accelerate>=1.1.0", +# "datasets>=4.0", +# "torchvision", +# "monai", +# "trackio", +# "huggingface_hub", +# ] +# /// + +"""Fine-tune SAM or SAM2 for segmentation using bounding-box or point prompts with the HF Trainer API.""" + +import json +import logging +import math +import os +import sys +from dataclasses import dataclass, field +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F +from datasets import load_dataset +from torch.utils.data import Dataset + +import monai +import trackio + +import transformers +from transformers import ( + HfArgumentParser, + Trainer, + TrainingArguments, +) +from transformers.utils import check_min_version + +logger = logging.getLogger(__name__) + +check_min_version("4.57.0.dev0") + + +# --------------------------------------------------------------------------- +# Dataset wrapper +# --------------------------------------------------------------------------- + +class SAMSegmentationDataset(Dataset): + """Wraps a HF dataset into the format expected by SAM/SAM2 processors. + + Each sample must contain an image, a binary mask, and a prompt (bbox or + point). Prompts are read from a JSON-encoded ``prompt`` column or from + dedicated ``bbox`` / ``point`` columns. + """ + + def __init__(self, dataset, processor, prompt_type: str, + image_col: str, mask_col: str, prompt_col: str | None, + bbox_col: str | None, point_col: str | None): + self.dataset = dataset + self.processor = processor + self.prompt_type = prompt_type + self.image_col = image_col + self.mask_col = mask_col + self.prompt_col = prompt_col + self.bbox_col = bbox_col + self.point_col = point_col + + def __len__(self): + return len(self.dataset) + + def _extract_prompt(self, item): + if self.prompt_col and self.prompt_col in item: + raw = item[self.prompt_col] + parsed = json.loads(raw) if isinstance(raw, str) else raw + if self.prompt_type == "bbox": + return parsed.get("bbox") or parsed.get("box") + return parsed.get("point") or parsed.get("points") + + if self.prompt_type == "bbox" and self.bbox_col: + return item[self.bbox_col] + if self.prompt_type == "point" and self.point_col: + return item[self.point_col] + raise ValueError("Could not extract prompt from sample") + + def __getitem__(self, idx): + item = self.dataset[idx] + image = item[self.image_col] + prompt = self._extract_prompt(item) + + if self.prompt_type == "bbox": + inputs = self.processor(image, input_boxes=[[prompt]], return_tensors="pt") + else: + if isinstance(prompt[0], (int, float)): + prompt = [prompt] + inputs = self.processor(image, input_points=[[prompt]], return_tensors="pt") + + mask = np.array(item[self.mask_col]) + if mask.ndim == 3: + mask = mask[:, :, 0] + inputs["labels"] = (mask > 0).astype(np.float32) + inputs["original_image_size"] = torch.tensor(image.size[::-1]) + return inputs + + +def collate_fn(batch): + pixel_values = torch.cat([item["pixel_values"] for item in batch], dim=0) + original_sizes = torch.stack([item["original_sizes"] for item in batch]) + original_image_size = torch.stack([item["original_image_size"] for item in batch]) + + has_boxes = "input_boxes" in batch[0] + has_points = "input_points" in batch[0] + + labels = torch.cat( + [ + F.interpolate( + torch.as_tensor(x["labels"]).unsqueeze(0).unsqueeze(0).float(), + size=(256, 256), + mode="nearest", + ) + for x in batch + ], + dim=0, + ).long() + + result = { + "pixel_values": pixel_values, + "original_sizes": original_sizes, + "labels": labels, + "original_image_size": original_image_size, + "multimask_output": False, + } + + if has_boxes: + result["input_boxes"] = torch.cat([item["input_boxes"] for item in batch], dim=0) + if has_points: + result["input_points"] = torch.cat([item["input_points"] for item in batch], dim=0) + if "input_labels" in batch[0]: + result["input_labels"] = torch.cat([item["input_labels"] for item in batch], dim=0) + + return result + + +# --------------------------------------------------------------------------- +# Custom loss (SAM/SAM2 don't compute loss in forward()) +# --------------------------------------------------------------------------- + +seg_loss = monai.losses.DiceCELoss(sigmoid=True, squared_pred=True, reduction="mean") + + +def compute_loss(outputs, labels, num_items_in_batch=None): + predicted_masks = outputs.pred_masks.squeeze(1) + return seg_loss(predicted_masks, labels.float()) + + +# --------------------------------------------------------------------------- +# CLI arguments +# --------------------------------------------------------------------------- + +@dataclass +class DataTrainingArguments: + dataset_name: str = field( + default="merve/MicroMat-mini", + metadata={"help": "Hub dataset ID."}, + ) + dataset_config_name: str | None = field( + default=None, + metadata={"help": "Dataset config name."}, + ) + train_val_split: float | None = field( + default=0.1, + metadata={"help": "Fraction to split off for validation (used when no validation split exists)."}, + ) + max_train_samples: int | None = field( + default=None, + metadata={"help": "Truncate training set (for quick tests)."}, + ) + max_eval_samples: int | None = field( + default=None, + metadata={"help": "Truncate evaluation set."}, + ) + image_column_name: str = field( + default="image", + metadata={"help": "Column containing PIL images."}, + ) + mask_column_name: str = field( + default="mask", + metadata={"help": "Column containing ground-truth binary masks."}, + ) + prompt_column_name: str | None = field( + default="prompt", + metadata={"help": "Column with JSON-encoded prompt (bbox/point). Set to '' to disable."}, + ) + bbox_column_name: str | None = field( + default=None, + metadata={"help": "Column with bbox prompt ([x0,y0,x1,y1]). Used when prompt_column_name is unset."}, + ) + point_column_name: str | None = field( + default=None, + metadata={"help": "Column with point prompt ([x,y] or [[x,y],...]). Used when prompt_column_name is unset."}, + ) + prompt_type: str = field( + default="bbox", + metadata={"help": "Prompt type: 'bbox' or 'point'."}, + ) + + +@dataclass +class ModelArguments: + model_name_or_path: str = field( + default="facebook/sam2.1-hiera-small", + metadata={"help": "Pretrained SAM/SAM2 model identifier."}, + ) + cache_dir: str | None = field(default=None, metadata={"help": "Cache directory."}) + model_revision: str = field(default="main", metadata={"help": "Model revision."}) + token: str | None = field(default=None, metadata={"help": "Auth token."}) + trust_remote_code: bool = field(default=False, metadata={"help": "Trust remote code."}) + freeze_vision_encoder: bool = field( + default=True, + metadata={"help": "Freeze vision encoder weights."}, + ) + freeze_prompt_encoder: bool = field( + default=True, + metadata={"help": "Freeze prompt encoder weights."}, + ) + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def main(): + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) + parser.set_defaults(per_device_train_batch_size=4, num_train_epochs=30) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + model_args, data_args, training_args = parser.parse_json_file( + json_file=os.path.abspath(sys.argv[1]) + ) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + from huggingface_hub import login + hf_token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob") + if hf_token: + login(token=hf_token) + training_args.hub_token = hf_token + logger.info("Logged in to Hugging Face Hub") + elif training_args.push_to_hub: + logger.warning("HF_TOKEN not found in environment. Hub push will likely fail.") + + trackio.init(project=training_args.output_dir, name=training_args.run_name) + + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + if training_args.should_log: + transformers.utils.logging.set_verbosity_info() + + log_level = training_args.get_process_log_level() + logger.setLevel(log_level) + transformers.utils.logging.set_verbosity(log_level) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + logger.info(f"Training/evaluation parameters {training_args}") + + # ---- Load dataset ---- + dataset = load_dataset( + data_args.dataset_name, + data_args.dataset_config_name, + cache_dir=model_args.cache_dir, + trust_remote_code=model_args.trust_remote_code, + ) + + if "train" not in dataset: + if len(dataset.keys()) == 1: + only_split = list(dataset.keys())[0] + dataset[only_split] = dataset[only_split].shuffle(seed=training_args.seed) + dataset = dataset[only_split].train_test_split(test_size=data_args.train_val_split or 0.1) + dataset = {"train": dataset["train"], "validation": dataset["test"]} + else: + raise ValueError(f"No 'train' split found. Available: {list(dataset.keys())}") + elif "validation" not in dataset and "test" not in dataset: + dataset["train"] = dataset["train"].shuffle(seed=training_args.seed) + split = dataset["train"].train_test_split( + test_size=data_args.train_val_split or 0.1, seed=training_args.seed + ) + dataset["train"] = split["train"] + dataset["validation"] = split["test"] + + if data_args.max_train_samples is not None: + n = min(data_args.max_train_samples, len(dataset["train"])) + dataset["train"] = dataset["train"].select(range(n)) + logger.info(f"Truncated training set to {n} samples") + eval_key = "validation" if "validation" in dataset else "test" + if data_args.max_eval_samples is not None and eval_key in dataset: + n = min(data_args.max_eval_samples, len(dataset[eval_key])) + dataset[eval_key] = dataset[eval_key].select(range(n)) + logger.info(f"Truncated eval set to {n} samples") + + # ---- Detect model family (SAM vs SAM2) and load processor/model ---- + model_id = model_args.model_name_or_path.lower() + is_sam2 = "sam2" in model_id + + if is_sam2: + from transformers import Sam2Processor, Sam2Model + processor = Sam2Processor.from_pretrained(model_args.model_name_or_path) + model = Sam2Model.from_pretrained(model_args.model_name_or_path) + else: + from transformers import SamProcessor, SamModel + processor = SamProcessor.from_pretrained(model_args.model_name_or_path) + model = SamModel.from_pretrained(model_args.model_name_or_path) + + if model_args.freeze_vision_encoder: + for name, param in model.named_parameters(): + if name.startswith("vision_encoder"): + param.requires_grad_(False) + if model_args.freeze_prompt_encoder: + for name, param in model.named_parameters(): + if name.startswith("prompt_encoder"): + param.requires_grad_(False) + + trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) + total = sum(p.numel() for p in model.parameters()) + logger.info(f"Trainable params: {trainable:,} / {total:,} ({100 * trainable / total:.1f}%)") + + # ---- Build datasets ---- + prompt_col = data_args.prompt_column_name if data_args.prompt_column_name else None + ds_kwargs = dict( + processor=processor, + prompt_type=data_args.prompt_type, + image_col=data_args.image_column_name, + mask_col=data_args.mask_column_name, + prompt_col=prompt_col, + bbox_col=data_args.bbox_column_name, + point_col=data_args.point_column_name, + ) + + train_dataset = SAMSegmentationDataset(dataset=dataset["train"], **ds_kwargs) + eval_dataset = None + if eval_key in dataset: + eval_dataset = SAMSegmentationDataset(dataset=dataset[eval_key], **ds_kwargs) + + # ---- Train ---- + trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset if training_args.do_train else None, + eval_dataset=eval_dataset if training_args.do_eval else None, + data_collator=collate_fn, + compute_loss_func=compute_loss, + ) + + if training_args.do_train: + train_result = trainer.train(resume_from_checkpoint=training_args.resume_from_checkpoint) + trainer.save_model() + trainer.log_metrics("train", train_result.metrics) + trainer.save_metrics("train", train_result.metrics) + trainer.save_state() + + if training_args.do_eval and eval_dataset is not None: + metrics = trainer.evaluate() + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + trackio.finish() + + kwargs = { + "finetuned_from": model_args.model_name_or_path, + "dataset": data_args.dataset_name, + "tags": ["image-segmentation", "vision", "sam"], + } + if training_args.push_to_hub: + trainer.push_to_hub(**kwargs) + else: + trainer.create_model_card(**kwargs) + + +if __name__ == "__main__": + main() diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..cf4f3428a3f49361e766bafe77205fea100e94d3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/.codex-plugin/plugin.json @@ -0,0 +1,43 @@ +{ + "name": "outlook-calendar", + "version": "0.1.3", + "description": "Connect Outlook Calendar for scheduling, daily briefs, event prep, and safe meeting changes.", + "author": { + "name": "OpenAI", + "email": "support@openai.com", + "url": "https://openai.com/" + }, + "homepage": "https://www.microsoft.com/en-us/microsoft-365/outlook/calendar-app", + "repository": "https://github.com/openai/plugins", + "license": "MIT", + "keywords": [ + "outlook-calendar", + "calendar", + "microsoft", + "scheduling", + "teams", + "daily-brief", + "meeting-prep" + ], + "skills": "./skills/", + "apps": "./.app.json", + "interface": { + "displayName": "Outlook Calendar", + "shortDescription": "Manage Outlook schedules and meeting changes", + "longDescription": "Use Outlook Calendar to summarize a day, compare availability, prepare for meetings, explain Outlook status semantics, and schedule, reschedule, or cancel events through the connected Microsoft Outlook app.", + "developerName": "OpenAI", + "category": "Productivity", + "capabilities": [ + "Interactive", + "Write" + ], + "websiteURL": "https://www.microsoft.com/en-us/microsoft-365/outlook/calendar-app", + "privacyPolicyURL": "https://www.microsoft.com/en-us/privacy/privacystatement", + "termsOfServiceURL": "https://www.microsoft.com/en-us/servicesagreement/", + "defaultPrompt": "Summarize my day, compare availability, explain Outlook status, and draft the right event update", + "brandColor": "#0078D4", + "composerIcon": "./assets/logo.png", + "logo": "./assets/logo.png", + "screenshots": [] + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-daily-brief/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-daily-brief/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..d376a45f43d6587f1688e98b9c580b2936e2c965 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-daily-brief/SKILL.md @@ -0,0 +1,74 @@ +--- +name: outlook-calendar-daily-brief +description: Build polished one-day Outlook Calendar briefs. Use when the user asks for today, tomorrow, or a specific date summary with an agenda, conflict flags, free windows, remaining-meeting readouts, or a calendar brief, and Outlook Calendar is available. +--- + +# Outlook Calendar Daily Brief + +Use this skill to turn one day of Outlook Calendar events into a readable brief rather than a raw event dump. + +## Relevant Actions + +- Prefer `list_events` with explicit start and end datetimes for the day window. +- Use `fetch_event` or `fetch_events_batch` only if the brief needs fuller event details than the list surface returns. +- Use `find_available_slots` only when the user explicitly wants concrete free windows after buffers. + +## Workflow + +1. Resolve the day window explicitly in the user's mailbox timezone if it is known, otherwise in the user's stated timezone. +2. Use the Outlook Calendar connector's `list_events` action for the day window and relevant calendar. Default to the primary personal calendar unless the user names a different one. +3. Build the brief around the actual workday shape, not just a chronological list. +4. Separate real meetings from lightweight holds, travel buffers, or transparent blocks before writing the brief. +5. Distinguish true busy time from `Tentative`, `Free`, `Out of Office`, or `Working Elsewhere` blocks when the source data exposes those statuses. +6. If the day has meaningful work-location or out-of-office context, mention it near the top because Outlook users often use that information to interpret the schedule. +7. Call out overlaps, compressed transitions, overloaded stretches, and any meaningful remaining free windows. +8. When shared-calendar visibility is partial, say that clearly instead of implying the agenda is complete. +9. Return a brief that reads like a schedule understanding aid, not a raw connector dump. + +## Data Source Rules + +- Use the Outlook Calendar connector from this plugin, not web search and not a manually reconstructed schedule. +- Query with explicit day boundaries such as `[local_midnight, next_local_midnight)` in the user's timezone. +- Preserve titles exactly as returned by Outlook Calendar. +- If the connector only exposes busy windows for a calendar, build the brief around availability patterns and say that event-level detail was not available. + +## Output Contract + +Render the brief in this order: + +1. `**Weekday, Month Day**` +2. Up to four short summary lines with restrained markers: + - `📍` day marker such as office / travel / PTO when the source data supports it + - `⚠` conflict-zone count + - `🍽` lunch-window note when useful + - `🟢` best free windows +3. `**Day Shape**` paragraph +4. `**Agenda**` Markdown table with columns `Time | Meeting` +5. `**What Needs Attention**` only when there are conflicts, dense handoffs, or unusual Outlook-status ambiguity +6. `**Useful Readout**` with 2-4 short bullets +7. `**Remaining Today**` only when the requested day is today and there are future events left + +Keep the tone compact and practical. Do not use a fenced code block for the agenda. + +## Formatting Rules + +- Keep markers restrained. Use only the markers in the output contract unless the user explicitly asks for more decoration. +- Keep the agenda table to two columns only: `Time` and `Meeting`. +- Use compact agenda times and include the timezone in the section header or summary, not on every row. +- Treat all-day status markers such as PTO or OOF as context even when they are not meetings. +- When the source data includes Outlook status, mention it only when it changes the user's real availability. +- Mention work-location or building context only when it affects meeting logistics or how the day should be interpreted. +- Keep overlap explanations in `What Needs Attention`, not inline in every agenda row. +- If the day contains only tentative holds or shared-calendar busy markers, say that plainly. +- If the user is asking about `today`, emphasize what is still upcoming and what may require prep. +- If the user is asking about a future day, emphasize density, conflict zones, large open blocks, and unusual holds. + +## Outlook-Specific Notes + +- `Working Elsewhere` and `Free` should not be treated as the same thing as a hard busy meeting. +- `Tentative` often means the slot may still be usable, but only if the user accepts that ambiguity. +- Shared calendars may expose only free/busy signals, not full titles or notes. + +## Fallback + +If the Outlook Calendar connector is unavailable or returns no events unexpectedly, say that Microsoft Outlook access may be unavailable or scoped to the wrong calendar and ask the user to reconnect or clarify the intended calendar. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-daily-brief/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-daily-brief/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dab9e1083216e88b6273057b4766ff234fac8c9e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-daily-brief/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Daily Brief" + short_description: "Summarize a day into a readable agenda" + default_prompt: "Use $outlook-calendar-daily-brief to summarize my Outlook calendar for today with conflicts and free windows." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-free-up-time/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-free-up-time/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..9aba3d5eedb12bf7d35ca32095ac5ac17ffb6864 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-free-up-time/SKILL.md @@ -0,0 +1,43 @@ +--- +name: outlook-calendar-free-up-time +description: Find ways to open up meaningful free time in Outlook Calendar. Use when the user wants to clear part of their schedule, make room for focus time, create a longer uninterrupted block, or see the smallest set of calendar changes that would give time back. +--- + +# Outlook Calendar Free Up Time + +Use this skill when the goal is to create time, not just inspect time. + +## Relevant Actions + +- Use `list_events` to map the current fragmentation and identify movable candidates. +- Use `fetch_event` when one candidate needs a closer read before proposing a change. +- Use `find_available_slots` to verify whether a better block exists on the user's own calendar. +- Use `get_schedule` before moving attendee-heavy meetings when cross-attendee availability matters. +- Use `update_event` only after the proposal is grounded and the intended event is unambiguous. + +## Workflow + +1. Start by identifying the target: today, tomorrow, this afternoon, a specific day, or a broader window. +2. Optimize for contiguous free blocks, not raw free-minute totals. +3. Identify which meetings are likely fixed and which are more movable before proposing changes. +4. Look for the smallest edit set that creates a meaningful uninterrupted block. +5. Prefer solutions that reduce fragmentation across the rest of the day, not just one local gap. +6. Treat `Tentative`, `Free`, self-created placeholders, and lightly attended internal holds as lower-cost candidates than hard external meetings, accepted commitments, or `Out of Office` blocks. +7. When work hours or work location are relevant, prefer openings that produce a useful block inside the user's actual workday. +8. If no clean block exists, show the best partial win and what tradeoff it requires. + +## Prioritization Heuristics + +- Protect hard anchors such as external meetings, major reviews, commute buffers, and stable lunch windows. +- Move lower-cost meetings first, such as tentative holds, lightweight internal syncs, or self-created placeholders. +- When two meetings are similarly movable, prefer moving a 1:1 over a larger group meeting because it creates less attendee thrash. +- Favor one or two coherent shifts over a chain of many tiny moves. +- Prefer creating one useful block over scattering a few small openings. +- Preserve existing Teams links and attendee lists unless the user wants to change them. +- If a meeting has weak attendee commitment, interpret that in context rather than as a blanket signal. Far-future weak commitment is normal; imminent weak commitment is a much stronger sign that the meeting may be movable or unstable. + +## Output Conventions + +- Show the before-and-after effect of the proposal. +- Name the block created and the minimum meetings that would need to move. +- If suggesting multiple options, keep them short and explain the tradeoff for each. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-free-up-time/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-free-up-time/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..30dab17db0a73422b2dee223668259dc4841ee71 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-free-up-time/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Free Up Time" + short_description: "Create a meaningful block of free time" + default_prompt: "Use $outlook-calendar-free-up-time to find the smallest set of Outlook calendar changes that would open up a meaningful block of time." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-group-scheduler/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-group-scheduler/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..5ccd1feadab816acfe7b452aea448f3901cfd0c6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-group-scheduler/SKILL.md @@ -0,0 +1,48 @@ +--- +name: outlook-calendar-group-scheduler +description: Find and rank good meeting times for several people using Outlook Calendar data. Use when the user wants to schedule a meeting, compare candidate slots across attendees, find the best compromise time, or add a room/resource check after narrowing the attendee-compatible options. +--- + +# Outlook Calendar Group Scheduler + +Use this skill when the scheduling problem is the task. + +## Relevant Actions + +- Use `get_schedule` for attendee and room/resource free-busy windows once you know the concrete schedule identifiers. +- Use `find_available_slots` when the problem is mostly about the user's own calendar and buffered openings. +- Use `search_events` or `list_events` when you need conflict context before ranking options. +- Use `create_event` only after the winning slot and attendee set are settled. + +## Outlook Product Framing + +- Treat free/busy visibility, work hours, and work location as first-class scheduling evidence when full event detail is unavailable. +- Treat attendee response state and organizer logistics as part of scheduling, not just the final event body. +- When rooms or resources are visible, treat them as Outlook-style scheduling constraints rather than a separate "room finder" workflow. + +## Workflow + +1. Ground the scheduling problem first: date window, duration, timezone, required attendees, optional attendees, and any hard constraints such as "this week", "afternoons only", or "avoid lunch". +2. If the scheduling window is ambiguous, assess the meeting stakes before choosing a default search window. For relatively high-stakes meetings, go back to the user and suggest tightening the timeline, for example to the next week. For lower-stakes or more casual group scheduling, default to a near-term search such as the next 1 to 3 weeks. +3. Normalize the request into explicit candidate windows before ranking anything. +4. Rank slots, do not enumerate everything. Optimize for a short list of strong options. +5. Treat `Busy` and `Out of Office` as harder constraints than `Tentative` or `Working Elsewhere` unless the user says otherwise. +6. Prefer slots that minimize conflict cost, fit within work hours, and avoid avoidable hybrid-work friction such as forcing an in-office room meeting onto remote-heavy attendees. +7. When rooms, resources, or building context are available, prefer slots that keep the meeting logistically coherent instead of treating time as the only variable. +8. If shared-calendar visibility is partial, say when a recommendation is based on free/busy signals rather than full event detail. + +## Ranking Heuristics + +- Favor required-attendee fit over optional-attendee fit. +- Favor slots that avoid very early or very late local times for distributed attendees. +- Favor slots that stay inside work hours and avoid consuming the only large free block in someone's day unless the meeting is clearly important. +- Favor a small number of high-confidence options over a long weak list. +- When two slots are similar, prefer the one that causes less calendar fragmentation. +- When one attendee is only `Tentative` or `Working Elsewhere`, describe that as a softer constraint instead of silently treating it as unavailable. +- When one option aligns better with attendees' work locations or room logistics, explain that advantage explicitly. + +## Output Conventions + +- Return 2-4 candidate slots by default. +- For each slot, say why it works and who, if anyone, would be inconvenienced. +- If there is no clean option, say what tradeoff the best slot is making. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-group-scheduler/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-group-scheduler/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4e2743ec995d2ef6b044cea3b1dacca46d0f9f8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-group-scheduler/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Group Scheduler" + short_description: "Rank the best meeting times for several people" + default_prompt: "Use $outlook-calendar-group-scheduler to find and rank the best Outlook meeting times, with clear tradeoffs instead of an exhaustive list." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-meeting-prep/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-meeting-prep/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..031103195157a25cc6d801aa8d950ecde7a904c1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-meeting-prep/SKILL.md @@ -0,0 +1,49 @@ +--- +name: outlook-calendar-meeting-prep +description: Build a practical meeting prep brief from an Outlook Calendar event and its nearby Microsoft context. Use when the user wants to prepare for an upcoming meeting, understand what to read beforehand, pull in linked notes or docs, or get a concise brief on what the meeting appears to require. +--- + +# Outlook Calendar Meeting Prep + +Use this skill when the user wants a prep brief, not just the event details. + +## Relevant Actions + +- Use `fetch_event` for the focal meeting. +- Use `fetch_events_batch` or `search_events` when recurrence history, adjacent meetings, or same-day context matters. +- Use Outlook Email and Microsoft SharePoint tool surfaces when the event clearly points to related mail or docs. + +## Workflow + +1. Start from the event itself: title, description, attendees, response state, recurrence context, Teams details, and any obvious linked materials. +2. If the event points to connected docs, decks, threads, or notes and they are cheap to follow, inspect them before writing the brief. +3. Build the prep brief around what the meeting appears to be for, what decisions or inputs seem likely, and what context is attached versus missing. +4. Highlight what the user should read or prepare first rather than dumping every detail. +5. Stay close to the event and its linked context. Do broader research only if the user explicitly asks for it. +6. If the event comes from a shared calendar with limited detail, say what is confirmed versus what remains opaque. +7. If context gathering, note lookup, or related-event retrieval takes more than 5 minutes, recheck that the target meeting is still upcoming before updating the invite or presenting it as the next meeting. +8. If you write back into the Outlook event description, keep it short: usually one concise agenda block and, at most, one short prep block rather than a long meeting brief. +9. Preserve the event's existing body format when editing. If the event already uses plain text, keep the update plain text unless richer structure is necessary. If you are creating new formatted content with bullets or links, use HTML deliberately rather than mixing rich structure into plain text. + +## Output Conventions + +- Lead with what the meeting appears to be about. +- Call out the most relevant notes, emails, or linked docs. +- Separate confirmed context from missing context or open questions. +- End with a short `What To Do Before This Meeting` list when the evidence supports it. + +## Outlook-Specific Focus + +- Call out whether attendees have accepted, tentatively accepted, declined, or not responded when that changes the prep picture. +- Mention the presence of a Teams meeting link, room resource, or organizer note when those shape logistics. +- Treat organizer notes, response tracking, and last-minute RSVP drift as part of the meeting story, because Outlook users often rely on the invitation itself as the operational source of truth. +- Separate confirmed context from inferred context, especially when the event description is sparse. + +## Output Conventions + +- Lead with what this meeting appears to be about. +- Call out the most relevant notes, attachments, links, or Teams details. +- Separate confirmed context from missing context or open questions. +- End with a short "what to do before this meeting" list when there is enough evidence to support it. +- If updating the invite body, compress the brief aggressively so the description stays readable inside Outlook without scrolling through a long memo. +- If the original invite body already has formatting conventions, match them rather than switching formats midstream. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-meeting-prep/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-meeting-prep/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d50820dc124bb5ea7b87c5bb70f30ab54162231 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-meeting-prep/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Meeting Prep" + short_description: "Turn an event and its context into a prep brief" + default_prompt: "Use $outlook-calendar-meeting-prep to build a concise prep brief from this Outlook calendar event, its notes, related mail, and linked docs." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-shared-calendars/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-shared-calendars/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..78fe5df0a739ef9ba8ffff14e6d412dfde5b5a12 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-shared-calendars/SKILL.md @@ -0,0 +1,48 @@ +--- +name: outlook-calendar-shared-calendars +description: Safely write to delegated or shared Outlook calendars. Use when the user explicitly wants to create, update, respond to, cancel, delete, or add a small attachment to an event on a shared or delegated Outlook Calendar. +--- + +# Outlook Calendar Shared Calendars + +Use this skill for writes on delegated or shared Outlook calendars. These write actions are separate from the signed-in user's own calendar actions on purpose. + +## Required Target + +- Start with `list_calendars` and identify the exact shared or delegated `calendar_id`. +- Use the shared-calendar action names only when the target is a delegated or shared calendar. +- For the signed-in user's own calendar, use the base Outlook Calendar skill and the non-shared event actions. + +## Action Routing + +- Create event on signed-in user's calendar: `create_event`. +- Create event on shared calendar: `create_shared_calendar_event`. +- Update signed-in user's event: `update_event`. +- Update shared calendar event: `update_shared_calendar_event`. +- Respond to signed-in user's invite: `respond_to_event`. +- Respond to shared calendar invite: `respond_to_shared_calendar_event`. +- Cancel or delete signed-in user's event: `cancel_or_delete_event`. +- Cancel or delete shared calendar event: `cancel_or_delete_shared_calendar_event`. +- Add small attachment to signed-in user's event: `add_event_attachment`. +- Add small attachment to shared calendar event: `add_shared_calendar_event_attachment`. + +## Workflow + +1. Resolve the target calendar with `list_calendars`; preserve the exact shared `calendar_id`. +2. Fetch or list the relevant event context before a write, and say when the shared calendar exposes only partial detail. +3. Restate the exact target calendar and event before create, update, RSVP, cancel, delete, or attachment writes. +4. Use the shared-calendar action that matches the requested write. Do not pass shared-calendar intent through the normal signed-in-user action. +5. For recurring events, preserve the base Outlook Calendar recurrence safety flow and require the intended update scope. + +## Safety + +- Treat shared-calendar writes as high impact because they modify another calendar surface. +- Do not assume that free/busy access implies delegated write access. +- If a shared-calendar write action is not available in-session, say that the shared/delegated calendar write capability is unavailable; do not silently retry with the signed-in-user write action. +- Preserve Teams links, rooms, attendees, body format, reminders, recurrence, and show-as state unless the user explicitly asked to change them. + +## Example Requests + +- "Create this event on the team shared calendar, not my personal calendar." +- "Move the event on the recruiting shared calendar to Thursday at 10 AM Pacific." +- "Cancel that event from the ops shared calendar and send this cancellation note." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-shared-calendars/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-shared-calendars/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..75bfd6f3420f91c685059f3307b1771362086775 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar-shared-calendars/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Shared Calendars" + short_description: "Safely write to delegated Outlook calendars" + default_prompt: "Use $outlook-calendar-shared-calendars to create, update, RSVP, cancel, delete, or attach files to events on delegated or shared Outlook calendars." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..9eae1b455982c28bc387d83273c51e3f5fcaa360 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/SKILL.md @@ -0,0 +1,146 @@ +--- +name: outlook-calendar +description: Handle Outlook Calendar workflows, including delegated/shared calendar writes. Use when the user asks for schedule understanding, availability checks, meeting scheduling, intelligent rescheduling, meeting prep, reminder updates, RSVP responses, recurring maintenance, travel coordination, deadline planning, or safe create, update, reschedule, respond, attach, delete, or cancel changes with timezone-aware event times and attendee validation. +--- + +# Outlook Calendar + +## Overview + +Use this skill to turn raw Outlook Calendar data into clear scheduling decisions and safe event updates. Favor exact dates, times, attendee details, and calendar evidence over ambiguous natural-language plans. + +If recurrence scope or cadence matters, consult `resources/recurring-meetings.md` before proposing a recurring change. +If a request depends on flights, commute blocks, airport timing, or in-person travel logistics, consult `resources/travel-coordination.md` before proposing a change. +If a request depends on prep alerts, meeting reminder timing, or deciding which meetings deserve reminders, consult `resources/reminder-planning.md` before proposing a change. +If a request depends on proposing candidate times, checking when the user is free, or placing a temporary hold, consult `resources/availability-response.md` before proposing a change. + +## Specialized Skills + +- For one-day schedule understanding and agenda readouts, prefer [outlook-calendar-daily-brief](../outlook-calendar-daily-brief/SKILL.md). +- For creating a meaningful focus block through intelligent moves, prefer [outlook-calendar-free-up-time](../outlook-calendar-free-up-time/SKILL.md). +- For ranking the best group meeting options, prefer [outlook-calendar-group-scheduler](../outlook-calendar-group-scheduler/SKILL.md). +- For meeting prep briefs grounded in the event and nearby Microsoft context, prefer [outlook-calendar-meeting-prep](../outlook-calendar-meeting-prep/SKILL.md). +- For creating, updating, responding to, deleting, canceling, or attaching files on delegated or shared calendars, prefer [outlook-calendar-shared-calendars](../outlook-calendar-shared-calendars/SKILL.md). +- Keep reminder planning, RSVP replies, recurring-series maintenance, travel-aware scheduling, and deadline planning in this base Outlook skill. + +Use this base skill when the request spans multiple Outlook Calendar workflows or when no more focused calendar skill is a better fit. + +## Preferred Deliverables + +- Availability summaries with exact candidate slots, timezone, and conflicts. +- Event change proposals that show the current event and the intended update. +- Shared-calendar summaries that explain when Outlook is showing free/busy only versus full event detail. +- Meeting-status explanations that decode Outlook concepts such as `Busy`, `Tentative`, `Free`, `Out of Office`, and `Working Elsewhere`. +- Meeting-readiness summaries that incorporate attendee response state, organizer intent, and whether a Teams link, room, or work-location detail already exists. +- Final event details that are ready to create, reschedule, or cancel directly when the request is clear. +- Meeting-note drafts that are phrased as shared, meeting-ready agenda or prep bullets rather than assistant-facing analysis. +- Reminder or deadline plans that make clear whether the outcome is an Outlook event reminder, a calendar hold, an invite response, or a separate automation. + +## Workflow + +### Grounding + +1. Read mailbox profile context first when available so the request is grounded in the signed-in identity, locale, timezone, and default calendar assumptions. +2. Resolve calendar scope before reasoning. If multiple calendars are available, identify the intended one explicitly and prefer the default personal calendar unless the user names a shared, delegated, team, or resource calendar. +3. Read current calendar state first. Gather the relevant events, time window, attendee responses, and any existing event IDs before proposing changes. +4. Normalize all time language. Convert phrases like `tomorrow morning` or `next Tuesday` into explicit dates, times, and timezone-aware ranges. + +### Scheduling Reasoning + +5. Surface conflicts before edits. Call out overlapping events, travel gaps, double bookings, overload, and missing meeting details before suggesting a create or update. +6. Start from Outlook scheduling surfaces, not generic calendar abstractions. Account for attendee response state, organizer vs attendee role, shared-calendar visibility, work hours, work location, and room or resource context when available. +7. When the request depends on workday norms, prefer Outlook-native cues such as work hours, location plans, and partial free/busy visibility over generic assumptions about what counts as open work time. +8. Treat recurring meetings carefully. Determine whether the user means one occurrence, future instances, or the whole series, and if the scope is not explicit or not verifiable from the tool output, stop and confirm before editing. +9. Treat prompts about past meetings as retrospective by default. Analyze what happened and propose future scheduling changes unless the user explicitly asks to edit or annotate past events. + +### Confirmation and Writes + +12. When the request is ambiguous, summarize the scheduling options or the exact event diff before writing anything. +13. Treat missing title, attendees, location, Teams link, or timezone as confirmation points rather than assumptions. +14. For reschedules where the user did not specify the destination time, propose one to three exact replacement slots and get confirmation on the chosen slot before moving the event. +15. Check attendee availability before rescheduling when the connector can do so. If recipient availability cannot be verified, say that explicitly and treat any move as best-effort rather than silently assuming the slot works. +16. When notes, Teams links, rooms, or missing details matter, inspect the event payload before proposing a change and say when the source data appears partial. +17. For meeting-prep or invite-note requests, collect the relevant source material first, then apply a short, grounded write directly unless the request is still ambiguous or under-specified. +18. Before any create or reschedule write, restate the final interpreted weekday, date, local clock time, and timezone for the event. If the task spans multiple cities or time zones, restate each relevant timestamp separately. +19. Only create, update, move, or cancel events when the user has clearly asked for that action. +20. For delegated or shared calendar writes, route to [../outlook-calendar-shared-calendars/SKILL.md](../outlook-calendar-shared-calendars/SKILL.md). Do not use signed-in-user write actions as a substitute for the explicit shared-calendar action names. + +## Read Path + +- Use `list_events` as the default tool for bounded calendar reads when the user is asking about a specific day, week, or date window. +- Prefer an explicit time window with both `start_datetime` and `end_datetime` instead of an unbounded fetch whenever the user intent is tied to a concrete range such as today, tomorrow, next week, or the next 3 days. +- Normalize relative ranges into exact ISO-8601 timestamps with an explicit UTC offset before calling `list_events`. +- Use the default event shape for ordinary schedule review. Only narrow fields if the task truly needs a smaller payload and the connector contract for that field set is known to be safe. +- Use `search_events` when the user is trying to find a meeting by phrase, attendee, or event title rather than asking for a simple time-window read. +- Use `fetch_event` after discovery when one concrete event needs deeper inspection before editing. +- If multiple information surfaces are available for meeting prep, prefer this retrieval order unless the user names a specific source: current event body, prior related event bodies, Outlook Email, SharePoint or OneDrive docs, then lower-signal notes sources. +- For document retrieval across Microsoft surfaces, use the actual connector or tool surfaces directly: + - Outlook mail context: use the Outlook Email app tools. + - SharePoint or OneDrive docs: use the Microsoft SharePoint app tools such as `get_site`, `list_site_drives`, `search(query="...")`, `search(query=None, hostname=..., site_path=..., folder_path=...)`, and `fetch`. + - Do not use generic MCP resource discovery such as `list_mcp_resources` to discover SharePoint content for this workflow. + +## Outlook-Specific Checks + +- Distinguish true busy time from softer constraints such as `Tentative`, `Free`, `Out of Office`, or `Working Elsewhere`. +- If the source data includes attendee response state, organizer role, Teams details, room booking, or work-location context, preserve those details unless the user asked to change them. +- Shared calendars may expose only free/busy signals rather than full event details. Say that directly instead of implying the view is complete. +- Shared or delegated calendar writes use explicit shared action names. Reading and availability can be partial; writing requires a concrete shared `calendar_id`. +- If a slot is free only because another item is marked `Free` or `Working Elsewhere`, describe that nuance. +- If a meeting is online, preserve the existing Teams or online-meeting setup unless the user asks to change it. + +## Write Safety + +- Preserve exact event titles, attendees, start and end times, locations, Teams or online-meeting details, reminders, and notes from the source data unless the user requests a change. +- Preserve the original invite body format when editing. If the existing event body is plain text, keep the update plain text unless the user explicitly wants richer formatting. If the existing body is HTML, preserve HTML structure instead of flattening it into text. +- Keep Outlook event descriptions brief by default. Unless the user explicitly asks for a detailed write-up, limit description updates to at most one or two short blocks or paragraphs of operationally useful content. +- When creating invite content from scratch, prefer plain text for short linear notes and use HTML only when the content needs real structure such as bullets, links, or clearly separated sections. +- Do not write attendee-facing invite notes that include assistant provenance or meta commentary. +- When source material is incomplete or unverified, omit the uncertain item, label it as a question for the meeting, or present a draft only when unresolved details still block a safe write. +- Treat deletes and broad availability changes as high-impact actions. Restate the affected event or calendar before applying them. +- If multiple calendars or similarly named events are in play, identify the intended one explicitly before editing. +- For cross-timezone requests such as travel, flights, or events tied to a different city, interpret each stated local time in the timezone of the city where that timestamp occurs before converting it into the Outlook event payload. +- Treat Outlook timezone names as a required formatting step. Convert from user-facing timezone references such as cities, offsets, abbreviations, or IANA names into the Outlook-compatible timezone expected by the connector before writing. +- If a cross-timezone request leaves any timestamp interpretation ambiguous, stop and ask rather than silently choosing one timezone basis. + +## Product Terminology + +- Translate Outlook-native terms into plain language when they matter to the task, and briefly note when a term may be ambiguous across products. +- In Outlook Calendar, `reminder` normally means the built-in pre-meeting or pre-event alert on the calendar event itself, not a separate task or Apple Reminders item. +- If the user says `reminder` while clearly working inside Outlook Calendar, default to the Outlook event alert meaning, but say so briefly when the distinction could matter. +- If the phrasing could reasonably mean either an Outlook event alert or a separate task-style reminder, acknowledge the ambiguity and clarify which meaning you are using before writing. +- Treat `event body`, `description`, `invite notes`, and `meeting notes in the event` as closely related Outlook concepts, but preserve the actual event body rather than inventing a separate notes surface. +- Treat `Teams link`, `online meeting`, and `join info` as logistics attached to the event, and preserve them unless the user explicitly wants them changed. +- Treat `tentative`, `busy`, `free`, `out of office`, and `working elsewhere` as Outlook availability states, not casual prose, and explain them in user language when they affect the recommendation. + +## Output Conventions + +- Present scheduling summaries with exact weekday, date, time, and timezone. +- When a task spans multiple time zones, label every timestamp with its local timezone rather than collapsing them into a single timezone summary. +- When sharing availability, explain why a slot works or conflicts instead of listing raw times without context. +- When Outlook status matters, translate it into user language, such as tentative hold, true busy, out of office, working elsewhere, or visible only as shared-calendar busy time. +- When attendee responses matter, name them directly instead of flattening everything into available or unavailable. +- When proposing a new or updated event, format the response as title, attendees, start, end, timezone, location or Teams link, status if relevant, and purpose. +- Keep option lists short and explain the tradeoff for each candidate slot. +- When reporting conflicts, name the overlapping events and how much time is affected. +- When a workflow turns into a reminder, RSVP, recurring-series, or travel-buffer task, say explicitly which Outlook action or follow-up path is being used rather than presenting it as a generic edit. +- When comparing options, keep the list short and explain the tradeoff for each slot. +- When the source data is incomplete, say whether the limitation seems to come from shared-calendar permissions or missing meeting metadata. +- For retrospective schedule prompts, separate `What happened` from `What to change next time` so the user gets analysis even when no safe write should occur. +- For invite-note drafts, prefer a compact structure such as `Agenda`, `Open items`, `Decisions needed`, or `Next steps`. +- Prefer short Outlook-style descriptions over memo-like notes. The default target is one concise agenda block plus, at most, one short prep block. + +## Example Requests + +- "Check my Outlook Calendar availability this Thursday afternoon and suggest the best two meeting slots." +- "Move the project review to next week and keep the same attendees and Teams link." +- "Summarize my calendar for tomorrow, including which holds are only tentative." +- "Go through yesterday's meetings and tell me how I should schedule similar meetings next time to reduce context switching." +- "Draft the exact event details for a 30 minute sync with the vendor at 2 PM Pacific on Friday." +- "Help me decide whether to accept this invite, decline it, or propose a better time." +- "Clean up this recurring staff meeting without breaking the whole series." +- "Add the right reminder coverage for my review next week and the deadline after it." +- "Create this event on the team shared calendar instead of my personal calendar." + +## Light Fallback + +If Outlook Calendar data is missing or the connector does not return the expected events, say that Microsoft Outlook access may be unavailable or pointed at the wrong calendar and ask the user to reconnect or clarify which calendar should be used. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a3484663b2827140f1d891676cf5a216a8314184 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/agents/openai.yaml @@ -0,0 +1,7 @@ +interface: + display_name: "Outlook Calendar" + short_description: "Find availability and safe event changes" + icon_small: "./assets/outlook-calendar-small.svg" + icon_large: "./assets/outlook-calendar.svg" + brand_color: "#0078D4" + default_prompt: "Use $outlook-calendar to compare availability, explain Outlook meeting status, or draft the exact personal or shared-calendar event change, including Teams details when relevant." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/assets/outlook-calendar-small.svg b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/assets/outlook-calendar-small.svg new file mode 100644 index 0000000000000000000000000000000000000000..3cd8190f50fc0c8f0da28fb664afa86e8a20c063 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/assets/outlook-calendar-small.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/assets/outlook-calendar.svg b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/assets/outlook-calendar.svg new file mode 100644 index 0000000000000000000000000000000000000000..3cd8190f50fc0c8f0da28fb664afa86e8a20c063 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/assets/outlook-calendar.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/availability-response.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/availability-response.md new file mode 100644 index 0000000000000000000000000000000000000000..38589a71adba4631591b4f54219ba63da2d8bf88 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/availability-response.md @@ -0,0 +1,28 @@ +# Availability Response + +Use this resource when the user wants Outlook Calendar to propose meeting options, check when they are free, draft a response with candidate times, or place a temporary hold. + +## Defaults + +- For broad availability requests without a stated window, default to a near-term business window. Prefer the current workweek when it still has useful time left, otherwise use the next 7 days. +- For broad availability requests without a stated time of day, prefer business hours from Outlook working-hours data. If Outlook does not expose working hours, use standard weekday business hours that fit the user's locale and work culture rather than early mornings, evenings, or weekends. +- Prefer a short list of strong options over an exhaustive dump of open time. + +## Outlook-Specific Focus + +- Distinguish firm conflicts from softer constraints such as `Tentative`, `Free`, or `Working Elsewhere`. +- If a slot is available only because another item is marked `Free` or `Working Elsewhere`, explain that nuance rather than presenting it as a fully clean opening. +- If the answer depends on partial shared-calendar visibility, say that directly. + +## Temporary Holds and Replies + +- If the user asks for a temporary hold and does not provide a title, use a simple Outlook-style placeholder such as `Temporary hold`. +- If the user asks for a hold and does not provide a narrower search window, choose a reasonable near-term slot using the defaults above rather than stopping for avoidable clarification. +- If drafting a response to send elsewhere, make it directly sendable and keep the wording polished and practical. +- If applying a temporary hold, say whether it is tentative, private, or expected to be removed later. + +## Output Conventions + +- Return 2-3 options by default unless the user asked for more. +- Label each option with exact weekday, date, time, and timezone. +- Say why each slot is good, not just that it is open. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/recurring-meetings.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/recurring-meetings.md new file mode 100644 index 0000000000000000000000000000000000000000..5cbe6184951d13a2a70bc6f87eda563b8e04178b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/recurring-meetings.md @@ -0,0 +1,47 @@ +# Recurring Meetings Behavior + +Use this resource when a request depends on recurring-meeting scope, cadence, or workplace norms rather than only the event title and time. + +## Outlook and Graph Semantics + +- Outlook and Microsoft Graph distinguish between a single occurrence, future instances, and the full recurring series. +- Graph event objects can represent `singleInstance`, `occurrence`, `exception`, or `seriesMaster`. +- A recurring meeting may also carry recurrence metadata such as `seriesMasterId`, `recurrence`, and original-start information, but not every connector surface exposes that metadata clearly. +- If the tool output only shows an occurrence-like event and does not expose reliable series-master metadata, treat the read as an instance view rather than a fully trustworthy series view. +- If the user asks to `adjust future instances`, `modify the series`, `skip next week's meeting`, or similar, treat that as a recurrence-scope request rather than a simple one-off event edit. +- If the tool surface cannot prove whether a write is targeting one occurrence, future instances, or the whole series, say so clearly before editing. + +## Outlook Product Expectations + +- Outlook users expect recurring edits to preserve logistics such as the attendee list, Teams meeting details, room booking, organizer intent, and invite-note format unless the user asks to change them. +- Recurring edits are higher risk than one-off edits because they can silently change attendee expectations across many dates. +- `This event`, `the whole series`, and `future meetings` are real Outlook concepts. Use that language directly when clarifying scope. +- If a request sounds series-wide but the connector behaves instance-by-instance, explain that limitation instead of claiming a true series-level update. + +## Workplace Norms + +- Use the person's configured work days and work hours as the default frame for recurring work meetings when Outlook exposes them. +- If work hours are unavailable, default work recurrences to weekdays rather than nights or weekends unless the existing pattern or the user's wording says otherwise. +- Prefer stable recurring slots for standing meetings. Avoid proposing frequent time-of-day drift unless the user is intentionally redesigning the pattern. +- Avoid silently moving work recurrences into Friday late afternoon or outside work hours unless the existing series already uses that pattern or the user asked for it. + +## Cadence Heuristics + +- Prefer weekly for true standing coordination such as team syncs, active project check-ins, or regular 1:1s. +- Prefer biweekly as the lighter default for operational syncs when the user is creating a new recurring work meeting without a clearly stated need for weekly cadence. +- Prefer monthly for reviews, steering meetings, and broader status or planning rituals. +- Avoid suggesting daily recurrence unless the meeting is clearly a standup, incident cadence, or another operational rhythm that truly benefits from daily repetition. +- Treat 1:1s as a special case: longer and more frequent can be reasonable, and consistency usually matters more than aggressive compression. + +## Series Length and Buffers + +- For project-bound recurring meetings, prefer a bounded series when the work has an obvious horizon rather than an indefinite recurrence. +- If the user is optimizing calendars, consider Outlook-native meeting hygiene such as ending recurring meetings a bit early or preserving transition time between them. +- When extending recurring meetings, check whether the longer duration creates repeated conflicts before recommending a series-wide change. + +## Skill Guidance + +- Restate the interpreted recurrence scope before any write: one occurrence, future instances, or whole series. +- If the connector output is missing series-master evidence, explicitly say that recurrence scope is being inferred from the visible occurrence pattern. +- When proposing a recurring change, describe both the current pattern and the intended future pattern. +- If the user's request is under-specified, ask the smallest useful recurrence question instead of a generic scheduling question. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/reminder-planning.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/reminder-planning.md new file mode 100644 index 0000000000000000000000000000000000000000..6947802d066ddb0e8eced52a40fe172640dde62a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/reminder-planning.md @@ -0,0 +1,29 @@ +# Reminder Planning + +Use this resource when the user wants Outlook reminders added, adjusted, or recommended for meetings that need prep, deliverables, or presentation readiness. + +## Reminder Read Path + +- Identify which meetings actually warrant reminders: prep-heavy meetings, meetings with deliverables, presentations, external meetings, or anything with required follow-through. +- Read the relevant events before proposing reminders so the reminder plan matches the real meeting timing, attendee context, and the user's role. +- Distinguish routine reminders from elevated reminders. A normal internal sync usually does not need the same lead time as an external presentation or a meeting with deliverables due beforehand. + +## Outlook-Specific Focus + +- In Outlook Calendar, `reminder` normally means the built-in pre-event alert on the event itself rather than a separate to-do item. +- External participants, presenter role, and organizer responsibility are stronger signals than generic meeting-importance labels. +- Reminder timing should reflect Outlook-style operational needs such as joining a Teams call, getting to a room, or finishing prep before the event starts. +- If the event already has useful reminder settings, preserve them unless the user asks to change them. + +## Coordination Rules + +- If the user wants reminders added, restate the event, reminder timing, and whether the reminder should apply to one event or several. +- Group reminder recommendations by why they matter, not just by chronology. +- Use exact lead times such as 15 minutes, 30 minutes, 1 hour, or end of previous workday rather than vague language. +- If several events qualify, keep the list short and prioritize the strongest candidates first. + +## Output Conventions + +- Explain which meetings deserve reminders and why. +- If applying reminders, restate the write scope clearly. +- If the wording could mean either an Outlook event alert or a separate task-style reminder, briefly clarify which meaning is being used before writing. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/travel-coordination.md b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/travel-coordination.md new file mode 100644 index 0000000000000000000000000000000000000000..5e6cf04281d30baae46f49fe247e729e02adaf57 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/outlook-calendar/skills/outlook-calendar/resources/travel-coordination.md @@ -0,0 +1,31 @@ +# Travel Coordination + +Use this resource when Outlook Calendar work depends on physical movement, airport timing, or in-person logistics rather than only meeting duration. + +## Travel Read Path + +- Resolve the travel context first: meeting locations, departure and arrival times, cities, timezone boundaries, and whether the travel block should be public or private. +- Interpret each stated travel time in the local timezone where that timestamp occurs before comparing it to calendar events. +- Read the affected calendar window before proposing any travel buffer or reschedule. +- If the travel request spans multiple cities or airports, keep each local timestamp anchored to the city where it occurs until after interpretation. + +## Outlook-Specific Focus + +- Work location and in-person versus online context matter more here than raw availability. +- Travel buffers should usually protect the user's real day rather than appear as optional notes buried inside another event. +- Hybrid-office days often need explicit before and after commute blocks to keep Outlook availability realistic. +- If the user asks to shift meetings because of travel, restate the travel anchor and the affected meetings before writing. + +## Coordination Rules + +- Add buffer time around in-person meetings, office commutes, and airport travel in a way that reflects how the day is actually used. +- When travel overlaps existing meetings, identify which meetings are fixed versus movable before suggesting changes. +- Preserve privacy expectations for travel events such as flights when the user asks for them to be private. +- If a commute or travel block would create obvious overlap, prefer the minimum set of meeting changes needed rather than broadly reworking the day. + +## Output Conventions + +- Label every travel-related timestamp with its local timezone. +- Show which meetings are affected by the travel constraint. +- If proposing reschedules, explain the minimum set of moves needed. +- If creating new travel events, specify whether they should be private, public, or tentative. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..b41eb1de581a8aca540f7d7c5e5fec4426fe2af6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/.codex-plugin/plugin.json @@ -0,0 +1,45 @@ +{ + "name": "plugin-eval", + "version": "0.1.2", + "description": "Evaluate Codex skills and plugins from chat with a beginner-friendly start command, local-first reports, token budget explanations, and guided benchmarking.", + "author": { + "name": "OpenAI Codex", + "email": "support@openai.com", + "url": "https://openai.com/" + }, + "homepage": "https://openai.com/", + "repository": "https://github.com/openai/plugins", + "license": "MIT", + "keywords": [ + "codex", + "plugin", + "skill", + "evaluation", + "quality", + "budget" + ], + "skills": "./skills/", + "interface": { + "displayName": "Plugin Eval", + "shortDescription": "Start from chat, then evaluate or benchmark locally", + "longDescription": "Ask Codex to evaluate a plugin or skill, give you a full analysis of a named plugin such as game-studio, explain why it scored that way, show what to fix first, explain its token budget, measure real token usage, benchmark a plugin, or tell you what to run next. Plugin Eval keeps the path engineer-friendly: start with a natural chat request, then use the local `plugin-eval start` entrypoint or the routed workflow command it recommends.", + "developerName": "OpenAI", + "category": "Developer Tools", + "capabilities": [ + "Interactive", + "Write" + ], + "websiteURL": "https://openai.com/", + "privacyPolicyURL": "https://openai.com/policies/privacy-policy/", + "termsOfServiceURL": "https://openai.com/policies/terms-of-use/", + "defaultPrompt": [ + "Give me an analysis of the game studio plugin.", + "Evaluate this plugin.", + "Why did this score that way?" + ], + "brandColor": "#0F766E", + "composerIcon": "./assets/plugin-eval.svg", + "logo": "./assets/plugin-eval.svg", + "screenshots": [] + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/assets/plugin-eval.svg b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/assets/plugin-eval.svg new file mode 100644 index 0000000000000000000000000000000000000000..7d8b12a9f1bbea1684b1a896f86578807bf5d940 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/assets/plugin-eval.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/coverage-final.json b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/coverage-final.json new file mode 100644 index 0000000000000000000000000000000000000000..3165d0c9ded54f7202c5d6bb75139d71044d47a3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/coverage-final.json @@ -0,0 +1,29 @@ +{ + "/workspace/src/sample.ts": { + "path": "/workspace/src/sample.ts", + "statementMap": { + "0": { + "start": { "line": 1, "column": 0 }, + "end": { "line": 1, "column": 10 } + }, + "1": { + "start": { "line": 2, "column": 0 }, + "end": { "line": 2, "column": 10 } + }, + "2": { + "start": { "line": 3, "column": 0 }, + "end": { "line": 3, "column": 10 } + }, + "3": { + "start": { "line": 4, "column": 0 }, + "end": { "line": 4, "column": 10 } + } + }, + "s": { + "0": 1, + "1": 1, + "2": 0, + "3": 0 + } + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/coverage.xml b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/coverage.xml new file mode 100644 index 0000000000000000000000000000000000000000..ccaf24cad3fea0763492df4782263f7b77d141a6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/coverage.xml @@ -0,0 +1,2 @@ + + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/lcov.info b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/lcov.info new file mode 100644 index 0000000000000000000000000000000000000000..37daa6e9708882702807edb4a09c0d3f9a4dee2f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/coverage-samples/lcov.info @@ -0,0 +1,5 @@ +TN: +SF:src/sample.ts +LF:8 +LH:6 +end_of_record diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/metric-pack/emit-pack.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/metric-pack/emit-pack.js new file mode 100644 index 0000000000000000000000000000000000000000..30c91c78edd1a7b987ce1b8129d0211c710beac9 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/metric-pack/emit-pack.js @@ -0,0 +1,34 @@ +const [, , targetPath, targetKind] = process.argv; + +console.log( + JSON.stringify({ + checks: [ + { + id: "custom-target-kind", + category: "custom", + severity: "info", + status: "info", + message: `Metric pack saw ${targetKind}`, + evidence: [targetPath], + remediation: [] + } + ], + metrics: [ + { + id: "custom-pack-score", + category: "custom", + value: 7, + unit: "points", + band: "good" + } + ], + artifacts: [ + { + id: "custom-pack-artifact", + type: "custom", + label: "Custom pack artifact", + description: "Simple fixture artifact" + } + ] + }) +); diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/metric-pack/manifest.json b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/metric-pack/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..c9f824cab8c7cca04d3440ba89e7033aba7c8be4 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/metric-pack/manifest.json @@ -0,0 +1,6 @@ +{ + "name": "team-rubric", + "version": "1.0.0", + "supportedTargetKinds": ["skill", "plugin", "directory"], + "command": ["node", "./emit-pack.js"] +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..bea41c0cc8a132ea81385097bd088e5a21192f25 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/.codex-plugin/plugin.json @@ -0,0 +1,33 @@ +{ + "name": "minimal-plugin", + "version": "0.1.0", + "description": "Minimal plugin fixture for plugin-eval tests.", + "author": { + "name": "Plugin Eval", + "email": "support@example.com", + "url": "https://example.com/" + }, + "homepage": "https://example.com/", + "repository": "https://example.com/repo", + "license": "MIT", + "keywords": ["fixture", "plugin-eval"], + "skills": "./skills/", + "interface": { + "displayName": "Minimal Plugin", + "shortDescription": "Small valid plugin fixture", + "longDescription": "A minimal but valid plugin manifest and one bundled skill for plugin-eval testing.", + "developerName": "Plugin Eval", + "category": "Developer Tools", + "capabilities": ["Interactive", "Write"], + "websiteURL": "https://example.com/", + "privacyPolicyURL": "https://example.com/privacy", + "termsOfServiceURL": "https://example.com/terms", + "defaultPrompt": [ + "Evaluate the minimal plugin fixture." + ], + "brandColor": "#0F766E", + "composerIcon": "./assets/minimal.svg", + "logo": "./assets/minimal.svg", + "screenshots": [] + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/assets/minimal.svg b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/assets/minimal.svg new file mode 100644 index 0000000000000000000000000000000000000000..c16bdb14f17f91c333bdcc79063052f8be907839 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/assets/minimal.svg @@ -0,0 +1 @@ + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/skills/minimal-plugin-skill/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/skills/minimal-plugin-skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..31bcbd38f708aea06d67de0b4180ce3f8644a532 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-plugin/skills/minimal-plugin-skill/SKILL.md @@ -0,0 +1,8 @@ +--- +name: minimal-plugin-skill +description: Minimal plugin skill fixture. Use when a test needs a valid plugin skill. +--- + +# Minimal Plugin Skill + +Use this bundled skill to verify plugin-level skill discovery. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-skill/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..2a6efd9e569de57b5f2bbea157000a775e0020a6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-skill/SKILL.md @@ -0,0 +1,19 @@ +--- +name: minimal-skill +description: Minimal example skill for plugin-eval tests. Use when the user wants a compact demonstration of a well-structured skill. +license: MIT +--- + +# Minimal Skill + +Use this fixture to verify that skill evaluation works on a small but valid example. + +## Workflow + +1. Read the target file. +2. Summarize the important structure. +3. Reference deeper details only when needed. + +## Reference + +- `references/details.md` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-skill/references/details.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-skill/references/details.md new file mode 100644 index 0000000000000000000000000000000000000000..34a0b9b0e7ae3e727d0b9a6e21d592ead6661f8e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/minimal-skill/references/details.md @@ -0,0 +1,3 @@ +# Minimal Skill Details + +This file exists so deferred supporting context can be counted without making `SKILL.md` bulky. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..8cc3685b5cd272d344cf332ff0156e5c48c8ea0b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/.codex-plugin/plugin.json @@ -0,0 +1,34 @@ +{ + "name": "multi-skill-plugin", + "version": "0.1.0", + "description": "Multi-skill plugin fixture for plugin-eval tests.", + "author": { + "name": "Plugin Eval", + "email": "support@example.com", + "url": "https://example.com/" + }, + "homepage": "https://example.com/", + "repository": "https://example.com/repo", + "license": "MIT", + "keywords": ["fixture", "plugin-eval", "multi-skill"], + "skills": "./skills/", + "interface": { + "displayName": "Multi Skill Plugin", + "shortDescription": "Plugin fixture with two skills", + "longDescription": "A plugin fixture that exposes two skills so nested skill findings can be aggregated.", + "developerName": "Plugin Eval", + "category": "Developer Tools", + "capabilities": ["Interactive", "Write"], + "websiteURL": "https://example.com/", + "privacyPolicyURL": "https://example.com/privacy", + "termsOfServiceURL": "https://example.com/terms", + "defaultPrompt": [ + "Evaluate the multi-skill plugin fixture.", + "Compare both skills in this fixture." + ], + "brandColor": "#0F766E", + "composerIcon": "./assets/multi.svg", + "logo": "./assets/multi.svg", + "screenshots": [] + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/assets/multi.svg b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/assets/multi.svg new file mode 100644 index 0000000000000000000000000000000000000000..4ed8732b8860d81cdde3cb089fa14900d1d4880f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/assets/multi.svg @@ -0,0 +1 @@ + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/skills/alpha/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/skills/alpha/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..3abb67f9504794a649590398b2e6746a11f5eb23 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/skills/alpha/SKILL.md @@ -0,0 +1,8 @@ +--- +name: alpha +description: Alpha fixture skill. Use when plugin-eval tests need one of two bundled skills. +--- + +# Alpha + +Use this fixture skill as the first bundled plugin skill. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/skills/beta/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/skills/beta/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..21d90069e52edb6b65818a9306fb4f20f36c81ac --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/multi-skill-plugin/skills/beta/SKILL.md @@ -0,0 +1,8 @@ +--- +name: beta +description: Beta fixture skill. Use when plugin-eval tests need the second bundled skill. +--- + +# Beta + +Use this fixture skill as the second bundled plugin skill. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/src/sample.py b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/src/sample.py new file mode 100644 index 0000000000000000000000000000000000000000..1fff47be4b9562b2806c65707a894f1fc5905ac3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/src/sample.py @@ -0,0 +1,13 @@ +def choose_path(items, include_archived, prefer_fast): + next_items = [] + for item in items: + if not item: + continue + if include_archived or not item.startswith("archived:"): + if prefer_fast and "fast" in item: + next_items.append(item.upper()) + elif (not prefer_fast) and "slow" in item: + next_items.append(item.lower()) + elif len(item) > 3: + next_items.append(item) + return next_items diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/src/sample.ts b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/src/sample.ts new file mode 100644 index 0000000000000000000000000000000000000000..fdbbd305f2afafdea79bb03d36d15e8e2103ad92 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/src/sample.ts @@ -0,0 +1,18 @@ +export function choosePath(items: string[], includeArchived: boolean, preferFast: boolean): string[] { + const next: string[] = []; + for (const item of items) { + if (!item) { + continue; + } + if (includeArchived || !item.startsWith("archived:")) { + if (preferFast && item.includes("fast")) { + next.push(item.toUpperCase()); + } else if (!preferFast && item.includes("slow")) { + next.push(item.toLowerCase()); + } else if (item.length > 3) { + next.push(item); + } + } + } + return next; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/tests/sample.test.ts b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/tests/sample.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a892b60692a5d0248523f18a3704bf523ff8531 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/tests/sample.test.ts @@ -0,0 +1,8 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { choosePath } from "../src/sample.ts"; + +test("choosePath keeps fast items", () => { + assert.deepEqual(choosePath(["fast:item", "archived:slow"], false, true), ["FAST:ITEM"]); +}); diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/tests/test_sample.py b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/tests/test_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..0330c02d899598a43cf351ad8bca0a8fc25e0911 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/fixtures/ts-python-sample/tests/test_sample.py @@ -0,0 +1,5 @@ +from src.sample import choose_path + + +def test_choose_path(): + assert choose_path(["fast:item", "archived:slow"], False, True) == ["FAST:ITEM"] diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/benchmark-harness.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/benchmark-harness.md new file mode 100644 index 0000000000000000000000000000000000000000..508fcb0b0dd3232d4df447c034e59a53bdfa1435 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/benchmark-harness.md @@ -0,0 +1,32 @@ +# Benchmark Harness + +The benchmark harness gives `plugin-eval` a beginner-friendly path to measured usage. + +## Goals + +- help first-time skill authors collect real usage without building their own harness +- keep the workflow local-first and transparent +- produce usage logs that can be fed back into `plugin-eval analyze --observed-usage` + +## Workflow + +1. Run `plugin-eval init-benchmark `. +2. Edit the generated `benchmark.json` so `workspace.sourcePath`, the scenarios, and any verifier commands match real tasks. +3. Run the benchmark with `plugin-eval benchmark --config `. +4. Feed the usage log into `plugin-eval analyze` when usage telemetry is available. + +## Design Choices + +- The generated benchmark file is meant to be edited by humans. +- Scenarios use plain-language fields such as `title`, `purpose`, `userInput`, and `successChecklist`. +- Benchmarking means real `codex exec` runs, not simulated single-turn Responses API requests. +- Each benchmark run captures raw Codex logs plus a normalized report under `.plugin-eval/runs//`. +- When token usage is emitted by Codex, the benchmark also writes JSONL usage logs in a shape that `--observed-usage` already understands. + +## Commands + +```bash +plugin-eval init-benchmark ./skills/my-skill +plugin-eval benchmark ./skills/my-skill +plugin-eval analyze ./skills/my-skill --observed-usage ./skills/my-skill/.plugin-eval/benchmark-usage.jsonl --format markdown +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/chat-first-workflows.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/chat-first-workflows.md new file mode 100644 index 0000000000000000000000000000000000000000..a9a44af3178ac829fd7782dbcb2d33ec2600a5a8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/chat-first-workflows.md @@ -0,0 +1,98 @@ +# Plugin Eval Chat-First Workflows + +`plugin-eval` should feel usable from Codex chat before a user knows any CLI flags. + +## One Paved Road + +If the user speaks in natural language first, use: + +```bash +plugin-eval start --request "" --format markdown +``` + +That entrypoint recognizes the request, explains why the workflow fits, and shows the exact local command sequence behind it. + +## Recommended Beginner Requests + +Use these exact phrases as the paved road: + +- `Give me an analysis of the game dev skill.` +- `Evaluate this skill.` +- `Evaluate this plugin.` +- `Explain the token budget for this skill.` +- `Measure the real token usage of this skill.` +- `Help me benchmark this plugin.` +- `What should I run next?` + +## How Those Requests Map To Local Workflows + +### Give me an analysis of the game dev skill + +Start with: + +```bash +plugin-eval start ~/.codex/skills/game-dev --request "give me an analysis of the game dev skill" --format markdown +plugin-eval analyze ~/.codex/skills/game-dev --format markdown +plugin-eval init-benchmark ~/.codex/skills/game-dev +plugin-eval benchmark ~/.codex/skills/game-dev --config ~/.codex/skills/game-dev/.plugin-eval/benchmark.json +``` + +Use this when the user wants the overall report and wants Codex to set up starter benchmark scaffolding instead of stopping after the first report. + +### Evaluate this skill + +Start with: + +```bash +plugin-eval start --request "Evaluate this skill." --format markdown +plugin-eval analyze --format markdown +``` + +Use this when the user wants the overall report first. + +### Explain the token budget for this skill + +Start with: + +```bash +plugin-eval start --request "Explain the token budget for this skill." --format markdown +plugin-eval explain-budget --format markdown +``` + +Use this when the question is about cost, context pressure, or why a skill feels heavy. + +### Measure the real token usage of this skill + +Start with: + +```bash +plugin-eval start --request "Measure the real token usage of this skill." --format markdown +plugin-eval init-benchmark +plugin-eval benchmark --config +plugin-eval analyze --observed-usage --format markdown +plugin-eval measurement-plan --observed-usage --format markdown +``` + +Use this when the user wants measured usage from a real Codex run, not just the static estimate. + +### Help me benchmark this plugin + +Start with: + +```bash +plugin-eval start --request "Help me benchmark this plugin." --format markdown +plugin-eval init-benchmark +plugin-eval benchmark --config +``` + +Use this when the user wants starter scenarios or a repeatable real-Codex measurement harness. + +### What should I run next? + +Start with: + +```bash +plugin-eval start --request "What should I run next?" --format markdown +``` + +Use this when the user is unsure whether they should evaluate, explain a budget, benchmark, or collect measured usage next. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/evaluation-result-schema.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/evaluation-result-schema.md new file mode 100644 index 0000000000000000000000000000000000000000..cdbcafaf3f7a9e1a5a72ca3e27f353d07785d542 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/evaluation-result-schema.md @@ -0,0 +1,140 @@ +# Evaluation Result Schema + +The canonical `plugin-eval` result is JSON with this top-level shape: + +```json +{ + "schemaVersion": 1, + "tool": { + "name": "plugin-eval", + "version": "0.1.0" + }, + "createdAt": "2026-04-07T00:00:00.000Z", + "target": { + "kind": "skill", + "path": "/abs/path/to/target", + "entryPath": "/abs/path/to/target/SKILL.md", + "name": "target-name", + "relativePath": "fixtures/minimal-skill" + }, + "summary": { + "score": 92, + "grade": "A", + "riskLevel": "low", + "topRecommendations": [] + }, + "budgets": { + "method": "estimated-static-policy-aware", + "invocation_policy": { + "implicit_skill_count": 1, + "explicit_only_skill_count": 2, + "implicit_skills": ["router"], + "explicit_only_skills": ["specialist-a", "specialist-b"] + }, + "trigger_cost_tokens": { + "value": 48, + "band": "good", + "thresholds": { + "goodMax": 48, + "moderateMax": 92, + "heavyMax": 150 + }, + "components": [] + }, + "invoke_cost_tokens": { + "value": 220, + "band": "good", + "thresholds": { + "goodMax": 220, + "moderateMax": 480, + "heavyMax": 900 + }, + "components": [] + }, + "deferred_cost_tokens": { + "value": 180, + "band": "good", + "thresholds": { + "goodMax": 180, + "moderateMax": 520, + "heavyMax": 1200 + }, + "components": [] + }, + "explicit_only_invoke_cost_tokens": { + "value": 900, + "band": "heavy", + "thresholds": { + "goodMax": 220, + "moderateMax": 480, + "heavyMax": 900 + }, + "components": [] + }, + "total_tokens": { + "value": 448, + "band": "good" + } + }, + "checks": [], + "metrics": [], + "artifacts": [], + "extensions": [], + "improvementBrief": {} +} +``` + +The evaluation result may also include: + +- `observedUsage` +- `measurementPlan` + +For plugins or skills with `agents/openai.yaml` policies, `budgets.method` may be +`estimated-static-policy-aware`. In that mode, `policy.allow_implicit_invocation: false` +excludes the skill from `trigger_cost_tokens` and `invoke_cost_tokens`. The excluded skill +payloads are reported under `explicit_only_invoke_cost_tokens` for visibility, but they are +not scored as implicit active context. + +Separate benchmark runs use a `benchmark-run` payload with: + +- `mode` +- `config` +- `usageLogPath` +- `summary` +- `scenarios[]` +- `nextSteps[]` + +## Checks + +Checks use: + +- `id` +- `category` +- `severity` +- `status` +- `message` +- `evidence[]` +- `remediation[]` +- `source` + +## Metrics + +Metrics use: + +- `id` +- `category` +- `value` +- `unit` +- `band` +- `source` + +## Extensions + +`extensions[]` holds metric-pack outputs. Each extension records: + +- `name` +- `version` +- `manifestPath` +- `checks[]` +- `metrics[]` +- `artifacts[]` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/metric-pack-manifest.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/metric-pack-manifest.md new file mode 100644 index 0000000000000000000000000000000000000000..07dee22a84e150a996211db0a592d34f19e7d829 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/metric-pack-manifest.md @@ -0,0 +1,60 @@ +# Metric Pack Manifest + +Metric packs are user-authored local evaluators that output `plugin-eval`-compatible findings. + +## Manifest Shape + +```json +{ + "name": "team-rubric", + "version": "1.0.0", + "supportedTargetKinds": ["skill", "plugin"], + "command": ["node", "./emit-team-rubric.js"] +} +``` + +## Runtime Contract + +- The manifest is passed to `plugin-eval analyze --metric-pack `. +- The command runs from the manifest directory. +- The target path and target kind are appended as CLI arguments. +- The process also receives: + - `PLUGIN_EVAL_TARGET` + - `PLUGIN_EVAL_TARGET_KIND` + - `PLUGIN_EVAL_METRIC_PACK_MANIFEST` + +## Output Contract + +The metric pack must print JSON to stdout in this shape: + +```json +{ + "checks": [ + { + "id": "team-style", + "category": "custom", + "severity": "warning", + "status": "warn", + "message": "Custom rubric finding", + "evidence": ["detail"], + "remediation": ["fix detail"] + } + ], + "metrics": [ + { + "id": "team-score", + "category": "custom", + "value": 4, + "unit": "points", + "band": "good" + } + ], + "artifacts": [] +} +``` + +## Merge Rules + +- Metric-pack findings are stored under `extensions[]`. +- Metric packs do not overwrite the core summary. +- Metric packs should use unique IDs so repeated runs remain easy to compare. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/observed-usage.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/observed-usage.md new file mode 100644 index 0000000000000000000000000000000000000000..08d5265c74795e9609c9f1187afcdb59e274797b --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/observed-usage.md @@ -0,0 +1,49 @@ +# Observed Usage Inputs + +`plugin-eval` can ingest local JSON or JSONL files that contain token telemetry from real runs. + +## Supported Shapes + +The parser accepts these common patterns: + +- a Responses API object with a top-level `usage` +- a `response.done` event with `response.usage` +- a wrapper object with `response.usage` +- arrays of the objects above +- JSONL files where each line is one object + +## Example + +```json +{ + "id": "resp_123", + "usage": { + "input_tokens": 180, + "output_tokens": 96, + "total_tokens": 276, + "input_token_details": { + "cached_tokens": 48 + }, + "output_tokens_details": { + "reasoning_tokens": 22 + } + }, + "metadata": { + "scenario": "cold-start refactor task" + } +} +``` + +## CLI + +```bash +plugin-eval analyze ./skills/my-skill --observed-usage ./runs/responses.jsonl +plugin-eval measurement-plan ./skills/my-skill --observed-usage ./runs/responses.jsonl --format markdown +``` + +## Interpretation + +- Static budgets remain the deterministic local estimate. +- Observed usage adds a second signal based on real sessions. +- The tool compares `trigger_cost_tokens + invoke_cost_tokens` against the observed average input tokens. +- Cached and reasoning tokens are reported when present so warm-cache runs do not get mistaken for cold-start runs. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/technical-design.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/technical-design.md new file mode 100644 index 0000000000000000000000000000000000000000..734955689222e06c2f0ccb856acf97a46f39b36e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/references/technical-design.md @@ -0,0 +1,313 @@ +# Plugin Eval Technical Design + +## Overview + +`plugin-eval` is a local-first Codex plugin and CLI for evaluating Codex skills and plugins. The design centers on a deterministic local engine that emits a stable `evaluation-result` JSON document. Skills orchestrate the engine. Report renderers, comparison views, workflow guides, and future app visualizations consume the same JSON contract. + +The first version is intentionally static: + +- No live Codex benchmarking +- No remote repository evaluation +- No automatic test execution +- No requirement for external dependencies beyond Node + +## Primary Goals + +- Evaluate local skill and plugin bundles with predictable results. +- Make token and context costs visible early, especially for skill authors. +- Provide concrete quality signals for TypeScript and Python code. +- Create a normalized extension point for custom metric packs. +- Generate improvement briefs that pair naturally with the shipped `skill-creator` workflow. +- Make the recommended chat-first workflow obvious for first-time skill authors. + +## Non-Goals For V1 + +- Measuring actual Codex desktop host token consumption end to end +- Running a skill inside the Codex host as part of the evaluation +- Replacing model or product-level eval frameworks +- Language-specific deep analysis for every language beyond TypeScript and Python + +## Architecture + +### 1. Core Engine + +The core engine lives under `src/core/` and owns: + +- target resolution (`skill`, `plugin`, or generic directory/file) +- result schema creation +- budget calculation and banding +- score and risk summary generation +- metric-pack execution +- improvement brief generation + +The engine is the source of truth. Other surfaces must not invent their own scoring logic. + +### 2. Evaluators + +Evaluators live under `src/evaluators/` and return normalized fragments: + +- `checks[]` +- `metrics[]` +- `artifacts[]` + +Built-in evaluators: + +- skill structure and frontmatter checks +- plugin manifest and path checks +- token and context budget analysis +- TypeScript metrics +- Python metrics +- coverage artifact ingestion + +### 3. Renderers + +Renderers live under `src/renderers/` and consume the canonical evaluation payload. + +Supported report formats: + +- JSON +- Markdown +- HTML + +The report output is deliberately thin. It should present the existing result cleanly, not compute new conclusions. + +### 4. Codex Skills + +The plugin exposes lightweight skills that route users into the engine: + +- `plugin-eval` +- `evaluate-skill` +- `evaluate-plugin` +- `metric-pack-designer` +- `improve-skill` + +These skills stay small and point users to references and CLI commands instead of embedding bulky logic. + +The beginner paved road is: + +1. User asks in chat: "Evaluate this skill." or "What should I run next?" +2. The umbrella skill or focused skill can run `plugin-eval start --request "" --format markdown` to route that request intentionally. +3. The rendered output shows the routed chat request, the quick local entrypoint, and the first underlying workflow command side by side. + +## Canonical Result Shape + +The canonical result is a JSON object with: + +- `target` +- `summary` +- `budgets` +- `checks[]` +- `metrics[]` +- `artifacts[]` +- `extensions[]` +- `improvementBrief` + +### Summary + +`summary` includes: + +- `score` +- `grade` +- `riskLevel` +- `topRecommendations[]` + +The summary is calculated from built-in checks only. Extension metric packs are stored under `extensions[]` and do not overwrite the core summary. + +### Checks + +Every check uses the normalized fields: + +- `id` +- `category` +- `severity` +- `status` +- `message` +- `evidence[]` +- `remediation[]` +- `source` + +### Metrics + +Every metric uses the normalized fields: + +- `id` +- `category` +- `value` +- `unit` +- `band` +- `source` + +## Budget Model + +The budget model is a first-class part of the evaluation result and uses three scored buckets: + +- `trigger_cost_tokens` +- `invoke_cost_tokens` +- `deferred_cost_tokens` + +Policy-aware plugin analyses may also include an unscored visibility bucket: + +- `explicit_only_invoke_cost_tokens` + +### Definitions + +- `trigger_cost_tokens`: text likely to matter before explicit invocation, such as names, descriptions, and starter prompts +- `invoke_cost_tokens`: core instruction payloads that are likely loaded when the skill or plugin is invoked +- `deferred_cost_tokens`: supporting references, scripts, and related text assets that are only pulled in later +- `explicit_only_invoke_cost_tokens`: skill payloads marked `policy.allow_implicit_invocation: false` in `agents/openai.yaml`; these remain visible as explicit load ceilings but are excluded from implicit trigger/invoke scoring + +### Measurement Mode In V1 + +The current implementation labels budget analysis as `estimated-static` or `estimated-static-policy-aware`. + +That means: + +- token counts are estimated locally from file contents +- the estimate is deterministic and repeatable +- budget bands are calibrated against a baseline corpus of shipped Codex skills and plugins when available locally +- `estimated-static-policy-aware` honors `agents/openai.yaml` invocation policy, so explicit-only skills do not inflate implicit active-context findings + +### Why Static Estimation First + +We do not currently assume that the Codex plugin runtime exposes per-skill or per-plugin host token telemetry to plugins. The official OpenAI docs do show token usage support at the Responses API layer, but that is different from host-level Codex plugin execution telemetry. + +## OpenAI Token Telemetry Notes + +### What The Official Docs Do Show + +As of April 7, 2026: + +- the Responses API returns a `usage` object with `input_tokens`, `output_tokens`, and `total_tokens` +- the Responses API exposes `POST /v1/responses/input_tokens` to count request input tokens without running a full generation +- reasoning-capable responses expose extra token detail such as reasoning token counts + +### What We Did Not Confirm + +We did not find official documentation showing that a Codex plugin or skill can directly inspect the host runtime's own per-skill token usage from inside Codex. + +### Design Consequence + +V1 keeps token analysis local and estimated. + +V2 can add an optional measured harness that: + +- wraps a skill or plugin task in a controlled Responses API request +- captures `usage` from the response object +- optionally calls the input-token-count endpoint before execution +- records measured results beside static estimates instead of replacing them + +## Future Harness Design + +The future measured harness should be a separate execution mode, not the default. + +Recommended shape: + +- `static` mode: current default, zero network requirement +- `measured` mode: explicit opt-in, requires API credentials and a harness config + +Measured harness outputs should live next to the static budget fields, for example: + +- `budgets.method: "estimated-static"` or `"measured-responses-api"` +- `artifacts[]` entry for raw usage snapshots +- `extensions[]` or a dedicated measured-budget artifact for side-by-side comparison + +This keeps the schema forward-compatible. + +### Observed Usage In The Current Implementation + +The current CLI now supports an intermediate step between purely static analysis and a fully managed harness: + +- users can pass one or more `--observed-usage` files to `plugin-eval analyze` +- the files can contain Responses API usage payloads or Codex-like local session exports +- the result stores an `observedUsage` summary with averages, min/max values, cached tokens, and estimate drift +- the tool emits a built-in measurement plan so teams can decide what else to instrument beyond tokens + +This keeps the default local-first while giving teams a way to calibrate the estimate against reality. + +## Benchmark Harness For New Skill Authors + +The next layer is a guided benchmark harness designed to be approachable for first-time skill authors: + +- `plugin-eval init-benchmark ` writes a starter benchmark config with editable plain-language scenarios +- `plugin-eval benchmark --dry-run` previews the exact Requests API payload shape before any network call +- `plugin-eval benchmark ` runs the scenarios, captures `usage`, and writes a local JSONL usage log +- the resulting usage log can be fed directly back into `plugin-eval analyze --observed-usage ...` + +The benchmark harness is intentionally not framed as a full scientific eval system. It is the paved road for collecting: + +- representative token usage +- first-pass scenario coverage +- a reusable scenario file that teams can gradually improve + +This keeps the workflow intuitive: + +1. Generate starter scenarios. +2. Edit them to match the real task. +3. Dry-run to preview. +4. Run live. +5. Feed the usage file back into analysis. + +## Chat-First Workflow Guide + +The CLI now includes a beginner router: + +- `plugin-eval start ` + +It is intentionally small and deterministic. It does not replace the engine or invent new scoring. It only maps natural user intents such as: + +- `Evaluate this skill.` +- `Measure the real token usage of this skill.` +- `Help me benchmark this plugin.` +- `What should I run next?` + +to the existing local command sequences. + +## Metric Packs + +Metric packs are external evaluators that produce schema-compatible findings. + +Manifest responsibilities: + +- `name` +- `version` +- `supportedTargetKinds` +- `command` + +Runtime contract: + +- the pack executes locally +- the pack receives target path and target kind +- the pack writes JSON to stdout +- the JSON may contain `checks[]`, `metrics[]`, and optional `artifacts[]` + +The core engine stores the result under `extensions[]` without allowing packs to rewrite the main summary. + +## Improvement Loop + +The improvement loop is: + +1. Evaluate a skill or plugin. +2. Review the prioritized checks and budget findings. +3. Generate an improvement brief. +4. Use `improve-skill` together with `skill-creator` guidance to refactor the skill. +5. Re-run evaluation and compare results. + +## Testing Strategy + +Fixture-driven tests verify: + +- valid result JSON generation +- Markdown and HTML report rendering +- oversized descriptions and bloated `SKILL.md` detection +- broken plugin manifests and missing paths +- TypeScript and Python metrics +- coverage artifact ingestion +- custom metric-pack merging +- improvement brief generation +- comparison output + +## References + +- Responses API reference: [https://platform.openai.com/docs/api-reference/responses/create?api-mode=responses](https://platform.openai.com/docs/api-reference/responses/create?api-mode=responses) +- Responses input items and input token counts: [https://platform.openai.com/docs/api-reference/responses/input-items?lang=node.js](https://platform.openai.com/docs/api-reference/responses/input-items?lang=node.js) +- Reasoning token usage example: [https://platform.openai.com/docs/guides/reasoning/reasoning%3B.docx](https://platform.openai.com/docs/guides/reasoning/reasoning%3B.docx) diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/scripts/plugin-eval.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/scripts/plugin-eval.js new file mode 100644 index 0000000000000000000000000000000000000000..e3236af34ee0fcfd28d55e64928945122e7ba416 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/scripts/plugin-eval.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +import { runCli } from "../src/cli.js"; + +runCli(process.argv.slice(2)).catch((error) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; +}); diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-plugin/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-plugin/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..eef80263a398d9535d3341457150ef79e286c349 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-plugin/SKILL.md @@ -0,0 +1,43 @@ +--- +name: evaluate-plugin +description: Evaluate a local Codex plugin in engineer-friendly language. Use when the user says "evaluate this plugin", "audit this plugin", "why did this score that way", "what should I fix first", "help me benchmark this plugin", or asks for a plugin-wide report before comparing versions. +--- + +# Evaluate Plugin + +Use this skill when the target is a plugin root with `.codex-plugin/plugin.json`. + +## Workflow + +1. Treat "Evaluate this plugin." as the default entrypoint. +2. If the request comes in as natural chat language, use `plugin-eval start --request "" --format markdown` first so the user sees the routed local path. +3. Run `plugin-eval analyze --format markdown`. +4. Read `Fix First` before drilling into manifest findings, nested skill findings, and code or coverage details. +5. If the plugin contains multiple skills, summarize the strongest and weakest ones explicitly. +6. If the user wants measured usage, switch to "Help me benchmark this plugin." and use the starter benchmark flow. +7. If the user wants trend data, compare two JSON outputs with `plugin-eval compare`. + +## Chat Requests To Recognize + +- `Evaluate this plugin.` +- `Audit this plugin.` +- `Why did this score that way?` +- `What should I fix first?` +- `Help me benchmark this plugin.` +- `What should I run next?` + +## Commands + +```bash +plugin-eval start --request "Evaluate this plugin." --format markdown +plugin-eval analyze --format markdown +plugin-eval start --request "What should I run next?" --format markdown +plugin-eval compare before.json after.json +plugin-eval report result.json --format html --output ./plugin-eval-report.html +plugin-eval init-benchmark +plugin-eval benchmark --dry-run +``` + +## Reference + +- `../../references/chat-first-workflows.md` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-plugin/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-plugin/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9177c9821cbb2e9be1514183ae703797426606e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-plugin/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Evaluate Plugin" + short_description: "Evaluate a local Codex plugin" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-skill/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..fc42e3b3e88821a8d811acea1287bac8b58f4cab --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-skill/SKILL.md @@ -0,0 +1,54 @@ +--- +name: evaluate-skill +description: Evaluate a local Codex skill in engineer-friendly terms. Use when the user says "evaluate this skill", "give me an analysis of the game dev skill", "audit this skill", "why did this score that way", "what should I fix first", or asks for a skill-specific report before benchmarking it. +--- + +# Evaluate Skill + +Use this skill when the target is a local skill directory or `SKILL.md` file. + +## Workflow + +1. Treat "Evaluate this skill." as the default entrypoint. +2. If the user names a skill instead of giving a path, resolve it locally first, preferring `~/.codex/skills/` and then repo-local `skills/`. +3. If the user says the request in natural language first, use `plugin-eval start --request "" --format markdown` to show the routed path clearly. +4. Run `plugin-eval analyze --format markdown`. +5. Review `At a Glance`, `Why It Matters`, `Fix First`, and `Recommended Next Step` before drilling into details. +6. Explain which findings are structural, which are budget-related, and which are code-related. +7. If the user asks for an "analysis" of the skill, do not stop at the report. Also run `plugin-eval init-benchmark ` and show the setup questions for refining the starter scenarios in `.plugin-eval/benchmark.json`. +8. If the user wants real usage numbers, switch to "Measure the real token usage of this skill." and run the benchmark flow. +9. After observed usage is available, use `plugin-eval measurement-plan --observed-usage --format markdown` to recommend what to instrument or improve next. +10. If the user wants a rewrite plan, route to `../improve-skill/SKILL.md`. + +## Skill-Specific Priorities + +- frontmatter validity +- `name` and `description` quality +- progressive disclosure and reference usage +- broken relative links +- oversized `SKILL.md` or descriptions +- helper script quality for TypeScript and Python files + +## Chat Requests To Recognize + +- `Evaluate this skill.` +- `Give me an analysis of the game dev skill.` +- `Audit this skill.` +- `Why did this skill score that way?` +- `What should I fix first?` +- `Measure the real token usage of this skill.` + +## Commands + +```bash +plugin-eval start --request "Evaluate this skill." --format markdown +plugin-eval analyze --format markdown +plugin-eval explain-budget --format markdown +plugin-eval measurement-plan --format markdown +plugin-eval init-benchmark +plugin-eval benchmark --dry-run +``` + +## Reference + +- `../../references/chat-first-workflows.md` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-skill/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-skill/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6229bde63e4eaae58f5e7e2d1e0c879ff5142aef --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/evaluate-skill/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Evaluate Skill" + short_description: "Evaluate a local Codex skill" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/improve-skill/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/improve-skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..4b8aa0b878bad8a1c92c1ec4d8f1ce4e06280a9a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/improve-skill/SKILL.md @@ -0,0 +1,40 @@ +--- +name: improve-skill +description: Turn plugin-eval findings into a concrete rewrite brief for a Codex skill. Use when the user already evaluated a skill and now wants Codex to improve it, especially after asking what to fix first. +--- + +# Improve Skill + +Use this skill after `plugin-eval` has already produced findings for a local skill. + +## Workflow + +1. Run `plugin-eval analyze --brief-out `. +2. Read the improvement brief and group work into required fixes versus recommended fixes. +3. Apply the `skill-creator` guidance from `/Users/benlesh/.codex/skills/skill-creator/SKILL.md`. +4. Re-run the evaluation and compare before and after outputs. + +## Chat Requests To Recognize + +- `Improve this skill based on the evaluation.` +- `Rewrite this skill using the plugin-eval findings.` +- `What should I fix first in this skill?` + +## Focus Areas + +- reduce trigger and invoke token costs +- keep `SKILL.md` compact +- move bulky details into references or scripts +- improve trigger descriptions +- fix broken links and manifest/frontmatter issues + +## Commands + +```bash +plugin-eval analyze --brief-out ./skill-brief.json +plugin-eval compare before.json after.json +``` + +## Reference + +- `../../references/chat-first-workflows.md` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/improve-skill/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/improve-skill/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b92c9911e5b78598d5740733ac8ff79f6fc54f4 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/improve-skill/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Improve Skill" + short_description: "Turn plugin-eval findings into a rewrite brief" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/metric-pack-designer/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/metric-pack-designer/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..e7b7795253554383f75633c9b0133849e975662f --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/metric-pack-designer/SKILL.md @@ -0,0 +1,26 @@ +--- +name: metric-pack-designer +description: Design custom metric packs for plugin-eval so teams can add local evaluation rubrics that emit schema-compatible checks and metrics. Use when the user wants their own evaluation criteria or visualizations. +--- + +# Metric Pack Designer + +Use this skill when the user wants to extend `plugin-eval` with a local rubric. + +## Workflow + +1. Clarify the custom rubric categories and target kinds. +2. Define the smallest useful `checks[]` and `metrics[]` payload. +3. Create a metric-pack manifest plus a script that prints JSON to stdout. +4. Run the pack through `plugin-eval analyze --metric-pack `. + +## Design Rules + +- Keep IDs stable across runs so comparisons stay meaningful. +- Emit only `checks[]`, `metrics[]`, and optional `artifacts[]`. +- Do not try to overwrite the core score or summary. +- Prefer deterministic local signals over subjective text generation. + +## Reference + +- `../../references/metric-pack-manifest.md` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/metric-pack-designer/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/metric-pack-designer/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..35d64691902782887657255cb09d173a330cd229 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/metric-pack-designer/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Metric Pack Designer" + short_description: "Design custom metric packs for plugin-eval" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/plugin-eval/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/plugin-eval/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..3d58206a936c83ae15cc274a623604f64925f17d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/plugin-eval/SKILL.md @@ -0,0 +1,80 @@ +--- +name: plugin-eval +description: Help engineers evaluate a local skill or plugin, explain why it scored that way, show what to fix first, measure real token usage, benchmark starter scenarios, or decide what to run next. Use when the user says things like "evaluate this skill", "give me an analysis of the game dev skill", "why did this score that way", "what should I fix first", "measure the real token usage of this skill", or "what should I run next?". +--- + +# Plugin Eval + +Use this as the beginner-friendly umbrella entrypoint for local Codex skill and plugin evaluation. + +## Start Here + +1. Resolve whether the target path is a skill, a plugin, or another local folder. +2. Prefer the chat-first router when the user speaks naturally or is not sure which command they need: + +```bash +plugin-eval start --request "" --format markdown +``` + +3. Route natural chat requests to the matching workflow: + - "Give me an analysis of the game dev skill." -> resolve the named skill path, run `plugin-eval analyze --format markdown`, then initialize a benchmark and show the setup questions needed to tailor `benchmark.json` + - "Evaluate this skill." -> `plugin-eval analyze --format markdown` + - "Why did this score that way?" -> `plugin-eval analyze --format markdown` + - "What should I fix first?" -> `plugin-eval analyze --format markdown` + - "Explain the token budget for this skill." -> `plugin-eval explain-budget --format markdown` + - "Measure the real token usage of this skill." -> benchmark flow, then `plugin-eval measurement-plan` + - "Help me benchmark this plugin." -> starter benchmark flow + - "What should I run next?" -> `plugin-eval start --request "What should I run next?" --format markdown` +4. If the user wants rewrite help after evaluation, route to `../improve-skill/SKILL.md`. +5. If the user wants a custom rubric, route to `../metric-pack-designer/SKILL.md`. +6. If the user names a skill instead of giving a path, resolve it locally before running commands: + - check `~/.codex/skills/` first + - then check any repo-local `skills/` directory + - if the name is still ambiguous, ask one short clarifying question before continuing +7. When the request sounds like "analysis" rather than just "evaluate", do the fuller path: + - run the report + - initialize `.plugin-eval/benchmark.json` + - surface the setup questions that will refine the starter scenarios + - preview the dry-run command the user can execute next + +## Chat Requests To Recognize + +- `Give me an analysis of the game dev skill.` +- `Evaluate this skill.` +- `Evaluate this plugin.` +- `Why did this score that way?` +- `What should I fix first?` +- `Explain the token budget for this skill.` +- `Measure the real token usage of this skill.` +- `Help me benchmark this plugin.` +- `What should I run next?` + +## Matching Commands + +```bash +plugin-eval start --request "Evaluate this skill." --format markdown +plugin-eval start --request "Give me a full analysis of this skill, including benchmark setup." --format markdown +plugin-eval analyze --format markdown +plugin-eval explain-budget --format markdown +plugin-eval measurement-plan --format markdown +plugin-eval init-benchmark +plugin-eval benchmark --dry-run +plugin-eval benchmark +``` + +## Output Expectations + +- Prefer the JSON result as the source of truth. +- Lead with `At a Glance`, `Why It Matters`, `Fix First`, and `Recommended Next Step`. +- Keep the `why` content terse and easy to skim. +- Call out whether budget numbers are static estimates or measured harness results. +- Show the user the exact chat phrase they can reuse next, the `plugin-eval start` command that routes it, and the first local workflow command behind it. +- When the user asks for an analysis of a named skill, do not stop at the report if benchmark setup is still missing. +- When the user is asking about a skill specifically, hand off to `../evaluate-skill/SKILL.md`. +- When the user is asking about a plugin bundle, hand off to `../evaluate-plugin/SKILL.md`. + +## References + +- `../../references/chat-first-workflows.md` +- `../../references/technical-design.md` +- `../../references/evaluation-result-schema.md` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/plugin-eval/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/plugin-eval/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bf8bec76fe7c9269c06cae91d1dc16069a642c32 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/skills/plugin-eval/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Plugin Eval" + short_description: "Choose the right local evaluation workflow" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/cli.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..6709727dce6f5b6a763ea99a935bee55e4d0860c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/cli.js @@ -0,0 +1,219 @@ +import path from "node:path"; + +import { compareResults } from "./core/compare.js"; +import { analyzePath, explainBudget, recommendMeasures } from "./core/analyze.js"; +import { initializeBenchmark, runBenchmark } from "./core/benchmark.js"; +import { buildWorkflowGuide } from "./core/workflow-guide.js"; +import { readJson, writeText } from "./lib/files.js"; +import { renderPayload } from "./renderers/index.js"; + +function usage() { + return `Plugin Eval helps first-time skill authors start from chat and keep the workflow local-first. + +Start here: + plugin-eval start [--request ""] [--goal evaluate|budget|measure|benchmark|next] [--format json|markdown|html] [--output ] + +Core workflows: + plugin-eval analyze [--format json|markdown|html] [--output ] [--metric-pack ] [--observed-usage ] [--brief-out ] + plugin-eval explain-budget [--format json|markdown] [--output ] + plugin-eval measurement-plan [--format json|markdown] [--observed-usage ] [--output ] + plugin-eval init-benchmark [--output ] [--model ] [--format json|markdown] + plugin-eval benchmark [--config ] [--usage-out ] [--result-out ] [--model ] [--format json|markdown|html] [--output ] + +Reports: + plugin-eval report [--format json|markdown|html] [--output ] + plugin-eval compare [--format json|markdown|html] [--output ] + +Chat-first examples: + plugin-eval start ./skills/my-skill --request "evaluate this skill" --format markdown + plugin-eval start ./skills/my-skill --request "measure the real token usage of this skill" --format markdown + plugin-eval start ./plugins/my-plugin --request "help me benchmark this plugin" --format markdown + plugin-eval start ./skills/my-skill --request "what should I run next?" --format markdown + +Compatibility aliases: + guide -> start + recommend-measures -> measurement-plan +`; +} + +function parseOptions(argv) { + const positional = []; + const options = { + format: "json", + output: null, + metricPackManifests: [], + observedUsagePaths: [], + configPath: null, + usageOutPath: null, + resultOutPath: null, + model: null, + goal: null, + request: null, + dryRun: false, + briefOut: null, + }; + + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === "--format") { + options.format = argv[index + 1]; + index += 1; + } else if (arg === "--output") { + options.output = argv[index + 1]; + index += 1; + } else if (arg === "--metric-pack") { + options.metricPackManifests.push(argv[index + 1]); + index += 1; + } else if (arg === "--observed-usage") { + options.observedUsagePaths.push(argv[index + 1]); + index += 1; + } else if (arg === "--config") { + options.configPath = argv[index + 1]; + index += 1; + } else if (arg === "--usage-out") { + options.usageOutPath = argv[index + 1]; + index += 1; + } else if (arg === "--result-out") { + options.resultOutPath = argv[index + 1]; + index += 1; + } else if (arg === "--model") { + options.model = argv[index + 1]; + index += 1; + } else if (arg === "--goal") { + options.goal = argv[index + 1]; + index += 1; + } else if (arg === "--request") { + options.request = argv[index + 1]; + index += 1; + } else if (arg === "--dry-run") { + options.dryRun = true; + } else if (arg === "--brief-out") { + options.briefOut = argv[index + 1]; + index += 1; + } else if (arg === "--help" || arg === "-h") { + options.help = true; + } else { + positional.push(arg); + } + } + + return { positional, options }; +} + +async function emit(payload, format, output) { + const rendered = renderPayload(payload, format); + if (output) { + await writeText(path.resolve(output), rendered); + return; + } + process.stdout.write(rendered); +} + +export async function runCli(argv) { + const [command, ...rest] = argv; + if (!command || command === "--help" || command === "-h") { + process.stdout.write(usage()); + return; + } + + const { positional, options } = parseOptions(rest); + if (options.help) { + process.stdout.write(usage()); + return; + } + + if (command === "analyze") { + if (positional.length < 1) { + throw new Error("Missing target path.\n\n" + usage()); + } + const result = await analyzePath(positional[0], { + metricPackManifests: options.metricPackManifests, + observedUsagePaths: options.observedUsagePaths, + }); + if (options.briefOut) { + await writeText(path.resolve(options.briefOut), `${JSON.stringify(result.improvementBrief, null, 2)}\n`); + } + await emit(result, options.format, options.output); + return; + } + + if (command === "report") { + if (positional.length < 1) { + throw new Error("Missing result.json path.\n\n" + usage()); + } + const result = await readJson(path.resolve(positional[0])); + await emit(result, options.format, options.output); + return; + } + + if (command === "compare") { + if (positional.length < 2) { + throw new Error("Missing before/after result paths.\n\n" + usage()); + } + const before = await readJson(path.resolve(positional[0])); + const after = await readJson(path.resolve(positional[1])); + await emit(compareResults(before, after), options.format, options.output); + return; + } + + if (command === "start" || command === "guide") { + if (positional.length < 1) { + throw new Error("Missing target path.\n\n" + usage()); + } + const payload = await buildWorkflowGuide(positional[0], { + goal: options.goal, + request: options.request, + }); + await emit(payload, options.format, options.output); + return; + } + + if (command === "explain-budget") { + if (positional.length < 1) { + throw new Error("Missing target path.\n\n" + usage()); + } + const payload = await explainBudget(positional[0]); + await emit(payload, options.format, options.output); + return; + } + + if (command === "measurement-plan" || command === "recommend-measures") { + if (positional.length < 1) { + throw new Error("Missing target path.\n\n" + usage()); + } + const payload = await recommendMeasures(positional[0], { + observedUsagePaths: options.observedUsagePaths, + }); + await emit(payload, options.format, options.output); + return; + } + + if (command === "init-benchmark") { + if (positional.length < 1) { + throw new Error("Missing target path.\n\n" + usage()); + } + const payload = await initializeBenchmark(positional[0], { + outputPath: options.output, + model: options.model, + }); + await emit(payload, options.format, null); + return; + } + + if (command === "benchmark") { + if (positional.length < 1) { + throw new Error("Missing target path.\n\n" + usage()); + } + const payload = await runBenchmark(positional[0], { + configPath: options.configPath, + usageOutPath: options.usageOutPath, + resultOutPath: options.resultOutPath, + model: options.model, + dryRun: options.dryRun, + }); + await emit(payload, options.format, options.output); + return; + } + + throw new Error(`Unknown command: ${command}\n\n${usage()}`); +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/analyze.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/analyze.js new file mode 100644 index 0000000000000000000000000000000000000000..db2543a7bc092823e22710eaf1a7598a7e16d297 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/analyze.js @@ -0,0 +1,172 @@ +import path from "node:path"; + +import { loadBudgetBaseline } from "./baseline.js"; +import { applyBudgetBands, computeBudgetProfile } from "./budget.js"; +import { buildImprovementBrief } from "./improvement-brief.js"; +import { buildMeasurementPlan } from "./measurement-plan.js"; +import { runMetricPacks } from "./metric-packs.js"; +import { analyzeObservedUsage } from "./observed-usage.js"; +import { applyEvaluationPresentation, createBudgetNextAction, createMeasurementPlanNextAction } from "./presentation.js"; +import { createArtifact, createCheck, createEvaluationResult, createMetric } from "./schema.js"; +import { computeSummary } from "./scoring.js"; +import { resolveTarget } from "./target.js"; +import { buildWorkflowGuide } from "./workflow-guide.js"; +import { analyzeCodeMetrics } from "../evaluators/code.js"; +import { analyzeCoverageArtifacts } from "../evaluators/coverage.js"; +import { evaluatePlugin } from "../evaluators/plugin.js"; +import { evaluateSkill } from "../evaluators/skill.js"; + +function appendFragment(result, fragment) { + result.checks.push(...(fragment.checks || [])); + result.metrics.push(...(fragment.metrics || [])); + result.artifacts.push(...(fragment.artifacts || [])); +} + +function addBudgetFindings(result, budgets, baselineEvidence) { + result.budgets = budgets; + const bucketNames = ["trigger_cost_tokens", "invoke_cost_tokens", "deferred_cost_tokens"]; + + for (const bucketName of bucketNames) { + const bucket = budgets[bucketName]; + result.metrics.push( + createMetric({ + id: bucketName, + category: "budget", + value: bucket.value, + unit: "tokens", + band: bucket.band, + }), + ); + + if (bucket.band === "heavy" || bucket.band === "excessive") { + result.checks.push( + createCheck({ + id: `${bucketName}-budget-high`, + category: "budget", + severity: bucket.band === "excessive" ? "error" : "warning", + status: bucket.band === "excessive" ? "fail" : "warn", + message: `${bucketName} is ${bucket.band} relative to the current Codex baseline.`, + evidence: [ + `Value: ${bucket.value} tokens`, + `Baseline samples: skills=${baselineEvidence.skillSamples}, plugins=${baselineEvidence.pluginSamples}`, + ], + remediation: ["Reduce repeated instruction text and move detail into deferred supporting files."], + }), + ); + } + } + + if (budgets.explicit_only_invoke_cost_tokens) { + result.metrics.push( + createMetric({ + id: "explicit_only_invoke_cost_tokens", + category: "budget", + value: budgets.explicit_only_invoke_cost_tokens.value, + unit: "tokens", + band: budgets.explicit_only_invoke_cost_tokens.band, + }), + ); + } + + result.artifacts.push( + createArtifact({ + id: "budget-breakdown", + type: "budget", + label: "Budget breakdown", + description: "Trigger, invoke, and deferred token budget analysis.", + data: { + budgets, + baselineEvidence, + }, + }), + ); +} + +function normalizeExtensionPayload(extension) { + return { + ...extension, + checks: extension.checks.map((check) => ({ ...check, source: `extension:${extension.name}` })), + metrics: extension.metrics.map((metric) => ({ ...metric, source: `extension:${extension.name}` })), + artifacts: extension.artifacts.map((artifact) => ({ ...artifact, source: `extension:${extension.name}` })), + }; +} + +export async function analyzePath(targetPath, options = {}) { + const target = await resolveTarget(targetPath); + const result = createEvaluationResult(target); + + if (target.kind === "skill") { + appendFragment(result, await evaluateSkill(target.path)); + } else if (target.kind === "plugin") { + appendFragment(result, await evaluatePlugin(target.path)); + } else { + result.checks.push( + createCheck({ + id: "generic-target-analysis", + category: "best-practice", + severity: "info", + status: "info", + message: "The target is not a skill or plugin root, so only generic code, coverage, and budget analysis will run.", + evidence: [path.resolve(target.path)], + remediation: ["Point the analyzer at a skill directory or plugin root for richer structural checks."], + }), + ); + } + + const baseline = await loadBudgetBaseline(); + const rawBudget = await computeBudgetProfile(target); + addBudgetFindings(result, applyBudgetBands(rawBudget, baseline), baseline.evidence); + + const observedUsageFragment = await analyzeObservedUsage(options.observedUsagePaths || [], rawBudget, target); + if (observedUsageFragment) { + result.observedUsage = observedUsageFragment.observedUsage; + appendFragment(result, observedUsageFragment); + } + + appendFragment(result, await analyzeCodeMetrics(target.path, target)); + appendFragment(result, await analyzeCoverageArtifacts(target.path)); + + const extensions = await runMetricPacks(target, options.metricPackManifests || []); + result.extensions = extensions.map(normalizeExtensionPayload); + + result.summary = computeSummary(result); + result.measurementPlan = buildMeasurementPlan(result); + result.artifacts.push(result.measurementPlan.artifact); + result.improvementBrief = buildImprovementBrief(result); + result.workflowGuide = await buildWorkflowGuide(target.path, { + goal: result.observedUsage?.sampleCount ? "measure" : "evaluate", + }); + result.measurementPlan.nextAction = createMeasurementPlanNextAction(result.measurementPlan); + applyEvaluationPresentation(result); + return result; +} + +export async function explainBudget(targetPath) { + const target = await resolveTarget(targetPath); + const baseline = await loadBudgetBaseline(); + const rawBudget = await computeBudgetProfile(target); + const payload = { + kind: "budget-explanation", + createdAt: new Date().toISOString(), + target, + budgets: applyBudgetBands(rawBudget, baseline), + baselineEvidence: baseline.evidence, + workflowGuide: await buildWorkflowGuide(target.path, { + goal: "budget", + }), + }; + payload.nextAction = createBudgetNextAction(payload); + return payload; +} + +export async function recommendMeasures(targetPath, options = {}) { + const result = await analyzePath(targetPath, options); + const payload = { + ...result.measurementPlan, + workflowGuide: await buildWorkflowGuide(result.target.path, { + goal: "measure", + }), + }; + payload.nextAction = payload.nextAction || createMeasurementPlanNextAction(payload); + return payload; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/baseline.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/baseline.js new file mode 100644 index 0000000000000000000000000000000000000000..766ce625774ec699672d9872e8aee21a542cd7c6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/baseline.js @@ -0,0 +1,132 @@ +import os from "node:os"; +import path from "node:path"; + +import { computePluginBudget, computeSkillBudget } from "./budget.js"; +import { listImmediateDirectories, pathExists, readJson, relativePath } from "../lib/files.js"; + +const DEFAULT_BASELINE = { + skill: { + trigger_cost_tokens: [48, 92, 150], + invoke_cost_tokens: [220, 480, 900], + deferred_cost_tokens: [180, 520, 1200], + }, + plugin: { + trigger_cost_tokens: [120, 260, 420], + invoke_cost_tokens: [500, 1200, 2400], + deferred_cost_tokens: [320, 900, 2200], + }, + directory: { + trigger_cost_tokens: [1, 1, 1], + invoke_cost_tokens: [1, 1, 1], + deferred_cost_tokens: [240, 640, 1600], + }, +}; + +let cachedBaseline = null; + +function quantile(values, percentile) { + if (values.length === 0) { + return 0; + } + const sorted = [...values].sort((left, right) => left - right); + const index = Math.min(sorted.length - 1, Math.max(0, Math.floor((sorted.length - 1) * percentile))); + return sorted[index]; +} + +function summarizeSamples(samples) { + if (samples.length < 4) { + return null; + } + return { + trigger_cost_tokens: [ + quantile(samples.map((sample) => sample.trigger_cost_tokens.value), 0.5), + quantile(samples.map((sample) => sample.trigger_cost_tokens.value), 0.75), + quantile(samples.map((sample) => sample.trigger_cost_tokens.value), 0.9), + ], + invoke_cost_tokens: [ + quantile(samples.map((sample) => sample.invoke_cost_tokens.value), 0.5), + quantile(samples.map((sample) => sample.invoke_cost_tokens.value), 0.75), + quantile(samples.map((sample) => sample.invoke_cost_tokens.value), 0.9), + ], + deferred_cost_tokens: [ + quantile(samples.map((sample) => sample.deferred_cost_tokens.value), 0.5), + quantile(samples.map((sample) => sample.deferred_cost_tokens.value), 0.75), + quantile(samples.map((sample) => sample.deferred_cost_tokens.value), 0.9), + ], + }; +} + +async function collectSkillSamples(skillRoot) { + if (!(await pathExists(skillRoot))) { + return []; + } + const directories = await listImmediateDirectories(skillRoot); + const samples = []; + for (const directory of directories) { + const skillPath = path.join(directory, "SKILL.md"); + if (!(await pathExists(skillPath))) { + continue; + } + try { + samples.push(await computeSkillBudget(directory)); + } catch { + // Ignore malformed shipped samples and keep the baseline usable. + } + } + return samples; +} + +async function collectPluginSamples(pluginRoot) { + if (!(await pathExists(pluginRoot))) { + return []; + } + const directories = await listImmediateDirectories(pluginRoot); + const samples = []; + for (const directory of directories) { + const manifestPath = path.join(directory, ".codex-plugin", "plugin.json"); + if (!(await pathExists(manifestPath))) { + continue; + } + try { + const manifest = await readJson(manifestPath); + samples.push(await computePluginBudget(directory, manifest)); + } catch { + // Ignore malformed shipped samples and keep the baseline usable. + } + } + return samples; +} + +export async function loadBudgetBaseline() { + if (cachedBaseline) { + return cachedBaseline; + } + + const home = os.homedir(); + const skillRoot = path.join(home, ".codex", "skills"); + const curatedPluginRoot = path.join(home, ".codex", "plugins", "cache", "openai-curated"); + const tempPluginRoot = path.join(home, ".codex", ".tmp", "plugins", "plugins"); + + const skillSamples = await collectSkillSamples(skillRoot); + const pluginSamples = [ + ...(await collectPluginSamples(curatedPluginRoot)), + ...(await collectPluginSamples(tempPluginRoot)), + ]; + + cachedBaseline = { + skill: summarizeSamples(skillSamples) || DEFAULT_BASELINE.skill, + plugin: summarizeSamples(pluginSamples) || DEFAULT_BASELINE.plugin, + directory: DEFAULT_BASELINE.directory, + evidence: { + skillSamples: skillSamples.length, + pluginSamples: pluginSamples.length, + sourceRoots: [ + relativePath(process.cwd(), skillRoot), + relativePath(process.cwd(), curatedPluginRoot), + relativePath(process.cwd(), tempPluginRoot), + ], + }, + }; + + return cachedBaseline; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark-events.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark-events.js new file mode 100644 index 0000000000000000000000000000000000000000..edb660fe1e3312ec1e2e80f7776ee02a06c68a7d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark-events.js @@ -0,0 +1,233 @@ +function toNumber(value) { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} + +function normalizeUsageCandidate(candidate) { + if (!candidate || typeof candidate !== "object") { + return null; + } + + const usage = candidate.usage && typeof candidate.usage === "object" + ? candidate.usage + : candidate.response?.usage && typeof candidate.response?.usage === "object" + ? candidate.response.usage + : candidate; + + const inputTokens = toNumber(usage.input_tokens); + const outputTokens = toNumber(usage.output_tokens); + const totalTokens = toNumber(usage.total_tokens) ?? ((inputTokens || 0) + (outputTokens || 0)); + + if (inputTokens === null && outputTokens === null && totalTokens === null) { + return null; + } + + return { + input_tokens: inputTokens || 0, + output_tokens: outputTokens || 0, + total_tokens: totalTokens || 0, + ...(usage.input_token_details ? { input_token_details: usage.input_token_details } : {}), + ...(usage.output_token_details ? { output_token_details: usage.output_token_details } : {}), + ...(usage.output_tokens_details ? { output_tokens_details: usage.output_tokens_details } : {}), + raw: usage, + }; +} + +function collectUsageCandidate(value, matches) { + if (!value || typeof value !== "object") { + return; + } + + const normalized = normalizeUsageCandidate(value); + if (normalized) { + matches.push(normalized); + } + + if (Array.isArray(value)) { + for (const item of value) { + collectUsageCandidate(item, matches); + } + return; + } + + for (const nested of Object.values(value)) { + collectUsageCandidate(nested, matches); + } +} + +function extractLatestUsage(events) { + const matches = []; + for (const event of events) { + collectUsageCandidate(event, matches); + } + return matches.length > 0 ? matches[matches.length - 1] : null; +} + +function collectErrorMessage(event) { + if (!event || typeof event !== "object") { + return null; + } + + if (typeof event.message === "string" && event.type === "error") { + return event.message; + } + + if (typeof event.error?.message === "string") { + return event.error.message; + } + + return null; +} + +function extractShellCommand(event) { + if (!event || typeof event !== "object") { + return null; + } + + const candidates = [ + event.command, + event.cmd, + event.parameters?.cmd, + event.arguments?.cmd, + event.payload?.command, + event.payload?.cmd, + ]; + + for (const candidate of candidates) { + if (typeof candidate === "string" && candidate.trim()) { + return candidate.trim(); + } + } + + if (event.recipient_name === "functions.exec_command") { + return event.parameters?.cmd || event.arguments?.cmd || event.command || "functions.exec_command"; + } + + return null; +} + +function extractToolName(event) { + if (!event || typeof event !== "object") { + return null; + } + + const candidates = [ + event.tool_name, + event.tool?.name, + event.name, + event.recipient_name, + event.payload?.tool_name, + ]; + + for (const candidate of candidates) { + if (typeof candidate === "string" && candidate.trim()) { + return candidate.trim(); + } + } + + if (typeof event.type === "string" && event.type.includes("tool")) { + return event.type; + } + + return null; +} + +function isShellEvent(event) { + const type = typeof event?.type === "string" ? event.type : ""; + return Boolean( + extractShellCommand(event) || + type.includes("exec_command") || + type.includes("shell"), + ); +} + +function isToolEvent(event) { + const type = typeof event?.type === "string" ? event.type : ""; + return Boolean( + extractToolName(event) || + type.includes("tool"), + ); +} + +function isFailureEvent(event) { + const type = typeof event?.type === "string" ? event.type : ""; + return type.includes("failed") || type === "error" || Boolean(event?.error); +} + +export function parseCodexJsonStream(text) { + const lines = String(text || "").split(/\r?\n/); + const events = []; + const ignoredLines = []; + + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed) { + continue; + } + + try { + events.push(JSON.parse(trimmed)); + } catch { + ignoredLines.push(line); + } + } + + return { + events, + ignoredLines, + }; +} + +export function summarizeCodexEvents(events) { + const errorMessages = []; + const toolNames = []; + const shellCommands = []; + const failedShellCommands = []; + let threadId = null; + let turnFailed = false; + + for (const event of events) { + if (!threadId && typeof event.thread_id === "string") { + threadId = event.thread_id; + } + + const errorMessage = collectErrorMessage(event); + if (errorMessage) { + errorMessages.push(errorMessage); + } + + if (isToolEvent(event)) { + toolNames.push(extractToolName(event) || event.type || "tool"); + } + + if (isShellEvent(event)) { + const command = extractShellCommand(event) || event.type || "shell"; + shellCommands.push(command); + if (isFailureEvent(event)) { + failedShellCommands.push(command); + } + } + + if (event.type === "turn.failed") { + turnFailed = true; + } + } + + const usage = extractLatestUsage(events); + const completed = events.some((event) => event.type === "turn.completed"); + const failed = turnFailed || events.some((event) => event.type === "turn.cancelled"); + + return { + threadId, + eventCount: events.length, + ignoredLineCount: 0, + finalStatus: failed ? "failed" : completed ? "completed" : "unknown", + errorMessages, + toolCallCount: toolNames.length, + shellCommandCount: shellCommands.length, + failedShellCommandCount: failedShellCommands.length, + toolNames, + shellCommands, + usage, + usageAvailability: usage ? "present" : "unavailable", + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark-workspace.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark-workspace.js new file mode 100644 index 0000000000000000000000000000000000000000..20e5c4d358a0db741168f15de5d63445b1967012 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark-workspace.js @@ -0,0 +1,291 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; + +import { isProbablyTextFile, isDirectory, readText, relativePath } from "../lib/files.js"; + +const execFileAsync = promisify(execFile); + +const SNAPSHOT_IGNORED_DIRS = new Set([ + ".git", + "node_modules", + "dist", + "build", + ".next", + ".turbo", + ".cache", + ".tmp", + ".venv", + "venv", + "__pycache__", + ".pytest_cache", + ".plugin-eval", +]); + +function testFilePattern(filePath) { + return /(^|\/)(tests?|__tests__)\/|(\.test|\.spec)\.|(^|\/)test_[^/]+\.py$/.test(filePath); +} + +async function copyDirectory(sourcePath, destinationPath) { + await fs.mkdir(path.dirname(destinationPath), { recursive: true }); + await fs.cp(sourcePath, destinationPath, { recursive: true }); +} + +async function copyIfExists(sourcePath, destinationPath) { + try { + await fs.access(sourcePath); + } catch { + return false; + } + + await fs.mkdir(path.dirname(destinationPath), { recursive: true }); + await fs.copyFile(sourcePath, destinationPath); + return true; +} + +async function resolveGitRoot(sourcePath) { + const { stdout } = await execFileAsync("git", ["-C", sourcePath, "rev-parse", "--show-toplevel"]); + return stdout.trim(); +} + +async function createWorkspaceCopy(sourcePath, workspacePath) { + await copyDirectory(sourcePath, workspacePath); + return { + workspacePath, + cleanup: async () => { + await fs.rm(workspacePath, { recursive: true, force: true }); + }, + }; +} + +async function createWorkspaceFromGitWorktree(sourcePath, workspacePath) { + const repoRoot = await resolveGitRoot(sourcePath); + await execFileAsync("git", ["-C", repoRoot, "worktree", "add", "--detach", workspacePath]); + return { + workspacePath, + cleanup: async () => { + await execFileAsync("git", ["-C", repoRoot, "worktree", "remove", "--force", workspacePath]); + }, + }; +} + +async function provisionSkillInstall(target, codexHomePath) { + const skillPath = path.join(codexHomePath, "skills", target.name); + await copyDirectory(target.path, skillPath); + return skillPath; +} + +async function provisionPluginInstall(target, workspacePath) { + const pluginsRoot = path.join(workspacePath, "plugins"); + const installPath = path.join(pluginsRoot, target.name); + await copyDirectory(target.path, installPath); + + const marketplacePath = path.join(workspacePath, ".agents", "plugins", "marketplace.json"); + const marketplace = { + name: "plugin-eval-benchmark", + interface: { + displayName: "Plugin Eval Benchmark", + }, + plugins: [ + { + name: target.name, + source: { + source: "local", + path: `./plugins/${target.name}`, + }, + policy: { + installation: "AVAILABLE", + authentication: "ON_INSTALL", + }, + category: "Developer Tools", + }, + ], + }; + + await fs.mkdir(path.dirname(marketplacePath), { recursive: true }); + await fs.writeFile(marketplacePath, `${JSON.stringify(marketplace, null, 2)}\n`, "utf8"); + return installPath; +} + +async function seedCodexHome(codexHomePath) { + const sourceCodexHome = process.env.PLUGIN_EVAL_CODEX_HOME_SOURCE + ? path.resolve(process.env.PLUGIN_EVAL_CODEX_HOME_SOURCE) + : path.join(os.homedir(), ".codex"); + + await fs.mkdir(codexHomePath, { recursive: true }); + await Promise.all([ + copyIfExists(path.join(sourceCodexHome, "auth.json"), path.join(codexHomePath, "auth.json")), + copyIfExists(path.join(sourceCodexHome, "config.toml"), path.join(codexHomePath, "config.toml")), + ]); +} + +export function defaultTargetProvisioningMode(target) { + if (target.kind === "skill") { + return "isolated-skill-home"; + } + if (target.kind === "plugin") { + return "workspace-plugin-marketplace"; + } + throw new Error("Benchmarking only supports Codex skills and plugins."); +} + +export async function provisionBenchmarkWorkspace({ target, config, scenarioId }) { + const sourcePath = path.resolve(config.workspace.sourcePath); + if (!(await isDirectory(sourcePath))) { + throw new Error(`Benchmark workspace.sourcePath must be a directory: ${sourcePath}`); + } + + const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), `plugin-eval-${scenarioId}-`)); + const workspacePath = path.join(tempRoot, "workspace"); + const homePath = path.join(tempRoot, "home"); + const codexHomePath = path.join(homePath, ".codex"); + const setupMode = config.workspace.setupMode || "copy"; + + await seedCodexHome(codexHomePath); + + const workspace = + setupMode === "git-worktree" + ? await createWorkspaceFromGitWorktree(sourcePath, workspacePath) + : await createWorkspaceCopy(sourcePath, workspacePath); + + let installedTargetPath = null; + if (config.targetProvisioning.mode === "isolated-skill-home") { + installedTargetPath = await provisionSkillInstall(target, codexHomePath); + } else if (config.targetProvisioning.mode === "workspace-plugin-marketplace") { + installedTargetPath = await provisionPluginInstall(target, workspacePath); + } else { + throw new Error(`Unsupported target provisioning mode: ${config.targetProvisioning.mode}`); + } + + return { + tempRoot, + workspacePath, + homePath, + codexHomePath, + installedTargetPath, + setupMode, + cleanup: async () => { + await workspace.cleanup(); + await fs.rm(tempRoot, { recursive: true, force: true }); + }, + }; +} + +async function hashFile(filePath) { + const hash = createHash("sha1"); + hash.update(await fs.readFile(filePath)); + return hash.digest("hex"); +} + +async function visitSnapshot(rootPath, currentPath, entries) { + const directoryEntries = await fs.readdir(currentPath, { withFileTypes: true }); + + for (const entry of directoryEntries) { + const entryPath = path.join(currentPath, entry.name); + const relativeEntryPath = relativePath(rootPath, entryPath); + + if (entry.isDirectory()) { + if (SNAPSHOT_IGNORED_DIRS.has(entry.name)) { + continue; + } + await visitSnapshot(rootPath, entryPath, entries); + continue; + } + + if (!entry.isFile()) { + continue; + } + + const stats = await fs.stat(entryPath); + const isText = isProbablyTextFile(entryPath); + const text = isText ? await readText(entryPath) : null; + + entries.set(relativeEntryPath, { + path: relativeEntryPath, + absolutePath: entryPath, + size: stats.size, + hash: await hashFile(entryPath), + isText, + lineCount: text === null ? null : text.replace(/\r\n/g, "\n").split("\n").length, + }); + } +} + +export async function snapshotWorkspace(rootPath) { + const entries = new Map(); + await visitSnapshot(rootPath, rootPath, entries); + return entries; +} + +export function diffWorkspaceSnapshots(beforeSnapshot, afterSnapshot) { + const added = []; + const modified = []; + const deleted = []; + + for (const [filePath, afterEntry] of afterSnapshot.entries()) { + const beforeEntry = beforeSnapshot.get(filePath); + if (!beforeEntry) { + added.push({ + path: filePath, + status: "added", + isText: afterEntry.isText, + lineCountBefore: 0, + lineCountAfter: afterEntry.lineCount, + lineDelta: typeof afterEntry.lineCount === "number" ? afterEntry.lineCount : null, + }); + continue; + } + + if (beforeEntry.hash !== afterEntry.hash) { + modified.push({ + path: filePath, + status: "modified", + isText: afterEntry.isText || beforeEntry.isText, + lineCountBefore: beforeEntry.lineCount, + lineCountAfter: afterEntry.lineCount, + lineDelta: + typeof beforeEntry.lineCount === "number" && typeof afterEntry.lineCount === "number" + ? afterEntry.lineCount - beforeEntry.lineCount + : null, + }); + } + } + + for (const [filePath, beforeEntry] of beforeSnapshot.entries()) { + if (!afterSnapshot.has(filePath)) { + deleted.push({ + path: filePath, + status: "deleted", + isText: beforeEntry.isText, + lineCountBefore: beforeEntry.lineCount, + lineCountAfter: 0, + lineDelta: typeof beforeEntry.lineCount === "number" ? -beforeEntry.lineCount : null, + }); + } + } + + return { + added: added.sort((a, b) => a.path.localeCompare(b.path)), + modified: modified.sort((a, b) => a.path.localeCompare(b.path)), + deleted: deleted.sort((a, b) => a.path.localeCompare(b.path)), + }; +} + +export function summarizeWorkspaceDiff(diff) { + const changedFiles = [...diff.added, ...diff.modified]; + return { + addedFileCount: diff.added.length, + modifiedFileCount: diff.modified.length, + deletedFileCount: diff.deleted.length, + changedFileCount: changedFiles.length, + generatedFileCount: diff.added.length, + generatedTestFileCount: diff.added.filter((entry) => testFilePattern(entry.path)).length, + changedTestFileCount: changedFiles.filter((entry) => testFilePattern(entry.path)).length, + changedTextLineDelta: changedFiles.reduce((sum, entry) => sum + (entry.lineDelta || 0), 0), + changedFiles, + allChanges: [...diff.added, ...diff.modified, ...diff.deleted], + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark.js new file mode 100644 index 0000000000000000000000000000000000000000..5a6c89b70c28bd9aa6a185ee1fae224ae6c8ebdd --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/benchmark.js @@ -0,0 +1,681 @@ +import { spawn } from "node:child_process"; +import fs from "node:fs/promises"; +import path from "node:path"; + +import { analyzeCoverageArtifacts } from "../evaluators/coverage.js"; +import { analyzePythonFiles } from "../evaluators/python.js"; +import { analyzeTypeScriptFiles } from "../evaluators/typescript.js"; +import { formatCommandPath, pathExists, readJson, readText, relativePath, writeJson, writeText } from "../lib/files.js"; +import { createBenchmarkRunNextAction, createBenchmarkTemplateNextAction } from "./presentation.js"; +import { createArtifact } from "./schema.js"; +import { summarizeCodexEvents, parseCodexJsonStream } from "./benchmark-events.js"; +import { + defaultTargetProvisioningMode, + diffWorkspaceSnapshots, + provisionBenchmarkWorkspace, + snapshotWorkspace, + summarizeWorkspaceDiff, +} from "./benchmark-workspace.js"; +import { resolveTarget } from "./target.js"; +import { buildWorkflowGuide } from "./workflow-guide.js"; + +const BENCHMARK_SCHEMA_VERSION = 2; + +function sanitizeId(value) { + return String(value || "scenario") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") || "scenario"; +} + +function benchmarkDirectoryForTarget(target) { + return path.join(target.path, ".plugin-eval"); +} + +function benchmarkRunsDirectoryForTarget(target) { + return path.join(benchmarkDirectoryForTarget(target), "runs"); +} + +function defaultBenchmarkConfigPath(target) { + return path.join(benchmarkDirectoryForTarget(target), "benchmark.json"); +} + +function defaultUsageLogPath(target) { + return path.join(benchmarkDirectoryForTarget(target), "benchmark-usage.jsonl"); +} + +function defaultModelForTarget(target) { + return target.kind === "plugin" ? "gpt-5.4" : "gpt-5.4-mini"; +} + +function createRunId() { + return new Date().toISOString().replaceAll(":", "-").replace(/\..+$/, ""); +} + +function normalizeScenario(scenario, index) { + return { + id: sanitizeId(scenario.id || scenario.title || `scenario-${index + 1}`), + title: scenario.title || `Scenario ${index + 1}`, + purpose: scenario.purpose || "", + userInput: scenario.userInput || "", + successChecklist: Array.isArray(scenario.successChecklist) ? scenario.successChecklist : [], + }; +} + +function normalizeConfig(config, target) { + if (config?.schemaVersion === 1 || config?.harnessPrompt || config?.baseUrl || config?.apiKeyEnv) { + throw new Error( + "Legacy Responses-style benchmark configs are no longer supported. Re-run `plugin-eval init-benchmark ` to generate a CLI-only Codex benchmark config.", + ); + } + + if (!config || config.kind !== "plugin-eval-benchmark") { + throw new Error("Invalid benchmark config. Expected a plugin-eval benchmark config file."); + } + + if (config.schemaVersion !== BENCHMARK_SCHEMA_VERSION) { + throw new Error( + `Unsupported benchmark schema version: ${config.schemaVersion}. Re-run \`plugin-eval init-benchmark ${formatCommandPath(target.path)}\` to regenerate the config.`, + ); + } + + if (config.runner?.type !== "codex-cli") { + throw new Error("Benchmark runner.type must be \"codex-cli\"."); + } + + if (!config.workspace?.sourcePath) { + throw new Error("Benchmark config must set workspace.sourcePath."); + } + + if (!config.targetProvisioning?.mode) { + throw new Error("Benchmark config must set targetProvisioning.mode."); + } + + return config; +} + +function buildSetupQuestions(target) { + const label = target.kind === "plugin" ? "plugin" : "skill"; + return [ + `What are the 3 highest-value real tasks this ${label} should help complete inside a workspace?`, + `Which scenario is the must-pass end-to-end task for this ${label}?`, + `What output should exist on disk if the scenario succeeds?`, + `Which verification command would tell you the result is actually usable?`, + `What boundary case should this ${label} narrow, refuse, or hand off instead of overreaching on?`, + ]; +} + +function buildSkillScenarios(target) { + return [ + { + id: "happy-path", + title: "Happy path implementation", + purpose: "Run a representative task that should clearly justify using this skill inside the workspace.", + userInput: `Use the local Codex skill "${target.name}" if it helps. Complete a representative task for this skill in the current workspace and leave the result on disk.`, + successChecklist: [ + "The task is completed in the workspace, not only described.", + "The final answer explains what changed.", + "The run stays aligned with the skill's specialty.", + ], + }, + { + id: "follow-up", + title: "Focused refinement", + purpose: "Measure whether the skill can improve an implementation cleanly instead of restarting from scratch.", + userInput: `Use the local Codex skill "${target.name}" if it helps. Refine or extend the current workspace with one focused follow-up improvement and finish the change end to end.`, + successChecklist: [ + "The result makes a concrete change on disk.", + "The follow-up remains scoped and coherent.", + ], + }, + { + id: "boundary-case", + title: "Boundary handling", + purpose: "Check whether the skill avoids overreaching when the task is only a partial fit.", + userInput: `This task is only a partial match for the local Codex skill "${target.name}". Handle the appropriate slice in the workspace and narrow or refuse the rest honestly.`, + successChecklist: [ + "The run sets good boundaries instead of pretending the skill fits everything.", + "Any edits stay aligned with the justified scope.", + ], + }, + ]; +} + +function buildPluginScenarios(target) { + return [ + { + id: "entrypoint-routing", + title: "Entrypoint routing", + purpose: "Check whether the plugin routes a representative request through the right capability and finishes the task in the workspace.", + userInput: `Use the local Codex plugin "${target.name}" if it helps. Handle a representative request for this plugin in the current workspace and finish the task.`, + successChecklist: [ + "The run uses the right plugin capability.", + "The result changes the workspace instead of only describing work.", + ], + }, + { + id: "multi-skill-follow-up", + title: "Multi-capability follow-up", + purpose: "Measure whether a second request stays coherent when the plugin needs a different angle.", + userInput: `Use the local Codex plugin "${target.name}" if it helps. Complete a follow-up task in the current workspace that needs a different angle from the same plugin, and keep the result cohesive.`, + successChecklist: [ + "The task completes end to end.", + "The run stays coherent instead of redoing unrelated work.", + ], + }, + { + id: "plugin-boundary", + title: "Plugin boundary", + purpose: "Check whether the plugin narrows scope when the request is a weak match.", + userInput: `This task is a weak match for the local Codex plugin "${target.name}". Handle the appropriate slice in the workspace, leave unrelated work alone, and explain the boundary clearly.`, + successChecklist: [ + "The run narrows scope instead of forcing a bad fit.", + "Any edits stay justified by the request.", + ], + }, + ]; +} + +async function createStarterBenchmarkConfig(target, options = {}) { + if (!["skill", "plugin"].includes(target.kind)) { + throw new Error("Benchmarking only supports Codex skills and plugins."); + } + + return { + kind: "plugin-eval-benchmark", + schemaVersion: BENCHMARK_SCHEMA_VERSION, + version: BENCHMARK_SCHEMA_VERSION, + targetKind: target.kind, + targetName: target.name, + runner: { + type: "codex-cli", + model: options.model || defaultModelForTarget(target), + sandbox: "workspace-write", + approvalPolicy: "never", + extraArgs: [], + }, + workspace: { + sourcePath: path.resolve(options.sourcePath || process.cwd()), + setupMode: "copy", + preserve: "on-failure", + }, + targetProvisioning: { + mode: defaultTargetProvisioningMode(target), + }, + verifiers: { + commands: [], + }, + notes: [ + "Edit workspace.sourcePath so it points at the repo or template you want Codex to work inside.", + "Edit the scenarios so they match real tasks instead of generic starter prompts.", + "Benchmark means real codex exec runs now. There is no simulated dry-run mode.", + ], + setupQuestions: buildSetupQuestions(target), + scenarios: target.kind === "plugin" ? buildPluginScenarios(target) : buildSkillScenarios(target), + }; +} + +async function loadBenchmarkConfig(target, options = {}) { + if (options.configPath) { + const config = readJson(path.resolve(options.configPath)); + return { + config: normalizeConfig(await config, target), + configPath: path.resolve(options.configPath), + source: "file", + }; + } + + const defaultConfigPath = defaultBenchmarkConfigPath(target); + if (await pathExists(defaultConfigPath)) { + const config = await readJson(defaultConfigPath); + return { + config: normalizeConfig(config, target), + configPath: defaultConfigPath, + source: "file", + }; + } + + const generated = await createStarterBenchmarkConfig(target, options); + return { + config: generated, + configPath: null, + source: "generated", + }; +} + +async function runProcessCapture({ + command, + args, + cwd, + env, + stdoutPath, + stderrPath, +}) { + const startedAt = Date.now(); + const child = spawn(command, args, { + cwd, + env, + stdio: ["ignore", "pipe", "pipe"], + }); + + const stdoutChunks = []; + const stderrChunks = []; + + if (child.stdout) { + child.stdout.on("data", (chunk) => { + stdoutChunks.push(chunk); + }); + } + + if (child.stderr) { + child.stderr.on("data", (chunk) => { + stderrChunks.push(chunk); + }); + } + + const outcome = await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", (code, signal) => { + resolve({ code: code ?? 1, signal }); + }); + }); + + const stdoutText = Buffer.concat(stdoutChunks).toString("utf8"); + const stderrText = Buffer.concat(stderrChunks).toString("utf8"); + + if (stdoutPath) { + await writeText(stdoutPath, stdoutText); + } + if (stderrPath) { + await writeText(stderrPath, stderrText); + } + + return { + ...outcome, + durationMs: Date.now() - startedAt, + stdoutText, + stderrText, + }; +} + +function buildObservedUsageLine(target, scenario, usage) { + return JSON.stringify({ + id: `${target.name}-${scenario.id}`, + usage: usage.raw || usage, + metadata: { + scenario: scenario.title, + scenario_id: scenario.id, + benchmark_target_name: target.name, + benchmark_target_kind: target.kind, + }, + }); +} + +function tomlString(value) { + return JSON.stringify(String(value)); +} + +function buildCodexExecArgs({ + config, + model, + workspacePath, + finalMessagePath, + prompt, +}) { + return [ + "exec", + "--json", + "--ephemeral", + "--skip-git-repo-check", + "--cd", + workspacePath, + "--output-last-message", + finalMessagePath, + "-s", + config.runner.sandbox || "workspace-write", + "-c", + `approval_policy=${tomlString(config.runner.approvalPolicy || "never")}`, + "-m", + model, + ...(Array.isArray(config.runner.extraArgs) ? config.runner.extraArgs : []), + prompt, + ]; +} + +function filterCodeFiles(filePaths) { + const tsFiles = []; + const pyFiles = []; + + for (const filePath of filePaths) { + const extension = path.extname(filePath).toLowerCase(); + if ([".ts", ".tsx", ".mts", ".cts"].includes(extension)) { + tsFiles.push(filePath); + } else if (extension === ".py") { + pyFiles.push(filePath); + } + } + + return { tsFiles, pyFiles }; +} + +async function analyzeChangedWorkspaceCode(workspacePath, changedRelativePaths) { + const absoluteFilePaths = changedRelativePaths + .map((filePath) => path.join(workspacePath, filePath)) + .filter((filePath) => path.extname(filePath)); + const { tsFiles, pyFiles } = filterCodeFiles(absoluteFilePaths); + const tsAnalysis = await analyzeTypeScriptFiles(tsFiles, workspacePath); + const pyAnalysis = await analyzePythonFiles(pyFiles, workspacePath); + const coverageAnalysis = await analyzeCoverageArtifacts(workspacePath); + + return { + checks: [...tsAnalysis.checks, ...pyAnalysis.checks, ...coverageAnalysis.checks], + metrics: [...tsAnalysis.metrics, ...pyAnalysis.metrics, ...coverageAnalysis.metrics], + artifacts: [...tsAnalysis.artifacts, ...pyAnalysis.artifacts, ...coverageAnalysis.artifacts], + }; +} + +async function runVerifierCommands({ commands, cwd, processRunner, basePath }) { + const results = []; + + for (let index = 0; index < commands.length; index += 1) { + const command = commands[index]; + const stdoutPath = path.join(basePath, `verifier-${index + 1}.stdout.log`); + const stderrPath = path.join(basePath, `verifier-${index + 1}.stderr.log`); + const outcome = await processRunner({ + kind: "verifier", + command: "/bin/zsh", + args: ["-lc", command], + cwd, + env: process.env, + stdoutPath, + stderrPath, + }); + + results.push({ + command, + status: outcome.code === 0 ? "passed" : "failed", + exitCode: outcome.code, + signal: outcome.signal || null, + durationMs: outcome.durationMs, + stdoutPath, + stderrPath, + }); + } + + return results; +} + +function summarizeRunScenarios(runScenarios) { + const usageSamples = runScenarios.filter((scenario) => scenario.usage); + const completedScenarios = runScenarios.filter((scenario) => scenario.status === "completed").length; + const failedScenarios = runScenarios.filter((scenario) => scenario.status !== "completed").length; + const input = usageSamples.reduce((sum, scenario) => sum + (scenario.usage?.input_tokens || 0), 0); + const output = usageSamples.reduce((sum, scenario) => sum + (scenario.usage?.output_tokens || 0), 0); + const total = usageSamples.reduce((sum, scenario) => sum + (scenario.usage?.total_tokens || 0), 0); + const generatedFileCount = runScenarios.reduce((sum, scenario) => sum + (scenario.workspaceSummary?.generatedFileCount || 0), 0); + const generatedTestFileCount = runScenarios.reduce((sum, scenario) => sum + (scenario.workspaceSummary?.generatedTestFileCount || 0), 0); + const toolCallCount = runScenarios.reduce((sum, scenario) => sum + (scenario.telemetry?.toolCallCount || 0), 0); + const shellCommandCount = runScenarios.reduce((sum, scenario) => sum + (scenario.telemetry?.shellCommandCount || 0), 0); + const failedShellCommands = runScenarios.reduce((sum, scenario) => sum + (scenario.telemetry?.failedShellCommandCount || 0), 0); + const verifierPassCount = runScenarios.reduce( + (sum, scenario) => sum + scenario.verifierResults.filter((result) => result.status === "passed").length, + 0, + ); + const verifierFailCount = runScenarios.reduce( + (sum, scenario) => sum + scenario.verifierResults.filter((result) => result.status === "failed").length, + 0, + ); + + return { + scenarioCount: runScenarios.length, + completedScenarios, + failedScenarios, + sampleCount: usageSamples.length, + usageAvailability: + usageSamples.length === 0 + ? "unavailable" + : usageSamples.length === runScenarios.length + ? "present" + : "partial", + averageInputTokens: usageSamples.length > 0 ? Number((input / usageSamples.length).toFixed(2)) : 0, + averageOutputTokens: usageSamples.length > 0 ? Number((output / usageSamples.length).toFixed(2)) : 0, + averageTotalTokens: usageSamples.length > 0 ? Number((total / usageSamples.length).toFixed(2)) : 0, + generatedFileCount, + generatedTestFileCount, + toolCallCount, + shellCommandCount, + failedShellCommands, + verifierPassCount, + verifierFailCount, + }; +} + +export async function initializeBenchmark(targetPath, options = {}) { + const target = await resolveTarget(targetPath); + const config = await createStarterBenchmarkConfig(target, options); + const outputPath = path.resolve(options.outputPath || defaultBenchmarkConfigPath(target)); + await writeJson(outputPath, config); + + const payload = { + kind: "benchmark-template-init", + createdAt: new Date().toISOString(), + target: { + ...target, + relativePath: relativePath(process.cwd(), target.path), + }, + configPath: outputPath, + scenarioCount: config.scenarios.length, + notes: config.notes, + setupQuestions: config.setupQuestions || [], + nextSteps: [ + `Edit ${formatCommandPath(outputPath)} so workspace.sourcePath, scenarios, and verifiers match your real workflow.`, + `Run the benchmark with: plugin-eval benchmark ${formatCommandPath(target.path)} --config ${formatCommandPath(outputPath)}`, + "The benchmark result will be written under .plugin-eval/runs//benchmark-run.json.", + ], + workflowGuide: await buildWorkflowGuide(target.path, { + goal: "benchmark", + }), + artifact: createArtifact({ + id: "benchmark-template", + type: "benchmark-template", + label: "Benchmark template", + description: "Starter benchmark config for Codex CLI execution.", + path: outputPath, + }), + }; + payload.nextAction = createBenchmarkTemplateNextAction(payload); + return payload; +} + +export async function runBenchmark(targetPath, options = {}) { + const target = await resolveTarget(targetPath); + const { config, configPath, source } = await loadBenchmarkConfig(target, options); + const scenarios = (config.scenarios || []).map(normalizeScenario).filter((scenario) => scenario.userInput); + if (scenarios.length === 0) { + throw new Error("Benchmark config does not contain any runnable scenarios."); + } + if (options.dryRun) { + throw new Error("CLI-only benchmarking no longer supports --dry-run. Edit the benchmark config, then run `plugin-eval benchmark` for a real Codex execution."); + } + + const processRunner = options.processRunner || runProcessCapture; + const codexExecutable = options.codexExecutable || process.env.PLUGIN_EVAL_CODEX_EXECUTABLE || "codex"; + const runId = createRunId(); + const runDirectory = path.join(benchmarkRunsDirectoryForTarget(target), runId); + await fs.mkdir(runDirectory, { recursive: true }); + + let codexVersion = "unknown"; + try { + const versionResult = await processRunner({ + kind: "codex-version", + command: codexExecutable, + args: ["--version"], + cwd: process.cwd(), + env: process.env, + stdoutPath: path.join(runDirectory, "codex-version.stdout.log"), + stderrPath: path.join(runDirectory, "codex-version.stderr.log"), + }); + codexVersion = (versionResult.stdoutText || versionResult.stderrText || "unknown").trim().split(/\r?\n/).pop() || "unknown"; + } catch { + codexVersion = "unknown"; + } + + const usageLines = []; + const runScenarios = []; + + for (let index = 0; index < scenarios.length; index += 1) { + const scenario = scenarios[index]; + const scenarioDirectory = path.join(runDirectory, `${String(index + 1).padStart(2, "0")}-${scenario.id}`); + await fs.mkdir(scenarioDirectory, { recursive: true }); + + const provisioned = await provisionBenchmarkWorkspace({ + target, + config, + scenarioId: scenario.id, + }); + const beforeSnapshot = await snapshotWorkspace(provisioned.workspacePath); + const stdoutPath = path.join(scenarioDirectory, "codex.stdout.jsonl"); + const stderrPath = path.join(scenarioDirectory, "codex.stderr.log"); + const finalMessagePath = path.join(scenarioDirectory, "final-message.txt"); + + const args = buildCodexExecArgs({ + config, + model: options.model || config.runner.model || defaultModelForTarget(target), + workspacePath: provisioned.workspacePath, + finalMessagePath, + prompt: scenario.userInput, + }); + + const codexRun = await processRunner({ + kind: "codex", + command: codexExecutable, + args, + cwd: provisioned.workspacePath, + env: { + ...process.env, + HOME: provisioned.homePath, + CODEX_HOME: provisioned.codexHomePath, + }, + stdoutPath, + stderrPath, + }); + + const parsedEvents = parseCodexJsonStream(codexRun.stdoutText); + const telemetry = summarizeCodexEvents(parsedEvents.events); + telemetry.ignoredLineCount = parsedEvents.ignoredLines.length; + + const afterSnapshot = await snapshotWorkspace(provisioned.workspacePath); + const workspaceDiff = diffWorkspaceSnapshots(beforeSnapshot, afterSnapshot); + const workspaceSummary = summarizeWorkspaceDiff(workspaceDiff); + const generatedCode = await analyzeChangedWorkspaceCode( + provisioned.workspacePath, + workspaceSummary.changedFiles.map((entry) => entry.path), + ); + const verifierResults = await runVerifierCommands({ + commands: Array.isArray(config.verifiers?.commands) ? config.verifiers.commands : [], + cwd: provisioned.workspacePath, + processRunner, + basePath: scenarioDirectory, + }); + + const finalMessage = await readText(finalMessagePath).catch(() => ""); + const codexSucceeded = codexRun.code === 0 && telemetry.finalStatus !== "failed"; + const verifiersPassed = verifierResults.every((result) => result.status === "passed"); + const scenarioStatus = codexSucceeded && verifiersPassed ? "completed" : "failed"; + + if (telemetry.usage) { + usageLines.push(buildObservedUsageLine(target, scenario, telemetry.usage)); + } + + const preserveMode = config.workspace.preserve || "on-failure"; + const shouldPreserveWorkspace = + preserveMode === "always" || + (preserveMode === "on-failure" && scenarioStatus !== "completed"); + + runScenarios.push({ + id: scenario.id, + title: scenario.title, + purpose: scenario.purpose, + successChecklist: scenario.successChecklist, + status: scenarioStatus, + exitCode: codexRun.code, + signal: codexRun.signal || null, + durationMs: codexRun.durationMs, + prompt: scenario.userInput, + finalMessagePath: await pathExists(finalMessagePath) ? finalMessagePath : null, + finalMessagePreview: finalMessage.trim() || null, + rawEventLogPath: stdoutPath, + stderrLogPath: stderrPath, + usage: telemetry.usage, + usageAvailability: telemetry.usageAvailability, + telemetry, + workspacePath: shouldPreserveWorkspace ? provisioned.workspacePath : null, + workspaceSummary, + workspaceChanges: workspaceSummary.allChanges, + generatedCode, + verifierResults, + installedTargetPath: provisioned.installedTargetPath, + codexHomePath: provisioned.codexHomePath, + }); + + if (!shouldPreserveWorkspace) { + await provisioned.cleanup(); + } + } + + const usageOutPath = usageLines.length > 0 + ? path.resolve(options.usageOutPath || defaultUsageLogPath(target)) + : null; + if (usageOutPath) { + await writeText(usageOutPath, `${usageLines.join("\n")}\n`); + await writeText(path.join(runDirectory, "observed-usage.jsonl"), `${usageLines.join("\n")}\n`); + } + + const resultOutPath = path.resolve(options.resultOutPath || path.join(runDirectory, "benchmark-run.json")); + const summary = summarizeRunScenarios(runScenarios); + const payload = { + kind: "benchmark-run", + createdAt: new Date().toISOString(), + mode: "codex-cli", + target: { + ...target, + relativePath: relativePath(process.cwd(), target.path), + }, + codexVersion, + config: { + source, + path: configPath, + runnerType: config.runner.type, + model: options.model || config.runner.model || defaultModelForTarget(target), + sandbox: config.runner.sandbox || "workspace-write", + approvalPolicy: config.runner.approvalPolicy || "never", + scenarioCount: scenarios.length, + workspaceSourcePath: path.resolve(config.workspace.sourcePath), + workspaceSetupMode: config.workspace.setupMode || "copy", + workspacePreserve: config.workspace.preserve || "on-failure", + targetProvisioningMode: config.targetProvisioning.mode, + verifierCount: Array.isArray(config.verifiers?.commands) ? config.verifiers.commands.length : 0, + }, + runDirectory, + usageLogPath: usageOutPath, + resultPath: resultOutPath, + summary, + scenarios: runScenarios, + nextSteps: usageOutPath + ? [ + `Analyze the observed usage with: plugin-eval analyze ${formatCommandPath(target.path)} --observed-usage ${formatCommandPath(usageOutPath)} --format markdown`, + `Review the measurement plan with: plugin-eval measurement-plan ${formatCommandPath(target.path)} --observed-usage ${formatCommandPath(usageOutPath)} --format markdown`, + ] + : [ + `Review the benchmark report with: plugin-eval report ${formatCommandPath(resultOutPath)} --format markdown`, + "If token usage was unavailable, use the workspace outputs and verifier results as the primary quality signal.", + ], + workflowGuide: await buildWorkflowGuide(target.path, { + goal: summary.sampleCount > 0 ? "measure" : "benchmark", + }), + }; + + payload.nextAction = createBenchmarkRunNextAction(payload); + await writeJson(resultOutPath, payload); + return payload; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/budget.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/budget.js new file mode 100644 index 0000000000000000000000000000000000000000..8e58e35176185b67b731be84ab3110dfc7418486 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/budget.js @@ -0,0 +1,315 @@ +import fs from "node:fs/promises"; +import path from "node:path"; + +import { parseFrontmatter, parseYamlDocument } from "../lib/frontmatter.js"; +import { isDirectory, isProbablyTextFile, pathExists, readJson, readText, relativePath, walkFiles } from "../lib/files.js"; +import { estimateTokenCount, sumTokenCounts } from "../lib/tokens.js"; + +function createComponent(label, componentPath, tokens, note) { + return { + label, + path: componentPath, + tokens, + note, + }; +} + +function buildBudgetBucket(value, thresholds, components) { + const [goodMax, moderateMax, heavyMax] = thresholds; + const band = + value <= goodMax ? "good" : value <= moderateMax ? "moderate" : value <= heavyMax ? "heavy" : "excessive"; + return { + value, + band, + thresholds: { + goodMax, + moderateMax, + heavyMax, + }, + components, + }; +} + +async function gatherDeferredTextFiles(rootPath, excludeFiles = []) { + const files = await walkFiles(rootPath); + return files.filter( + (filePath) => !excludeFiles.includes(filePath) && isProbablyTextFile(filePath), + ); +} + +async function computeDeferredComponents(rootPath, excludeFiles = []) { + const files = await gatherDeferredTextFiles(rootPath, excludeFiles); + const components = []; + for (const filePath of files) { + const content = await readText(filePath); + components.push( + createComponent( + relativePath(rootPath, filePath), + filePath, + estimateTokenCount(content), + "Deferred supporting file", + ), + ); + } + return components; +} + +async function readInvocationPolicy(rootPath) { + const policyPath = path.join(rootPath, "agents", "openai.yaml"); + if (!(await pathExists(policyPath))) { + return { + allowImplicitInvocation: true, + path: null, + }; + } + + try { + const parsed = parseYamlDocument(await readText(policyPath)); + return { + allowImplicitInvocation: parsed?.policy?.allow_implicit_invocation !== false, + path: policyPath, + }; + } catch { + return { + allowImplicitInvocation: true, + path: policyPath, + }; + } +} + +export async function computeSkillBudget(skillRoot) { + const skillPath = path.join(skillRoot, "SKILL.md"); + const content = await readText(skillPath); + const parsed = parseFrontmatter(content); + const name = parsed.data?.name || path.basename(skillRoot); + const description = parsed.data?.description || ""; + const invocationPolicy = await readInvocationPolicy(skillRoot); + + const triggerComponents = invocationPolicy.allowImplicitInvocation ? [ + createComponent("skill-name", skillPath, estimateTokenCount(name), "Always-loaded skill identifier"), + createComponent( + "skill-description", + skillPath, + estimateTokenCount(description), + "Always-loaded trigger description", + ), + ] : []; + + const invokeComponents = [ + createComponent("skill-file", skillPath, estimateTokenCount(content), "Loaded when the skill is invoked"), + ]; + + const deferredComponents = await computeDeferredComponents(skillRoot, [skillPath]); + + return { + kind: "skill", + method: invocationPolicy.allowImplicitInvocation ? "estimated-static" : "estimated-static-policy-aware", + invocation_policy: { + allow_implicit_invocation: invocationPolicy.allowImplicitInvocation, + ...(invocationPolicy.path ? { path: invocationPolicy.path } : {}), + }, + trigger_cost_tokens: { + value: sumTokenCounts(triggerComponents), + components: triggerComponents, + }, + invoke_cost_tokens: { + value: sumTokenCounts(invokeComponents), + components: invokeComponents, + }, + deferred_cost_tokens: { + value: sumTokenCounts(deferredComponents), + components: deferredComponents, + }, + }; +} + +export async function computePluginBudget(pluginRoot, manifest) { + const manifestPath = path.join(pluginRoot, ".codex-plugin", "plugin.json"); + const manifestContent = await readText(manifestPath); + const skillDirs = manifest?.skills + ? await discoverSkillDirs(pluginRoot, manifest.skills) + : await discoverSkillDirs(pluginRoot, "./skills/"); + + const triggerComponents = [ + createComponent( + "plugin-description", + manifestPath, + estimateTokenCount(manifest?.description || ""), + "Plugin marketplace summary", + ), + createComponent( + "default-prompts", + manifestPath, + estimateTokenCount((manifest?.interface?.defaultPrompt || []).join("\n")), + "Starter prompts visible in the UI", + ), + ]; + + const invokeComponents = [ + createComponent("plugin-manifest", manifestPath, estimateTokenCount(manifestContent), "Manifest load cost"), + ]; + const explicitOnlyComponents = []; + const implicitSkills = []; + const explicitOnlySkills = []; + + for (const skillDir of skillDirs) { + const skillPath = path.join(skillDir, "SKILL.md"); + if (!(await pathExists(skillPath))) { + continue; + } + const content = await readText(skillPath); + const parsed = parseFrontmatter(content); + const skillName = path.basename(skillDir); + const invocationPolicy = await readInvocationPolicy(skillDir); + + if (invocationPolicy.allowImplicitInvocation) { + implicitSkills.push(skillName); + triggerComponents.push( + createComponent( + `${skillName}-description`, + skillPath, + estimateTokenCount(parsed.data?.description || ""), + "Skill trigger description exposed through the plugin", + ), + ); + invokeComponents.push( + createComponent( + `${skillName}-skill-file`, + skillPath, + estimateTokenCount(content), + "Implicit skill invocation cost ceiling", + ), + ); + } else { + explicitOnlySkills.push(skillName); + explicitOnlyComponents.push( + createComponent( + `${skillName}-skill-file`, + skillPath, + estimateTokenCount(content), + "Explicit-only skill file; excluded from implicit trigger/invoke budget", + ), + ); + } + } + + const deferredComponents = await computeDeferredComponents(pluginRoot, [ + manifestPath, + ...skillDirs.map((skillDir) => path.join(skillDir, "SKILL.md")), + ]); + + return { + kind: "plugin", + method: explicitOnlySkills.length > 0 ? "estimated-static-policy-aware" : "estimated-static", + invocation_policy: { + implicit_skill_count: implicitSkills.length, + explicit_only_skill_count: explicitOnlySkills.length, + implicit_skills: implicitSkills, + explicit_only_skills: explicitOnlySkills, + }, + trigger_cost_tokens: { + value: sumTokenCounts(triggerComponents), + components: triggerComponents, + }, + invoke_cost_tokens: { + value: sumTokenCounts(invokeComponents), + components: invokeComponents, + }, + deferred_cost_tokens: { + value: sumTokenCounts(deferredComponents), + components: deferredComponents, + }, + explicit_only_invoke_cost_tokens: { + value: sumTokenCounts(explicitOnlyComponents), + components: explicitOnlyComponents, + }, + }; +} + +async function discoverSkillDirs(pluginRoot, skillsPath) { + const directory = path.join(pluginRoot, skillsPath.replace(/^\.\//, "")); + if (!(await isDirectory(directory))) { + return []; + } + const entries = await fs.readdir(directory, { withFileTypes: true }); + return entries + .filter((entry) => entry.isDirectory()) + .map((entry) => path.join(directory, entry.name)) + .sort(); +} + +export async function computeBudgetProfile(target) { + if (target.kind === "skill") { + return computeSkillBudget(target.path); + } + if (target.kind === "plugin") { + const manifest = await readJson(path.join(target.path, ".codex-plugin", "plugin.json")); + return computePluginBudget(target.path, manifest); + } + + const files = await gatherDeferredTextFiles(target.path); + const components = []; + for (const filePath of files) { + const content = await readText(filePath); + components.push( + createComponent( + relativePath(target.path, filePath), + filePath, + estimateTokenCount(content), + "Generic text file budget", + ), + ); + } + return { + kind: target.kind, + trigger_cost_tokens: { value: 0, components: [] }, + invoke_cost_tokens: { value: 0, components: [] }, + deferred_cost_tokens: { value: sumTokenCounts(components), components }, + }; +} + +export function applyBudgetBands(rawBudget, baseline) { + const profile = baseline?.[rawBudget.kind] || baseline?.directory || baseline?.skill; + const trigger = buildBudgetBucket( + rawBudget.trigger_cost_tokens.value, + profile.trigger_cost_tokens, + rawBudget.trigger_cost_tokens.components, + ); + const invoke = buildBudgetBucket( + rawBudget.invoke_cost_tokens.value, + profile.invoke_cost_tokens, + rawBudget.invoke_cost_tokens.components, + ); + const deferred = buildBudgetBucket( + rawBudget.deferred_cost_tokens.value, + profile.deferred_cost_tokens, + rawBudget.deferred_cost_tokens.components, + ); + const explicitOnly = rawBudget.explicit_only_invoke_cost_tokens + ? buildBudgetBucket( + rawBudget.explicit_only_invoke_cost_tokens.value, + profile.invoke_cost_tokens, + rawBudget.explicit_only_invoke_cost_tokens.components, + ) + : null; + const total = trigger.value + invoke.value + deferred.value; + return { + method: rawBudget.method || "estimated-static", + ...(rawBudget.invocation_policy ? { invocation_policy: rawBudget.invocation_policy } : {}), + trigger_cost_tokens: trigger, + invoke_cost_tokens: invoke, + deferred_cost_tokens: deferred, + ...(explicitOnly ? { explicit_only_invoke_cost_tokens: explicitOnly } : {}), + total_tokens: { + value: total, + band: + [trigger.band, invoke.band, deferred.band].includes("excessive") + ? "excessive" + : [trigger.band, invoke.band, deferred.band].includes("heavy") + ? "heavy" + : [trigger.band, invoke.band, deferred.band].includes("moderate") + ? "moderate" + : "good", + }, + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/compare.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/compare.js new file mode 100644 index 0000000000000000000000000000000000000000..c1101bcbeb57699cbe1da577f329e0d150052403 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/compare.js @@ -0,0 +1,38 @@ +import { createComparisonNextAction } from "./presentation.js"; + +export function compareResults(before, after) { + const beforeFailures = new Set( + before.checks.filter((check) => check.status === "fail").map((check) => check.id), + ); + const afterFailures = new Set( + after.checks.filter((check) => check.status === "fail").map((check) => check.id), + ); + + const resolvedFailures = [...beforeFailures].filter((id) => !afterFailures.has(id)); + const newFailures = [...afterFailures].filter((id) => !beforeFailures.has(id)); + + const payload = { + kind: "comparison", + createdAt: new Date().toISOString(), + target: after.target, + scoreDelta: after.summary.score - before.summary.score, + gradeBefore: before.summary.grade, + gradeAfter: after.summary.grade, + riskBefore: before.summary.riskLevel, + riskAfter: after.summary.riskLevel, + budgetDelta: { + trigger_cost_tokens: + (after.budgets.trigger_cost_tokens?.value || 0) - (before.budgets.trigger_cost_tokens?.value || 0), + invoke_cost_tokens: + (after.budgets.invoke_cost_tokens?.value || 0) - (before.budgets.invoke_cost_tokens?.value || 0), + deferred_cost_tokens: + (after.budgets.deferred_cost_tokens?.value || 0) - (before.budgets.deferred_cost_tokens?.value || 0), + }, + resolvedFailures, + newFailures, + beforeSummary: before.summary, + afterSummary: after.summary, + }; + payload.nextAction = createComparisonNextAction(payload); + return payload; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/improvement-brief.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/improvement-brief.js new file mode 100644 index 0000000000000000000000000000000000000000..7fa116167039ca1629f4f948f72a222bbb10162e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/improvement-brief.js @@ -0,0 +1,35 @@ +export function buildImprovementBrief(result) { + const failingChecks = result.checks.filter((check) => check.status === "fail"); + const warningChecks = result.checks.filter((check) => check.status === "warn"); + const prioritized = [...failingChecks, ...warningChecks].slice(0, 8); + const measurementGoals = + result.measurementPlan?.recommendedToolsets?.length > 0 + ? result.measurementPlan.recommendedToolsets + : []; + + return { + title: `Improve ${result.target.name}`, + target: result.target, + summary: `Raise the evaluation from grade ${result.summary.grade} (${result.summary.score}/100) with a focus on the highest-signal structural and budget issues first.`, + goals: result.summary.topRecommendations, + measurementGoals, + requiredFixes: failingChecks.slice(0, 5).map((check) => ({ + id: check.id, + message: check.message, + remediation: check.remediation, + })), + recommendedFixes: warningChecks.slice(0, 5).map((check) => ({ + id: check.id, + message: check.message, + remediation: check.remediation, + })), + suggestedPrompt: [ + `Use the skill-creator guidance to improve ${result.target.name}.`, + `Keep the structure compact and move bulky details into references or scripts.`, + ...(measurementGoals.length > 0 + ? [`Define success measures with these toolsets: ${measurementGoals.join(", ")}.`] + : []), + ...prioritized.map((check) => `Address ${check.id}: ${check.message}`), + ].join(" "), + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/measurement-plan.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/measurement-plan.js new file mode 100644 index 0000000000000000000000000000000000000000..e5237e65bdd389bb9d8f01bcbdb8a8373a0e84e8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/measurement-plan.js @@ -0,0 +1,208 @@ +import { createArtifact } from "./schema.js"; +import { createMeasurementPlanNextAction } from "./presentation.js"; + +function hasMetric(result, id) { + return result.metrics.some((metric) => metric.id === id); +} + +function createToolset({ + id, + label, + priority, + goal, + why, + signals, + evidenceSources, + starterPack, +}) { + return { + id, + label, + priority, + goal, + why, + signals, + evidenceSources, + starterPack, + }; +} + +export function buildMeasurementPlan(result) { + const hasObservedUsage = Boolean(result.observedUsage?.sampleCount); + const hasBudgetPressure = + ["heavy", "excessive"].includes(result.budgets.trigger_cost_tokens?.band) || + ["heavy", "excessive"].includes(result.budgets.invoke_cost_tokens?.band); + const hasCode = + hasMetric(result, "ts_file_count") || + hasMetric(result, "py_file_count") || + result.target.kind === "directory"; + + const toolsets = [ + createToolset({ + id: "token-usage-observer", + label: "Token Usage Observer", + priority: !hasObservedUsage || hasBudgetPressure ? "high" : "medium", + goal: "Measure how many tokens the skill or plugin actually burns in representative runs.", + why: + "Static estimates are useful guardrails, but observed usage is what tells you whether a real workflow is affordable and whether caching or reasoning changes the picture.", + signals: [ + "observed_usage_sample_count", + "observed_input_tokens_avg", + "observed_total_tokens_avg", + "estimate_vs_observed_input_ratio", + ], + evidenceSources: [ + "Responses API usage logs", + "Codex-like session exports", + "JSONL traces captured from local benchmarking harnesses", + ], + starterPack: { + manifestName: "token-usage-pack", + focus: "Validate sample size, cold-start versus warm-cache behavior, and estimate drift over time.", + }, + }), + createToolset({ + id: "task-outcome-scorecard", + label: "Task Outcome Scorecard", + priority: "high", + goal: "Measure whether the skill helps users finish the intended job with fewer retries and less cleanup.", + why: + "A low-token skill is still a miss if it fails the task, and a verbose skill may be worth it if it consistently improves first-pass success.", + signals: [ + "task_success_rate", + "first_pass_success_rate", + "retry_rate", + "human_override_rate", + ], + evidenceSources: [ + "Task run logs", + "Structured user acceptance checklist", + "Before/after comparison runs on the same prompts", + ], + starterPack: { + manifestName: "task-outcomes-pack", + focus: "Score success, retries, and manual intervention across a fixed prompt set.", + }, + }), + createToolset({ + id: "tool-call-audit", + label: "Tool Call Audit", + priority: result.target.kind === "plugin" ? "high" : "medium", + goal: "Check whether the agent uses the right tools, arguments, and sequencing when the skill is active.", + why: + "For Codex plugins and many higher-agency skills, tool correctness is often the real determinant of user value.", + signals: [ + "tool_call_success_rate", + "invalid_tool_argument_rate", + "recoverable_tool_failure_rate", + ], + evidenceSources: [ + "Tool invocation traces", + "Recorded sessions", + "Golden-path scenario replays", + ], + starterPack: { + manifestName: "tool-audit-pack", + focus: "Flag wrong tool selection, malformed args, and missing follow-up calls.", + }, + }), + createToolset({ + id: "latency-efficiency", + label: "Latency And Efficiency", + priority: hasBudgetPressure ? "high" : "medium", + goal: "Track whether the skill speeds users up enough to justify its cost.", + why: + "DX improvements usually win when they reduce waiting or rework, not only when they reduce absolute token counts.", + signals: [ + "p50_time_to_first_acceptable_answer_seconds", + "p95_time_to_task_completion_seconds", + "tokens_per_successful_run", + ], + evidenceSources: [ + "Benchmark harness timings", + "Manual stopwatch runs on canonical tasks", + "Responses API timestamps combined with usage logs", + ], + starterPack: { + manifestName: "latency-efficiency-pack", + focus: "Measure time-to-value and cost-per-success on a stable prompt suite.", + }, + }), + createToolset({ + id: "human-rubric-review", + label: "Human Rubric Review", + priority: "medium", + goal: "Capture clarity, trust, and usefulness signals that automated checks will miss.", + why: + "The best skills often reduce confusion and editing effort in ways that do not show up in static lint-like checks.", + signals: [ + "clarity_score_avg", + "confidence_score_avg", + "follow_up_question_rate", + ], + evidenceSources: [ + "Reviewer scorecards", + "Team rubric sheets", + "Annotated transcripts", + ], + starterPack: { + manifestName: "human-rubric-pack", + focus: "Collect 1 to 5 scores for clarity, trust, and edit burden across a small evaluator panel.", + }, + }), + ]; + + if (hasCode) { + toolsets.push( + createToolset({ + id: "regression-suite", + label: "Regression Suite", + priority: "medium", + goal: "Protect the repository behavior that the skill is supposed to improve.", + why: + "If a skill is meant to help coding workflows, outcomes should be paired with deterministic repo checks so quality gains do not come from cutting corners.", + signals: [ + "test_pass_rate", + "lint_pass_rate", + "regression_escape_count", + ], + evidenceSources: [ + "Unit and integration test runs", + "Coverage deltas", + "Snapshot or golden-file checks", + ], + starterPack: { + manifestName: "regression-pack", + focus: "Blend repository test outcomes with evaluation-task success metrics.", + }, + }), + ); + } + + const recommendedToolsets = toolsets + .filter((toolset) => toolset.priority === "high") + .map((toolset) => toolset.id); + + const payload = { + kind: "measurement-plan", + createdAt: new Date().toISOString(), + target: result.target, + title: `Measurement plan for ${result.target.name}`, + summary: + "Combine cost, outcome, and trust signals so you can tell whether the skill or plugin is genuinely helping instead of only looking well-structured on paper.", + recommendedToolsets, + toolsets, + artifact: createArtifact({ + id: "measurement-plan", + type: "measurement-plan", + label: "Measurement plan", + description: "Recommended toolsets for measuring the real-world effect of this skill or plugin.", + data: { + recommendedToolsets, + toolsets, + }, + }), + }; + payload.nextAction = createMeasurementPlanNextAction(payload); + return payload; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/metric-packs.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/metric-packs.js new file mode 100644 index 0000000000000000000000000000000000000000..9421603daae36728c48525baee6b5b751f1f63b1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/metric-packs.js @@ -0,0 +1,75 @@ +import path from "node:path"; +import { spawnSync } from "node:child_process"; + +import { pathExists, readJson } from "../lib/files.js"; + +function normalizeCommand(manifest) { + if (Array.isArray(manifest.command)) { + return manifest.command.map((part, index) => (index === 0 && part === "node" ? process.execPath : part)); + } + if (typeof manifest.command === "string") { + return manifest.command + .split(/\s+/) + .filter(Boolean) + .map((part, index) => (index === 0 && part === "node" ? process.execPath : part)); + } + return []; +} + +export async function runMetricPacks(target, manifestPaths = []) { + const extensions = []; + + for (const manifestPath of manifestPaths) { + const resolvedManifestPath = path.resolve(manifestPath); + if (!(await pathExists(resolvedManifestPath))) { + throw new Error(`Metric pack manifest not found: ${resolvedManifestPath}`); + } + + const manifest = await readJson(resolvedManifestPath); + if ( + Array.isArray(manifest.supportedTargetKinds) && + !manifest.supportedTargetKinds.includes(target.kind) + ) { + continue; + } + + const command = normalizeCommand(manifest); + if (command.length === 0) { + throw new Error(`Metric pack command is missing: ${resolvedManifestPath}`); + } + + const [bin, ...args] = command; + const execution = spawnSync( + bin, + [...args, target.path, target.kind], + { + cwd: path.dirname(resolvedManifestPath), + encoding: "utf8", + env: { + ...process.env, + PLUGIN_EVAL_TARGET: target.path, + PLUGIN_EVAL_TARGET_KIND: target.kind, + PLUGIN_EVAL_METRIC_PACK_MANIFEST: resolvedManifestPath, + }, + }, + ); + + if (execution.status !== 0) { + throw new Error( + `Metric pack failed (${manifest.name || resolvedManifestPath}): ${execution.stderr || execution.stdout}`, + ); + } + + const payload = JSON.parse(execution.stdout || "{}"); + extensions.push({ + name: manifest.name || path.basename(resolvedManifestPath), + version: manifest.version || "0.0.0", + manifestPath: resolvedManifestPath, + checks: Array.isArray(payload.checks) ? payload.checks : [], + metrics: Array.isArray(payload.metrics) ? payload.metrics : [], + artifacts: Array.isArray(payload.artifacts) ? payload.artifacts : [], + }); + } + + return extensions; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/observed-usage.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/observed-usage.js new file mode 100644 index 0000000000000000000000000000000000000000..c8b2b921d7e6f95415d39a137859ae0758720a8e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/observed-usage.js @@ -0,0 +1,394 @@ +import path from "node:path"; + +import { pathExists, readText, relativePath } from "../lib/files.js"; +import { createArtifact, createCheck, createMetric } from "./schema.js"; + +function round(value) { + return Math.round(value * 100) / 100; +} + +function toNumber(value) { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} + +function buildStat(values) { + if (values.length === 0) { + return { + total: 0, + average: 0, + min: 0, + max: 0, + }; + } + + const total = values.reduce((sum, value) => sum + value, 0); + return { + total, + average: round(total / values.length), + min: Math.min(...values), + max: Math.max(...values), + }; +} + +function classifyEstimateAlignment(deltaRatio) { + if (deltaRatio <= 0.2) { + return "close"; + } + if (deltaRatio <= 0.5) { + return "drift"; + } + return "wide-drift"; +} + +function extractUsagePayload(candidate) { + if (!candidate || typeof candidate !== "object") { + return null; + } + + if (candidate.type === "response.done" && candidate.response?.usage) { + return { + usage: candidate.response.usage, + responseId: candidate.response.id || candidate.id || null, + label: candidate.metadata?.scenario || candidate.response?.metadata?.scenario || null, + }; + } + + if (candidate.response?.usage) { + return { + usage: candidate.response.usage, + responseId: candidate.response.id || candidate.id || null, + label: candidate.metadata?.scenario || candidate.response?.metadata?.scenario || null, + }; + } + + if (candidate.usage) { + return { + usage: candidate.usage, + responseId: candidate.response_id || candidate.id || null, + label: candidate.metadata?.scenario || candidate.scenario || null, + }; + } + + if ( + typeof candidate.input_tokens === "number" || + typeof candidate.output_tokens === "number" || + typeof candidate.total_tokens === "number" + ) { + return { + usage: candidate, + responseId: candidate.response_id || candidate.id || null, + label: candidate.metadata?.scenario || candidate.scenario || null, + }; + } + + return null; +} + +function normalizeSnapshot(candidate, sourcePath, index) { + const extracted = extractUsagePayload(candidate); + if (!extracted) { + return null; + } + + const usage = extracted.usage || {}; + const inputTokens = toNumber(usage.input_tokens); + const outputTokens = toNumber(usage.output_tokens); + const totalTokens = toNumber(usage.total_tokens) ?? ((inputTokens || 0) + (outputTokens || 0)); + const cachedTokens = + toNumber(usage.input_token_details?.cached_tokens) ?? + toNumber(usage.cached_tokens) ?? + 0; + const reasoningTokens = + toNumber(usage.output_tokens_details?.reasoning_tokens) ?? + toNumber(usage.reasoning_tokens) ?? + 0; + + if (inputTokens === null && outputTokens === null && totalTokens === null) { + return null; + } + + return { + id: extracted.responseId || `${path.basename(sourcePath)}#${index + 1}`, + label: extracted.label || null, + sourcePath, + inputTokens: inputTokens ?? 0, + outputTokens: outputTokens ?? 0, + totalTokens, + cachedTokens, + reasoningTokens, + }; +} + +function collectSnapshots(value, sourcePath, results) { + if (Array.isArray(value)) { + value.forEach((item) => collectSnapshots(item, sourcePath, results)); + return; + } + + if (!value || typeof value !== "object") { + return; + } + + const snapshot = normalizeSnapshot(value, sourcePath, results.length); + if (snapshot) { + results.push(snapshot); + return; + } + + Object.values(value).forEach((nested) => { + if (nested && typeof nested === "object") { + collectSnapshots(nested, sourcePath, results); + } + }); +} + +function parseUsageContent(content) { + const trimmed = content.trim(); + if (!trimmed) { + return []; + } + + if (trimmed.startsWith("[")) { + return [JSON.parse(trimmed)]; + } + + if (trimmed.startsWith("{")) { + try { + return [JSON.parse(trimmed)]; + } catch { + // Fall through to JSONL parsing when the file contains multiple JSON objects. + } + } + + return trimmed + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => JSON.parse(line)); +} + +async function loadSnapshotsFromFile(filePath) { + const resolvedPath = path.resolve(filePath); + if (!(await pathExists(resolvedPath))) { + throw new Error(`Observed usage file not found: ${resolvedPath}`); + } + + const parsedItems = parseUsageContent(await readText(resolvedPath)); + const snapshots = []; + parsedItems.forEach((item) => collectSnapshots(item, resolvedPath, snapshots)); + return snapshots; +} + +function createObservedUsageChecks(summary) { + const checks = []; + + if (summary.sampleCount < 3) { + checks.push( + createCheck({ + id: "observed-usage-small-sample", + category: "measurement", + severity: "warning", + status: "warn", + message: "Observed usage coverage is too small to trust as a stable benchmark yet.", + evidence: [`Samples collected: ${summary.sampleCount}`], + remediation: ["Capture at least 5 to 10 representative sessions before treating observed usage as a baseline."], + }), + ); + } + + const comparison = summary.estimateComparison; + if (comparison) { + if (comparison.band === "drift" || comparison.band === "wide-drift") { + checks.push( + createCheck({ + id: "observed-usage-estimate-drift", + category: "budget", + severity: comparison.band === "wide-drift" ? "error" : "warning", + status: comparison.band === "wide-drift" ? "fail" : "warn", + message: "Static budget estimates differ meaningfully from observed input token usage.", + evidence: [ + `Estimated active tokens: ${comparison.estimatedActiveTokens}`, + `Observed average input tokens: ${comparison.observedAverageInputTokens}`, + `Delta ratio: ${round(comparison.deltaRatio * 100)}%`, + ], + remediation: [ + "Trim repeated instructions or supporting text if the observed value is higher than expected.", + "If the static estimate is intentionally conservative, record that assumption in the skill or plugin references.", + ], + }), + ); + } + + if (summary.cachedTokens.average > 0) { + checks.push( + createCheck({ + id: "observed-usage-cache-present", + category: "measurement", + severity: "info", + status: "info", + message: "Observed runs include cached tokens, so repeated sessions are cheaper than the cold-start estimate.", + evidence: [`Average cached tokens: ${summary.cachedTokens.average}`], + remediation: ["Track cold-start and warm-cache sessions separately if you need tighter budgeting."], + }), + ); + } + } + + return checks; +} + +export async function analyzeObservedUsage(usagePaths = [], rawBudget, target) { + if (!Array.isArray(usagePaths) || usagePaths.length === 0) { + return null; + } + + const snapshots = []; + for (const usagePath of usagePaths) { + const loaded = await loadSnapshotsFromFile(usagePath); + snapshots.push(...loaded); + } + + if (snapshots.length === 0) { + throw new Error("Observed usage files were provided, but no usage payloads could be parsed."); + } + + const inputTokens = buildStat(snapshots.map((snapshot) => snapshot.inputTokens)); + const outputTokens = buildStat(snapshots.map((snapshot) => snapshot.outputTokens)); + const totalTokens = buildStat(snapshots.map((snapshot) => snapshot.totalTokens)); + const cachedTokens = buildStat(snapshots.map((snapshot) => snapshot.cachedTokens)); + const reasoningTokens = buildStat(snapshots.map((snapshot) => snapshot.reasoningTokens)); + const estimatedActiveTokens = rawBudget.trigger_cost_tokens.value + rawBudget.invoke_cost_tokens.value; + const observedAverageInputTokens = inputTokens.average; + const deltaTokens = round(observedAverageInputTokens - estimatedActiveTokens); + const deltaRatio = + estimatedActiveTokens > 0 ? round(Math.abs(deltaTokens) / estimatedActiveTokens) : 0; + + const observedUsage = { + method: "observed-usage-files", + target: { + name: target.name, + kind: target.kind, + path: target.path, + relativePath: relativePath(process.cwd(), target.path), + }, + sampleCount: snapshots.length, + files: [...new Set(snapshots.map((snapshot) => relativePath(process.cwd(), snapshot.sourcePath)))], + inputTokens, + outputTokens, + totalTokens, + cachedTokens, + reasoningTokens, + estimateComparison: estimatedActiveTokens + ? { + estimatedActiveTokens, + observedAverageInputTokens, + deltaTokens, + deltaRatio, + band: classifyEstimateAlignment(deltaRatio), + } + : null, + samples: snapshots.map((snapshot) => ({ + ...snapshot, + sourcePath: relativePath(process.cwd(), snapshot.sourcePath), + })), + }; + + const metrics = [ + createMetric({ + id: "observed_usage_sample_count", + category: "measurement", + value: observedUsage.sampleCount, + unit: "samples", + band: observedUsage.sampleCount >= 5 ? "good" : observedUsage.sampleCount >= 3 ? "moderate" : "heavy", + }), + createMetric({ + id: "observed_input_tokens_avg", + category: "measurement", + value: observedUsage.inputTokens.average, + unit: "tokens", + band: "info", + }), + createMetric({ + id: "observed_output_tokens_avg", + category: "measurement", + value: observedUsage.outputTokens.average, + unit: "tokens", + band: "info", + }), + createMetric({ + id: "observed_total_tokens_avg", + category: "measurement", + value: observedUsage.totalTokens.average, + unit: "tokens", + band: "info", + }), + ]; + + if (observedUsage.cachedTokens.total > 0) { + metrics.push( + createMetric({ + id: "observed_cached_tokens_avg", + category: "measurement", + value: observedUsage.cachedTokens.average, + unit: "tokens", + band: "info", + }), + ); + } + + if (observedUsage.reasoningTokens.total > 0) { + metrics.push( + createMetric({ + id: "observed_reasoning_tokens_avg", + category: "measurement", + value: observedUsage.reasoningTokens.average, + unit: "tokens", + band: "info", + }), + ); + } + + if (observedUsage.estimateComparison) { + metrics.push( + createMetric({ + id: "estimate_vs_observed_input_delta", + category: "measurement", + value: observedUsage.estimateComparison.deltaTokens, + unit: "tokens", + band: + observedUsage.estimateComparison.band === "close" + ? "good" + : observedUsage.estimateComparison.band === "drift" + ? "moderate" + : "heavy", + }), + createMetric({ + id: "estimate_vs_observed_input_ratio", + category: "measurement", + value: observedUsage.estimateComparison.deltaRatio, + unit: "ratio", + band: + observedUsage.estimateComparison.band === "close" + ? "good" + : observedUsage.estimateComparison.band === "drift" + ? "moderate" + : "heavy", + }), + ); + } + + return { + observedUsage, + checks: createObservedUsageChecks(observedUsage), + metrics, + artifacts: [ + createArtifact({ + id: "observed-usage-summary", + type: "measurement", + label: "Observed usage summary", + description: "Observed token telemetry aggregated from local usage log files.", + data: observedUsage, + }), + ], + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/presentation.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/presentation.js new file mode 100644 index 0000000000000000000000000000000000000000..3f594d2dcd13f07f1acdb124cf3a49aa0c0b44bc --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/presentation.js @@ -0,0 +1,191 @@ +import { formatCommandPath, relativePath } from "../lib/files.js"; +import { enrichSummary } from "./scoring.js"; + +function shellQuote(value) { + return `'${String(value).replaceAll("'", "'\\''")}'`; +} + +function targetLabel(target) { + if (target.kind === "plugin") { + return "plugin"; + } + if (target.kind === "skill") { + return "skill"; + } + return "target"; +} + +function targetTypeLabel(target) { + if (target.kind === "plugin") { + return "plugin"; + } + if (target.kind === "skill") { + return "skill"; + } + return "item"; +} + +function buildStartCommand(target, chatPrompt) { + return `plugin-eval start ${formatCommandPath(target.path)} --request ${shellQuote(chatPrompt)} --format markdown`; +} + +function hasStructuralFailures(result) { + return result.checks.some( + (check) => + check.status === "fail" && + (check.category === "manifest" || check.category === "skill-structure"), + ); +} + +function hasBudgetPressure(result) { + return ["heavy", "excessive"].includes(result.budgets?.trigger_cost_tokens?.band) || + ["heavy", "excessive"].includes(result.budgets?.invoke_cost_tokens?.band); +} + +function hasWarningsOrFailures(result) { + return result.checks.some((check) => check.status === "fail" || check.status === "warn"); +} + +export function createEvaluationNextAction(result) { + const labelName = targetLabel(result.target); + + if (hasStructuralFailures(result)) { + return { + label: "Fix structural issues first", + why: "Failing manifest or skill structure issues reduce trust and can invalidate later measurements.", + command: buildStartCommand(result.target, "What should I fix first?"), + chatPrompt: "What should I fix first?", + }; + } + + if (!result.observedUsage?.sampleCount && hasBudgetPressure(result)) { + return { + label: "Measure real token usage next", + why: "The static budget looks heavy, so live usage is the fastest way to confirm whether the cost is acceptable.", + command: buildStartCommand(result.target, `Measure the real token usage of this ${labelName}.`), + chatPrompt: `Measure the real token usage of this ${labelName}.`, + }; + } + + if (result.observedUsage?.sampleCount) { + return { + label: "Review the measurement plan", + why: "You already have observed usage, so the highest-value next step is deciding what to instrument or improve.", + command: buildStartCommand(result.target, "What should I run next?"), + chatPrompt: "What should I run next?", + }; + } + + if (hasWarningsOrFailures(result)) { + return { + label: "Fix the top findings and rerun the report", + why: "A short pass on the highest-value findings will improve trust, readability, and the signal quality of future benchmarks.", + command: buildStartCommand(result.target, "What should I fix first?"), + chatPrompt: "What should I fix first?", + }; + } + + return { + label: "Choose the next workflow from chat", + why: "The report is clean enough that the best next step depends on whether you want budgets, benchmarks, or comparisons.", + command: buildStartCommand(result.target, "What should I run next?"), + chatPrompt: "What should I run next?", + }; +} + +export function applyEvaluationPresentation(result) { + result.summary = enrichSummary(result, result.summary); + if (!result.nextAction) { + result.nextAction = createEvaluationNextAction(result); + } + return result; +} + +export function createWorkflowGuideNextAction(guide) { + const startHere = guide.startHere || guide.recommendedWorkflow; + return { + label: startHere?.label || guide.recommendedWorkflow?.label || "Start here", + why: startHere?.routingExplanation || guide.recommendedWorkflow?.summary || guide.beginnerSummary, + command: startHere?.firstCommand || guide.recommendedWorkflow?.firstCommand, + chatPrompt: startHere?.chatPrompt || guide.recommendedWorkflow?.chatPrompt, + }; +} + +export function createMeasurementPlanNextAction(plan) { + const toolset = plan.toolsets.find((entry) => plan.recommendedToolsets.includes(entry.id)) || plan.toolsets[0]; + const targetKind = targetTypeLabel(plan.target); + + return { + label: toolset ? `Start with ${toolset.label}` : "Decide what to measure next", + why: toolset + ? toolset.goal + : "A small measurement pass will turn the current report into a more trustworthy workflow decision.", + command: buildStartCommand(plan.target, `What should I run next?`), + chatPrompt: `What should I run next?`, + ...(toolset ? { toolsetId: toolset.id } : {}), + ...(toolset + ? {} + : { + why: `Use Plugin Eval to decide the next measurement move for this ${targetKind}.`, + }), + }; +} + +export function createBudgetNextAction(payload) { + const labelName = targetLabel(payload.target); + const hasHeavyBudget = ["heavy", "excessive"].includes(payload.budgets?.trigger_cost_tokens?.band) || + ["heavy", "excessive"].includes(payload.budgets?.invoke_cost_tokens?.band); + + if (hasHeavyBudget) { + return { + label: "Validate the budget with real usage", + why: "The estimate looks heavy enough that measured usage is worth collecting before you rewrite the skill or plugin.", + command: buildStartCommand(payload.target, `Measure the real token usage of this ${labelName}.`), + chatPrompt: `Measure the real token usage of this ${labelName}.`, + }; + } + + return { + label: "Review the full evaluation", + why: "The budget does not look alarming on its own, so the next useful step is the full structural and quality report.", + command: buildStartCommand(payload.target, `Evaluate this ${labelName}.`), + chatPrompt: `Evaluate this ${labelName}.`, + }; +} + +export function createBenchmarkTemplateNextAction(payload) { + const commandTargetPath = formatCommandPath(payload.target.path); + const commandConfigPath = formatCommandPath(payload.configPath); + return { + label: "Run the Codex benchmark", + why: "Benchmarking now means a real codex exec run, so the next step is to execute the edited scenarios in an isolated workspace.", + command: `plugin-eval benchmark ${commandTargetPath} --config ${commandConfigPath} --format markdown`, + chatPrompt: `Help me benchmark this ${targetLabel(payload.target)}.`, + }; +} + +export function createBenchmarkRunNextAction(payload) { + const commandTargetPath = formatCommandPath(payload.target.path); + return { + label: payload.usageLogPath ? "Fold the usage log back into analysis" : "Review the benchmark report", + why: payload.usageLogPath + ? "The Codex run produced observed usage, so the next step is to re-run analysis with those measurements." + : "This benchmark completed without usage telemetry, so the report and preserved artifacts are the primary signal.", + command: payload.usageLogPath + ? `plugin-eval analyze ${commandTargetPath} --observed-usage ${formatCommandPath(payload.usageLogPath)} --format markdown` + : `plugin-eval report ${formatCommandPath(payload.resultPath)} --format markdown`, + chatPrompt: payload.usageLogPath ? `What should I run next?` : `Help me benchmark this ${targetLabel(payload.target)}.`, + }; +} + +export function createComparisonNextAction(diff) { + const chatPrompt = diff.newFailures.length > 0 ? "What should I fix first?" : "What should I run next?"; + return { + label: diff.newFailures.length > 0 ? "Address the new failures first" : "Continue from the improved baseline", + why: diff.newFailures.length > 0 + ? "New failures block trust in the comparison, even if the score improved elsewhere." + : "The comparison is trending in the right direction, so the next move is to keep the workflow tight and repeatable.", + command: buildStartCommand(diff.target, chatPrompt), + chatPrompt, + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/schema.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/schema.js new file mode 100644 index 0000000000000000000000000000000000000000..c95736cd4b90e257bab56f6eeb0dab19122c3175 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/schema.js @@ -0,0 +1,121 @@ +import { relativePath } from "../lib/files.js"; + +export const TOOL_NAME = "plugin-eval"; +export const TOOL_VERSION = "0.1.0"; +export const SCHEMA_VERSION = 1; + +export function createEvaluationResult(target) { + return { + schemaVersion: SCHEMA_VERSION, + tool: { + name: TOOL_NAME, + version: TOOL_VERSION, + }, + createdAt: new Date().toISOString(), + target: { + ...target, + relativePath: relativePath(process.cwd(), target.path), + }, + summary: { + score: 0, + grade: "F", + riskLevel: "high", + riskReasons: [], + scoreBreakdown: { + startingScore: 100, + totalDeductions: 0, + finalScore: 0, + }, + checkCounts: { + total: 0, + pass: 0, + warn: 0, + fail: 0, + info: 0, + error: 0, + warning: 0, + }, + deductions: [], + categoryDeductions: [], + topRecommendations: [], + whyBullets: [], + fixFirst: [], + watchNext: [], + }, + budgets: {}, + observedUsage: null, + checks: [], + metrics: [], + artifacts: [], + extensions: [], + measurementPlan: null, + improvementBrief: null, + nextAction: null, + }; +} + +export function createCheck({ + id, + category, + severity, + status, + message, + evidence = [], + remediation = [], + source = "core", + targetPath = null, + why = null, +}) { + return { + id, + category, + severity, + status, + message, + evidence, + remediation, + source, + ...(why ? { why } : {}), + ...(targetPath ? { targetPath } : {}), + }; +} + +export function createMetric({ + id, + category, + value, + unit, + band = "info", + source = "core", + targetPath = null, +}) { + return { + id, + category, + value, + unit, + band, + source, + ...(targetPath ? { targetPath } : {}), + }; +} + +export function createArtifact({ + id, + type, + label, + description, + data = null, + path = null, + source = "core", +}) { + return { + id, + type, + label, + description, + source, + ...(path ? { path } : {}), + ...(data ? { data } : {}), + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/scoring.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/scoring.js new file mode 100644 index 0000000000000000000000000000000000000000..df8c0238a153ec49fdf338bfa3f063fb538ebc57 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/scoring.js @@ -0,0 +1,342 @@ +const SEVERITY_WEIGHT = { + error: 14, + warning: 6, + info: 1, +}; + +const STATUS_MULTIPLIER = { + fail: 1, + warn: 0.75, + info: 0.25, + pass: 0, +}; + +const GRADE_THRESHOLDS = { + A: 93, + B: 85, + C: 70, + D: 55, +}; + +const CATEGORY_PRIORITY = { + manifest: 0, + "skill-structure": 1, + budget: 2, + measurement: 3, + "best-practice": 4, + complexity: 5, + readability: 6, + "code-quality": 7, +}; + +const STATUS_PRIORITY = { + fail: 0, + warn: 1, + info: 2, + pass: 3, +}; + +function unique(items) { + return [...new Set(items.filter(Boolean))]; +} + +export function summarizeChecks(checks) { + return checks.reduce( + (summary, check) => { + summary.total += 1; + summary[check.status] = (summary[check.status] || 0) + 1; + summary[check.severity] = (summary[check.severity] || 0) + 1; + return summary; + }, + { + total: 0, + pass: 0, + warn: 0, + fail: 0, + info: 0, + error: 0, + warning: 0, + }, + ); +} + +function computeCheckPenalty(check) { + const weight = SEVERITY_WEIGHT[check.severity] ?? 0; + const multiplier = STATUS_MULTIPLIER[check.status] ?? 0; + return weight * multiplier; +} + +function deriveCheckWhy(check) { + if (check.why) { + return check.why; + } + + if (check.category === "manifest") { + return "Manifest issues reduce trust because Codex may not discover or represent the plugin correctly."; + } + + if (check.category === "skill-structure") { + return "Skill structure issues reduce trigger quality and make the skill harder to trust or maintain."; + } + + if (check.category === "budget") { + return "Budget pressure matters because always-loaded or frequently-loaded text can make the workflow feel expensive fast."; + } + + if (check.category === "measurement") { + return "Weak measurement means you are still steering with estimates instead of evidence."; + } + + if (check.category === "best-practice") { + return "Best-practice gaps usually do not break the workflow immediately, but they make the skill harder to understand and improve."; + } + + if (check.category === "complexity") { + return "Complexity findings matter because they increase review cost and make generated or helper code harder to change safely."; + } + + if (check.category === "readability") { + return "Readability issues slow engineers down during review, debugging, and follow-up edits."; + } + + if (check.category === "code-quality") { + return "Code-quality findings matter because helper scripts and supporting code are part of the user experience too."; + } + + return "This finding affects confidence, clarity, or trust in the overall workflow."; +} + +function buildDeductions(checks) { + return checks + .map((check) => ({ + id: check.id, + category: check.category, + severity: check.severity, + status: check.status, + message: check.message, + penalty: computeCheckPenalty(check), + remediation: check.remediation, + source: check.source, + ...(check.targetPath ? { targetPath: check.targetPath } : {}), + })) + .filter((entry) => entry.penalty > 0) + .sort((left, right) => { + if (right.penalty !== left.penalty) { + return right.penalty - left.penalty; + } + return left.id.localeCompare(right.id); + }); +} + +function buildCategoryDeductions(deductions) { + const totals = new Map(); + for (const deduction of deductions) { + const current = totals.get(deduction.category) || { + category: deduction.category, + totalPenalty: 0, + checks: 0, + }; + current.totalPenalty += deduction.penalty; + current.checks += 1; + totals.set(deduction.category, current); + } + + return [...totals.values()].sort((left, right) => { + if (right.totalPenalty !== left.totalPenalty) { + return right.totalPenalty - left.totalPenalty; + } + return left.category.localeCompare(right.category); + }); +} + +function rankActionableChecks(checks) { + return checks + .filter((check) => check.status === "fail" || check.status === "warn") + .map((check) => ({ + ...check, + penalty: computeCheckPenalty(check), + why: deriveCheckWhy(check), + })) + .sort((left, right) => { + if (right.penalty !== left.penalty) { + return right.penalty - left.penalty; + } + if ((STATUS_PRIORITY[left.status] ?? 99) !== (STATUS_PRIORITY[right.status] ?? 99)) { + return (STATUS_PRIORITY[left.status] ?? 99) - (STATUS_PRIORITY[right.status] ?? 99); + } + if ((CATEGORY_PRIORITY[left.category] ?? 99) !== (CATEGORY_PRIORITY[right.category] ?? 99)) { + return (CATEGORY_PRIORITY[left.category] ?? 99) - (CATEGORY_PRIORITY[right.category] ?? 99); + } + return left.id.localeCompare(right.id); + }); +} + +function summarizeFinding(check) { + return { + id: check.id, + category: check.category, + severity: check.severity, + status: check.status, + message: check.message, + why: check.why, + remediation: check.remediation, + penalty: check.penalty, + source: check.source, + ...(check.targetPath ? { targetPath: check.targetPath } : {}), + }; +} + +function buildWhyBullets(result, summary, failedErrors, warningSignals) { + const bullets = []; + + if (failedErrors > 0) { + bullets.push(`${failedErrors} failing error check${failedErrors === 1 ? "" : "s"} are driving the highest-confidence problems.`); + } + + if (warningSignals > 0) { + bullets.push(`${warningSignals} warning signal${warningSignals === 1 ? "" : "s"} still need cleanup before this feels polished.`); + } + + if (summary.categoryDeductions.length > 0) { + const topCategory = summary.categoryDeductions[0]; + bullets.push(`${topCategory.category} is the largest source of score loss at -${topCategory.totalPenalty} points.`); + } + + if ( + ["heavy", "excessive"].includes(result.budgets?.trigger_cost_tokens?.band) || + ["heavy", "excessive"].includes(result.budgets?.invoke_cost_tokens?.band) + ) { + bullets.push("Active budget pressure is high enough that token cost may dominate the user experience."); + } else { + bullets.push("Budget pressure is not the dominant issue right now."); + } + + if (result.observedUsage?.sampleCount) { + bullets.push(`Observed usage is available from ${result.observedUsage.sampleCount} sample${result.observedUsage.sampleCount === 1 ? "" : "s"}.`); + } else { + bullets.push("No observed usage is attached yet, so budget conclusions are still based on static estimates."); + } + + if (bullets.length === 0) { + bullets.push(`Current grade is ${summary.grade} with ${summary.riskLevel} reported risk.`); + } + + return bullets.slice(0, 5); +} + +function buildRiskReasons({ score, failedErrors, warningSignals, deductions, checkSummary }) { + const reasons = []; + if (failedErrors > 0) { + const examples = deductions + .filter((entry) => entry.status === "fail" && entry.severity === "error") + .slice(0, 3) + .map((entry) => entry.id); + reasons.push( + `Contains ${failedErrors} failing error check${failedErrors === 1 ? "" : "s"}${ + examples.length > 0 ? ` (${examples.join(", ")})` : "" + }.`, + ); + } + if (score < GRADE_THRESHOLDS.C) { + reasons.push(`Overall score is below ${GRADE_THRESHOLDS.C}, which the evaluator treats as high risk.`); + } else if (warningSignals > 0) { + reasons.push( + `Contains ${warningSignals} warning signal${warningSignals === 1 ? "" : "s"} that still need attention.`, + ); + } + if (checkSummary.info > 0 && reasons.length === 0) { + reasons.push("No failing or warning checks were found; remaining items are informational only."); + } + if (reasons.length === 0) { + reasons.push("No failing error checks and no warning signals were found."); + } + return reasons; +} + +export function computeSummary(result) { + const deductions = buildDeductions(result.checks); + const penalty = deductions.reduce((total, entry) => total + entry.penalty, 0); + + const score = Math.max(0, Math.round(100 - penalty)); + const grade = + score >= GRADE_THRESHOLDS.A + ? "A" + : score >= GRADE_THRESHOLDS.B + ? "B" + : score >= GRADE_THRESHOLDS.C + ? "C" + : score >= GRADE_THRESHOLDS.D + ? "D" + : "F"; + + const failedErrors = result.checks.filter( + (check) => check.status === "fail" && check.severity === "error", + ).length; + const warningSignals = result.checks.filter((check) => check.status === "warn").length; + const riskLevel = failedErrors > 0 || score < 70 ? "high" : warningSignals > 0 || score < 85 ? "medium" : "low"; + const checkCounts = summarizeChecks(result.checks); + const riskReasons = buildRiskReasons({ + score, + failedErrors, + warningSignals, + deductions, + checkSummary: checkCounts, + }); + + const topRecommendations = unique( + result.checks + .filter((check) => check.status === "fail" || check.status === "warn") + .flatMap((check) => check.remediation) + .slice(0, 5), + ); + + return enrichSummary(result, { + score, + grade, + riskLevel, + riskReasons, + scoreBreakdown: { + startingScore: 100, + totalDeductions: penalty, + finalScore: score, + gradeThresholds: GRADE_THRESHOLDS, + }, + checkCounts, + deductions, + categoryDeductions: buildCategoryDeductions(deductions), + topRecommendations, + }); +} + +export function enrichSummary(result, summary) { + const deductions = Array.isArray(summary?.deductions) ? summary.deductions : buildDeductions(result.checks); + const categoryDeductions = Array.isArray(summary?.categoryDeductions) + ? summary.categoryDeductions + : buildCategoryDeductions(deductions); + const failedErrors = result.checks.filter( + (check) => check.status === "fail" && check.severity === "error", + ).length; + const warningSignals = result.checks.filter((check) => check.status === "warn").length; + const actionableChecks = rankActionableChecks(result.checks).map(summarizeFinding); + const nextSummary = { + ...summary, + deductions, + categoryDeductions, + }; + + return { + ...nextSummary, + whyBullets: + Array.isArray(nextSummary.whyBullets) && nextSummary.whyBullets.length > 0 + ? nextSummary.whyBullets + : buildWhyBullets(result, { ...nextSummary, categoryDeductions }, failedErrors, warningSignals), + fixFirst: + Array.isArray(nextSummary.fixFirst) && nextSummary.fixFirst.length > 0 + ? nextSummary.fixFirst + : actionableChecks.slice(0, 3), + watchNext: + Array.isArray(nextSummary.watchNext) && nextSummary.watchNext.length > 0 + ? nextSummary.watchNext + : actionableChecks.slice(3, 6), + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/target.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/target.js new file mode 100644 index 0000000000000000000000000000000000000000..ca5545acb91abd7f1ce71167385401caf8e30ab1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/target.js @@ -0,0 +1,89 @@ +import path from "node:path"; + +import { isDirectory, isFile, pathExists, listImmediateDirectories, readJson } from "../lib/files.js"; + +export async function resolveTarget(inputPath) { + const resolvedPath = path.resolve(inputPath); + if (await isFile(resolvedPath)) { + if (path.basename(resolvedPath) === "SKILL.md") { + return { + kind: "skill", + path: path.dirname(resolvedPath), + entryPath: resolvedPath, + name: path.basename(path.dirname(resolvedPath)), + }; + } + if ( + path.basename(resolvedPath) === "plugin.json" && + path.basename(path.dirname(resolvedPath)) === ".codex-plugin" + ) { + return { + kind: "plugin", + path: path.dirname(path.dirname(resolvedPath)), + entryPath: resolvedPath, + name: path.basename(path.dirname(path.dirname(resolvedPath))), + }; + } + + return { + kind: "file", + path: resolvedPath, + entryPath: resolvedPath, + name: path.basename(resolvedPath), + }; + } + + if (!(await isDirectory(resolvedPath))) { + throw new Error(`Target path does not exist: ${resolvedPath}`); + } + + const pluginManifestPath = path.join(resolvedPath, ".codex-plugin", "plugin.json"); + if (await pathExists(pluginManifestPath)) { + return { + kind: "plugin", + path: resolvedPath, + entryPath: pluginManifestPath, + name: path.basename(resolvedPath), + }; + } + + const skillPath = path.join(resolvedPath, "SKILL.md"); + if (await pathExists(skillPath)) { + return { + kind: "skill", + path: resolvedPath, + entryPath: skillPath, + name: path.basename(resolvedPath), + }; + } + + return { + kind: "directory", + path: resolvedPath, + entryPath: resolvedPath, + name: path.basename(resolvedPath), + }; +} + +export async function discoverPluginSkillDirectories(pluginRoot, manifest) { + const configuredPath = manifest?.skills ? manifest.skills.replace(/^\.\//, "") : "skills"; + const skillsRoot = path.join(pluginRoot, configuredPath); + if (!(await isDirectory(skillsRoot))) { + return []; + } + + const candidates = await listImmediateDirectories(skillsRoot); + const directories = []; + for (const candidate of candidates) { + const skillFile = path.join(candidate, "SKILL.md"); + if (await pathExists(skillFile)) { + directories.push(candidate); + } + } + return directories; +} + +export async function loadPluginManifest(pluginRoot) { + const manifestPath = path.join(pluginRoot, ".codex-plugin", "plugin.json"); + return readJson(manifestPath); +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/workflow-guide.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/workflow-guide.js new file mode 100644 index 0000000000000000000000000000000000000000..d19f97a9ec02be1885f999cc150b763a8cbefd8d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/core/workflow-guide.js @@ -0,0 +1,397 @@ +import path from "node:path"; + +import { formatCommandPath, pathExists, relativePath } from "../lib/files.js"; +import { createWorkflowGuideNextAction } from "./presentation.js"; +import { resolveTarget } from "./target.js"; + +function shellQuote(value) { + return `'${String(value).replaceAll("'", "'\\''")}'`; +} + +function benchmarkConfigPath(target) { + return path.join(target.path, ".plugin-eval", "benchmark.json"); +} + +function usageLogPath(target) { + return path.join(target.path, ".plugin-eval", "benchmark-usage.jsonl"); +} + +function targetLabel(target) { + if (target.kind === "plugin") { + return "plugin"; + } + if (target.kind === "skill") { + return "skill"; + } + return "target"; +} + +function chatPromptForGoal(goal, target) { + const label = targetLabel(target); + if (goal === "analysis") { + return `Give me a full analysis of this ${label}, including benchmark setup.`; + } + if (goal === "evaluate") { + return `Evaluate this ${label}.`; + } + if (goal === "budget") { + return `Explain the token budget for this ${label}.`; + } + if (goal === "measure") { + return `Measure the real token usage of this ${label}.`; + } + if (goal === "benchmark") { + return `Help me benchmark this ${label}.`; + } + return "What should I run next?"; +} + +function requestSignal(phrases, reason) { + return { + phrases, + reason, + }; +} + +function inferGoalFromRequest(requestText) { + const normalized = String(requestText || "") + .trim() + .toLowerCase(); + + if (!normalized) { + return null; + } + + const signals = [ + [ + "analysis", + requestSignal( + [ + "full analysis", + "full eval", + "full evaluation", + "analyze this", + "analysis of", + "give me an analysis", + "deep analysis", + "deep dive", + ], + "it asks for a fuller analysis flow instead of only a single report or benchmark step", + ), + ], + [ + "measure", + requestSignal( + [ + "measure the real token usage", + "real token usage", + "observed usage", + "actual token usage", + "measure token usage", + ], + "it asks for measured or observed token usage", + ), + ], + [ + "benchmark", + requestSignal( + [ + "benchmark", + "dry-run", + "dry run", + "starter scenario", + "scenario", + ], + "it asks for a benchmark flow or scenario harness", + ), + ], + [ + "budget", + requestSignal( + [ + "explain the token budget", + "token budget", + "context cost", + "cost feels heavy", + "why is this expensive", + ], + "it asks why the target feels expensive before measuring live usage", + ), + ], + [ + "evaluate", + requestSignal( + [ + "evaluate", + "audit", + "review", + "score", + "report on", + "why did this score", + "what should i fix first", + "fix first", + ], + "it asks for the overall evaluation report or prioritized findings from it", + ), + ], + [ + "next", + requestSignal( + [ + "what should i run next", + "what next", + "where should i start", + "where do i start", + "start here", + "i'm not sure", + ], + "it asks for the best next step instead of a specific workflow", + ), + ], + ]; + + for (const [goal, signal] of signals) { + if (signal.phrases.some((phrase) => normalized.includes(phrase))) { + return { + goal, + reason: signal.reason, + }; + } + } + + return null; +} + +function workflowLabel(goal, target) { + if (goal === "analysis") { + return target.kind === "plugin" ? "Full Plugin Analysis" : "Full Skill Analysis"; + } + if (goal === "evaluate") { + return target.kind === "plugin" ? "Evaluate Plugin" : "Evaluate Skill"; + } + if (goal === "budget") { + return "Explain Token Budget"; + } + if (goal === "measure") { + return "Measure Real Token Usage"; + } + if (goal === "benchmark") { + return "Benchmark With Starter Scenarios"; + } + return "Start Here"; +} + +function commandsForGoal(goal, target, status) { + const commandTargetPath = formatCommandPath(target.path); + const commandConfigPath = formatCommandPath(benchmarkConfigPath(target)); + const commandUsagePath = formatCommandPath(usageLogPath(target)); + + if (goal === "analysis") { + if (!status.hasBenchmarkConfig) { + return [ + `plugin-eval analyze ${commandTargetPath} --format markdown`, + `plugin-eval init-benchmark ${commandTargetPath}`, + `plugin-eval benchmark ${commandTargetPath} --config ${commandConfigPath}`, + ]; + } + + if (!status.hasUsageLog) { + return [ + `plugin-eval analyze ${commandTargetPath} --format markdown`, + `plugin-eval benchmark ${commandTargetPath} --config ${commandConfigPath}`, + ]; + } + + return [ + `plugin-eval analyze ${commandTargetPath} --observed-usage ${commandUsagePath} --format markdown`, + `plugin-eval measurement-plan ${commandTargetPath} --observed-usage ${commandUsagePath} --format markdown`, + ]; + } + + if (goal === "evaluate") { + return [`plugin-eval analyze ${commandTargetPath} --format markdown`]; + } + + if (goal === "budget") { + return [`plugin-eval explain-budget ${commandTargetPath} --format markdown`]; + } + + if (goal === "measure") { + if (!status.hasBenchmarkConfig) { + return [ + `plugin-eval init-benchmark ${commandTargetPath}`, + `plugin-eval benchmark ${commandTargetPath} --config ${commandConfigPath}`, + `plugin-eval analyze ${commandTargetPath} --observed-usage ${commandUsagePath} --format markdown`, + ]; + } + + if (!status.hasUsageLog) { + return [ + `plugin-eval benchmark ${commandTargetPath} --config ${commandConfigPath}`, + `plugin-eval analyze ${commandTargetPath} --observed-usage ${commandUsagePath} --format markdown`, + ]; + } + + return [ + `plugin-eval analyze ${commandTargetPath} --observed-usage ${commandUsagePath} --format markdown`, + `plugin-eval measurement-plan ${commandTargetPath} --observed-usage ${commandUsagePath} --format markdown`, + ]; + } + + if (goal === "benchmark") { + if (!status.hasBenchmarkConfig) { + return [ + `plugin-eval init-benchmark ${commandTargetPath}`, + ]; + } + + return [ + `plugin-eval benchmark ${commandTargetPath} --config ${commandConfigPath}`, + ]; + } + + if (status.hasUsageLog) { + return [ + `plugin-eval analyze ${commandTargetPath} --observed-usage ${commandUsagePath} --format markdown`, + `plugin-eval measurement-plan ${commandTargetPath} --observed-usage ${commandUsagePath} --format markdown`, + ]; + } + + if (status.hasBenchmarkConfig) { + return [ + `plugin-eval benchmark ${commandTargetPath} --config ${commandConfigPath}`, + ]; + } + + return [`plugin-eval analyze ${commandTargetPath} --format markdown`]; +} + +function summaryForGoal(goal, target, status) { + const label = targetLabel(target); + + if (goal === "analysis") { + if (status.hasUsageLog) { + return `Use this when you want the full report plus measured usage follow-through for this ${label}.`; + } + if (status.hasBenchmarkConfig) { + return `Use this when you want the full report and already have benchmark scaffolding ready for this ${label}.`; + } + return `Use this when you want the full report and starter benchmark setup for this ${label} in one guided path.`; + } + + if (goal === "evaluate") { + return `Start here when you want the overall report for a ${label}, including structure, budgets, and code checks.`; + } + + if (goal === "budget") { + return `Use this when the main question is why the ${label} feels expensive before you collect any live measurements.`; + } + + if (goal === "measure") { + return status.hasUsageLog + ? `You already have a local usage log, so the next step is to fold those real measurements back into the report.` + : `Use this when you want real token usage instead of only the static estimate.`; + } + + if (goal === "benchmark") { + return `Use this when you want starter scenarios and a repeatable real-Codex benchmark run for this ${label}.`; + } + + if (status.hasUsageLog) { + return "You already collected benchmark output, so the best next step is to analyze the real usage and decide what to improve."; + } + + if (status.hasBenchmarkConfig) { + return "You already have a benchmark config, so the next step is to run it."; + } + + return `If you are new to plugin-eval, start with the overall evaluation report for this ${label}.`; +} + +function inferRecommendedGoal(status, explicitGoal) { + if (explicitGoal && explicitGoal !== "next") { + return explicitGoal; + } + + if (status.hasUsageLog) { + return "measure"; + } + + if (status.hasBenchmarkConfig) { + return "benchmark"; + } + + return "evaluate"; +} + +function createEntry(goal, target, status) { + const commandTargetPath = formatCommandPath(target.path); + const chatPrompt = chatPromptForGoal(goal, target); + const commands = commandsForGoal(goal, target, status); + return { + id: goal, + label: workflowLabel(goal, target), + chatPrompt, + summary: summaryForGoal(goal, target, status), + firstCommand: commands[0], + commands, + startCommand: `plugin-eval start ${commandTargetPath} --request ${shellQuote(chatPrompt)} --format markdown`, + }; +} + +export async function buildWorkflowGuide(targetPath, options = {}) { + const target = await resolveTarget(targetPath); + const status = { + hasBenchmarkConfig: await pathExists(benchmarkConfigPath(target)), + hasUsageLog: await pathExists(usageLogPath(target)), + }; + const requestMatch = inferGoalFromRequest(options.request || ""); + + const entries = [ + createEntry("analysis", target, status), + createEntry("evaluate", target, status), + createEntry("budget", target, status), + createEntry("measure", target, status), + createEntry("benchmark", target, status), + createEntry("next", target, status), + ]; + + const requestedGoal = options.goal || requestMatch?.goal || null; + const recommendedGoal = inferRecommendedGoal(status, requestedGoal); + const recommendedWorkflow = entries.find((entry) => entry.id === recommendedGoal) || entries[0]; + const routedRequest = options.request || recommendedWorkflow.chatPrompt; + const commandTargetPath = formatCommandPath(target.path); + const routingExplanation = requestMatch + ? `Plugin Eval routed "${options.request}" to ${recommendedWorkflow.label} because ${requestMatch.reason}.` + : `Plugin Eval recommended ${recommendedWorkflow.label} from the current local state for this ${targetLabel(target)}.`; + + const payload = { + kind: "workflow-guide", + createdAt: new Date().toISOString(), + target: { + ...target, + relativePath: relativePath(process.cwd(), target.path), + }, + requestedGoal, + requestedChatPrompt: options.request || null, + requestRouting: requestMatch, + recommendedWorkflowId: recommendedWorkflow.id, + recommendedWorkflow, + workflowStatus: status, + beginnerSummary: + "Start with a natural chat request, then let plugin-eval show the exact local command sequence behind it.", + startHere: { + chatPrompt: routedRequest, + label: recommendedWorkflow.label, + summary: recommendedWorkflow.summary, + routingExplanation, + startCommand: `plugin-eval start ${commandTargetPath} --request ${shellQuote(routedRequest)} --format markdown`, + firstCommand: recommendedWorkflow.firstCommand, + commands: recommendedWorkflow.commands, + }, + entrypoints: entries, + nextSteps: recommendedWorkflow.commands, + }; + payload.nextAction = createWorkflowGuideNextAction(payload); + return payload; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/code.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/code.js new file mode 100644 index 0000000000000000000000000000000000000000..b9afa61a995be9b7ea60494d02ec8b7130549522 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/code.js @@ -0,0 +1,41 @@ +import path from "node:path"; + +import { walkFiles } from "../lib/files.js"; +import { analyzePythonFiles } from "./python.js"; +import { analyzeTypeScriptFiles } from "./typescript.js"; + +function filterLanguageFiles(files) { + const tsFiles = []; + const pyFiles = []; + + for (const filePath of files) { + const extension = path.extname(filePath).toLowerCase(); + if ([".ts", ".tsx", ".mts", ".cts"].includes(extension)) { + tsFiles.push(filePath); + } else if (extension === ".py") { + pyFiles.push(filePath); + } + } + + return { tsFiles, pyFiles }; +} + +export async function analyzeCodeMetrics(rootPath, target) { + const files = + target.kind === "file" + ? [target.path] + : await walkFiles(rootPath, { + excludeDirs: [], + skipTopLevel: target.kind === "directory" ? [] : ["fixtures", "__fixtures__"], + }); + const { tsFiles, pyFiles } = filterLanguageFiles(files); + + const tsAnalysis = await analyzeTypeScriptFiles(tsFiles, rootPath); + const pyAnalysis = await analyzePythonFiles(pyFiles, rootPath); + + return { + checks: [...tsAnalysis.checks, ...pyAnalysis.checks], + metrics: [...tsAnalysis.metrics, ...pyAnalysis.metrics], + artifacts: [...tsAnalysis.artifacts, ...pyAnalysis.artifacts], + }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/coverage.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/coverage.js new file mode 100644 index 0000000000000000000000000000000000000000..ba902cad7f185fc681adc479cf2d9efae4ef545c --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/coverage.js @@ -0,0 +1,180 @@ +import fs from "node:fs/promises"; +import path from "node:path"; + +import { createArtifact, createCheck, createMetric } from "../core/schema.js"; +import { pathExists, readJson, readText, relativePath } from "../lib/files.js"; + +async function findCoverageFiles(rootPath) { + const results = []; + const ignored = new Set([".git", "node_modules", ".venv", "venv", "__pycache__"]); + + async function visit(currentPath) { + const entries = await fs.readdir(currentPath, { withFileTypes: true }); + for (const entry of entries) { + const entryPath = path.join(currentPath, entry.name); + if (entry.isDirectory()) { + if (ignored.has(entry.name)) { + continue; + } + await visit(entryPath); + continue; + } + if ( + entry.isFile() && + ["lcov.info", "coverage.xml", "coverage-final.json", "coverage-summary.json"].includes(entry.name) + ) { + results.push(entryPath); + } + } + } + + await visit(rootPath); + return results.sort(); +} + +async function parseLcov(filePath) { + const text = await readText(filePath); + let found = 0; + let hit = 0; + for (const line of text.split("\n")) { + if (line.startsWith("LF:")) { + found += Number(line.slice(3)); + } else if (line.startsWith("LH:")) { + hit += Number(line.slice(3)); + } + } + return found > 0 ? Number(((hit / found) * 100).toFixed(2)) : null; +} + +async function parseCoverageXml(filePath) { + const text = await readText(filePath); + const lineRateMatch = /line-rate="([^"]+)"/.exec(text); + if (lineRateMatch) { + return Number((Number(lineRateMatch[1]) * 100).toFixed(2)); + } + const coveredMatch = /lines-covered="([^"]+)"/.exec(text); + const validMatch = /lines-valid="([^"]+)"/.exec(text); + if (coveredMatch && validMatch && Number(validMatch[1]) > 0) { + return Number(((Number(coveredMatch[1]) / Number(validMatch[1])) * 100).toFixed(2)); + } + return null; +} + +async function parseCoverageJson(filePath) { + const payload = await readJson(filePath); + if (payload.total?.lines?.pct != null) { + return Number(payload.total.lines.pct); + } + + const fileEntries = Object.values(payload).filter((value) => value && typeof value === "object" && value.s); + let totalStatements = 0; + let coveredStatements = 0; + for (const entry of fileEntries) { + for (const count of Object.values(entry.s)) { + totalStatements += 1; + if (Number(count) > 0) { + coveredStatements += 1; + } + } + } + if (totalStatements === 0) { + return null; + } + return Number(((coveredStatements / totalStatements) * 100).toFixed(2)); +} + +async function parseCoverageFile(filePath) { + if (filePath.endsWith("lcov.info")) { + return parseLcov(filePath); + } + if (filePath.endsWith("coverage.xml")) { + return parseCoverageXml(filePath); + } + if (filePath.endsWith(".json")) { + return parseCoverageJson(filePath); + } + return null; +} + +export async function analyzeCoverageArtifacts(rootPath) { + const checks = []; + const metrics = []; + const artifacts = []; + const coverageFiles = await findCoverageFiles(rootPath); + + metrics.push( + createMetric({ + id: "coverage_artifact_count", + category: "coverage", + value: coverageFiles.length, + unit: "files", + band: coverageFiles.length > 0 ? "good" : "info", + }), + ); + + if (coverageFiles.length === 0) { + checks.push( + createCheck({ + id: "coverage-artifacts-unavailable", + category: "coverage", + severity: "info", + status: "info", + message: "No coverage artifacts were found for this target.", + evidence: [relativePath(process.cwd(), rootPath)], + remediation: ["Generate `lcov.info`, `coverage.xml`, or an Istanbul coverage JSON file if you want coverage scoring."], + }), + ); + return { checks, metrics, artifacts }; + } + + const fileSummaries = []; + for (const filePath of coverageFiles) { + const coverage = await parseCoverageFile(filePath); + if (coverage != null) { + fileSummaries.push({ + path: relativePath(rootPath, filePath), + coverage, + }); + } + } + + if (fileSummaries.length > 0) { + const bestCoverage = Math.max(...fileSummaries.map((item) => item.coverage)); + metrics.push( + createMetric({ + id: "coverage_percent", + category: "coverage", + value: bestCoverage, + unit: "percent", + band: bestCoverage >= 85 ? "good" : bestCoverage >= 70 ? "moderate" : "heavy", + }), + ); + if (bestCoverage < 70) { + checks.push( + createCheck({ + id: "coverage-low", + category: "coverage", + severity: "warning", + status: "warn", + message: "Coverage artifacts were found, but the measured coverage is low.", + evidence: fileSummaries.map((item) => `${item.path}: ${item.coverage}%`), + remediation: ["Increase test coverage on the code that carries the most complexity or risk."], + }), + ); + } + } + + artifacts.push( + createArtifact({ + id: "coverage-artifacts", + type: "coverage", + label: "Coverage artifacts", + description: "Coverage files discovered during evaluation.", + data: { + files: fileSummaries, + }, + }), + ); + + return { checks, metrics, artifacts }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/plugin.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..468c7dec94e62664e60ac345bce2270eed8d28b7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/plugin.js @@ -0,0 +1,291 @@ +import path from "node:path"; + +import { createArtifact, createCheck, createMetric } from "../core/schema.js"; +import { evaluateSkill } from "./skill.js"; +import { discoverPluginSkillDirectories } from "../core/target.js"; +import { pathExists, readJson, relativePath } from "../lib/files.js"; + +function isHyphenCase(value) { + return /^[a-z0-9-]+$/.test(value) && !value.startsWith("-") && !value.endsWith("-") && !value.includes("--"); +} + +export async function evaluatePlugin(pluginRoot) { + const manifestPath = path.join(pluginRoot, ".codex-plugin", "plugin.json"); + const targetPath = relativePath(process.cwd(), pluginRoot); + const checks = []; + const metrics = []; + const artifacts = []; + + if (!(await pathExists(manifestPath))) { + checks.push( + createCheck({ + id: "plugin-manifest-missing", + category: "manifest", + severity: "error", + status: "fail", + message: "The plugin root is missing .codex-plugin/plugin.json.", + evidence: [targetPath], + remediation: ["Add .codex-plugin/plugin.json to the plugin root."], + targetPath, + }), + ); + return { checks, metrics, artifacts }; + } + + let manifest; + try { + manifest = await readJson(manifestPath); + } catch (error) { + checks.push( + createCheck({ + id: "plugin-manifest-invalid-json", + category: "manifest", + severity: "error", + status: "fail", + message: "plugin.json could not be parsed as JSON.", + evidence: [error instanceof Error ? error.message : String(error)], + remediation: ["Fix the JSON syntax in .codex-plugin/plugin.json."], + targetPath, + }), + ); + return { checks, metrics, artifacts }; + } + + const requiredFields = ["name", "version", "description", "author", "interface"]; + for (const field of requiredFields) { + if (!(field in manifest)) { + checks.push( + createCheck({ + id: `manifest-missing-${field}`, + category: "manifest", + severity: "error", + status: "fail", + message: `plugin.json is missing the required \`${field}\` field.`, + evidence: [manifestPath], + remediation: [`Add \`${field}\` to plugin.json.`], + targetPath, + }), + ); + } + } + + if (manifest.name && !isHyphenCase(manifest.name)) { + checks.push( + createCheck({ + id: "manifest-name-not-hyphen-case", + category: "manifest", + severity: "error", + status: "fail", + message: "The plugin name should be lowercase hyphen-case.", + evidence: [`Current name: ${manifest.name}`], + remediation: ["Rename the plugin using lowercase letters, digits, and single hyphens only."], + targetPath, + }), + ); + } + + if (manifest.name && manifest.name !== path.basename(pluginRoot)) { + checks.push( + createCheck({ + id: "manifest-name-directory-mismatch", + category: "manifest", + severity: "warning", + status: "warn", + message: "The plugin manifest name does not match the plugin directory name.", + evidence: [`Directory: ${path.basename(pluginRoot)}`, `Manifest: ${manifest.name}`], + remediation: ["Keep the plugin directory name and plugin.json name aligned."], + targetPath, + }), + ); + } + + const interfaceFields = [ + "displayName", + "shortDescription", + "longDescription", + "developerName", + "category", + "capabilities", + "websiteURL", + "privacyPolicyURL", + "termsOfServiceURL", + "defaultPrompt", + ]; + const iface = manifest.interface || {}; + for (const field of interfaceFields) { + if (!(field in iface)) { + checks.push( + createCheck({ + id: `interface-missing-${field}`, + category: "manifest", + severity: "error", + status: "fail", + message: `plugin.json interface is missing \`${field}\`.`, + evidence: [manifestPath], + remediation: [`Add interface.${field} to plugin.json.`], + targetPath, + }), + ); + } + } + + const pathFields = [ + ["skills", manifest.skills], + ["hooks", manifest.hooks], + ["mcpServers", manifest.mcpServers], + ["apps", manifest.apps], + ["interface.composerIcon", iface.composerIcon], + ["interface.logo", iface.logo], + ]; + for (const [label, fieldValue] of pathFields) { + if (!fieldValue) { + continue; + } + if (typeof fieldValue !== "string" || !fieldValue.startsWith("./")) { + checks.push( + createCheck({ + id: `${label}-path-invalid`, + category: "manifest", + severity: "error", + status: "fail", + message: `${label} should use a plugin-relative path that starts with ./`, + evidence: [`Current value: ${String(fieldValue)}`], + remediation: [`Rewrite ${label} as a plugin-relative path like ./skills/.`], + targetPath, + }), + ); + continue; + } + + const resolvedPath = path.resolve(pluginRoot, fieldValue); + if (!(await pathExists(resolvedPath))) { + checks.push( + createCheck({ + id: `${label}-path-missing`, + category: "manifest", + severity: "error", + status: "fail", + message: `${label} points to a missing file or directory.`, + evidence: [fieldValue], + remediation: [`Create the target for ${label} or remove the field.`], + targetPath, + }), + ); + } + } + + if (Array.isArray(iface.defaultPrompt)) { + if (iface.defaultPrompt.length > 3) { + checks.push( + createCheck({ + id: "default-prompt-too-many", + category: "manifest", + severity: "warning", + status: "warn", + message: "Only the first three default prompts are used by Codex.", + evidence: [`Prompt count: ${iface.defaultPrompt.length}`], + remediation: ["Trim interface.defaultPrompt to three strong starters."], + targetPath, + }), + ); + } + const oversizedPrompts = iface.defaultPrompt.filter((prompt) => prompt.length > 128); + if (oversizedPrompts.length > 0) { + checks.push( + createCheck({ + id: "default-prompt-too-long", + category: "manifest", + severity: "warning", + status: "warn", + message: "One or more default prompts exceed the UI-friendly length budget.", + evidence: oversizedPrompts.map((prompt) => `${prompt.slice(0, 140)} (${prompt.length} chars)`), + remediation: ["Keep default prompts under 128 characters and ideally closer to 50."], + targetPath, + }), + ); + } + } + + if (iface.brandColor && !/^#[0-9A-Fa-f]{6}$/.test(iface.brandColor)) { + checks.push( + createCheck({ + id: "brand-color-invalid", + category: "manifest", + severity: "warning", + status: "warn", + message: "brandColor should be a six-character hex color.", + evidence: [`Current value: ${iface.brandColor}`], + remediation: ["Use a color like #0F766E."], + targetPath, + }), + ); + } + + const skillDirs = await discoverPluginSkillDirectories(pluginRoot, manifest); + if (skillDirs.length === 0) { + checks.push( + createCheck({ + id: "plugin-skills-missing", + category: "manifest", + severity: "warning", + status: "warn", + message: "The plugin did not expose any discoverable skills.", + evidence: [manifest.skills || "./skills/"], + remediation: ["Add at least one skill under the configured skills path."], + targetPath, + }), + ); + } + + for (const skillDir of skillDirs) { + const prefix = `skill:${path.basename(skillDir)}`; + const fragment = await evaluateSkill(skillDir, { prefix }); + checks.push(...fragment.checks); + metrics.push(...fragment.metrics); + artifacts.push(...fragment.artifacts); + } + + metrics.push( + createMetric({ + id: "plugin_skill_count", + category: "manifest", + value: skillDirs.length, + unit: "skills", + band: skillDirs.length > 0 ? "good" : "moderate", + targetPath, + }), + createMetric({ + id: "plugin_keyword_count", + category: "manifest", + value: Array.isArray(manifest.keywords) ? manifest.keywords.length : 0, + unit: "keywords", + band: Array.isArray(manifest.keywords) && manifest.keywords.length > 0 ? "good" : "info", + targetPath, + }), + createMetric({ + id: "plugin_default_prompt_count", + category: "manifest", + value: Array.isArray(iface.defaultPrompt) ? iface.defaultPrompt.length : 0, + unit: "prompts", + band: + Array.isArray(iface.defaultPrompt) && iface.defaultPrompt.length <= 3 + ? "good" + : "moderate", + targetPath, + }), + ); + + artifacts.push( + createArtifact({ + id: "plugin-skill-inventory", + type: "inventory", + label: "Plugin skills", + description: "Discoverable skills under the plugin.", + data: { + skills: skillDirs.map((skillDir) => relativePath(pluginRoot, skillDir)), + }, + }), + ); + + return { checks, metrics, artifacts, manifest }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/python.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/python.js new file mode 100644 index 0000000000000000000000000000000000000000..17b7d83af61ef2fdd80cea6aae32075b09b4f476 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/python.js @@ -0,0 +1,254 @@ +import { createArtifact, createCheck, createMetric } from "../core/schema.js"; +import { readText, relativePath } from "../lib/files.js"; + +function countMatches(text, expression) { + return (text.match(expression) || []).length; +} + +function countDecisionPoints(text) { + return ( + countMatches(text, /\bif\b/g) + + countMatches(text, /\belif\b/g) + + countMatches(text, /\bfor\b/g) + + countMatches(text, /\bwhile\b/g) + + countMatches(text, /\bexcept\b/g) + + countMatches(text, /\band\b/g) + + countMatches(text, /\bor\b/g) + ); +} + +function detectFunctions(lines) { + const functions = []; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]; + const match = /^(\s*)(?:async\s+def|def)\s+([A-Za-z0-9_]+)\s*\(([^)]*)\)\s*:/.exec(line); + if (!match) { + continue; + } + + const indent = match[1].length; + let endIndex = index; + for (let cursor = index + 1; cursor < lines.length; cursor += 1) { + const cursorLine = lines[cursor]; + const trimmed = cursorLine.trim(); + if (!trimmed) { + continue; + } + const cursorIndent = cursorLine.length - cursorLine.trimStart().length; + if (cursorIndent <= indent && !trimmed.startsWith("#")) { + break; + } + endIndex = cursor; + } + + const slice = lines.slice(index, endIndex + 1); + const source = slice.join("\n"); + const maxIndent = slice.reduce((max, sliceLine) => { + if (!sliceLine.trim()) { + return max; + } + const currentIndent = sliceLine.length - sliceLine.trimStart().length; + return Math.max(max, currentIndent); + }, indent); + const params = match[3] + .split(",") + .map((item) => item.trim()) + .filter(Boolean).length; + + functions.push({ + name: match[2], + startLine: index + 1, + endLine: endIndex + 1, + length: slice.length, + params, + complexity: 1 + countDecisionPoints(source), + nesting: Math.max(0, Math.round((maxIndent - indent) / 4)), + }); + } + return functions; +} + +export async function analyzePythonFiles(filePaths, rootPath) { + const checks = []; + const metrics = []; + const artifacts = []; + + if (filePaths.length === 0) { + return { checks, metrics, artifacts }; + } + + const perFile = []; + let totalCommentLines = 0; + let totalCodeLines = 0; + let totalLongLines = 0; + let totalImports = 0; + let totalClasses = 0; + let maxComplexity = 0; + let maxFunctionLength = 0; + let maxNesting = 0; + let functionCount = 0; + let totalFunctionLength = 0; + let testFileCount = 0; + + for (const filePath of filePaths) { + const source = await readText(filePath); + const lines = source.replace(/\r\n/g, "\n").split("\n"); + const functions = detectFunctions(lines); + const commentLines = lines.filter((line) => line.trim().startsWith("#")).length; + const longLines = lines.filter((line) => line.length > 120).length; + const imports = lines.filter((line) => /^(\s*)(import|from)\b/.test(line)).length; + const classes = countMatches(source, /^\s*class\s+[A-Za-z0-9_]+/gm); + const complexity = 1 + countDecisionPoints(source); + const fileMaxComplexity = functions.reduce((max, fn) => Math.max(max, fn.complexity), complexity); + const fileMaxFunctionLength = functions.reduce((max, fn) => Math.max(max, fn.length), 0); + const fileMaxNesting = functions.reduce((max, fn) => Math.max(max, fn.nesting), 0); + + totalCommentLines += commentLines; + totalCodeLines += lines.filter((line) => line.trim()).length; + totalLongLines += longLines; + totalImports += imports; + totalClasses += classes; + maxComplexity = Math.max(maxComplexity, fileMaxComplexity); + maxFunctionLength = Math.max(maxFunctionLength, fileMaxFunctionLength); + maxNesting = Math.max(maxNesting, fileMaxNesting); + functionCount += functions.length; + totalFunctionLength += functions.reduce((sum, fn) => sum + fn.length, 0); + if (/(^|\/)(tests?|__tests__)\/|(^|\/)test_[^/]+\.py$/.test(filePath)) { + testFileCount += 1; + } + + perFile.push({ + path: relativePath(rootPath, filePath), + functionCount: functions.length, + complexity: fileMaxComplexity, + maxFunctionLength: fileMaxFunctionLength, + maxNesting: fileMaxNesting, + longLines, + }); + } + + const averageFunctionLength = functionCount > 0 ? Number((totalFunctionLength / functionCount).toFixed(2)) : 0; + const commentRatio = totalCodeLines > 0 ? Number((totalCommentLines / totalCodeLines).toFixed(3)) : 0; + + metrics.push( + createMetric({ + id: "py_file_count", + category: "code-quality", + value: filePaths.length, + unit: "files", + band: filePaths.length > 0 ? "good" : "info", + }), + createMetric({ + id: "py_function_count", + category: "code-quality", + value: functionCount, + unit: "functions", + band: functionCount > 0 ? "good" : "info", + }), + createMetric({ + id: "py_max_cyclomatic_complexity", + category: "complexity", + value: maxComplexity, + unit: "score", + band: maxComplexity >= 18 ? "heavy" : maxComplexity >= 10 ? "moderate" : "good", + }), + createMetric({ + id: "py_average_function_length", + category: "readability", + value: averageFunctionLength, + unit: "lines", + band: averageFunctionLength >= 50 ? "heavy" : averageFunctionLength >= 30 ? "moderate" : "good", + }), + createMetric({ + id: "py_max_nesting_depth", + category: "complexity", + value: maxNesting, + unit: "levels", + band: maxNesting >= 5 ? "heavy" : maxNesting >= 3 ? "moderate" : "good", + }), + createMetric({ + id: "py_comment_ratio", + category: "readability", + value: commentRatio, + unit: "ratio", + band: commentRatio < 0.03 ? "moderate" : "good", + }), + createMetric({ + id: "py_test_file_count", + category: "best-practice", + value: testFileCount, + unit: "files", + band: testFileCount > 0 ? "good" : "moderate", + }), + ); + + if (maxComplexity >= 18) { + checks.push( + createCheck({ + id: "py-complexity-high", + category: "complexity", + severity: "warning", + status: "warn", + message: "At least one Python function has high cyclomatic complexity.", + evidence: [`Max complexity: ${maxComplexity}`], + remediation: ["Split complex functions into smaller helpers or guard clauses."], + }), + ); + } + + if (maxFunctionLength >= 80) { + checks.push( + createCheck({ + id: "py-function-length-high", + category: "readability", + severity: "warning", + status: "warn", + message: "At least one Python function is long enough to hurt readability.", + evidence: [`Max function length: ${maxFunctionLength} lines`], + remediation: ["Break large functions into smaller helpers with clear names."], + }), + ); + } + + if (totalLongLines > 0) { + checks.push( + createCheck({ + id: "py-long-lines", + category: "readability", + severity: "warning", + status: "warn", + message: "Some Python lines exceed 120 characters.", + evidence: [`Long lines: ${totalLongLines}`], + remediation: ["Wrap long expressions and keep docstrings or SQL fragments easier to scan."], + }), + ); + } + + if (filePaths.length > 0 && testFileCount === 0) { + checks.push( + createCheck({ + id: "py-tests-missing", + category: "best-practice", + severity: "warning", + status: "warn", + message: "Python source files were found without matching test files.", + evidence: [`Source files: ${filePaths.length}`], + remediation: ["Add `test_*.py` or `tests/` coverage for the main Python logic."], + }), + ); + } + + artifacts.push( + createArtifact({ + id: "py-per-file-analysis", + type: "analysis", + label: "Python per-file analysis", + description: "Heuristic Python quality and complexity breakdown by file.", + data: { + files: perFile, + }, + }), + ); + + return { checks, metrics, artifacts }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/skill.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/skill.js new file mode 100644 index 0000000000000000000000000000000000000000..b7c2dbcd5f4ede66f9b2388412fba0e5b8617929 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/skill.js @@ -0,0 +1,320 @@ +import path from "node:path"; + +import { createArtifact, createCheck, createMetric } from "../core/schema.js"; +import { parseFrontmatter } from "../lib/frontmatter.js"; +import { pathExists, readText, relativePath, walkFiles } from "../lib/files.js"; + +const ALLOWED_FRONTMATTER_KEYS = new Set([ + "name", + "description", + "license", + "allowed-tools", + "metadata", + "disable-model-invocation", + "user-invocable", + "context", + "agent", +]); + +function countCodeFences(markdown) { + return (markdown.match(/```/g) || []).length / 2; +} + +function findRelativeLinks(markdown) { + return [...markdown.matchAll(/\[[^\]]+\]\(([^)]+)\)/g)] + .map((match) => match[1]) + .filter( + (target) => + !target.startsWith("http://") && + !target.startsWith("https://") && + !target.startsWith("app://") && + !target.startsWith("plugin://") && + !target.startsWith("rules://") && + !target.startsWith("mailto:") && + !target.startsWith("#"), + ); +} + +function isHyphenCase(value) { + return /^[a-z0-9-]+$/.test(value) && !value.startsWith("-") && !value.endsWith("-") && !value.includes("--"); +} + +export async function evaluateSkill(skillRoot, options = {}) { + const prefix = options.prefix ? `${options.prefix}:` : ""; + const skillPath = path.join(skillRoot, "SKILL.md"); + const targetPath = relativePath(process.cwd(), skillRoot); + const checks = []; + const metrics = []; + const artifacts = []; + + if (!(await pathExists(skillPath))) { + checks.push( + createCheck({ + id: `${prefix}skill-file-missing`, + category: "skill-structure", + severity: "error", + status: "fail", + message: "The target skill directory is missing SKILL.md.", + evidence: [targetPath], + remediation: ["Add SKILL.md to the skill root."], + targetPath, + }), + ); + return { checks, metrics, artifacts }; + } + + const content = await readText(skillPath); + const lines = content.replace(/\r\n/g, "\n").split("\n"); + const parsed = parseFrontmatter(content); + const relativeLinks = findRelativeLinks(content); + const supportFiles = (await walkFiles(skillRoot)).filter((filePath) => filePath !== skillPath); + + if (parsed.errors.length > 0) { + checks.push( + createCheck({ + id: `${prefix}frontmatter-invalid`, + category: "skill-structure", + severity: "error", + status: "fail", + message: "The skill frontmatter could not be parsed.", + evidence: parsed.errors, + remediation: ["Fix the YAML frontmatter at the top of SKILL.md."], + targetPath, + }), + ); + } + + const frontmatter = parsed.data || {}; + const unexpectedKeys = Object.keys(frontmatter).filter((key) => !ALLOWED_FRONTMATTER_KEYS.has(key)); + if (unexpectedKeys.length > 0) { + checks.push( + createCheck({ + id: `${prefix}frontmatter-extra-keys`, + category: "best-practice", + severity: "warning", + status: "warn", + message: "The skill frontmatter contains keys outside the common Codex skill conventions.", + evidence: unexpectedKeys.map((key) => `Unexpected key: ${key}`), + remediation: ["Remove non-standard frontmatter keys or move the metadata into references."], + targetPath, + }), + ); + } + + if (!frontmatter.name) { + checks.push( + createCheck({ + id: `${prefix}name-missing`, + category: "skill-structure", + severity: "error", + status: "fail", + message: "The skill frontmatter is missing `name`.", + evidence: [targetPath], + remediation: ["Add a hyphen-case `name` field to the frontmatter."], + targetPath, + }), + ); + } else if (!isHyphenCase(frontmatter.name)) { + checks.push( + createCheck({ + id: `${prefix}name-not-hyphen-case`, + category: "skill-structure", + severity: "error", + status: "fail", + message: "The skill name should be lowercase hyphen-case.", + evidence: [`Current name: ${frontmatter.name}`], + remediation: ["Rename the skill using lowercase letters, digits, and single hyphens only."], + targetPath, + }), + ); + } + + if (!frontmatter.description) { + checks.push( + createCheck({ + id: `${prefix}description-missing`, + category: "skill-structure", + severity: "error", + status: "fail", + message: "The skill frontmatter is missing `description`.", + evidence: [targetPath], + remediation: ["Add a description that explains what the skill does and when to use it."], + targetPath, + }), + ); + } else { + if (frontmatter.description.length > 1024) { + checks.push( + createCheck({ + id: `${prefix}description-too-long`, + category: "budget", + severity: "warning", + status: "warn", + message: "The skill description is long enough to create unnecessary always-loaded context cost.", + evidence: [`Description length: ${frontmatter.description.length} characters`], + remediation: ["Shorten the description and push details into SKILL.md or references."], + targetPath, + }), + ); + } + if (!/use when/i.test(frontmatter.description)) { + checks.push( + createCheck({ + id: `${prefix}description-trigger-weak`, + category: "best-practice", + severity: "warning", + status: "warn", + message: "The description does not clearly advertise when the skill should trigger.", + evidence: ["Descriptions are the primary auto-load surface in Codex."], + remediation: ["Rewrite the description to include a clear 'Use when ...' trigger sentence."], + targetPath, + }), + ); + } + } + + if (lines.length > 800) { + checks.push( + createCheck({ + id: `${prefix}skill-too-large`, + category: "budget", + severity: "error", + status: "fail", + message: "SKILL.md is extremely large for an always-loaded invocation surface.", + evidence: [`Line count: ${lines.length}`], + remediation: ["Move large details into references/ and keep SKILL.md focused on the core workflow."], + targetPath, + }), + ); + } else if (lines.length > 500) { + checks.push( + createCheck({ + id: `${prefix}skill-large`, + category: "budget", + severity: "warning", + status: "warn", + message: "SKILL.md exceeds the recommended compact size for progressive disclosure.", + evidence: [`Line count: ${lines.length}`], + remediation: ["Trim repetitive detail and move long variants into references/."], + targetPath, + }), + ); + } + + if (lines.length > 350 && supportFiles.filter((filePath) => filePath.includes("/references/")).length === 0) { + checks.push( + createCheck({ + id: `${prefix}progressive-disclosure-missing`, + category: "best-practice", + severity: "warning", + status: "warn", + message: "The skill is getting large without using references for progressive disclosure.", + evidence: ["Large skills are easier to maintain when variants live under references/."], + remediation: ["Move deep detail or edge-case variants into references/ and link them from SKILL.md."], + targetPath, + }), + ); + } + + const brokenLinks = []; + for (const target of relativeLinks) { + const candidatePath = path.resolve(skillRoot, target); + if (!(await pathExists(candidatePath))) { + brokenLinks.push(target); + } + } + if (brokenLinks.length > 0) { + checks.push( + createCheck({ + id: `${prefix}broken-relative-links`, + category: "skill-structure", + severity: "error", + status: "fail", + message: "The skill contains relative links that do not resolve inside the skill directory.", + evidence: brokenLinks, + remediation: ["Fix or remove broken links in SKILL.md."], + targetPath, + }), + ); + } + + const extraDocs = supportFiles + .map((filePath) => path.basename(filePath)) + .filter((name) => ["README.md", "CHANGELOG.md", "CONTRIBUTING.md"].includes(name)); + if (extraDocs.length > 0) { + checks.push( + createCheck({ + id: `${prefix}extra-doc-files`, + category: "best-practice", + severity: "warning", + status: "warn", + message: "The skill includes extra documentation files that usually belong in references/ or outside the skill bundle.", + evidence: extraDocs, + remediation: ["Move reusable guidance into references/ and avoid extra top-level docs inside the skill bundle."], + targetPath, + }), + ); + } + + metrics.push( + createMetric({ + id: `${prefix}skill_line_count`, + category: "budget", + value: lines.length, + unit: "lines", + band: lines.length > 500 ? "heavy" : lines.length > 350 ? "moderate" : "good", + targetPath, + }), + createMetric({ + id: `${prefix}description_length_chars`, + category: "budget", + value: String(frontmatter.description || "").length, + unit: "chars", + band: + String(frontmatter.description || "").length > 1024 + ? "heavy" + : String(frontmatter.description || "").length > 512 + ? "moderate" + : "good", + targetPath, + }), + createMetric({ + id: `${prefix}relative_link_count`, + category: "documentation", + value: relativeLinks.length, + unit: "links", + band: relativeLinks.length > 10 ? "moderate" : "good", + targetPath, + }), + createMetric({ + id: `${prefix}code_fence_count`, + category: "readability", + value: countCodeFences(content), + unit: "blocks", + band: countCodeFences(content) > 8 ? "moderate" : "good", + targetPath, + }), + createMetric({ + id: `${prefix}support_file_count`, + category: "documentation", + value: supportFiles.length, + unit: "files", + band: supportFiles.length > 0 ? "good" : "info", + targetPath, + }), + ); + + artifacts.push( + createArtifact({ + id: `${prefix}skill-link-inventory`, + type: "inventory", + label: "Skill relative links", + description: "Relative links found in SKILL.md.", + data: { + links: relativeLinks, + }, + }), + ); + + return { checks, metrics, artifacts }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/typescript.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/typescript.js new file mode 100644 index 0000000000000000000000000000000000000000..db812ff7afdb4497360a2f7b05ea59123f09d9c6 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/evaluators/typescript.js @@ -0,0 +1,255 @@ +import { createArtifact, createCheck, createMetric } from "../core/schema.js"; +import { readText, relativePath } from "../lib/files.js"; + +function countMatches(text, expression) { + return (text.match(expression) || []).length; +} + +function countDecisionPoints(text) { + return ( + countMatches(text, /\bif\b/g) + + countMatches(text, /\bfor\b/g) + + countMatches(text, /\bwhile\b/g) + + countMatches(text, /\bcase\b/g) + + countMatches(text, /\bcatch\b/g) + + countMatches(text, /&&/g) + + countMatches(text, /\|\|/g) + + countMatches(text, /\?/g) + ); +} + +function detectFunctions(lines) { + const functions = []; + const startMatchers = [ + /\b(?:async\s+)?function\s+([A-Za-z0-9_$]+)\s*\(([^)]*)\)\s*\{/, + /\b(?:const|let|var)\s+([A-Za-z0-9_$]+)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>\s*\{/, + /^\s*(?:public|private|protected|static|readonly|\s)*(?!if\b|for\b|while\b|switch\b|catch\b)([A-Za-z0-9_$]+)\s*\(([^)]*)\)\s*\{/, + ]; + + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]; + const match = startMatchers.map((matcher) => matcher.exec(line)).find(Boolean); + if (!match) { + continue; + } + + let braceBalance = countMatches(line, /\{/g) - countMatches(line, /\}/g); + let endIndex = index; + while (braceBalance > 0 && endIndex + 1 < lines.length) { + endIndex += 1; + braceBalance += countMatches(lines[endIndex], /\{/g) - countMatches(lines[endIndex], /\}/g); + } + + const slice = lines.slice(index, endIndex + 1); + const source = slice.join("\n"); + const params = match[2] + .split(",") + .map((item) => item.trim()) + .filter(Boolean).length; + + let braceDepth = 0; + let maxDepth = 0; + for (const sliceLine of slice) { + braceDepth += countMatches(sliceLine, /\{/g); + maxDepth = Math.max(maxDepth, braceDepth); + braceDepth -= countMatches(sliceLine, /\}/g); + } + + functions.push({ + name: match[1], + startLine: index + 1, + endLine: endIndex + 1, + length: slice.length, + params, + complexity: 1 + countDecisionPoints(source), + nesting: Math.max(0, maxDepth - 1), + }); + } + + return functions; +} + +export async function analyzeTypeScriptFiles(filePaths, rootPath) { + const checks = []; + const metrics = []; + const artifacts = []; + + if (filePaths.length === 0) { + return { checks, metrics, artifacts }; + } + + const perFile = []; + let totalCommentLines = 0; + let totalCodeLines = 0; + let totalLongLines = 0; + let totalImports = 0; + let totalClasses = 0; + let maxComplexity = 0; + let maxFunctionLength = 0; + let maxNesting = 0; + let functionCount = 0; + let totalFunctionLength = 0; + let testFileCount = 0; + + for (const filePath of filePaths) { + const source = await readText(filePath); + const lines = source.replace(/\r\n/g, "\n").split("\n"); + const functions = detectFunctions(lines); + const commentLines = lines.filter((line) => line.trim().startsWith("//") || line.trim().startsWith("*") || line.trim().startsWith("/*")).length; + const longLines = lines.filter((line) => line.length > 120).length; + const imports = lines.filter((line) => line.trim().startsWith("import ")).length; + const classes = countMatches(source, /\bclass\s+[A-Za-z0-9_$]+/g); + const complexity = 1 + countDecisionPoints(source); + const fileMaxComplexity = functions.reduce((max, fn) => Math.max(max, fn.complexity), complexity); + const fileMaxFunctionLength = functions.reduce((max, fn) => Math.max(max, fn.length), 0); + const fileMaxNesting = functions.reduce((max, fn) => Math.max(max, fn.nesting), 0); + + totalCommentLines += commentLines; + totalCodeLines += lines.filter((line) => line.trim()).length; + totalLongLines += longLines; + totalImports += imports; + totalClasses += classes; + maxComplexity = Math.max(maxComplexity, fileMaxComplexity); + maxFunctionLength = Math.max(maxFunctionLength, fileMaxFunctionLength); + maxNesting = Math.max(maxNesting, fileMaxNesting); + functionCount += functions.length; + totalFunctionLength += functions.reduce((sum, fn) => sum + fn.length, 0); + if (/(^|\/)(tests?|__tests__)\/|(\.test|\.spec)\./.test(filePath)) { + testFileCount += 1; + } + + perFile.push({ + path: relativePath(rootPath, filePath), + functionCount: functions.length, + complexity: fileMaxComplexity, + maxFunctionLength: fileMaxFunctionLength, + maxNesting: fileMaxNesting, + longLines, + }); + } + + const averageFunctionLength = functionCount > 0 ? Number((totalFunctionLength / functionCount).toFixed(2)) : 0; + const commentRatio = totalCodeLines > 0 ? Number((totalCommentLines / totalCodeLines).toFixed(3)) : 0; + + metrics.push( + createMetric({ + id: "ts_file_count", + category: "code-quality", + value: filePaths.length, + unit: "files", + band: filePaths.length > 0 ? "good" : "info", + }), + createMetric({ + id: "ts_function_count", + category: "code-quality", + value: functionCount, + unit: "functions", + band: functionCount > 0 ? "good" : "info", + }), + createMetric({ + id: "ts_max_cyclomatic_complexity", + category: "complexity", + value: maxComplexity, + unit: "score", + band: maxComplexity >= 18 ? "heavy" : maxComplexity >= 10 ? "moderate" : "good", + }), + createMetric({ + id: "ts_average_function_length", + category: "readability", + value: averageFunctionLength, + unit: "lines", + band: averageFunctionLength >= 50 ? "heavy" : averageFunctionLength >= 30 ? "moderate" : "good", + }), + createMetric({ + id: "ts_max_nesting_depth", + category: "complexity", + value: maxNesting, + unit: "levels", + band: maxNesting >= 5 ? "heavy" : maxNesting >= 3 ? "moderate" : "good", + }), + createMetric({ + id: "ts_comment_ratio", + category: "readability", + value: commentRatio, + unit: "ratio", + band: commentRatio < 0.03 ? "moderate" : "good", + }), + createMetric({ + id: "ts_test_file_count", + category: "best-practice", + value: testFileCount, + unit: "files", + band: testFileCount > 0 ? "good" : "moderate", + }), + ); + + if (maxComplexity >= 18) { + checks.push( + createCheck({ + id: "ts-complexity-high", + category: "complexity", + severity: "warning", + status: "warn", + message: "At least one TypeScript function has high cyclomatic complexity.", + evidence: [`Max complexity: ${maxComplexity}`], + remediation: ["Split complex functions into smaller branches with clearer responsibilities."], + }), + ); + } + + if (maxFunctionLength >= 80) { + checks.push( + createCheck({ + id: "ts-function-length-high", + category: "readability", + severity: "warning", + status: "warn", + message: "At least one TypeScript function is long enough to hurt readability.", + evidence: [`Max function length: ${maxFunctionLength} lines`], + remediation: ["Break large functions into smaller helpers with single-purpose logic."], + }), + ); + } + + if (totalLongLines > 0) { + checks.push( + createCheck({ + id: "ts-long-lines", + category: "readability", + severity: "warning", + status: "warn", + message: "Some TypeScript lines exceed 120 characters.", + evidence: [`Long lines: ${totalLongLines}`], + remediation: ["Wrap long expressions and object literals to keep scanability high."], + }), + ); + } + + if (filePaths.length > 0 && testFileCount === 0) { + checks.push( + createCheck({ + id: "ts-tests-missing", + category: "best-practice", + severity: "warning", + status: "warn", + message: "TypeScript source files were found without matching test files.", + evidence: [`Source files: ${filePaths.length}`], + remediation: ["Add `.test.ts` or `.spec.ts` coverage for the main TypeScript logic."], + }), + ); + } + + artifacts.push( + createArtifact({ + id: "ts-per-file-analysis", + type: "analysis", + label: "TypeScript per-file analysis", + description: "Heuristic TypeScript quality and complexity breakdown by file.", + data: { + files: perFile, + }, + }), + ); + + return { checks, metrics, artifacts }; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/index.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c08f1a313c4fab0e4ec46bf995476d064b082448 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/index.js @@ -0,0 +1,5 @@ +export { analyzePath, explainBudget, recommendMeasures } from "./core/analyze.js"; +export { initializeBenchmark, runBenchmark } from "./core/benchmark.js"; +export { compareResults } from "./core/compare.js"; +export { buildWorkflowGuide } from "./core/workflow-guide.js"; +export { renderPayload } from "./renderers/index.js"; diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/files.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/files.js new file mode 100644 index 0000000000000000000000000000000000000000..d4264f55bcb2bd67448960ddcfd0b00e5abdc961 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/files.js @@ -0,0 +1,163 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const IGNORED_DIRS = new Set([ + ".git", + ".hg", + ".svn", + "node_modules", + "dist", + "build", + ".next", + ".turbo", + ".cache", + ".tmp", + ".venv", + "venv", + "__pycache__", + ".pytest_cache", + "coverage", +]); + +const TEXT_EXTENSIONS = new Set([ + ".cjs", + ".css", + ".csv", + ".html", + ".js", + ".json", + ".jsonc", + ".jsx", + ".md", + ".mjs", + ".py", + ".sh", + ".svg", + ".toml", + ".ts", + ".tsx", + ".txt", + ".xml", + ".yaml", + ".yml", +]); + +export async function pathExists(targetPath) { + try { + await fs.access(targetPath); + return true; + } catch { + return false; + } +} + +export async function isDirectory(targetPath) { + try { + const stats = await fs.stat(targetPath); + return stats.isDirectory(); + } catch { + return false; + } +} + +export async function isFile(targetPath) { + try { + const stats = await fs.stat(targetPath); + return stats.isFile(); + } catch { + return false; + } +} + +export async function readText(targetPath) { + return fs.readFile(targetPath, "utf8"); +} + +export async function readJson(targetPath) { + return JSON.parse(await readText(targetPath)); +} + +export async function writeText(targetPath, content) { + await fs.mkdir(path.dirname(targetPath), { recursive: true }); + await fs.writeFile(targetPath, content, "utf8"); +} + +export async function writeJson(targetPath, payload) { + await writeText(targetPath, `${JSON.stringify(payload, null, 2)}\n`); +} + +export function isProbablyTextFile(filePath) { + return TEXT_EXTENSIONS.has(path.extname(filePath).toLowerCase()); +} + +export function toPosixPath(filePath) { + return filePath.split(path.sep).join("/"); +} + +export function relativePath(fromPath, toPath) { + const value = path.relative(fromPath, toPath) || "."; + return toPosixPath(value); +} + +export function formatCommandPath(targetPath, options = {}) { + const absoluteTargetPath = path.resolve(targetPath); + const cwd = path.resolve(options.cwd || process.cwd()); + const homeDir = path.resolve(options.homeDir || os.homedir()); + + if (absoluteTargetPath === homeDir) { + return "~"; + } + + const relativeToHome = path.relative(homeDir, absoluteTargetPath); + if (relativeToHome && !relativeToHome.startsWith("..") && !path.isAbsolute(relativeToHome)) { + return `~/${toPosixPath(relativeToHome)}`; + } + + const relativeToCwd = path.relative(cwd, absoluteTargetPath) || "."; + if (!relativeToCwd.startsWith("..") && !path.isAbsolute(relativeToCwd)) { + return toPosixPath(relativeToCwd); + } + + return toPosixPath(absoluteTargetPath); +} + +export async function walkFiles(rootPath, options = {}) { + const files = []; + const { + excludeDirs = [], + skipTopLevel = ["fixtures", "__fixtures__"], + } = options; + const excluded = new Set([...IGNORED_DIRS, ...excludeDirs]); + + async function visit(currentPath, depth = 0) { + const entries = await fs.readdir(currentPath, { withFileTypes: true }); + for (const entry of entries) { + const entryPath = path.join(currentPath, entry.name); + if (entry.isDirectory()) { + if (excluded.has(entry.name)) { + continue; + } + if (depth === 0 && skipTopLevel.includes(entry.name)) { + continue; + } + await visit(entryPath, depth + 1); + continue; + } + if (entry.isFile()) { + files.push(entryPath); + } + } + } + + await visit(rootPath); + return files.sort(); +} + +export async function listImmediateDirectories(rootPath) { + const entries = await fs.readdir(rootPath, { withFileTypes: true }); + return entries + .filter((entry) => entry.isDirectory()) + .map((entry) => path.join(rootPath, entry.name)) + .sort(); +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/frontmatter.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/frontmatter.js new file mode 100644 index 0000000000000000000000000000000000000000..b3a4bc33bd0822107fb745cd2aa4c1fa503e14ab --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/frontmatter.js @@ -0,0 +1,261 @@ +function countIndent(line) { + return line.length - line.trimStart().length; +} + +function parseScalar(rawValue) { + const value = rawValue.trim(); + if (!value) { + return ""; + } + if ( + (value.startsWith("\"") && value.endsWith("\"")) || + (value.startsWith("'") && value.endsWith("'")) + ) { + return value.slice(1, -1); + } + if (value === "true") { + return true; + } + if (value === "false") { + return false; + } + if (value === "null") { + return null; + } + if (/^-?\d+(\.\d+)?$/.test(value)) { + return Number(value); + } + if (value.startsWith("[") && value.endsWith("]")) { + return value + .slice(1, -1) + .split(",") + .map((item) => item.trim()) + .filter(Boolean) + .map(parseScalar); + } + return value; +} + +function nextMeaningfulIndex(lines, startIndex) { + for (let index = startIndex; index < lines.length; index += 1) { + const trimmed = lines[index].trim(); + if (!trimmed || trimmed.startsWith("#")) { + continue; + } + return index; + } + return -1; +} + +function parseBlockScalarHeader(rawValue) { + const value = rawValue.trim(); + if (!value) { + return null; + } + if (!value.startsWith(">") && !value.startsWith("|")) { + return null; + } + return { + style: value[0], + }; +} + +function foldBlockScalarLines(lines) { + let result = ""; + for (let index = 0; index < lines.length; index += 1) { + const current = lines[index]; + const next = lines[index + 1]; + + result += current; + if (next === undefined) { + continue; + } + if (current === "" || next === "") { + result += "\n"; + } else { + result += " "; + } + } + return result; +} + +function parseBlockScalar(lines, startIndex, parentIndent, style) { + const blockLines = []; + let index = startIndex; + + while (index < lines.length) { + const line = lines[index]; + const trimmed = line.trim(); + const currentIndent = countIndent(line); + + if (trimmed && currentIndent <= parentIndent) { + break; + } + + blockLines.push(line); + index += 1; + } + + const contentIndent = blockLines.reduce((minimumIndent, line) => { + const trimmed = line.trim(); + if (!trimmed) { + return minimumIndent; + } + const currentIndent = countIndent(line); + if (currentIndent <= parentIndent) { + return minimumIndent; + } + return minimumIndent === null ? currentIndent : Math.min(minimumIndent, currentIndent); + }, null); + + const normalizedLines = blockLines.map((line) => { + if (!line.trim()) { + return ""; + } + if (contentIndent === null) { + return line.trim(); + } + return line.slice(contentIndent); + }); + + return { + value: style === "|" ? normalizedLines.join("\n") : foldBlockScalarLines(normalizedLines), + nextIndex: index, + }; +} + +function parseBlock(lines, startIndex, indent) { + const firstIndex = nextMeaningfulIndex(lines, startIndex); + if (firstIndex === -1) { + return { value: {}, nextIndex: lines.length }; + } + + const firstLine = lines[firstIndex]; + const isArray = firstLine.trim().startsWith("- "); + const container = isArray ? [] : {}; + let index = firstIndex; + + while (index < lines.length) { + const line = lines[index]; + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) { + index += 1; + continue; + } + + const currentIndent = countIndent(line); + if (currentIndent < indent) { + break; + } + if (currentIndent > indent) { + throw new Error(`Unexpected indentation at line ${index + 1}`); + } + + if (isArray) { + if (!trimmed.startsWith("- ")) { + break; + } + const payload = trimmed.slice(2).trim(); + index += 1; + if (!payload) { + const nested = parseBlock(lines, index, indent + 2); + container.push(nested.value); + index = nested.nextIndex; + } else { + container.push(parseScalar(payload)); + } + continue; + } + + const match = /^([A-Za-z0-9_-]+):(.*)$/.exec(trimmed); + if (!match) { + throw new Error(`Invalid key/value pair at line ${index + 1}`); + } + + const [, key, remainder] = match; + if (remainder.trim()) { + const blockScalar = parseBlockScalarHeader(remainder); + if (blockScalar) { + const parsed = parseBlockScalar(lines, index + 1, indent, blockScalar.style); + container[key] = parsed.value; + index = parsed.nextIndex; + continue; + } + + container[key] = parseScalar(remainder.trim()); + index += 1; + continue; + } + + const nestedIndex = nextMeaningfulIndex(lines, index + 1); + if (nestedIndex === -1 || countIndent(lines[nestedIndex]) <= indent) { + container[key] = ""; + index += 1; + continue; + } + + const nested = parseBlock(lines, index + 1, indent + 2); + container[key] = nested.value; + index = nested.nextIndex; + } + + return { value: container, nextIndex: index }; +} + +export function parseYamlDocument(yamlText) { + const normalized = yamlText.replace(/\r\n/g, "\n"); + return parseBlock(normalized.split("\n"), 0, 0).value; +} + +export function extractFrontmatter(markdown) { + const normalized = markdown.replace(/\r\n/g, "\n"); + const lines = normalized.split("\n"); + if (lines[0] !== "---") { + return { + frontmatterText: "", + body: normalized, + errors: ["No YAML frontmatter found."], + }; + } + + const closingIndex = lines.indexOf("---", 1); + if (closingIndex === -1) { + return { + frontmatterText: "", + body: normalized, + errors: ["Frontmatter opening delimiter is missing a closing delimiter."], + }; + } + + return { + frontmatterText: lines.slice(1, closingIndex).join("\n"), + body: lines.slice(closingIndex + 1).join("\n"), + errors: [], + }; +} + +export function parseFrontmatter(markdown) { + const extracted = extractFrontmatter(markdown); + if (extracted.errors.length > 0) { + return { + data: null, + body: extracted.body, + errors: extracted.errors, + }; + } + + try { + const parsed = parseYamlDocument(extracted.frontmatterText); + return { + data: parsed, + body: extracted.body, + errors: [], + }; + } catch (error) { + return { + data: null, + body: extracted.body, + errors: [error instanceof Error ? error.message : String(error)], + }; + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/tokens.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/tokens.js new file mode 100644 index 0000000000000000000000000000000000000000..604e29bba91fda09645cb285041bcb9237c246d7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/lib/tokens.js @@ -0,0 +1,10 @@ +export function estimateTokenCount(text) { + if (!text) { + return 0; + } + return Math.ceil(text.length / 4); +} + +export function sumTokenCounts(items) { + return items.reduce((total, item) => total + item.tokens, 0); +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/html.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/html.js new file mode 100644 index 0000000000000000000000000000000000000000..c44c41d4feccb0580c4234e747573442d1cef3d3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/html.js @@ -0,0 +1,331 @@ +function escapeHtml(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll("\"", """); +} + +function renderList(items) { + if (items.length === 0) { + return "

None.

"; + } + return `
    ${items.map((item) => `
  • ${escapeHtml(item)}
  • `).join("")}
`; +} + +function renderOptionalList(items, emptyLabel = "None.") { + return renderList(Array.isArray(items) && items.length > 0 ? items : [emptyLabel]); +} + +function renderChecks(checks) { + if (checks.length === 0) { + return "

No checks recorded.

"; + } + + return `
    ${checks + .map( + (check) => + `
  • ${escapeHtml(check.id)} [${escapeHtml(check.status)}] ${escapeHtml(check.message)}
  • `, + ) + .join("")}
`; +} + +function renderMetrics(metrics) { + if (metrics.length === 0) { + return "

No metrics recorded.

"; + } + + return `
    ${metrics + .map( + (metric) => + `
  • ${escapeHtml(metric.id)}: ${escapeHtml(metric.value)} ${escapeHtml(metric.unit)} (${escapeHtml(metric.band)})
  • `, + ) + .join("")}
`; +} + +function renderDeductions(summary) { + if (!summary.deductions || summary.deductions.length === 0) { + return "

No deductions were applied.

"; + } + + return `
    ${summary.deductions + .map( + (entry) => + `
  • -${escapeHtml(entry.penalty)} points ${escapeHtml(entry.id)} [${escapeHtml(entry.status)}/${escapeHtml(entry.severity)}] ${escapeHtml(entry.message)}
  • `, + ) + .join("")}
`; +} + +function renderCategoryDeductions(summary) { + if (!summary.categoryDeductions || summary.categoryDeductions.length === 0) { + return "

No category deductions recorded.

"; + } + + return `
    ${summary.categoryDeductions + .map( + (entry) => + `
  • ${escapeHtml(entry.category)}: -${escapeHtml(entry.totalPenalty)} points across ${escapeHtml(entry.checks)} check${entry.checks === 1 ? "" : "s"}
  • `, + ) + .join("")}
`; +} + +function renderObservedUsage(observedUsage) { + if (!observedUsage) { + return "

No observed usage supplied.

"; + } + + const items = [ + `Samples: ${observedUsage.sampleCount}`, + `Observed input avg: ${observedUsage.inputTokens.average}`, + `Observed output avg: ${observedUsage.outputTokens.average}`, + `Observed total avg: ${observedUsage.totalTokens.average}`, + ]; + + if (observedUsage.cachedTokens.total > 0) { + items.push(`Observed cached avg: ${observedUsage.cachedTokens.average}`); + } + + if (observedUsage.estimateComparison) { + items.push(`Estimated active tokens: ${observedUsage.estimateComparison.estimatedActiveTokens}`); + items.push(`Estimate delta: ${observedUsage.estimateComparison.deltaTokens}`); + items.push(`Estimate ratio: ${observedUsage.estimateComparison.deltaRatio} (${observedUsage.estimateComparison.band})`); + } + + return renderList(items); +} + +function renderMeasurementPlan(plan) { + if (!plan) { + return "

No measurement plan available.

"; + } + + return `

${escapeHtml(plan.summary)}

    ${plan.toolsets + .map( + (toolset) => + `
  • ${escapeHtml(toolset.label)} [${escapeHtml(toolset.priority)}] ${escapeHtml(toolset.goal)}
  • `, + ) + .join("")}
`; +} + +function renderWorkflowGuide(guide) { + if (!guide) { + return "

No chat workflow guidance available.

"; + } + + const startHere = guide.startHere || { + chatPrompt: guide.recommendedWorkflow.chatPrompt, + routingExplanation: guide.recommendedWorkflow.summary, + startCommand: guide.recommendedWorkflow.startCommand, + firstCommand: guide.recommendedWorkflow.firstCommand, + }; + + return [ + `

${escapeHtml(guide.beginnerSummary)}

`, + `

Start with this chat request: ${escapeHtml(`"${startHere.chatPrompt}"`)}

`, + `

Why this path: ${escapeHtml(startHere.routingExplanation)}

`, + `

Quick local entrypoint: ${escapeHtml(startHere.startCommand)}

`, + `

Plugin Eval will run first: ${escapeHtml(startHere.firstCommand)}

`, + "

Other chat requests you can use

", + renderList( + guide.entrypoints.map( + (entry) => `${entry.label}: say "${entry.chatPrompt}" then run ${entry.firstCommand}`, + ), + ), + ].join(""); +} + +function renderNextAction(nextAction) { + if (!nextAction) { + return "

No recommended next step.

"; + } + + return renderList([ + nextAction.label, + `Why: ${nextAction.why}`, + ...(nextAction.chatPrompt ? [`Chat request: "${nextAction.chatPrompt}"`] : []), + ...(nextAction.command ? [`Local command: ${nextAction.command}`] : []), + ]); +} + +export function renderHtml(result) { + if (result.kind === "workflow-guide") { + return ` + + + + Plugin Eval Start Here + + +
+

Plugin Eval Start Here: ${escapeHtml(result.target.name)}

+ ${renderWorkflowGuide(result)} +

Recommended Next Step

+ ${renderNextAction(result.nextAction)} +

Current Local State

+ ${renderList([ + `Benchmark config present: ${result.workflowStatus.hasBenchmarkConfig ? "yes" : "no"}`, + `Usage log present: ${result.workflowStatus.hasUsageLog ? "yes" : "no"}`, + ])} +

Full Local Sequence

+ ${renderList(result.startHere?.commands || [])} +
+ +`; + } + + if (result.kind === "measurement-plan") { + return ` + + + + Measurement Plan + + +
+

Measurement Plan: ${escapeHtml(result.target.name)}

+ ${renderMeasurementPlan(result)} +

Recommended Next Step

+ ${renderNextAction(result.nextAction)} +

Use From Codex Chat

+ ${renderWorkflowGuide(result.workflowGuide)} +
+ +`; + } + + if (result.kind === "benchmark-template-init") { + return ` + + + + Benchmark Template Ready + + +
+

Benchmark Template Ready: ${escapeHtml(result.target.name)}

+

Config: ${escapeHtml(result.configPath)}

+

Recommended Next Step

+ ${renderNextAction(result.nextAction)} +

Setup Questions To Ask First

+ ${renderOptionalList(result.setupQuestions, "No setup questions provided.")} + ${renderList(result.nextSteps || [])} +

Use From Codex Chat

+ ${renderWorkflowGuide(result.workflowGuide)} +
+ +`; + } + + if (result.kind === "benchmark-run") { + return ` + + + + Benchmark Run + + +
+

Benchmark Run: ${escapeHtml(result.target.name)}

+

Mode: ${escapeHtml(result.mode)}

+

Codex version: ${escapeHtml(result.codexVersion || "unknown")}

+

Model: ${escapeHtml(result.config?.model || "")}

+

Workspace source: ${escapeHtml(result.config?.workspaceSourcePath || "")}

+

Run directory: ${escapeHtml(result.runDirectory || "")}

+

Recommended Next Step

+ ${renderNextAction(result.nextAction)} +

Next Steps

+ ${renderList(result.nextSteps || [])} +

Use From Codex Chat

+ ${renderWorkflowGuide(result.workflowGuide)} +
+ +`; + } + + return ` + + + + Plugin Eval Report + + + +
+

Plugin Eval Report: ${escapeHtml(result.target.name)}

+
+
Score
${escapeHtml(result.summary.score)}/100
+
Grade
${escapeHtml(result.summary.grade)}
+
Risk
${escapeHtml(result.summary.riskLevel)}
+
Deductions
-${escapeHtml(result.summary.scoreBreakdown?.totalDeductions || 0)}
+
Total Tokens
${escapeHtml(result.budgets.total_tokens?.value || 0)}
+
+

Why It Matters

+ ${renderList(result.summary.whyBullets || [ + `Started at ${result.summary.scoreBreakdown?.startingScore || 100} and deducted ${result.summary.scoreBreakdown?.totalDeductions || 0} points.`, + `Final score: ${result.summary.scoreBreakdown?.finalScore || result.summary.score}/100.`, + ])} +

Fix First

+ ${renderList((result.summary.fixFirst || []).map((item) => `${item.message} Why: ${item.why}`))} +

Recommended Next Step

+ ${renderNextAction(result.nextAction)} +

Risk Assessment

+ ${renderList(result.summary.riskReasons || [])} +

Deductions

+ ${renderDeductions(result.summary)} +

Deductions By Category

+ ${renderCategoryDeductions(result.summary)} +

Recommendations

+ ${renderList(result.summary.topRecommendations)} +

Observed Usage

+ ${renderObservedUsage(result.observedUsage)} +

Measurement Plan

+ ${renderMeasurementPlan(result.measurementPlan)} +

Use From Codex Chat

+ ${renderWorkflowGuide(result.workflowGuide)} +

Checks

+ ${renderChecks(result.checks)} +

Metrics

+ ${renderMetrics(result.metrics)} +
+ +`; +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/index.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4da7f8ca0f8a2fe2485e68b144191d4b193dd34d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/index.js @@ -0,0 +1,15 @@ +import { renderHtml } from "./html.js"; +import { renderMarkdown } from "./markdown.js"; + +export function renderPayload(payload, format) { + if (format === "json") { + return `${JSON.stringify(payload, null, 2)}\n`; + } + if (format === "markdown" || format === "md") { + return `${renderMarkdown(payload)}\n`; + } + if (format === "html") { + return renderHtml(payload); + } + throw new Error(`Unsupported format: ${format}`); +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/markdown.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/markdown.js new file mode 100644 index 0000000000000000000000000000000000000000..d05284bc886ace0747fb333826a6ca2ab6510340 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/src/renderers/markdown.js @@ -0,0 +1,674 @@ +import { + applyEvaluationPresentation, + createBenchmarkRunNextAction, + createBenchmarkTemplateNextAction, + createBudgetNextAction, + createComparisonNextAction, + createEvaluationNextAction, + createMeasurementPlanNextAction, + createWorkflowGuideNextAction, +} from "../core/presentation.js"; +import { enrichSummary } from "../core/scoring.js"; + +function detailsBlock(summary, body) { + const content = Array.isArray(body) ? body.join("\n") : body; + if (!content || content.trim().length === 0) { + return ""; + } + + return [`
`, `${summary}`, "", content, `
`].join("\n"); +} + +function section(title, lines) { + return [`## ${title}`, ...lines].join("\n"); +} + +function renderNextAction(nextAction) { + if (!nextAction) { + return ["- No recommended next step."]; + } + + return [ + `- ${nextAction.label}`, + `- Why: ${nextAction.why}`, + ...(nextAction.chatPrompt ? [`- Chat request: "${nextAction.chatPrompt}"`] : []), + ...(nextAction.command ? [`- Local command: \`${nextAction.command}\``] : []), + ]; +} + +function renderBudgets(budgets) { + const lines = [ + `- trigger_cost_tokens: ${budgets.trigger_cost_tokens.value} (${budgets.trigger_cost_tokens.band})`, + `- invoke_cost_tokens: ${budgets.invoke_cost_tokens.value} (${budgets.invoke_cost_tokens.band})`, + `- deferred_cost_tokens: ${budgets.deferred_cost_tokens.value} (${budgets.deferred_cost_tokens.band})`, + ]; + + if (budgets.explicit_only_invoke_cost_tokens) { + lines.push( + `- explicit_only_invoke_cost_tokens: ${budgets.explicit_only_invoke_cost_tokens.value} (${budgets.explicit_only_invoke_cost_tokens.band}, unscored)`, + ); + } + + lines.push(`- total_tokens: ${budgets.total_tokens.value} (${budgets.total_tokens.band})`); + + if (budgets.invocation_policy?.explicit_only_skill_count > 0) { + lines.push( + `- invocation_policy: ${budgets.invocation_policy.implicit_skill_count} implicit skill(s), ${budgets.invocation_policy.explicit_only_skill_count} explicit-only skill(s)`, + ); + } + + return lines.join("\n"); +} + +function renderObservedUsage(observedUsage) { + if (!observedUsage) { + return "- No observed usage supplied."; + } + + const comparison = observedUsage.estimateComparison; + return [ + `- samples: ${observedUsage.sampleCount}`, + `- observed_input_tokens_avg: ${observedUsage.inputTokens.average}`, + `- observed_output_tokens_avg: ${observedUsage.outputTokens.average}`, + `- observed_total_tokens_avg: ${observedUsage.totalTokens.average}`, + ...(observedUsage.cachedTokens.total > 0 + ? [`- observed_cached_tokens_avg: ${observedUsage.cachedTokens.average}`] + : []), + ...(comparison + ? [ + `- estimated_active_tokens: ${comparison.estimatedActiveTokens}`, + `- estimate_vs_observed_input_delta: ${comparison.deltaTokens}`, + `- estimate_vs_observed_input_ratio: ${comparison.deltaRatio} (${comparison.band})`, + ] + : []), + ].join("\n"); +} + +function renderFindingList(findings, emptyLabel) { + if (!findings || findings.length === 0) { + return [`- ${emptyLabel}`]; + } + + return findings.map((finding) => { + const parts = [`- [${finding.status}/${finding.severity}] ${finding.message}`]; + if (finding.why) { + parts.push(`Why: ${finding.why}`); + } + if (finding.remediation?.length > 0) { + parts.push(`Fix: ${finding.remediation.join(" ")}`); + } + return parts.join(" "); + }); +} + +function renderChecks(checks) { + if (checks.length === 0) { + return "No checks recorded."; + } + + return checks + .map((check) => { + const parts = [`- [${check.status.toUpperCase()}] ${check.id}: ${check.message}`]; + if (check.why) { + parts.push(`Why: ${check.why}`); + } + if (check.evidence?.length > 0) { + parts.push(`Evidence: ${check.evidence.join(" ")}`); + } + if (check.remediation?.length > 0) { + parts.push(`Remediation: ${check.remediation.join(" ")}`); + } + return parts.join(" "); + }) + .join("\n"); +} + +function renderMetrics(metrics) { + if (metrics.length === 0) { + return "No metrics recorded."; + } + + return metrics + .map((metric) => `- ${metric.id}: ${metric.value} ${metric.unit} (${metric.band})`) + .join("\n"); +} + +function renderDeductions(summary) { + if (!summary.deductions || summary.deductions.length === 0) { + return "No deductions were applied."; + } + + return summary.deductions + .map( + (entry) => + `- -${entry.penalty} points: ${entry.id} [${entry.status}/${entry.severity}] ${entry.message}`, + ) + .join("\n"); +} + +function renderCategoryDeductions(summary) { + if (!summary.categoryDeductions || summary.categoryDeductions.length === 0) { + return "No category deductions recorded."; + } + + return summary.categoryDeductions + .map( + (entry) => + `- ${entry.category}: -${entry.totalPenalty} points across ${entry.checks} check${entry.checks === 1 ? "" : "s"}`, + ) + .join("\n"); +} + +function renderWorkflowGuide(guide) { + if (!guide) { + return "No chat workflow guidance available."; + } + + const startHere = guide.startHere || guide.recommendedWorkflow; + return [ + guide.beginnerSummary, + "", + `Start with this chat request: "${startHere.chatPrompt}"`, + `Why this path: ${startHere.routingExplanation || startHere.summary}`, + `Quick local entrypoint: ${startHere.startCommand}`, + `Plugin Eval will run first: ${startHere.firstCommand}`, + "", + "Other chat requests you can use:", + ...guide.entrypoints.map((entry) => + `- ${entry.label}: say "${entry.chatPrompt}" -> ${entry.firstCommand}`, + ), + ].join("\n"); +} + +function renderMeasurementPlan(plan) { + if (!plan) { + return "No measurement plan available."; + } + + return [ + plan.summary, + "", + ...plan.toolsets.map( + (toolset) => + `- ${toolset.label} [${toolset.priority}] ${toolset.goal} Signals: ${toolset.signals.join(", ")}. Evidence: ${toolset.evidenceSources.join(", ")}.`, + ), + ].join("\n"); +} + +function ensureEvaluationPayload(payload) { + const nextPayload = { + ...payload, + summary: enrichSummary(payload, payload.summary || {}), + }; + + if (!nextPayload.nextAction) { + nextPayload.nextAction = createEvaluationNextAction(nextPayload); + } + + return applyEvaluationPresentation(nextPayload); +} + +function ensureMeasurementPlanPayload(payload) { + return { + ...payload, + nextAction: payload.nextAction || createMeasurementPlanNextAction(payload), + }; +} + +function ensureBudgetPayload(payload) { + return { + ...payload, + nextAction: payload.nextAction || createBudgetNextAction(payload), + }; +} + +function ensureWorkflowPayload(payload) { + return { + ...payload, + nextAction: payload.nextAction || createWorkflowGuideNextAction(payload), + }; +} + +function ensureBenchmarkTemplatePayload(payload) { + return { + ...payload, + nextAction: payload.nextAction || createBenchmarkTemplateNextAction(payload), + }; +} + +function ensureBenchmarkRunPayload(payload) { + return { + ...payload, + nextAction: payload.nextAction || createBenchmarkRunNextAction(payload), + }; +} + +function ensureComparisonPayload(payload) { + return { + ...payload, + nextAction: payload.nextAction || createComparisonNextAction(payload), + }; +} + +function renderEvaluation(payload) { + const result = ensureEvaluationPayload(payload); + + return [ + `# Plugin Eval Report: ${result.target.name}`, + "", + section("At a Glance", [ + `- Score: ${result.summary.score}/100`, + `- Grade: ${result.summary.grade}`, + `- Risk: ${result.summary.riskLevel}`, + `- Checks: ${result.summary.checkCounts.fail} fail, ${result.summary.checkCounts.warn} warn, ${result.summary.checkCounts.info} info`, + `- Active budget: ${result.budgets.trigger_cost_tokens.value + result.budgets.invoke_cost_tokens.value} tokens (${result.budgets.invoke_cost_tokens.band})`, + `- Observed usage: ${result.observedUsage?.sampleCount ? `${result.observedUsage.sampleCount} sample${result.observedUsage.sampleCount === 1 ? "" : "s"}` : "not supplied"}`, + ]), + "", + section("Why It Matters", result.summary.whyBullets.map((item) => `- ${item}`)), + "", + section("Fix First", renderFindingList(result.summary.fixFirst, "No urgent fixes were identified.")), + "", + section("Recommended Next Step", renderNextAction(result.nextAction)), + "", + section("Details", [ + detailsBlock("Watch next", renderFindingList(result.summary.watchNext, "No secondary findings queued.")), + detailsBlock( + "Improvement brief", + [ + `- ${result.improvementBrief?.summary || "No improvement brief available."}`, + ...(result.improvementBrief?.goals?.length > 0 + ? result.improvementBrief.goals.map((item) => `- Goal: ${item}`) + : []), + ...(result.improvementBrief?.measurementGoals?.length > 0 + ? result.improvementBrief.measurementGoals.map((item) => `- Measure: ${item}`) + : []), + ...(result.improvementBrief?.suggestedPrompt + ? [`- Suggested prompt: ${result.improvementBrief.suggestedPrompt}`] + : []), + ].join("\n"), + ), + detailsBlock( + "Budgets and observed usage", + [renderBudgets(result.budgets), "", renderObservedUsage(result.observedUsage)].join("\n"), + ), + detailsBlock("Measurement plan", renderMeasurementPlan(result.measurementPlan)), + detailsBlock("Use From Codex Chat", renderWorkflowGuide(result.workflowGuide)), + detailsBlock("Checks", renderChecks(result.checks)), + detailsBlock("Metrics", renderMetrics(result.metrics)), + detailsBlock("Score details", [ + `- Starting score: ${result.summary.scoreBreakdown.startingScore}`, + `- Total deductions: -${result.summary.scoreBreakdown.totalDeductions}`, + `- Final score: ${result.summary.scoreBreakdown.finalScore}`, + ...(result.summary.riskReasons?.length > 0 + ? result.summary.riskReasons.map((item) => `- Risk: ${item}`) + : []), + "", + renderDeductions(result.summary), + "", + renderCategoryDeductions(result.summary), + ].join("\n")), + ].filter(Boolean)), + ].join("\n"); +} + +function renderWorkflowGuidePayload(payload) { + const guide = ensureWorkflowPayload(payload); + + return [ + `# Plugin Eval Start Here: ${guide.target.name}`, + "", + section("At a Glance", [ + `- Recommended path: ${guide.startHere.label}`, + `- Benchmark config present: ${guide.workflowStatus.hasBenchmarkConfig ? "yes" : "no"}`, + `- Usage log present: ${guide.workflowStatus.hasUsageLog ? "yes" : "no"}`, + `- Quick local entrypoint: \`${guide.startHere.startCommand}\``, + `- First local command: \`${guide.startHere.firstCommand}\``, + ]), + "", + section("Why It Matters", [ + `- ${guide.beginnerSummary}`, + `- ${guide.startHere.routingExplanation}`, + ]), + "", + section("Fix First", ["- Start with the recommended path before branching into secondary workflows."]), + "", + section("Recommended Next Step", renderNextAction(guide.nextAction)), + "", + section("Details", [ + detailsBlock( + "Full local sequence", + guide.startHere.commands.map((command) => `- ${command}`).join("\n"), + ), + detailsBlock( + "Other chat requests", + guide.entrypoints + .map((entry) => `- ${entry.label}: "${entry.chatPrompt}" -> ${entry.firstCommand}`) + .join("\n"), + ), + ]), + ].join("\n"); +} + +function renderBudgetExplanation(payload) { + const budgetPayload = ensureBudgetPayload(payload); + const budgets = budgetPayload.budgets; + const whyBullets = [ + `- Budget method: ${budgets.method}.`, + `- Trigger and invoke tokens matter most because they are closest to always-loaded or frequently-loaded context.`, + ...(budgets.invocation_policy?.explicit_only_skill_count > 0 + ? [ + `- Explicit-only skills are excluded from trigger and invoke budgets, but their standalone load ceiling is shown separately.`, + ] + : []), + ...(budgetPayload.baselineEvidence + ? [`- Baseline corpus: skills=${budgetPayload.baselineEvidence.skillSamples}, plugins=${budgetPayload.baselineEvidence.pluginSamples}.`] + : []), + ]; + const fixFirst = ["- Nothing to fix from this view alone; use the next step to validate or contextualize the estimate."]; + + if (["heavy", "excessive"].includes(budgets.trigger_cost_tokens.band) || ["heavy", "excessive"].includes(budgets.invoke_cost_tokens.band)) { + fixFirst.unshift("- The active budget is heavy enough that measured usage is worth collecting before tuning copy or structure."); + } + + return [ + `# Budget Explanation: ${budgetPayload.target.name}`, + "", + section("At a Glance", [ + ...renderBudgets(budgets).split("\n"), + ]), + "", + section("Why It Matters", whyBullets), + "", + section("Fix First", fixFirst), + "", + section("Recommended Next Step", renderNextAction(budgetPayload.nextAction)), + "", + section("Details", [ + detailsBlock( + "Trigger components", + budgets.trigger_cost_tokens.components.map((component) => `- ${component.label}: ${component.tokens} tokens`).join("\n"), + ), + detailsBlock( + "Invoke components", + budgets.invoke_cost_tokens.components.map((component) => `- ${component.label}: ${component.tokens} tokens`).join("\n"), + ), + detailsBlock( + "Deferred components", + budgets.deferred_cost_tokens.components.length > 0 + ? budgets.deferred_cost_tokens.components.map((component) => `- ${component.label}: ${component.tokens} tokens`).join("\n") + : "- None", + ), + budgets.explicit_only_invoke_cost_tokens + ? detailsBlock( + "Explicit-only skill components", + budgets.explicit_only_invoke_cost_tokens.components.length > 0 + ? budgets.explicit_only_invoke_cost_tokens.components.map((component) => `- ${component.label}: ${component.tokens} tokens`).join("\n") + : "- None", + ) + : "", + detailsBlock("Use From Codex Chat", renderWorkflowGuide(budgetPayload.workflowGuide)), + ]), + ].join("\n"); +} + +function renderMeasurementPlanPayload(payload) { + const plan = ensureMeasurementPlanPayload(payload); + const recommendedToolsets = plan.toolsets.filter((toolset) => plan.recommendedToolsets.includes(toolset.id)); + + return [ + `# Measurement Plan: ${plan.target.name}`, + "", + section("At a Glance", [ + `- Recommended toolsets: ${plan.recommendedToolsets.length > 0 ? plan.recommendedToolsets.join(", ") : "none"}`, + `- Toolset count: ${plan.toolsets.length}`, + `- Summary: ${plan.summary}`, + ]), + "", + section("Why It Matters", [ + `- ${plan.summary}`, + ...recommendedToolsets.map((toolset) => `- ${toolset.label}: ${toolset.goal}`), + ]), + "", + section( + "Fix First", + recommendedToolsets.length > 0 + ? recommendedToolsets.map((toolset) => `- ${toolset.label}: ${toolset.why}`) + : ["- No high-priority toolsets were selected."], + ), + "", + section("Recommended Next Step", renderNextAction(plan.nextAction)), + "", + section("Details", [ + detailsBlock( + "Recommended toolsets", + plan.recommendedToolsets.length > 0 + ? plan.recommendedToolsets.map((item) => `- ${item}`).join("\n") + : "- None", + ), + detailsBlock( + "All toolsets", + plan.toolsets + .map( + (toolset) => + `- ${toolset.label} [${toolset.priority}] ${toolset.goal} Signals: ${toolset.signals.join(", ")}. Evidence: ${toolset.evidenceSources.join(", ")}. Starter pack: ${toolset.starterPack.manifestName}.`, + ) + .join("\n"), + ), + detailsBlock("Use From Codex Chat", renderWorkflowGuide(plan.workflowGuide)), + ]), + ].join("\n"); +} + +function renderBenchmarkTemplateInit(payload) { + const benchmarkPayload = ensureBenchmarkTemplatePayload(payload); + + return [ + `# Benchmark Template Ready: ${benchmarkPayload.target.name}`, + "", + section("At a Glance", [ + `- Config: \`${benchmarkPayload.configPath}\``, + `- Scenarios: ${benchmarkPayload.scenarioCount}`, + ]), + "", + section("Why It Matters", benchmarkPayload.notes.map((item) => `- ${item}`)), + "", + section("Fix First", ["- Edit the benchmark config so the scenarios match your real workflow before you trust the run."]), + "", + section("Recommended Next Step", renderNextAction(benchmarkPayload.nextAction)), + "", + section("Details", [ + detailsBlock( + "Setup questions to ask first", + benchmarkPayload.setupQuestions?.length > 0 + ? benchmarkPayload.setupQuestions.map((item) => `- ${item}`).join("\n") + : "- No setup questions provided.", + ), + detailsBlock("Next steps", benchmarkPayload.nextSteps.map((item) => `- ${item}`).join("\n")), + detailsBlock("Use From Codex Chat", renderWorkflowGuide(benchmarkPayload.workflowGuide)), + ]), + ].join("\n"); +} + +function renderBenchmarkScenario(scenario, mode) { + const lines = [ + `- Purpose: ${scenario.purpose || "Not provided"}`, + ...(scenario.successChecklist?.length > 0 + ? scenario.successChecklist.map((item) => `- Success checklist: ${item}`) + : []), + ]; + + lines.push(`- Status: ${scenario.status}`); + lines.push(`- Duration: ${scenario.durationMs} ms`); + lines.push(`- Tool calls: ${scenario.telemetry?.toolCallCount || 0}`); + lines.push(`- Shell commands: ${scenario.telemetry?.shellCommandCount || 0}`); + lines.push(`- Failed shell commands: ${scenario.telemetry?.failedShellCommandCount || 0}`); + lines.push(`- Usage availability: ${scenario.usageAvailability || "unavailable"}`); + + if (scenario.usage) { + lines.push(`- Input tokens: ${scenario.usage.input_tokens || 0}`); + lines.push(`- Output tokens: ${scenario.usage.output_tokens || 0}`); + lines.push(`- Total tokens: ${scenario.usage.total_tokens || 0}`); + } + + if (scenario.workspaceSummary) { + lines.push(`- Added files: ${scenario.workspaceSummary.addedFileCount}`); + lines.push(`- Modified files: ${scenario.workspaceSummary.modifiedFileCount}`); + lines.push(`- Deleted files: ${scenario.workspaceSummary.deletedFileCount}`); + lines.push(`- Generated tests: ${scenario.workspaceSummary.generatedTestFileCount}`); + } + + if (scenario.finalMessagePreview) { + lines.push("", "```text", scenario.finalMessagePreview, "```"); + } + + if (scenario.workspaceChanges?.length > 0) { + lines.push("", ...scenario.workspaceChanges.map((entry) => `- ${entry.status}: ${entry.path}`)); + } + + if (scenario.verifierResults?.length > 0) { + lines.push("", ...scenario.verifierResults.map((result) => `- Verifier [${result.status}]: ${result.command}`)); + } + + if (scenario.generatedCode?.metrics?.length > 0) { + lines.push("", ...scenario.generatedCode.metrics.map((metric) => `- ${metric.id}: ${metric.value} ${metric.unit} (${metric.band})`)); + } + + if (scenario.generatedCode?.checks?.length > 0) { + lines.push("", ...scenario.generatedCode.checks.map((check) => `- [${check.status}] ${check.message}`)); + } + + return detailsBlock(scenario.title, lines.join("\n")); +} + +function renderBenchmarkRun(payload) { + const benchmarkPayload = ensureBenchmarkRunPayload(payload); + + return [ + `# Benchmark Run: ${benchmarkPayload.target.name}`, + "", + section("At a Glance", [ + `- Mode: ${benchmarkPayload.mode}`, + `- Codex version: ${benchmarkPayload.codexVersion}`, + `- Scenarios: ${benchmarkPayload.config.scenarioCount}`, + `- Model: ${benchmarkPayload.config.model}`, + `- Workspace source: \`${benchmarkPayload.config.workspaceSourcePath}\``, + `- Setup mode: ${benchmarkPayload.config.workspaceSetupMode}`, + `- Preserve policy: ${benchmarkPayload.config.workspacePreserve}`, + ...(benchmarkPayload.usageLogPath ? [`- Usage log: \`${benchmarkPayload.usageLogPath}\``] : []), + `- Run directory: \`${benchmarkPayload.runDirectory}\``, + `- Usage availability: ${benchmarkPayload.summary.usageAvailability}`, + `- Average input tokens: ${benchmarkPayload.summary.averageInputTokens}`, + `- Average output tokens: ${benchmarkPayload.summary.averageOutputTokens}`, + `- Average total tokens: ${benchmarkPayload.summary.averageTotalTokens}`, + `- Tool calls: ${benchmarkPayload.summary.toolCallCount}`, + `- Shell commands: ${benchmarkPayload.summary.shellCommandCount}`, + `- Failed shell commands: ${benchmarkPayload.summary.failedShellCommands}`, + `- Generated files: ${benchmarkPayload.summary.generatedFileCount}`, + `- Generated tests: ${benchmarkPayload.summary.generatedTestFileCount}`, + ]), + "", + section("Why It Matters", [ + "- Benchmarking now runs real `codex exec` sessions in isolated workspaces instead of simulating the skill or plugin through a single API request.", + `- Completed scenarios: ${benchmarkPayload.summary.completedScenarios}/${benchmarkPayload.summary.scenarioCount}`, + `- Usage samples collected: ${benchmarkPayload.summary.sampleCount}`, + ]), + "", + section( + "Fix First", + benchmarkPayload.summary.failedScenarios > 0 + ? ["- At least one scenario failed. Inspect the scenario logs and any preserved workspace before trusting the benchmark."] + : benchmarkPayload.summary.usageAvailability === "unavailable" + ? ["- No usage telemetry was emitted, so treat workspace outcomes and verifier results as the primary benchmark signal."] + : ["- Re-run analysis with the usage log before you start optimizing the skill or plugin."], + ), + "", + section("Recommended Next Step", renderNextAction(benchmarkPayload.nextAction)), + "", + section("Details", [ + detailsBlock( + "Scenarios", + benchmarkPayload.scenarios + .map((scenario) => renderBenchmarkScenario(scenario, benchmarkPayload.mode)) + .join("\n\n"), + ), + detailsBlock("Workflow follow-up", benchmarkPayload.nextSteps.map((item) => `- ${item}`).join("\n")), + detailsBlock("Use From Codex Chat", renderWorkflowGuide(benchmarkPayload.workflowGuide)), + ]), + ].join("\n"); +} + +function renderComparison(payload) { + const diff = ensureComparisonPayload(payload); + const whyBullets = [ + `- Score delta: ${diff.scoreDelta >= 0 ? "+" : ""}${diff.scoreDelta}.`, + `- Grade moved from ${diff.gradeBefore} to ${diff.gradeAfter}.`, + `- Risk moved from ${diff.riskBefore} to ${diff.riskAfter}.`, + ]; + + if (diff.newFailures.length > 0) { + whyBullets.push(`- ${diff.newFailures.length} new failure${diff.newFailures.length === 1 ? "" : "s"} were introduced.`); + } + if (diff.resolvedFailures.length > 0) { + whyBullets.push(`- ${diff.resolvedFailures.length} failure${diff.resolvedFailures.length === 1 ? "" : "s"} were resolved.`); + } + + return [ + `# Plugin Eval Comparison: ${diff.target.name}`, + "", + section("At a Glance", [ + `- Score delta: ${diff.scoreDelta >= 0 ? "+" : ""}${diff.scoreDelta}`, + `- Grade: ${diff.gradeBefore} -> ${diff.gradeAfter}`, + `- Risk: ${diff.riskBefore} -> ${diff.riskAfter}`, + `- Budget delta (trigger/invoke/deferred): ${diff.budgetDelta.trigger_cost_tokens >= 0 ? "+" : ""}${diff.budgetDelta.trigger_cost_tokens} / ${diff.budgetDelta.invoke_cost_tokens >= 0 ? "+" : ""}${diff.budgetDelta.invoke_cost_tokens} / ${diff.budgetDelta.deferred_cost_tokens >= 0 ? "+" : ""}${diff.budgetDelta.deferred_cost_tokens}`, + ]), + "", + section("Why It Matters", whyBullets), + "", + section( + "Fix First", + diff.newFailures.length > 0 + ? diff.newFailures.map((item) => `- New failure: ${item}`) + : ["- No new failures were introduced."], + ), + "", + section("Recommended Next Step", renderNextAction(diff.nextAction)), + "", + section("Details", [ + detailsBlock( + "Resolved failures", + diff.resolvedFailures.length > 0 + ? diff.resolvedFailures.map((item) => `- ${item}`).join("\n") + : "- No resolved failures.", + ), + detailsBlock( + "New failures", + diff.newFailures.length > 0 + ? diff.newFailures.map((item) => `- ${item}`).join("\n") + : "- No new failures.", + ), + ]), + ].join("\n"); +} + +export function renderMarkdown(payload) { + if (payload.kind === "comparison") { + return renderComparison(payload); + } + if (payload.kind === "workflow-guide") { + return renderWorkflowGuidePayload(payload); + } + if (payload.kind === "budget-explanation") { + return renderBudgetExplanation(payload); + } + if (payload.kind === "measurement-plan") { + return renderMeasurementPlanPayload(payload); + } + if (payload.kind === "benchmark-template-init") { + return renderBenchmarkTemplateInit(payload); + } + if (payload.kind === "benchmark-run") { + return renderBenchmarkRun(payload); + } + return renderEvaluation(payload); +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/tests/plugin-eval.test.js b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/tests/plugin-eval.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4ada4f6d31ffa8eb0204337341d3471050c38ba1 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/plugin-eval/tests/plugin-eval.test.js @@ -0,0 +1,841 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { execFile } from "node:child_process"; +import test from "node:test"; +import { promisify } from "node:util"; + +import { analyzePath, explainBudget } from "../src/core/analyze.js"; +import { initializeBenchmark, runBenchmark } from "../src/core/benchmark.js"; +import { provisionBenchmarkWorkspace } from "../src/core/benchmark-workspace.js"; +import { parseCodexJsonStream, summarizeCodexEvents } from "../src/core/benchmark-events.js"; +import { compareResults } from "../src/core/compare.js"; +import { buildWorkflowGuide } from "../src/core/workflow-guide.js"; +import { parseFrontmatter } from "../src/lib/frontmatter.js"; +import { formatCommandPath } from "../src/lib/files.js"; +import { renderPayload } from "../src/renderers/index.js"; + +const execFileAsync = promisify(execFile); +const repoRoot = path.resolve(path.dirname(new URL(import.meta.url).pathname), ".."); +const fixturesRoot = path.join(repoRoot, "fixtures"); +const cliPath = path.join(repoRoot, "scripts", "plugin-eval.js"); +const nodeBin = process.execPath; + +async function makeTempDir(prefix) { + return fs.mkdtemp(path.join(os.tmpdir(), `${prefix}-`)); +} + +async function writeSkillFixture(rootPath, { description, bodyLines }) { + await fs.mkdir(rootPath, { recursive: true }); + const body = Array.from({ length: bodyLines }, (_, index) => `Line ${index + 1}`).join("\n"); + await fs.writeFile( + path.join(rootPath, "SKILL.md"), + `---\nname: temp-skill\ndescription: ${description}\n---\n\n# Temp Skill\n\n${body}\n`, + "utf8", + ); +} + +async function writeBlockScalarSkillFixture(rootPath, { style = ">", descriptionLines, bodyLines = 3 }) { + await fs.mkdir(rootPath, { recursive: true }); + const description = descriptionLines.map((line) => ` ${line}`).join("\n"); + const body = Array.from({ length: bodyLines }, (_, index) => `Line ${index + 1}`).join("\n"); + await fs.writeFile( + path.join(rootPath, "SKILL.md"), + `---\nname: temp-skill\ndescription: ${style}\n${description}\n---\n\n# Temp Skill\n\n${body}\n`, + "utf8", + ); +} + +async function writePluginBudgetFixture(rootPath) { + await fs.mkdir(path.join(rootPath, ".codex-plugin"), { recursive: true }); + await fs.writeFile( + path.join(rootPath, ".codex-plugin", "plugin.json"), + JSON.stringify( + { + name: "policy-aware-plugin", + version: "0.1.0", + description: "Evaluate policy-aware plugin budgets.", + author: { + name: "Plugin Eval", + }, + homepage: "https://example.com/", + license: "MIT", + keywords: ["fixture"], + skills: "./skills/", + interface: { + displayName: "Policy Aware Plugin", + shortDescription: "Fixture for policy-aware budgets", + longDescription: "Fixture for policy-aware budget tests.", + developerName: "Plugin Eval", + category: "Developer Tools", + capabilities: ["Read"], + defaultPrompt: ["Route the request first."], + brandColor: "#0B7285", + composerIcon: "./assets/icon.svg", + logo: "./assets/logo.svg", + screenshots: [], + }, + }, + null, + 2, + ), + "utf8", + ); + + await writeSkillFixture(path.join(rootPath, "skills", "router"), { + description: "Route fixture requests.", + bodyLines: 3, + }); + await fs.mkdir(path.join(rootPath, "skills", "router", "agents"), { recursive: true }); + await fs.writeFile( + path.join(rootPath, "skills", "router", "agents", "openai.yaml"), + "policy:\n allow_implicit_invocation: true\n", + "utf8", + ); + + await writeSkillFixture(path.join(rootPath, "skills", "specialist"), { + description: `Specialist fixture ${"x".repeat(500)}`, + bodyLines: 200, + }); + await fs.mkdir(path.join(rootPath, "skills", "specialist", "agents"), { recursive: true }); + await fs.writeFile( + path.join(rootPath, "skills", "specialist", "agents", "openai.yaml"), + "policy:\n allow_implicit_invocation: false\n", + "utf8", + ); +} + +async function copyDirectory(source, destination) { + await fs.cp(source, destination, { recursive: true }); +} + +async function createFakeCodexExecutable(rootPath) { + const binDir = path.join(rootPath, "bin"); + const executablePath = path.join(binDir, "codex"); + await fs.mkdir(binDir, { recursive: true }); + await fs.writeFile( + executablePath, + `#!/bin/sh +if [ "$1" = "--version" ]; then + echo "codex-cli fake-test" + exit 0 +fi + +if [ "$1" = "exec" ]; then + final="" + workspace="" + while [ "$#" -gt 0 ]; do + if [ "$1" = "--output-last-message" ]; then + shift + final="$1" + elif [ "$1" = "--cd" ]; then + shift + workspace="$1" + fi + shift + done + + mkdir -p "$(dirname "$final")" + printf "Implemented benchmark fixture.\\n" > "$final" + printf 'export const generated = 1;\\n' > "$workspace/generated.ts" + printf 'import { generated } from "./generated";\\nexport default generated;\\n' > "$workspace/generated.test.ts" + printf '{"type":"thread.started","thread_id":"thread-test"}\\n' + printf '{"type":"tool.called","tool_name":"functions.exec_command"}\\n' + printf '{"type":"shell.command","command":"npm test"}\\n' + printf '{"type":"turn.completed","usage":{"input_tokens":120,"output_tokens":45,"total_tokens":165}}\\n' + exit 0 +fi + +echo "unsupported invocation" >&2 +exit 1 +`, + "utf8", + ); + await fs.chmod(executablePath, 0o755); + return executablePath; +} + +test("analyze minimal skill and render markdown/html", async () => { + const skillPath = path.join(fixturesRoot, "minimal-skill"); + const result = await analyzePath(skillPath); + + assert.equal(result.target.kind, "skill"); + assert.equal(result.budgets.method, "estimated-static"); + assert.ok(result.summary.score > 0); + assert.ok(result.metrics.some((metric) => metric.id === "trigger_cost_tokens")); + assert.ok(Array.isArray(result.summary.whyBullets)); + assert.ok(Array.isArray(result.summary.fixFirst)); + assert.ok(result.nextAction); + + const markdown = renderPayload(result, "markdown"); + const html = renderPayload(result, "html"); + + assert.match(markdown, /Plugin Eval Report: minimal-skill/); + assert.match(markdown, /At a Glance/); + assert.match(markdown, /Why It Matters/); + assert.match(markdown, /Fix First/); + assert.match(markdown, /Recommended Next Step/); + assert.match(markdown, /
/); + assert.match(html, //i); + assert.match(html, /Risk Assessment/); + assert.match(html, /Use From Codex Chat/); + assert.match(html, /Quick local entrypoint/); +}); + +test("flags oversized descriptions and bloated SKILL.md files", async () => { + const tempDir = await makeTempDir("plugin-eval-skill"); + await writeSkillFixture(tempDir, { + description: `Verbose description ${"x".repeat(1300)}`, + bodyLines: 650, + }); + + const result = await analyzePath(tempDir); + const ids = new Set(result.checks.map((check) => check.id)); + + assert.ok(ids.has("description-too-long")); + assert.ok(ids.has("skill-large") || ids.has("skill-too-large")); + assert.notEqual(result.budgets.trigger_cost_tokens.band, "good"); +}); + +test("parses folded and literal YAML block scalars in frontmatter", async () => { + const folded = parseFrontmatter(`---\nname: temp-skill\ndescription: >\n Use when the task needs\n a folded block scalar.\n---\n`); + const literal = parseFrontmatter(`---\nname: temp-skill\ndescription: |\n First line.\n Second line.\n---\n`); + + assert.deepEqual(folded.errors, []); + assert.equal(folded.data.description, "Use when the task needs a folded block scalar."); + + assert.deepEqual(literal.errors, []); + assert.equal(literal.data.description, "First line.\nSecond line."); +}); + +test("analyze accepts skills with block-scalar descriptions", async () => { + const tempDir = await makeTempDir("plugin-eval-block-scalar"); + await writeBlockScalarSkillFixture(tempDir, { + style: ">", + descriptionLines: [ + "Use when the task needs", + "a folded block scalar description.", + ], + }); + + const result = await analyzePath(tempDir); + const ids = new Set(result.checks.map((check) => check.id)); + + assert.ok(!ids.has("frontmatter-invalid")); + assert.ok(!ids.has("name-missing")); + assert.ok(!ids.has("description-missing")); + assert.ok(result.summary.score > 0); +}); + +test("explicit-only skill policy removes trigger budget", async () => { + const tempDir = await makeTempDir("plugin-eval-explicit-skill"); + await writeSkillFixture(tempDir, { + description: `Explicit-only description ${"x".repeat(500)}`, + bodyLines: 10, + }); + await fs.mkdir(path.join(tempDir, "agents"), { recursive: true }); + await fs.writeFile( + path.join(tempDir, "agents", "openai.yaml"), + "policy:\n allow_implicit_invocation: false\n", + "utf8", + ); + + const result = await analyzePath(tempDir); + + assert.equal(result.budgets.method, "estimated-static-policy-aware"); + assert.equal(result.budgets.invocation_policy.allow_implicit_invocation, false); + assert.equal(result.budgets.trigger_cost_tokens.value, 0); + assert.ok(result.budgets.invoke_cost_tokens.value > 0); + assert.ok(!result.checks.some((check) => check.id === "trigger_cost_tokens-budget-high")); +}); + +test("plugin budget excludes explicit-only specialist skills from implicit active budget", async () => { + const tempDir = await makeTempDir("plugin-eval-policy-plugin"); + await writePluginBudgetFixture(tempDir); + + const result = await analyzePath(tempDir); + const triggerLabels = result.budgets.trigger_cost_tokens.components.map((component) => component.label); + const invokeLabels = result.budgets.invoke_cost_tokens.components.map((component) => component.label); + const explicitLabels = result.budgets.explicit_only_invoke_cost_tokens.components.map((component) => component.label); + + assert.equal(result.target.kind, "plugin"); + assert.equal(result.budgets.method, "estimated-static-policy-aware"); + assert.equal(result.budgets.invocation_policy.implicit_skill_count, 1); + assert.equal(result.budgets.invocation_policy.explicit_only_skill_count, 1); + assert.ok(triggerLabels.includes("router-description")); + assert.ok(!triggerLabels.includes("specialist-description")); + assert.ok(invokeLabels.includes("router-skill-file")); + assert.ok(!invokeLabels.includes("specialist-skill-file")); + assert.deepEqual(explicitLabels, ["specialist-skill-file"]); + assert.ok(result.metrics.some((metric) => metric.id === "explicit_only_invoke_cost_tokens")); +}); + +test("finds broken plugin manifests, missing paths, and prompt issues", async () => { + const tempDir = await makeTempDir("plugin-eval-plugin"); + await fs.mkdir(path.join(tempDir, ".codex-plugin"), { recursive: true }); + await fs.writeFile( + path.join(tempDir, ".codex-plugin", "plugin.json"), + JSON.stringify( + { + name: "bad-plugin", + version: "0.1.0", + description: "Broken plugin for testing.", + author: { + name: "Plugin Eval", + email: "support@example.com", + url: "https://example.com/", + }, + homepage: "https://example.com/", + repository: "https://example.com/repo", + license: "MIT", + keywords: ["fixture"], + skills: "./missing-skills/", + interface: { + displayName: "Bad Plugin", + shortDescription: "Broken fixture", + longDescription: "Broken fixture for plugin-eval tests.", + developerName: "Plugin Eval", + category: "Developer Tools", + capabilities: ["Interactive", "Write"], + websiteURL: "https://example.com/", + privacyPolicyURL: "https://example.com/privacy", + termsOfServiceURL: "https://example.com/terms", + defaultPrompt: [ + "Prompt one that is fine.", + "Prompt two that is also fine.", + "Prompt three that is also fine.", + "Prompt four is ignored and should be flagged because there are too many starter prompts in this broken fixture, and this sentence is intentionally extended well past the interface length budget so the evaluator can deterministically flag it as too long." + ], + brandColor: "teal", + composerIcon: "./assets/missing.svg", + logo: "./assets/missing.svg", + screenshots: [] + } + }, + null, + 2, + ), + "utf8", + ); + + const result = await analyzePath(tempDir); + const ids = new Set(result.checks.map((check) => check.id)); + + assert.ok(ids.has("skills-path-missing")); + assert.ok(ids.has("default-prompt-too-many")); + assert.ok(ids.has("default-prompt-too-long")); + assert.ok(ids.has("brand-color-invalid")); + assert.ok(ids.has("plugin-skills-missing")); +}); + +test("collects deterministic TypeScript and Python metrics", async () => { + const samplePath = path.join(fixturesRoot, "ts-python-sample"); + const result = await analyzePath(samplePath); + + const metric = (id) => result.metrics.find((item) => item.id === id)?.value; + + assert.equal(metric("ts_file_count"), 2); + assert.equal(metric("py_file_count"), 2); + assert.equal(metric("ts_test_file_count"), 1); + assert.equal(metric("py_test_file_count"), 1); + assert.ok(metric("ts_max_cyclomatic_complexity") >= 4); + assert.ok(metric("py_max_cyclomatic_complexity") >= 4); +}); + +test("ingests lcov, coverage.xml, and coverage-final.json artifacts", async () => { + const samplePath = path.join(fixturesRoot, "coverage-samples"); + const result = await analyzePath(samplePath); + const coveragePercent = result.metrics.find((metric) => metric.id === "coverage_percent")?.value; + + assert.equal(coveragePercent, 82); + assert.equal(result.metrics.find((metric) => metric.id === "coverage_artifact_count")?.value, 3); +}); + +test("merges custom metric pack output without changing the core summary", async () => { + const skillPath = path.join(fixturesRoot, "minimal-skill"); + const result = await analyzePath(skillPath, { + metricPackManifests: [path.join(fixturesRoot, "metric-pack", "manifest.json")], + }); + + assert.equal(result.extensions.length, 1); + assert.equal(result.extensions[0].metrics[0].id, "custom-pack-score"); + assert.ok(result.summary.score > 0); +}); + +test("ingests observed usage files and compares estimates against real sessions", async () => { + const skillPath = path.join(fixturesRoot, "minimal-skill"); + const usagePath = path.join(fixturesRoot, "observed-usage", "responses.jsonl"); + const result = await analyzePath(skillPath, { + observedUsagePaths: [usagePath], + }); + + assert.equal(result.observedUsage.sampleCount, 3); + assert.equal(result.metrics.find((metric) => metric.id === "observed_usage_sample_count")?.value, 3); + assert.ok(result.metrics.some((metric) => metric.id === "estimate_vs_observed_input_ratio")); + assert.ok(result.measurementPlan.toolsets.length >= 5); +}); + +test("init-benchmark writes a beginner-friendly starter config", async () => { + const sourcePath = path.join(fixturesRoot, "minimal-skill"); + const tempDir = await makeTempDir("plugin-eval-benchmark-init"); + const skillPath = path.join(tempDir, "minimal-skill"); + await copyDirectory(sourcePath, skillPath); + + const payload = await initializeBenchmark(skillPath); + const config = JSON.parse(await fs.readFile(path.join(skillPath, ".plugin-eval", "benchmark.json"), "utf8")); + + assert.equal(payload.kind, "benchmark-template-init"); + assert.equal(config.kind, "plugin-eval-benchmark"); + assert.equal(config.schemaVersion, 2); + assert.equal(config.runner.type, "codex-cli"); + assert.equal(config.workspace.setupMode, "copy"); + assert.equal(config.scenarios.length, 3); + assert.ok(Array.isArray(config.setupQuestions)); + assert.ok(config.setupQuestions.length >= 3); + assert.match(config.notes[0], /workspace\.sourcePath/i); + assert.ok(Array.isArray(payload.setupQuestions)); + assert.ok(payload.setupQuestions.some((item) => /must-pass/i.test(item))); + assert.ok(payload.workflowGuide); +}); + +test("benchmark rejects the removed dry-run mode", async () => { + const sourcePath = path.join(fixturesRoot, "minimal-skill"); + const tempDir = await makeTempDir("plugin-eval-benchmark-dry-run"); + const skillPath = path.join(tempDir, "minimal-skill"); + await copyDirectory(sourcePath, skillPath); + + await initializeBenchmark(skillPath); + await assert.rejects( + () => + runBenchmark(skillPath, { + configPath: path.join(skillPath, ".plugin-eval", "benchmark.json"), + dryRun: true, + }), + /no longer supports --dry-run/i, + ); +}); + +test("parses codex json event streams and extracts usage plus shell activity", async () => { + const stream = [ + JSON.stringify({ type: "thread.started", thread_id: "thread-123" }), + JSON.stringify({ type: "tool.called", tool_name: "functions.exec_command" }), + JSON.stringify({ type: "shell.command", command: "npm test" }), + "warning text that should be ignored", + JSON.stringify({ type: "turn.completed", usage: { input_tokens: 101, output_tokens: 44, total_tokens: 145 } }), + ].join("\n"); + + const parsed = parseCodexJsonStream(stream); + const summary = summarizeCodexEvents(parsed.events); + + assert.equal(parsed.events.length, 4); + assert.equal(parsed.ignoredLines.length, 1); + assert.equal(summary.threadId, "thread-123"); + assert.equal(summary.toolCallCount, 1); + assert.equal(summary.shellCommandCount, 1); + assert.equal(summary.failedShellCommandCount, 0); + assert.equal(summary.usage.input_tokens, 101); + assert.equal(summary.finalStatus, "completed"); +}); + +test("formats command paths with home shorthand for user-facing commands", () => { + const formatted = formatCommandPath(path.join(os.homedir(), ".codex", "skills", "game-dev"), { + cwd: repoRoot, + }); + + assert.equal(formatted, "~/.codex/skills/game-dev"); +}); + +test("workflow guide next action uses the first actionable local command", async () => { + const sourcePath = path.join(fixturesRoot, "minimal-skill"); + const tempDir = await makeTempDir("plugin-eval-workflow-guide"); + const skillPath = path.join(tempDir, "minimal-skill"); + await copyDirectory(sourcePath, skillPath); + + const guide = await buildWorkflowGuide(skillPath, { + request: "Measure the real token usage of this skill.", + }); + + assert.equal(guide.nextAction.command, `plugin-eval init-benchmark ${formatCommandPath(skillPath)}`); +}); + +test("benchmark run writes usage logs and generated-code analysis from a codex-cli run", async () => { + const sourcePath = path.join(fixturesRoot, "minimal-skill"); + const tempDir = await makeTempDir("plugin-eval-benchmark-live"); + const skillPath = path.join(tempDir, "minimal-skill"); + await copyDirectory(sourcePath, skillPath); + + await initializeBenchmark(skillPath); + const payload = await runBenchmark(skillPath, { + configPath: path.join(skillPath, ".plugin-eval", "benchmark.json"), + processRunner: async ({ kind, args }) => { + if (kind === "codex-version") { + return { + code: 0, + signal: null, + durationMs: 1, + stdoutText: "codex-cli fake-test\n", + stderrText: "", + }; + } + + if (kind === "codex") { + const finalMessagePath = args[args.indexOf("--output-last-message") + 1]; + const workspacePath = args[args.indexOf("--cd") + 1]; + await fs.writeFile(finalMessagePath, "Benchmark completed.\n", "utf8"); + await fs.writeFile(path.join(workspacePath, "generated.ts"), "export const value = 1;\n", "utf8"); + await fs.writeFile(path.join(workspacePath, "generated.test.ts"), "import { value } from './generated';\nconsole.log(value);\n", "utf8"); + return { + code: 0, + signal: null, + durationMs: 10, + stdoutText: [ + JSON.stringify({ type: "thread.started", thread_id: "thread-test" }), + JSON.stringify({ type: "tool.called", tool_name: "functions.exec_command" }), + JSON.stringify({ type: "shell.command", command: "npm test" }), + JSON.stringify({ type: "turn.completed", usage: { input_tokens: 150, output_tokens: 70, total_tokens: 220 } }), + ].join("\n"), + stderrText: "", + }; + } + + return { + code: 0, + signal: null, + durationMs: 5, + stdoutText: "", + stderrText: "", + }; + }, + }); + + assert.equal(payload.mode, "codex-cli"); + assert.equal(payload.summary.sampleCount, 3); + assert.equal(payload.summary.generatedFileCount, 6); + assert.equal(payload.summary.generatedTestFileCount, 3); + assert.equal(payload.scenarios[0].generatedCode.metrics.find((metric) => metric.id === "ts_file_count")?.value, 2); + + const result = await analyzePath(skillPath, { + observedUsagePaths: [payload.usageLogPath], + }); + assert.equal(result.observedUsage.sampleCount, 3); +}); + +test("benchmark run uses config-based approval policy syntax for codex exec", async () => { + const sourcePath = path.join(fixturesRoot, "minimal-skill"); + const tempDir = await makeTempDir("plugin-eval-benchmark-args"); + const skillPath = path.join(tempDir, "minimal-skill"); + await copyDirectory(sourcePath, skillPath); + + await initializeBenchmark(skillPath); + const seenArgs = []; + + await runBenchmark(skillPath, { + configPath: path.join(skillPath, ".plugin-eval", "benchmark.json"), + processRunner: async ({ kind, args }) => { + if (kind === "codex-version") { + return { + code: 0, + signal: null, + durationMs: 1, + stdoutText: "codex-cli fake-test\n", + stderrText: "", + }; + } + + if (kind === "codex") { + seenArgs.push(args); + const finalMessagePath = args[args.indexOf("--output-last-message") + 1]; + const workspacePath = args[args.indexOf("--cd") + 1]; + await fs.writeFile(finalMessagePath, "Benchmark completed.\n", "utf8"); + await fs.writeFile(path.join(workspacePath, "generated.ts"), "export const value = 1;\n", "utf8"); + return { + code: 0, + signal: null, + durationMs: 10, + stdoutText: [ + JSON.stringify({ type: "thread.started", thread_id: "thread-test" }), + JSON.stringify({ type: "turn.completed", usage: { input_tokens: 150, output_tokens: 70, total_tokens: 220 } }), + ].join("\n"), + stderrText: "", + }; + } + + return { + code: 0, + signal: null, + durationMs: 5, + stdoutText: "", + stderrText: "", + }; + }, + }); + + assert.equal(seenArgs.length, 3); + assert.ok(seenArgs.every((args) => !args.includes("-a"))); + assert.ok(seenArgs.every((args) => args.includes("-c"))); + assert.ok(seenArgs.every((args) => args.includes('approval_policy="never"'))); +}); + +test("provisionBenchmarkWorkspace seeds auth and config into the isolated codex home", async () => { + const sourcePath = path.join(fixturesRoot, "minimal-skill"); + const tempDir = await makeTempDir("plugin-eval-benchmark-home"); + const skillPath = path.join(tempDir, "minimal-skill"); + const codexHomeSource = path.join(tempDir, "codex-home-source"); + await copyDirectory(sourcePath, skillPath); + await fs.mkdir(codexHomeSource, { recursive: true }); + await fs.writeFile(path.join(codexHomeSource, "auth.json"), '{"token":"test"}\n', "utf8"); + await fs.writeFile(path.join(codexHomeSource, "config.toml"), 'model = "gpt-5.4"\n', "utf8"); + + const previousSource = process.env.PLUGIN_EVAL_CODEX_HOME_SOURCE; + process.env.PLUGIN_EVAL_CODEX_HOME_SOURCE = codexHomeSource; + + const provisioned = await provisionBenchmarkWorkspace({ + target: { + kind: "skill", + name: "minimal-skill", + path: skillPath, + }, + config: { + workspace: { + sourcePath: skillPath, + setupMode: "copy", + }, + targetProvisioning: { + mode: "isolated-skill-home", + }, + }, + scenarioId: "seed-auth", + }); + + try { + assert.equal( + await fs.readFile(path.join(provisioned.codexHomePath, "auth.json"), "utf8"), + '{"token":"test"}\n', + ); + assert.equal( + await fs.readFile(path.join(provisioned.codexHomePath, "config.toml"), "utf8"), + 'model = "gpt-5.4"\n', + ); + } finally { + if (previousSource === undefined) { + delete process.env.PLUGIN_EVAL_CODEX_HOME_SOURCE; + } else { + process.env.PLUGIN_EVAL_CODEX_HOME_SOURCE = previousSource; + } + await provisioned.cleanup(); + } +}); + +test("generates improvement briefs and comparison payloads", async () => { + const goodPath = path.join(fixturesRoot, "minimal-skill"); + const badDir = await makeTempDir("plugin-eval-compare"); + await writeSkillFixture(badDir, { + description: `Verbose description ${"y".repeat(1300)}`, + bodyLines: 650, + }); + + const before = await analyzePath(badDir); + const after = await analyzePath(goodPath); + const diff = compareResults(before, after); + + assert.match(after.improvementBrief.suggestedPrompt, /skill-creator/i); + assert.ok(diff.scoreDelta > 0); + assert.ok(diff.resolvedFailures.length >= 1); +}); + +test("summary includes deductions, category totals, and risk reasons", async () => { + const tempDir = await makeTempDir("plugin-eval-summary"); + await writeSkillFixture(tempDir, { + description: `Verbose description ${"z".repeat(1300)}`, + bodyLines: 650, + }); + + const result = await analyzePath(tempDir); + + assert.ok(result.summary.scoreBreakdown.totalDeductions > 0); + assert.ok(result.summary.deductions.length > 0); + assert.ok(result.summary.categoryDeductions.length > 0); + assert.ok(result.summary.riskReasons.length > 0); + assert.equal(result.summary.scoreBreakdown.finalScore, result.summary.score); +}); + +test("CLI analyze, report, compare, and explain-budget commands work together", async () => { + const tempDir = await makeTempDir("plugin-eval-cli"); + const resultPath = path.join(tempDir, "result.json"); + const markdownPath = path.join(tempDir, "result.md"); + const comparePath = path.join(tempDir, "compare.md"); + const briefPath = path.join(tempDir, "brief.json"); + const measuresPath = path.join(tempDir, "measures.md"); + const skillPath = path.join(fixturesRoot, "minimal-skill"); + const usagePath = path.join(fixturesRoot, "observed-usage", "responses.jsonl"); + + await execFileAsync( + nodeBin, + [cliPath, "analyze", skillPath, "--output", resultPath, "--brief-out", briefPath, "--observed-usage", usagePath], + { + cwd: repoRoot, + }, + ); + const result = JSON.parse(await fs.readFile(resultPath, "utf8")); + assert.equal(result.target.kind, "skill"); + assert.ok(await fs.stat(briefPath)); + assert.equal(result.observedUsage.sampleCount, 3); + + await execFileAsync(nodeBin, [cliPath, "report", resultPath, "--format", "markdown", "--output", markdownPath], { + cwd: repoRoot, + }); + assert.match(await fs.readFile(markdownPath, "utf8"), /Plugin Eval Report/); + assert.match(await fs.readFile(markdownPath, "utf8"), /Recommended Next Step/); + + await execFileAsync(nodeBin, [cliPath, "compare", resultPath, resultPath, "--format", "markdown", "--output", comparePath], { + cwd: repoRoot, + }); + assert.match(await fs.readFile(comparePath, "utf8"), /Plugin Eval Comparison/); + assert.match(await fs.readFile(comparePath, "utf8"), /Recommended Next Step/); + + const { stdout } = await execFileAsync(nodeBin, [cliPath, "explain-budget", skillPath], { + cwd: repoRoot, + }); + const budgetPayload = JSON.parse(stdout); + assert.equal(budgetPayload.kind, "budget-explanation"); + assert.ok(budgetPayload.nextAction); + + await execFileAsync( + nodeBin, + [cliPath, "measurement-plan", skillPath, "--format", "markdown", "--output", measuresPath, "--observed-usage", usagePath], + { + cwd: repoRoot, + }, + ); + assert.match(await fs.readFile(measuresPath, "utf8"), /Measurement Plan/); + assert.match(await fs.readFile(measuresPath, "utf8"), /Recommended Next Step/); + assert.match(await fs.readFile(measuresPath, "utf8"), /
/); +}); + +test("CLI init-benchmark and benchmark commands work together with a fake codex executable", async () => { + const sourcePath = path.join(fixturesRoot, "minimal-skill"); + const tempDir = await makeTempDir("plugin-eval-cli-benchmark"); + const skillPath = path.join(tempDir, "minimal-skill"); + const fakeCodexPath = await createFakeCodexExecutable(tempDir); + const initPath = path.join(tempDir, "init.md"); + const runPath = path.join(tempDir, "run.md"); + await copyDirectory(sourcePath, skillPath); + + await execFileAsync( + nodeBin, + [cliPath, "init-benchmark", skillPath, "--format", "markdown", "--output", path.join(skillPath, ".plugin-eval", "benchmark.json")], + { + cwd: repoRoot, + }, + ); + + const { stdout } = await execFileAsync( + nodeBin, + [cliPath, "init-benchmark", skillPath, "--format", "markdown"], + { + cwd: repoRoot, + }, + ); + await fs.writeFile(initPath, stdout, "utf8"); + assert.match(await fs.readFile(initPath, "utf8"), /Benchmark Template Ready/); + assert.match(await fs.readFile(initPath, "utf8"), /Use From Codex Chat/); + + const run = await execFileAsync( + nodeBin, + [cliPath, "benchmark", skillPath, "--format", "markdown"], + { + cwd: repoRoot, + env: { + ...process.env, + PATH: `${path.dirname(fakeCodexPath)}:${process.env.PATH}`, + PLUGIN_EVAL_CODEX_EXECUTABLE: fakeCodexPath, + }, + }, + ); + await fs.writeFile(runPath, run.stdout, "utf8"); + assert.match(await fs.readFile(runPath, "utf8"), /Benchmark Run/); + assert.match(await fs.readFile(runPath, "utf8"), /Recommended Next Step/); + assert.match(await fs.readFile(runPath, "utf8"), /Scenarios/); + assert.match(await fs.readFile(runPath, "utf8"), /Codex version: codex-cli fake-test/); +}); + +test("explainBudget returns a budget-only payload", async () => { + const payload = await explainBudget(path.join(fixturesRoot, "minimal-skill")); + + assert.equal(payload.kind, "budget-explanation"); + assert.equal(payload.budgets.method, "estimated-static"); + assert.ok(payload.budgets.trigger_cost_tokens.value > 0); + assert.ok(payload.workflowGuide); +}); + +test("workflow guide routes natural chat requests into the beginner-friendly path", async () => { + const skillPath = path.join(fixturesRoot, "minimal-skill"); + const guide = await buildWorkflowGuide(skillPath, { + request: "Measure the real token usage of this skill.", + }); + const markdown = renderPayload(guide, "markdown"); + + assert.equal(guide.kind, "workflow-guide"); + assert.equal(guide.recommendedWorkflowId, "measure"); + assert.equal(guide.requestRouting.goal, "measure"); + assert.ok(guide.nextAction); + assert.match(markdown, /Plugin Eval Start Here/); + assert.match(markdown, /Measure the real token usage of this skill\./); + assert.match(markdown, /Quick local entrypoint: `plugin-eval start/); + assert.match(markdown, /plugin-eval init-benchmark/); +}); + +test("workflow guide routes analysis requests into report plus benchmark setup", async () => { + const skillPath = path.join(fixturesRoot, "minimal-skill"); + const guide = await buildWorkflowGuide(skillPath, { + request: "give me an analysis of the game dev skill", + }); + const markdown = renderPayload(guide, "markdown"); + + assert.equal(guide.kind, "workflow-guide"); + assert.equal(guide.recommendedWorkflowId, "analysis"); + assert.equal(guide.requestRouting.goal, "analysis"); + assert.equal(guide.startHere.firstCommand, `plugin-eval analyze ${formatCommandPath(skillPath)} --format markdown`); + assert.ok(guide.startHere.commands.some((command) => command.includes("plugin-eval init-benchmark"))); + assert.match(markdown, /Full Skill Analysis/); + assert.match(markdown, /plugin-eval init-benchmark/); +}); + +test("CLI start command renders chat-first workflow suggestions", async () => { + const skillPath = path.join(fixturesRoot, "minimal-skill"); + const { stdout } = await execFileAsync( + nodeBin, + [cliPath, "start", skillPath, "--request", "what should I run next?", "--format", "markdown"], + { + cwd: repoRoot, + }, + ); + + assert.match(stdout, /Plugin Eval Start Here/); + assert.match(stdout, /What should I run next\?/i); + assert.match(stdout, /plugin-eval start .*what should I run next/i); + assert.match(stdout, /plugin-eval analyze/); + assert.match(stdout, /Recommended Next Step/); +}); + +test("shipped plugin surfaces advertise beginner chat prompts", async () => { + const manifest = JSON.parse(await fs.readFile(path.join(repoRoot, ".codex-plugin", "plugin.json"), "utf8")); + const umbrellaSkill = await fs.readFile(path.join(repoRoot, "skills", "plugin-eval", "SKILL.md"), "utf8"); + const readme = await fs.readFile(path.join(repoRoot, "README.md"), "utf8"); + + assert.match(manifest.interface.longDescription, /plugin-eval start/i); + assert.deepEqual(manifest.interface.defaultPrompt, [ + "Give me an analysis of the game studio plugin.", + "Evaluate this plugin.", + "Why did this score that way?", + ]); + assert.match(umbrellaSkill, /plugin-eval start --request/); + assert.match(umbrellaSkill, /analysis of the game dev skill/i); + assert.match(umbrellaSkill, /plugin-eval measurement-plan/); + assert.match(umbrellaSkill, /What should I fix first\?/); + assert.match(readme, /Start From Chat/); + assert.match(readme, /plugin-eval start --request/); + assert.match(readme, /analysis of the game dev skill/i); + assert.match(readme, /Why did this score that way\?/); +}); diff --git a/data/.codex/.codex/.tmp/plugins/plugins/remotion/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/remotion/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..1f48c9d145d9d119f8b0cbe68420cb2df158e927 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/remotion/.codex-plugin/plugin.json @@ -0,0 +1,46 @@ +{ + "name": "remotion", + "version": "1.0.3", + "description": "Remotion video creation skills — best practices, animations, audio, captions, 3D, and more for building programmatic videos with React.", + "author": { + "name": "Remotion", + "email": "hi@remotion.dev", + "url": "https://remotion.dev" + }, + "homepage": "https://remotion.dev", + "repository": "https://github.com/remotion-dev/remotion", + "license": "MIT", + "keywords": [ + "remotion", + "video", + "react", + "animation", + "composition", + "rendering", + "ffmpeg", + "captions", + "audio" + ], + "skills": "./skills/", + "interface": { + "displayName": "Remotion", + "shortDescription": "Create motion graphics from prompts", + "longDescription": "Build videos programmatically with Remotion and React. Covers animations, timing, audio, captions, 3D, transitions, charts, text effects, and more.", + "developerName": "Remotion", + "category": "Creativity", + "capabilities": ["Read", "Write"], + "websiteURL": "https://remotion.dev", + "privacyPolicyURL": "https://remotion.pro/privacy", + "termsOfServiceURL": "https://remotion.pro/terms", + "defaultPrompt": [ + "Create an animated chart with 5 bars", + "Make an animated call-to-action subscribe button for our YouTube channel", + "Use Remotion to add captions and audio to a video composition." + ], + "screenshots": [], + "brandColor": "#0B84F3", + "composerIcon": "./assets/icon.png", + "logo": "./assets/logo.png", + "logoDark": "./assets/logo-dark.png" + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..84679e271197f97ab0b052c84a0a3f10100e075a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/SKILL.md @@ -0,0 +1,95 @@ +--- +name: remotion-best-practices +description: Best practices for Remotion - Video creation in React +metadata: + tags: remotion, video, react, animation, composition +--- + +## When to use + +Use this skills whenever you are dealing with Remotion code to obtain the domain-specific knowledge. + +## New project setup + +When in an empty folder or workspace with no existing Remotion project, scaffold one using: + +```bash +npx create-video@latest --yes --blank --no-tailwind my-video +``` + +Replace `my-video` with a suitable project name. + +## Starting preview + +Start the Remotion Studio to preview a video: + +```bash +npx remotion studio +``` + +## Optional: one-frame render check + +You can render a single frame with the CLI to sanity-check layout, colors, or timing. +Skip it for trivial edits, pure refactors, or when you already have enough confidence from Studio or prior renders. + +```bash +npx remotion still [composition-id] --scale=0.25 --frame=30 +``` + +At 30 fps, `--frame=30` is the one-second mark (`--frame` is zero-based). + +## Captions + +When dealing with captions or subtitles, load the [./rules/subtitles.md](./rules/subtitles.md) file for more information. + +## Using FFmpeg + +For some video operations, such as trimming videos or detecting silence, FFmpeg should be used. Load the [./rules/ffmpeg.md](./rules/ffmpeg.md) file for more information. + +## Silence detection + +When needing to detect and trim silent segments from video or audio files, load the [./rules/silence-detection.md](./rules/silence-detection.md) file. + +## Audio visualization + +When needing to visualize audio (spectrum bars, waveforms, bass-reactive effects), load the [./rules/audio-visualization.md](./rules/audio-visualization.md) file for more information. + +## Sound effects + +When needing to use sound effects, load the [./rules/sfx.md](./rules/sfx.md) file for more information. + +## How to use + +Read individual rule files for detailed explanations and code examples: + +- [rules/3d.md](rules/3d.md) - 3D content in Remotion using Three.js and React Three Fiber +- [rules/animations.md](rules/animations.md) - Fundamental animation skills for Remotion +- [rules/assets.md](rules/assets.md) - Importing images, videos, audio, and fonts into Remotion +- [rules/audio.md](rules/audio.md) - Using audio and sound in Remotion - importing, trimming, volume, speed, pitch +- [rules/calculate-metadata.md](rules/calculate-metadata.md) - Dynamically set composition duration, dimensions, and props +- [rules/can-decode.md](rules/can-decode.md) - Check if a video can be decoded by the browser using Mediabunny +- [rules/charts.md](rules/charts.md) - Chart and data visualization patterns for Remotion (bar, pie, line, stock charts) +- [rules/compositions.md](rules/compositions.md) - Defining compositions, stills, folders, default props and dynamic metadata +- [rules/extract-frames.md](rules/extract-frames.md) - Extract frames from videos at specific timestamps using Mediabunny +- [rules/fonts.md](rules/fonts.md) - Loading Google Fonts and local fonts in Remotion +- [rules/get-audio-duration.md](rules/get-audio-duration.md) - Getting the duration of an audio file in seconds with Mediabunny +- [rules/get-video-dimensions.md](rules/get-video-dimensions.md) - Getting the width and height of a video file with Mediabunny +- [rules/get-video-duration.md](rules/get-video-duration.md) - Getting the duration of a video file in seconds with Mediabunny +- [rules/gifs.md](rules/gifs.md) - Displaying GIFs synchronized with Remotion's timeline +- [rules/images.md](rules/images.md) - Embedding images in Remotion using the Img component +- [rules/light-leaks.md](rules/light-leaks.md) - Light leak overlay effects using @remotion/light-leaks +- [rules/lottie.md](rules/lottie.md) - Embedding Lottie animations in Remotion +- [rules/measuring-dom-nodes.md](rules/measuring-dom-nodes.md) - Measuring DOM element dimensions in Remotion +- [rules/measuring-text.md](rules/measuring-text.md) - Measuring text dimensions, fitting text to containers, and checking overflow +- [rules/sequencing.md](rules/sequencing.md) - Sequencing patterns for Remotion - delay, trim, limit duration of items +- [rules/tailwind.md](rules/tailwind.md) - Using TailwindCSS in Remotion +- [rules/text-animations.md](rules/text-animations.md) - Typography and text animation patterns for Remotion +- [rules/timing.md](rules/timing.md) - Timing with interpolate and Bézier easing, springs +- [rules/transitions.md](rules/transitions.md) - Scene transition patterns for Remotion +- [rules/transparent-videos.md](rules/transparent-videos.md) - Rendering out a video with transparency +- [rules/trimming.md](rules/trimming.md) - Trimming patterns for Remotion - cut the beginning or end of animations +- [rules/videos.md](rules/videos.md) - Embedding videos in Remotion - trimming, volume, speed, looping, pitch +- [rules/parameters.md](rules/parameters.md) - Make a video parametrizable by adding a Zod schema +- [rules/maps.md](rules/maps.md) - Add a map using Mapbox and animate it +- [rules/silence-detection.md](rules/silence-detection.md) - Adaptive silence detection using FFmpeg loudnorm and silencedetect +- [rules/voiceover.md](rules/voiceover.md) - Adding AI-generated voiceover to Remotion compositions using ElevenLabs TTS diff --git a/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0580d79a7ec757933ea2e2ee911dfcf47308517d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Remotion Best Practices" + short_description: "Apply Remotion patterns for programmatic video creation in React" diff --git a/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/3d.md b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/3d.md new file mode 100644 index 0000000000000000000000000000000000000000..c9d254f1209d83fd6f8a313659cfc694ec7b7837 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/3d.md @@ -0,0 +1,86 @@ +--- +name: 3d +description: 3D content in Remotion using Three.js and React Three Fiber. +metadata: + tags: 3d, three, threejs +--- + +# Using Three.js and React Three Fiber in Remotion + +Follow React Three Fiber and Three.js best practices. +Only the following Remotion-specific rules need to be followed: + +## Prerequisites + +First, the `@remotion/three` package needs to be installed. +If it is not, use the following command: + +```bash +npx remotion add @remotion/three # If project uses npm +bunx remotion add @remotion/three # If project uses bun +yarn remotion add @remotion/three # If project uses yarn +pnpm exec remotion add @remotion/three # If project uses pnpm +``` + +## Using ThreeCanvas + +You MUST wrap 3D content in `` and include proper lighting. +`` MUST have a `width` and `height` prop. + +```tsx +import { ThreeCanvas } from "@remotion/three"; +import { useVideoConfig } from "remotion"; + +const { width, height } = useVideoConfig(); + + + + + + + + +; +``` + +## No animations not driven by `useCurrentFrame()` + +Shaders, models etc MUST NOT animate by themselves. +No animations are allowed unless they are driven by `useCurrentFrame()`. +Otherwise, it will cause flickering during rendering. + +Using `useFrame()` from `@react-three/fiber` is forbidden. + +## Animate using `useCurrentFrame()` + +Use `useCurrentFrame()` to perform animations. + +```tsx +const frame = useCurrentFrame(); +const rotationY = frame * 0.02; + + + + +; +``` + +## Using `` inside `` + +The `layout` prop of any `` inside a `` must be set to `none`. + +```tsx +import { Sequence } from "remotion"; +import { ThreeCanvas } from "@remotion/three"; + +const { width, height } = useVideoConfig(); + + + + + + + + +; +``` diff --git a/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/animations.md b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/animations.md new file mode 100644 index 0000000000000000000000000000000000000000..4a02e553570e570e45319112626adb214a39b025 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/animations.md @@ -0,0 +1,31 @@ +--- +name: animations +description: Fundamental animation skills for Remotion +metadata: + tags: animations, transitions, frames, useCurrentFrame +--- + +All animations MUST be driven by the `useCurrentFrame()` hook. +Write animations in seconds and multiply them by the `fps` value from `useVideoConfig()`. + +For eased motion, prefer `interpolate` with explicit frame ranges and an easing—especially `Easing.bezier`, which matches CSS `cubic-bezier` so timing can be shared with web specs and curve editors. See [timing](./timing.md). + +```tsx +import { useCurrentFrame, Easing } from "remotion"; + +export const FadeIn = () => { + const frame = useCurrentFrame(); + const { fps } = useVideoConfig(); + + const opacity = interpolate(frame, [0, 2 * fps], [0, 1], { + extrapolateRight: "clamp", + extrapolateLeft: "clamp", + easing: Easing.bezier(0.16, 1, 0.3, 1), + }); + + return
Hello World!
; +}; +``` + +CSS transitions or animations are FORBIDDEN - they will not render correctly. +Tailwind animation class names are FORBIDDEN - they will not render correctly. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/assets.md b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/assets.md new file mode 100644 index 0000000000000000000000000000000000000000..a5d40152eff6a5852fb0a4f27c50618c795758af --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/remotion/skills/remotion/rules/assets.md @@ -0,0 +1,78 @@ +--- +name: assets +description: Importing images, videos, audio, and fonts into Remotion +metadata: + tags: assets, staticFile, images, fonts, public +--- + +# Importing assets in Remotion + +## The public folder + +Place assets in the `public/` folder at your project root. + +## Using staticFile() + +You MUST use `staticFile()` to reference files from the `public/` folder: + +```tsx +import { Img, staticFile } from "remotion"; + +export const MyComposition = () => { + return ; +}; +``` + +The function returns an encoded URL that works correctly when deploying to subdirectories. + +## Using with components + +**Images:** + +```tsx +import { Img, staticFile } from "remotion"; + +; +``` + +**Videos:** + +```tsx +import { Video } from "@remotion/media"; +import { staticFile } from "remotion"; + +