Repository navigation
Expand file tree
/
Copy pathRequestContext.java
More file actions
365 lines (331 loc) · 11.9 KB
/
Copy pathRequestContext.java
File metadata and controls
365 lines (331 loc) · 11.9 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package io.a2a.server.agentexecution;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import io.a2a.server.ServerCallContext;
import io.a2a.spec.InvalidParamsError;
import io.a2a.spec.Message;
import io.a2a.spec.MessageSendConfiguration;
import io.a2a.spec.MessageSendParams;
import io.a2a.spec.Part;
import io.a2a.spec.Task;
import io.a2a.spec.TextPart;
import org.jspecify.annotations.Nullable;
/**
* Container for request parameters and task state provided to {@link AgentExecutor}.
* <p>
* This class encapsulates all the information an agent needs to process a request:
* the user's message, existing task state (for continuing conversations), configuration,
* and server call context. It's the primary way agents access request data.
* </p>
*
* <h2>Key Components</h2>
* <ul>
* <li><b>Message:</b> The user's input message with parts (text, images, etc.)</li>
* <li><b>Task:</b> Existing task state for continuing conversations (null for new conversations)</li>
* <li><b>TaskId/ContextId:</b> Identifiers for the task and conversation (auto-generated if not provided)</li>
* <li><b>Configuration:</b> Request settings (blocking mode, push notifications, etc.)</li>
* <li><b>Related Tasks:</b> Other tasks in the same conversation context</li>
* </ul>
*
* <h2>Common Usage Patterns</h2>
* <pre>{@code
* public void execute(RequestContext context, AgentEmitter emitter) {
* // Check if this is a new conversation or continuation
* Task existingTask = context.getTask();
* if (existingTask == null) {
* // New conversation - initialize
* } else {
* // Continuing conversation - access history
* List<Message> history = existingTask.history();
* }
*
* // Extract user input
* String userMessage = context.getUserInput("\n");
*
* // Access configuration if needed
* MessageSendConfiguration config = context.getConfiguration();
* boolean isBlocking = config != null && config.blocking();
*
* // Process and respond...
* }
* }</pre>
*
* <h2>Text Extraction Helper</h2>
* The {@link #getUserInput(String)} method is a convenient way to extract text from
* message parts:
* <pre>{@code
* // Get all text parts joined with newlines
* String text = context.getUserInput("\n");
*
* // Get all text parts joined with spaces
* String text = context.getUserInput(" ");
* }</pre>
*
* @see AgentExecutor
* @see Message
* @see Task
* @see MessageSendConfiguration
*/
public class RequestContext {
private @Nullable MessageSendParams params;
private @Nullable String taskId;
private @Nullable String contextId;
private @Nullable Task task;
private List<Task> relatedTasks;
private final @Nullable ServerCallContext callContext;
public RequestContext(
@Nullable MessageSendParams params,
@Nullable String taskId,
@Nullable String contextId,
@Nullable Task task,
@Nullable List<Task> relatedTasks,
@Nullable ServerCallContext callContext) throws InvalidParamsError {
this.params = params;
this.taskId = taskId;
this.contextId = contextId;
this.task = task;
this.relatedTasks = relatedTasks == null ? new ArrayList<>() : relatedTasks;
this.callContext = callContext;
// If the taskId and contextId were specified, they must match the params
if (params != null) {
if (taskId != null && !taskId.equals(params.message().taskId())) {
throw new InvalidParamsError("bad task id");
}
this.taskId = checkOrGenerateTaskId();
if (contextId != null && !contextId.equals(params.message().contextId())) {
throw new InvalidParamsError("bad context id");
}
this.contextId = checkOrGenerateContextId();
}
}
/**
* Returns the task identifier.
* <p>
* This is auto-generated (UUID) if not provided by the client in the message parameters.
* It can be null if the context was not created from message parameters.
* </p>
*
* @return the task ID
*/
public @Nullable String getTaskId() {
return taskId;
}
/**
* Returns the conversation context identifier.
* <p>
* Conversation contexts group related tasks together (e.g., multiple tasks
* in the same user session). This is auto-generated (UUID) if not provided by the client
* in the message parameters. It can be null if the context was not created from message parameters.
* </p>
*
* @return the context ID
*/
public @Nullable String getContextId() {
return contextId;
}
/**
* Returns the existing task state, if this is a continuation of a conversation.
* <p>
* For new conversations, this is null. For continuing conversations, contains
* the full task state including history, artifacts, and status.
* <p>
* <b>Common Pattern:</b>
* <pre>{@code
* if (context.getTask() == null) {
* // New conversation - initialize state
* } else {
* // Continuing - access previous messages
* List<Message> history = context.getTask().history();
* }
* }</pre>
*
* @return the existing task, or null if this is a new conversation
*/
public @Nullable Task getTask() {
return task;
}
/**
* Returns other tasks in the same conversation context.
* <p>
* Useful for multi-task conversations where the agent needs to access
* state from related tasks.
* </p>
*
* @return unmodifiable list of related tasks (empty if none)
*/
public List<Task> getRelatedTasks() {
return Collections.unmodifiableList(relatedTasks);
}
/**
* Returns the user's message.
* <p>
* Contains the message parts (text, images, etc.) sent by the client.
* Use {@link #getUserInput(String)} for convenient text extraction.
* </p>
*
* @return the message, or null if not available
* @see #getUserInput(String)
*/
public @Nullable Message getMessage() {
return params != null ? params.message() : null;
}
/**
* Returns the request configuration.
* <p>
* Contains settings like blocking mode, push notification config, etc.
* </p>
*
* @return the configuration, or null if not provided
*/
public @Nullable MessageSendConfiguration getConfiguration() {
return params != null ? params.configuration() : null;
}
/**
* Returns the server call context.
* <p>
* Contains transport-specific information like authentication, headers, etc.
* Most agents don't need this.
* </p>
*
* @return the call context, or null if not available
*/
public @Nullable ServerCallContext getCallContext() {
return callContext;
}
/**
* Extracts all text content from the message and joins with the specified delimiter.
* <p>
* This is a convenience method for getting text input from messages that may contain
* multiple text parts. Non-text parts (images, etc.) are ignored.
* <p>
* <b>Examples:</b>
* <pre>{@code
* // Join with newlines (common for multi-paragraph input)
* String text = context.getUserInput("\n");
*
* // Join with spaces (common for single-line input)
* String text = context.getUserInput(" ");
*
* // Default delimiter is newline
* String text = context.getUserInput(null); // uses "\n"
* }</pre>
*
* @param delimiter the string to insert between text parts (null defaults to "\n")
* @return all text parts joined with delimiter, or empty string if no message
*/
public String getUserInput(String delimiter) {
if (params == null) {
return "";
}
if (delimiter == null) {
delimiter = "\n";
}
return getMessageText(params.message(), delimiter);
}
public void attachRelatedTask(Task task) {
relatedTasks.add(task);
}
private @Nullable String checkOrGenerateTaskId() {
if (params == null) {
return taskId;
}
if (taskId == null && params.message().taskId() == null) {
// Message is immutable, create new one with generated taskId
String generatedTaskId = UUID.randomUUID().toString();
Message updatedMessage = Message.builder(params.message())
.taskId(generatedTaskId)
.build();
params = new MessageSendParams(updatedMessage, params.configuration(), params.metadata());
return generatedTaskId;
}
if (params.message().taskId() != null) {
return params.message().taskId();
}
return taskId;
}
private @Nullable String checkOrGenerateContextId() {
if (params == null) {
return contextId;
}
if (contextId == null && params.message().contextId() == null) {
// Message is immutable, create new one with generated contextId
String generatedContextId = UUID.randomUUID().toString();
Message updatedMessage = Message.builder(params.message())
.contextId(generatedContextId)
.build();
params = new MessageSendParams(updatedMessage, params.configuration(), params.metadata());
return generatedContextId;
}
if (params.message().contextId() != null) {
return params.message().contextId();
}
return contextId;
}
private String getMessageText(Message message, String delimiter) {
List<String> textParts = getTextParts(message.parts());
return String.join(delimiter, textParts);
}
private List<String> getTextParts(List<Part<?>> parts) {
return parts.stream()
.filter(part -> part instanceof TextPart)
.map(part -> (TextPart) part)
.map(TextPart::text)
.collect(Collectors.toList());
}
public static class Builder {
private @Nullable MessageSendParams params;
private @Nullable String taskId;
private @Nullable String contextId;
private @Nullable Task task;
private @Nullable List<Task> relatedTasks;
private @Nullable ServerCallContext serverCallContext;
public Builder setParams(@Nullable MessageSendParams params) {
this.params = params;
return this;
}
public Builder setTaskId(@Nullable String taskId) {
this.taskId = taskId;
return this;
}
public Builder setContextId(@Nullable String contextId) {
this.contextId = contextId;
return this;
}
public Builder setTask(@Nullable Task task) {
this.task = task;
return this;
}
public Builder setRelatedTasks(@Nullable List<Task> relatedTasks) {
this.relatedTasks = relatedTasks;
return this;
}
public Builder setServerCallContext(@Nullable ServerCallContext serverCallContext) {
this.serverCallContext = serverCallContext;
return this;
}
public @Nullable MessageSendParams getParams() {
return params;
}
public @Nullable String getTaskId() {
return taskId;
}
public @Nullable String getContextId() {
return contextId;
}
public @Nullable Task getTask() {
return task;
}
public @Nullable List<Task> getRelatedTasks() {
return relatedTasks;
}
public @Nullable ServerCallContext getServerCallContext() {
return serverCallContext;
}
public RequestContext build() {
return new RequestContext(params, taskId, contextId, task, relatedTasks, serverCallContext);
}
}
}