/ scripts / utils / add_session_consult.sh
add_session_consult.sh
  1  #!/bin/bash
  2  # Script to add session_consult tool to all ECHO agents
  3  
  4  set -euo pipefail
  5  
  6  # Agents to update (module name, role atom)
  7  declare -A AGENTS
  8  AGENTS["cto"]="cto"
  9  AGENTS["chro"]="chro"
 10  AGENTS["operations_head"]="operations_head"
 11  AGENTS["product_manager"]="product_manager"
 12  AGENTS["senior_architect"]="senior_architect"
 13  AGENTS["uiux_engineer"]="uiux_engineer"
 14  AGENTS["senior_developer"]="senior_developer"
 15  AGENTS["test_lead"]="test_lead"
 16  
 17  # Tool definition template
 18  TOOL_DEF='      },
 19        %{
 20          name: "session_consult",
 21          description: """
 22          Query the AI assistant with conversation memory (LocalCode-style).
 23  
 24          Maintains multi-turn conversations with automatic context injection:
 25          - Your role, responsibilities, and authority limits
 26          - Recent decisions and messages (last 5 each)
 27          - Current system status (PostgreSQL, Redis, Ollama)
 28          - Git context (branch, last commit)
 29          - Conversation history (last 5 turns)
 30  
 31          Perfect for exploratory questions, decision analysis with iterative thinking,
 32          and strategy planning with follow-up questions.
 33          """,
 34          inputSchema: %{
 35            type: "object",
 36            properties: %{
 37              question: %{
 38                type: "string",
 39                description: "The question to ask the AI assistant",
 40                minLength: 1
 41              },
 42              session_id: %{
 43                type: "string",
 44                description: "Session ID to continue conversation (optional, omit for new session)"
 45              },
 46              context: %{
 47                type: "string",
 48                description: "Additional context for this specific query (optional)"
 49              }
 50            },
 51            required: ["question"]
 52          }
 53        }'
 54  
 55  # Execute tool handler template (will be customized per agent)
 56  EXECUTE_HANDLER_TEMPLATE='
 57    def execute_tool("session_consult", args) do
 58      question = Map.fetch!(args, "question")
 59      session_id = Map.get(args, "session_id")
 60      context = Map.get(args, "context")
 61  
 62      opts = if context, do: [context: context], else: []
 63  
 64      case DecisionHelper.consult_session(AGENT_ROLE, session_id, question, opts) do
 65        {:ok, result} ->
 66          response = format_session_response(result)
 67          {:ok, response}
 68  
 69        {:error, :llm_disabled} ->
 70          {:error, "LLM is disabled for AGENT_NAME. Enable with LLM_ENABLED=true or AGENT_NAME_LLM_ENABLED=true"}
 71  
 72        {:error, :session_not_found} ->
 73          {:error, "Session not found: #{session_id}. It may have expired after 1 hour of inactivity."}
 74  
 75        {:error, reason} ->
 76          {:error, "AI consultation failed: #{inspect(reason)}"}
 77      end
 78    end
 79  '
 80  
 81  # Format session response helper template (will be customized per agent)
 82  FORMAT_HELPER_TEMPLATE='
 83    defp format_session_response(result) do
 84      model = EchoShared.LLM.Config.get_model(AGENT_ROLE)
 85  
 86      base = %{
 87        "response" => result.response,
 88        "session_id" => result.session_id,
 89        "turn_count" => result.turn_count,
 90        "estimated_tokens" => result.total_tokens,
 91        "model" => model,
 92        "agent" => "AGENT_NAME"
 93      }
 94  
 95      if result.warnings != [] do
 96        Map.put(base, "warnings", result.warnings)
 97      else
 98        base
 99      end
100    end'
101  
102  echo "========================================="
103  echo " Adding session_consult to all agents"
104  echo "========================================="
105  echo
106  
107  for agent_dir in "${!AGENTS[@]}"; do
108    role="${AGENTS[$agent_dir]}"
109    file_path="apps/${agent_dir}/lib/${agent_dir}.ex"
110  
111    if [ ! -f "$file_path" ]; then
112      echo "⚠️  Skipping $agent_dir: File not found at $file_path"
113      continue
114    fi
115  
116    echo "📝 Processing $agent_dir (role: $role)..."
117  
118    # Check if already has session_consult
119    if grep -q '"session_consult"' "$file_path"; then
120      echo "   ✓ Already has session_consult, skipping..."
121      continue
122    fi
123  
124    # Create backup
125    cp "$file_path" "${file_path}.backup"
126  
127    # Add tool definition (find last tool in list, add before closing ])
128    # This is fragile - find the line with last tool's closing }, before ]
129    # Look for the pattern: "      }\n    ]\n  end" and insert before ]
130  
131    # Create temporary files
132    TOOL_TMP=$(mktemp)
133    HANDLER_TMP=$(mktemp)
134    FORMAT_TMP=$(mktemp)
135  
136    # Customize templates with agent-specific values
137    echo "$TOOL_DEF" > "$TOOL_TMP"
138    echo "$EXECUTE_HANDLER_TEMPLATE" | sed "s/AGENT_ROLE/:$role/g" | sed "s/AGENT_NAME/$agent_dir/g" > "$HANDLER_TMP"
139    echo "$FORMAT_HELPER_TEMPLATE" | sed "s/AGENT_ROLE/:$role/g" | sed "s/AGENT_NAME/$agent_dir/g" > "$FORMAT_TMP"
140  
141    # Use awk to insert in the right places
142    awk -v tool="$(<$TOOL_TMP)" -v handler="$(<$HANDLER_TMP)" -v helper="$(<$FORMAT_TMP)" '
143      # State machine
144      /^    \]$/  && !tool_added && in_tools {
145        print tool
146        print $0
147        tool_added = 1
148        in_tools = 0
149        next
150      }
151      /def tools do/ {
152        in_tools = 1
153      }
154      /def execute_tool\(name, _args\) do/ && !handler_added {
155        print handler
156        handler_added = 1
157      }
158      /^end$/ && !helper_added {
159        print helper
160        helper_added = 1
161      }
162      { print }
163    ' "$file_path" > "${file_path}.tmp"
164  
165    mv "${file_path}.tmp" "$file_path"
166  
167    # Cleanup
168    rm -f "$TOOL_TMP" "$HANDLER_TMP" "$FORMAT_TMP"
169  
170    # Compile to check for errors
171    echo "   🔨 Compiling..."
172    if (cd "apps/$agent_dir" && mix compile 2>&1 | grep -q "Generated"); then
173      echo "   ✅ $agent_dir: Success!"
174      rm "${file_path}.backup"
175    else
176      echo "   ❌ $agent_dir: Compilation failed!"
177      echo "   Restoring backup..."
178      mv "${file_path}.backup" "$file_path"
179    fi
180  
181    echo
182  done
183  
184  echo "========================================="
185  echo " Summary"
186  echo "========================================="
187  echo "✅ Updated all agents with session_consult tool"
188  echo "Run './rebuild_all.sh' to rebuild all executables"