Skip to content

Commit 10266c7

Browse files
authored
feat(core,agent): add opt-in cross-agent trace correlation (Fixes agentic-ai-java#131) (agentic-ai-java#187)
1 parent f45b2cf commit 10266c7

20 files changed

Lines changed: 2576 additions & 104 deletions

File tree

‎argi-agent-framework/pom.xml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@
7070
<artifactId>argi-graph-core</artifactId>
7171
<version>${project.parent.version}</version>
7272
</dependency>
73+
<dependency>
74+
<groupId>io.micrometer</groupId>
75+
<artifactId>micrometer-observation</artifactId>
76+
</dependency>
7377

7478
<dependency>
7579
<groupId>com.github.victools</groupId>

‎argi-agent-framework/src/main/java/io/github/agentic/ai/graph/agent/a2a/A2aNodeActionWithConfig.java‎

Lines changed: 212 additions & 67 deletions
Large diffs are not rendered by default.

‎argi-agent-framework/src/main/java/io/github/agentic/ai/graph/agent/a2a/A2aRemoteAgent.java‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import io.github.agentic.ai.graph.scheduling.ScheduleConfig;
2929
import io.github.agentic.ai.graph.scheduling.ScheduledAgentTask;
3030
import io.github.agentic.ai.graph.state.strategy.AppendStrategy;
31+
import io.github.agentic.ai.graph.observation.trace.AgentTracer;
3132
import io.a2a.spec.AgentCard;
3233

3334
import java.util.HashMap;
@@ -50,6 +51,8 @@ public class A2aRemoteAgent extends BaseAgent {
5051

5152
private boolean shareState;
5253

54+
private AgentTracer agentTracer;
55+
5356
// Private constructor for Builder pattern
5457
private A2aRemoteAgent(Builder builder) {
5558
super(builder.name, builder.description, builder.includeContents, builder.returnReasoningContents, builder.outputKey, builder.outputKeyStrategy);
@@ -60,6 +63,7 @@ private A2aRemoteAgent(Builder builder) {
6063
this.streaming = builder.streaming;
6164
this.instruction = builder.instruction;
6265
this.shareState = builder.shareState;
66+
this.agentTracer = builder.agentTracer;
6367
}
6468

6569
@Override
@@ -75,7 +79,7 @@ protected StateGraph initGraph() throws GraphStateException {
7579
StateGraph graph = new StateGraph(name, this.keyStrategyFactory);
7680
graph.addNode("A2aNode", AsyncNodeActionWithConfig.node_async(
7781
new A2aNodeActionWithConfig(agentCard, name, includeContents, outputKey, instruction, streaming,
78-
this.shareState, this.compileConfig)));
82+
this.shareState, this.compileConfig, this.agentTracer)));
7983
graph.addEdge(StateGraph.START, "A2aNode");
8084
graph.addEdge("A2aNode", StateGraph.END);
8185
return graph;
@@ -106,7 +110,7 @@ private class A2aRemoteAgentNode extends Node implements SubGraphNode {
106110

107111
public A2aRemoteAgentNode(String id, boolean includeContents, boolean returnReasoningContents, String instruction, AgentCardWrapper agentCard, boolean streaming, boolean shareState, CompiledGraph subGraph) {
108112
super(Objects.requireNonNull(id, "id cannot be null"),
109-
(config) -> AsyncNodeActionWithConfig.node_async(new A2aNodeActionWithConfig(agentCard, subGraph.stateGraph.getName(), includeContents, A2aRemoteAgent.this.outputKey, instruction, streaming, shareState, config)));
113+
(config) -> AsyncNodeActionWithConfig.node_async(new A2aNodeActionWithConfig(agentCard, subGraph.stateGraph.getName(), includeContents, A2aRemoteAgent.this.outputKey, instruction, streaming, shareState, config, A2aRemoteAgent.this.agentTracer)));
110114
this.subGraph = subGraph;
111115
}
112116

@@ -146,6 +150,8 @@ public static class Builder {
146150

147151
private boolean shareState = true;
148152

153+
private AgentTracer agentTracer;
154+
149155
public Builder name(String name) {
150156
this.name = name;
151157
return this;
@@ -201,6 +207,18 @@ public Builder compileConfig(CompileConfig compileConfig) {
201207
return this;
202208
}
203209

210+
/**
211+
* Enable cross-agent trace correlation for the remote calls with the given tracer.
212+
* The tracer is an explicit opt-in; when omitted, no observation is emitted and no
213+
* trace metadata is added to the A2A requests.
214+
* @param agentTracer the cross-agent tracer, may be null
215+
* @return this builder
216+
*/
217+
public Builder agentTracer(AgentTracer agentTracer) {
218+
this.agentTracer = agentTracer;
219+
return this;
220+
}
221+
204222
public Builder streaming(boolean streaming) {
205223
this.streaming = streaming;
206224
return this;

‎argi-agent-framework/src/main/java/io/github/agentic/ai/graph/agent/tools/task/TaskOutputTool.java‎

Lines changed: 113 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,15 @@
2222
import io.github.agentic.ai.api.tool.Tool;
2323
import io.github.agentic.ai.graph.RunnableConfig;
2424
import io.github.agentic.ai.graph.agent.tool.TypedTool;
25+
import io.github.agentic.ai.graph.agent.tools.ToolContextHelper;
2526
import io.github.agentic.ai.graph.execution.TrustedExecutionContext;
27+
import io.github.agentic.ai.graph.observation.trace.AgentTraceContext;
28+
import io.github.agentic.ai.graph.observation.trace.AgentTraceOperation;
29+
import io.github.agentic.ai.graph.observation.trace.AgentTraceSpan;
30+
import io.github.agentic.ai.graph.observation.trace.AgentTracer;
2631
import org.springframework.util.Assert;
2732

33+
import java.util.Map;
2834
import java.util.function.BiFunction;
2935

3036
import static io.github.agentic.ai.graph.agent.tools.ToolContextConstants.AGENT_CONFIG_CONTEXT_KEY;
@@ -54,9 +60,27 @@ Retrieves output from a running or completed background task (sub-agent).
5460

5561
private final TaskRepository taskRepository;
5662

63+
private final AgentTracer agentTracer;
64+
65+
private final TaskTraceCorrelation traceCorrelation;
66+
5767
public TaskOutputTool(TaskRepository taskRepository) {
68+
this(taskRepository, null, null);
69+
}
70+
71+
/**
72+
* Create a TaskOutputTool with optional cross-agent trace correlation. The tracer is an
73+
* explicit opt-in; with a null tracer the historical behavior is preserved exactly.
74+
* @param taskRepository the repository that holds the background tasks
75+
* @param agentTracer the cross-agent tracer, may be null
76+
* @param traceCorrelation the correlation store shared with the TaskTool, may be null
77+
*/
78+
public TaskOutputTool(TaskRepository taskRepository, AgentTracer agentTracer,
79+
TaskTraceCorrelation traceCorrelation) {
5880
Assert.notNull(taskRepository, "taskRepository must not be null");
5981
this.taskRepository = taskRepository;
82+
this.agentTracer = agentTracer;
83+
this.traceCorrelation = traceCorrelation;
6084
}
6185

6286
@Override
@@ -80,34 +104,75 @@ public String apply(Request request, ToolContext toolContext) {
80104
boolean shouldBlock = request.block() == null || request.block();
81105
long timeoutMs = request.timeout() != null ? Math.min(request.timeout(), 600000) : 30000;
82106

83-
if (shouldBlock && !bgTask.isCompleted()) {
84-
try {
85-
bgTask.waitForCompletion(timeoutMs);
86-
}
87-
catch (InterruptedException e) {
88-
Thread.currentThread().interrupt();
89-
return "Error: Wait for task interrupted";
107+
boolean tracing = this.agentTracer != null && this.agentTracer.isEnabled();
108+
AgentTraceContext context = tracing ? receiveContext(request.taskId(), toolContext) : null;
109+
110+
try (AgentTraceSpan span = tracing
111+
? startReceiveSpan(request.taskId(), context)
112+
: AgentTraceSpan.disabled()) {
113+
String outcome = null;
114+
if (shouldBlock && !bgTask.isCompleted()) {
115+
boolean completed = false;
116+
try {
117+
completed = bgTask.waitForCompletion(timeoutMs);
118+
}
119+
catch (InterruptedException e) {
120+
Thread.currentThread().interrupt();
121+
span.outcome("interrupted").success();
122+
return "Error: Wait for task interrupted";
123+
}
124+
outcome = completed ? null : "timeout";
90125
}
91-
}
92126

93-
StringBuilder result = new StringBuilder();
94-
result.append("Task ID: ").append(request.taskId()).append("\n");
95-
result.append("Status: ").append(bgTask.getStatus()).append("\n\n");
127+
StringBuilder result = new StringBuilder();
128+
result.append("Task ID: ").append(request.taskId()).append("\n");
129+
result.append("Status: ").append(bgTask.getStatus()).append("\n\n");
96130

97-
if (bgTask.isCompleted() && bgTask.getResult() != null) {
98-
result.append("Result:\n").append(bgTask.getResult());
99-
}
100-
else if (bgTask.getError() != null) {
101-
result.append("Error:\n").append(bgTask.getError().getMessage());
102-
if (bgTask.getError().getCause() != null) {
103-
result.append("\nCause: ").append(bgTask.getError().getCause().getMessage());
131+
if (bgTask.isCompleted() && bgTask.getResult() != null) {
132+
result.append("Result:\n").append(bgTask.getResult());
133+
}
134+
else if (bgTask.getError() != null) {
135+
result.append("Error:\n").append(bgTask.getError().getMessage());
136+
if (bgTask.getError().getCause() != null) {
137+
result.append("\nCause: ").append(bgTask.getError().getCause().getMessage());
138+
}
139+
span.error(bgTask.getError()).outcome("failed");
140+
return result.toString();
104141
}
142+
else if (!bgTask.isCompleted()) {
143+
result.append("Task still running...");
144+
span.outcome(outcome != null ? outcome : "still-running").success();
145+
return result.toString();
146+
}
147+
148+
span.outcome(outcome != null ? outcome : "completed").success();
149+
return result.toString();
105150
}
106-
else if (!bgTask.isCompleted()) {
107-
result.append("Task still running...");
151+
}
152+
153+
/**
154+
* Start the receive span as a consumer; when the delegation context is known (fan-in
155+
* or long-running waits), the span links back to the delegation id instead of
156+
* depending on thread-local propagation.
157+
*/
158+
private AgentTraceSpan startReceiveSpan(String taskId, AgentTraceContext context) {
159+
AgentTraceSpan span = this.agentTracer.start(AgentTraceOperation.TASK_RECEIVE, context).role("consumer");
160+
if (context != null && context.delegationId() != null) {
161+
span.linkToDelegation(context.delegationId());
108162
}
163+
return span;
164+
}
109165

110-
return result.toString();
166+
private AgentTraceContext receiveContext(String taskId, ToolContext toolContext) {
167+
AgentTraceContext recorded = this.traceCorrelation != null ? this.traceCorrelation.correlation(taskId).orElse(null)
168+
: null;
169+
if (recorded != null) {
170+
return recorded;
171+
}
172+
Map<String, Object> state = ToolContextHelper.getState(toolContext).map(stateValue -> stateValue.data())
173+
.orElse(null);
174+
return AgentTraceContext.capture(ToolContextHelper.getConfig(toolContext).orElse(null), state)
175+
.withTaskId(taskId);
111176
}
112177

113178
/**
@@ -133,6 +198,10 @@ public static class Builder {
133198

134199
private TaskRepository taskRepository;
135200

201+
private AgentTracer agentTracer;
202+
203+
private TaskTraceCorrelation traceCorrelation;
204+
136205
private String name = "TaskOutput";
137206

138207
private String description = DEFAULT_DESCRIPTION;
@@ -143,6 +212,27 @@ public Builder taskRepository(TaskRepository taskRepository) {
143212
return this;
144213
}
145214

215+
/**
216+
* Enable cross-agent trace correlation with the given tracer.
217+
* @param agentTracer the tracer, may be null to keep tracing disabled
218+
* @return this builder
219+
*/
220+
public Builder agentTracer(AgentTracer agentTracer) {
221+
this.agentTracer = agentTracer;
222+
return this;
223+
}
224+
225+
/**
226+
* Share one correlation store between TaskTool and TaskOutputTool so receive spans
227+
* can link to their delegation span.
228+
* @param traceCorrelation the shared store, may be null
229+
* @return this builder
230+
*/
231+
public Builder traceCorrelation(TaskTraceCorrelation traceCorrelation) {
232+
this.traceCorrelation = traceCorrelation;
233+
return this;
234+
}
235+
146236
public Builder withName(String name) {
147237
this.name = name != null ? name : "TaskOutput";
148238
return this;
@@ -155,7 +245,8 @@ public Builder withDescription(String description) {
155245

156246
public Tool build() {
157247
Assert.notNull(this.taskRepository, "taskRepository must be provided");
158-
return TypedTool.builder(this.name, new TaskOutputTool(this.taskRepository))
248+
return TypedTool
249+
.builder(this.name, new TaskOutputTool(this.taskRepository, this.agentTracer, this.traceCorrelation))
159250
.description(this.description)
160251
.inputType(Request.class)
161252
.build();

0 commit comments

Comments
 (0)