<!--
hoody-exec Subskill (sdk)
Auto-generated by Hoody Skills Generator
Generated: 2026-05-06T20:07:10.749Z
Model: mimo-v2.5-pro + fixer:mimo-v2.5-pro
Mode: sdk


Tokens: 14429

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 REST API endpoint. Upload a script, and it instantly becomes accessible via HTTP with automatic JSON parsing, error handling, and monitoring built in.

### When to Use hoody-exec

Use hoody-exec when you need to:

- **Deploy instant REST APIs** from TypeScript/JavaScript files without server configuration
- **Create webhook handlers** that automatically parse incoming JSON payloads
- **Build data transformation pipelines** (ETL) as executable scripts
- **Chain scripts together** to compose complex workflows by calling between exec endpoints
- **Expose system monitoring** endpoints that return structured JSON responses
- **Schedule recurring tasks** using cron-like scheduling with script execution
- **Manage shared state** across multiple script executions

### How It Fits Into Hoody Philosophy

hoody-exec embodies the Hoody principle of **zero-configuration deployment**. Instead of setting up Express servers, configuring routes, or managing process lifecycles, you simply write a script and it becomes an API. The service handles:

- Automatic route discovery using Next.js-style dynamic routing (`[param]`, `[...slug]`, `[[...path]]`)
- Built-in dependency management via Bun's package system
- Real-time log streaming and search
- Script validation (syntax, TypeScript, dependencies, magic comments)
- OpenAPI spec generation from your scripts
- Cron scheduling for automated execution

### Service Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      hoody-exec Service                      │
├─────────────────────────────────────────────────────────────┤
│  Script Layer          │  Execution Layer    │  Monitoring   │
│  - Scripts CRUD        │  - Bun Runtime      │  - Metrics    │
│  - Templates           │  - Route Resolution │  - Logs       │
│  - Magic Comments      │  - Shared State     │  - Performance│
│  - Validation          │  - Schedules        │  - Health     │
├─────────────────────────────────────────────────────────────┤
│  Package Layer         │  API Layer          │  SDK Layer    │
│  - Dependencies        │  - OpenAPI Gen      │  - Import     │
│  - Package.json        │  - Schema Merge     │  - List       │
│  - Version Pinning     │  - Validation       │  - Manage     │
└─────────────────────────────────────────────────────────────┘
```

### Base URL Pattern

All hoody-exec endpoints use this base URL:

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

**Important**: This service uses `/api/v1/exec/...` prefixed paths for management endpoints, and root-level `/{path}` for script execution.

---

## Common Workflows

### Workflow 1: Deploy and Execute a Script

This is the fundamental workflow—write a script, deploy it, then execute it via HTTP.

**Step 1: Write a Script**

```
import { HoodyClient } from '@hoody-ai/hoody-sdk'

const client = new HoodyClient({
  baseURL: 'https://api.hoody.icu',
  token: 'YOUR_TOKEN'
})

// Write a new script to the exec service
await client.exec.scripts.write({
  path: 'api/hello.ts',
  content: `
export default async function handler(req: Request) {
  const body = await req.json();
  return {
    message: \`Hello, \${body.name || 'World'}!\`,
    timestamp: new Date().toISOString()
  };
}
`
})
```

**Step 2: Verify Script Was Created**

```
// Read the script back to confirm
const script = await client.exec.scripts.read({
  path: 'api/hello.ts'
})

console.log('Script content:', script.content)
```

**Step 3: Execute the Script**

```
// Execute via the execution endpoint
const result = await client.exec.execution.execute({ path: 'api/hello' })
console.log('Execution result:', result)
```

**Step 4: List All Scripts**

```
// See all deployed scripts
const scripts = await client.exec.scripts.list()
console.log('Deployed scripts:', scripts)
```

---

### Workflow 2: Script Validation Pipeline

Before deploying scripts to production, validate them thoroughly.

**Step 1: Validate Syntax**

```
const syntaxResult = await client.exec.validate.validateSyntax({
  code: `
export default function handler() {
  return { status: 'ok' }
}
`
})

console.log('Syntax valid:', syntaxResult.valid)
```

**Step 2: Validate TypeScript**

```
const tsResult = await client.exec.validate.validateTypeScript({
  code: `
interface Response {
  status: string
  data: number[]
}

export default function handler(): Response {
  return { status: 'ok', data: [1, 2, 3] }
}
`
})

console.log('TypeScript valid:', tsResult.valid)
```

**Step 3: Validate Dependencies**

```
const depResult = await client.exec.validate.validateDependencies({
  code: `
import { format } from 'date-fns'

export default function handler() {
  return { date: format(new Date(), 'yyyy-MM-dd') }
}
`
})

console.log('Dependencies available:', depResult.available)
```

**Step 4: Validate Return Type**

```
const returnResult = await client.exec.validate.validateReturnType({
  typeDefinition: '{ status: string; count: number }',
  value: { status: 'active', count: 42 }
})

console.log('Return type valid:', returnResult.valid)
```

**Step 5: Validate Magic Comments**

```
const magicResult = await client.exec.validate.validateMagicComments({
  code: `
// @schedule: */5 * * * *
// @method: POST
export default function handler() {
  return { executed: true }
}
`
})

console.log('Magic comments valid:', magicResult.valid)
```

**Step 6: Full Script Validation**

```
const fullResult = await client.exec.validate.validateScript({
  code: `
// @method: GET
// @path: /api/health
export default function handler() {
  return { status: 'healthy', uptime: process.uptime() }
}
`
})

console.log('Full validation:', fullResult)
```

---

### Workflow 3: Template-Based Script Generation

Use templates to quickly scaffold common script patterns.

**Step 1: List Available Templates**

```
const templates = await client.exec.templates.list()
console.log('Available templates:', templates)
```

**Step 2: Preview a Template**

```
const preview = await client.exec.templates.preview({
  name: 'webhook-handler'
})

console.log('Template preview:', preview)
```

**Step 3: Generate Script from Template**

```
const generated = await client.exec.templates.generate({
  name: 'webhook-handler',
  variables: {
    endpoint: '/api/webhooks/github',
    secret: 'my-webhook-secret'
  }
})

console.log('Generated script:', generated.content)
```

**Step 4: Create Custom Template**

```
await client.exec.templates.createCustom({
  name: 'data-pipeline',
  description: 'ETL pipeline template',
  content: `
// @method: POST
// @schedule: {{schedule}}
export default async function handler(req: Request) {
  const data = await req.json();
  // Transform
  const transformed = {{transformLogic}};
  // Load
  return { processed: transformed.length };
}
`,
  variables: ['schedule', 'transformLogic']
})
```

**Step 5: Update Custom Template**

```
await client.exec.templates.updateCustom({
  name: 'data-pipeline',
  content: `
// Updated template content
export default async function handler(req: Request) {
  // New implementation
}
`
})
```

**Step 6: Delete Custom Template**

```
await client.exec.templates.deleteCustom({
  name: 'data-pipeline'
})
```

---

### Workflow 4: Route Management

hoody-exec uses Next.js-style dynamic routing. Manage and test your routes.

**Step 1: Discover All Routes**

```
const routes = await client.exec.route.discover()
console.log('Discovered routes:', routes)
```

**Step 2: Resolve a Specific Route**

```
const resolved = await client.exec.route.resolve({
  path: '/api/users/123'
})

console.log('Resolved to script:', resolved.script)
console.log('Route type:', resolved.type) // 'dynamic'
console.log('Parameters:', resolved.params) // { id: '123' }
```

**Step 3: Test Multiple Routes**

```
const testResults = await client.exec.route.test({
  paths: [
    '/api/users',
    '/api/users/456',
    '/api/products/electronics/phones',
    '/api/unknown'
  ]
})

console.log('Route test results:', testResults)
```

---

### Workflow 5: Log Management

Monitor script execution through comprehensive logging.

**Step 1: List Available Logs**

```
const logs = await client.exec.logs.list()
console.log('Available log files:', logs)
```

**Step 2: Read Specific Log**

```
const logContent = await client.exec.logs.read({
  file: 'exec.log',
  lines: 100
})

console.log('Log entries:', logContent)
```

**Step 3: Stream Logs in Real-Time**

```
// Stream logs for real-time monitoring
await client.exec.logs.stream({
  file: 'exec.log',
  follow: 'true'
})
```

**Step 4: Search Logs**

```
const searchResults = await client.exec.logs.search({
  query: 'error',
  file: 'exec.log',
  limit: 50
})

console.log('Matching log entries:', searchResults)
```

**Step 5: Clear Old Logs**

```
await client.exec.logs.clear({
  olderThanDays: 7,
  confirm: 'true'
})

console.log('Old logs cleared')
```

---

### Workflow 6: Dependency Management

Manage npm packages for your scripts.

**Step 1: List Bundled Dependencies**

```
const bundled = await client.exec.dependencies.listBundled()
console.log('Bundled dependencies:', bundled)
```

**Step 2: Check Dependencies**

```
const checkResult = await client.exec.dependencies.check({
  dependencies: ['lodash', 'date-fns', 'zod']
})

console.log('Dependency status:', checkResult)
```

**Step 3: Install Dependencies**

```
await client.exec.dependencies.install({
  dependencies: ['lodash', 'date-fns']
})

console.log('Dependencies installed')
```

**Step 4: Read Package.json**

```
const packageJson = await client.exec.package.readJson()
console.log('Current package.json:', packageJson)
```

**Step 5: Update Package.json**

```
await client.exec.package.updateJson({
  dependencies: {
    'lodash': '^4.17.21',
    'date-fns': '^2.30.0'
  }
})
```

**Step 6: Install Packages**

```
await client.exec.package.install()
console.log('Packages installed from package.json')
```

**Step 7: Compare Package Versions**

```
const comparison = await client.exec.package.compare({
  packages: ['lodash', 'date-fns']
})

console.log('Version comparison:', comparison)
```





---

### Workflow 7: Shared State Management

Share data between script executions using the shared state system.

**Step 1: Set Shared State**

```
await client.exec.state.set({
  hostname: 'api-server',
  value: {
    requestCount: 1547,
    lastError: null,
    activeUsers: ['user1', 'user2', 'user3']
  }
})

console.log('State set successfully')
```

**Step 2: Get Shared State**

```
const state = await client.exec.state.get({
  hostname: 'api-server'
})

console.log('Current state:', state)
console.log('Request count:', state.requestCount)
```

**Step 3: Clear Shared State**

```
await client.exec.state.clear({
  hostname: 'api-server'
})

console.log('State cleared')
```

---

### Workflow 8: Schedule Management

Automate script execution with cron-like scheduling.

**Step 1: List All Schedules**

```
const schedules = await client.exec.schedules.listSchedules()
console.log('Active schedules:', schedules)
```



**Step 3: Reload Schedules**

```
await client.exec.schedules.reloadSchedules()
console.log('Schedules reloaded from scripts')
```

**Step 4: View Schedule History**

```
const history = await client.exec.schedules.scheduleHistory({
  scriptPath: 'api/cleanup.ts',
  limit: 20
})

console.log('Execution history:', history)
```

---

### Workflow 9: Magic Comments Configuration

Configure script behavior through magic comments.

**Step 1: Get Magic Comments Schema**

```
const schema = await client.exec.magic.getSchema()
console.log('Available magic comments:', schema)
```

**Step 2: Read Magic Comments from Script**

```
const comments = await client.exec.magic.read({
  path: 'api/hello.ts'
})

console.log('Current magic comments:', comments)
```

**Step 3: Update Magic Comments**

```
await client.exec.magic.updateHandler({
  path: 'api/hello.ts',
  comments: {
    method: 'POST',
    schedule: '*/10 * * * *',
    cors: true,
    rateLimit: 100
  }
})

console.log('Magic comments updated')
```

**Step 4: Bulk Update Magic Comments**

```
await client.exec.magic.bulkUpdate({
  updates: [
    {
      path: 'api/endpoint1.ts',
      comments: { method: 'GET' }
    },
    {
      path: 'api/endpoint2.ts',
      comments: { method: 'POST' }
    }
  ]
})

console.log('Bulk update complete')
```

---

### Workflow 10: OpenAPI Specification Generation

Generate and manage OpenAPI specs from your scripts.

**Step 1: List Scripts with Schema Info**

```
const scriptsWithSchema = await client.exec.openapi.listScripts()
console.log('Scripts with schema:', scriptsWithSchema)
```

**Step 2: Generate OpenAPI Spec**

```
const spec = await client.exec.openapi.generate({
  scripts: ['api/users.ts', 'api/products.ts'],
  title: 'My API',
  version: '1.0.0'
})

console.log('Generated OpenAPI spec:', spec)
```

**Step 3: Validate Script Schema**

```
const validation = await client.exec.openapi.validateSchema({
  path: 'api/users.ts'
})

console.log('Schema valid:', validation.valid)
```

**Step 4: Serve OpenAPI Spec**

```
const servedSpec = await client.exec.openapi.serve({
  format: 'json'
})

console.log('Served spec:', servedSpec)
```

**Step 5: Merge Multiple Specs**

```
const merged = await client.exec.openapi.merge({
  specs: [
    { path: 'api/users-spec.json' },
    { path: 'api/products-spec.json' }
  ],
  title: 'Combined API'
})

console.log('Merged spec:', merged)
```

---

### Workflow 11: SDK Management

Import and manage external SDKs for use in your scripts.

**Step 1: List Available SDKs**

```
const sdks = await client.exec.sdk.list()
console.log('Available SDKs:', sdks)
```

**Step 2: Import an SDK**

```
await client.exec.sdk.importSDK({
  name: 'stripe',
  version: '14.0.0',
  source: 'npm'
})

console.log('SDK imported')
```

**Step 3: Get SDK Details**

```
const sdkDetails = await client.exec.sdk.get({
  id: 'stripe-14.0.0'
})

console.log('SDK details:', sdkDetails)
```

**Step 4: Delete an SDK**

```
await client.exec.sdk.delete({
  id: 'stripe-14.0.0'
})

console.log('SDK deleted')
```

---

## Advanced Operations

### Advanced Workflow 1: Complete Script Lifecycle

This workflow demonstrates the full lifecycle of a script from creation to production deployment with monitoring.

**Phase 1: Development and Validation**

```
import { HoodyClient } from '@hoody-ai/hoody-sdk'

const client = new HoodyClient({
  baseURL: 'https://api.hoody.icu',
  token: 'YOUR_TOKEN'
})

// Step 1: Write the script
const scriptContent = `
// @method: POST
// @path: /api/data/process
// @cors: true
// @rateLimit: 50

interface ProcessRequest {
  data: number[];
  operation: 'sum' | 'average' | 'max' | 'min';
}

interface ProcessResponse {
  result: number;
  operation: string;
  processedAt: string;
}

export default async function handler(req: Request): Promise<ProcessResponse> {
  const body: ProcessRequest = await req.json();
  
  let result: number;
  switch (body.operation) {
    case 'sum':
      result = body.data.reduce((a, b) => a + b, 0);
      break;
    case 'average':
      result = body.data.reduce((a, b) => a + b, 0) / body.data.length;
      break;
    case 'max':
      result = Math.max(...body.data);
      break;
    case 'min':
      result = Math.min(...body.data);
      break;
    default:
      throw new Error('Invalid operation');
  }
  
  return {
    result,
    operation: body.operation,
    processedAt: new Date().toISOString()
  };
}
`

await client.exec.scripts.write({
  path: 'api/data/process.ts',
  content: scriptContent
})

// Step 2: Validate the script
const validation = await client.exec.validate.validateScript({
  code: scriptContent
})

if (!validation.valid) {
  console.error('Validation failed:', validation.errors)
  throw new Error('Script validation failed')
}

// Step 3: Validate TypeScript types
const tsValidation = await client.exec.validate.validateTypeScript({
  code: scriptContent
})

if (!tsValidation.valid) {
  console.error('TypeScript errors:', tsValidation.errors)
  throw new Error('TypeScript validation failed')
}

console.log('Script validated successfully')
```

**Phase 2: Route Verification**

```
// Step 4: Verify route resolution
const routeResolution = await client.exec.route.resolve({
  path: '/api/data/process'
})

console.log('Route resolved:', routeResolution)

// Step 5: Test the route
const routeTest = await client.exec.route.test({
  paths: ['/api/data/process', '/api/data/process/extra']
})

console.log('Route test results:', routeTest)
```

**Phase 3: Execution and Monitoring**

```
// Step 6: Execute the script
const result = await client.exec.execution.execute({ path: 'api/data/process' })
console.log('Execution result:', result)

// Step 7: Check execution logs
const logs = await client.exec.logs.search({
  query: 'api/data/process',
  limit: 10
})

console.log('Recent execution logs:', logs)

// Step 8: Monitor script performance
const performance = await client.exec.monitor.getScriptPerformance({
  scriptPath: 'api/data/process.ts',
  period: '1h'
})

console.log('Performance metrics:', performance)
```

**Phase 4: Production Hardening**

```
// Step 9: Set up shared state for rate limiting
await client.exec.state.set({
  hostname: 'api-data-process',
  value: {
    requestCount: 0,
    lastReset: new Date().toISOString(),
    errors: []
  }
})

// Step 10: Clear cache to ensure fresh execution
await client.exec.cache.clear({
  pattern: 'api/data/process*'
})

console.log('Production hardening complete')
```

---

### Advanced Workflow 2: Error Recovery and Debugging

When scripts fail, use this systematic debugging approach.

**Step 1: Check Service Health**

```
const health = await client.exec.health.check()
console.log('Service health:', health)

if (health.status !== 'healthy') {
  console.error('Service unhealthy, checking restart status...')
  const restartStatus = await client.exec.system.getRestartStatus()
  console.log('Restart status:', restartStatus)
}
```

**Step 2: Review Recent Logs**

```
// List available log files
const logFiles = await client.exec.logs.list()
console.log('Log files:', logFiles)

// Search for errors
const errors = await client.exec.logs.search({
  query: 'error',
  limit: 20
})

console.log('Recent errors:', errors)
```

**Step 3: Check Active Requests**

```
const activeRequests = await client.exec.monitor.getActiveRequests()
console.log('Active requests:', activeRequests)

// If stuck requests exist, consider restart
if (activeRequests.length > 10) {
  console.warn('High number of active requests, considering restart...')
}
```

**Step 4: Validate Failing Script**

```
const script = await client.exec.scripts.read({
  path: 'api/failing-endpoint.ts'
})

const validation = await client.exec.validate.validateScript({
  code: script.content
})

console.log('Validation result:', validation)

// Check dependencies
const depCheck = await client.exec.validate.validateDependencies({
  code: script.content
})

console.log('Dependency check:', depCheck)
```

**Step 5: Service Restart (Last Resort)**

```
// Initiate restart
await client.exec.system.restartServer()

// Poll for restart completion
let restartComplete = false
while (!restartComplete) {
  const status = await client.exec.system.getRestartStatus()
  console.log('Restart status:', status)
  
  if (status.status === 'ready') {
    restartComplete = true
    console.log('Service restarted successfully')
  } else {
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}
```

---

### Advanced Workflow 3: Script Chaining and Composition

Build complex workflows by chaining multiple scripts together.

**Step 1: Create Data Fetcher Script**

```
await client.exec.scripts.write({
  path: 'api/pipeline/fetch.ts',
  content: `
// @method: POST
export default async function handler(req: Request) {
  const { source } = await req.json();
  
  // Simulate data fetching
  const data = Array.from({ length: 100 }, (_, i) => ({
    id: i,
    value: Math.random() * 1000,
    timestamp: Date.now()
  }));
  
  return { source, data, fetchedAt: new Date().toISOString() };
}
`
})
```

**Step 2: Create Data Transformer Script**

```
await client.exec.scripts.write({
  path: 'api/pipeline/transform.ts',
  content: `
// @method: POST
export default async function handler(req: Request) {
  const { data, transformations } = await req.json();
  
  let result = [...data];
  
  for (const transform of transformations) {
    switch (transform.type) {
      case 'filter':
        result = result.filter(item => item.value > transform.threshold);
        break;
      case 'sort':
        result.sort((a, b) => a[transform.field] - b[transform.field]);
        break;
      case 'limit':
        result = result.slice(0, transform.count);
        break;
    }
  }
  
  return { transformed: result, count: result.length };
}
`
})
```

**Step 3: Create Pipeline Orchestrator**

```
await client.exec.scripts.write({
  path: 'api/pipeline/orchestrate.ts',
  content: `
// @method: POST
export default async function handler(req: Request) {
  const { source, transformations } = await req.json();
  
  // Step 1: Fetch data
  const fetchResult = await fetch('/api/pipeline/fetch', {
    method: 'POST',
    body: JSON.stringify({ source })
  });
  const { data } = await fetchResult.json();
  
  // Step 2: Transform data
  const transformResult = await fetch('/api/pipeline/transform', {
    method: 'POST',
    body: JSON.stringify({ data, transformations })
  });
  const { transformed, count } = await transformResult.json();
  
  return {
    pipeline: 'complete',
    originalCount: data.length,
    transformedCount: count,
    result: transformed
  };
}
`
})
```

**Step 4: Execute the Pipeline**

```
const pipelineResult = await client.exec.execution.execute({ path: 'api/pipeline/orchestrate' })
console.log('Pipeline result:', pipelineResult)
```

---

### Advanced Workflow 4: Performance Optimization

Optimize script execution for high-throughput scenarios.

**Step 1: Monitor Current Performance**

```
const stats = await client.exec.monitor.getStats()
console.log('Current stats:', stats)

const scripts = await client.exec.monitor.listMonitorScripts({
  limit: 10,
  sort: 'execution_time'
})

console.log('Slowest scripts:', scripts)
```

**Step 2: Analyze Script Performance**

```
const performance = await client.exec.monitor.getScriptPerformance({
  scriptPath: 'api/heavy-endpoint.ts',
  period: '24h'
})

console.log('Performance analysis:', performance)
console.log('Average execution time:', performance.avgTime)
console.log('P95 execution time:', performance.p95Time)
console.log('Error rate:', performance.errorRate)
```

**Step 3: Export Metrics for External Monitoring**

```
const prometheusMetrics = await client.exec.monitor.prometheusExport()
console.log('Prometheus metrics exported')
// Feed this to your Prometheus/Grafana setup
```

**Step 4: Optimize with Caching**

```
// Clear stale cache
await client.exec.cache.clear({
  pattern: 'heavy-endpoint*'
})

// Update script with caching magic comments
await client.exec.magic.updateHandler({
  path: 'api/heavy-endpoint.ts',
  comments: {
    cache: '5m',
    cacheKey: 'heavy-endpoint-{{params.id}}'
  }
})

console.log('Caching configured')
```

---

### Advanced Workflow 5: Multi-Instance Management

Manage multiple exec instances across different containers.

**Step 1: List All Exec Instances**

```
const instances = await client.exec.ids.list()
console.log('All exec instances:', instances)
```

**Step 2: Cross-Instance Script Deployment**

```
// Read script from one instance
const script = await client.exec.scripts.read({
  path: 'api/shared-utility.ts',
  execId: 'instance-1'
})

// Deploy to another instance
await client.exec.scripts.write({
  path: 'api/shared-utility.ts',
  content: script.content,
  execId: 'instance-2'
})

console.log('Script deployed across instances')
```

**Step 3: Aggregate Monitoring**

```
// Get stats from multiple instances
const instance1Stats = await client.exec.monitor.getStats({
  execId: 'instance-1'
})

const instance2Stats = await client.exec.monitor.getStats({
  execId: 'instance-2'
})

console.log('Instance 1 stats:', instance1Stats)
console.log('Instance 2 stats:', instance2Stats)
```

---

## Quick Reference

### Most Common Endpoints

| Operation | SDK Method | HTTP Endpoint |
|-----------|------------|---------------|
| Execute Script | `client.exec.execution.execute(path)` | `GET /{path}` |
| Write Script | `client.exec.scripts.write(data)` | `POST /api/v1/exec/scripts/write` |
| Read Script | `client.exec.scripts.read(path)` | `GET /api/v1/exec/scripts/read` |
| List Scripts | `client.exec.scripts.list()` | `GET /api/v1/exec/scripts/list` |
| Delete Script | `client.exec.scripts.delete(path)` | `DELETE /api/v1/exec/scripts/delete` |
| Health Check | `client.exec.health.check()` | `GET /api/v1/exec/health` |
| List Logs | `client.exec.logs.list()` | `GET /api/v1/exec/logs/list` |
| Search Logs | `client.exec.logs.search(data)` | `POST /api/v1/exec/logs/search` |
| Get Stats | `client.exec.monitor.getStats()` | `GET /api/v1/exec/monitor/stats` |
| Restart Server | `client.exec.system.restartServer()` | `POST /api/v1/exec/system/restart` |

### Essential Parameters

**Script Operations**
- `path` (string, required): Script file path (e.g., `api/hello.ts`)
- `content` (string, required): Script source code
- `dir` (string, optional): Directory to list/filter

**Validation Operations**
- `code` (string, required): Source code to validate
- `typeDefinition` (string, required): TypeScript type definition
- `value` (unknown, required): Value to validate against type

**Log Operations**
- `file` (string, required for stream): Log file name
- `query` (string, optional): Search query
- `limit` (number, optional): Number of results
- `olderThanDays` (number, optional): Age threshold for clearing

**Shared State Operations**
- `hostname` (string, required): State namespace identifier
- `value` (unknown, required for set): JSON value to store

**Route Operations**
- `path` (string, required): URL path to resolve
- `paths` (string[], required for test): Array of paths to test

### Typical Response Formats

**Success Response**
```
{
  "success": true,
  "data": {
    "key": "value"
  }
}
```

**List Response**
```
{
  "items": [
    {
      "name": "item1",
      "path": "api/item1.ts"
    }
  ],
  "total": 1,
  "page": 1
}
```

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

**Error Response**
```
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid script syntax",
    "details": {
      "line": 5,
      "column": 10
    }
  }
}
```

**Health Response**
```
{
  "status": "healthy",
  "uptime": 3600,
  "version": "1.0.0"
}
```

**Performance Response**
```
{
  "avgTime": 45.2,
  "p95Time": 120.5,
  "p99Time": 250.1,
  "errorRate": 0.02,
  "requestCount": 1547
}
```

### Magic Comments Reference

Available magic comments for script configuration:

| Comment | Description | Example |
|---------|-------------|---------|
| `@method` | HTTP method | `// @method: POST` |
| `@path` | Custom path | `// @path: /api/custom` |
| `@cors` | Enable CORS | `// @cors: true` |
| `@rateLimit` | Rate limit (req/min) | `// @rateLimit: 100` |
| `@cache` | Cache duration | `// @cache: 5m` |
| `@schedule` | Cron schedule | `// @schedule: */5 * * * *` |
| `@timeout` | Execution timeout | `// @timeout: 30s` |
| `@auth` | Require authentication | `// @auth: true` |

### Route Types

| Type | Pattern | Example |
|------|---------|---------|
| Static | `/path/to/resource` | `/api/users` |
| Dynamic | `/path/[param]` | `/api/users/[id]` |
| Catch-all | `/path/[...slug]` | `/api/docs/[...path]` |
| Optional Catch-all | `/path/[[...path]]` | `/api/[[...path]]` |

### Common Workflow Patterns

**Deploy → Validate → Execute**
```
scripts.write → validate.validateScript → execution.execute
```

**Debug → Fix → Redeploy**
```
logs.search → scripts.read → scripts.write → execution.execute
```

**Template → Customize → Deploy**
```
templates.list → templates.generate → scripts.write
```

**Monitor → Analyze → Optimize**
```
monitor.getStats → monitor.getScriptPerformance → cache.clear
```

**Schedule → Trigger → Verify**
```
schedules.listSchedules → schedules.trigger → schedules.scheduleHistory
```