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


Tokens: 12497

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

# hoody-exec Subskill

## Overview

**Service**: hoody-exec  
**Purpose**: Turn any TypeScript/JavaScript script into a production-ready API endpoint with minimal configuration. Bun-powered execution environment with built-in monitoring, scheduling, and OpenAPI integration.

### When to Use hoody-exec

- **Deploy instant REST API endpoints** from TypeScript/JavaScript files
- **Create webhook handlers** with automatic JSON parsing and response formatting
- **Build data transformation pipelines** for ETL workflows
- **Script chaining** - call between exec scripts to compose complex workflows
- **System monitoring endpoints** that return structured JSON
- **Scheduled tasks** (cron jobs) with history tracking
- **API-first development** with automatic OpenAPI spec generation

### Hoody Philosophy Alignment

hoody-exec embodies the "Infrastructure as Code" philosophy by:
- Treating scripts as deployable units with automatic API endpoint creation
- Providing zero-configuration deployment for individual functions
- Enabling script composition and reuse across services
- Offering comprehensive observability and debugging tools

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

**⚠️ CRITICAL PATH RULES**:
- Use EXACTLY the paths shown in endpoint inventory
- Do NOT add `/api/v1/` prefix unless shown in inventory
- Some endpoints use root-level paths (e.g., `/{path}`)
- All examples use the SDK, never raw HTTP

---

## Common Workflows

### 1. Script Management & Execution

#### Create and Execute a Script

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

const client = new HoodyClient({ baseURL: 'https://project-123-exec-456.node.containers.hoody.com', token: 'your-token' });

// Step 1: Write a new script
const writeResult = await client.exec.scripts.write({
  path: 'utils/format-data.ts',
  content: `
export default async function handler(req: Request) {
  const data = await req.json();
  return {
    formatted: true,
    timestamp: new Date().toISOString(),
    data
  };
}
`
});

// Step 2: Execute the script
const executionResult = await client.exec.execution.execute({ path: 'utils/format-data' });

// Step 3: Verify execution
console.log('Script executed:', executionResult.success);
```

#### List and Manage Scripts

```
// List all scripts with filtering
const scripts = await client.exec.scripts.list({
  dir: 'utils',
  filter: '*.ts',
  metadata: 'true'
});

// Read script content
const scriptContent = await client.exec.scripts.read({
  path: 'utils/format-data.ts'
});

// Move/rename a script
await client.exec.scripts.move({
  from: 'utils/format-data.ts',
  to: 'api/data-formatter.ts'
});

// Delete a script
await client.exec.scripts.delete({
  path: 'utils/old-script.ts',
  confirm: 'true'
});
```

#### Get Script Directory Structure

```
const scriptTree = await client.exec.scripts.tree({
  // Optional filters can be added in request body
});
```

### 2. Script Validation & Quality Assurance

#### Validate TypeScript Code

```
// Validate TypeScript syntax and types
const validation = await client.exec.validate.validateTypeScript({
  code: `
interface User {
  id: string;
  name: string;
}

export default async function handler(): Promise<User[]> {
  return [{ id: '1', name: 'John' }];
}
`
});

if (validation.success) {
  console.log('TypeScript validation passed');
} else {
  console.error('Validation errors:', validation.errors);
}
```

#### Validate Script Dependencies

```
// Check if dependencies are available
const depValidation = await client.exec.validate.validateDependencies({
  code: `
import { format } from 'date-fns';
import _ from 'lodash';

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

#### Validate Magic Comments

```
// Validate magic comments syntax
const magicValidation = await client.exec.validate.validateMagicComments({
  code: `
// @exec.route("/api/users")
// @exec.method("GET")
// @exec.cache(60)
export default async function handler() {
  return { users: [] };
}
`
});
```

### 3. Template Management

#### List and Use Templates

```
// List available templates
const templates = await client.exec.templates.list({
  category: 'api',
  includeBuiltin: 'true'
});

// Preview a template
const preview = await client.exec.templates.preview({
  name: 'rest-api'
});

// Generate script from template
const generated = await client.exec.templates.generate({
  name: 'rest-api',
  // Template-specific variables would go here
});
```

#### Create Custom Templates

```
// Create a custom template
const customTemplate = await client.exec.templates.createCustom({
  name: 'company-webhook',
  // Template definition
});

// Update custom template
await client.exec.templates.updateCustom({
  name: 'company-webhook',
  // Updated template definition
});

// Delete custom template
await client.exec.templates.deleteCustom({
  name: 'company-webhook'
});
```

### 4. Monitoring & Observability

#### View System Stats and Metrics

```
// Get overall system statistics
const stats = await client.exec.monitor.getStats();

// Get active requests
const activeRequests = await client.exec.monitor.getActiveRequests();

// List scripts with performance metrics
const monitorScripts = await client.exec.monitor.listMonitorScripts({
  limit: 10,
  sort: 'performance'
});

// Get detailed script performance
const performance = await client.exec.monitor.getScriptPerformance({
  // Script path or filter
});

// Export metrics in Prometheus format
const prometheusMetrics = await client.exec.monitor.prometheusExport();
```

#### Health Check and System Management

```
// Perform health check
const health = await client.exec.health.check();

// Restart the execution server
await client.exec.system.restartServer({});

// Check restart status
const restartStatus = await client.exec.system.getRestartStatus();
```

### 5. Dependency Management

#### Manage Dependencies

```
// List bundled dependencies
const bundledDeps = await client.exec.dependencies.listBundled();

// Check missing dependencies
const depCheck = await client.exec.dependencies.check({
  // Dependencies to check
});

// Install dependencies
await client.exec.dependencies.install({
  packages: ['axios', 'lodash']
});
```

#### Package.json Operations

```
// Read package.json
const packageJson = await client.exec.package.readJson();

// Update package.json
await client.exec.package.updateJson({
  dependencies: {
    'axios': '^1.4.0'
  }
});

// Install packages
await client.exec.package.install({
  // Package specification
});

// Pin versions for reproducibility
await client.exec.package.pinVersions({
  // Versions to pin
});
```

### 6. Logging & Debugging

#### View and Search Logs

```
// List available logs
const logs = await client.exec.logs.list({
  type: 'exec',
  limit: '100'
});

// Read specific log
const logContent = await client.exec.logs.read({
  file: 'exec-2024-01-15.log'
});

// Search logs
const searchResults = await client.exec.logs.search({
  query: 'error',
  // Additional filters
});

// Stream logs in real-time
// (Note: This returns a readable stream, not a promise)
await client.exec.logs.stream({
  file: 'exec-2024-01-15.log',
  follow: 'true'
});

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

### 7. Routing & API Management

#### Script Routing

```
// Resolve a URL path to a script
const routeInfo = await client.exec.route.resolve({
  path: '/api/users/123'
});

// Discover all available routes
const allRoutes = await client.exec.route.discover({
  // Optional filters
});

// Test multiple routes at once
const routeTests = await client.exec.route.test({
  paths: ['/api/users', '/api/users/123', '/api/unknown']
});
```

### 8. Scheduled Tasks (Cron Jobs)

#### Manage Schedules

```
// List all scheduled tasks
const schedules = await client.exec.schedules.listSchedules();

// Trigger a schedule manually
await client.exec.schedules.triggerSchedule({
  id: 'daily-report'
});

// Reload schedules from configuration
await client.exec.schedules.reloadSchedules({});

// View schedule execution history
const scheduleHistory = await client.exec.schedules.scheduleHistory({
  scriptPath: 'tasks/daily-report.ts',
  since: '2024-01-01',
  limit: 50
});
```

### 9. OpenAPI Integration

#### Generate and Serve OpenAPI Specs

```
// List scripts with OpenAPI schema information
const scriptsWithSchema = await client.exec.openapi.listScripts({
  directory: 'api'
});

// Generate OpenAPI spec for specific scripts
const openApiSpec = await client.exec.openapi.generate({
  // Scripts to include
});

// Serve the OpenAPI spec
const servedSpec = await client.exec.openapi.serve({
  format: 'json'
});

// Validate a script's schema
await client.exec.openapi.validateSchema({
  // Schema validation config
});

// Merge multiple OpenAPI specs
const mergedSpec = await client.exec.openapi.merge({
  specs: [
    { name: 'users-api', spec: { /* ... */ } },
    { name: 'products-api', spec: { /* ... */ } }
  ]
});
```

### 10. Magic Comments & Metadata

#### Manage Script Metadata

```
// Get the schema for magic comments
const commentSchema = await client.exec.magic.getSchema();

// Read magic comments from a script
const scriptComments = await client.exec.magic.read({
  path: 'api/users.ts'
});

// Update comments for a single script
await client.exec.magic.updateHandler({
  path: 'api/users.ts',
  comments: {
    route: '/api/users',
    method: 'GET',
    cache: 300
  }
});

// Bulk update comments for multiple scripts
await client.exec.magic.bulkUpdate({
  updates: [
    { path: 'api/users.ts', comments: { route: '/api/v2/users' } },
    { path: 'api/products.ts', comments: { method: 'POST' } }
  ]
});
```

---

## Advanced Operations

### 1. Complete API Deployment Workflow

#### Deploy a Production-Ready API Endpoint

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

async function deployProductionAPI() {
  const client = new HoodyClient({ baseURL: 'BASE_URL', token: 'TOKEN' });

  try {
    // Step 1: Start with a template
    const template = await client.exec.templates.generate({
      name: 'rest-api-with-validation'
    });

    // Step 2: Customize the script
    const customScript = `
// @exec.route("/api/v1/users/:id")
// @exec.method("GET")
// @exec.validate-param("id", "string", { minLength: 1 })
// @exec.cache(300)
// @exec.tags("users", "public")

interface User {
  id: string;
  name: string;
  email: string;
}

export default async function handler(req: Request, params: { id: string }): Promise<User> {
  // Simulated database call
  return {
    id: params.id,
    name: 'John Doe',
    email: 'john@example.com'
  };
}
`;

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

    if (!validation.success) {
      throw new Error('Script validation failed: ' + JSON.stringify(validation.errors));
    }

    // Step 4: Write and deploy
    await client.exec.scripts.write({
      path: 'api/users/[id].ts',
      content: customScript
    });

    // Step 5: Verify deployment
    const routes = await client.exec.route.discover();
    const deployed = routes.routes.find((r: any) => r.path.includes('/api/v1/users'));

    if (!deployed) {
      throw new Error('Deployment verification failed');
    }

    // Step 6: Generate OpenAPI documentation
    await client.exec.openapi.generate({
      // Generate for the deployed script
    });

    return {
      success: true,
      endpoint: '/api/v1/users/{id}',
      documentation: '/openapi.json'
    };

  } catch (error) {
    // Error recovery: Clear any partial state
    await client.exec.scripts.delete({ path: 'api/users/[id].ts' });
    throw error;
  }
}
```

### 2. Script Composition Patterns

#### Chain Multiple Scripts

```
// Script 1: Data validation (api/validate-user.ts)
/*
// @exec.route("/internal/validate-user")
// @exec.method("POST")
export default async function handler(req: Request) {
  const data = await req.json();
  // Validation logic
  return { valid: true, data };
}
*/

// Script 2: Data processing (api/process-user.ts)
/*
// @exec.route("/internal/process-user")
// @exec.method("POST")
export default async function handler(req: Request) {
  const validation = await fetch('/internal/validate-user', { 
    method: 'POST', 
    body: JSON.stringify(await req.json()) 
  });
  
  const validatedData = await validation.json();
  // Processing logic
  return { processed: true, result: validatedData };
}
*/

// Script 3: Main API (api/users.ts)
/*
// @exec.route("/api/users")
// @exec.method("POST")
export default async function handler(req: Request) {
  const processing = await fetch('/internal/process-user', { 
    method: 'POST', 
    body: JSON.stringify(await req.json()) 
  });
  
  const result = await processing.json();
  return { success: true, user: result };
}
*/
```

### 3. Performance Optimization

#### Cache Management and Optimization

```
async function optimizePerformance() {
  const client = new HoodyClient({ baseURL: 'BASE_URL', token: 'TOKEN' });

  // Monitor script performance
  const performance = await client.exec.monitor.getScriptPerformance({
    // Optional: specify scripts to monitor
  });

  // Identify slow scripts
  const slowScripts = performance.scripts.filter((s: any) => s.avgResponseTime > 1000);

  // For each slow script, analyze and optimize
  for (const script of slowScripts) {
    // Check dependencies
    const deps = await client.exec.dependencies.check({
      code: (await client.exec.scripts.read({ path: script.path })).content
    });

    // Install any missing optimized dependencies
    if (deps.missing && deps.missing.length > 0) {
      await client.exec.dependencies.install({
        packages: deps.missing.map((d: any) => d.name + '@latest')
      });
    }

    // Update script with caching
    const content = (await client.exec.scripts.read({ path: script.path })).content;
    const cachedContent = `// @exec.cache(3600)\n${content}`;
    
    await client.exec.scripts.write({
      path: script.path,
      content: cachedContent
    });
  }

  // Clear cache to apply changes
  await client.exec.cache.clear({});

  return {
    optimized: slowScripts.length,
    cacheCleared: true
  };
}
```

### 4. Error Recovery Patterns

#### Comprehensive Error Recovery

```
async function recoverFromErrors() {
  const client = new HoodyClient({ baseURL: 'BASE_URL', token: 'TOKEN' });

  // Check system health
  const health = await client.exec.health.check();
  if (!health.healthy) {
    // Restart the system
    await client.exec.system.restartServer({});
    
    // Wait for restart
    let status = 'restarting';
    while (status === 'restarting') {
      await new Promise(resolve => setTimeout(resolve, 2000));
      const restartStatus = await client.exec.system.getRestartStatus();
      status = restartStatus.status;
    }
  }

  // Check for dependency issues
  const scripts = await client.exec.scripts.list();
  for (const script of scripts.scripts) {
    try {
      const validation = await client.exec.validate.validateScript({
        code: (await client.exec.scripts.read({ path: script.path })).content
      });

      if (!validation.success) {
        // Fix common issues
        const fixedContent = fixCommonIssues(
          (await client.exec.scripts.read({ path: script.path })).content
        );
        
        await client.exec.scripts.write({
          path: script.path,
          content: fixedContent
        });
      }
    } catch (error) {
      console.error(`Failed to fix script ${script.path}:`, error);
    }
  }

  // Clear all caches
  await client.exec.cache.clear({});
  
  // Reload schedules
  await client.exec.schedules.reloadSchedules({});

  return { recovered: true };
}

function fixCommonIssues(content: string): string {
  // Fix common syntax issues
  let fixed = content;
  // Add missing semicolons
  fixed = fixed.replace(/([^;])\n/g, '$1;\n');
  // Fix common import issues
  // ... more fixes
  return fixed;
}
```

### 5. Shared State Management

#### Distributed State Between Scripts

```
async function manageSharedState() {
  const client = new HoodyClient({ baseURL: 'BASE_URL', token: 'TOKEN' });

  // Set shared state for a hostname (virtual host)
  await client.exec.state.set({
    hostname: 'api.example.com',
    value: {
      config: {
        maxUsers: 1000,
        featureFlags: {
          newUI: true
        }
      },
      cache: {
        lastCleanup: new Date().toISOString()
      }
    }
  });

  // Get shared state from any script
  const state = await client.exec.state.get({
    hostname: 'api.example.com'
  });

  // Clear state when no longer needed
  await client.exec.state.clear({
    hostname: 'api.example.com'
  });

  return state;
}
```

### 6. SDK Management

#### Import and Manage SDKs

```
async function manageSDKs() {
  const client = new HoodyClient({ baseURL: 'BASE_URL', token: 'TOKEN' });

  // List available SDKs
  const sdks = await client.exec.sdk.list();

  // Import a new SDK
  const importResult = await client.exec.sdk.importSDK({
    name: 'company-sdk',
    // SDK definition
  });

  // Get SDK details
  const sdkDetails = await client.exec.sdk.get({
    id: importResult.id
  });

  // Delete SDK if no longer needed
  await client.exec.sdk.delete({
    id: importResult.id
  });

  return sdkDetails;
}
```

---

## Quick Reference

### Most Common Endpoints

| Endpoint | Method | SDK Method | Purpose |
|----------|--------|------------|---------|
| `/{path}` | POST | `execution.execute()` | Execute a script |
| `/api/v1/exec/scripts/write` | POST | `scripts.write()` | Create/update script |
| `/api/v1/exec/scripts/read` | GET | `scripts.read()` | Read script content |
| `/api/v1/exec/scripts/list` | GET | `scripts.list()` | List all scripts |
| `/api/v1/exec/health` | GET | `health.check()` | Health check |
| `/api/v1/exec/schedules/list` | GET | `schedules.listSchedules()` | List scheduled tasks |
| `/api/v1/exec/monitor/stats` | GET | `monitor.getStats()` | System statistics |

### Essential Parameters

**Script Execution**:
- `path` (string): Script path (e.g., `utils/format-data`)

**Script Management**:
- `path` (string): Script file path
- `content` (string): Script source code
- `from`/`to` (string): Paths for move operations

**Validation**:
- `code` (string): Code to validate
- `typeDefinition` (string): Type definition for return validation

**Monitoring**:
- `limit` (number): Number of results
- `sort` (string): Sort order

### Typical Response Formats

**Success Response**:
```
{
  "success": true,
  "data": {},
  "timestamp": "2024-01-15T10:30:00Z"
}
```

**Error Response**:
```
{
  "success": false,
  "error": "Validation failed",
  "details": [],
  "timestamp": "2024-01-15T10:30:00Z"
}
```

**List Response**:
```
{
  "success": true,
  "data": [],
  "total": 10,
  "page": 1,
  "limit": 50
}
```

### Common Workflow Patterns

1. **Deploy Script**: `write()` → `validateScript()` → `execute()` → `monitor()`
2. **Debug Script**: `logs.search()` → `read()` → `execute()` → `cache.clear()`
3. **Schedule Task**: `write()` → `schedules.trigger()` → `schedules.scheduleHistory()`
4. **Generate API**: `templates.generate()` → `write()` → `openapi.generate()`
5. **Performance Tune**: `monitor.getScriptPerformance()` → `dependencies.install()` → `cache.clear()`

### SDK Initialization

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

// With existing token
const client = new HoodyClient({
  baseURL: 'https://project-123-exec-456.node.containers.hoody.com',
  token: 'your-jwt-token'
});

// With authentication
await HoodyClient.authenticate(
  'https://project-123-exec-456.node.containers.hoody.com',
  { username: 'user', password: 'pass' }
);
```

### Best Practices

1. **Always validate** scripts before deployment
2. **Use magic comments** for configuration (routes, methods, caching)
3. **Monitor performance** regularly with monitoring endpoints
4. **Pin dependencies** for production stability
5. **Clear caches** after major changes
6. **Use templates** for common patterns
7. **Implement error handling** in all scripts
8. **Generate OpenAPI specs** for API documentation

**Remember**: All endpoints use the exact paths from the inventory. The base URL contains your project, container, and service identifiers. Never use `api.hoody.com` for service endpoints - that's for the Hoody API only.