You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by we...@apache.org on 2026/10/13 11:36:25 UTC
(flink-agents) branch main updated: [Tech Debt][API][ReActAgent] Support skills in constructors (#1223)
This is an automated email from the ASF dual-hosted git repository.
wenjin272 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/flink-agents.git
The following commit(s) were added to refs/heads/main by this push:
new 5d49238e8 [Tech Debt][API][ReActAgent] Support skills in constructors (#1223)
5d49238e8 is described below
commit 5d49238e8842efd96b5a8d4c022f3dfe1de8862b
Author: daken <94...@users.noreply.github.com>
AuthorDate: Tue Oct 13 19:36:18 2026 +0800
[Tech Debt][API][ReActAgent] Support skills in constructors (#1223)
Generated-by: cursor (deepseek-v4.1-flash)
Co-authored-by: da-daken <da...@qq.com>
---
.../org/apache/flink/agents/api/agents/Agent.java | 33 ++-
.../apache/flink/agents/api/agents/ReActAgent.java | 112 +++++++++-
.../agents/api/chat/model/BaseChatModelSetup.java | 63 ++++++
.../flink/agents/api/resource/ResourceContext.java | 21 ++
.../flink/agents/api/agents/ReActAgentTest.java | 204 +++++++++++++++++++
.../chat/model/BaseChatModelSetupSkillsTest.java | 64 ++++++
docs/content/docs/development/react_agent.md | 65 ++++++
docs/content/docs/development/skills.md | 3 +-
.../integration/test/SkillsIntegrationTest.java | 7 +-
.../org/apache/flink/agents/plan/AgentPlan.java | 26 ++-
.../plan/resource/python/PythonChatModelSetup.java | 3 +-
.../agents/plan/AgentPlanDeclareSkillsTest.java | 127 ++++++++++++
.../agents/plan/AgentPlanRoutingBackstopTest.java | 2 +-
.../resource/python/PythonChatModelSetupTest.java | 64 ++++++
python/flink_agents/api/agents/react_agent.py | 86 +++++++-
.../api/agents/tests/test_react_agent.py | 156 +++++++++++++-
python/flink_agents/api/chat_models/chat_model.py | 17 +-
python/flink_agents/api/resource_context.py | 21 ++
.../e2e_tests_integration/agent_skills_test.py | 5 +-
python/flink_agents/plan/agent_plan.py | 11 +-
.../plan/resource/java/java_chat_model.py | 2 +
.../plan/resource/java/java_resource_adapter.py | 4 +
.../plan/resource/java/java_resource_wrapper.py | 25 ++-
.../tests/test_agent_plan_skills_precedence.py | 66 ++++++
.../flink_agents/runtime/java_resource_adapter.py | 4 +
.../runtime/remote_execution_environment.py | 14 +-
python/flink_agents/runtime/resource_context.py | 11 +-
python/flink_agents/runtime/skill/skill_manager.py | 29 ++-
.../runtime/skill/tests/test_react_agent_skills.py | 197 ++++++++++++++++++
.../tests/test_cross_language_chat_model_skills.py | 74 +++++++
.../tests/test_cross_language_skill_sources.py | 145 +++++++++++++
.../tests/test_remote_execution_environment.py | 34 ++++
.../runtime/python/utils/JavaResourceAdapter.java | 26 +++
.../python/utils/PythonResourceAdapterImpl.java | 15 ++
.../runtime/resource/ResourceContextImpl.java | 8 +
.../flink/agents/runtime/skill/SkillManager.java | 33 ++-
.../python/utils/JavaResourceAdapterTest.java | 39 ++++
.../utils/PythonResourceAdapterImplTest.java | 50 +++++
.../agents/runtime/skill/ReActAgentSkillsTest.java | 225 +++++++++++++++++++++
.../agents/runtime/skill/SkillManagerTest.java | 88 ++++++++
40 files changed, 2142 insertions(+), 37 deletions(-)
diff --git a/api/src/main/java/org/apache/flink/agents/api/agents/Agent.java b/api/src/main/java/org/apache/flink/agents/api/agents/Agent.java
index 73170e122..26603610a 100644
--- a/api/src/main/java/org/apache/flink/agents/api/agents/Agent.java
+++ b/api/src/main/java/org/apache/flink/agents/api/agents/Agent.java
@@ -28,7 +28,6 @@ import org.apache.flink.api.java.tuple.Tuple3;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
-import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -39,9 +38,9 @@ public class Agent {
private final Map<ResourceType, Map<String, Object>> resources;
public Agent() {
- this.resources = new HashMap<>();
+ this.resources = new LinkedHashMap<>();
for (ResourceType type : ResourceType.values()) {
- this.resources.put(type, new HashMap<>());
+ this.resources.put(type, new LinkedHashMap<>());
}
this.actions = new LinkedHashMap<>();
}
@@ -101,10 +100,34 @@ public class Agent {
return this;
}
+ /**
+ * Merge environment-level resources into this agent. Entries already present at the agent level
+ * are kept (agent wins on duplicates). Environment entries are placed before agent entries in
+ * iteration order, so downstream merging sees env-then-agent precedence.
+ *
+ * <p>Order is load-bearing, not cosmetic: downstream consumers derive precedence from it.
+ * {@code AgentPlan} flattens these entries into an ordered source list, and later entries win
+ * on duplicate names. Overwriting an environment entry in place would leave the agent's
+ * replacement in the environment's slot, so an unrelated environment entry could end up last
+ * and win instead — the opposite of the contract above. Environment entries the agent overrides
+ * are therefore dropped, and the agent's own entries are appended as a block.
+ */
public void addResourcesIfAbsent(Map<ResourceType, Map<String, Object>> resources) {
for (ResourceType type : resources.keySet()) {
- Map<String, Object> typedResources = resources.get(type);
- typedResources.forEach(this.resources.get(type)::putIfAbsent);
+ Map<String, Object> envTyped = resources.get(type);
+ if (envTyped == null || envTyped.isEmpty()) {
+ continue;
+ }
+ Map<String, Object> existing = this.resources.get(type);
+ Map<String, Object> merged = new LinkedHashMap<>();
+ for (Map.Entry<String, Object> envEntry : envTyped.entrySet()) {
+ if (!existing.containsKey(envEntry.getKey())) {
+ merged.put(envEntry.getKey(), envEntry.getValue());
+ }
+ }
+ // Appended as a block so agent entries stay last and keep winning on duplicates.
+ merged.putAll(existing);
+ this.resources.put(type, merged);
}
}
diff --git a/api/src/main/java/org/apache/flink/agents/api/agents/ReActAgent.java b/api/src/main/java/org/apache/flink/agents/api/agents/ReActAgent.java
index e535da9fa..70a858bb2 100644
--- a/api/src/main/java/org/apache/flink/agents/api/agents/ReActAgent.java
+++ b/api/src/main/java/org/apache/flink/agents/api/agents/ReActAgent.java
@@ -38,6 +38,7 @@ import org.apache.flink.agents.api.prompt.Prompt;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceDescriptor;
import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.skills.Skills;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.types.Row;
import org.slf4j.Logger;
@@ -48,9 +49,11 @@ import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
import java.util.concurrent.CancellationException;
/**
@@ -74,11 +77,41 @@ public class ReActAgent extends Agent {
"The final response must include the information for every required field of the"
+ " following schema. It does not need to be in JSON format. Schema: ";
+ private static final String SKILLS_ARGUMENT = "skills";
+ private static final String SKILLS_SOURCES_ARGUMENT = "skills_sources";
+ private static final String SKILLS_RESOURCE_NAME = "_react_agent_skills";
+
private static final ObjectMapper mapper = new ObjectMapper();
public ReActAgent(
ResourceDescriptor descriptor, @Nullable Prompt prompt, @Nullable Object outputSchema) {
- this.addResource(DEFAULT_CHAT_MODEL, ResourceType.CHAT_MODEL, descriptor);
+ this(descriptor, prompt, outputSchema, (List<String>) null);
+ }
+
+ /**
+ * Creates a ReAct agent whose chat model may use the given skills.
+ *
+ * <p>The skills are combined with the {@code skills} argument of {@code descriptor}: the
+ * descriptor's skills come first, followed by these, keeping only the first occurrence of each
+ * name. A {@code null} or empty list adds nothing, so the descriptor is used exactly as given.
+ * The descriptor itself is never modified.
+ *
+ * <p>Only skill names are combined. The {@code bash} tool's command policy, such as {@code
+ * allowed_commands}, stays owned by the chat model descriptor and is left unchanged.
+ *
+ * @param descriptor The descriptor of the chat model used in this agent.
+ * @param prompt Prompt to format the input into user messages.
+ * @param outputSchema A {@link RowTypeInfo} or a Pojo class the response must match.
+ * @param skills Names of the skills to expose to the chat model, each matching the {@code name}
+ * of a {@code SKILL.md} available to the agent.
+ */
+ public ReActAgent(
+ ResourceDescriptor descriptor,
+ @Nullable Prompt prompt,
+ @Nullable Object outputSchema,
+ @Nullable List<String> skills) {
+ this.addResource(
+ DEFAULT_CHAT_MODEL, ResourceType.CHAT_MODEL, withSkills(descriptor, skills));
Map<String, Object> actionConfig = new HashMap<>();
if (outputSchema != null) {
@@ -150,6 +183,83 @@ public class ReActAgent extends Agent {
}
}
+ /**
+ * Creates a ReAct agent whose chat model may use skills from the given sources.
+ *
+ * <p>This is the {@code Skills}-object form. The constructor registers the {@code Skills}
+ * object as an agent-level resource so its sources are included in the merged {@code
+ * _skills_config}, and records the source declarations as a marker in the chat model
+ * descriptor. At runtime, the marker is expanded into skill names through {@code SkillManager}
+ * and merged with any explicitly named skills on the descriptor.
+ *
+ * <p>The descriptor itself is never modified. The {@code bash} tool's command policy stays
+ * owned by the chat model descriptor and is left unchanged.
+ *
+ * @param descriptor The descriptor of the chat model used in this agent.
+ * @param prompt Prompt to format the input into user messages.
+ * @param outputSchema A {@link RowTypeInfo} or a Pojo class the response must match.
+ * @param skills Skill sources to expose to the chat model — all skills from these sources
+ * become available. A single {@code Skills} object may declare several sources, so it is
+ * not limited to one source. To combine sources declared in separate objects, gather them
+ * into one {@code Skills}, declare further {@code @Skills} methods, or register them on the
+ * agent with {@code addResource}. May be {@code null} or empty, in which case no source
+ * marker is recorded.
+ */
+ public ReActAgent(
+ ResourceDescriptor descriptor,
+ @Nullable Prompt prompt,
+ @Nullable Object outputSchema,
+ @Nullable Skills skills) {
+ this(descriptor, prompt, outputSchema, (List<String>) null);
+ if (skills != null && !skills.getSources().isEmpty()) {
+ this.addResource(SKILLS_RESOURCE_NAME, ResourceType.SKILLS, skills);
+ this.getResources()
+ .get(ResourceType.CHAT_MODEL)
+ .put(
+ DEFAULT_CHAT_MODEL,
+ withSkillsSources(
+ (ResourceDescriptor)
+ this.getResources()
+ .get(ResourceType.CHAT_MODEL)
+ .get(DEFAULT_CHAT_MODEL),
+ skills));
+ }
+ }
+
+ private static ResourceDescriptor withSkillsSources(
+ ResourceDescriptor descriptor, Skills skills) {
+ if (skills == null || skills.getSources().isEmpty()) {
+ return descriptor;
+ }
+ Map<String, Object> arguments =
+ descriptor.getInitialArguments() == null
+ ? new HashMap<>()
+ : new HashMap<>(descriptor.getInitialArguments());
+ arguments.put(SKILLS_SOURCES_ARGUMENT, skills.getSources());
+ // Rebuilt through the language dispatch so a Python chat model stays a Python declaration.
+ return ResourceDescriptor.fromJson(
+ descriptor.getLanguage(), descriptor.getModule(), descriptor.getClazz(), arguments);
+ }
+
+ private static ResourceDescriptor withSkills(
+ ResourceDescriptor descriptor, @Nullable List<String> skills) {
+ if (skills == null || skills.isEmpty()) {
+ return descriptor;
+ }
+ Map<String, Object> arguments =
+ descriptor.getInitialArguments() == null
+ ? new HashMap<>()
+ : new HashMap<>(descriptor.getInitialArguments());
+ @SuppressWarnings("unchecked")
+ List<String> declared = (List<String>) arguments.get(SKILLS_ARGUMENT);
+ Set<String> merged = new LinkedHashSet<>(declared == null ? List.of() : declared);
+ merged.addAll(skills);
+ arguments.put(SKILLS_ARGUMENT, new ArrayList<>(merged));
+ // Rebuilt through the language dispatch so a Python chat model stays a Python declaration.
+ return ResourceDescriptor.fromJson(
+ descriptor.getLanguage(), descriptor.getModule(), descriptor.getClazz(), arguments);
+ }
+
public static void startAction(Event event, RunnerContext ctx) {
// Built-in events reach an action as their concrete subclass (restored at the JSON
// boundary), so the dispatched InputEvent is cast directly.
diff --git a/api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetup.java b/api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetup.java
index fed92e27c..7a7dfb1ad 100644
--- a/api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetup.java
+++ b/api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetup.java
@@ -18,6 +18,7 @@
package org.apache.flink.agents.api.chat.model;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.agents.api.agents.OutputSchema;
import org.apache.flink.agents.api.chat.messages.ChatMessage;
import org.apache.flink.agents.api.chat.messages.ChatResult;
@@ -28,6 +29,7 @@ import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceContext;
import org.apache.flink.agents.api.resource.ResourceDescriptor;
import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
import org.apache.flink.agents.api.skills.Skills;
import org.apache.flink.agents.api.subagent.SubagentSetup;
import org.apache.flink.agents.api.tools.Tool;
@@ -50,6 +52,9 @@ public abstract class BaseChatModelSetup extends Resource {
private static final Set<String> TOOL_ONLY_PARAMS =
Set.of("tool_choice", "tool_choice_option", "parallel_tool_calls");
+ /** Used to re-type the {@code skills_sources} marker on read (see below). */
+ private static final ObjectMapper SKILL_SOURCES_MAPPER = new ObjectMapper();
+
protected final String connectionName;
protected String model;
protected Object prompt;
@@ -63,9 +68,11 @@ public abstract class BaseChatModelSetup extends Resource {
@Nullable protected BaseChatModelConnection connection;
protected final List<Tool> tools = new ArrayList<>();
+ protected final ResourceDescriptor descriptor;
public BaseChatModelSetup(ResourceDescriptor descriptor, ResourceContext resourceContext) {
super(descriptor, resourceContext);
+ this.descriptor = descriptor;
this.connectionName = descriptor.getArgument("connection");
this.model = descriptor.getArgument("model");
this.prompt = descriptor.getArgument("prompt");
@@ -105,6 +112,11 @@ public abstract class BaseChatModelSetup extends Resource {
this.prompt =
this.resourceContext.getResource((String) this.prompt, ResourceType.PROMPT);
}
+
+ // Resolve the skills_sources marker (plan-time source declarations) into skill names and
+ // merge them with the descriptor's explicit "skills" list. See resolveSkillsFromSources.
+ resolveSkillsFromSources();
+
if (this.skills != null) {
this.skillDiscoveryPrompt =
nullIfEmpty(this.resourceContext.generateAvailableSkillsPrompt(this.skills));
@@ -166,6 +178,57 @@ public abstract class BaseChatModelSetup extends Resource {
return value == null || value.isEmpty() ? null : value;
}
+ /**
+ * Resolve the {@code skills_sources} descriptor marker into concrete skill names and merge them
+ * into {@link #skills}: the descriptor's explicit names come first, resolved names are
+ * appended, and duplicates collapse while preserving order.
+ *
+ * <p>Separate from {@link #open()} because a cross-language wrapper overrides {@code open()} to
+ * delegate to the other language, so the base implementation never runs for that instance and
+ * its own {@code skills} field would stay at its construction-time value. The wrapper shares
+ * this setup's {@link ResourceContext}, so resolving here yields the same list the delegated
+ * setup computed — with no bridge round trip.
+ */
+ protected void resolveSkillsFromSources() throws Exception {
+ List<SkillSourceSpec> skillsSources =
+ toSkillSourceSpecs(descriptor.getArgument("skills_sources"));
+ if (skillsSources.isEmpty()) {
+ return;
+ }
+ List<String> resolved = this.resourceContext.resolveSkillNamesForSources(skillsSources);
+ Set<String> merged = new LinkedHashSet<>();
+ if (this.skills != null) {
+ merged.addAll(this.skills);
+ }
+ merged.addAll(resolved);
+ this.skills = new ArrayList<>(merged);
+ }
+
+ /**
+ * Re-type the {@code skills_sources} descriptor argument into {@link SkillSourceSpec} entries.
+ *
+ * <p>The marker is written as a {@code List<SkillSourceSpec>} at plan time, but it travels
+ * inside {@link ResourceDescriptor#getInitialArguments()} — a {@code Map<String, Object>} — so
+ * its element type is erased. An {@code AgentPlan} Java-serialization round trip re-reads the
+ * plan through Jackson, which leaves plain maps in the list; casting that list back to {@code
+ * List<SkillSourceSpec>} then fails with a {@link ClassCastException}. Re-typing each element
+ * at the read point keeps the marker usable across serialization boundaries.
+ */
+ private static List<SkillSourceSpec> toSkillSourceSpecs(@Nullable Object raw) {
+ if (!(raw instanceof List)) {
+ return Collections.emptyList();
+ }
+ List<SkillSourceSpec> specs = new ArrayList<>();
+ for (Object element : (List<?>) raw) {
+ if (element instanceof SkillSourceSpec) {
+ specs.add((SkillSourceSpec) element);
+ } else if (element != null) {
+ specs.add(SKILL_SOURCES_MAPPER.convertValue(element, SkillSourceSpec.class));
+ }
+ }
+ return specs;
+ }
+
public abstract Map<String, Object> getParameters();
/**
diff --git a/api/src/main/java/org/apache/flink/agents/api/resource/ResourceContext.java b/api/src/main/java/org/apache/flink/agents/api/resource/ResourceContext.java
index b401bf999..6e2ad8242 100644
--- a/api/src/main/java/org/apache/flink/agents/api/resource/ResourceContext.java
+++ b/api/src/main/java/org/apache/flink/agents/api/resource/ResourceContext.java
@@ -18,6 +18,8 @@
package org.apache.flink.agents.api.resource;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
+
import java.util.Collections;
import java.util.List;
import java.util.function.BiFunction;
@@ -47,6 +49,20 @@ public interface ResourceContext {
*/
List<String> getSkillDirs(List<String> skillNames) throws Exception;
+ /**
+ * Resolve skill names from the given source specifications.
+ *
+ * <p>At plan time, a descriptor may record a set of {@link SkillSourceSpec} entries as a marker
+ * meaning "all skills from these sources." At runtime, this method resolves the marker into
+ * actual skill names by looking up the sources in the agent's {@code SkillManager}.
+ *
+ * <p>Returns an empty list if no skills are configured or the sources are not loaded.
+ */
+ default List<String> resolveSkillNamesForSources(List<SkillSourceSpec> sources)
+ throws Exception {
+ return Collections.emptyList();
+ }
+
/**
* Create a {@link ResourceContext} backed by the given resource lookup function. The skill
* methods return empty defaults — convenient for tests or for runtimes without skills support.
@@ -67,6 +83,11 @@ public interface ResourceContext {
public List<String> getSkillDirs(List<String> skillNames) {
return Collections.emptyList();
}
+
+ @Override
+ public List<String> resolveSkillNamesForSources(List<SkillSourceSpec> sources) {
+ return Collections.emptyList();
+ }
};
}
}
diff --git a/api/src/test/java/org/apache/flink/agents/api/agents/ReActAgentTest.java b/api/src/test/java/org/apache/flink/agents/api/agents/ReActAgentTest.java
index a34b85336..d4474a5c2 100644
--- a/api/src/test/java/org/apache/flink/agents/api/agents/ReActAgentTest.java
+++ b/api/src/test/java/org/apache/flink/agents/api/agents/ReActAgentTest.java
@@ -33,9 +33,12 @@ import org.apache.flink.agents.api.chat.model.routing.ModelRouter;
import org.apache.flink.agents.api.context.RunnerContext;
import org.apache.flink.agents.api.event.ChatRequestEvent;
import org.apache.flink.agents.api.prompt.Prompt;
+import org.apache.flink.agents.api.resource.PythonResourceDescriptor;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceDescriptor;
import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
+import org.apache.flink.agents.api.skills.Skills;
import org.apache.flink.agents.api.tools.Tool;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
@@ -47,6 +50,7 @@ import org.mockito.ArgumentCaptor;
import javax.annotation.Nullable;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -374,6 +378,102 @@ public class ReActAgentTest {
}
}
+ @Test
+ @DisplayName("Constructor skills alone become the chat model's skills")
+ public void testConstructorOnlySkills() {
+ ResourceDescriptor chatModel = descriptor(Map.of("model", "qwen3:8b"));
+
+ ResourceDescriptor actual = chatModelOf(agentWithSkills(chatModel, List.of("a", "b")));
+
+ assertThat(actual.<List<String>>getArgument("skills")).containsExactly("a", "b");
+ assertThat(actual.<String>getArgument("model")).isEqualTo("qwen3:8b");
+ }
+
+ @Test
+ @DisplayName("Without constructor skills the descriptor is used exactly as given")
+ public void testDescriptorOnlySkills() {
+ ResourceDescriptor chatModel = descriptor(Map.of("skills", List.of("a")));
+
+ assertThat(chatModelOf(agentWithSkills(chatModel, null))).isSameAs(chatModel);
+ assertThat(chatModelOf(new ReActAgent(chatModel, null, null))).isSameAs(chatModel);
+ }
+
+ @Test
+ @DisplayName("An empty skills list adds nothing, so skills stay disabled")
+ public void testEmptyConstructorSkillsAddNothing() {
+ ResourceDescriptor chatModel = descriptor(Map.of("model", "qwen3:8b"));
+
+ ResourceDescriptor actual = chatModelOf(agentWithSkills(chatModel, List.of()));
+
+ assertThat(actual).isSameAs(chatModel);
+ assertThat(actual.getInitialArguments()).doesNotContainKey("skills");
+ }
+
+ @Test
+ @DisplayName("Descriptor skills come first, then constructor skills, each name kept once")
+ public void testCombinedSkillsAreOrderedAndDeduplicated() {
+ ResourceDescriptor chatModel = descriptor(Map.of("skills", List.of("a", "b")));
+
+ ResourceDescriptor actual =
+ chatModelOf(agentWithSkills(chatModel, List.of("b", "c", "a", "c")));
+
+ assertThat(actual.<List<String>>getArgument("skills")).containsExactly("a", "b", "c");
+ assertThat(chatModel.<List<String>>getArgument("skills")).containsExactly("a", "b");
+ }
+
+ @Test
+ @DisplayName("Agents sharing one descriptor each get only their own constructor skills")
+ public void testDescriptorSharedAcrossAgentsStaysIndependent() {
+ // Writable collections, as a caller typically builds them, so a merge done in place would
+ // show up as one agent's skills leaking into the other instead of an immutable-write error.
+ ResourceDescriptor chatModel =
+ new ResourceDescriptor(
+ "com.example.ChatModel",
+ new HashMap<>(Map.of("skills", new ArrayList<>(List.of("shared")))));
+
+ ResourceDescriptor first = chatModelOf(agentWithSkills(chatModel, List.of("a")));
+ ResourceDescriptor second = chatModelOf(agentWithSkills(chatModel, List.of("b")));
+
+ assertThat(first.<List<String>>getArgument("skills")).containsExactly("shared", "a");
+ assertThat(second.<List<String>>getArgument("skills")).containsExactly("shared", "b");
+ assertThat(chatModel.<List<String>>getArgument("skills")).containsExactly("shared");
+ }
+
+ @Test
+ @DisplayName("Constructor skills leave the descriptor's command policy untouched")
+ public void testConstructorSkillsKeepAllowedCommands() {
+ ResourceDescriptor chatModel =
+ descriptor(
+ Map.of(
+ "skills", List.of("a"),
+ "allowed_commands", List.of("echo", "bc"),
+ "allowed_script_dirs", List.of("/opt/scripts")));
+
+ ResourceDescriptor actual = chatModelOf(agentWithSkills(chatModel, List.of("b")));
+
+ assertThat(actual.<List<String>>getArgument("allowed_commands"))
+ .containsExactly("echo", "bc");
+ assertThat(actual.<List<String>>getArgument("allowed_script_dirs"))
+ .containsExactly("/opt/scripts");
+ }
+
+ @Test
+ @DisplayName("Constructor skills on a Python chat model keep it a Python declaration")
+ public void testConstructorSkillsKeepDescriptorLanguage() {
+ ResourceDescriptor chatModel =
+ PythonResourceDescriptor.Builder.newBuilder("my_module.MyChatModel")
+ .addInitialArgument("skills", List.of("a"))
+ .build();
+
+ ResourceDescriptor actual = chatModelOf(agentWithSkills(chatModel, List.of("b")));
+
+ assertThat(actual)
+ .isInstanceOf(PythonResourceDescriptor.class)
+ .extracting(ResourceDescriptor::getModule, ResourceDescriptor::getClazz)
+ .containsExactly("my_module", "MyChatModel");
+ assertThat(actual.<List<String>>getArgument("skills")).containsExactly("a", "b");
+ }
+
private static ReActAgent agentWithSchema(Object outputSchema) {
return agentWithSchema(outputSchema, null);
}
@@ -385,6 +485,21 @@ public class ReActAgentTest {
outputSchema);
}
+ private static ReActAgent agentWithSkills(
+ ResourceDescriptor chatModel, @Nullable List<String> skills) {
+ return new ReActAgent(chatModel, null, null, skills);
+ }
+
+ /** An immutable argument map, so any write to the caller's descriptor fails the test. */
+ private static ResourceDescriptor descriptor(Map<String, Object> arguments) {
+ return new ResourceDescriptor("com.example.ChatModel", arguments);
+ }
+
+ private static ResourceDescriptor chatModelOf(ReActAgent agent) {
+ return (ResourceDescriptor)
+ agent.getResources().get(ResourceType.CHAT_MODEL).get("_default_chat_model");
+ }
+
private static String schemaPromptOf(ReActAgent agent) {
return promptTextOf(agent, "_default_schema_prompt");
}
@@ -398,6 +513,95 @@ public class ReActAgentTest {
return prompt.formatString(Map.of());
}
+ @Test
+ @DisplayName("Skill source specs are registered as a marker on the chat model descriptor")
+ public void testSkillsObjectRegistersSourcesMarker() {
+ ResourceDescriptor chatModel = descriptor(Map.of("model", "qwen3:8b"));
+ Skills skills = Skills.fromLocalDir("/tmp/skill-a", "/tmp/skill-b");
+
+ ReActAgent agent = new ReActAgent(chatModel, null, null, skills);
+ ResourceDescriptor actual = chatModelOf(agent);
+
+ @SuppressWarnings("unchecked")
+ List<SkillSourceSpec> sources = actual.getArgument("skills_sources");
+ assertThat(sources).isNotNull();
+ assertThat(sources).hasSize(2);
+ assertThat(sources.get(0).getScheme()).isEqualTo("local");
+ assertThat(sources.get(0).getParams()).containsEntry("path", "/tmp/skill-a");
+ // The original descriptor is not modified.
+ assertThat((Object) chatModel.getArgument("skills_sources")).isNull();
+ // The Skills object is registered as a resource.
+ assertThat(agent.getResources().get(ResourceType.SKILLS))
+ .containsKey("_react_agent_skills");
+ }
+
+ @Test
+ @DisplayName("Null Skills object adds nothing")
+ public void testNullSkillsObjectIsNoOp() {
+ ResourceDescriptor chatModel = descriptor(Map.of("model", "qwen3:8b"));
+
+ ReActAgent agent = new ReActAgent(chatModel, null, null, (Skills) null);
+ ResourceDescriptor actual = chatModelOf(agent);
+
+ assertThat(actual).isSameAs(chatModel);
+ assertThat((Object) actual.getArgument("skills_sources")).isNull();
+ assertThat((Object) actual.getArgument("skills")).isNull();
+ }
+
+ @Test
+ @DisplayName("Empty Skills object adds nothing")
+ public void testEmptySkillsObjectIsNoOp() {
+ ResourceDescriptor chatModel = descriptor(Map.of("model", "qwen3:8b"));
+ Skills empty = new Skills(List.of());
+
+ ReActAgent agent = new ReActAgent(chatModel, null, null, empty);
+ ResourceDescriptor actual = chatModelOf(agent);
+
+ assertThat(actual).isSameAs(chatModel);
+ assertThat((Object) actual.getArgument("skills_sources")).isNull();
+ }
+
+ @Test
+ @DisplayName("Skills object and descriptor skills coexist — merge happens at runtime")
+ public void testSkillsObjectAndDescriptorSkillsCoexist() {
+ ResourceDescriptor chatModel =
+ descriptor(Map.of("skills", List.of("a", "b"), "model", "qwen3:8b"));
+ Skills skills = Skills.fromLocalDir("/tmp/skill-c");
+
+ ReActAgent agent = new ReActAgent(chatModel, null, null, skills);
+ ResourceDescriptor actual = chatModelOf(agent);
+
+ // Explicit skills are preserved on the descriptor.
+ assertThat(actual.<List<String>>getArgument("skills")).containsExactly("a", "b");
+ // The skills_sources marker is present for runtime resolution.
+ @SuppressWarnings("unchecked")
+ List<SkillSourceSpec> sources = actual.getArgument("skills_sources");
+ assertThat(sources).hasSize(1);
+ // The original descriptor is not modified.
+ assertThat((Object) chatModel.getArgument("skills_sources")).isNull();
+ }
+
+ @Test
+ @DisplayName("Skills-object constructor keeps the descriptor language")
+ public void testSkillsObjectKeepsDescriptorLanguage() {
+ ResourceDescriptor chatModel =
+ PythonResourceDescriptor.Builder.newBuilder("my_module.MyChatModel")
+ .addInitialArgument("skills", List.of("a"))
+ .build();
+ Skills skills = Skills.fromLocalDir("/tmp/skill-b");
+
+ ReActAgent agent = new ReActAgent(chatModel, null, null, skills);
+ ResourceDescriptor actual = chatModelOf(agent);
+
+ assertThat(actual)
+ .isInstanceOf(PythonResourceDescriptor.class)
+ .extracting(ResourceDescriptor::getModule, ResourceDescriptor::getClazz)
+ .containsExactly("my_module", "MyChatModel");
+ @SuppressWarnings("unchecked")
+ List<SkillSourceSpec> sources = actual.getArgument("skills_sources");
+ assertThat(sources).hasSize(1);
+ }
+
/** A class with no members at all, which Jackson refuses to render rather than rendering. */
public static class FieldLess {}
diff --git a/api/src/test/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetupSkillsTest.java b/api/src/test/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetupSkillsTest.java
index 880dcf9ba..ee61c9a16 100644
--- a/api/src/test/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetupSkillsTest.java
+++ b/api/src/test/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetupSkillsTest.java
@@ -18,6 +18,7 @@
package org.apache.flink.agents.api.chat.model;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.agents.api.chat.messages.ChatMessage;
import org.apache.flink.agents.api.chat.messages.ChatResult;
import org.apache.flink.agents.api.chat.messages.MessageRole;
@@ -26,6 +27,7 @@ import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceContext;
import org.apache.flink.agents.api.resource.ResourceDescriptor;
import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
import org.apache.flink.agents.api.skills.Skills;
import org.apache.flink.agents.api.tools.Tool;
import org.apache.flink.agents.api.tools.ToolMetadata;
@@ -178,4 +180,66 @@ class BaseChatModelSetupSkillsTest {
assertTrue(connection.capturedMessages.get(1).getText().contains("<available_skills>"));
assertEquals(MessageRole.USER, connection.capturedMessages.get(2).getRole());
}
+
+ @Test
+ void openResolvesSkillsSourcesMarkerAfterJsonRoundTrip() throws Exception {
+ // The skills_sources marker is declared as a List<SkillSourceSpec> but travels inside
+ // ResourceDescriptor's Map<String, Object>. An AgentPlan Java-serialization round trip
+ // re-reads the descriptor through Jackson, erasing the element type into plain maps, so
+ // the read point must re-type the marker instead of blindly casting the list.
+ ObjectMapper mapper = new ObjectMapper();
+ List<SkillSourceSpec> declared =
+ List.of(new SkillSourceSpec("local", Map.of("path", "/tmp/skills")));
+ Object roundTripped = mapper.readValue(mapper.writeValueAsString(declared), Object.class);
+
+ Map<String, Resource> store = new HashMap<>();
+ StubConnection connection = new StubConnection(new ResourceDescriptor("X", Map.of()), null);
+ store.put("conn", connection);
+ store.put(Skills.LOAD_SKILL_TOOL, new StubTool(Skills.LOAD_SKILL_TOOL));
+ store.put(Skills.BASH_TOOL, new StubTool(Skills.BASH_TOOL));
+
+ List<SkillSourceSpec> resolvedFrom = new ArrayList<>();
+ ResourceContext ctx =
+ new ResourceContext() {
+ @Override
+ public Resource getResource(String name, ResourceType type) {
+ return store.get(name);
+ }
+
+ @Override
+ public String generateAvailableSkillsPrompt(List<String> skillNames) {
+ return "<available_skills>marker</available_skills>";
+ }
+
+ @Override
+ public List<String> getSkillDirs(List<String> skillNames) {
+ return List.of();
+ }
+
+ @Override
+ public List<String> resolveSkillNamesForSources(List<SkillSourceSpec> sources) {
+ // Iterate with the declared element type, exactly as
+ // SkillManager.getSkillNamesForSources does, so an untyped marker
+ // surfaces as the same ClassCastException production would see.
+ for (SkillSourceSpec source : sources) {
+ resolvedFrom.add(source);
+ }
+ return List.of("math-calculator");
+ }
+ };
+
+ Map<String, Object> args = new HashMap<>();
+ args.put("connection", "conn");
+ args.put("skills", List.of("explicit-skill"));
+ args.put("skills_sources", roundTripped);
+
+ StubChatSetup setup = new StubChatSetup(new ResourceDescriptor("X", args), ctx);
+ setup.open();
+
+ // The marker reached the resolver as real SkillSourceSpec entries, not maps.
+ assertEquals(
+ List.of(new SkillSourceSpec("local", Map.of("path", "/tmp/skills"))), resolvedFrom);
+ // Explicit names come first, resolved names are appended.
+ assertEquals(List.of("explicit-skill", "math-calculator"), setup.getSkills());
+ }
}
diff --git a/docs/content/docs/development/react_agent.md b/docs/content/docs/development/react_agent.md
index 8bbd893c1..537771655 100644
--- a/docs/content/docs/development/react_agent.md
+++ b/docs/content/docs/development/react_agent.md
@@ -332,3 +332,68 @@ RowTypeInfo myRowTypeInfo =
{{< /tabs >}}
+### Skills
+User can pass [skills]({{< ref "docs/development/skills" >}}) to the constructor instead of adding a `skills` argument to the chat model descriptor. Two forms are accepted: a list of skill names, or a `Skills` object declaring where the skills are loaded from.
+
+**Skill names.** Pass the names of skills that are already declared to the agent:
+
+{{< tabs "Skills" >}}
+
+{{< tab "Python" >}}
+```python
+my_react_agent = ReActAgent(
+ chat_model=chat_model_descriptor,
+ prompt=my_prompt,
+ skills=["math-calculator"],
+)
+```
+{{< /tab >}}
+
+{{< tab "Java" >}}
+```java
+ReActAgent myReActAgent =
+ new ReActAgent(chatModelDescriptor, myPrompt, null, List.of("math-calculator"));
+```
+{{< /tab >}}
+
+{{< /tabs >}}
+
+The constructor skills are combined with any `skills` already set on the chat model descriptor:
+
+- The descriptor's skills come first, followed by the constructor skills; a name listed more than once is kept only at its first occurrence.
+- Passing no skills, or an empty list, adds nothing: the descriptor is used exactly as given.
+- The descriptor you pass in is not modified; the agent uses a copy with the combined skills.
+- Only skill names are combined. The command policy of the built-in `bash` tool, such as `allowed_commands`, is always taken from the chat model descriptor, so set it there.
+- The sources behind those names have to be declared somewhere the agent can see them: a `@Skills`/`@skills` method, the execution environment, or the agent itself.
+
+**Skill sources.** Pass a `Skills` object to declare the sources and let the framework resolve the skill names at runtime:
+
+{{< tabs "Skill Sources" >}}
+
+{{< tab "Python" >}}
+```python
+my_react_agent = ReActAgent(
+ chat_model=chat_model_descriptor,
+ prompt=my_prompt,
+ skills=Skills.from_local_dir("./skills"),
+)
+```
+{{< /tab >}}
+
+{{< tab "Java" >}}
+```java
+ReActAgent myReActAgent =
+ new ReActAgent(
+ chatModelDescriptor,
+ myPrompt,
+ null,
+ Skills.fromLocalDir("./skills"));
+```
+{{< /tab >}}
+
+{{< /tabs >}}
+
+The constructor registers those sources on the agent, so they do not also need `add_resource(..., ResourceType.SKILLS, ...)` on the execution environment. Every skill found in the sources becomes available, and the resolved names are appended after any explicitly named ones. A single `Skills` object may declare several sources; to combine sources held in separate objects, gather them into one `Skills`, declare further `@Skills`/`@skills` methods, or register them on the agent with `addRe [...]
+
+**Which declaration wins.** Sources reach the agent from three levels. `@Skills`/`@skills` methods are merged first, then the execution environment's `SKILLS` resources, then the agent's own. A declaration from a later level wins when two of them resolve to the same skill name.
+
diff --git a/docs/content/docs/development/skills.md b/docs/content/docs/development/skills.md
index d526c890e..663501e3d 100644
--- a/docs/content/docs/development/skills.md
+++ b/docs/content/docs/development/skills.md
@@ -131,6 +131,7 @@ public class MathAgent extends Agent {
- In Python, use `@skills`.
- In Java, use `@Skills`.
- Declare more than one `@skills`/`@Skills` method on the same agent to combine sources; the runtime merges them and de-duplicates identical entries.
+ - The order in which those methods are merged is deterministic, but it differs between languages: Java orders them by method name, while Python keeps declaration order. When two sources provide the same skill name, the later source wins.
- Declaring a skill source only makes the skills *available*. A skill is exposed to a chat model only when that model lists it in its `skills` (see [Enable Skills on a Chat Model](#enable-skills-on-a-chat-model)).
### Skill Sources
@@ -228,7 +229,7 @@ public static ResourceDescriptor mathModel() {
- The `load_skill` and `bash` tools are added automatically — you do not declare them in `tools`. They are added alongside any tools you do declare.
- Make sure the system prompt instructs the agent to load the relevant skill before acting, for example: *"You must load the skill first and strictly follow its instructions."* Without this nudge, smaller models may answer directly instead of consulting the skill.
-Skills work with both the [Workflow Agent]({{< ref "docs/development/workflow_agent" >}}) (configure the chat model via `@chat_model_setup`/`@ChatModelSetup` as above) and the [ReAct Agent]({{< ref "docs/development/react_agent" >}}) (set `skills` and `allowed_commands` on the `ReActAgent`'s chat model descriptor, and register the `Skills` resource on the execution environment with `add_resource(..., ResourceType.SKILLS, ...)`).
+Skills work with both the [Workflow Agent]({{< ref "docs/development/workflow_agent" >}}) (configure the chat model via `@chat_model_setup`/`@ChatModelSetup` as above) and the [ReAct Agent]({{< ref "docs/development/react_agent" >}}). For the ReAct Agent, either pass the skill names to the `ReActAgent` constructor and register the sources on the execution environment with `add_resource(..., ResourceType.SKILLS, ...)`, or pass a `Skills` object, which registers its own sources on the agen [...]
## How Skills Work
diff --git a/e2e-test/flink-agents-end-to-end-tests-integration/src/test/java/org/apache/flink/agents/integration/test/SkillsIntegrationTest.java b/e2e-test/flink-agents-end-to-end-tests-integration/src/test/java/org/apache/flink/agents/integration/test/SkillsIntegrationTest.java
index b67e7aeed..3d86ecdc9 100644
--- a/e2e-test/flink-agents-end-to-end-tests-integration/src/test/java/org/apache/flink/agents/integration/test/SkillsIntegrationTest.java
+++ b/e2e-test/flink-agents-end-to-end-tests-integration/src/test/java/org/apache/flink/agents/integration/test/SkillsIntegrationTest.java
@@ -161,12 +161,13 @@ public class SkillsIntegrationTest {
agentsEnv.getConfig().set(MAX_RETRIES, 3);
+ // The skill is named on the ReActAgent constructor below, while the bash command policy
+ // stays on the chat model descriptor that owns it.
ResourceDescriptor chatModelDescriptor =
ResourceDescriptor.Builder.newBuilder(
ResourceName.ChatModel.OPENAI_COMPLETIONS_SETUP)
.addInitialArgument("connection", "openai")
.addInitialArgument("model", SkillsIntegrationAgent.MODEL)
- .addInitialArgument("skills", List.of("math-calculator"))
.addInitialArgument("allowed_commands", List.of("echo", "bc"))
.build();
@@ -188,7 +189,9 @@ public class SkillsIntegrationTest {
new TypeInformation[] {BasicTypeInfo.INT_TYPE_INFO},
new String[] {"result"});
- Agent agent = new ReActAgent(chatModelDescriptor, prompt, outputTypeInfo);
+ Agent agent =
+ new ReActAgent(
+ chatModelDescriptor, prompt, outputTypeInfo, List.of("math-calculator"));
Table inputTable =
tableEnv.fromValues(
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/AgentPlan.java b/plan/src/main/java/org/apache/flink/agents/plan/AgentPlan.java
index 0eeac3f70..806b0a159 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/AgentPlan.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/AgentPlan.java
@@ -487,8 +487,9 @@ public class AgentPlan implements Serializable {
private void extractResourceProvidersFromAgent(Agent agent) throws Exception {
Class<?> agentClass = agent.getClass();
- // Collect Skills declarations from both @Skills methods and Agent.addResource(SKILLS, ...)
- Map<String, Skills> skillsObjects = new LinkedHashMap<>();
+ // Collect @Skills methods into a sorted staging map (getDeclaredMethods() order is
+ // non-deterministic across JDKs / class layouts).
+ Map<String, Skills> annotationSkills = new java.util.TreeMap<>();
// Scan all fields in the agent class for @Tool and @ChatModel annotations
for (Field field : agentClass.getDeclaredFields()) {
@@ -574,7 +575,7 @@ public class AgentPlan implements Serializable {
+ method.getName()
+ " must return org.apache.flink.agents.api.skills.Skills");
}
- skillsObjects.put(method.getName(), (Skills) value);
+ annotationSkills.put(method.getName(), (Skills) value);
} else if (method.isAnnotationPresent(MCPServer.class)) {
// Check the MCPServer annotation version to determine which version to use.
MCPServer MCPServerAnnotation = method.getAnnotation(MCPServer.class);
@@ -607,6 +608,12 @@ public class AgentPlan implements Serializable {
}
}
+ // Seed the merge with the sorted @Skills methods: the LinkedHashMap copy constructor
+ // inserts them in annotationSkills' (method-name) order. Environment and agent resources
+ // are appended afterwards, in that order; later sources win on duplicate skill names
+ // (see {@link #addSkills(Map)}).
+ Map<String, Skills> skillsObjects = new LinkedHashMap<>(annotationSkills);
+
for (Map.Entry<ResourceType, Map<String, Object>> entry : agent.getResources().entrySet()) {
ResourceType type = entry.getKey();
if (type == PROMPT) {
@@ -638,6 +645,10 @@ public class AgentPlan implements Serializable {
} else if (type == ResourceType.SKILLS) {
for (Map.Entry<String, Object> kv : entry.getValue().entrySet()) {
if (kv.getValue() instanceof Skills) {
+ // Re-insert instead of overwriting in place: a name already seeded from a
+ // @Skills method would otherwise keep its annotation-time slot, and the
+ // flattened source order decides which declaration wins.
+ skillsObjects.remove(kv.getKey());
skillsObjects.put(kv.getKey(), (Skills) kv.getValue());
}
}
@@ -727,12 +738,11 @@ public class AgentPlan implements Serializable {
ResourceType.TOOL,
new ResourceDescriptor(BashTool.class.getName(), new HashMap<>())));
- // Sort by key before merging: getDeclaredMethods() makes no order guarantee, so without
- // this the winner on a duplicate skill name would vary across JDK / class layout.
- List<String> orderedKeys = new ArrayList<>(skillsObjects.keySet());
- Collections.sort(orderedKeys);
+ // Merge sources in insertion order: @Skills methods (sorted by name) →
+ // environment resources → agent resources. Later sources win on duplicate
+ // skill names, matching Python's level-aware precedence.
LinkedHashSet<SkillSourceSpec> sources = new LinkedHashSet<>();
- for (String key : orderedKeys) {
+ for (String key : skillsObjects.keySet()) {
sources.addAll(skillsObjects.get(key).getSources());
}
Skills merged = new Skills(new ArrayList<>(sources));
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetup.java b/plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetup.java
index b434a8e28..806be3c7c 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetup.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetup.java
@@ -62,8 +62,9 @@ public class PythonChatModelSetup extends BaseChatModelSetup implements PythonRe
}
@Override
- public void open() {
+ public void open() throws Exception {
this.adapter.callMethod(chatModelSetup, "open", Collections.emptyMap());
+ resolveSkillsFromSources();
}
@Override
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareSkillsTest.java b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareSkillsTest.java
index c2cd4f7e2..8f25968e0 100644
--- a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareSkillsTest.java
+++ b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareSkillsTest.java
@@ -27,6 +27,8 @@ import org.apache.flink.agents.plan.resourceprovider.JavaSerializableResourcePro
import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
import org.junit.jupiter.api.Test;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -193,6 +195,131 @@ class AgentPlanDeclareSkillsTest {
merged.getSources());
}
+ @Test
+ void annotationSkillsAreSortedByNameBeforeAgentAddResourceSources() throws Exception {
+ // Agent with @Skills methods declared as zSkills, aSkills, mSkills (declaration order
+ // is non-deterministic across JDKs). The merged sources must appear in sorted-method-name
+ // order (aSkills, mSkills, zSkills) before agent.addResource sources.
+ Agent agent = new AnnotationOrderAgent();
+ agent.addResource("extra", ResourceType.SKILLS, Skills.fromLocalDir("/tmp/skill-extra"));
+ Skills merged = mergedSkillsOf(agent);
+ assertEquals(
+ List.of(
+ new SkillSourceSpec("local", Map.of("path", "/tmp/m-skill-a")),
+ new SkillSourceSpec("local", Map.of("path", "/tmp/m-skill-b")),
+ new SkillSourceSpec("local", Map.of("path", "/tmp/z-skill-a")),
+ new SkillSourceSpec("local", Map.of("path", "/tmp/skill-extra"))),
+ merged.getSources());
+ }
+
+ @Test
+ void agentLevelSkillsOverrideEnvironmentLevelBySourceOrder() throws Exception {
+ // Environment skills come before agent skills in the merged sources list so that
+ // agent-level sources win on duplicate skill names (SkillManager last-write-wins).
+ Agent agent = new NoSkillsAgent();
+ // Simulate environment-level skills via addResourcesIfAbsent.
+ Map<ResourceType, Map<String, Object>> envResources = new HashMap<>();
+ Map<String, Object> envSkills = new LinkedHashMap<>();
+ envSkills.put("env-skills", Skills.fromLocalDir("/tmp/env-skill"));
+ envResources.put(ResourceType.SKILLS, envSkills);
+ agent.addResourcesIfAbsent(envResources);
+ // Agent-level skills added afterwards.
+ agent.addResource(
+ "agent-skills", ResourceType.SKILLS, Skills.fromLocalDir("/tmp/agent-skill"));
+ Skills merged = mergedSkillsOf(agent);
+ assertEquals(
+ List.of(
+ new SkillSourceSpec("local", Map.of("path", "/tmp/env-skill")),
+ new SkillSourceSpec("local", Map.of("path", "/tmp/agent-skill"))),
+ merged.getSources());
+ }
+
+ @Test
+ void agentLevelSkillsWinOnSameNameCollision() throws Exception {
+ // addResourcesIfAbsent merges environment resources without overwriting an agent-level
+ // entry registered under the same name, so the agent's sources survive the merge.
+ Agent agent = new NoSkillsAgent();
+ agent.addResource("skills", ResourceType.SKILLS, Skills.fromLocalDir("/tmp/agent-skill"));
+ Map<ResourceType, Map<String, Object>> envResources = new HashMap<>();
+ Map<String, Object> envSkills = new LinkedHashMap<>();
+ envSkills.put("skills", Skills.fromLocalDir("/tmp/env-skill"));
+ envResources.put(ResourceType.SKILLS, envSkills);
+ agent.addResourcesIfAbsent(envResources);
+
+ Skills merged = mergedSkillsOf(agent);
+ assertEquals(
+ List.of(new SkillSourceSpec("local", Map.of("path", "/tmp/agent-skill"))),
+ merged.getSources());
+ }
+
+ @Test
+ void environmentEntriesKeepTheirOrderWhenTheAgentOverridesOneOfThem() throws Exception {
+ // The agent wins on duplicates, and its entry has to stay last: overwriting the
+ // environment entry in place would leave the agent's source early in the flattened order,
+ // so the environment's "a" declaration would end up last and win instead.
+ Agent agent = new NoSkillsAgent();
+ agent.addResource("z", ResourceType.SKILLS, Skills.fromLocalDir("/tmp/z-agent"));
+ Map<ResourceType, Map<String, Object>> envResources = new HashMap<>();
+ Map<String, Object> envSkills = new LinkedHashMap<>();
+ envSkills.put("z", Skills.fromLocalDir("/tmp/z-env"));
+ envSkills.put("a", Skills.fromLocalDir("/tmp/a-env"));
+ envResources.put(ResourceType.SKILLS, envSkills);
+
+ agent.addResourcesIfAbsent(envResources);
+
+ Skills merged = mergedSkillsOf(agent);
+ assertEquals(
+ List.of(
+ new SkillSourceSpec("local", Map.of("path", "/tmp/a-env")),
+ new SkillSourceSpec("local", Map.of("path", "/tmp/z-agent"))),
+ merged.getSources());
+ }
+
+ @Test
+ void agentAddResourceSkillsOverrideAnnotationSkillsByNameAndMoveLast() throws Exception {
+ // @Skills methods are seeded first, sorted by method name. A programmatic SKILLS resource
+ // reusing one of those names has to move behind the remaining annotation entries, because
+ // the flattened source order decides which declaration wins.
+ Agent agent = new AnnotationCollisionAgent();
+ agent.addResource("alpha", ResourceType.SKILLS, Skills.fromLocalDir("/tmp/prog-alpha"));
+
+ Skills merged = mergedSkillsOf(agent);
+ assertEquals(
+ List.of(
+ new SkillSourceSpec("local", Map.of("path", "/tmp/ann-beta")),
+ new SkillSourceSpec("local", Map.of("path", "/tmp/prog-alpha"))),
+ merged.getSources());
+ }
+
+ public static class AnnotationCollisionAgent extends Agent {
+ @org.apache.flink.agents.api.annotation.Skills
+ public static Skills alpha() {
+ return Skills.fromLocalDir("/tmp/ann-alpha");
+ }
+
+ @org.apache.flink.agents.api.annotation.Skills
+ public static Skills beta() {
+ return Skills.fromLocalDir("/tmp/ann-beta");
+ }
+ }
+
+ public static class AnnotationOrderAgent extends Agent {
+ @org.apache.flink.agents.api.annotation.Skills
+ public static Skills zSkills() {
+ return Skills.fromLocalDir("/tmp/z-skill-a");
+ }
+
+ @org.apache.flink.agents.api.annotation.Skills
+ public static Skills aSkills() {
+ return Skills.fromLocalDir("/tmp/m-skill-a");
+ }
+
+ @org.apache.flink.agents.api.annotation.Skills
+ public static Skills mSkills() {
+ return Skills.fromLocalDir("/tmp/m-skill-b");
+ }
+ }
+
private static Skills mergedSkillsOf(Agent agent) throws Exception {
AgentPlan plan = new AgentPlan(agent);
ResourceProvider configProvider =
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanRoutingBackstopTest.java b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanRoutingBackstopTest.java
index a2a079131..ae56fefcb 100644
--- a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanRoutingBackstopTest.java
+++ b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanRoutingBackstopTest.java
@@ -57,7 +57,7 @@ class AgentPlanRoutingBackstopTest {
void planBackstopRejectsClashArrivingFromDifferentRegistries() {
Agent agent = new Agent();
agent.addResource("shared", ResourceType.MODEL_ROUTER, descriptor("some.Router"));
- // Environment-level resources merge in via putIfAbsent, bypassing the per-call
+ // Environment-level resources merge in via addResourcesIfAbsent, bypassing the per-call
// checks: neither addResource call ever saw both registrations.
agent.addResourcesIfAbsent(
Map.of(
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetupTest.java b/plan/src/test/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetupTest.java
index d9c99dc73..3e0f12b4c 100644
--- a/plan/src/test/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetupTest.java
+++ b/plan/src/test/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetupTest.java
@@ -22,6 +22,7 @@ import org.apache.flink.agents.api.chat.messages.ChatResult;
import org.apache.flink.agents.api.metrics.FlinkAgentsMetricGroup;
import org.apache.flink.agents.api.resource.ResourceContext;
import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -39,6 +40,8 @@ import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyList;
+import static org.mockito.Mockito.anyMap;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
@@ -225,4 +228,65 @@ public class PythonChatModelSetupTest {
verify(mockAdapter).setMetricGroup(mockChatModelSetup, metricGroup);
}
+
+ /**
+ * The wrapper's {@code open()} only delegates to Python, so the base implementation — the only
+ * place that expands the {@code skills_sources} marker — never runs for this instance. The
+ * resolved names still have to land on the wrapper, because the Java-side reader ({@code
+ * ChatModelAction.injectBashToolArgs}) builds the bash tool's {@code allowed_script_dirs} from
+ * {@code getSkills()} and a source-only declaration carries no explicit {@code skills}
+ * argument.
+ */
+ @Test
+ void openResolvesSkillsSourcesMarkerOntoTheWrapper() throws Exception {
+ ResourceDescriptor descriptor =
+ new ResourceDescriptor(
+ "flink_agents.integrations.chat_models.ollama.OllamaChatModelSetup",
+ Map.of(
+ "skills_sources",
+ List.of(
+ new SkillSourceSpec(
+ "local", Map.of("path", "/data/skills")))));
+ when(mockGetResource.resolveSkillNamesForSources(anyList()))
+ .thenReturn(List.of("demo", "extra"));
+ PythonChatModelSetup setup =
+ new PythonChatModelSetup(
+ mockAdapter, mockChatModelSetup, descriptor, mockGetResource);
+
+ setup.open();
+
+ assertThat(setup.getSkills()).containsExactly("demo", "extra");
+ verify(mockAdapter).callMethod(eq(mockChatModelSetup), eq("open"), anyMap());
+ }
+
+ @Test
+ void openKeepsExplicitSkillsFirstAndAppendsResolvedSources() throws Exception {
+ ResourceDescriptor descriptor =
+ new ResourceDescriptor(
+ "flink_agents.integrations.chat_models.ollama.OllamaChatModelSetup",
+ Map.of(
+ "skills",
+ List.of("explicit"),
+ "skills_sources",
+ List.of(
+ new SkillSourceSpec(
+ "local", Map.of("path", "/data/skills")))));
+ when(mockGetResource.resolveSkillNamesForSources(anyList()))
+ .thenReturn(List.of("explicit", "demo"));
+ PythonChatModelSetup setup =
+ new PythonChatModelSetup(
+ mockAdapter, mockChatModelSetup, descriptor, mockGetResource);
+
+ setup.open();
+
+ assertThat(setup.getSkills()).containsExactly("explicit", "demo");
+ }
+
+ @Test
+ void openLeavesSkillsNullWhenNoSourcesAreDeclared() throws Exception {
+ pythonChatModelSetup.open();
+
+ assertThat(pythonChatModelSetup.getSkills()).isNull();
+ verify(mockAdapter).callMethod(eq(mockChatModelSetup), eq("open"), anyMap());
+ }
}
diff --git a/python/flink_agents/api/agents/react_agent.py b/python/flink_agents/api/agents/react_agent.py
index 0958103b0..d1661a873 100644
--- a/python/flink_agents/api/agents/react_agent.py
+++ b/python/flink_agents/api/agents/react_agent.py
@@ -16,6 +16,7 @@
# limitations under the License.
#################################################################################
import logging
+from collections.abc import Sequence
from concurrent.futures import CancelledError
from typing import TYPE_CHECKING, cast
@@ -40,6 +41,7 @@ from flink_agents.api.events.event_type import EventType
from flink_agents.api.prompts.prompt import Prompt
from flink_agents.api.resource import ResourceDescriptor, ResourceType
from flink_agents.api.runner_context import RunnerContext
+from flink_agents.api.skills import Skills
if TYPE_CHECKING:
from flink_agents.api.events.chat_event import ChatResponseEvent
@@ -51,6 +53,42 @@ _DEFAULT_SCHEMA_PROMPT = "_default_schema_prompt"
_DEFAULT_NATIVE_SCHEMA_PROMPT = "_default_native_schema_prompt"
_DEFAULT_USER_PROMPT = "_default_user_prompt"
_OUTPUT_SCHEMA = "_output_schema"
+_SKILLS_ARGUMENT = "skills"
+_SKILLS_SOURCES_ARGUMENT = "skills_sources"
+_SKILLS_RESOURCE_NAME = "_react_agent_skills"
+
+
+def _with_skills(
+ chat_model: ResourceDescriptor, skills: Sequence[str] | None
+) -> ResourceDescriptor:
+ """Combine constructor skills into a copy of the chat model descriptor."""
+ if isinstance(skills, str):
+ # A bare string would otherwise be iterated into one-letter skill names.
+ err_msg = f"skills must be a list of skill names, not the string {skills!r}."
+ raise TypeError(err_msg)
+ if not skills:
+ return chat_model
+ declared = chat_model.arguments.get(_SKILLS_ARGUMENT) or []
+ merged = list(dict.fromkeys([*declared, *skills]))
+ return chat_model.model_copy(
+ update={"arguments": {**chat_model.arguments, _SKILLS_ARGUMENT: merged}}
+ )
+
+
+def _with_skills_sources(
+ chat_model: ResourceDescriptor, skills: Skills
+) -> ResourceDescriptor:
+ """Record source declarations as a marker in the chat model descriptor."""
+ if not skills.sources:
+ return chat_model
+ return chat_model.model_copy(
+ update={
+ "arguments": {
+ **chat_model.arguments,
+ _SKILLS_SOURCES_ARGUMENT: skills.sources,
+ }
+ }
+ )
# Kept byte-identical to the Java NATIVE_SCHEMA_PROMPT_PREFIX.
_NATIVE_SCHEMA_PROMPT_PREFIX = (
@@ -117,6 +155,7 @@ class ReActAgent(Agent):
chat_model: ResourceDescriptor,
prompt: Prompt | None = None,
output_schema: type[BaseModel] | RowTypeInfo | None = None,
+ skills: Sequence[str] | Skills | None = None,
) -> None:
"""Init method of ReActAgent.
@@ -134,15 +173,56 @@ class ReActAgent(Agent):
natively, the prompt describes the schema's fields without requiring
JSON, and the schema is applied on the final conversion. Otherwise it
asks for a JSON response matching the schema.
+ skills : Optional[Sequence[str] | Skills] = None
+ Either the names of the skills to expose to the chat model, each
+ matching the ``name`` of a ``SKILL.md`` available to the agent, or a
+ :class:`Skills` object declaring one or more skill sources.
+
+ With names, they are combined with the ``skills`` argument of
+ ``chat_model``: the descriptor's skills come first, followed by these,
+ keeping only the first occurrence of each name. ``None`` or an empty
+ sequence adds nothing, so the descriptor is used exactly as given.
+
+ With a :class:`Skills` object, its sources are registered on the agent
+ and recorded as a marker on the chat model descriptor; the skill names
+ are resolved from those sources at runtime and appended to any
+ explicitly named skills. A single ``Skills`` may declare several
+ sources, so the object is not limited to one source. To combine
+ sources declared in separate objects, gather them into one ``Skills``,
+ declare further ``@skills`` methods, or register them on the agent with
+ ``add_resource``. An empty ``Skills`` adds nothing.
+
+ In both forms the descriptor itself is never modified, and only skill
+ names are combined; the ``bash`` tool's command policy, such as
+ ``allowed_commands``, stays owned by the chat model descriptor and is
+ left unchanged.
Raises:
------
TypeError
- If the schema is neither a RowTypeInfo nor a BaseModel subclass, or if a
- BaseModel schema cannot be rendered as a JSON Schema.
+ If the schema is neither a RowTypeInfo nor a BaseModel subclass, if a
+ BaseModel schema cannot be rendered as a JSON Schema, or if ``skills``
+ is a bare string rather than a sequence of names.
"""
super().__init__()
- self.add_resource(_DEFAULT_CHAT_MODEL, ResourceType.CHAT_MODEL, chat_model)
+
+ # Handle skills: either a Skills object (register sources + marker) or
+ # a list of skill names (merge into descriptor's "skills" argument).
+ if isinstance(skills, Skills):
+ if skills.sources:
+ self.add_resource(
+ _SKILLS_RESOURCE_NAME, ResourceType.SKILLS, skills
+ )
+ chat_model = _with_skills_sources(chat_model, skills)
+ # else: empty Skills — pass descriptor unchanged
+ else:
+ chat_model = _with_skills(chat_model, skills)
+
+ self.add_resource(
+ _DEFAULT_CHAT_MODEL,
+ ResourceType.CHAT_MODEL,
+ chat_model,
+ )
if output_schema:
if isinstance(output_schema, type) and issubclass(output_schema, BaseModel):
diff --git a/python/flink_agents/api/agents/tests/test_react_agent.py b/python/flink_agents/api/agents/tests/test_react_agent.py
index 1854dc2d2..3435a47ba 100644
--- a/python/flink_agents/api/agents/tests/test_react_agent.py
+++ b/python/flink_agents/api/agents/tests/test_react_agent.py
@@ -22,11 +22,17 @@ from pydantic import BaseModel, Field
from pyflink.common.typeinfo import Types
from flink_agents.api.agents.react_agent import (
+ _DEFAULT_CHAT_MODEL,
_DEFAULT_NATIVE_SCHEMA_PROMPT,
_DEFAULT_SCHEMA_PROMPT,
ReActAgent,
)
-from flink_agents.api.resource import ResourceDescriptor, ResourceType
+from flink_agents.api.resource import (
+ JavaResourceDescriptor,
+ ResourceDescriptor,
+ ResourceType,
+)
+from flink_agents.api.skills import Skills
# Named rather than imported so building an agent needs no chat model on the path;
# a descriptor records the class and resolves it only when the resource is created.
@@ -143,3 +149,151 @@ def test_unsupported_output_schema_type_reports_the_type() -> None:
"""A schema of neither supported kind is rejected, named by the type received."""
with pytest.raises(TypeError, match=r"<class 'str'> is not supported"):
_agent("not-a-schema")
+
+
+def _descriptor(**arguments: Any) -> ResourceDescriptor:
+ return ResourceDescriptor(clazz=_CHAT_MODEL_CLASS, **arguments)
+
+
+def _chat_model(chat_model: ResourceDescriptor, skills: Any) -> ResourceDescriptor:
+ """The chat model descriptor an agent registers for the given skills."""
+ agent = ReActAgent(chat_model=chat_model, skills=skills)
+ return agent._resources[ResourceType.CHAT_MODEL][_DEFAULT_CHAT_MODEL]
+
+
+def test_constructor_only_skills_become_the_chat_model_skills() -> None:
+ """Constructor skills alone become the chat model's skills."""
+ actual = _chat_model(_descriptor(model="qwen3:8b"), ["a", "b"])
+
+ assert actual.arguments == {"model": "qwen3:8b", "skills": ["a", "b"]}
+
+
+@pytest.mark.parametrize("skills", [None, [], ()])
+def test_without_constructor_skills_the_descriptor_is_used_as_given(
+ skills: Any,
+) -> None:
+ """No constructor skills add nothing, so an absent ``skills`` stays absent."""
+ with_skills = _descriptor(skills=["a"])
+ without_skills = _descriptor(model="qwen3:8b")
+
+ assert _chat_model(with_skills, skills) is with_skills
+ assert _chat_model(without_skills, skills) is without_skills
+ assert "skills" not in without_skills.arguments
+
+
+def test_combined_skills_are_ordered_and_deduplicated() -> None:
+ """Descriptor skills come first, then constructor skills, each name kept once."""
+ chat_model = _descriptor(skills=["a", "b"])
+
+ actual = _chat_model(chat_model, ["b", "c", "a", "c"])
+
+ assert actual.arguments["skills"] == ["a", "b", "c"]
+ assert chat_model.arguments["skills"] == ["a", "b"]
+
+
+def test_descriptor_shared_across_agents_stays_independent() -> None:
+ """Agents sharing one descriptor each get only their own constructor skills."""
+ chat_model = _descriptor(skills=["shared"])
+
+ first = _chat_model(chat_model, ["a"])
+ second = _chat_model(chat_model, ["b"])
+
+ assert first.arguments["skills"] == ["shared", "a"]
+ assert second.arguments["skills"] == ["shared", "b"]
+ assert chat_model.arguments["skills"] == ["shared"]
+
+
+def test_constructor_skills_keep_allowed_commands() -> None:
+ """Constructor skills leave the descriptor's command policy untouched."""
+ chat_model = _descriptor(
+ skills=["a"],
+ allowed_commands=["echo", "bc"],
+ allowed_script_dirs=["/opt/scripts"],
+ )
+
+ actual = _chat_model(chat_model, ["b"])
+
+ assert actual.arguments["allowed_commands"] == ["echo", "bc"]
+ assert actual.arguments["allowed_script_dirs"] == ["/opt/scripts"]
+
+
+def test_constructor_skills_keep_the_descriptor_language() -> None:
+ """Constructor skills on a Java chat model keep it a Java declaration."""
+ chat_model = JavaResourceDescriptor(clazz="com.example.ChatModel", skills=["a"])
+
+ actual = _chat_model(chat_model, ["b"])
+
+ assert isinstance(actual, JavaResourceDescriptor)
+ assert (actual.target_module, actual.target_clazz) == ("", "com.example.ChatModel")
+ assert actual.arguments["skills"] == ["a", "b"]
+
+
+def test_bare_string_skills_are_rejected() -> None:
+ """A bare string is rejected rather than split into one-letter skill names."""
+ with pytest.raises(TypeError, match="not the string 'math-calculator'"):
+ _chat_model(_descriptor(), "math-calculator")
+
+
+def _chat_model_of(agent: ReActAgent) -> ResourceDescriptor:
+ """The chat model descriptor an agent registered."""
+ return agent._resources[ResourceType.CHAT_MODEL][_DEFAULT_CHAT_MODEL]
+
+
+def test_skills_object_records_sources_and_registers_the_resource() -> None:
+ """A Skills object becomes a source marker plus an agent-level resource."""
+ chat_model = _descriptor(model="qwen3:8b")
+ skills = Skills.from_local_dir("/tmp/skill-a", "/tmp/skill-b")
+
+ agent = ReActAgent(chat_model=chat_model, skills=skills)
+ actual = _chat_model_of(agent)
+
+ sources = actual.arguments["skills_sources"]
+ assert [spec.scheme for spec in sources] == ["local", "local"]
+ assert sources[0].params == {"path": "/tmp/skill-a"}
+ assert sources[1].params == {"path": "/tmp/skill-b"}
+ # The original descriptor is never modified.
+ assert "skills_sources" not in chat_model.arguments
+ # The Skills object is registered under the reserved agent-level name.
+ assert "_react_agent_skills" in agent.resources[ResourceType.SKILLS]
+
+
+def test_empty_skills_object_is_a_no_op() -> None:
+ """A Skills object with no sources adds neither a marker nor a resource."""
+ chat_model = _descriptor(model="qwen3:8b")
+
+ agent = ReActAgent(chat_model=chat_model, skills=Skills())
+ actual = _chat_model_of(agent)
+
+ assert actual is chat_model
+ assert "skills_sources" not in actual.arguments
+ assert "_react_agent_skills" not in agent.resources[ResourceType.SKILLS]
+
+
+def test_skills_object_and_descriptor_skills_coexist() -> None:
+ """A recorded source marker leaves the descriptor's explicit skills as given."""
+ chat_model = _descriptor(skills=["a", "b"], model="qwen3:8b")
+
+ agent = ReActAgent(
+ chat_model=chat_model, skills=Skills.from_local_dir("/tmp/skill-c")
+ )
+ actual = _chat_model_of(agent)
+
+ # Explicit skills are preserved; the marker carries the sources for the
+ # runtime to resolve, and the two are merged when the setup is opened.
+ assert actual.arguments["skills"] == ["a", "b"]
+ assert len(actual.arguments["skills_sources"]) == 1
+ assert "skills_sources" not in chat_model.arguments
+
+
+def test_skills_object_keeps_the_descriptor_language() -> None:
+ """Sources recorded on a Java chat model keep it a Java declaration."""
+ chat_model = JavaResourceDescriptor(clazz="com.example.ChatModel", skills=["a"])
+
+ agent = ReActAgent(
+ chat_model=chat_model, skills=Skills.from_local_dir("/tmp/skill-b")
+ )
+ actual = _chat_model_of(agent)
+
+ assert isinstance(actual, JavaResourceDescriptor)
+ assert (actual.target_module, actual.target_clazz) == ("", "com.example.ChatModel")
+ assert len(actual.arguments["skills_sources"]) == 1
diff --git a/python/flink_agents/api/chat_models/chat_model.py b/python/flink_agents/api/chat_models/chat_model.py
index 77bd59b4e..1ce95c4f0 100644
--- a/python/flink_agents/api/chat_models/chat_model.py
+++ b/python/flink_agents/api/chat_models/chat_model.py
@@ -34,7 +34,7 @@ from flink_agents.api.chat_result import ChatResult
from flink_agents.api.metric_group import MetricGroup
from flink_agents.api.prompts.prompt import Prompt
from flink_agents.api.resource import Resource, ResourceType
-from flink_agents.api.skills import BASH_TOOL, LOAD_SKILL_TOOL
+from flink_agents.api.skills import BASH_TOOL, LOAD_SKILL_TOOL, SkillSourceSpec
from flink_agents.api.subagent import CALLABLE_NAME_PREFIX, SubagentSetup
from flink_agents.api.tools.tool import Tool
@@ -432,6 +432,7 @@ class BaseChatModelSetup(Resource):
description="Names of the AGENT resources this setup may delegate to.",
)
skills: List[str] | None = None
+ skills_sources: List[SkillSourceSpec] | None = None
skill_discovery_prompt: str | None = None
allowed_commands: List[str] = Field(default_factory=list)
allowed_script_dirs: List[str] = Field(default_factory=list)
@@ -489,6 +490,20 @@ class BaseChatModelSetup(Resource):
self.prompt, ResourceType.PROMPT
),
)
+
+ # Resolve skills_sources marker (plan-time source declarations) into skill
+ # names, then merge with the explicit "skills" list. Explicit names come
+ # first; resolved names are appended, de-duplicated while preserving order.
+ if self.skills_sources:
+ resolved = self.resource_context.resolve_skill_names_for_sources(
+ self.skills_sources
+ )
+ merged: list[str] = list(self.skills) if self.skills else []
+ for name in resolved:
+ if name not in merged:
+ merged.append(name)
+ self.skills = merged or None
+
if self.skills is not None:
self.skill_discovery_prompt = (
self.resource_context.generate_available_skills_prompt(*self.skills)
diff --git a/python/flink_agents/api/resource_context.py b/python/flink_agents/api/resource_context.py
index 8b323df77..440ed935e 100644
--- a/python/flink_agents/api/resource_context.py
+++ b/python/flink_agents/api/resource_context.py
@@ -26,6 +26,7 @@ from typing import TYPE_CHECKING, List
if TYPE_CHECKING:
from flink_agents.api.resource import Resource, ResourceType
+ from flink_agents.api.skills import SkillSourceSpec
class ResourceContext(ABC):
@@ -49,3 +50,23 @@ class ResourceContext(ABC):
Returns an empty list if no skills are configured or none of the
requested skills are filesystem-backed.
"""
+
+ def resolve_skill_names_for_sources(
+ self, sources: list["SkillSourceSpec"]
+ ) -> List[str]:
+ """Resolve skill names from the given source specifications.
+
+ At plan time, a descriptor may record a set of source specs as a marker
+ meaning "all skills from these sources." At runtime, this method resolves
+ the marker into actual skill names by looking up the sources in the
+ agent's ``SkillManager``.
+
+ Returns an empty list if no skills are configured or the sources are not
+ loaded.
+
+ Deliberately not abstract, mirroring the Java ``ResourceContext``
+ ``default`` method: the empty default keeps ``ResourceContext``
+ subclasses that predate skill-source resolution instantiable instead of
+ breaking them.
+ """
+ return []
diff --git a/python/flink_agents/e2e_tests/e2e_tests_integration/agent_skills_test.py b/python/flink_agents/e2e_tests/e2e_tests_integration/agent_skills_test.py
index 7a0bde62d..4ab205a97 100644
--- a/python/flink_agents/e2e_tests/e2e_tests_integration/agent_skills_test.py
+++ b/python/flink_agents/e2e_tests/e2e_tests_integration/agent_skills_test.py
@@ -293,17 +293,18 @@ def test_react_agent_with_skills(tmp_path: Path) -> None:
["result"],
)
- # create ReAct agent.
+ # create ReAct agent. The skill is named on the constructor, while the bash
+ # command policy stays on the chat model descriptor that owns it.
agent = ReActAgent(
chat_model=ResourceDescriptor(
clazz=ResourceName.ChatModel.OPENAI_COMPLETIONS_SETUP,
connection="openai",
model=MODEL,
- skills=["math-calculator"],
allowed_commands=["echo", "bc"],
),
prompt=prompt,
output_schema=output_type_info,
+ skills=["math-calculator"],
)
output_type = ExternalTypeInfo(output_type_info)
diff --git a/python/flink_agents/plan/agent_plan.py b/python/flink_agents/plan/agent_plan.py
index 340c99216..211db981f 100644
--- a/python/flink_agents/plan/agent_plan.py
+++ b/python/flink_agents/plan/agent_plan.py
@@ -471,10 +471,13 @@ def _get_resource_providers(
for name, descriptor in agent.resources[ResourceType.MCP_SERVER].items():
_add_mcp_server(name, resource_providers, descriptor, config)
- # Merge decorator-based and programmatic skills
- all_skills: Dict[str, Skills] = dict(
- {**skills_descriptors, **agent.resources[ResourceType.SKILLS]}.items()
- )
+ # Merge decorator-based and programmatic skills. A name declared both ways resolves
+ # to the programmatic declaration and moves to the end: the flattened source order
+ # decides which declaration wins, and decorator declarations are the lowest level.
+ all_skills: Dict[str, Skills] = dict(skills_descriptors)
+ for name, skills in agent.resources[ResourceType.SKILLS].items():
+ all_skills.pop(name, None)
+ all_skills[name] = skills
_add_skills(all_skills, resource_providers)
for name, value in agent.resources[ResourceType.AGENT].items():
diff --git a/python/flink_agents/plan/resource/java/java_chat_model.py b/python/flink_agents/plan/resource/java/java_chat_model.py
index 3c454b7bb..ce83ae22c 100644
--- a/python/flink_agents/plan/resource/java/java_chat_model.py
+++ b/python/flink_agents/plan/resource/java/java_chat_model.py
@@ -167,6 +167,8 @@ class JavaChatModelSetup(BaseChatModelSetup):
def open(self) -> None:
"""Open the java resource."""
self._j_resource.open()
+ resolved = self._j_resource.getSkills()
+ self.skills = list(resolved) if resolved else None
@override
def chat(
diff --git a/python/flink_agents/plan/resource/java/java_resource_adapter.py b/python/flink_agents/plan/resource/java/java_resource_adapter.py
index 955c7d4cd..dba67df2e 100644
--- a/python/flink_agents/plan/resource/java/java_resource_adapter.py
+++ b/python/flink_agents/plan/resource/java/java_resource_adapter.py
@@ -46,3 +46,7 @@ class JavaResourceAdapter(Protocol):
def getSkillDirs(self, skill_names: list[str]) -> list[str]:
"""Resolve materialized skill directories."""
...
+
+ def resolveSkillNamesForSources(self, sources: list[dict]) -> list[str]:
+ """Resolve skill names declared by skill source specs."""
+ ...
diff --git a/python/flink_agents/plan/resource/java/java_resource_wrapper.py b/python/flink_agents/plan/resource/java/java_resource_wrapper.py
index d59843aff..64c4ce375 100644
--- a/python/flink_agents/plan/resource/java/java_resource_wrapper.py
+++ b/python/flink_agents/plan/resource/java/java_resource_wrapper.py
@@ -15,7 +15,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#################################################################################
-from typing import Any, List
+from typing import TYPE_CHECKING, Any, List
from pydantic import ConfigDict, Field
from typing_extensions import override
@@ -27,6 +27,9 @@ from flink_agents.api.resource_context import ResourceContext
from flink_agents.api.tools.tool import Tool, ToolMetadata, ToolType
from flink_agents.plan.resource.java.java_resource_adapter import JavaResourceAdapter
+if TYPE_CHECKING:
+ from flink_agents.api.skills import SkillSourceSpec
+
class JavaTool(Tool):
"""Java Tool that carries tool metadata and can be recognized by PythonChatModel."""
@@ -115,3 +118,23 @@ class JavaResourceContextWrapper(ResourceContext):
"""Return absolute directory paths for the given skill names."""
result = self._j_resource_adapter.getSkillDirs(list(skill_names))
return list(result) if result is not None else []
+
+ @override
+ def resolve_skill_names_for_sources(
+ self, sources: list["SkillSourceSpec"]
+ ) -> List[str]:
+ """Resolve skill names from the given source specifications.
+
+ Forwards to the Java ``JavaResourceAdapter#resolveSkillNamesForSources``
+ so that a Python chat model running inside a Java agent can expand the
+ ``skills_sources`` marker written by a Java-side ``Skills`` object. An
+ empty input short-circuits, keeping the no-skill path free of a bridge
+ call. The specs cross as plain ``{scheme, params}`` maps, per the bridge
+ rule that values entering Java stay flattened.
+ """
+ if not sources:
+ return []
+ result = self._j_resource_adapter.resolveSkillNamesForSources(
+ [source.model_dump() for source in sources]
+ )
+ return list(result) if result is not None else []
diff --git a/python/flink_agents/plan/tests/test_agent_plan_skills_precedence.py b/python/flink_agents/plan/tests/test_agent_plan_skills_precedence.py
new file mode 100644
index 000000000..a5d4afdc4
--- /dev/null
+++ b/python/flink_agents/plan/tests/test_agent_plan_skills_precedence.py
@@ -0,0 +1,66 @@
+################################################################################
+# 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.
+#################################################################################
+"""Skill source precedence when one name is declared at more than one level.
+
+``AgentPlan`` flattens every ``Skills`` declaration into one ordered source list,
+and later entries win on duplicate skill names. Decorator declarations are the
+lowest-precedence level, so a programmatic declaration reusing a decorator
+method's name has to move to the end of that list instead of keeping the
+decorator's slot.
+"""
+
+from flink_agents.api.agents.agent import Agent
+from flink_agents.api.decorators import skills
+from flink_agents.api.resource import ResourceType
+from flink_agents.api.skills import Skills
+from flink_agents.plan.agent_plan import SKILLS_CONFIG, AgentPlan
+from flink_agents.plan.configuration import AgentConfiguration
+
+
+class _SkillsAgent(Agent):
+ @skills
+ @staticmethod
+ def alpha() -> Skills:
+ return Skills.from_local_dir("/tmp/ann-alpha")
+
+ @skills
+ @staticmethod
+ def beta() -> Skills:
+ return Skills.from_local_dir("/tmp/ann-beta")
+
+
+def _merged_source_paths(agent: Agent) -> list[str]:
+ plan = AgentPlan.from_agent(agent, AgentConfiguration())
+ provider = plan.resource_providers[ResourceType.SKILLS][SKILLS_CONFIG]
+ merged = provider.provide(None, AgentConfiguration())
+ return [spec.params["path"] for spec in merged.sources]
+
+
+def test_decorator_skills_are_merged_in_declaration_order() -> None:
+ assert _merged_source_paths(_SkillsAgent()) == ["/tmp/ann-alpha", "/tmp/ann-beta"]
+
+
+def test_programmatic_skills_override_decorator_skills_by_name_and_move_last() -> None:
+ agent = _SkillsAgent()
+ agent.add_resource(
+ "alpha", ResourceType.SKILLS, Skills.from_local_dir("/tmp/prog-alpha")
+ )
+
+ # "alpha" resolves to the programmatic declaration, and that declaration is
+ # flattened behind "beta" so it stays the winning entry.
+ assert _merged_source_paths(agent) == ["/tmp/ann-beta", "/tmp/prog-alpha"]
diff --git a/python/flink_agents/runtime/java_resource_adapter.py b/python/flink_agents/runtime/java_resource_adapter.py
index 729882b5c..64a8cfa16 100644
--- a/python/flink_agents/runtime/java_resource_adapter.py
+++ b/python/flink_agents/runtime/java_resource_adapter.py
@@ -54,6 +54,10 @@ class JavaResourceAdapterImpl:
"""Resolve the directories of Java-hosted skills."""
return list(self._bridge.getSkillDirs(skill_names) or [])
+ def resolveSkillNamesForSources(self, sources: list[dict]) -> list[str]:
+ """Resolve the names of Java-hosted skills declared by source specs."""
+ return list(self._bridge.resolveSkillNamesForSources(sources) or [])
+
def set_metric_group(self, resource: Any, metric_group: Any) -> None:
"""Forward the Java metric group without exposing runtime types to Plan."""
if resource is None:
diff --git a/python/flink_agents/runtime/remote_execution_environment.py b/python/flink_agents/runtime/remote_execution_environment.py
index d26c14e5f..e1e21df7d 100644
--- a/python/flink_agents/runtime/remote_execution_environment.py
+++ b/python/flink_agents/runtime/remote_execution_environment.py
@@ -130,8 +130,20 @@ class RemoteAgentBuilder(AgentBuilder):
agent = self.__agents[agent]
# inspect refer actions and resources from env to agent.
+ # Environment entries are placed before agent entries so downstream merging sees
+ # env-then-agent precedence. An entry the agent overrides is dropped from the
+ # environment side rather than replaced in place: ``dict.__or__`` keeps the left
+ # operand's slot, which would leave the agent's replacement early in the order
+ # and let an unrelated environment entry end up last and win instead.
for type, name_to_resource in self.__resources.items():
- agent.resources[type] = name_to_resource | agent.resources[type]
+ agent_level = agent.resources[type]
+ merged = {
+ name: resource
+ for name, resource in name_to_resource.items()
+ if name not in agent_level
+ }
+ merged.update(agent_level)
+ agent.resources[type] = merged
agent_plan_json = AgentPlan.from_agent(
agent, self.__config, agent_name
diff --git a/python/flink_agents/runtime/resource_context.py b/python/flink_agents/runtime/resource_context.py
index 67e68b1aa..66833b289 100644
--- a/python/flink_agents/runtime/resource_context.py
+++ b/python/flink_agents/runtime/resource_context.py
@@ -28,7 +28,7 @@ from flink_agents.runtime.skill.skill_manager import SkillManager
if TYPE_CHECKING:
from flink_agents.api.resource import Resource
- from flink_agents.api.skills import Skills
+ from flink_agents.api.skills import Skills, SkillSourceSpec
from flink_agents.runtime.resource_cache import ResourceCache
@@ -65,6 +65,15 @@ class ResourceContextImpl(ResourceContext):
return []
return manager.get_skill_dirs(*skill_names)
+ def resolve_skill_names_for_sources(
+ self, sources: list[SkillSourceSpec]
+ ) -> List[str]:
+ """Resolve skill names from the given source specifications."""
+ manager = self.get_skill_manager()
+ if manager is None:
+ return []
+ return manager.get_skill_names_for_sources(sources)
+
def get_skill_manager(self) -> SkillManager | None:
"""Get the SkillManager (runtime-internal only).
diff --git a/python/flink_agents/runtime/skill/skill_manager.py b/python/flink_agents/runtime/skill/skill_manager.py
index 3affff411..e633955ac 100644
--- a/python/flink_agents/runtime/skill/skill_manager.py
+++ b/python/flink_agents/runtime/skill/skill_manager.py
@@ -57,6 +57,11 @@ class SkillManager:
"""Initialize the SkillManager from a Skills configuration."""
self._skills: Dict[str, AgentSkill] = {}
self._repos: Dict[str, SkillRepository] = {}
+ # Reverse index: for every SkillSourceSpec that was loaded, the skill names
+ # that came from it. When two sources define the same skill name the later
+ # registration wins in _skills, but both sources retain their own entries
+ # here — callers can ask "what names did this source contribute?"
+ self._source_to_skills: Dict[SkillSourceSpec, List[str]] = {}
# Every opened repo in load order, kept separately from `_repos` because that
# map is keyed by skill name — duplicate names overwrite the earlier repo's
# reference, so close() iterates this list (id-deduped) instead.
@@ -182,6 +187,21 @@ class SkillManager:
repo = self._repos.get(skill_name)
return None if repo is None else repo.get_skill_dir(skill_name)
+ def get_skill_names_for_sources(
+ self, specs: list[SkillSourceSpec]
+ ) -> list[str]:
+ """Return the skill names that were loaded from the given sources.
+
+ Sources that were not loaded contribute an empty list. The order follows the
+ iteration order of *specs*; within each source, names follow load order.
+ """
+ result: list[str] = []
+ for spec in specs:
+ names = self._source_to_skills.get(spec)
+ if names:
+ result.extend(names)
+ return result
+
def _load_skills(self) -> None:
try:
for spec in self._config.sources:
@@ -198,7 +218,7 @@ class SkillManager:
msg = f"Failed to load skills from {source_identity}"
raise RuntimeError(msg) from e
assert origin is not None
- self._register_repo(repo, origin)
+ self._register_repo(repo, spec, origin)
except BaseException:
# Release every repo opened so far — the caller never receives a
# SkillManager reference to clean them up via close() itself, so
@@ -217,7 +237,10 @@ class SkillManager:
)
raise
- def _register_repo(self, repo: "SkillRepository", origin: SkillOrigin) -> None:
+ def _register_repo(
+ self, repo: "SkillRepository", spec: SkillSourceSpec, origin: SkillOrigin
+ ) -> None:
+ names: list[str] = []
for skill in repo.get_skills():
skill.set_resource_loader(
lambda name=skill.name, r=repo: r.get_resources(name)
@@ -233,6 +256,8 @@ class SkillManager:
)
self._skills[skill.name] = skill
self._repos[skill.name] = repo
+ names.append(skill.name)
+ self._source_to_skills[spec] = names
def close(self) -> None:
"""Close every opened :class:`SkillRepository`, releasing any temp directory
diff --git a/python/flink_agents/runtime/skill/tests/test_react_agent_skills.py b/python/flink_agents/runtime/skill/tests/test_react_agent_skills.py
new file mode 100644
index 000000000..b0bc2aabb
--- /dev/null
+++ b/python/flink_agents/runtime/skill/tests/test_react_agent_skills.py
@@ -0,0 +1,197 @@
+################################################################################
+# 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.
+################################################################################
+"""Skills passed to the ReActAgent constructor, as seen by its chat model.
+
+Checking the agent's descriptor alone would not show that the opened setup
+discovers the skills, exposes ``load_skill`` and ``bash``, or grants the skill
+directories to ``bash``. These tests take the path a job takes: ``AgentPlan``
+registers the providers and ``ResourceCache`` builds and opens the setup.
+"""
+
+from collections.abc import Iterator, Sequence
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Any, Dict, List, cast
+
+from flink_agents.api.agents.react_agent import ReActAgent
+from flink_agents.api.chat_message import ChatMessage
+from flink_agents.api.chat_models.chat_model import (
+ BaseChatModelConnection,
+ BaseChatModelSetup,
+)
+from flink_agents.api.resource import ResourceDescriptor, ResourceType
+from flink_agents.api.skills import BASH_TOOL, LOAD_SKILL_TOOL, Skills
+from flink_agents.api.tools.tool import Tool
+from flink_agents.plan.agent_plan import AgentPlan
+from flink_agents.plan.configuration import AgentConfiguration
+from flink_agents.runtime.resource_cache import ResourceCache
+
+_CHAT_MODEL = "_default_chat_model"
+_CONNECTION = "connection"
+_SKILLS_DIR = Path(__file__).parent / "resources" / "skills"
+
+
+class StubConnection(BaseChatModelConnection):
+ """Resolved by the setup on open; never asked to chat."""
+
+ def chat(
+ self,
+ messages: Sequence[ChatMessage],
+ tools: List[Tool] | None = None,
+ output_schema: Any = None,
+ **kwargs: Any,
+ ) -> ChatMessage:
+ """Refuse: these tests only open the setup."""
+ msg = "These tests only open the setup."
+ raise NotImplementedError(msg)
+
+
+class StubChatModelSetup(BaseChatModelSetup):
+ """Built by the plan's provider from its import path."""
+
+ @property
+ def model_kwargs(self) -> Dict[str, Any]:
+ """No model settings."""
+ return {}
+
+
+def _import_path(clazz: type) -> str:
+ return f"{clazz.__module__}.{clazz.__name__}"
+
+
+def _chat_model(**arguments: Any) -> ResourceDescriptor:
+ return ResourceDescriptor(
+ clazz=_import_path(StubChatModelSetup),
+ connection=_CONNECTION,
+ model="stub-model",
+ **arguments,
+ )
+
+
+@contextmanager
+def _opened_chat_model(
+ agent: ReActAgent, *, register_skill_source: bool = True
+) -> Iterator[BaseChatModelSetup]:
+ agent.add_resource(
+ name=_CONNECTION,
+ resource_type=ResourceType.CHAT_MODEL_CONNECTION,
+ instance=ResourceDescriptor(clazz=_import_path(StubConnection)),
+ )
+ if register_skill_source:
+ # Names-form tests name skills from this shared source. Skills-object
+ # tests register their own source through the constructor instead, so
+ # they pass ``register_skill_source=False``.
+ agent.add_resource(
+ name="test_skills",
+ resource_type=ResourceType.SKILLS,
+ instance=Skills.from_local_dir(str(_SKILLS_DIR)),
+ )
+ plan = AgentPlan.from_agent(agent, AgentConfiguration())
+ cache = ResourceCache(plan.resource_providers, plan.config)
+ try:
+ yield cast(
+ "BaseChatModelSetup",
+ cache.get_resource(_CHAT_MODEL, ResourceType.CHAT_MODEL),
+ )
+ finally:
+ cache.close()
+
+
+def test_constructor_skills_alone_are_loadable_by_the_chat_model() -> None:
+ agent = ReActAgent(chat_model=_chat_model(), skills=["github"])
+
+ with _opened_chat_model(agent) as setup:
+ assert setup.skills == ["github"]
+ assert "<name>github</name>" in setup.skill_discovery_prompt
+ assert "<name>nano-banana-pro</name>" not in setup.skill_discovery_prompt
+ assert [tool.name for tool in setup.tools] == [LOAD_SKILL_TOOL, BASH_TOOL]
+ load_skill = next(tool for tool in setup.tools if tool.name == LOAD_SKILL_TOOL)
+ assert load_skill.call(name="github").startswith(
+ '<skill_content name="github">'
+ )
+
+
+def test_descriptor_and_constructor_skills_share_the_descriptor_command_policy() -> (
+ None
+):
+ agent = ReActAgent(
+ chat_model=_chat_model(skills=["github"], allowed_commands=["gh"]),
+ skills=["nano-banana-pro", "github"],
+ )
+
+ with _opened_chat_model(agent) as setup:
+ assert setup.skills == ["github", "nano-banana-pro"]
+ assert "<name>github</name>" in setup.skill_discovery_prompt
+ assert "<name>nano-banana-pro</name>" in setup.skill_discovery_prompt
+ assert setup.allowed_commands == ["gh"]
+ # The chat model action grants bash these directories as allowed script
+ # dirs, so a skill added only through the constructor can still run its
+ # own scripts.
+ skill_dirs = setup.resource_context.get_skill_dirs(*setup.skills)
+ assert len(skill_dirs) == 2
+ assert any(
+ Path(skill_dir).name == "nano-banana-pro" for skill_dir in skill_dirs
+ )
+
+
+def test_empty_constructor_skills_leave_the_chat_model_without_skills() -> None:
+ # Skill sources are registered, so load_skill and bash exist in the plan; the
+ # chat model must still not pick them up when no skill is named.
+ agent = ReActAgent(chat_model=_chat_model(), skills=[])
+
+ with _opened_chat_model(agent) as setup:
+ assert setup.skills is None
+ assert setup.skill_discovery_prompt is None
+ assert setup.tools == []
+
+
+def test_skills_object_constructor_resolves_sources_to_skill_names() -> None:
+ # The constructor registers the source itself, so the setup resolves the
+ # names from it at open time rather than being handed a list of names.
+ agent = ReActAgent(
+ chat_model=_chat_model(), skills=Skills.from_local_dir(str(_SKILLS_DIR))
+ )
+
+ with _opened_chat_model(agent, register_skill_source=False) as setup:
+ assert set(setup.skills or []) == {"github", "nano-banana-pro"}
+ assert "<name>github</name>" in setup.skill_discovery_prompt
+ assert "<name>nano-banana-pro</name>" in setup.skill_discovery_prompt
+ assert [tool.name for tool in setup.tools] == [LOAD_SKILL_TOOL, BASH_TOOL]
+
+
+def test_skills_object_with_explicit_skills_merges_both_at_runtime() -> None:
+ agent = ReActAgent(
+ chat_model=_chat_model(skills=["github"]),
+ skills=Skills.from_local_dir(str(_SKILLS_DIR)),
+ )
+
+ with _opened_chat_model(agent, register_skill_source=False) as setup:
+ # Explicit skills come first, then the names resolved from the sources;
+ # "github" is kept once.
+ assert setup.skills == ["github", "nano-banana-pro"]
+
+
+def test_empty_skills_object_leaves_the_chat_model_without_skills() -> None:
+ # An empty Skills object registers no source and writes no marker, so the
+ # chat model has nothing to resolve.
+ agent = ReActAgent(chat_model=_chat_model(), skills=Skills())
+
+ with _opened_chat_model(agent, register_skill_source=False) as setup:
+ assert setup.skills is None
+ assert setup.skill_discovery_prompt is None
+ assert setup.tools == []
diff --git a/python/flink_agents/runtime/tests/test_cross_language_chat_model_skills.py b/python/flink_agents/runtime/tests/test_cross_language_chat_model_skills.py
new file mode 100644
index 000000000..7d6904870
--- /dev/null
+++ b/python/flink_agents/runtime/tests/test_cross_language_chat_model_skills.py
@@ -0,0 +1,74 @@
+################################################################################
+# 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.
+#################################################################################
+"""A Python agent reading the skills a Java chat model resolved.
+
+The Java setup expands the ``skills_sources`` marker during its own ``open()``
+and writes the names into the Java object. The Python wrapper is what the
+Python-side readers see (``chat_model_action._inject_bash_tool_args`` builds the
+bash ``allowed_script_dirs`` from ``chat_model.skills``), so ``open()`` has to
+mirror the resolved names back — a source-only declaration carries no explicit
+``skills`` argument and would otherwise stay ``None``.
+"""
+
+from typing import Any
+
+from flink_agents.plan.resource.java.java_chat_model import JavaChatModelSetup
+from flink_agents.runtime.java_resource_adapter import JavaResourceAdapterImpl
+
+
+class _JavaChatModelSetup:
+ """Stand-in for the Java setup object reached through pemja."""
+
+ def __init__(self, skills: list[str] | None) -> None:
+ self._skills = skills
+ self.opened = False
+
+ def open(self) -> None:
+ self.opened = True
+
+ def getSkills(self) -> list[str] | None:
+ return self._skills
+
+
+def _wrapper(java_setup: _JavaChatModelSetup, **kwargs: Any) -> JavaChatModelSetup:
+ return JavaChatModelSetup(
+ j_resource=java_setup,
+ j_resource_adapter=JavaResourceAdapterImpl(None),
+ connection="connection",
+ model="model",
+ **kwargs,
+ )
+
+
+def test_open_mirrors_the_skills_resolved_on_the_java_side():
+ java_setup = _JavaChatModelSetup(["demo", "extra"])
+
+ wrapper = _wrapper(java_setup)
+ wrapper.open()
+
+ assert java_setup.opened
+ assert wrapper.skills == ["demo", "extra"]
+
+
+def test_open_clears_stale_skills_when_the_java_side_reports_none():
+ java_setup = _JavaChatModelSetup(None)
+
+ wrapper = _wrapper(java_setup, skills=["stale"])
+ wrapper.open()
+
+ assert wrapper.skills is None
diff --git a/python/flink_agents/runtime/tests/test_cross_language_skill_sources.py b/python/flink_agents/runtime/tests/test_cross_language_skill_sources.py
new file mode 100644
index 000000000..bc72deb5b
--- /dev/null
+++ b/python/flink_agents/runtime/tests/test_cross_language_skill_sources.py
@@ -0,0 +1,145 @@
+################################################################################
+# 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.
+#################################################################################
+"""Cross-language forwarding of the ``skills_sources`` marker.
+
+A Python chat model running inside a Java agent reaches its ``ResourceContext``
+through :class:`JavaResourceContextWrapper`, so expanding the marker written by a
+Java-side ``Skills`` object has to cross the bridge. Before the forwarding
+existed the wrapper inherited the empty default and the marker resolved to no
+skills without any error.
+
+The same wrapper builds the skill discovery prompt and the bash skill
+directories, so all three calls are covered here: the Java object behind the
+bridge (``PythonResourceAdapterImpl``) has to expose a matching method for each
+one, or the call fails with an ``AttributeError`` instead of resolving.
+"""
+
+from typing import Any
+
+from flink_agents.api.skills import SkillSourceSpec
+from flink_agents.plan.resource.java.java_resource_wrapper import (
+ JavaResourceContextWrapper,
+)
+from flink_agents.runtime.java_resource_adapter import JavaResourceAdapterImpl
+
+
+class _FakeJavaBridge:
+ """Stand-in for the Java adapter object reached through pemja."""
+
+ def __init__(
+ self,
+ names: list[str] | None,
+ prompt: str | None = None,
+ dirs: list[str] | None = None,
+ ) -> None:
+ self._names = names
+ self._prompt = prompt
+ self._dirs = dirs
+ self.received: Any = None
+ self.prompt_argument: Any = None
+ self.dirs_argument: Any = None
+
+ def resolveSkillNamesForSources(self, sources: list[dict]) -> list[str] | None:
+ self.received = sources
+ return self._names
+
+ def generateAvailableSkillsPrompt(self, skill_names: list[str]) -> str | None:
+ self.prompt_argument = skill_names
+ return self._prompt
+
+ def getSkillDirs(self, skill_names: list[str]) -> list[str] | None:
+ self.dirs_argument = skill_names
+ return self._dirs
+
+
+def _wrapper(bridge: _FakeJavaBridge) -> JavaResourceContextWrapper:
+ return JavaResourceContextWrapper(JavaResourceAdapterImpl(bridge))
+
+
+def test_flattens_specs_to_wire_maps_and_returns_bridge_result():
+ bridge = _FakeJavaBridge(["math-calculator", "joke-generator"])
+
+ resolved = _wrapper(bridge).resolve_skill_names_for_sources(
+ [SkillSourceSpec(scheme="Local", params={"path": "/data/skills"})]
+ )
+
+ assert resolved == ["math-calculator", "joke-generator"]
+ # "Local" is normalized before crossing, so the Java SkillSourceSpec
+ # constructor receives the same lowercase scheme.
+ assert bridge.received == [{"scheme": "local", "params": {"path": "/data/skills"}}]
+
+
+def test_empty_sources_short_circuit_without_crossing():
+ bridge = _FakeJavaBridge(["unused"])
+
+ assert _wrapper(bridge).resolve_skill_names_for_sources([]) == []
+ assert bridge.received is None
+
+
+def test_missing_bridge_result_resolves_to_empty_list():
+ bridge = _FakeJavaBridge(None)
+
+ resolved = _wrapper(bridge).resolve_skill_names_for_sources(
+ [SkillSourceSpec(scheme="local", params={"path": "/data"})]
+ )
+
+ assert resolved == []
+
+
+def test_adapter_impl_normalizes_missing_bridge_result():
+ bridge = _FakeJavaBridge(None)
+
+ assert JavaResourceAdapterImpl(bridge).resolveSkillNamesForSources([]) == []
+
+
+def test_skill_prompt_and_dirs_forward_through_the_wrapper():
+ """The wrapper forwards all three skill calls, not just name resolution.
+
+ A Python chat model running inside a Java agent builds its discovery prompt and its
+ bash ``allowed_script_dirs`` through this context, so the Java object behind the
+ bridge has to expose the matching methods.
+ """
+ bridge = _FakeJavaBridge(None, prompt="<available_skills/>", dirs=["/tmp/demo"])
+
+ wrapper = _wrapper(bridge)
+
+ assert wrapper.generate_available_skills_prompt("demo") == "<available_skills/>"
+ assert wrapper.get_skill_dirs("demo") == ["/tmp/demo"]
+ assert bridge.prompt_argument == ["demo"]
+ assert bridge.dirs_argument == ["demo"]
+
+
+def test_missing_bridge_skill_prompt_and_dirs_resolve_to_empty():
+ bridge = _FakeJavaBridge(None)
+
+ assert _wrapper(bridge).generate_available_skills_prompt("demo") == ""
+ assert _wrapper(bridge).get_skill_dirs("demo") == []
+
+
+def test_adapter_impl_forwards_skill_prompt_and_dirs():
+ bridge = _FakeJavaBridge(None, prompt="prompt", dirs=["/tmp/a"])
+ adapter = JavaResourceAdapterImpl(bridge)
+
+ assert adapter.generateAvailableSkillsPrompt(["demo"]) == "prompt"
+ assert adapter.getSkillDirs(["demo"]) == ["/tmp/a"]
+
+
+def test_adapter_impl_normalizes_missing_skill_prompt_and_dirs():
+ adapter = JavaResourceAdapterImpl(_FakeJavaBridge(None))
+
+ assert adapter.getSkillDirs(["demo"]) == []
diff --git a/python/flink_agents/runtime/tests/test_remote_execution_environment.py b/python/flink_agents/runtime/tests/test_remote_execution_environment.py
index 7705c7629..b3b549adf 100644
--- a/python/flink_agents/runtime/tests/test_remote_execution_environment.py
+++ b/python/flink_agents/runtime/tests/test_remote_execution_environment.py
@@ -32,7 +32,9 @@ from pyflink.table import DataTypes, Schema
from flink_agents.api.agents.agent import Agent
from flink_agents.api.events.event import Event
+from flink_agents.api.resource import ResourceType
from flink_agents.api.runner_context import RunnerContext
+from flink_agents.api.skills import Skills
from flink_agents.plan.configuration import AgentConfiguration
from flink_agents.runtime.output_type_utils import (
infer_row_type_info,
@@ -283,6 +285,38 @@ def test_apply_sends_plan_to_java_validator() -> None:
]
+def test_environment_resource_entries_keep_their_order_when_agent_overrides_one():
+ """The agent's override moves last instead of keeping the environment slot.
+
+ Downstream, ``AgentPlan`` flattens these entries into an ordered source list
+ where later entries win, so an entry left in its environment slot would let an
+ unrelated environment declaration win instead.
+ """
+ env_skills = {
+ "z": Skills.from_local_dir("/tmp/z-env"),
+ "a": Skills.from_local_dir("/tmp/a-env"),
+ }
+ agent = Agent()
+ agent_override = Skills.from_local_dir("/tmp/z-agent")
+ agent.resources[ResourceType.SKILLS]["z"] = agent_override
+ builder = RemoteAgentBuilder(
+ input=MagicMock(),
+ config=AgentConfiguration(),
+ resources={ResourceType.SKILLS: env_skills},
+ agents={},
+ )
+
+ with patch(
+ "flink_agents.runtime.remote_execution_environment.invoke_method",
+ return_value=None,
+ ):
+ builder.apply(agent)
+
+ merged = agent.resources[ResourceType.SKILLS]
+ assert list(merged) == ["a", "z"]
+ assert merged["z"] is agent_override
+
+
def test_apply_surfaces_java_error_and_allows_retry() -> None:
builder = _remote_builder()
agent = _agent_with_conditions(["type =="])
diff --git a/runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapter.java b/runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapter.java
index c0f3381d4..4fd12e6bc 100644
--- a/runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapter.java
+++ b/runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapter.java
@@ -23,6 +23,7 @@ import org.apache.flink.agents.api.chat.messages.ChatResult;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceContext;
import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
import org.apache.flink.agents.api.tools.ToolMetadata;
import org.apache.flink.agents.api.tools.ToolParameterInjection;
import org.apache.flink.agents.api.tools.ToolParameters;
@@ -93,6 +94,31 @@ public class JavaResourceAdapter {
return resourceContext.getSkillDirs(skillNames);
}
+ /**
+ * Resolve the skill names declared by a set of skill source specs. Used by the Python {@code
+ * JavaResourceContextWrapper} when a Python chat model running in a Java agent was constructed
+ * with a {@code Skills} object: the descriptor carries its sources as a marker, and expanding
+ * that marker into names requires the agent's skill manager, which only the Java side owns.
+ *
+ * <p>The specs cross the boundary as plain {@code {"scheme": ..., "params": {...}}} maps, per
+ * the bridge rule that values crossing into Java stay flattened to primitives, strings, lists,
+ * and maps.
+ *
+ * @param sources the source specs as flat maps
+ * @return the resolved skill names
+ */
+ public List<String> resolveSkillNamesForSources(List<Map<String, Object>> sources)
+ throws Exception {
+ List<SkillSourceSpec> specs = new java.util.ArrayList<>();
+ if (sources != null) {
+ ObjectMapper mapper = new ObjectMapper();
+ for (Map<String, Object> source : sources) {
+ specs.add(mapper.convertValue(source, SkillSourceSpec.class));
+ }
+ }
+ return resourceContext.resolveSkillNamesForSources(specs);
+ }
+
/**
* Convert a Python chat message to a Java chat message. This method is intended for use by the
* Python interpreter.
diff --git a/runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/PythonResourceAdapterImpl.java b/runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/PythonResourceAdapterImpl.java
index 685dc2dfa..26c18f8c5 100644
--- a/runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/PythonResourceAdapterImpl.java
+++ b/runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/PythonResourceAdapterImpl.java
@@ -138,6 +138,21 @@ public class PythonResourceAdapterImpl implements PythonResourceAdapter, AutoClo
return interpreterManager.invoke(FROM_JAVA_RESOURCE, resourceType, kwargs);
}
+ public List<String> resolveSkillNamesForSources(List<Map<String, Object>> sources)
+ throws Exception {
+ return javaResourceAdapter.resolveSkillNamesForSources(sources);
+ }
+
+ /** Build the {@code <available_skills>} discovery prompt for the given skill names. */
+ public String generateAvailableSkillsPrompt(List<String> skillNames) throws Exception {
+ return javaResourceAdapter.generateAvailableSkillsPrompt(skillNames);
+ }
+
+ /** Return the absolute directory paths backing the given skill names. */
+ public List<String> getSkillDirs(List<String> skillNames) throws Exception {
+ return javaResourceAdapter.getSkillDirs(skillNames);
+ }
+
@Override
public PyObject initPythonResource(String module, String clazz, Map<String, Object> kwargs) {
kwargs.put(RESOURCE_CONTEXT_KEY, pythonResourceContext);
diff --git a/runtime/src/main/java/org/apache/flink/agents/runtime/resource/ResourceContextImpl.java b/runtime/src/main/java/org/apache/flink/agents/runtime/resource/ResourceContextImpl.java
index fa1fb979c..a7b79cac1 100644
--- a/runtime/src/main/java/org/apache/flink/agents/runtime/resource/ResourceContextImpl.java
+++ b/runtime/src/main/java/org/apache/flink/agents/runtime/resource/ResourceContextImpl.java
@@ -21,6 +21,7 @@ package org.apache.flink.agents.runtime.resource;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceContext;
import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
import org.apache.flink.agents.api.skills.Skills;
import org.apache.flink.agents.runtime.python.utils.PythonInterpreterManager;
import org.apache.flink.agents.runtime.skill.SkillManager;
@@ -98,6 +99,13 @@ public class ResourceContextImpl implements ResourceContext, AutoCloseable {
return manager == null ? Collections.emptyList() : manager.getSkillDirs(skillNames);
}
+ @Override
+ public List<String> resolveSkillNamesForSources(List<SkillSourceSpec> sources)
+ throws Exception {
+ SkillManager manager = ensureSkillManager();
+ return manager == null ? Collections.emptyList() : manager.getSkillNamesForSources(sources);
+ }
+
/**
* Returns the cached {@link SkillManager} for this context, or {@code null} if not configured.
*/
diff --git a/runtime/src/main/java/org/apache/flink/agents/runtime/skill/SkillManager.java b/runtime/src/main/java/org/apache/flink/agents/runtime/skill/SkillManager.java
index 7b89b264b..60a8aa22d 100644
--- a/runtime/src/main/java/org/apache/flink/agents/runtime/skill/SkillManager.java
+++ b/runtime/src/main/java/org/apache/flink/agents/runtime/skill/SkillManager.java
@@ -65,6 +65,14 @@ public class SkillManager implements AutoCloseable {
private final Map<String, AgentSkill> skills = new LinkedHashMap<>();
private final Map<String, SkillRepository> repos = new HashMap<>();
+ /**
+ * Reverse index: for every {@link SkillSourceSpec} that was loaded, the skill names that came
+ * from it. When two sources define the same skill name the later registration wins in {@link
+ * #skills}, but both sources still own their own names in this map — callers can ask "what
+ * names did this specific source contribute?" at any point after load.
+ */
+ private final Map<SkillSourceSpec, List<String>> sourceToSkills = new LinkedHashMap<>();
+
/**
* Every {@link SkillRepository} this manager has opened, in load order. Kept separately from
* {@link #repos} because that map is keyed by skill name — when two sources register the same
@@ -262,6 +270,24 @@ public class SkillManager implements AutoCloseable {
return repo == null ? null : repo.getSkillDir(skillName);
}
+ /**
+ * Return the skill names that were loaded from the given sources.
+ *
+ * <p>Sources that were not loaded (e.g. because they failed before any skill was registered)
+ * contribute an empty list. The order of returned names follows the load order within each
+ * source; the order across sources follows the iteration order of {@code specs}.
+ */
+ public List<String> getSkillNamesForSources(List<SkillSourceSpec> specs) {
+ List<String> result = new ArrayList<>();
+ for (SkillSourceSpec spec : specs) {
+ List<String> names = sourceToSkills.get(spec);
+ if (names != null) {
+ result.addAll(names);
+ }
+ }
+ return result;
+ }
+
private void loadAll() {
try {
for (SkillSourceSpec spec : config.getSources()) {
@@ -271,7 +297,7 @@ public class SkillManager implements AutoCloseable {
SkillRepository repo =
getHandler(spec.getScheme()).open(spec.getParams(), classLoader);
openedRepos.add(repo);
- registerRepo(repo, origin);
+ registerRepo(repo, spec, origin);
} catch (IOException | IllegalArgumentException e) {
String sourceIdentity =
origin == null ? spec.getScheme() + " source" : origin.toString();
@@ -346,7 +372,8 @@ public class SkillManager implements AutoCloseable {
}
}
- private void registerRepo(SkillRepository repo, SkillOrigin origin) {
+ private void registerRepo(SkillRepository repo, SkillSourceSpec spec, SkillOrigin origin) {
+ List<String> namesFromSource = new ArrayList<>();
for (AgentSkill skill : repo.getSkills()) {
final String skillName = skill.getName();
skill.setResourceLoader(() -> repo.getResources(skillName));
@@ -360,6 +387,8 @@ public class SkillManager implements AutoCloseable {
previous.getOrigin() == null ? "<unknown>" : previous.getOrigin());
}
repos.put(skillName, repo);
+ namesFromSource.add(skillName);
}
+ sourceToSkills.put(spec, namesFromSource);
}
}
diff --git a/runtime/src/test/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapterTest.java b/runtime/src/test/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapterTest.java
index a0c3f7046..20dd8ad91 100644
--- a/runtime/src/test/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapterTest.java
+++ b/runtime/src/test/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapterTest.java
@@ -26,13 +26,20 @@ import org.apache.flink.agents.api.chat.messages.ChatMessage;
import org.apache.flink.agents.api.chat.messages.ChatResult;
import org.apache.flink.agents.api.chat.messages.ImageBlock;
import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
import org.apache.flink.agents.api.tools.ToolParameterSource;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class JavaResourceAdapterTest {
@@ -196,6 +203,38 @@ public class JavaResourceAdapterTest {
assertThat(result).doesNotContainKey("result");
}
+ @Test
+ @SuppressWarnings("unchecked")
+ void resolveSkillNamesForSourcesConvertsWireMapsAndDelegates() throws Exception {
+ ResourceContext context = mock(ResourceContext.class);
+ when(context.resolveSkillNamesForSources(anyList())).thenReturn(List.of("demo"));
+ JavaResourceAdapter adapter =
+ new JavaResourceAdapter(context, Thread.currentThread().getContextClassLoader());
+
+ List<String> resolved =
+ adapter.resolveSkillNamesForSources(
+ List.of(
+ Map.<String, Object>of(
+ "scheme", "Local", "params", Map.of("path", "/data"))));
+
+ assertThat(resolved).containsExactly("demo");
+ ArgumentCaptor<List<SkillSourceSpec>> captor = ArgumentCaptor.forClass(List.class);
+ verify(context).resolveSkillNamesForSources(captor.capture());
+ assertThat(captor.getValue())
+ .containsExactly(new SkillSourceSpec("local", Map.of("path", "/data")));
+ }
+
+ @Test
+ void resolveSkillNamesForSourcesReturnsEmptyForNullAndEmptyInput() throws Exception {
+ ResourceContext context = mock(ResourceContext.class);
+ when(context.resolveSkillNamesForSources(anyList())).thenReturn(List.of());
+ JavaResourceAdapter adapter =
+ new JavaResourceAdapter(context, Thread.currentThread().getContextClassLoader());
+
+ assertThat(adapter.resolveSkillNamesForSources(null)).isEmpty();
+ assertThat(adapter.resolveSkillNamesForSources(List.of())).isEmpty();
+ }
+
@Tool(description = "Query order.")
public static String queryOrder(
@ToolParam(name = "order_id") String orderId,
diff --git a/runtime/src/test/java/org/apache/flink/agents/runtime/python/utils/PythonResourceAdapterImplTest.java b/runtime/src/test/java/org/apache/flink/agents/runtime/python/utils/PythonResourceAdapterImplTest.java
index be428685d..713322ccd 100644
--- a/runtime/src/test/java/org/apache/flink/agents/runtime/python/utils/PythonResourceAdapterImplTest.java
+++ b/runtime/src/test/java/org/apache/flink/agents/runtime/python/utils/PythonResourceAdapterImplTest.java
@@ -22,6 +22,7 @@ import org.apache.flink.agents.api.prompt.Prompt;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceContext;
import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.skills.SkillSourceSpec;
import org.apache.flink.agents.api.tools.Tool;
import org.apache.flink.agents.api.vectorstores.VectorStoreQueryResult;
import org.apache.flink.agents.plan.resource.python.PythonChatModelSetup;
@@ -29,6 +30,7 @@ import org.apache.flink.agents.plan.resource.python.PythonResourceWrapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import pemja.core.PythonInterpreter;
@@ -246,4 +248,52 @@ public class PythonResourceAdapterImplTest {
assertThat(result).isEqualTo(expectedResult);
verify(mockInterpreter).invoke(name, args);
}
+
+ /**
+ * A Python chat model running inside a Java agent reaches the agent's skill manager through
+ * this adapter — it is the object handed to {@code python_java_utils.get_resource_context}. The
+ * bridge therefore has to expose the skill methods the Python wrapper forwards to, and the
+ * specs have to reach the Java context retyped rather than as raw wire maps.
+ */
+ @Test
+ @SuppressWarnings("unchecked")
+ void resolveSkillNamesForSourcesDelegatesThroughRealJavaResourceAdapter() throws Exception {
+ when(resourceContext.resolveSkillNamesForSources(anyList())).thenReturn(List.of("demo"));
+
+ List<String> resolved =
+ adapterWithJavaResourceAdapter()
+ .resolveSkillNamesForSources(
+ List.of(
+ Map.<String, Object>of(
+ "scheme",
+ "Local",
+ "params",
+ Map.of("path", "/data"))));
+
+ assertThat(resolved).containsExactly("demo");
+ ArgumentCaptor<List<SkillSourceSpec>> captor = ArgumentCaptor.forClass(List.class);
+ verify(resourceContext).resolveSkillNamesForSources(captor.capture());
+ assertThat(captor.getValue())
+ .containsExactly(new SkillSourceSpec("local", Map.of("path", "/data")));
+ }
+
+ @Test
+ void generateAvailableSkillsPromptAndGetSkillDirsDelegateThroughBridge() throws Exception {
+ when(resourceContext.generateAvailableSkillsPrompt(List.of("demo")))
+ .thenReturn("<available_skills>demo</available_skills>");
+ when(resourceContext.getSkillDirs(List.of("demo"))).thenReturn(List.of("/tmp/demo"));
+
+ PythonResourceAdapterImpl adapter = adapterWithJavaResourceAdapter();
+
+ assertThat(adapter.generateAvailableSkillsPrompt(List.of("demo")))
+ .isEqualTo("<available_skills>demo</available_skills>");
+ assertThat(adapter.getSkillDirs(List.of("demo"))).containsExactly("/tmp/demo");
+ }
+
+ private PythonResourceAdapterImpl adapterWithJavaResourceAdapter() {
+ return new PythonResourceAdapterImpl(
+ resourceContext,
+ interpreterManager,
+ new JavaResourceAdapter(resourceContext, null));
+ }
}
diff --git a/runtime/src/test/java/org/apache/flink/agents/runtime/skill/ReActAgentSkillsTest.java b/runtime/src/test/java/org/apache/flink/agents/runtime/skill/ReActAgentSkillsTest.java
new file mode 100644
index 000000000..f671f2245
--- /dev/null
+++ b/runtime/src/test/java/org/apache/flink/agents/runtime/skill/ReActAgentSkillsTest.java
@@ -0,0 +1,225 @@
+/*
+ * 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.runtime.skill;
+
+import org.apache.flink.agents.api.agents.ReActAgent;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.ChatResult;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.chat.model.BaseChatModelSetup;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.skills.Skills;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolParameters;
+import org.apache.flink.agents.plan.AgentPlan;
+import org.apache.flink.agents.runtime.ResourceCache;
+import org.junit.jupiter.api.Test;
+
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Skills passed to the {@link ReActAgent} constructor must reach its chat model along the path a
+ * job takes: {@link AgentPlan} registers the providers and {@link ResourceCache} builds and opens
+ * the setup. Checking the agent's descriptor alone would not show that the setup discovers the
+ * skills, exposes {@code load_skill} and {@code bash}, or grants the skill directories to {@code
+ * bash}.
+ */
+class ReActAgentSkillsTest {
+
+ private static final String CHAT_MODEL = "_default_chat_model";
+ private static final String CONNECTION = "connection";
+ private static final String SKILLS_DIR =
+ Path.of("src/test/resources/skills").toAbsolutePath().toString();
+
+ /** Resolved by the setup on open; never asked to chat. */
+ public static class StubConnection extends BaseChatModelConnection {
+ public StubConnection(ResourceDescriptor descriptor, ResourceContext resourceContext) {
+ super(descriptor, resourceContext);
+ }
+
+ @Override
+ public ChatResult chat(
+ List<ChatMessage> messages, List<Tool> tools, Map<String, Object> modelParams) {
+ throw new UnsupportedOperationException("These tests only open the setup.");
+ }
+ }
+
+ /** Built reflectively by the plan's provider, hence public with the provider constructor. */
+ public static class StubChatModelSetup extends BaseChatModelSetup {
+ public StubChatModelSetup(ResourceDescriptor descriptor, ResourceContext resourceContext) {
+ super(descriptor, resourceContext);
+ }
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return new HashMap<>();
+ }
+ }
+
+ @Test
+ void constructorSkillsAloneAreLoadableByTheChatModel() throws Exception {
+ ReActAgent agent = new ReActAgent(chatModel().build(), null, null, List.of("github"));
+
+ try (ResourceCache cache = cacheFor(agent)) {
+ BaseChatModelSetup setup = openChatModel(cache);
+
+ assertThat(setup.getSkills()).containsExactly("github");
+ assertThat(setup.getSkillDiscoveryPrompt())
+ .contains("<name>github</name>")
+ .doesNotContain("<name>nano-banana-pro</name>");
+ assertThat(setup.getTools())
+ .extracting(Tool::getName)
+ .containsExactly(Skills.LOAD_SKILL_TOOL, Skills.BASH_TOOL);
+ Object loaded =
+ toolNamed(setup, Skills.LOAD_SKILL_TOOL)
+ .call(new ToolParameters(Map.of("name", "github")))
+ .getText();
+ assertThat((String) loaded).startsWith("<skill_content name=\"github\">");
+ }
+ }
+
+ @Test
+ void descriptorAndConstructorSkillsAreBothAvailableUnderTheDescriptorCommandPolicy()
+ throws Exception {
+ ReActAgent agent =
+ new ReActAgent(
+ chatModel()
+ .addInitialArgument("skills", List.of("github"))
+ .addInitialArgument("allowed_commands", List.of("gh"))
+ .build(),
+ null,
+ null,
+ List.of("nano-banana-pro", "github"));
+
+ try (ResourceCache cache = cacheFor(agent)) {
+ BaseChatModelSetup setup = openChatModel(cache);
+
+ assertThat(setup.getSkills()).containsExactly("github", "nano-banana-pro");
+ assertThat(setup.getSkillDiscoveryPrompt())
+ .contains("<name>github</name>", "<name>nano-banana-pro</name>");
+ assertThat(setup.getAllowedCommands()).containsExactly("gh");
+ // ChatModelAction grants bash these directories as allowed script dirs, so a skill
+ // added only through the constructor can still run its own scripts.
+ assertThat(setup.getResourceContext().getSkillDirs(setup.getSkills()))
+ .hasSize(2)
+ .anySatisfy(dir -> assertThat(dir).endsWith("nano-banana-pro"));
+ }
+ }
+
+ @Test
+ void emptyConstructorSkillsLeaveTheChatModelWithoutSkills() throws Exception {
+ // Skill sources are registered, so load_skill and bash exist in the plan; the chat model
+ // must still not pick them up when no skill is named.
+ ReActAgent agent = new ReActAgent(chatModel().build(), null, null, List.of());
+
+ try (ResourceCache cache = cacheFor(agent)) {
+ BaseChatModelSetup setup = openChatModel(cache);
+
+ assertThat(setup.getSkills()).isNull();
+ assertThat(setup.getSkillDiscoveryPrompt()).isNull();
+ assertThat(setup.getTools()).isEmpty();
+ }
+ }
+
+ private static ResourceDescriptor.Builder chatModel() {
+ return ResourceDescriptor.Builder.newBuilder(StubChatModelSetup.class.getName())
+ .addInitialArgument("connection", CONNECTION);
+ }
+
+ private static ResourceCache cacheFor(ReActAgent agent) throws Exception {
+ agent.addResource(
+ CONNECTION,
+ ResourceType.CHAT_MODEL_CONNECTION,
+ ResourceDescriptor.Builder.newBuilder(StubConnection.class.getName()).build());
+ agent.addResource("test_skills", ResourceType.SKILLS, Skills.fromLocalDir(SKILLS_DIR));
+ return new ResourceCache(new AgentPlan(agent).getResourceProviders());
+ }
+
+ private static BaseChatModelSetup openChatModel(ResourceCache cache) throws Exception {
+ return (BaseChatModelSetup) cache.getResource(CHAT_MODEL, ResourceType.CHAT_MODEL);
+ }
+
+ private static Tool toolNamed(BaseChatModelSetup setup, String name) {
+ return setup.getTools().stream()
+ .filter(tool -> tool.getName().equals(name))
+ .findFirst()
+ .orElseThrow();
+ }
+
+ @Test
+ void skillsObjectConstructorResolvesSourcesToSkillNames() throws Exception {
+ Skills skills = Skills.fromLocalDir(SKILLS_DIR);
+ ReActAgent agent = new ReActAgent(chatModel().build(), null, null, skills);
+
+ try (ResourceCache cache = cacheForSkillsObjectAgent(agent)) {
+ BaseChatModelSetup setup = openChatModel(cache);
+
+ assertThat(setup.getSkills()).containsExactlyInAnyOrder("github", "nano-banana-pro");
+ assertThat(setup.getSkillDiscoveryPrompt())
+ .contains("<name>github</name>", "<name>nano-banana-pro</name>");
+ assertThat(setup.getTools())
+ .extracting(Tool::getName)
+ .containsExactly(Skills.LOAD_SKILL_TOOL, Skills.BASH_TOOL);
+ }
+ }
+
+ @Test
+ void skillsObjectWithExplicitSkillsMergesBothAtRuntime() throws Exception {
+ Skills skills = Skills.fromLocalDir(SKILLS_DIR);
+ ResourceDescriptor chatModelDesc =
+ chatModel().addInitialArgument("skills", List.of("github")).build();
+ ReActAgent agent = new ReActAgent(chatModelDesc, null, null, skills);
+
+ try (ResourceCache cache = cacheForSkillsObjectAgent(agent)) {
+ BaseChatModelSetup setup = openChatModel(cache);
+
+ // Explicit skills come first, then resolved from sources. Both "github" and
+ // "nano-banana-pro" are present, with "github" deduplicated.
+ assertThat(setup.getSkills()).containsExactly("github", "nano-banana-pro");
+ }
+ }
+
+ @Test
+ void nullSkillsObjectProducesNoSkills() throws Exception {
+ ReActAgent agent = new ReActAgent(chatModel().build(), null, null, (Skills) null);
+
+ try (ResourceCache cache = cacheForSkillsObjectAgent(agent)) {
+ BaseChatModelSetup setup = openChatModel(cache);
+
+ assertThat(setup.getSkills()).isNull();
+ assertThat(setup.getSkillDiscoveryPrompt()).isNull();
+ assertThat(setup.getTools()).isEmpty();
+ }
+ }
+
+ private static ResourceCache cacheForSkillsObjectAgent(ReActAgent agent) throws Exception {
+ agent.addResource(
+ CONNECTION,
+ ResourceType.CHAT_MODEL_CONNECTION,
+ ResourceDescriptor.Builder.newBuilder(StubConnection.class.getName()).build());
+ return new ResourceCache(new AgentPlan(agent).getResourceProviders());
+ }
+}
diff --git a/runtime/src/test/java/org/apache/flink/agents/runtime/skill/SkillManagerTest.java b/runtime/src/test/java/org/apache/flink/agents/runtime/skill/SkillManagerTest.java
index 0dad4013c..50b80b202 100644
--- a/runtime/src/test/java/org/apache/flink/agents/runtime/skill/SkillManagerTest.java
+++ b/runtime/src/test/java/org/apache/flink/agents/runtime/skill/SkillManagerTest.java
@@ -639,4 +639,92 @@ class SkillManagerTest {
assertTrue(first.closed.get(), "displaced repo must still be closed");
assertTrue(second.closed.get(), "winning repo must be closed");
}
+
+ @Test
+ void getSkillNamesForSourcesReturnsNamesFromLoadedSpecs() {
+ FakeRepo repoA = new FakeRepo("alpha");
+ FakeRepo repoB = new FakeRepo("beta");
+ Map<String, SkillSourceHandler> handlers = new java.util.HashMap<>();
+ handlers.put("test-get-spec-a", (params, cl) -> repoA);
+ handlers.put("test-get-spec-b", (params, cl) -> repoB);
+
+ SkillSourceSpec specA = new SkillSourceSpec("test-get-spec-a", Map.of());
+ SkillSourceSpec specB = new SkillSourceSpec("test-get-spec-b", Map.of());
+ Skills config = new Skills(List.of(specA, specB));
+ SkillManager manager = new SkillManager(config, handlers);
+
+ assertEquals(List.of("alpha"), manager.getSkillNamesForSources(List.of(specA)));
+ assertEquals(List.of("beta"), manager.getSkillNamesForSources(List.of(specB)));
+ assertEquals(
+ List.of("alpha", "beta"), manager.getSkillNamesForSources(List.of(specA, specB)));
+ }
+
+ @Test
+ void getSkillNamesForSourcesPreservesSpecOrder() {
+ // Register the same scheme for both — each call creates a new FakeRepo with its own name.
+ AtomicInteger seq = new AtomicInteger();
+ FakeRepo repoA = new FakeRepo("alpha");
+ FakeRepo repoB = new FakeRepo("beta");
+ List<FakeRepo> ordered = List.of(repoA, repoB);
+ Map<String, SkillSourceHandler> handlers = new java.util.HashMap<>();
+ handlers.put("test-spec-order", (params, cl) -> ordered.get(seq.getAndIncrement()));
+
+ SkillSourceSpec specA = new SkillSourceSpec("test-spec-order", Map.of("order", "a"));
+ SkillSourceSpec specB = new SkillSourceSpec("test-spec-order", Map.of("order", "b"));
+ Skills config = new Skills(List.of(specA, specB));
+ SkillManager manager = new SkillManager(config, handlers);
+
+ // specB → specA: the result must follow the argument list order, not load order.
+ assertEquals(
+ List.of("beta", "alpha"), manager.getSkillNamesForSources(List.of(specB, specA)));
+ }
+
+ @Test
+ void getSkillNamesForSourcesReturnsEmptyForUnknownSpecs() {
+ Skills config =
+ Skills.fromLocalDir(
+ Path.of("src/test/resources/skills").toAbsolutePath().toString());
+ SkillManager manager = new SkillManager(config);
+
+ List<String> result =
+ manager.getSkillNamesForSources(
+ List.of(new SkillSourceSpec("local", Map.of("path", "/nonexistent"))));
+ assertTrue(result.isEmpty());
+ }
+
+ @Test
+ void getSkillNamesForSourcesReturnsAllNamesForMultiSkillRepo() {
+ FakeRepo multi = new FakeRepo("alpha");
+ // Override getSkills to return two skills from one repo.
+ AgentSkill skillA = new AgentSkill("alpha", "a-desc", "a-body", null, null, null);
+ AgentSkill skillB = new AgentSkill("beta", "b-desc", "b-body", null, null, null);
+ SkillRepository multiSkillRepo =
+ new SkillRepository() {
+ @Override
+ public AgentSkill getSkill(String name) {
+ return "alpha".equals(name) ? skillA : "beta".equals(name) ? skillB : null;
+ }
+
+ @Override
+ public List<AgentSkill> getSkills() {
+ return List.of(skillA, skillB);
+ }
+
+ @Override
+ public Map<String, String> getResources(String name) {
+ return Map.of();
+ }
+
+ @Override
+ public void close() {}
+ };
+ Map<String, SkillSourceHandler> handlers = new java.util.HashMap<>();
+ handlers.put("test-multi-skill-repo", (params, cl) -> multiSkillRepo);
+
+ SkillSourceSpec spec = new SkillSourceSpec("test-multi-skill-repo", Map.of());
+ Skills config = new Skills(List.of(spec));
+ SkillManager manager = new SkillManager(config, handlers);
+
+ assertEquals(List.of("alpha", "beta"), manager.getSkillNamesForSources(List.of(spec)));
+ }
}