/**
 * Shell Agent
 * Handles: shell-command
 *
 * Two execution modes:
 * - Persistent shell (connect.js) — commands share one shell process
 * - Simple exec (relay-client.js) — each command spawns a new process
 *
 * The caller provides the execution strategy via ctx.execShell or falls back to execCommand.
 */
import { execCommand, DANGEROUS_SHELL_PATTERNS } from './utils.js';

export default {
  name: 'shell',
  actions: {
    'shell-command': async (params, ctx) => {
      const { command, cwd } = params;
      if (!command || typeof command !== 'string') throw new Error('Invalid command');

      // Block dangerous shell patterns
      const cmdLower = command.toLowerCase();
      if (DANGEROUS_SHELL_PATTERNS.some(d => cmdLower.includes(d.toLowerCase()))) {
        throw new Error('Command blocked for safety');
      }

      // Use persistent shell if provided (connect.js), otherwise simple exec
      if (ctx.getPersistentShell) {
        const shell = ctx.getPersistentShell(cwd || process.cwd());
        const result = await shell.exec(command, { timeoutMs: 60000 });
        return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode, cwd: result.cwd };
      }

      // Simple exec fallback
      const result = await execCommand(command, [], { cwd: cwd || process.cwd(), timeout: 60000 });
      return { stdout: result };
    },
  },
};
