Repository navigation
Expand file tree
/
Copy pathAgentRunExecutor.java
More file actions
279 lines (262 loc) · 12.3 KB
/
Copy pathAgentRunExecutor.java
File metadata and controls
279 lines (262 loc) · 12.3 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
274
275
276
277
278
279
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.reactor.agent.run;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import prerna.engine.impl.model.Room;
import prerna.om.ThreadStore;
import prerna.reactor.agent.AgentHarnessResult;
import prerna.reactor.agent.AgentRunner;
import prerna.reactor.agent.exceptions.AgentCancelledException;
import prerna.reactor.agent.exceptions.AgentInputRequiredException;
import prerna.reactor.agent.stream.AgentRunStreamService;
import prerna.reactor.agent.stream.AgentStreamItems;
import prerna.reactor.agent.subagent.AgentSubAgentRegistry;
import prerna.reactor.agent.subagent.SubAgentMeta;
import prerna.security.SecretRedactor;
/**
* Runs one agent run to completion and records how it ended.
*
* <p>
* {@link AgentRunQueueLoop} decides which runs start and on what thread; this
* class is what that thread does. It seeds the run's identity, invokes the
* harness, and translates the outcome into a durable status plus the stream
* events a parent run needs.
*
* <h3>How an outcome is classified</h3> The harness signals its result by
* throwing, so the catch block is the real decision point:
* <ul>
* <li>a cancel, direct or via the thread's interrupt flag, settles the run as
* {@code CANCELLED};</li>
* <li>{@link AgentInputRequiredException} means the harness paused on a tool
* needing approval and is not terminal, so the run becomes
* {@code INPUT_REQUIRED} and no terminal stream event is published;</li>
* <li>anything else is {@code FAILED}.</li>
* </ul>
*/
final class AgentRunExecutor {
private static final Logger logger = LogManager.getLogger(AgentRunExecutor.class);
/** Cap on what gets written to the {@code ERROR_MESSAGE} column. */
private static final int MAX_ERROR_LENGTH = 8000;
private AgentRunExecutor() {
}
/**
* Runs the harness on the calling thread and records the outcome.
*
* <p>
* {@code activeRun} is passed rather than looked up by id because a cancel
* unregisters the run as it releases the room; the object outlives the registry
* entry and is what still carries the cancel flag.
*/
static void execute(AgentRunRecord record, InsightHandle insightHandle, AgentRunRegistry.ActiveRun activeRun,
Room automationResumeRoom) {
String runId = record.runId();
String jobId = runId;
String parentRunId = record.request() != null ? record.request().getParentRunId() : null;
try {
insightHandle.seedThreadStore(runId);
// A cancel can land after the room is claimed but before this thread starts,
// and interrupting an unstarted thread does nothing. The flag is the only
// record of it, so check before announcing RUNNING or doing any work.
if (activeRun.isCancelRequested()) {
throw new AgentCancelledException();
}
publishSubagentPatch(parentRunId, runId, AgentRunStatus.RUNNING);
AgentRunRequest request = record.request();
// Detect resume: the persisted request always has resumeMode=false on initial
// submission, so fall back to checking for existing AGENT_RUN_ACTION rows.
boolean resumeMode = request.isResumeMode() || AgentRunActionStore.hasAnyActions(runId);
AgentHarnessResult result = automationResumeRoom == null
? AgentRunner.run(request.getRoomId(), request.getInput(), request.getEngineIdFallback(),
request.getHarnessType(), request.getMaxTurns(), request.getMaxReflections(),
request.getParamMap(), request.getAgentParamMap(), request.getMediaInputPaths(),
request.getMediaUrls(), runId, insightHandle.insight(), resumeMode)
: AgentRunner.resumeAutomationRun(request.getRoomId(), request.getInput(),
request.getEngineIdFallback(), request.getHarnessType(), request.getMaxTurns(),
request.getMaxReflections(), request.getParamMap(), request.getAgentParamMap(),
request.getMediaInputPaths(), request.getMediaUrls(), runId, insightHandle.insight(),
automationResumeRoom);
if (result != null) {
AgentRunStore.markInputMessage(runId, result.getInputMessageId());
}
jobId = firstNonBlank(ThreadStore.getJobId(), jobId);
if (result != null) {
AgentRunStore.markFinalOutputMessage(runId, result.getFinalOutputMessageId());
}
if (Thread.currentThread().isInterrupted()) {
throw new AgentCancelledException();
}
String completionError = result == null ? null : result.getCompletionError();
String finalText = result == null ? null : result.getFinalText();
boolean recorded = completionError == null ? AgentRunStore.markCompleted(runId, jobId, finalText)
: AgentRunStore.markIncomplete(runId, jobId, finalText, completionError);
AgentRunStreamService.get().markTerminal(runId);
if (recorded) {
publishSubagentTerminal(parentRunId, record, runId,
completionError == null ? AgentRunStatus.COMPLETED : AgentRunStatus.FAILED, finalText,
completionError);
} else {
AgentRunStore.recordFinalOutputAfterCancel(runId, finalText);
publishCancelledMeanwhile(parentRunId, record, runId);
}
queueChildCompletion(parentRunId, record, runId);
} catch (Exception e) {
// A cancel reaches this thread as an interrupt and the flag is still set.
// Clear it before the bookkeeping below, because this thread is virtual and
// an interrupted virtual thread closes whatever socket it blocks on -- which
// here would be the shared connection these status writes need, taking the
// engine down for every other caller too. The flag is not restored: the run
// is over, and the teardown that follows this method also does I/O.
boolean interrupted = Thread.interrupted();
jobId = firstNonBlank(ThreadStore.getJobId(), jobId);
if (isCancelled(e, interrupted)) {
// A stop, a cascade or an admin closing the room records why, and when, as it
// cancels the run; keep that over the exception the interrupt surfaced as.
AgentRunStore.markCancelledIfNotTerminal(runId, jobId, boundedError(e));
AgentRunStreamService.get().markTerminal(runId);
publishSubagentTerminal(parentRunId, record, runId, AgentRunStatus.CANCELLED, null, boundedError(e));
queueChildCompletion(parentRunId, record, runId);
logger.info("AgentRunExecutor: runId={} cancelled: {}", runId, e.getMessage());
} else if (e instanceof AgentInputRequiredException) {
// The harness already persisted the AGENT_RUN_ACTION rows; only
// transition the durable run status here.
AgentRunStore.markInputRequired(runId, jobId);
publishSubagentPatch(parentRunId, runId, AgentRunStatus.INPUT_REQUIRED);
logger.info("AgentRunExecutor: runId={} paused for user input", runId);
} else {
boolean recorded = AgentRunStore.markFailed(runId, jobId, boundedError(e));
AgentRunStreamService.get().markTerminal(runId);
if (recorded) {
publishSubagentTerminal(parentRunId, record, runId, AgentRunStatus.FAILED, null, boundedError(e));
} else {
publishCancelledMeanwhile(parentRunId, record, runId);
}
queueChildCompletion(parentRunId, record, runId);
logger.warn("AgentRunExecutor: runId={} failed: {}", runId, e.getMessage(), e);
}
} finally {
ThreadStore.remove();
}
}
private static void queueChildCompletion(String parentRunId, AgentRunRecord record, String childRunId) {
if (parentRunId != null && !parentRunId.isBlank() && record.request() != null
&& record.request().getCompletionMode() != SubAgentRunCompletionMode.WAIT) {
AgentRunService.get().queueChildCompletion(childRunId);
}
}
private static void publishSubagentPatch(String parentRunId, String childRunId, AgentRunStatus status) {
if (parentRunId == null || parentRunId.isBlank()) {
return;
}
Map<String, Object> patch = new HashMap<>();
patch.put("status", status.name());
AgentRunStreamService.get().publishSubagentUpdated(parentRunId, childRunId, patch);
}
/**
* Reports a run that was cancelled while it ran, such as by a room closed from
* another server, as the cancel its row keeps rather than the outcome this
* thread reached, so the parent's live view and the database agree.
*
* @param parentRunId the run that spawned it, or null
* @param record the run
* @param runId the run's id
*/
private static void publishCancelledMeanwhile(String parentRunId, AgentRunRecord record, String runId) {
logger.info("AgentRunExecutor: runId={} was cancelled before it finished; it stays cancelled", runId);
if (parentRunId != null && !parentRunId.isBlank()) {
publishSubagentTerminal(parentRunId, record, runId, AgentRunStatus.CANCELLED, null,
AgentRunStore.getErrorMessage(runId));
}
}
private static void publishSubagentTerminal(String parentRunId, AgentRunRecord record, String runId,
AgentRunStatus status, String resultPreview, String error) {
if (parentRunId == null || parentRunId.isBlank()) {
return;
}
String alias = null;
String workspaceId = record.request() != null ? record.request().getWorkspaceId() : null;
SubAgentMeta meta = AgentSubAgentRegistry.getManager().lookup(runId);
if (meta != null) {
alias = meta.getAlias();
if (meta.getWorkspaceId() != null) {
workspaceId = meta.getWorkspaceId();
}
}
Map<String, Object> item = AgentStreamItems.subagentItem(runId, alias, record.roomId(), workspaceId,
status.name());
if (resultPreview != null && !resultPreview.isBlank()) {
item.put("resultPreview",
AgentStreamItems.truncate(resultPreview, AgentStreamItems.MAX_RESULT_PREVIEW_CHARS));
}
if (error != null && !error.isBlank()) {
item.put("error", AgentStreamItems.truncate(error, AgentStreamItems.MAX_RESULT_PREVIEW_CHARS));
}
AgentRunStreamService.get().publishSubagentCompleted(parentRunId, item);
}
/**
* Whether {@code t} represents a cancel rather than a failure, so the run
* settles as {@code CANCELLED}.
*
* @param interrupted whether the run's thread was interrupted, read and cleared
* by the caller. It counts as a cancel because a cancel
* interrupts the run's thread, and whatever that unblocks
* may surface as an unrelated exception type
*/
private static boolean isCancelled(Throwable t, boolean interrupted) {
Throwable cur = t;
while (cur != null) {
if (cur instanceof AgentCancelledException) {
return true;
}
cur = cur.getCause();
}
return interrupted;
}
/**
* Message for the {@code ERROR_MESSAGE} column, never null and never oversized.
*/
private static String boundedError(Throwable t) {
String message = t == null ? null : t.getMessage();
if (message == null || message.trim().isEmpty()) {
message = t == null ? "Unknown agent run failure" : t.getClass().getName();
}
message = SecretRedactor.redactError(message);
if (message.length() <= MAX_ERROR_LENGTH) {
return message;
}
return message.substring(0, MAX_ERROR_LENGTH);
}
private static String firstNonBlank(String first, String second) {
if (first != null && !first.trim().isEmpty()) {
return first;
}
return second;
}
}