# Magic Comments

**Page:** kit/exec/magic-comments

[Download Raw Markdown](./kit/exec/magic-comments.md)

---

# Magic Comments

**Configure script behavior with special comments at the top of your file.** No code changes, no config files, no environment variables. Change a comment, behavior changes instantly.

```javascript
// @mode worker
// @cors reflective
// @timeout 5000
// @log-level standard
// @ai true

// Your code starts here...
return { hello: 'world' };
```

---

## How Magic Comments Work

Magic comments are parsed at script load time. They must be placed at the **very top** of your file, before any code.

**Rules:**
- Start with `//` followed by a space and `@`
- Must be at the top of the file — before any code, imports, or expressions
- One comment per line
- Validated via the [validation API](/api/exec/validation/)
- Take precedence over default values
- Case-sensitive for comment names

**Validation example:**


  
    ```bash
    # Validate magic comments in a script
    hoody exec validate magic-comments \
      --code "// @mode worker\n// @cors reflective\n// @timeout 5000\nreturn {};"
    ```
  
  
    ```typescript
    const containerClient = await client.withContainer({
      id: CONTAINER_ID, project_id: PROJECT_ID, server: SERVER
    });
    const result = await containerClient.exec.validate.validateMagicComments({
      code: '// @mode worker\n// @cors reflective\n// @timeout 5000\nreturn {};'
    });
    console.log(result.data); // { valid: true, comments: { mode: "worker", cors: "reflective", timeout: 5000 } }
    ```
  
  
    ```bash
    curl -s -X POST "https://PROJECT-CONTAINER-exec-1.SERVER.containers.hoody.icu/api/v1/exec/validate/magic-comments" \
      -H "Content-Type: application/json" \
      -d '{
        "code": "// @mode worker\n// @cors reflective\n// @timeout 5000\nreturn {};"
      }'
    ```
  


---

## Execution & Performance

| Comment | Values | Default | Description |
|---------|--------|---------|-------------|
| `@mode` | `worker` \| `serverless` | `serverless` | **Choose execution mode** — Worker for stateful persistent VM, Serverless for isolated fresh VM per request |
| `@enabled` | `true` \| `false` | `true` | Enable or disable script execution — a disabled script does not run |
| `@timeout` | number (ms) \| `0` \| `unlimited` | `3600000` | Request timeout in milliseconds (default: 1 hour). Use `0` or `unlimited` for no timeout |
| `@await-promises` | `true` \| `false` | `true` | Auto-await returned promises before sending response |
| `@concurrent` | number \| `true` \| `false` | `true` | **Serverless only** — Max concurrent executions. `true` = unlimited, `false` = single serial execution |

**Examples:**
```javascript
// @mode worker          // Persistent VM, shared state
// @timeout 60000        // 60 second timeout
// @concurrent false     // Serverless: process one at a time
// @timeout 0            // No timeout (use carefully!)
// @timeout unlimited    // Same as @timeout 0
```


Always set `@mode` as the **first** magic comment — it determines the fundamental execution behavior and affects which other comments are relevant.


---

## CORS Configuration

| Comment | Values | Default | Description |
|---------|--------|---------|-------------|
| `@cors` | `reflective` \| `*` \| URL \| `none` | `none` | CORS origin. `reflective` mirrors the request origin |
| `@cors-credentials` | `true` \| `false` | `false` | Allow credentials (cookies, auth headers) |
| `@cors-methods` | `GET,POST,...` | `GET,POST,PUT,DELETE,PATCH,OPTIONS` | Allowed HTTP methods |
| `@cors-headers` | `Authorization,...` | `Content-Type,Authorization,X-Requested-With` | Allowed request headers |
| `@cors-max-age` | number (seconds) | _(unset)_ | Preflight response cache duration — omitted from responses unless set |

**Examples:**
```javascript
// @cors reflective              // Mirror request origin (development)
// @cors *                       // Allow any origin (testing)
// @cors https://app.example.com // Specific origin (production)
// @cors none                    // No CORS headers
// @cors-credentials true        // Allow cookies
// @cors-methods GET,POST        // Only allow GET and POST
```


Use `@cors reflective` during development for convenience. In production, **always specify the exact origin** (`@cors https://your-app.com`) to prevent unauthorized cross-origin access.


---

## Logging & Debug

| Comment | Values | Default | Description |
|---------|--------|---------|-------------|
| `@log-level` | `none` \| `minimal` \| `standard` \| `full` \| `debug` | `standard` | Logging verbosity |
| `@debug` | `true` \| `false` | `false` | Shortcut for `@log-level debug` |
| `@log-request-body` | `full` \| `redacted` \| `off` \| `true` \| `false` | `full` | Log incoming request bodies |
| `@log-response-body` | `full` \| `redacted` \| `off` \| `true` \| `false` | `full` | Log response bodies |
| `@log-max-body-size` | number (bytes) | `1048576` | Max body size to log (e.g., `1048576` for 1MB) |
| `@log-exclude-headers` | header names | `authorization cookie x-token` | Headers to exclude from logs (e.g., `authorization cookie`) |
| `@log-retention-days` | number | `14` | How long to keep log files |
| `@debug-instrument` | `true` \| `false` | `false` | Enable code instrumentation for detailed tracing |

**Examples:**
```javascript
// @log-level full                  // Maximum logging
// @log-request-body true           // Log request payloads
// @log-response-body true          // Log response payloads
// @log-exclude-headers authorization cookie  // Hide sensitive headers
// @log-retention-days 30           // Keep logs for 30 days
// @debug-instrument true           // Detailed code tracing
```

**Log levels explained:**
- `none` — No logging
- `minimal` — Request line and final status/duration only (skips the detailed request/response logs)
- `standard` — Request metadata and headers (default)
- `full` — Standard plus request/response bodies (body capture still gated by `@log-request-body` / `@log-response-body`)
- `debug` — Full plus internal execution details (VM creation, module loading, etc.)

---

## AI Integration

| Comment | Values | Default | Description |
|---------|--------|---------|-------------|
| `@ai` | `true` \| `false` | `true` | Enable AI helpers — injects `model`, `openai`, `ai`, `generateText`, `streamText`, `generateObject` |
| `@ai-model` | model name | `minimax/minimax-m2.5` | AI model to use (e.g., `anthropic/claude-sonnet-4.5`) |
| `@ai-temperature` | `0` - `2` | — | AI temperature parameter (provider default when unset) |
| `@ai-max-tokens` | number | — | Max tokens for AI response (provider default when unset) |
| `@ai-key` | string | server-configured | AI API key override (default uses the server's `--ai-key` flag) |

**Example:**
```javascript
// @mode serverless
// @ai true
// @ai-model anthropic/claude-sonnet-4.5
// @ai-temperature 0.3

const { text } = await generateText({
  model,
  prompt: `Summarize this: ${req.body.content}`
});

return { summary: text };
```


When `@ai true` is set, you get the **Vercel AI SDK** helpers injected directly — no imports, no API key setup. The `model` variable is pre-configured with your `@ai-model` selection and uses [Hoody AI](/foundation/hoody-ai/) for authentication.

**See [AI-Powered Scripts](/kit/exec/ai-integration/) for the complete AI integration guide.**


---

## Authentication

| Comment | Values | Default | Description |
|---------|--------|---------|-------------|
| `@token` | string | — | Per-endpoint shared secret. Requests must provide the token via one of four methods |

**Add `@token` to protect any endpoint — no middleware, no auth library, no config:**

```javascript
// @token my-secret-key-123
// @cors reflective

return { data: 'only authenticated requests see this' };
```

Clients authenticate using any of these methods (checked in priority order):

| Priority | Method | Example |
|----------|--------|---------|
| 1a | `Authorization: Bearer <token>` | `curl -H "Authorization: Bearer my-secret-key-123" ...` |
| 1b | `Authorization: Basic` (password field) | `curl -u user:my-secret-key-123 ...` or `curl -u :my-secret-key-123 ...` |
| 2 | `X-Token` header | `curl -H "X-Token: my-secret-key-123" ...` |
| 3 | `?token=` query parameter | `curl "https://...?token=my-secret-key-123"` |


**Basic auth uses the password field as the token.** The username is ignored — send anything (or nothing) as the username. This makes `@token` work out-of-the-box with tools like `curl -u :secret`, browser auth dialogs, and HTTP clients that only support Basic auth.


**Security details:**
- Constant-time comparison (SHA-256 + `timingSafeEqual`) — immune to timing attacks
- Token is **redacted** in all API responses, logs, and access logs (`[REDACTED]`)
- `?token=` is stripped from `req.url` and `metadata.parameters` before your script runs
- CORS preflight (`OPTIONS`) returns `204` without requiring auth (spec-correct behavior)
- WebSocket `upgrade` requests are also gated — pass the token via header or `?token=`
- Empty or whitespace-only values are ignored (endpoint stays public)

**See [Authentication](/kit/exec/authentication/) for the complete guide with examples.**

---

## Advanced Features

| Comment | Values | Default | Description |
|---------|--------|---------|-------------|
| `@websocket` | _(flag)_ | — | **Requires worker mode** — Enable WebSocket support |
| `@label` | string | — | Script classification label for filtering and organization |
| `@return-type` | TypeScript type | — | TypeScript type definition for the script's return value |
| `@return-type-mode` | `strict` \| `warn` \| `dev` | `strict` | Enforcement mode for `@return-type` validation. `strict` rejects on mismatch, `warn` logs only, `dev` enforces only outside production |
| `@description` | text | — | API documentation description |
| `@tags` | `Tag1, Tag2` | — | Categorization tags for API documentation |

**Examples:**
```javascript
// @mode worker
// @websocket                     // Enable WebSocket handlers
// @label user-api               // Classify this script
// @return-type { id: string, name: string, email: string }
// @return-type-mode strict      // Enforce return-type at runtime
// @description User profile API
// @tags Users, Profile
```


`@websocket` requires worker mode — serverless mode cannot maintain persistent connections. See [Execution Modes](/kit/exec/execution-modes/#websocket-support-worker-mode-only) for WebSocket details.


---

## Magic Comments API

Manage magic comments programmatically via API endpoints:

| Endpoint | Description |
|----------|-------------|
| `GET /api/v1/exec/magic-comments/schema` | Get the canonical schema of all supported magic comments |
| `GET /api/v1/exec/magic-comments/read` | Read magic comments from a script |
| `PUT /api/v1/exec/magic-comments/update` | Update magic comments on a script |
| `POST /api/v1/exec/magic-comments/bulk-update` | Bulk update magic comments across multiple scripts |


  
    ```bash
    # Read magic comments from a specific script
    hoody exec magic-comments read --path "api/hello.ts"
    ```
  
  
    ```typescript
    // Get the full magic comments schema
    const schema = await containerClient.exec.magic.getSchema();
    console.log(schema.data);

    // Read magic comments from a specific script
    const comments = await containerClient.exec.magic.read({ path: 'api/hello.ts' });
    console.log(comments.data); // { mode: "serverless", cors: "reflective", ... }
    ```
  
  
    ```bash
    # Get the full magic comments schema
    curl "https://PROJECT-CONTAINER-exec-1.SERVER.containers.hoody.icu/api/v1/exec/magic-comments/schema"

    # Read magic comments from a specific script
    curl "https://PROJECT-CONTAINER-exec-1.SERVER.containers.hoody.icu/api/v1/exec/magic-comments/read?path=api/hello.ts"
    ```
  


---

## Quick Reference

All magic comments at a glance:

| Category | Comments |
|----------|----------|
| **Execution** | `@mode`, `@enabled`, `@timeout`, `@await-promises`, `@concurrent` |
| **Authentication** | `@token` |
| **CORS** | `@cors`, `@cors-credentials`, `@cors-methods`, `@cors-headers`, `@cors-max-age` |
| **Logging** | `@log-level`, `@debug`, `@log-request-body`, `@log-response-body`, `@log-max-body-size`, `@log-exclude-headers`, `@log-retention-days`, `@debug-instrument` |
| **AI** | `@ai`, `@ai-model`, `@ai-temperature`, `@ai-max-tokens`, `@ai-key` |
| **Advanced** | `@websocket`, `@label`, `@return-type`, `@return-type-mode`, `@description`, `@tags` |

---

## What's Next