about summary refs log tree commit diff stats
path: root/bash/talk-to-computer/common.sh
blob: 4f11ffe24cc238872b5f087b3239b63b3662d980 (plain) (blame)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/bin/bash

# Common functionality shared across all AI thinking mechanisms
# This file contains utilities and initialization code used by multiple scripts

# --- Script Directory Setup ---
# Get the directory where this script is located
get_script_dir() {
    echo "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
}

# --- Initialization Functions ---

# Initialize a thinking mechanism script with common dependencies
init_thinking_mechanism() {
    local script_path="$1"

    # Set up script directory
    SCRIPT_DIR="$(cd "$(dirname "${script_path}")" && pwd)"

    # Source configuration
    source "${SCRIPT_DIR}/config.sh"

    # Source logging system
    source "${SCRIPT_DIR}/logging.sh"

    # Source quality guard for output quality protection
    source "${SCRIPT_DIR}/quality_guard.sh"

    # Get mechanism name automatically
    MECHANISM_NAME=$(get_mechanism_name "$script_path")

    # Set up resource management
    setup_cleanup_trap

    export SCRIPT_DIR MECHANISM_NAME
}

# Initialize the main dispatcher with common dependencies
init_dispatcher() {
    local script_path="$1"

    # Set up script directory
    SCRIPT_DIR="$(cd "$(dirname "${script_path}")" && pwd)"

    # Source logging system (dispatcher sources this later)
    # source "${SCRIPT_DIR}/logging.sh"

    export SCRIPT_DIR
}

# --- Model Validation Functions ---

# Validate and set a model with fallback
validate_and_set_model() {
    local model_var="$1"
    local model_name="$2"
    local fallback_model="$3"

    local validated_model
    validated_model=$(validate_model "$model_name" "$fallback_model")

    if [ $? -ne 0 ]; then
        log_error "No valid model available for $model_var"
        return 1
    fi

    eval "$model_var=\"$validated_model\""
    echo "Set $model_var to: $validated_model"
}

# --- Argument Processing Functions ---

# Common file path validation
validate_file_arg() {
    local file_path="$1"

    if [ -n "$file_path" ]; then
        validate_file_path "$file_path"
        if [ $? -ne 0 ]; then
            return 1
        fi
    fi

    echo "$file_path"
}

# --- Cleanup Functions ---

# Global array to track resources for cleanup
declare -a CLEANUP_RESOURCES=()

# Register a resource for cleanup
register_cleanup_resource() {
    local resource="$1"
    CLEANUP_RESOURCES+=("$resource")
}

# Clean up temporary resources
cleanup_resources() {
    local exit_code=$?

    # Clean up registered resources
    for resource in "${CLEANUP_RESOURCES[@]}"; do
        if [ -d "$resource" ]; then
            rm -rf "$resource" 2>/dev/null || true
        elif [ -f "$resource" ]; then
            rm -f "$resource" 2>/dev/null || true
        fi
    done

    # Clean up any additional temp directories
    if [ -n "$TEMP_DIR" ] && [ -d "$TEMP_DIR" ]; then
        rm -rf "$TEMP_DIR" 2>/dev/null || true
    fi

    exit $exit_code
}

# Set up trap for cleanup on script exit
setup_cleanup_trap() {
    trap cleanup_resources EXIT INT TERM
}

# Create a temporary directory with automatic cleanup
create_managed_temp_dir() {
    local prefix="${1:-ai_thinking}"
    local temp_dir

    temp_dir=$(mktemp -d -t "${prefix}_XXXXXX")
    register_cleanup_resource "$temp_dir"

    echo "$temp_dir"
}

# Create a temporary file with automatic cleanup
create_managed_temp_file() {
    local prefix="${1:-ai_thinking}"
    local suffix="${2:-tmp}"
    local temp_file

    temp_file=$(mktemp -t "${prefix}_XXXXXX.${suffix}")
    register_cleanup_resource "$temp_file"

    echo "$temp_file"
}

# --- Standardized Error Handling ---

# Standardized error codes
ERROR_INVALID_ARGUMENT=1
ERROR_FILE_NOT_FOUND=2
ERROR_MODEL_UNAVAILABLE=3
ERROR_VALIDATION_FAILED=4
ERROR_PROCESSING_FAILED=5
ERROR_RESOURCE_ERROR=6

# Standardized error handling function
handle_error() {
    local error_code="$1"
    local error_message="$2"
    local script_name="${3:-$(basename "${BASH_SOURCE[1]}")}"
    local line_number="${4:-${BASH_LINENO[0]}}"

    # Log the error
    log_error "[$script_name:$line_number] $error_message"

    # Print user-friendly error message
    echo "Error: $error_message" >&2

    # Exit with appropriate code
    exit "$error_code"
}

# Validation error handler
handle_validation_error() {
    local error_message="$1"
    local script_name="${2:-$(basename "${BASH_SOURCE[1]}")}"

    handle_error "$ERROR_VALIDATION_FAILED" "$error_message" "$script_name" "${BASH_LINENO[0]}"
}

# Model error handler
handle_model_error() {
    local model_name="$1"
    local script_name="${2:-$(basename "${BASH_SOURCE[1]}")}"

    handle_error "$ERROR_MODEL_UNAVAILABLE" "Model '$model_name' is not available" "$script_name" "${BASH_LINENO[0]}"
}

# File error handler
handle_file_error() {
    local file_path="$1"
    local operation="$2"
    local script_name="${3:-$(basename "${BASH_SOURCE[1]}")}"

    handle_error "$ERROR_FILE_NOT_FOUND" "Cannot $operation file: $file_path" "$script_name" "${BASH_LINENO[0]}"
}

# Processing error handler
handle_processing_error() {
    local operation="$1"
    local details="$2"
    local script_name="${3:-$(basename "${BASH_SOURCE[1]}")}"

    handle_error "$ERROR_PROCESSING_FAILED" "Failed to $operation: $details" "$script_name" "${BASH_LINENO[0]}"
}

# --- Utility Functions ---

# Check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Create a temporary directory with cleanup
create_temp_dir() {
    local prefix="${1:-ai_thinking}"
    local temp_dir

    temp_dir=$(mktemp -d -t "${prefix}_XXXXXX")
    echo "$temp_dir"
}

# --- Common Constants ---

# Default values
DEFAULT_ROUNDS=2
DEFAULT_MODEL="gemma3n:e2b"

# File paths
LOG_DIR=~/tmp/ai_thinking

export DEFAULT_ROUNDS DEFAULT_MODEL LOG_DIR