<!--
hoody-terminal Subskill (sdk)
Auto-generated by Hoody Skills Generator
Generated: 2026-06-20T00:04:40.691Z
Model: mimo-v2.5-pro + fixer:mimo-v2.5-pro
Mode: sdk


Tokens: 9334

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

# hoody-terminal Subskill

## Overview

`hoody-terminal` provides HTTP-accessible terminal sessions that are multiplayer by default. Every terminal session becomes a REST endpoint, enabling command execution, screen automation, process management, and system monitoring — all without maintaining persistent SSH connections.

**When to use this service:**
- Running shell commands in container environments programmatically
- Building browser-based terminal UIs or remote desktops
- Automating CLI tools via snapshot/find/wait/patterns
- Monitoring and managing system processes, ports, and resources
- Capturing terminal screenshots or raw output buffers
- Multi-client collaboration on shared terminal sessions

**Hoody philosophy fit:** Terminals are treated as first-class HTTP resources. Sessions are created on-demand, addressable by ID, and support both synchronous and asynchronous execution. WebSocket connections layer real-time I/O on top of the same session model. This removes the need for persistent SSH tunnels or tmux socket management.

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

All paths below are appended directly to this base URL with no additional prefix.

---

## Common Workflows

### 1. Create a Session and Execute a Command

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

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

// Create a terminal session
const session = await client.terminal.sessions.create({})

// Execute a command in that session
const execution = await client.terminal.execution.execute({
  command: 'ls -la /hoody/storage'
})

// Poll for result using the returned command_id
const result = await client.terminal.execution.getResult(execution.command_id)
```

**Verification:** After `getResult`, check `result.exit_code === 0` and inspect `result.stdout` for expected output.

### 2. Fire-and-Forget: Run Command, Retrieve Result Later

```
// Execute with deferred result retrieval
const execution = await client.terminal.execution.execute({
  command: 'npm run build'
})

// Do other work...
// Later, fetch result (works while running or after completion)
const result = await client.terminal.execution.getResult(execution.command_id)

if (result.status === 'running') {
  // Command still in progress
} else {
  console.log(result.exit_code, result.stdout)
}
```

### 3. Write Raw Input to a Terminal

```
// Create session first
const session = await client.terminal.sessions.create({})

// Write keystrokes directly (Enter appended by default)
await client.terminal.write(session.terminal_id, { data: 'echo hello' })

// To send without auto-Enter:
await client.terminal.write(session.terminal_id, { data: 'partial line', append_newline: false })
```

### 4. Abort a Running Command

```
const execution = await client.terminal.execution.execute({
  command: 'sleep 999'
})

// Graceful abort (SIGINT, like Ctrl+C)
await client.terminal.abort(execution.command_id)

// Or force kill
await client.terminal.abort(execution.command_id, { force: true })
```

### 5. Session Lifecycle Management

```
// List all active sessions
const sessions = await client.terminal.sessions.list({ history_limit: 5 })

// Get command history for a specific session
const history = await client.terminal.sessions.listHistory({ terminal_id: 'terminal-abc123' })

// Get raw output buffer
const raw = await client.terminal.sessions.getRawOutput({ terminal_id: 'terminal-abc123', format: 'text' })

// Capture screenshot (saved to /hoody/storage/hoody-terminal/screenshots/)
const screenshot = await client.terminal.sessions.captureScreenshot({
  terminal_id: 'terminal-abc123',
  fontsize: 14
})

// Destroy session and free all resources
await client.terminal.sessions.delete({ terminal_id: 'terminal-abc123' })
```

### 6. Check Service Health

```
const health = await client.terminal.health.check()
// Returns 9-field health object, HTTP 200 when service is up
```

### 7. Real-Time Terminal via WebSocket

```
// Establish WebSocket for bidirectional I/O (multiple clients can share)
client.terminal.sessions.connectWebSocket({
  terminal_id: 'terminal-abc123'
})
```

### 8. Browser-Based Terminal UI

```
// Returns the HTML page — pass parameters for session/display/SSH customization
const page = await client.terminal.web.get({
  terminal_id: 'terminal-abc123',
  fontSize: 14,
  backgroundColor: '#1e1e1e',
  hide_toolbar: false
})
```

---

## Advanced Operations

### 1. Terminal Automation: Snapshot → Find → Act

This pattern automates interactive CLI tools by reading the screen and responding.

```
// Step 1: Get a rendered snapshot of the terminal
const snapshot = await client.terminal.terminalAutomation.getTerminalSnapshot({
  terminal_id: 'terminal-abc123',
  include_colors: false
})
// snapshot.lines is the visible text grid; snapshot.cursor contains position

// Step 2: Search for a pattern on screen
const hits = await client.terminal.terminalAutomation.findInTerminal({
  terminal_id: 'terminal-abc123',
  pattern: 'Password:',
  scope: 'screen',
  case_insensitive: true
})

// Step 3: If found, send input
if (hits.length > 0) {
  await client.terminal.terminalAutomation.pasteTerminalText({
    terminal_id: 'terminal-abc123',
    text: 'my-secret-password'
  })
  await client.terminal.terminalAutomation.pressTerminalKeys({
    terminal_id: 'terminal-abc123',
    keys: ['Enter']
  })
}
```

### 2. Wait for Terminal Condition

Block until the screen stabilizes or a pattern appears — essential for reliable automation.

```
// Wait for a prompt to appear (stable screen, no changes for 500ms)
const snapshot = await client.terminal.terminalAutomation.waitForTerminal({
  terminal_id: 'terminal-abc123',
  mode: 'regex',
  pattern: '\\$\\s*$',
  debounce_ms: 500,
  timeout_ms: 10000
})
// Returns atomic snapshot at the moment of resolution
```

### 3. Mouse Event Automation

```
// Send a click at row 5, column 10
await client.terminal.terminalAutomation.sendTerminalMouseEvents({
  terminal_id: 'terminal-abc123',
  events: [
    { type: 'click', row: 5, col: 10 }
  ]
})

// Scroll up
await client.terminal.terminalAutomation.sendTerminalMouseEvents({
  terminal_id: 'terminal-abc123',
  events: [
    { type: 'scroll', direction: 'up', row: 10, col: 20 }
  ]
})
```

### 4. System Monitoring and Process Control

```
// List all processes with filtering
const processes = await client.terminal.system.listProcesses({
  sort: 'cpu',
  limit: 20,
  filter: 'node'
})

// Get details for a specific process
const detail = await client.terminal.system.getProcess(1234)

// Send signal to processes by name
await client.terminal.system.sendSignal({
  name: 'node',
  signal: 'SIGTERM'
})

// Freeze/unfreeze process trees
await client.terminal.system.freezeProcess({ pid: 1234, include_descendants: true })
await client.terminal.system.unfreezeProcess({ pid: 1234, include_descendants: true })

// List listening ports with filters
const ports = await client.terminal.system.listPorts({ protocol: 'tcp', hoody_only: true })

// Get system resources overview
const resources = await client.terminal.system.getResources()

// Display information
const displays = await client.terminal.system.getDisplayInfo()

// Daemon configuration
const daemons = await client.terminal.system.getDaemonConfig()
```

### 5. SSH Session via Terminal

```
// Create an SSH terminal session by specifying SSH params on execute
const execution = await client.terminal.execution.execute({
  command: 'hostname',
  ssh_host: '192.168.1.100',
  ssh_user: 'deploy',
  ssh_key: '/hoody/storage/keys/deploy.pem'
})
```

### 6. Error Recovery: Abort + Restart

```
// Create a terminal session
const session = await client.terminal.sessions.create({})

let execution
try {
  execution = await client.terminal.execution.execute({ command: 'make build' })
  const result = await client.terminal.execution.getResult(execution.command_id)
  if (result.exit_code !== 0) throw new Error(`Build failed: ${result.stderr}`)

  const deploy = await client.terminal.execution.execute({ command: 'make deploy' })
  const deployResult = await client.terminal.execution.getResult(deploy.command_id)
} catch (err) {
  // Abort any running command
  if (execution) {
    await client.terminal.abort(execution.command_id, { force: true })
  }

  // Destroy and recreate session for clean state
  await client.terminal.sessions.delete(session.terminal_id)
  const fresh = await client.terminal.sessions.create({})
}
```

### 7. Performance Considerations

- **Session reuse:** Create once, execute many. Session creation blocks until display port is ready (if configured).
- **Async execution:** `execute` returns immediately with a `command_id`. Poll via `getResult` for long-running commands.
- **Automation metrics:** Monitor resource usage to avoid exhausting VT parser limits.
- **Screencapture:** Screenshot generation is CPU-intensive; avoid high-frequency polling.

```
const metrics = await client.terminal.terminalAutomation.getAutomationMetrics()
// Check active sessions, memory usage, and wait-waiter counts
```

### 8. API Documentation Retrieval

```
const specJson = await client.terminal.docs.getJson()
const specYaml = await client.terminal.docs.getYaml()
```

### 9. Supported Keys Discovery

```
const keys = await client.terminal.terminalAutomation.listSupportedKeys()
// Returns all key names accepted by /press endpoint

const state = await client.terminal.terminalAutomation.getSessionAutomationState({
  terminal_id: 'terminal-abc123'
})
// Returns vterm state, dimensions, alt-screen flag, active waitees
```

---

## Quick Reference

### Most Common Endpoints

| Operation | SDK Method | HTTP |
|-----------|-----------|------|
| Health check | `client.terminal.health.check()` | `GET /api/v1/terminal/health` |
| Create session | `client.terminal.sessions.create({})` | `POST /api/v1/terminal/create` |
| Execute command | `client.terminal.execution.execute({command})` | `POST /api/v1/terminal/execute` |
| Get result | `client.terminal.execution.getResult(cmd_id)` | `GET /api/v1/terminal/result/{command_id}` |
| Write input | `client.terminal.write(terminal_id, {data})` | `POST /api/v1/terminal/write` |
| Abort command | `client.terminal.abort(cmd_id)` | `POST /api/v1/terminal/execute/{command_id}/abort` |
| List sessions | `client.terminal.sessions.list()` | `GET /api/v1/terminal/sessions` |
| Delete session | `client.terminal.sessions.delete(id)` | `DELETE /api/v1/terminal/{terminal_id}` |
| Screenshot | `client.terminal.sessions.captureScreenshot({terminal_id})` | `GET /api/v1/terminal/screenshot` |
| System resources | `client.terminal.system.getResources()` | `GET /api/v1/system/resources` |

### Essential Parameters

- **terminal_id**: Required for write, screenshot, delete, history, snapshot, find, press, mouse, paste, wait
- **command_id**: Returned by `execute`; used for `getResult` and `abort`
- **command** (request body): The shell command string for `execute`
- **pattern**: PCRE2 regex for `find` and `wait` modes
- **format**: Output format for raw endpoint (`text`, `html`, `json`)

### Typical Response Formats

Health check returns a 9-field object. Execution returns `{ command_id, status }`. Result returns `{ exit_code, stdout, stderr, status }`. Sessions list returns JSON array with metadata and recent history. System endpoints return JSON arrays or objects with process/port/resource data.