<!--
hoody-exec Subskill (http)
Auto-generated by Hoody Skills Generator
Generated: 2026-05-06T18:30:08.094Z
Model: mimo-v2.5-pro + fixer:mimo-v2.5-pro
Mode: http


Tokens: 15454

DO NOT EDIT MANUALLY - Changes will be overwritten on next generation
-->

# hoody-exec Subskill

## Overview

### What is hoody-exec?

hoody-exec is a Bun-powered script execution service that transforms any TypeScript or JavaScript file into a fully functional API endpoint. It provides the bridge between writing code and exposing it as a REST API — no framework setup, no server configuration, no deployment pipelines. You write a script, hoody-exec serves it.

### When to Use hoody-exec

Use hoody-exec when you need to:

- **Deploy instant REST API endpoints** from TypeScript/JavaScript files without framework boilerplate
- **Handle webhooks** with automatic JSON parsing and structured responses
- **Build data transformation pipelines** (ETL) that accept input, process it, and return results
- **Chain scripts together** — call between exec scripts to compose multi-step workflows
- **Create monitoring endpoints** that return structured JSON health/status data
- **Run scheduled tasks** via cron-based script execution
- **Prototype APIs rapidly** — write code, execute immediately, iterate

### How It Fits Into Hoody Philosophy

hoody-exec embodies the Hoody principle of **zero-friction infrastructure**. Traditional API development requires choosing a framework, configuring routing, setting up a server, managing process lifecycles, and deploying. hoody-exec eliminates all of that. A script file with a default export function becomes an endpoint. The file path determines the URL. Magic comments configure behavior. The service handles everything else — parsing, routing, logging, monitoring, dependency management.

This service runs inside a Hoody container alongside other Hoody Kit services. Access it via the Hoody Proxy routing system using the standardized domain pattern. Authentication flows through the Hoody API layer — no separate auth configuration needed for the exec service itself.

### Core Concepts

**Script-as-Endpoint**: Every `.js` or `.ts` file in the scripts directory becomes an API endpoint. The file path maps directly to the URL path: remove the file extension and use the directory structure as the URL. For example, `api/users/[id].ts` maps to `/api/users/{id}`, and `docs/[...slug].ts` captures multiple path segments. Supported patterns: static routes, `[param]` dynamic segments, `[...slug]` catch-all routes, `[[...path]]` optional catch-all routes.

**Magic Comments**: Special comment annotations in script files that configure endpoint behavior — HTTP method restrictions, return type declarations, caching rules, rate limits, and more. These are read and applied at runtime.

**Shared State**: A key-value store accessible across all scripts, enabling stateful operations and inter-script communication without external databases. Keys are logical identifiers (e.g., session IDs, service names) — they do not need to match the container hostname. Use distinct prefixes to avoid collisions between unrelated scripts.

**Bun Runtime**: Scripts execute in Bun, a high-performance JavaScript/TypeScript runtime with native TypeScript support, fast startup, and built-in package management.

### Service Access Pattern

All hoody-exec endpoints are accessed through the Hoody Kit service URL:

```
https://{projectId}-{containerId}-exec-{serviceId}.{node}.containers.hoody.icu
```

For documentation clarity, the examples below use the placeholder `EXEC_BASE_URL`. Replace this with your actual service URL obtained from container discovery (see core SKILL.md).

---

## Common Workflows

> **Note:** All curl examples use `-s` for silent output and a 10-minute timeout. Adjust these flags as needed for your environment.

### Workflow 1: Script Lifecycle — Create, Execute, Update

This is the fundamental workflow: write a script, execute it, modify it, and execute again.

**Step 1: Write a new script**

Create a script file that will become an API endpoint.

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "greeting.ts",
    "content": "export default function handler(req: Request) {\n  const body = req.body ? JSON.parse(req.body) : {};\n  const name = body.name || \"World\";\n  return { message: `Hello, ${name}!`, timestamp: new Date().toISOString() };\n}"
  }'
```

**Step 2: Verify the script was created**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/scripts/read?path=greeting.ts"
```

**Step 3: Execute the script**

The script is now available at `POST /greeting`. Pass data in the request body.

```
curl -s -X POST "${EXEC_BASE_URL}/greeting" \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice"}'
```

Expected response:

```
{
  "message": "Hello, Alice!",
  "timestamp": "2025-01-15T10:30:00.000Z"
}
```

**Step 4: Update the script**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "greeting.ts",
    "content": "export default function handler(req: Request) {\n  const body = req.body ? JSON.parse(req.body) : {};\n  const name = body.name || \"World\";\n  const lang = body.lang || \"en\";\n  const greetings: Record<string, string> = {\n    en: \"Hello\",\n    es: \"Hola\",\n    fr: \"Bonjour\",\n    de: \"Hallo\"\n  };\n  const greeting = greetings[lang] || greetings.en;\n  return { message: `${greeting}, ${name}!`, lang, timestamp: new Date().toISOString() };\n}"
  }'
```

**Step 5: Execute updated script**

```
curl -s -X POST "${EXEC_BASE_URL}/greeting" \
  -H "Content-Type: application/json" \
  -d '{"name": "Maria", "lang": "es"}'
```

Expected response:

```
{
  "message": "Hola, Maria!",
  "lang": "es",
  "timestamp": "2025-01-15T10:31:00.000Z"
}
```

**Step 6: List all scripts**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/scripts/list"
```

**Step 7: Delete the script when done**

```
curl -s -X DELETE "${EXEC_BASE_URL}/api/v1/exec/scripts/delete?path=greeting.ts"
```

---

### Workflow 2: Script Validation Before Deployment

Validate scripts for syntax errors, TypeScript issues, dependency problems, and magic comment correctness before executing them.

**Step 1: Validate TypeScript compilation**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/validate/typescript" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "interface User { name: string; age: number; }\nexport default function handler(): User {\n  return { name: \"test\", age: 25 };\n}"
  }'
```

**Step 2: Validate syntax**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/validate/syntax" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "export default function handler() { return { status: \"ok\" }; }"
  }'
```

**Step 3: Validate dependencies**

Check that all imports in the script are resolvable.

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/validate/dependencies" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import { z } from \"zod\";\nexport default function handler() { return { valid: true }; }"
  }'
```

**Step 4: Validate return type**

Ensure a value matches a declared type definition.

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/validate/return-type" \
  -H "Content-Type: application/json" \
  -d '{
    "typeDefinition": "{ status: string; count: number }",
    "value": {"status": "active", "count": 42}
  }'
```

**Step 5: Validate magic comments**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/validate/magic-comments" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "// @method GET\n// @returns { message: string }\nexport default function handler() {\n  return { message: \"hello\" };\n}"
  }'
```

**Step 6: Full script validation**

Run all validations in a single call.

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/validate/script" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "export default function handler(req: Request) {\n  return { ok: true };\n}"
  }'
```

---

### Workflow 3: Template-Based Script Generation

Use templates to scaffold new scripts from predefined patterns.

**Step 1: List available templates**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/templates/list"
```

**Step 2: Preview a template**

See what a template generates before committing.

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/templates/preview?name=webhook-handler"
```

**Step 3: Generate a script from a template**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/templates/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "webhook-handler"
  }'
```

**Step 4: Create a custom template**

Save your own reusable template.

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/templates/create-custom" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "etl-pipeline",
    "content": "export default async function handler(req: Request) {\n  const input = await req.json();\n  const transformed = transform(input);\n  return { result: transformed, processedAt: new Date().toISOString() };\n}\n\nfunction transform(data: any) {\n  return data;\n}"
  }'
```

**Step 5: Update a custom template**

```
curl -s -X PUT "${EXEC_BASE_URL}/api/v1/exec/templates/update-custom/etl-pipeline" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "export default async function handler(req: Request) {\n  const input = await req.json();\n  const transformed = transform(input);\n  return { result: transformed, processedAt: new Date().toISOString(), version: 2 };\n}\n\nfunction transform(data: any) {\n  return { ...data, enriched: true };\n}"
  }'
```

**Step 6: Delete a custom template**

```
curl -s -X DELETE "${EXEC_BASE_URL}/api/v1/exec/templates/delete-custom/etl-pipeline"
```

---

### Workflow 4: Dependency Management

Install and manage npm packages that scripts depend on.

**Step 1: Check bundled dependencies**

See what packages are already available.

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/dependencies/bundled"
```

**Step 2: Check if specific dependencies are needed**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/dependencies/check" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import { z } from \"zod\";\nimport { format } from \"date-fns\";\nexport default function handler() { return { ok: true }; }"
  }'
```

**Step 3: Install missing dependencies**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/dependencies/install" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import { z } from \"zod\";\nexport default function handler() { return { ok: true }; }"
  }'
```

**Step 4: Package management — read current package.json**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/package/read"
```

**Step 5: Initialize package.json**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/package/init" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-exec-scripts",
    "version": "1.0.0"
  }'
```

**Step 6: Install a specific package**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/package/install" \
  -H "Content-Type: application/json" \
  -d '{
    "packages": ["zod", "date-fns"]
  }'
```

**Step 7: Update packages**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/package/update" \
  -H "Content-Type: application/json" \
  -d '{
    "packages": ["zod"]
  }'
```

**Step 8: Compare package versions**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/package/compare" \
  -H "Content-Type: application/json" \
  -d '{
    "packages": ["zod", "date-fns"]
  }'
```

**Step 9: Pin a package version**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/package/pin" \
  -H "Content-Type: application/json" \
  -d '{
    "package": "zod",
    "version": "3.22.0"
  }'
```

---

### Workflow 5: Logging and Debugging

Monitor script execution, read logs, and debug issues.

**Step 1: List available log files**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/logs/list"
```

**Step 2: Read a specific log file**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/logs/read" \
  -H "Content-Type: application/json" \
  -d '{
    "file": "exec-2025-01-15.log"
  }'
```

**Step 3: Stream logs in real-time**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/logs/stream?file=exec-2025-01-15.log"
```

**Step 4: Search logs for specific patterns**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/logs/search" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "error",
    "file": "exec-2025-01-15.log"
  }'
```

**Step 5: Clear logs when debugging is complete**

```
curl -s -X DELETE "${EXEC_BASE_URL}/api/v1/exec/logs/clear"
```

---

### Workflow 6: Route Discovery and Resolution

Understand how URL paths map to script files using Next.js-style routing.

**Step 1: Discover all available routes**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/route/discover" \
  -H "Content-Type: application/json" \
  -d '{}'
```

This returns all routes classified as static, dynamic (`[param]`), catch-all (`[...slug]`), or optional catch-all (`[[...path]]`).

**Step 2: Resolve a specific URL path to its handler script**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/route/resolve" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/users/123/posts"
  }'
```

**Step 3: Test multiple paths in batch**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/route/test" \
  -H "Content-Type: application/json" \
  -d '{
    "paths": ["/users", "/users/123", "/users/123/posts", "/unknown"]
  }'
```

---

### Workflow 7: Shared State Management

Use the shared state store for inter-script communication and stateful operations.

**Step 1: Set a value in shared state**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/shared-state/set" \
  -H "Content-Type: application/json" \
  -d '{
    "hostname": "api.example.com",
    "value": {"requestCount": 0, "lastReset": "2025-01-15T00:00:00Z", "config": {"rateLimit": 100}}
  }'
```

**Step 2: Retrieve the shared state**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/shared-state/get" \
  -H "Content-Type: application/json" \
  -d '{
    "hostname": "api.example.com"
  }'
```

**Step 3: Clear shared state**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/shared-state/clear" \
  -H "Content-Type: application/json" \
  -d '{
    "hostname": "api.example.com"
  }'
```

---

### Workflow 8: Magic Comments Configuration

Configure script behavior through inline comment annotations.

**Step 1: Read the magic comments schema**

Understand what annotations are available.

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/magic-comments/schema"
```

**Step 2: Read current magic comments from a script**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/magic-comments/read?path=greeting.ts"
```

**Step 3: Update magic comments for a single script**

```
curl -s -X PUT "${EXEC_BASE_URL}/api/v1/exec/magic-comments/update" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "greeting.ts",
    "comments": {
      "method": "POST",
      "returns": "{ message: string; timestamp: string }"
    }
  }'
```

**Step 4: Bulk update magic comments across multiple scripts**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/magic-comments/bulk-update" \
  -H "Content-Type: application/json" \
  -d '{
    "updates": [
      {"path": "greeting.ts", "comments": {"method": "POST"}},
      {"path": "health.ts", "comments": {"method": "GET"}}
    ]
  }'
```

---

### Workflow 9: Monitoring and Performance

Track active requests, script performance, and system metrics.

**Step 1: Check active requests**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/monitor/active-requests"
```

**Step 2: List monitored scripts**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/monitor/scripts"
```

**Step 3: Get script performance data**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/monitor/script-performance" \
  -H "Content-Type: application/json" \
  -d '{
    "script": "greeting.ts"
  }'
```

**Step 4: Get overall monitoring stats**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/monitor/stats"
```

**Step 5: Export Prometheus metrics**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/monitor/metrics"
```

---

### Workflow 10: Scheduled Script Execution

Set up cron-based script execution.

**Step 1: List all schedules**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/schedules/list"
```

**Step 2: Trigger a schedule manually**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/schedules/trigger" \
  -H "Content-Type: application/json" \
  -d '{
    "scheduleId": "daily-report"
  }'
```

**Step 3: Reload schedules from configuration**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/schedules/reload" \
  -H "Content-Type: application/json" \
  -d '{}'
```

**Step 4: View schedule execution history**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/schedules/history"
```

---

### Workflow 11: OpenAPI Specification Generation

Generate OpenAPI specs from your scripts for documentation and client generation.

**Step 1: List scripts with schema information**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/user-openapi/list"
```

**Step 2: Get the OpenAPI schema definition**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/user-openapi/schema"
```

**Step 3: Generate OpenAPI spec from scripts**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/user-openapi/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "scripts": ["greeting.ts", "health.ts"]
  }'
```

**Step 4: Get the live OpenAPI spec**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/user-openapi/spec"
```

**Step 5: Validate a script's schema file**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/user-openapi/validate" \
  -H "Content-Type: application/json" \
  -d '{
    "script": "greeting.ts"
  }'
```

**Step 6: Merge multiple OpenAPI specs**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/user-openapi/merge" \
  -H "Content-Type: application/json" \
  -d '{
    "specs": ["spec-1.json", "spec-2.json"]
  }'
```

---

### Workflow 12: SDK Management

Import and manage SDK integrations.

**Step 1: List available SDKs**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/sdk/list"
```

**Step 2: Import an SDK**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/sdk/import" \
  -H "Content-Type: application/json" \
  -d '{
    "source": "https://example.com/sdk-spec.json"
  }'
```

**Step 3: Get SDK details by ID**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/sdk/my-sdk-id"
```

**Step 4: Delete an SDK**

```
curl -s -X DELETE "${EXEC_BASE_URL}/api/v1/exec/sdk/my-sdk-id"
```

---

## Advanced Operations

### Advanced Workflow 1: Full Deployment Pipeline

A complete workflow from script creation to production-ready endpoint with validation, dependency management, and monitoring.

**Phase 1: Environment Preparation**

```
# Check current health
curl -s "${EXEC_BASE_URL}/api/v1/exec/health"

# Check bundled dependencies
curl -s "${EXEC_BASE_URL}/api/v1/exec/dependencies/bundled"

# Review existing scripts
curl -s "${EXEC_BASE_URL}/api/v1/exec/scripts/list"
```

**Phase 2: Script Development and Validation**

```
# Write the script
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "api/users.ts",
    "content": "import { z } from \"zod\";\n\nconst UserSchema = z.object({\n  name: z.string().min(1),\n  email: z.string().email(),\n  role: z.enum([\"admin\", \"user\", \"viewer\"])\n});\n\nexport default async function handler(req: Request) {\n  const body = await req.json();\n  const parsed = UserSchema.safeParse(body);\n  if (!parsed.success) {\n    return { error: parsed.error.issues, status: 400 };\n  }\n  return { user: parsed.data, created: true, id: crypto.randomUUID() };\n}"
  }'

# Validate TypeScript (see Workflow 2 for standalone examples; same UserSchema code as above)
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/validate/typescript" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import { z } from \"zod\";\n\nconst UserSchema = z.object({\n  name: z.string().min(1),\n  email: z.string().email(),\n  role: z.enum([\"admin\", \"user\", \"viewer\"])\n});\n\nexport default async function handler(req: Request) {\n  const body = await req.json();\n  const parsed = UserSchema.safeParse(body);\n  if (!parsed.success) {\n    return { error: parsed.error.issues, status: 400 };\n  }\n  return { user: parsed.data, created: true, id: crypto.randomUUID() };\n}"
  }'

# Check dependencies
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/dependencies/check" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import { z } from \"zod\";\nexport default function handler() { return { ok: true }; }"
  }'

# Install if needed
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/dependencies/install" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import { z } from \"zod\";\nexport default function handler() { return { ok: true }; }"
  }'
```

**Phase 3: Test Execution**

```
# Execute with valid data
curl -s -X POST "${EXEC_BASE_URL}/api/users" \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice", "email": "alice@example.com", "role": "admin"}'

# Execute with invalid data to test validation
curl -s -X POST "${EXEC_BASE_URL}/api/users" \
  -H "Content-Type: application/json" \
  -d '{"name": "", "email": "not-an-email", "role": "superadmin"}'
```

**Phase 4: Route Verification**

```
# Verify routing resolves correctly
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/route/resolve" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/api/users"
  }'

# Discover all routes
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/route/discover" \
  -H "Content-Type: application/json" \
  -d '{}'
```

**Phase 5: Monitoring Setup**

```
# Check script performance
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/monitor/script-performance" \
  -H "Content-Type: application/json" \
  -d '{
    "script": "api/users.ts"
  }'

# Generate OpenAPI documentation
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/user-openapi/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "scripts": ["api/users.ts"]
  }'
```

---

### Advanced Workflow 2: Script Chaining Pattern

Create scripts that call other scripts to build composable workflows.

**Step 1: Create utility scripts**

```
# Create a data fetching script
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "utils/fetch-data.ts",
    "content": "export default async function handler(req: Request) {\n  const { url } = await req.json();\n  const response = await fetch(url);\n  const data = await response.json();\n  return { data, status: response.status, fetchedAt: new Date().toISOString() };\n}"
  }'

# Create a transformation script
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "utils/transform.ts",
    "content": "export default async function handler(req: Request) {\n  const { data, fields } = await req.json();\n  const result = Array.isArray(data)\n    ? data.map((item: any) => {\n        const picked: any = {};\n        fields.forEach((f: string) => { if (item[f] !== undefined) picked[f] = item[f]; });\n        return picked;\n      })\n    : data;\n  return { result, count: Array.isArray(result) ? result.length : 1 };\n}"
  }'

# Create a pipeline script that chains them
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "pipeline/etl.ts",
    "content": "export default async function handler(req: Request) {\n  const { sourceUrl, fields } = await req.json();\n  const baseUrl = \"http://localhost:3000\";\n  const fetchRes = await fetch(`${baseUrl}/utils/fetch-data`, {\n    method: \"POST\",\n    headers: { \"Content-Type\": \"application/json\" },\n    body: JSON.stringify({ url: sourceUrl })\n  });\n  const fetched = await fetchRes.json();\n  const transformRes = await fetch(`${baseUrl}/utils/transform`, {\n    method: \"POST\",\n    headers: { \"Content-Type\": \"application/json\" },\n    body: JSON.stringify({ data: fetched.data, fields })\n  });\n  const transformed = await transformRes.json();\n  return { pipeline: \"etl\", source: sourceUrl, result: transformed };\n}"
  }'
```

**Step 2: Execute the pipeline**

```
curl -s -X POST "${EXEC_BASE_URL}/pipeline/etl" \
  -H "Content-Type: application/json" \
  -d '{
    "sourceUrl": "https://jsonplaceholder.typicode.com/users",
    "fields": ["id", "name", "email"]
  }'
```

---

### Advanced Workflow 3: Error Recovery and Cache Management

Handle failures gracefully and manage the execution cache.

**Step 1: Clear the execution cache**

When scripts behave unexpectedly after updates, clear the cache to force fresh compilation.

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/cache/clear" \
  -H "Content-Type: application/json" \
  -d '{}'
```

**Step 2: Restart the execution system**

For more severe issues, trigger a full system restart.

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/system/restart" \
  -H "Content-Type: application/json" \
  -d '{}'
```

**Step 3: Monitor restart progress**

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/system/restart-status"
```

**Step 4: Verify recovery**

```
# Check health
curl -s "${EXEC_BASE_URL}/api/v1/exec/health"

# Verify scripts are still present
curl -s "${EXEC_BASE_URL}/api/v1/exec/scripts/list"

# Test a known endpoint
curl -s -X POST "${EXEC_BASE_URL}/greeting" \
  -H "Content-Type: application/json" \
  -d '{"name": "Recovery Test"}'
```

---

### Advanced Workflow 4: Script File Management

Organize scripts into directories, move them, and manage the file tree.

**Step 1: View the script directory tree**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/tree" \
  -H "Content-Type: application/json" \
  -d '{}'
```

**Step 2: Create scripts in subdirectories**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "api/v2/users/list.ts",
    "content": "export default function handler() {\n  return { users: [], version: 2 };\n}"
  }'
```

**Step 3: Move a script to a new location**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/move" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "greeting.ts",
    "to": "api/v1/greeting.ts"
  }'
```

**Step 4: Verify the move and updated routing**

```
# Old path should no longer resolve
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/route/resolve" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/greeting"
  }'

# New path should resolve
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/route/resolve" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/api/v1/greeting"
  }'
```

---

### Advanced Workflow 5: Dynamic Routing with Parameters

Leverage Next.js-style dynamic routing for parameterized endpoints.

**Step 1: Create a dynamic route script**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "users/[id].ts",
    "content": "export default function handler(req: Request, params: { id: string }) {\n  return { userId: params.id, fetched: true, timestamp: new Date().toISOString() };\n}"
  }'
```

**Step 2: Create a catch-all route script**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "docs/[...slug].ts",
    "content": "export default function handler(req: Request, params: { slug: string[] }) {\n  return { path: params.slug.join(\"/\"), sections: params.slug };\n}"
  }'
```

**Step 3: Test dynamic route resolution**

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/route/test" \
  -H "Content-Type: application/json" \
  -d '{
    "paths": ["/users/42", "/users/abc", "/docs/getting-started", "/docs/api/reference/auth"]
  }'
```

**Step 4: Execute the dynamic endpoints**

```
# Dynamic segment
curl -s -X POST "${EXEC_BASE_URL}/users/42" \
  -H "Content-Type: application/json" \
  -d '{}'

# Catch-all route
curl -s -X POST "${EXEC_BASE_URL}/docs/api/reference/auth" \
  -H "Content-Type: application/json" \
  -d '{}'
```

---

### Performance Considerations

**Cache Management**: The execution cache stores compiled scripts for fast execution. After bulk script updates, clear the cache to ensure consistency:

```
curl -s -X POST "${EXEC_BASE_URL}/api/v1/exec/cache/clear" \
  -H "Content-Type: application/json" \
  -d '{}'
```

**Dependency Pre-installation**: Install dependencies before deploying scripts to avoid cold-start delays during first execution. Use the dependencies/install endpoint with representative code that imports all needed packages.

**Monitoring for Bottlenecks**: Regularly check script performance to identify slow endpoints:

```
curl -s "${EXEC_BASE_URL}/api/v1/exec/monitor/stats"
curl -s "${EXEC_BASE_URL}/api/v1/exec/monitor/active-requests"
```

**Shared State Scope**: Shared state is keyed by hostname. Use distinct hostnames for different logical contexts to avoid key collisions between unrelated scripts.

**Log Rotation**: Clear logs periodically to prevent disk space issues in the container:

```
curl -s -X DELETE "${EXEC_BASE_URL}/api/v1/exec/logs/clear"
```

---

## Quick Reference

### Health and System

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/health` | Service health check |
| POST | `/api/v1/exec/system/restart` | Restart execution system |
| GET | `/api/v1/exec/system/restart-status` | Check restart progress |
| POST | `/api/v1/exec/cache/clear` | Clear execution cache |

### Script Execution

| Method | Path | Purpose |
|--------|------|---------|
| POST | `/{path}` | Execute a script (path = script file path without extension) |

> **Note:** Script execution uses the base service URL directly (e.g., `POST /greeting`), NOT the `/api/v1/exec` prefix. The `/api/v1/exec` path is reserved for management endpoints only.

### Script Management

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/scripts/list` | List all scripts |
| GET | `/api/v1/exec/scripts/read?path={path}` | Read script content |
| POST | `/api/v1/exec/scripts/write` | Create or update script (requires: `path`, `content`) |
| DELETE | `/api/v1/exec/scripts/delete?path={path}` | Delete a script |
| POST | `/api/v1/exec/scripts/tree` | Get directory tree |
| POST | `/api/v1/exec/scripts/move` | Move/rename script (requires: `from`, `to`) |

### Validation

| Method | Path | Required Fields |
|--------|------|-----------------|
| POST | `/api/v1/exec/validate/typescript` | `code` |
| POST | `/api/v1/exec/validate/syntax` | `code` |
| POST | `/api/v1/exec/validate/dependencies` | `code` |
| POST | `/api/v1/exec/validate/return-type` | `typeDefinition`, `value` |
| POST | `/api/v1/exec/validate/magic-comments` | `code` |
| POST | `/api/v1/exec/validate/script` | `code` |

### Templates

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/templates/list` | List templates |
| GET | `/api/v1/exec/templates/preview?name={name}` | Preview template |
| POST | `/api/v1/exec/templates/generate` | Generate from template (requires: `name`) |
| POST | `/api/v1/exec/templates/create-custom` | Create custom template |
| PUT | `/api/v1/exec/templates/update-custom/{name}` | Update custom template |
| DELETE | `/api/v1/exec/templates/delete-custom/{name}` | Delete custom template |

### Dependencies and Packages

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/dependencies/bundled` | List bundled dependencies |
| POST | `/api/v1/exec/dependencies/check` | Check script dependencies (requires: `code`) |
| POST | `/api/v1/exec/dependencies/install` | Install dependencies (requires: `code`) |
| GET | `/api/v1/exec/package/read` | Read package.json |
| POST | `/api/v1/exec/package/init` | Initialize package.json |
| POST | `/api/v1/exec/package/install` | Install packages |
| POST | `/api/v1/exec/package/update` | Update packages |
| POST | `/api/v1/exec/package/compare` | Compare package versions |
| POST | `/api/v1/exec/package/pin` | Pin package version |

### Logs

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/logs/list` | List log files |
| POST | `/api/v1/exec/logs/read` | Read log file |
| GET | `/api/v1/exec/logs/stream?file={file}` | Stream logs |
| POST | `/api/v1/exec/logs/search` | Search logs |
| DELETE | `/api/v1/exec/logs/clear` | Clear all logs |

### Routing

| Method | Path | Purpose |
|--------|------|---------|
| POST | `/api/v1/exec/route/resolve` | Resolve URL to script |
| POST | `/api/v1/exec/route/discover` | Discover all routes |
| POST | `/api/v1/exec/route/test` | Batch test routes |

### Shared State

| Method | Path | Required Fields |
|--------|------|-----------------|
| POST | `/api/v1/exec/shared-state/get` | `hostname` |
| POST | `/api/v1/exec/shared-state/set` | `hostname`, `value` |
| POST | `/api/v1/exec/shared-state/clear` | `hostname` |

### Monitoring

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/monitor/active-requests` | Active requests |
| GET | `/api/v1/exec/monitor/scripts` | Monitored scripts |
| POST | `/api/v1/exec/monitor/script-performance` | Script performance |
| GET | `/api/v1/exec/monitor/metrics` | Prometheus metrics |
| GET | `/api/v1/exec/monitor/stats` | System stats |

### Schedules

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/schedules/list` | List schedules |
| POST | `/api/v1/exec/schedules/trigger` | Trigger schedule |
| POST | `/api/v1/exec/schedules/reload` | Reload schedules |
| GET | `/api/v1/exec/schedules/history` | Schedule history |

### Magic Comments

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/magic-comments/schema` | Get annotation schema |
| GET | `/api/v1/exec/magic-comments/read?path={path}` | Read script annotations |
| PUT | `/api/v1/exec/magic-comments/update` | Update annotations |
| POST | `/api/v1/exec/magic-comments/bulk-update` | Bulk update annotations |

### SDK

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/sdk/list` | List SDKs |
| POST | `/api/v1/exec/sdk/import` | Import SDK |
| GET | `/api/v1/exec/sdk/{id}` | Get SDK details |
| DELETE | `/api/v1/exec/sdk/{id}` | Delete SDK |

### User OpenAPI

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/v1/exec/user-openapi/list` | List scripts with schemas |
| GET | `/api/v1/exec/user-openapi/schema` | Get schema definition |
| POST | `/api/v1/exec/user-openapi/generate` | Generate OpenAPI spec |
| GET | `/api/v1/exec/user-openapi/spec` | Live OpenAPI spec |
| POST | `/api/v1/exec/user-openapi/validate` | Validate schema |
| POST | `/api/v1/exec/user-openapi/merge` | Merge specs |

### Essential Response Patterns

**Success response** (typical):

```
{
  "success": true,
  "data": {}
}
```

**Error response** (typical):

```
{
  "success": false,
  "error": "Description of what went wrong"
}
```

**Script execution response**: The return value of the script's default export function is serialized as JSON directly. No wrapper envelope — the script's return value IS the response body.

### Base URL Reminder

Replace `EXEC_BASE_URL` in all examples with:

```
https://{projectId}-{containerId}-exec-{serviceId}.{node}.containers.hoody.icu
```

Obtain these values from container discovery as described in the core SKILL.md. Do NOT use `api.hoody.com` or `api.hoody.icu` for hoody-exec endpoints.