<!--
hoody-exec Subskill (http)
Auto-generated by Hoody Skills Generator
Generated: 2026-06-20T00:36:35.454Z
Model: mimo-v2.5-pro
Mode: http


Tokens: 20020

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

```
# hoody-exec Subskill

## 1. Overview

### What is hoody-exec?

hoody-exec is Hoody's script-to-API execution service. It turns any TypeScript or JavaScript file into an HTTP API endpoint using a Bun-powered runtime. Drop a script file in the scripts directory, and it becomes a live API endpoint — no build step, no deployment pipeline, no container restart.

### When to Use hoody-exec

- **Instant API endpoints**: Deploy REST APIs from TypeScript/JavaScript files
- **Webhook handlers**: Receive and process incoming webhooks with automatic JSON parsing
- **Data transformation**: Build ETL pipelines as script chains
- **Script composition**: Call between exec scripts to compose multi-step workflows
- **Monitoring endpoints**: Return structured JSON from system monitoring scripts
- **Scheduled tasks**: Run scripts on cron schedules
- **Shared state management**: Store and retrieve state across script executions

### How It Fits Into Hoody Philosophy

hoody-exec embodies the "script-first" principle: you write code, the platform handles everything else. No configuration files, no infrastructure setup, no deployment rituals. The service provides:

- Automatic routing based on file path (Next.js-style dynamic routing)
- Built-in dependency management via Bun
- Real-time log streaming and search
- Template-based scaffolding for common patterns
- Shared state for cross-script coordination
- OpenAPI spec generation from script metadata

### Service Architecture

```
Scripts Directory/
├── api/
│   ├── users.ts          → POST /api/users
│   ├── health.ts         → POST /api/health
│   └── webhook.ts        → POST /api/webhook
├── data/
│   └── transform.ts      → POST /data/transform
└── utils/
    └── [id].ts           → POST /utils/:id (dynamic route)
```

Every `.js` or `.ts` file becomes an endpoint at its corresponding path. The script's default export function receives the request context and returns the response.

### Base URL

All hoody-exec endpoints use this base URL pattern:

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

**Example base URL** (used in all examples below):

```
https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com
```

Replace with your actual project, container, service, and node values from Hoody Kit discovery.

---

## 2. Common Workflows

### 2.1 Script Lifecycle: Create, Execute, Verify

This is the fundamental workflow — create a script, execute it, and verify the output.

#### Step 1: List Existing Scripts

```
EXEC_BASE="https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com"

curl -s "$EXEC_BASE/api/v1/exec/scripts/list"
```

Response:

```
{
  "scripts": [
    {
      "path": "api/health.ts",
      "size": 245,
      "modified": "2025-01-15T10:30:00Z"
    }
  ]
}
```

#### Step 2: Write a New Script

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

Response:

```
{
  "success": true,
  "path": "api/greeting.ts"
}
```

#### Step 3: Execute the Script

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

Response:

```
{
  "message": "Hello, World!",
  "timestamp": "2025-01-15T10:35:00Z"
}
```

#### Step 4: Read Script Contents

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

Response:

```
{
  "path": "api/greeting.ts",
  "content": "export default async function(req: Request) {\n  const body = await req.json();\n  return { message: `Hello, ${body.name}!`, timestamp: new Date().toISOString() };\n}"
}
```

#### Step 5: Delete the Script

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

Response:

```
{
  "success": true,
  "deleted": "api/greeting.ts"
}
```

---

### 2.2 Script Directory Management

#### Get Script Tree Structure

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/scripts/tree"
```

Response:

```
{
  "tree": {
    "name": "scripts",
    "type": "directory",
    "children": [
      {
        "name": "api",
        "type": "directory",
        "children": [
          {
            "name": "health.ts",
            "type": "file",
            "path": "api/health.ts"
          }
        ]
      }
    ]
  }
}
```

#### Move/Rename a Script

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

Response:

```
{
  "success": true,
  "from": "api/old-name.ts",
  "to": "api/new-name.ts"
}
```

---

### 2.3 Script Validation Workflow

Before deploying, validate scripts for correctness. The validation suite covers TypeScript types, syntax, dependencies, return types, and magic comments.

#### Validate TypeScript

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

Response:

```
{
  "valid": true,
  "errors": []
}
```

#### Validate Syntax

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

Response:

```
{
  "valid": true,
  "errors": []
}
```

#### Validate Dependencies

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/validate/dependencies" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import lodash from \"lodash\";\nexport default function() { return lodash.isEmpty({}); }"
  }'
```

Response:

```
{
  "valid": false,
  "missing": ["lodash"],
  "errors": ["Module lodash is not installed"]
}
```

#### Validate Return Type

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/validate/return-type" \
  -H "Content-Type: application/json" \
  -d '{
    "typeDefinition": "{ id: number; name: string; active: boolean }",
    "value": {
      "id": 1,
      "name": "test",
      "active": true
    }
  }'
```

Response:

```
{
  "valid": true,
  "errors": []
}
```

#### Validate Magic Comments

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/validate/magic-comments" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "// @method GET\n// @path /api/users\nexport default function() { return []; }"
  }'
```

Response:

```
{
  "valid": true,
  "errors": []
}
```

#### Full Script Validation

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/validate/script" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "export default async function(req: Request) {\n  const data = await fetch(\"https://api.example.com/data\");\n  return data.json();\n}"
  }'
```

Response:

```
{
  "valid": true,
  "errors": [],
  "warnings": []
}
```

---

### 2.4 Template Workflow

Templates provide scaffolding for common script patterns.

#### List Available Templates

```
curl -s "$EXEC_BASE/api/v1/exec/templates/list"
```

Response:

```
{
  "templates": [
    {
      "name": "api-endpoint",
      "description": "Basic REST API endpoint",
      "builtin": true
    },
    {
      "name": "webhook-handler",
      "description": "Webhook receiver with validation",
      "builtin": true
    }
  ]
}
```

#### Preview a Template

```
curl -s "$EXEC_BASE/api/v1/exec/templates/preview?name=api-endpoint"
```

Response:

```
{
  "name": "api-endpoint",
  "content": "// @method POST\n// @path /api/resource\nexport default async function(req: Request) {\n  const body = await req.json();\n  return { success: true, data: body };\n}"
}
```

#### Generate Script from Template

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

Response:

```
{
  "success": true,
  "path": "api-endpoint.ts",
  "content": "// @method POST\n// @path /api/resource\nexport default async function(req: Request) {\n  const body = await req.json();\n  return { success: true, data: body };\n}"
}
```

#### Create Custom Template

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/templates/create-custom" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-etl-pipeline",
    "description": "ETL pipeline with logging",
    "content": "// @method POST\n// @path /api/etl\nexport default async function(req: Request) {\n  const input = await req.json();\n  const transformed = transformData(input);\n  return { success: true, result: transformed };\n}\n\nfunction transformData(data: any) {\n  return { ...data, processed: true, timestamp: new Date().toISOString() };\n}"
  }'
```

Response:

```
{
  "success": true,
  "name": "my-etl-pipeline"
}
```

#### Update Custom Template

```
curl -s -X PUT "$EXEC_BASE/api/v1/exec/templates/update-custom/my-etl-pipeline" \
  -H "Content-Type: application/json" \
  -d '{
    "description": "Updated ETL pipeline with retry logic",
    "content": "// @method POST\n// @path /api/etl\nexport default async function(req: Request) {\n  const input = await req.json();\n  return { processed: true };\n}"
  }'
```

Response:

```
{
  "success": true,
  "name": "my-etl-pipeline"
}
```

#### Delete Custom Template

```
curl -s -X DELETE "$EXEC_BASE/api/v1/exec/templates/delete-custom/my-etl-pipeline"
```

Response:

```
{
  "success": true,
  "deleted": "my-etl-pipeline"
}
```

---

### 2.5 Dependency Management

#### Check Bundled Dependencies

```
curl -s "$EXEC_BASE/api/v1/exec/dependencies/bundled"
```

Response:

```
{
  "dependencies": [
    "bun:ffi",
    "bun:sqlite",
    "lodash",
    "date-fns",
    "zod"
  ]
}
```

#### Check Script Dependencies

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

Response:

```
{
  "installed": ["zod"],
  "missing": ["axios"],
  "bundled": ["zod"]
}
```

#### Install Dependencies

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/dependencies/install" \
  -H "Content-Type: application/json" \
  -d '{
    "dependencies": ["axios", "cheerio"]
  }'
```

Response:

```
{
  "success": true,
  "installed": ["axios", "cheerio"]
}
```

---

### 2.6 Package Management

#### Initialize Package

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/package/init"
```

Response:

```
{
  "success": true,
  "packageJson": {
    "name": "hoody-exec-scripts",
    "version": "1.0.0",
    "dependencies": {}
  }
}
```

#### Read Package Configuration

```
curl -s "$EXEC_BASE/api/v1/exec/package/read"
```

Response:

```
{
  "packageJson": {
    "name": "hoody-exec-scripts",
    "version": "1.0.0",
    "dependencies": {
      "axios": "^1.6.0",
      "zod": "^3.22.0"
    }
  }
}
```

#### Install Package Dependencies

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

Response:

```
{
  "success": true,
  "installed": {
    "date-fns": "3.3.0"
  }
}
```

#### Update Package

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/package/update" \
  -H "Content-Type: application/json" \
  -d '{
    "package": "axios"
  }'
```

Response:

```
{
  "success": true,
  "package": "axios",
  "from": "1.6.0",
  "to": "1.6.5"
}
```

#### Compare Package Versions

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/package/compare" \
  -H "Content-Type: application/json" \
  -d '{
    "package": "axios"
  }'
```

Response:

```
{
  "package": "axios",
  "current": "1.6.0",
  "latest": "1.6.5",
  "updateAvailable": true
}
```

#### Pin Package Version

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

Response:

```
{
  "success": true,
  "package": "axios",
  "pinnedVersion": "1.6.0"
}
```

---

### 2.7 Route Discovery and Resolution

hoody-exec uses Next.js-style dynamic routing. Scripts can define static routes, dynamic segments, catch-all routes, and optional catch-all routes.

#### Discover All Routes

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/route/discover"
```

Response:

```
{
  "routes": [
    {
      "path": "api/health.ts",
      "route": "/api/health",
      "type": "static"
    },
    {
      "path": "api/users/[id].ts",
      "route": "/api/users/:id",
      "type": "dynamic"
    },
    {
      "path": "api/docs/[...slug].ts",
      "route": "/api/docs/*",
      "type": "catch-all"
    }
  ]
}
```

#### Resolve a URL Path to Script

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

Response:

```
{
  "script": "api/users/[id].ts",
  "route": "/api/users/:id",
  "type": "dynamic",
  "params": {
    "id": "42"
  }
}
```

#### Test Multiple Routes (Batch)

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

Response:

```
{
  "results": [
    {
      "path": "/api/health",
      "resolved": true,
      "script": "api/health.ts",
      "type": "static"
    },
    {
      "path": "/api/users/123",
      "resolved": true,
      "script": "api/users/[id].ts",
      "type": "dynamic",
      "params": { "id": "123" }
    },
    {
      "path": "/api/unknown/path",
      "resolved": false,
      "error": "No matching route found"
    }
  ]
}
```

---

### 2.8 Log Management

#### List Available Logs

```
curl -s "$EXEC_BASE/api/v1/exec/logs/list"
```

Response:

```
{
  "logs": [
    {
      "file": "exec-2025-01-15.log",
      "size": 15240,
      "modified": "2025-01-15T23:59:00Z"
    },
    {
      "file": "exec-2025-01-14.log",
      "size": 42180,
      "modified": "2025-01-14T23:59:00Z"
    }
  ]
}
```

#### Read a Specific Log

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

Response:

```
{
  "file": "exec-2025-01-15.log",
  "content": "[2025-01-15T10:30:00Z] POST /api/users - 200 - 12ms\n[2025-01-15T10:30:05Z] POST /api/greeting - 200 - 3ms"
}
```

#### Stream Logs (SSE)

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

This returns a Server-Sent Events stream:

```
data: {"timestamp":"2025-01-15T10:30:00Z","level":"info","message":"POST /api/users - 200 - 12ms"}

data: {"timestamp":"2025-01-15T10:30:05Z","level":"info","message":"POST /api/greeting - 200 - 3ms"}
```

#### Search Logs

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/logs/search" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "error",
    "limit": 20
  }'
```

Response:

```
{
  "results": [
    {
      "file": "exec-2025-01-15.log",
      "line": 142,
      "content": "[2025-01-15T14:22:00Z] ERROR POST /api/import - 500 - TypeError: Cannot read property",
      "timestamp": "2025-01-15T14:22:00Z"
    }
  ],
  "total": 1
}
```

#### Clear Logs

```
curl -s -X DELETE "$EXEC_BASE/api/v1/exec/logs/clear"
```

Response:

```
{
  "success": true,
  "cleared": 3,
  "freedBytes": 128400
}
```

---

### 2.9 Shared State Management

Shared state enables scripts to persist data that other scripts can read, useful for caching, counters, and cross-script coordination.

#### Set Shared State

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/shared-state/set" \
  -H "Content-Type: application/json" \
  -d '{
    "hostname": "api-cache",
    "value": {
      "lastRefresh": "2025-01-15T10:00:00Z",
      "itemCount": 1542,
      "status": "active"
    }
  }'
```

Response:

```
{
  "success": true,
  "hostname": "api-cache"
}
```

#### Get Shared State

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

Response:

```
{
  "hostname": "api-cache",
  "value": {
    "lastRefresh": "2025-01-15T10:00:00Z",
    "itemCount": 1542,
    "status": "active"
  }
}
```

#### Clear Shared State

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

Response:

```
{
  "success": true,
  "hostname": "api-cache",
  "cleared": true
}
```

---

### 2.10 Scheduled Tasks (Crontab)

#### List Schedules

```
curl -s "$EXEC_BASE/api/v1/exec/schedules/list"
```

Response:

```
{
  "schedules": [
    {
      "id": "sched-001",
      "script": "api/cleanup.ts",
      "cron": "0 2 * * *",
      "enabled": true,
      "lastRun": "2025-01-15T02:00:00Z",
      "nextRun": "2025-01-16T02:00:00Z"
    }
  ]
}
```

#### Trigger a Schedule Manually

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/schedules/trigger" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "sched-001"
  }'
```

Response:

```
{
  "success": true,
  "scheduleId": "sched-001",
  "triggeredAt": "2025-01-15T15:30:00Z"
}
```

#### View Schedule History

```
curl -s "$EXEC_BASE/api/v1/exec/schedules/history"
```

Response:

```
{
  "history": [
    {
      "scheduleId": "sched-001",
      "script": "api/cleanup.ts",
      "startedAt": "2025-01-15T02:00:00Z",
      "completedAt": "2025-01-15T02:00:12Z",
      "status": "success",
      "duration": 12000
    }
  ]
}
```

#### Reload Schedules

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/schedules/reload"
```

Response:

```
{
  "success": true,
  "reloaded": 3
}
```

---

### 2.11 Magic Comments Configuration

Magic comments in script files control metadata like HTTP method, path, caching, and rate limiting.

#### Read Magic Comments Schema

```
curl -s "$EXEC_BASE/api/v1/exec/magic-comments/schema"
```

Response:

```
{
  "comments": {
    "@method": {
      "description": "HTTP method for the endpoint",
      "values": ["GET", "POST", "PUT", "DELETE", "PATCH"]
    },
    "@path": {
      "description": "Custom path override"
    },
    "@cache": {
      "description": "Cache duration in seconds"
    },
    "@rateLimit": {
      "description": "Requests per minute limit"
    }
  }
}
```

#### Read Magic Comments from Script

```
curl -s "$EXEC_BASE/api/v1/exec/magic-comments/read"
```

Response:

```
{
  "scripts": {
    "api/health.ts": {
      "comments": {
        "@method": "GET",
        "@path": "/api/health"
      }
    },
    "api/users.ts": {
      "comments": {
        "@method": "POST",
        "@path": "/api/users",
        "@cache": "60"
      }
    }
  }
}
```

#### Update Magic Comments for a Script

```
curl -s -X PUT "$EXEC_BASE/api/v1/exec/magic-comments/update" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "api/users.ts",
    "comments": {
      "@method": "GET",
      "@path": "/api/users",
      "@cache": "120",
      "@rateLimit": "100"
    }
  }'
```

Response:

```
{
  "success": true,
  "path": "api/users.ts",
  "comments": {
    "@method": "GET",
    "@path": "/api/users",
    "@cache": "120",
    "@rateLimit": "100"
  }
}
```

#### Bulk Update Magic Comments

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

Response:

```
{
  "success": true,
  "updated": 2,
  "results": [
    { "path": "api/health.ts", "success": true },
    { "path": "api/users.ts", "success": true }
  ]
}
```

---

### 2.12 System Monitoring

#### Get Active Requests

```
curl -s "$EXEC_BASE/api/v1/exec/monitor/active-requests"
```

Response:

```
{
  "activeRequests": [
    {
      "id": "req-abc123",
      "method": "POST",
      "path": "/api/import",
      "startedAt": "2025-01-15T10:30:00Z",
      "duration": 5200
    }
  ],
  "count": 1
}
```

#### List Monitored Scripts

```
curl -s "$EXEC_BASE/api/v1/exec/monitor/scripts"
```

Response:

```
{
  "scripts": [
    {
      "path": "api/health.ts",
      "totalRequests": 15420,
      "avgDuration": 3.2,
      "errorRate": 0.001
    },
    {
      "path": "api/users.ts",
      "totalRequests": 8934,
      "avgDuration": 12.5,
      "errorRate": 0.02
    }
  ]
}
```

#### Get Script Performance

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/monitor/script-performance" \
  -H "Content-Type: application/json" \
  -d '{
    "script": "api/users.ts",
    "period": "24h"
  }'
```

Response:

```
{
  "script": "api/users.ts",
  "period": "24h",
  "metrics": {
    "totalRequests": 8934,
    "avgDuration": 12.5,
    "p95Duration": 45.2,
    "p99Duration": 120.8,
    "errorCount": 178,
    "errorRate": 0.02
  }
}
```

#### Get System Stats

```
curl -s "$EXEC_BASE/api/v1/exec/monitor/stats"
```

Response:

```
{
  "uptime": 864000,
  "totalRequests": 152400,
  "activeConnections": 3,
  "memoryUsage": {
    "rss": 52428800,
    "heapUsed": 31457280,
    "heapTotal": 41943040
  }
}
```

#### Prometheus Metrics Export

```
curl -s "$EXEC_BASE/api/v1/exec/monitor/metrics"
```

Response (text format):

```
# HELP exec_requests_total Total number of requests
# TYPE exec_requests_total counter
exec_requests_total{script="api/health.ts"} 15420
exec_requests_total{script="api/users.ts"} 8934
# HELP exec_request_duration_seconds Request duration in seconds
# TYPE exec_request_duration_seconds histogram
exec_request_duration_seconds_bucket{script="api/health.ts",le="0.01"} 14800
```

---

### 2.13 SDK Management

#### List SDKs

```
curl -s "$EXEC_BASE/api/v1/exec/sdk/list"
```

Response:

```
{
  "sdks": [
    {
      "id": "sdk-001",
      "name": "hoody-client",
      "version": "1.2.0",
      "importedAt": "2025-01-10T00:00:00Z"
    }
  ]
}
```

#### Get SDK by ID

```
curl -s "$EXEC_BASE/api/v1/exec/sdk/sdk-001"
```

Response:

```
{
  "id": "sdk-001",
  "name": "hoody-client",
  "version": "1.2.0",
  "exports": ["createClient", "fetchData", "uploadFile"],
  "importedAt": "2025-01-10T00:00:00Z"
}
```

#### Import an SDK

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/sdk/import" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-utils",
    "code": "export function formatDate(d: Date): string {\n  return d.toISOString();\n}\n\nexport function parseJSON(s: string) {\n  return JSON.parse(s);\n}"
  }'
```

Response:

```
{
  "success": true,
  "id": "sdk-002",
  "name": "my-utils",
  "exports": ["formatDate", "parseJSON"]
}
```

#### Delete SDK

```
curl -s -X DELETE "$EXEC_BASE/api/v1/exec/sdk/sdk-002"
```

Response:

```
{
  "success": true,
  "deleted": "sdk-002"
}
```

---

### 2.14 User OpenAPI Generation

Auto-generate OpenAPI specifications from your scripts' magic comments and type annotations.

#### List Scripts with Schema Info

```
curl -s "$EXEC_BASE/api/v1/exec/user-openapi/list"
```

Response:

```
{
  "scripts": [
    {
      "path": "api/users.ts",
      "method": "GET",
      "route": "/api/users",
      "hasSchema": true,
      "schemaFile": "api/users.schema.ts"
    },
    {
      "path": "api/health.ts",
      "method": "GET",
      "route": "/api/health",
      "hasSchema": false,
      "schemaFile": null
    }
  ]
}
```

#### Generate OpenAPI Spec for a Script

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

Response:

```
{
  "path": "/api/users",
  "method": "get",
  "summary": "List users",
  "responses": {
    "200": {
      "description": "Success",
      "content": {
        "application/json": {
          "schema": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": { "type": "number" },
                "name": { "type": "string" }
              }
            }
          }
        }
      }
    }
  }
}
```

#### Validate a Script's Schema

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

Response:

```
{
  "valid": true,
  "errors": [],
  "warnings": []
}
```

#### Get Full OpenAPI Spec

```
curl -s "$EXEC_BASE/api/v1/exec/user-openapi/spec"
```

Response:

```
{
  "openapi": "3.0.3",
  "info": {
    "title": "hoody-exec API",
    "version": "1.0.0"
  },
  "paths": {
    "/api/users": {
      "get": {
        "summary": "List users",
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    }
  }
}
```

#### Get Schema Definition

```
curl -s "$EXEC_BASE/api/v1/exec/user-openapi/schema"
```

Response:

```
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "openapi": { "type": "string" },
    "info": { "type": "object" },
    "paths": { "type": "object" }
  }
}
```

#### Merge Multiple OpenAPI Specs

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/user-openapi/merge" \
  -H "Content-Type: application/json" \
  -d '{
    "specs": ["api/users.ts", "api/health.ts"]
  }'
```

Response:

```
{
  "openapi": "3.0.3",
  "info": {
    "title": "Merged API",
    "version": "1.0.0"
  },
  "paths": {
    "/api/users": {
      "get": {
        "summary": "List users"
      }
    },
    "/api/health": {
      "get": {
        "summary": "Health check"
      }
    }
  }
}
```

---

### 2.15 Cache and System Operations

#### Clear Execution Cache

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/cache/clear"
```

Response:

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

#### Health Check

```
curl -s "$EXEC_BASE/api/v1/exec/health"
```

Response:

```
{
  "status": "healthy",
  "uptime": 864000,
  "version": "1.0.0",
  "bunVersion": "1.1.0"
}
```

#### Restart System

```
curl -s -X POST "$EXEC_BASE/api/v1/exec/system/restart"
```

Response:

```
{
  "success": true,
  "message": "Restart initiated",
  "restartId": "restart-abc123"
}
```

#### Check Restart Status

```
curl -s "$EXEC_BASE/api/v1/exec/system/restart-status"
```

Response:

```
{
  "status": "ready",
  "lastRestart": "2025-01-15T10:30:00Z",
  "restartId": "restart-abc123",
  "duration": 2500
}
```

---

## 3. Advanced Operations

### 3.1 Multi-Step API Deployment Workflow

Deploy a complete REST API from scratch with validation, testing, and documentation.

#### Phase 1: Setup and Scaffolding

```
EXEC_BASE="https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com"

# Step 1: Verify service is healthy
curl -s "$EXEC_BASE/api/v1/exec/health"

# Step 2: Initialize package and install dependencies
curl -s -X POST "$EXEC_BASE/api/v1/exec/package/init"

curl -s -X POST "$EXEC_BASE/api/v1/exec/dependencies/install" \
  -H "Content-Type: application/json" \
  -d '{
    "dependencies": ["zod"]
  }'
```

#### Phase 2: Create API Scripts

```
# Step 3: Create the main API endpoint
curl -s -X POST "$EXEC_BASE/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "api/data/transform.ts",
    "content": "import { z } from \"zod\";\n\nconst InputSchema = z.object({\n  values: z.array(z.number()),\n  operation: z.enum([\"sum\", \"avg\", \"max\", \"min\"])\n});\n\nexport default async function(req: Request) {\n  const body = await req.json();\n  const input = InputSchema.parse(body);\n  \n  let result: number;\n  switch (input.operation) {\n    case \"sum\": result = input.values.reduce((a, b) => a + b, 0); break;\n    case \"avg\": result = input.values.reduce((a, b) => a + b, 0) / input.values.length; break;\n    case \"max\": result = Math.max(...input.values); break;\n    case \"min\": result = Math.min(...input.values); break;\n  }\n  \n  return { operation: input.operation, result, count: input.values.length };\n}"
  }'

# Step 4: Create a health endpoint
curl -s -X POST "$EXEC_BASE/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "api/status.ts",
    "content": "export default async function() {\n  return {\n    status: \"operational\",\n    timestamp: new Date().toISOString(),\n    version: \"1.0.0\"\n  };\n}"
  }'
```

#### Phase 3: Validate and Test

```
# Step 5: Validate all scripts
curl -s -X POST "$EXEC_BASE/api/v1/exec/validate/typescript" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import { z } from \"zod\";\nconst InputSchema = z.object({ values: z.array(z.number()), operation: z.enum([\"sum\", \"avg\", \"max\", \"min\"]) });\nexport default async function(req: Request) {\n  const body = await req.json();\n  const input = InputSchema.parse(body);\n  return { result: 0 };\n}"
  }'

# Step 6: Execute and test the transform endpoint
curl -s -X POST "$EXEC_BASE/api/data/transform" \
  -H "Content-Type: application/json" \
  -d '{
    "values": [1, 2, 3, 4, 5],
    "operation": "sum"
  }'

# Step 7: Verify route resolution
curl -s -X POST "$EXEC_BASE/api/v1/exec/route/resolve" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/api/data/transform"
  }'
```

#### Phase 4: Generate Documentation

```
# Step 8: Generate OpenAPI spec
curl -s "$EXEC_BASE/api/v1/exec/user-openapi/spec"

# Step 9: Set up monitoring
curl -s "$EXEC_BASE/api/v1/exec/monitor/scripts"
```

---

### 3.2 Script Chain Workflow (Composition)

Execute multiple scripts in sequence, passing results between them.

```
EXEC_BASE="https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com"

# Step 1: Execute first script in chain (data fetch)
curl -s -X POST "$EXEC_BASE/api/data/fetch" \
  -H "Content-Type: application/json" \
  -d '{
    "source": "external-api",
    "endpoint": "https://api.example.com/data"
  }'

# Store result in shared state for downstream scripts
curl -s -X POST "$EXEC_BASE/api/v1/exec/shared-state/set" \
  -H "Content-Type: application/json" \
  -d '{
    "hostname": "pipeline-data",
    "value": {
      "records": [
        { "id": 1, "name": "Item A", "value": 100 },
        { "id": 2, "name": "Item B", "value": 200 }
      ],
      "fetchedAt": "2025-01-15T10:00:00Z"
    }
  }'

# Step 2: Second script reads shared state and transforms
curl -s -X POST "$EXEC_BASE/api/data/transform" \
  -H "Content-Type: application/json" \
  -d '{
    "inputKey": "pipeline-data",
    "transform": "aggregate"
  }'

# Step 3: Final output script
curl -s -X POST "$EXEC_BASE/api/data/export" \
  -H "Content-Type: application/json" \
  -d '{
    "format": "csv",
    "source": "pipeline-data"
  }'
```

---

### 3.3 Dynamic Route with Parameters

Create and use dynamic route scripts with path parameters.

```
EXEC_BASE="https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com"

# Step 1: Create a dynamic route script
curl -s -X POST "$EXEC_BASE/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "api/items/[id].ts",
    "content": "export default async function(req: Request, context: { params: { id: string } }) {\n  const { id } = context.params;\n  return {\n    item: {\n      id: parseInt(id),\n      name: `Item ${id}`,\n      retrieved: new Date().toISOString()\n    }\n  };\n}"
  }'

# Step 2: Test route resolution with parameter extraction
curl -s -X POST "$EXEC_BASE/api/v1/exec/route/resolve" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/api/items/42"
  }'

# Step 3: Execute with the dynamic path
curl -s -X POST "$EXEC_BASE/api/items/42"
```

---

### 3.4 Error Recovery Patterns

#### Script Execution Failure — Diagnose and Fix

```
EXEC_BASE="https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com"

# Step 1: Execute the failing script
curl -s -X POST "$EXEC_BASE/api/data/process" \
  -H "Content-Type: application/json" \
  -d '{"data": "test"}'
# Response might be: { "error": "Module not found: lodash" }

# Step 2: Check logs for details
curl -s -X POST "$EXEC_BASE/api/v1/exec/logs/search" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "error",
    "limit": 10
  }'

# Step 3: Check dependencies
curl -s -X POST "$EXEC_BASE/api/v1/exec/dependencies/check" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import lodash from \"lodash\";\nexport default function() { return lodash.isEmpty({}); }"
  }'

# Step 4: Install missing dependency
curl -s -X POST "$EXEC_BASE/api/v1/exec/dependencies/install" \
  -H "Content-Type: application/json" \
  -d '{
    "dependencies": ["lodash"]
  }'

# Step 5: Clear cache after fix
curl -s -X POST "$EXEC_BASE/api/v1/exec/cache/clear"

# Step 6: Re-execute
curl -s -X POST "$EXEC_BASE/api/data/process" \
  -H "Content-Type: application/json" \
  -d '{"data": "test"}'
```

#### Service Unresponsive — Restart and Verify

```
EXEC_BASE="https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com"

# Step 1: Initiate restart
curl -s -X POST "$EXEC_BASE/api/v1/exec/system/restart"

# Step 2: Poll restart status
curl -s "$EXEC_BASE/api/v1/exec/system/restart-status"
# Wait until status is "ready"

# Step 3: Verify health
curl -s "$EXEC_BASE/api/v1/exec/health"

# Step 4: Verify routes are still available
curl -s -X POST "$EXEC_BASE/api/v1/exec/route/discover"
```

---

### 3.5 Performance Monitoring and Optimization

```
EXEC_BASE="https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com"

# Step 1: Get overall system stats
curl -s "$EXEC_BASE/api/v1/exec/monitor/stats"

# Step 2: Check which scripts are running now
curl -s "$EXEC_BASE/api/v1/exec/monitor/active-requests"

# Step 3: Get performance metrics for a specific script
curl -s -X POST "$EXEC_BASE/api/v1/exec/monitor/script-performance" \
  -H "Content-Type: application/json" \
  -d '{
    "script": "api/data/transform.ts",
    "period": "7d"
  }'

# Step 4: Export metrics for external monitoring
curl -s "$EXEC_BASE/api/v1/exec/monitor/metrics"
```

---

### 3.6 Complete API with OpenAPI Documentation

Build a fully documented API endpoint with schema validation.

```
EXEC_BASE="https://proj-abc123-cont-def456-exec-svc789.us-east.containers.hoody.com"

# Step 1: Create a well-documented API endpoint
curl -s -X POST "$EXEC_BASE/api/v1/exec/scripts/write" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "api/webhooks/stripe.ts",
    "content": "// @method POST\n// @path /api/webhooks/stripe\n// @description Stripe webhook handler\n// @rateLimit 1000\n\ninterface StripeEvent {\n  id: string;\n  type: string;\n  data: { object: Record<string, unknown> };\n}\n\nexport default async function(req: Request) {\n  const event: StripeEvent = await req.json();\n  \n  switch (event.type) {\n    case \"payment_intent.succeeded\":\n      return { processed: true, eventId: event.id };\n    case \"payment_intent.failed\":\n      return { processed: true, eventId: event.id, alert: true };\n    default:\n      return { processed: false, reason: \"Unhandled event type\" };\n  }\n}"
  }'

# Step 2: Set magic comments explicitly
curl -s -X PUT "$EXEC_BASE/api/v1/exec/magic-comments/update" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "api/webhooks/stripe.ts",
    "comments": {
      "@method": "POST",
      "@path": "/api/webhooks/stripe",
      "@rateLimit": "1000"
    }
  }'

# Step 3: Generate OpenAPI spec for the webhook
curl -s -X POST "$EXEC_BASE/api/v1/exec/user-openapi/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "script": "api/webhooks/stripe.ts"
  }'

# Step 4: Validate the schema
curl -s -X POST "$EXEC_BASE/api/v1/exec/user-openapi/validate" \
  -H "Content-Type: application/json" \
  -d '{
    "script": "api/webhooks/stripe.ts"
  }'

# Step 5: Get the merged OpenAPI spec
curl -s "$EXEC_BASE/api/v1/exec/user-openapi/spec"
```

---

## 4. Quick Reference

### Most Common Endpoints

| Operation | Method | Path | Purpose |
|-----------|--------|------|---------|
| Execute script | POST | `/{path}` | Run any script as API |
| List scripts | GET | `/api/v1/exec/scripts/list` | View all scripts |
| Write script | POST | `/api/v1/exec/scripts/write` | Create/update script |
| Delete script | DELETE | `/api/v1/exec/scripts/delete` | Remove script |
| Health check | GET | `/api/v1/exec/health` | Service health |
| List logs | GET | `/api/v1/exec/logs/list` | View log files |
| Clear cache | POST | `/api/v1/exec/cache/clear` | Reset cache |
| List templates | GET | `/api/v1/exec/templates/list` | Available templates |
| Discover routes | POST | `/api/v1/exec/route/discover` | All API routes |
| Set shared state | POST | `/api/v1/exec/shared-state/set` | Store shared data |
| Monitor stats | GET | `/api/v1/exec/monitor/stats` | System statistics |

### Essential Parameters

| Endpoint | Required Fields | Notes |
|----------|----------------|-------|
| `POST /api/v1/exec/scripts/write` | `path`, `content` | path = file path, content = script code |
| `DELETE /api/v1/exec/scripts/delete` | query: `path` | File path to delete |
| `GET /api/v1/exec/scripts/read` | query: `path` | File path to read |
| `POST /api/v1/exec/validate/typescript` | `code` | TypeScript source to validate |
| `POST /api/v1/exec/validate/syntax` | `code` | JavaScript/TS source |
| `POST /api/v1/exec/validate/dependencies` | `code` | Source with imports |
| `POST /api/v1/exec/validate/return-type` | `typeDefinition`, `value` | Type string + JSON value |
| `POST /api/v1/exec/validate/magic-comments` | `code` | Source with magic comments |
| `POST /api/v1/exec/validate/script` | `code` | Full script validation |
| `POST /api/v1/exec/shared-state/set` | `hostname`, `value` | State key + JSON value |
| `POST /api/v1/exec/shared-state/get` | `hostname` | State key to retrieve |
| `POST /api/v1/exec/shared-state/clear` | `hostname` | State key to clear |
| `GET /api/v1/exec/logs/stream` | query: `file` | Log filename for SSE stream |
| `POST /api/v1/exec/scripts/move` | `from`, `to` | Source and destination paths |
| `GET /api/v1/exec/templates/preview` | query: `name` | Template name |
| `POST /api/v1/exec/templates/generate` | `name` | Template name to generate from |
| `PUT /api/v1/exec/templates/update-custom/:name` | query: `name` | Custom template name |
| `DELETE /api/v1/exec/templates/delete-custom/:name` | query: `name` | Custom template name |

### Typical Response Formats

**Success response:**

```
{
  "success": true,
  "message": "Operation completed"
}
```

**List response:**

```
{
  "items": [],
  "total": 0
}
```

**Error response:**

```
{
  "error": "Error message",
  "code": "ERROR_CODE",
  "details": {}
}
```

**Script execution response** (varies by script):

```
{
  "data": {},
  "meta": {}
}
```

### curl Pattern

All hoody-exec requests follow this pattern:

```
curl -s -X METHOD "https://{BASE_URL}/api/v1/exec/ENDPOINT" \
  -H "Content-Type: application/json" \
  -d '{ "required_field": "value" }'
```

**Flags:**
- `-s`: Silent mode (required — suppresses progress output)
- ``: 10-minute timeout for long-running operations
- `-X METHOD`: HTTP method (GET, POST, PUT, DELETE)
- `-H "Content-Type: application/json"`: Required for all POST/PUT requests
- `-d '{...}'`: Request body (JSON)

### Script Execution Path

The `POST /{path}` endpoint is the core execution path. Any script file at `api/users.ts` becomes accessible at `POST /api/users`. The path maps directly to the file structure in the scripts directory.

```
# Script at: api/data/transform.ts
# Executed via:
curl -s -X POST "$EXEC_BASE/api/data/transform" \
  -H "Content-Type: application/json" \
  -d '{"key": "value"}'
```

### Endpoint Groups Summary

| Group | Endpoints | Purpose |
|-------|-----------|---------|
| **Script Execution** | `POST /{path}` | Core execution |
| **Scripts** | 6 endpoints | CRUD for script files |
| **Templates** | 6 endpoints | Scaffolding and generation |
| **Validation** | 6 endpoints | Pre-deployment checks |
| **Dependencies** | 3 endpoints | Module management |
| **Package** | 6 endpoints | Package.json management |
| **Logs** | 5 endpoints | Log viewing and search |
| **Shared State** | 3 endpoints | Cross-script state |
| **Routes** | 3 endpoints | Route discovery/resolution |
| **Monitor** | 5 endpoints | Performance and stats |
| **Schedules** | 4 endpoints | Cron task management |
| **Magic Comments** | 4 endpoints | Script metadata |
| **User OpenAPI** | 6 endpoints | Spec generation |
| **SDK** | 4 endpoints | SDK management |
| **System** | 2 endpoints | Restart and health |
| **Cache** | 1 endpoint | Cache clearing |
```