Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,21 @@ under the License.
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ public enum ResourceType {
TOOL("tool"),
MCP_SERVER("mcp_server"),
SKILLS("skills"),
MODEL_ROUTER("model_router");
MODEL_ROUTER("model_router"),
AGENT("agent");

private final String value;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/

package org.apache.flink.agents.api.subagent;

/**
* Handle for one sub-agent invocation, identified by the {@code (sessionId, callId)} pair that keys
* the invocation.
*/
public abstract class SubagentFuture {

private final String sessionId;
private final String callId;

protected SubagentFuture(String sessionId, String callId) {
this.sessionId = sessionId;
this.callId = callId;
}

public String getSessionId() {
return sessionId;
}

public String getCallId() {
return callId;
}

/** Whether the invocation has reached a terminal state. */
public abstract boolean isDone();

/**
* Resolves the invocation, waiting until it reaches a terminal state. Failures converge into a
* failed {@link SubagentResult} rather than a separately reported exceptional completion.
*/
public abstract SubagentResult await() throws Exception;

/** Requests cancellation of the invocation. */
public void cancel() {}

/** Groups this handle with others to be resolved together through {@link SubagentFutures}. */
public abstract SubagentFutures combine(SubagentFuture... others);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/

package org.apache.flink.agents.api.subagent;

import java.util.List;

/**
* A group of sub-agent handles to be resolved together. A group is not itself an invocation and
* carries no {@code (sessionId, callId)} identity.
*/
public abstract class SubagentFutures {

/** Whether every handle in the group has reached a terminal state. */
public abstract boolean isDone();

/**
* Waits for every handle in the group and returns their outcomes in the order the handles were
* added. Like {@link SubagentFuture#await()}, failures surface through failed {@link
* SubagentResult}s.
*/
public abstract List<SubagentResult> awaitAll() throws Exception;

/** Requests cancellation of every handle in the group. */
public void cancel() {}

/** Adds more handles to the group. */
public abstract SubagentFutures combine(SubagentFuture... others);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/

package org.apache.flink.agents.api.subagent;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

/**
* Outcome of a sub-agent call issued through {@link SubagentSetup}. A successful outcome carries a
* JSON-serializable payload, and a failed one carries a serializable error message.
*
* <p>Implementations capture their internal failures into a result through {@link #error} instead
* of throwing, so callers inspect {@link #isSuccess()} rather than catching. Because the failure is
* carried as a message rather than a live exception, the whole result can be persisted through
* durable execution and survive a failover.
*/
public class SubagentResult implements Serializable {

private static final Logger LOG = LoggerFactory.getLogger(SubagentResult.class);

private static final long serialVersionUID = 1L;

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

private final boolean success;
private final Object result;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

result is typed Object, BaseSubagentCallable.getResultClass() pins the durable result class to Result.class (BaseSubagentCallable.java:47-48), and recovery re-binds through the plain OBJECT_MAPPER at RunnerContextImpl.java:516, which is constructed with no polymorphic typing (:67-68).

I round-tripped a small POJO payload through this Result with writeValueAsString / readValue(s, Result.class):

serialized: {"success":true,"result":{"verdict":"approve","score":7},"errorMessage":null}
payload class after replay: java.util.LinkedHashMap
ClassCastException: class java.util.LinkedHashMap cannot be cast to class Review

So getResult() hands back the author's type on the first execution and a LinkedHashMap after a failover replay. The shipped example casts at ExternalSubagentAgent.java:52 (((List<?>) result.getResult()).get(0)) and survives only because JSON arrays bind to ArrayList. Every payload in the suite is a String or a List<String> (MockExternalSubagentSetup.java:92, SubagentIdentityRecoveryTest.java:108), so nothing currently exercises the shape that breaks.

Python does not diverge here. Its durable payload goes through cloudpickle (flink_runner_context.py:430,473), which preserves the type, so this is also a Java/Python semantic gap on new public API that AGENTS.md asks to keep aligned.

What should getResult() return after a replay when the sub-agent returned a record or a POJO? A couple of routes, in case they help: making Result generic and threading the payload class through getResultClass(), or keeping the field opaque and adding getResult(Class<T>) backed by OBJECT_MAPPER.convertValue. Either way a test with a non-String, non-collection payload would pin the behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching this — it's a real oversight. I'm currently working on the cross-language sub-agent invocation design and ran into the same issue there.

The plan is to add getResult(Class<T>) backed by OBJECT_MAPPER.convertValue. This unifies all three paths where result can appear as a LinkedHashMap: durable recovery (Jackson JSON deserialization), cross-language sub-agent calls (pemja conversion), and first execution (direct cast, no conversion needed). convertValue handles the Map→POJO conversion uniformly regardless of the source.

One known limitation: for generic collection payloads like List, both recovery and cross-language paths leave result as ArrayList — getResult(List.class) only returns List, losing element types. A getResult(TypeReference<T>) overload can be added later if type-safe collections are needed.

private final String errorMessage;

@JsonCreator
public SubagentResult(
@JsonProperty("success") boolean success,
@JsonProperty("result") Object result,
@JsonProperty("errorMessage") String errorMessage) {
this.success = success;
this.result = result;
this.errorMessage = errorMessage;
}

/** Creates a successful result carrying the given value. */
public static SubagentResult ok(Object result) {
return new SubagentResult(true, result, null);
}

/**
* Creates a failed result carrying the exception's type and message. The full stack trace is
* logged here rather than persisted, keeping the durable payload bounded.
*/
public static SubagentResult error(Exception exception) {
if (exception == null) {
return new SubagentResult(false, null, null);
}
LOG.warn("Sub-agent call failed; persisting the exception summary.", exception);
return new SubagentResult(false, null, summaryOf(exception));
}

/** Creates a failed result carrying the given message. */
public static SubagentResult error(String errorMessage) {
return new SubagentResult(false, null, errorMessage);
}

private static String summaryOf(Exception exception) {
return exception.getClass().getName() + ": " + exception.getMessage();
}

public boolean isSuccess() {
return success;
}

public Object getResult() {
return result;
}

/**
* Returns the payload converted to {@code resultClass}.
*
* <p>Durable recovery re-binds the persisted payload through a plain {@link ObjectMapper}
* without polymorphic typing, so after a failover replay {@link #getResult()} hands back a
* {@code LinkedHashMap} instead of the caller's type. This accessor converts the payload to the
* expected class uniformly on both the first execution and a replay.
*/
public <T> T getResult(Class<T> resultClass) {
return OBJECT_MAPPER.convertValue(result, resultClass);
}

public String getErrorMessage() {
return errorMessage;
}

/**
* Reconstructs an exception carrying the stored summary as its message, or null if this result
* is successful.
*/
@JsonIgnore
public Exception getException() {
return success ? null : new RuntimeException(errorMessage);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/

package org.apache.flink.agents.api.subagent;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.flink.agents.api.context.RunnerContext;
import org.apache.flink.agents.api.resource.ResourceType;
import org.apache.flink.agents.api.resource.SerializableResource;

/**
* Caller-facing definition of a sub-agent, registered in the agent plan as an {@code AGENT}
* resource.
*/
public abstract class SubagentSetup extends SerializableResource {

@Override
@JsonIgnore
public ResourceType getResourceType() {
return ResourceType.AGENT;
}

/**
* Issues a new invocation with an implementation-assigned identity. This is the preferred form.
*/
public abstract SubagentFuture submit(RunnerContext ctx, Object prompt) throws Exception;

/**
* Issues an invocation that continues the conversation of an earlier invocation. Pass the
* {@code sessionId} of the earlier invocation to continue it. The session id is available on
* the handle returned by that invocation. Whether a conversation can be continued across
* actions is up to the concrete implementation.
*/
public abstract SubagentFuture submit(RunnerContext ctx, Object prompt, String sessionId)
throws Exception;

/**
* Issues an invocation under the given {@code (sessionId, callId)} identity. This form is
* reserved for implementation use.
*/
public abstract SubagentFuture submit(
RunnerContext ctx, Object prompt, String sessionId, String callId) throws Exception;
}
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ public static LoadedFile buildAgents(Path path) {
addSharedDescriptors(
sharedResources, ResourceType.VECTOR_STORE, doc.getVectorStores(), path);
addSharedDescriptors(sharedResources, ResourceType.MCP_SERVER, doc.getMcpServers(), path);
addSharedDescriptors(sharedResources, ResourceType.AGENT, doc.getSubagents(), path);

for (ToolSpec t : doc.getTools()) {
if (sharedResources.get(ResourceType.TOOL).put(t.getName(), buildTool(t)) != null) {
Expand Down Expand Up @@ -411,6 +412,7 @@ private static Agent buildAgent(AgentSpec spec) {
addAgentDescriptors(agent, ResourceType.EMBEDDING_MODEL, spec.getEmbeddingModelSetups());
addAgentDescriptors(agent, ResourceType.VECTOR_STORE, spec.getVectorStores());
addAgentDescriptors(agent, ResourceType.MCP_SERVER, spec.getMcpServers());
addAgentDescriptors(agent, ResourceType.AGENT, spec.getSubagents());

for (ToolSpec t : spec.getTools()) {
agent.addResource(t.getName(), ResourceType.TOOL, buildTool(t));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public final class AgentSpec {
private final List<DescriptorSpec> embeddingModelSetups;
private final List<DescriptorSpec> vectorStores;
private final List<DescriptorSpec> mcpServers;
private final List<DescriptorSpec> subagents;

@JsonCreator
public AgentSpec(
Expand All @@ -55,7 +56,8 @@ public AgentSpec(
List<DescriptorSpec> embeddingModelConnections,
@JsonProperty("embedding_model_setups") List<DescriptorSpec> embeddingModelSetups,
@JsonProperty("vector_stores") List<DescriptorSpec> vectorStores,
@JsonProperty("mcp_servers") List<DescriptorSpec> mcpServers) {
@JsonProperty("mcp_servers") List<DescriptorSpec> mcpServers,
@JsonProperty("subagents") List<DescriptorSpec> subagents) {
this.name = name;
this.description = description;
this.prompts = orEmpty(prompts);
Expand All @@ -68,6 +70,7 @@ public AgentSpec(
this.embeddingModelSetups = orEmpty(embeddingModelSetups);
this.vectorStores = orEmpty(vectorStores);
this.mcpServers = orEmpty(mcpServers);
this.subagents = orEmpty(subagents);
}

private static <T> List<T> orEmpty(List<T> list) {
Expand Down Expand Up @@ -121,4 +124,8 @@ public List<DescriptorSpec> getVectorStores() {
public List<DescriptorSpec> getMcpServers() {
return mcpServers;
}

public List<DescriptorSpec> getSubagents() {
return subagents;
}
}
Loading
Loading