_synu_cache.zsh

 1# SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
 2#
 3# SPDX-License-Identifier: Unlicense
 4
 5# Cache management for synu model preferences
 6# File format: agent.slot = model_id (one per line, # comments allowed)
 7
 8typeset -g _SYNU_CACHE_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/synu/models.conf"
 9
10_synu_cache_get() {
11    local agent=$1
12    local slot=$2
13    local key="${agent}.${slot}"
14
15    if [[ ! -f "${_SYNU_CACHE_FILE}" ]]; then
16        return 1
17    fi
18
19    # Match "key = value" or "key=value", ignoring comments and whitespace
20    local line value
21    while IFS= read -r line; do
22        # Skip comments and empty lines
23        [[ "${line}" =~ ^[[:space:]]*# ]] && continue
24        [[ -z "${line}" ]] && continue
25
26        if [[ "${line}" =~ ^${key}[[:space:]]*=[[:space:]]*(.+)$ ]]; then
27            value="${match[1]}"
28            # Trim whitespace
29            echo "${value## }"
30            return 0
31        fi
32    done < "${_SYNU_CACHE_FILE}"
33
34    return 1
35}
36
37_synu_cache_set() {
38    local agent=$1
39    local slot=$2
40    local value=$3
41    local key="${agent}.${slot}"
42
43    # Ensure directory exists
44    mkdir -p "${_SYNU_CACHE_FILE:h}"
45
46    if [[ ! -f "${_SYNU_CACHE_FILE}" ]]; then
47        # Create new file with header
48        cat > "${_SYNU_CACHE_FILE}" <<'EOF'
49# synu model preferences
50# Format: agent.slot = model_id
51
52EOF
53    fi
54
55    # Check if key already exists
56    if grep -q "^${key}[[:space:]]*=" "${_SYNU_CACHE_FILE}" 2>/dev/null; then
57        # Replace existing line
58        local tmp=$(mktemp)
59        sed "s|^${key}[[:space:]]*=.*|${key} = ${value}|" "${_SYNU_CACHE_FILE}" > "${tmp}"
60        mv "${tmp}" "${_SYNU_CACHE_FILE}"
61    else
62        # Append new line
63        echo "${key} = ${value}" >> "${_SYNU_CACHE_FILE}"
64    fi
65}