File size: 3,159 Bytes
e249c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
 * Bash command execution with streaming support and cancellation.
 */

import { createStreamingBinaryOutputSanitizer } from "../shell-utils.js";
import type { BashOperations } from "./tools/bash-operations.js";
import { OutputAccumulator } from "./tools/output-accumulator.js";

// ============================================================================
// Types
// ============================================================================

export interface BashExecutorOptions {
  /** Callback for streaming output chunks (already sanitized) */
  onChunk?: (chunk: string) => void;
  /** AbortSignal for cancellation */
  signal?: AbortSignal;
}

export interface BashResult {
  /** Combined stdout + stderr output (sanitized, possibly truncated) */
  output: string;
  /** Process exit code (undefined if killed/cancelled) */
  exitCode: number | undefined;
  /** Whether the command was cancelled via signal */
  cancelled: boolean;
  /** Whether the output was truncated */
  truncated: boolean;
  /** Path to temp file containing full output (if output exceeded truncation threshold) */
  fullOutputPath?: string;
}

// ============================================================================
// Implementation
// ============================================================================

/**
 * Execute a bash command using custom BashOperations.
 * Used for remote execution (SSH, containers, etc.).
 */
export async function executeBashWithOperations(
  command: string,
  cwd: string,
  operations: BashOperations,
  options?: BashExecutorOptions,
): Promise<BashResult> {
  const output = new OutputAccumulator({
    tempFilePrefix: "openclaw-bash",
    createTextTransform: () => {
      const sanitizeOutput = createStreamingBinaryOutputSanitizer();
      return (text) => sanitizeOutput(text).replace(/\r/g, "");
    },
  });

  const onData = (data: Buffer, stream?: "stdout" | "stderr") => {
    const text = output.append(data, stream);
    options?.onChunk?.(text);
  };

  const finalizeOutput = async () => {
    const finalText = output.finish();
    const snapshot = output.snapshot({ persistIfTruncated: true });
    try {
      if (finalText) {
        options?.onChunk?.(finalText);
      }
      return snapshot;
    } finally {
      await output.closeTempFile();
    }
  };

  const buildResult = async (
    exitCode: number | undefined,
    cancelled: boolean,
  ): Promise<BashResult> => {
    const snapshot = await finalizeOutput();
    return {
      output: snapshot.content,
      exitCode: cancelled ? undefined : exitCode,
      cancelled,
      truncated: snapshot.truncation.truncated,
      fullOutputPath: snapshot.fullOutputPath,
    };
  };

  let result: Awaited<ReturnType<BashOperations["exec"]>>;
  try {
    result = await operations.exec(command, cwd, {
      onData,
      signal: options?.signal,
    });
  } catch (err) {
    if (options?.signal?.aborted) {
      return await buildResult(undefined, true);
    }
    await finalizeOutput();
    throw err;
  }

  const cancelled = options?.signal?.aborted ?? false;
  return await buildResult(result.exitCode ?? undefined, cancelled);
}