snapkitty
developer-tools
c++
SNAPKITTYWEST commited on
Commit
99af586
·
verified ·
1 Parent(s): dcb6526

Add src/hk_agent_fsm.erl

Browse files
Files changed (1) hide show
  1. src/hk_agent_fsm.erl +339 -0
src/hk_agent_fsm.erl ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%-------------------------------------------------------------------
2
+ %%% @doc HK-AGENT :: Agent Runtime state machine.
3
+ %%%
4
+ %%% One `gen_statem' per agent, implementing exactly the state set
5
+ %%% from the specification's `<agent_state>' list and the
6
+ %%% `<browser_agent_loop>':
7
+ %%%
8
+ %%% created -> ready -> planning -> executing -> waiting -> planning -> ...
9
+ %%% \-> completed
10
+ %%% `- (any of planning/executing/waiting) -> failed
11
+ %%% (any non-terminal state) -> terminated (explicit external stop)
12
+ %%%
13
+ %%% Deliberately *not* implemented here: the planning intelligence
14
+ %%% itself (an LLM call or other policy that decides which tool to
15
+ %%% invoke next). That is intentionally external to this module --
16
+ %%% callers (a planner process, a human operator via the API, a
17
+ %%% test) drive the loop one step at a time via `next_action/4',
18
+ %%% supplying the already-decided tool call for this iteration. What
19
+ %%% this module owns is everything the spec calls out as needing to
20
+ %%% be explicit and enforced regardless of what decided the action:
21
+ %%% capability authorization, argument validation, the configurable
22
+ %%% loop limits, action history, and the state machine itself. This
23
+ %%% is the "AGENT INTENT -> EXPLICIT CAPABILITY -> ERLANG SUPERVISED
24
+ %%% PROCESS" boundary from the implementation principle.
25
+ %%%
26
+ %%% Execution is asynchronous by design: `next_action/4' validates
27
+ %%% synchronously (fast, in the caller's context) but performs the
28
+ %%% actual browser/search operation in a spawned worker so the FSM
29
+ %%% process is never blocked on a slow page load -- the FSM sits in
30
+ %%% `waiting' for the worker's `{agent_observation, ...}' message,
31
+ %%% which is a real sojourn in `waiting', not a cosmetic one.
32
+ %%% @end
33
+ %%%-------------------------------------------------------------------
34
+ -module(hk_agent_fsm).
35
+ -behaviour(gen_statem).
36
+
37
+ -include("hyperkitty.hrl").
38
+
39
+ -export([start_link/1]).
40
+ -export([assign_objective/2, next_action/4, complete/2, fail/2, terminate_agent/2, describe/1]).
41
+ -export([callback_mode/0, init/1]).
42
+ -export([created/3, ready/3, planning/3, executing/3, waiting/3,
43
+ completed/3, failed/3, terminated/3]).
44
+
45
+ -define(ACTION_TIMEOUT_MS, 45000).
46
+
47
+ -record(data, {
48
+ agent_id :: binary(),
49
+ objective :: #agent_objective{} | undefined,
50
+ capabilities :: [term()],
51
+ limits :: map(),
52
+ action_count = 0 :: non_neg_integer(),
53
+ network_requests = 0 :: non_neg_integer(),
54
+ search_iterations = 0 :: non_neg_integer(),
55
+ browser_session_ids = [] :: [binary()],
56
+ started_at_ms :: integer(),
57
+ action_history = [] :: [map()],
58
+ pending :: {gen_statem:from(), reference(), map()} | undefined,
59
+ result :: term() | undefined,
60
+ failure_reason :: term() | undefined
61
+ }).
62
+
63
+ %% Args: #{agent_id, capabilities => [...], limits => map() (merged over defaults)}
64
+ start_link(Args) ->
65
+ gen_statem:start_link(?MODULE, Args, []).
66
+
67
+ -spec assign_objective(pid(), binary()) -> ok | {error, term()}.
68
+ assign_objective(Pid, Description) ->
69
+ gen_statem:call(Pid, {assign_objective, Description}).
70
+
71
+ %% @doc Perform one loop iteration: `Tool' is `browser' or `search',
72
+ %% `Op' is the typed operation (see `hk_browser_capability:operation()'
73
+ %% for browser; `start' for search), `Args' is the operation's argument
74
+ %% map. Blocks the caller (not the FSM) until the observation is
75
+ %% available or the per-action timeout fires.
76
+ -spec next_action(pid(), browser | search, atom(), map()) -> {ok, term()} | {error, term()}.
77
+ next_action(Pid, Tool, Op, Args) ->
78
+ gen_statem:call(Pid, {tool_call, Tool, Op, Args}, ?ACTION_TIMEOUT_MS + 5000).
79
+
80
+ -spec complete(pid(), term()) -> ok.
81
+ complete(Pid, Result) ->
82
+ gen_statem:call(Pid, {complete, Result}).
83
+
84
+ -spec fail(pid(), term()) -> ok.
85
+ fail(Pid, Reason) ->
86
+ gen_statem:call(Pid, {fail, Reason}).
87
+
88
+ -spec terminate_agent(pid(), term()) -> ok.
89
+ terminate_agent(Pid, Reason) ->
90
+ gen_statem:call(Pid, {terminate, Reason}).
91
+
92
+ -spec describe(pid()) -> {ok, map()}.
93
+ describe(Pid) ->
94
+ gen_statem:call(Pid, describe).
95
+
96
+ callback_mode() -> state_functions.
97
+
98
+ init(#{agent_id := AgentId} = Args) ->
99
+ Capabilities = maps:get(capabilities, Args, []),
100
+ DefaultLimits = application:get_env(hyperkitty, default_agent_limits, #{}),
101
+ Limits = maps:merge(DefaultLimits, maps:get(limits, Args, #{})),
102
+ Data = #data{
103
+ agent_id = AgentId,
104
+ capabilities = Capabilities,
105
+ limits = Limits,
106
+ started_at_ms = hk_id:timestamp_ms()
107
+ },
108
+ ok = hk_agent_registry:register(AgentId, self()),
109
+ emit(Data, <<"agent.created">>, #{capabilities => Capabilities, limits => Limits}),
110
+ {ok, created, Data}.
111
+
112
+ %%% created
113
+
114
+ created({call, From}, {assign_objective, Description}, Data) ->
115
+ Objective = #agent_objective{
116
+ objective_id = hk_id:new(<<"obj">>),
117
+ agent_id = Data#data.agent_id,
118
+ description = Description,
119
+ created_at_ms = hk_id:timestamp_ms()
120
+ },
121
+ Data2 = Data#data{objective = Objective},
122
+ emit(Data2, <<"agent.objective.assigned">>, #{description => Description}),
123
+ {next_state, ready, Data2, [{reply, From, ok}]};
124
+ created({call, From}, describe, Data) ->
125
+ {keep_state_and_data, [{reply, From, {ok, describe_map(created, Data)}}]};
126
+ created({call, From}, {terminate, Reason}, Data) ->
127
+ do_terminate(From, Reason, Data);
128
+ created(EventType, EventContent, Data) ->
129
+ reject_in_state(created, EventType, EventContent, Data).
130
+
131
+ %%% ready: objective assigned, awaiting the first planning cycle.
132
+
133
+ ready({call, From}, {tool_call, Tool, Op, Args}, Data) ->
134
+ handle_tool_call(executing, From, Tool, Op, Args, Data, ready);
135
+ ready({call, From}, describe, Data) ->
136
+ {keep_state_and_data, [{reply, From, {ok, describe_map(ready, Data)}}]};
137
+ ready({call, From}, {terminate, Reason}, Data) ->
138
+ do_terminate(From, Reason, Data);
139
+ ready(EventType, EventContent, Data) ->
140
+ reject_in_state(ready, EventType, EventContent, Data).
141
+
142
+ %%% planning: ready to accept the next tool call decided by the external planner.
143
+
144
+ planning({call, From}, {tool_call, Tool, Op, Args}, Data) ->
145
+ handle_tool_call(executing, From, Tool, Op, Args, Data, planning);
146
+ planning({call, From}, {complete, Result}, Data) ->
147
+ do_complete(From, Result, Data);
148
+ planning({call, From}, {fail, Reason}, Data) ->
149
+ do_fail(From, Reason, Data);
150
+ planning({call, From}, describe, Data) ->
151
+ {keep_state_and_data, [{reply, From, {ok, describe_map(planning, Data)}}]};
152
+ planning({call, From}, {terminate, Reason}, Data) ->
153
+ do_terminate(From, Reason, Data);
154
+ planning(EventType, EventContent, Data) ->
155
+ reject_in_state(planning, EventType, EventContent, Data).
156
+
157
+ %%% executing: a worker was just spawned for the current tool call;
158
+ %%% this state is transient and immediately moves to `waiting'.
159
+
160
+ executing(internal, {dispatch, Tool, Op, Args, From, Ref}, Data) ->
161
+ Worker = self(),
162
+ _Pid = spawn_link(fun() -> run_worker(Worker, Ref, Tool, Op, Args, Data#data.agent_id) end),
163
+ Data2 = Data#data{pending = {From, Ref, #{tool => Tool, op => Op, args => Args}}},
164
+ {next_state, waiting, Data2, [{state_timeout, ?ACTION_TIMEOUT_MS, action_timeout}]};
165
+ executing(EventType, EventContent, Data) ->
166
+ reject_in_state(executing, EventType, EventContent, Data).
167
+
168
+ %%% waiting: a worker is running; the FSM is not blocked and can
169
+ %%% still answer `describe' or `terminate' while an action is in flight.
170
+
171
+ waiting(info, {agent_observation, Ref, Outcome}, Data = #data{pending = {From, Ref, Call}}) ->
172
+ finish_action(From, Call, Outcome, Data#data{pending = undefined});
173
+ waiting(state_timeout, action_timeout, Data = #data{pending = {From, _Ref, Call}}) ->
174
+ finish_action(From, Call, {error, action_timeout}, Data#data{pending = undefined});
175
+ waiting({call, From}, describe, Data) ->
176
+ {keep_state_and_data, [{reply, From, {ok, describe_map(waiting, Data)}}]};
177
+ waiting({call, From}, {terminate, Reason}, Data) ->
178
+ do_terminate(From, Reason, Data);
179
+ waiting(EventType, EventContent, Data) ->
180
+ reject_in_state(waiting, EventType, EventContent, Data).
181
+
182
+ %%% terminal states
183
+
184
+ completed({call, From}, describe, Data) ->
185
+ {keep_state_and_data, [{reply, From, {ok, describe_map(completed, Data)}}]};
186
+ completed({call, From}, _Other, _Data) ->
187
+ {keep_state_and_data, [{reply, From, {error, agent_completed}}]}.
188
+
189
+ failed({call, From}, describe, Data) ->
190
+ {keep_state_and_data, [{reply, From, {ok, describe_map(failed, Data)}}]};
191
+ failed({call, From}, _Other, _Data) ->
192
+ {keep_state_and_data, [{reply, From, {error, agent_failed}}]}.
193
+
194
+ terminated({call, From}, describe, Data) ->
195
+ {keep_state_and_data, [{reply, From, {ok, describe_map(terminated, Data)}}]};
196
+ terminated({call, From}, _Other, _Data) ->
197
+ {keep_state_and_data, [{reply, From, {error, agent_terminated}}]}.
198
+
199
+ %%% internal
200
+
201
+ handle_tool_call(NextAfterValidate, From, Tool, Op, Args, Data, CurrentStateName) ->
202
+ case check_limits(Data) of
203
+ {error, LimitReason} ->
204
+ %% The call that tripped the limit gets an error reply (it
205
+ %% was refused, not acknowledged); the agent still moves to
206
+ %% `failed' so no further action is accepted after this.
207
+ Data2 = Data#data{failure_reason = {limit_exceeded, LimitReason}},
208
+ emit(Data2, <<"agent.failed">>, #{reason => term_bin({limit_exceeded, LimitReason})}),
209
+ {next_state, failed, Data2, [{reply, From, {error, {limit_exceeded, LimitReason}}}]};
210
+ ok ->
211
+ case hk_browser_capability:is_granted(Data#data.capabilities, grant_key(Tool, Op, Args)) of
212
+ false ->
213
+ emit(Data, <<"agent.action.rejected">>,
214
+ #{tool => Tool, op => Op, reason => not_authorized}),
215
+ {keep_state_and_data, [{reply, From, {error, not_authorized}}]};
216
+ true ->
217
+ case validate_args(Tool, Op, Args) of
218
+ {error, Reason} ->
219
+ emit(Data, <<"agent.action.rejected">>,
220
+ #{tool => Tool, op => Op, reason => term_bin(Reason)}),
221
+ {keep_state_and_data, [{reply, From, {error, {invalid_arguments, Reason}}}]};
222
+ {ok, ValidArgs} ->
223
+ Ref = make_ref(),
224
+ emit(Data, <<"agent.action.started">>,
225
+ #{tool => Tool, op => Op, from_state => CurrentStateName}),
226
+ {next_state, NextAfterValidate, Data,
227
+ [{next_event, internal, {dispatch, Tool, Op, ValidArgs, From, Ref}}]}
228
+ end
229
+ end
230
+ end.
231
+
232
+ grant_key(browser, navigate, Args) -> {navigate, Args};
233
+ grant_key(browser, Op, _Args) -> Op;
234
+ grant_key(search, Op, _Args) -> {search, Op}.
235
+
236
+ validate_args(browser, Op, Args) -> hk_browser_capability:validate_args(Op, Args);
237
+ validate_args(search, start, #{query := Q} = Args) when is_binary(Q), byte_size(Q) > 0 -> {ok, Args};
238
+ validate_args(search, _Op, _Args) -> {error, invalid_search_arguments}.
239
+
240
+ check_limits(Data) ->
241
+ #data{limits = L, action_count = Ac, network_requests = Nr,
242
+ search_iterations = Si, started_at_ms = Start} = Data,
243
+ Now = hk_id:timestamp_ms(),
244
+ MaxActions = maps:get(max_actions, L, 1000000),
245
+ MaxExecutionMs = maps:get(max_execution_ms, L, 3600000),
246
+ MaxNetworkRequests = maps:get(max_network_requests, L, 1000000),
247
+ MaxSearchIterations = maps:get(max_search_iterations, L, 1000000),
248
+ if
249
+ Ac >= MaxActions -> {error, max_actions};
250
+ Now - Start >= MaxExecutionMs -> {error, max_execution_time};
251
+ Nr >= MaxNetworkRequests -> {error, max_network_requests};
252
+ Si >= MaxSearchIterations -> {error, max_search_iterations};
253
+ true -> ok
254
+ end.
255
+
256
+ finish_action(From, Call, Outcome, Data0) ->
257
+ #{tool := Tool, op := Op} = Call,
258
+ HistEntry = #{tool => Tool, op => Op, at_ms => hk_id:timestamp_ms(),
259
+ outcome => outcome_tag(Outcome)},
260
+ Data = Data0#data{
261
+ action_count = Data0#data.action_count + 1,
262
+ network_requests = Data0#data.network_requests + network_cost(Tool),
263
+ search_iterations = Data0#data.search_iterations + search_cost(Tool, Op),
264
+ action_history = [HistEntry | Data0#data.action_history]
265
+ },
266
+ Data2 = track_session(Tool, Op, Outcome, Data),
267
+ case Outcome of
268
+ {ok, Result} ->
269
+ emit(Data2, <<"agent.action.completed">>, #{tool => Tool, op => Op}),
270
+ {next_state, planning, Data2, [{reply, From, {ok, Result}}]};
271
+ {error, Reason} ->
272
+ emit(Data2, <<"agent.action.failed">>, #{tool => Tool, op => Op, reason => term_bin(Reason)}),
273
+ {next_state, planning, Data2, [{reply, From, {error, Reason}}]}
274
+ end.
275
+
276
+ track_session(browser, create_session, {ok, #{session_id := Sid}}, Data) ->
277
+ Data#data{browser_session_ids = [Sid | Data#data.browser_session_ids]};
278
+ track_session(_Tool, _Op, _Outcome, Data) ->
279
+ Data.
280
+
281
+ outcome_tag({ok, _}) -> ok;
282
+ outcome_tag({error, Reason}) -> {error, Reason}.
283
+
284
+ network_cost(browser) -> 1;
285
+ network_cost(search) -> 0.
286
+
287
+ search_cost(search, start) -> 1;
288
+ search_cost(_, _) -> 0.
289
+
290
+ run_worker(Owner, Ref, Tool, Op, Args, AgentId) ->
291
+ Outcome = try hk_agent_toolbox:dispatch(Tool, Op, Args, AgentId)
292
+ catch Class:Reason:Stack ->
293
+ {error, {worker_crashed, Class, Reason, hd(Stack ++ [none])}}
294
+ end,
295
+ Owner ! {agent_observation, Ref, Outcome}.
296
+
297
+ do_complete(From, Result, Data) ->
298
+ Data2 = Data#data{result = Result},
299
+ emit(Data2, <<"agent.completed">>, #{}),
300
+ {next_state, completed, Data2, [{reply, From, ok}]}.
301
+
302
+ do_fail(From, Reason, Data) ->
303
+ Data2 = Data#data{failure_reason = Reason},
304
+ emit(Data2, <<"agent.failed">>, #{reason => term_bin(Reason)}),
305
+ {next_state, failed, Data2, [{reply, From, ok}]}.
306
+
307
+ do_terminate(From, Reason, Data) ->
308
+ emit(Data, <<"agent.terminated">>, #{reason => term_bin(Reason)}),
309
+ {next_state, terminated, Data, [{reply, From, ok}]}.
310
+
311
+ reject_in_state(StateName, {call, From}, _EventContent, _Data) ->
312
+ {keep_state_and_data, [{reply, From, {error, {invalid_in_state, StateName}}}]};
313
+ reject_in_state(_StateName, _EventType, _EventContent, _Data) ->
314
+ keep_state_and_data.
315
+
316
+ describe_map(StateName, Data) ->
317
+ #agent{
318
+ agent_id = Data#data.agent_id,
319
+ objective = Data#data.objective,
320
+ state = StateName,
321
+ capabilities = [cap_atom(C) || C <- Data#data.capabilities],
322
+ action_count = Data#data.action_count,
323
+ started_at_ms = Data#data.started_at_ms,
324
+ updated_at_ms = hk_id:timestamp_ms(),
325
+ limits = Data#data.limits,
326
+ result = Data#data.result,
327
+ failure_reason = Data#data.failure_reason
328
+ }.
329
+
330
+ cap_atom({Op, _}) -> Op;
331
+ cap_atom(Op) -> Op.
332
+
333
+ emit(Data, Category, ExtraData) ->
334
+ Base = #{agent_id => Data#data.agent_id, action_count => Data#data.action_count},
335
+ Event = hk_event:new(Category, {agent, Data#data.agent_id}, maps:merge(Base, ExtraData)),
336
+ catch hk_event_bus:publish(Event).
337
+
338
+ term_bin(Term) ->
339
+ iolist_to_binary(io_lib:format("~p", [Term])).