-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent_manager.ex
More file actions
273 lines (228 loc) · 8.71 KB
/
Copy pathagent_manager.ex
File metadata and controls
273 lines (228 loc) · 8.71 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
defmodule AgentManager do
use GenServer
# Reads config/agents.json and keeps one TaskAgentNode running per enabled
# agent under Ala.NodeSupervisor. Watches the file, so agents can be added,
# edited, enabled, disabled, or removed from the UI without restarting the
# system. Edits and removals always let the agent finish its current task.
#
# agents.json record fields:
# id unique, lowercase letters, numbers, underscore, hyphen
# type marketing, customerservice, socialmedia, or custom
# enabled false means the agent does not run (and is stopped if running)
# tick_minutes timer loop interval
# model any model key from the conversation_turn builders
# permission_mode claude/codex permission tier, blank leaves it unset
#
# Preset types fill in the fields below automatically. A custom agent must
# provide instructions_file, the rest are optional:
# instructions_file role instructions, path relative to homepath
# trigger_label first words of the tick trigger text
# pre_command argv list run each tick, output goes into the trigger
# gate_command argv list printing json, checked before the AI call
# gate_keys the tick runs when any of these json keys is true
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: :agent_manager)
end
def init(_opts) do
settings_path = Path.join(__DIR__, "settings.txt")
settings = case Jason.decode(read_file(settings_path)) do
{:ok, decoded} -> decoded
{:error, _} -> %{}
end
homepath = Map.get(settings, "homepath", "/app/")
config_dir = homepath <> "config"
config_path = config_dir <> "/agents.json"
# the UI drops kill_<id> files here to terminate an agent's current task
commands_dir = homepath <> "work/agent_commands"
File.mkdir_p(commands_dir)
{:ok, watcher_pid} = FileSystem.start_link(dirs: [config_dir, commands_dir])
FileSystem.subscribe(watcher_pid)
state = %{homepath: homepath, config_path: config_path, watcher_pid: watcher_pid, agents: %{}}
{:ok, state, {:continue, :initial_reconcile}}
end
def handle_continue(:initial_reconcile, state) do
{:noreply, reconcile(state)}
end
# ===== EVENT HANDLERS =====
def handle_info({:file_event, _watcher, {path, _events}}, state) do
base = Path.basename(path)
cond do
base == "agents.json" ->
{:noreply, reconcile(state)}
String.starts_with?(base, "kill_") and File.exists?(path) ->
id = String.replace_prefix(base, "kill_", "")
File.rm(path)
if Regex.match?(~r/^[a-z0-9_\-]+$/, id), do: TaskAgentNode.kill_now(id)
{:noreply, state}
true ->
{:noreply, state}
end
end
def handle_info({:file_event, _watcher, :stop}, state) do
{:noreply, state}
end
def handle_info(_msg, state) do
{:noreply, state}
end
def handle_cast({:core_message, _from, _data}, state) do
{:noreply, state}
end
def handle_cast({:master_message, _data}, state) do
{:noreply, state}
end
# ===== RECONCILE =====
defp reconcile(state) do
desired = load_agents(state)
current = state.agents
Enum.each(current, fn {id, _agent} ->
if not Map.has_key?(desired, id), do: TaskAgentNode.remove(id)
end)
# Only record agents that are actually running. A start that fails is logged
# and left out of state.agents, so the next reconcile retries it instead of
# treating the missing agent as present.
started = Enum.reduce(desired, %{}, fn {id, agent}, acc ->
case Map.get(current, id) do
nil ->
case DynamicSupervisor.start_child(Ala.NodeSupervisor, {TaskAgentNode, agent}) do
{:ok, _} -> Map.put(acc, id, agent)
{:error, {:already_started, _}} ->
TaskAgentNode.update_config(id, agent)
Map.put(acc, id, agent)
{:error, reason} ->
log_config_error(state.homepath, "agent " <> id <> " failed to start: " <> inspect(reason))
acc
end
^agent -> Map.put(acc, id, agent)
_changed ->
TaskAgentNode.update_config(id, agent)
Map.put(acc, id, agent)
end
end)
%{state | agents: started}
end
# ===== CONFIG LOADING =====
defp load_agents(state) do
case Jason.decode(read_file(state.config_path)) do
{:ok, %{"agents" => list}} when is_list(list) ->
Enum.reduce(list, %{}, fn record, acc ->
case resolve_agent(record, state.homepath) do
{:ok, agent} ->
if Map.has_key?(acc, agent.id) do
log_config_error(state.homepath, "agent skipped: duplicate id " <> agent.id)
acc
else
Map.put(acc, agent.id, agent)
end
:skip -> acc
{:error, reason} ->
log_config_error(state.homepath, reason)
acc
end
end)
_ ->
# a partial write or hand-edit made agents.json unparseable; keep the
# current set rather than removing every running agent
log_config_error(state.homepath, "agents.json unreadable or invalid; keeping current agent set")
state.agents
end
end
defp resolve_agent(record, homepath) when is_map(record) do
id = Map.get(record, "id", "")
type = Map.get(record, "type", "custom")
enabled = Map.get(record, "enabled", false) == true
cond do
not is_binary(id) or not Regex.match?(~r/^[a-z0-9_\-]+$/, id) ->
{:error, "agent skipped: id must be lowercase letters, numbers, underscore, or hyphen"}
not enabled -> :skip
true ->
defaults = type_defaults(type)
instructions = Map.get(record, "instructions_file", Map.get(defaults, :instructions_file, ""))
if not is_binary(instructions) or String.trim(instructions) == "" do
{:error, "agent " <> id <> " skipped: custom agents need an instructions_file"}
else
prompts = normalize_prompts(Map.get(record, "prompts", Map.get(defaults, :prompts, [])))
if prompts == [] do
{:error, "agent " <> id <> " skipped: needs at least one non-empty prompt"}
else
tick = case Map.get(record, "tick_minutes") do
n when is_integer(n) and n >= 1 -> n
_ -> 15
end
{:ok, %{
id: id,
type: type,
homepath: homepath,
model: Map.get(record, "model", "claude-sonnet"),
permission_mode: Map.get(record, "permission_mode", ""),
tick_minutes: tick,
instructions_file: instructions,
prompts: prompts,
trigger_label: Map.get(record, "trigger_label", Map.get(defaults, :trigger_label, "Scheduled agent tick")),
pre_command: normalize_argv(Map.get(record, "pre_command", Map.get(defaults, :pre_command))),
gate_command: normalize_argv(Map.get(record, "gate_command", Map.get(defaults, :gate_command))),
gate_keys: normalize_keys(Map.get(record, "gate_keys", Map.get(defaults, :gate_keys, [])))
}}
end
end
end
end
defp resolve_agent(_, _), do: {:error, "agent skipped: record is not an object"}
# ===== PRESET TYPES =====
defp type_defaults("marketing") do
%{
instructions_file: "memory/agent_systems/marketing_outreach.md",
trigger_label: "Scheduled outreach tick",
pre_command: ["php", "tools/marketing.php", "checkIncoming"],
gate_command: ["php", "tools/marketing.php", "config"],
gate_keys: ["email_configured", "sms_configured"],
prompts: ["run the tasks outlined above"]
}
end
defp type_defaults("customerservice") do
%{
instructions_file: "memory/agent_systems/customerservice_intake.md",
trigger_label: "Scheduled intake tick",
pre_command: ["php", "tools/customerservice.php", "checkIncoming"],
gate_command: ["php", "tools/customerservice.php", "config"],
gate_keys: ["email_configured"],
prompts: ["run the tasks outlined above"]
}
end
defp type_defaults("socialmedia") do
%{
instructions_file: "memory/agent_systems/socialmedia_engagement.md",
trigger_label: "Scheduled engagement tick",
pre_command: ["python3", "tools/socialmedia.py", "checkIncoming", "all"],
prompts: ["run the tasks outlined above"]
}
end
defp type_defaults(_), do: %{}
# ===== UTILITY FUNCTIONS =====
defp normalize_argv(list) when is_list(list) do
if length(list) > 0 and Enum.all?(list, &is_binary/1), do: list, else: nil
end
defp normalize_argv(_), do: nil
defp normalize_keys(list) when is_list(list), do: Enum.filter(list, &is_binary/1)
defp normalize_keys(_), do: []
# Keeps the user's prompt strings in order, dropping blank or non-string
# entries. An agent left with no usable prompt is a config error, flagged
# upstream the same way a missing instructions_file is.
defp normalize_prompts(list) when is_list(list) do
Enum.filter(list, fn s -> is_binary(s) and String.trim(s) != "" end)
end
defp normalize_prompts(_), do: []
# Broken agent records are owner-actionable, so they surface as flags. The
# filename is derived from the reason so repeated reconciles overwrite one
# flag instead of spamming a new file every config change.
defp log_config_error(homepath, reason) do
File.mkdir_p(homepath <> "threads/flags")
path = homepath <> "threads/flags/flag_acfg_" <> Integer.to_string(:erlang.phash2(reason)) <> ".txt"
File.write(path, "type: system_observation\nsource: agent_manager\ntopic: agents.json config error\n\n" <> reason <> "\n")
end
defp read_file(path) do
case File.read(path) do
{:ok, content} -> content
{:error, _} -> ""
end
end
end