gnodet-bot commented on code in PR #30671:
URL: https://github.com/apache/camel/pull/30671#discussion_r4667010280


##########
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/RuntimeAccess.java:
##########
@@ -0,0 +1,112 @@
+/*
+ * 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.camel.dsl.jbang.core.common;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * Framework-neutral access to running Camel runtimes.
+ * <p>
+ * Implementations own the transport and the mapping from an opaque {@link 
RuntimeTarget} to that transport. The default
+ * implementation is local file-based IPC; a remote implementation can use the 
same contract without making the JBang
+ * core depend on MCP, CDI, Quarkus, Spring Boot, or a particular network 
protocol.
+ *
+ */
+public interface RuntimeAccess {
+

Review Comment:
   ℹ️ **Missing `@since` tag** — `RuntimeAccess` is a new public API type. 
Please add `@since` (e.g. `@since 4.11`) to the type Javadoc.



##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RemoteRuntimeEntry.java:
##########
@@ -0,0 +1,204 @@
+/*
+ * 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.camel.dsl.jbang.core.commands.mcp;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
+/** Stable server-side identity and bounded last-known state for one remote 
integration. */
+final class RemoteRuntimeEntry {
+
+    private final String ownerId;
+    private final String executionId;
+    private final int maxSnapshotChars;
+    private final int maxRetainedMessages;
+    private final Map<String, JsonObject> snapshots = new LinkedHashMap<>();
+    private final LinkedHashMap<Long, JsonObject> traces = new 
LinkedHashMap<>();
+    private final LinkedHashMap<Long, JsonObject> received = new 
LinkedHashMap<>();
+
+    private volatile JsonObject hello;
+    private volatile RemoteRuntimeConnection connection;
+    private volatile long lastSeen = System.currentTimeMillis();
+
+    RemoteRuntimeEntry(String ownerId, String executionId, int 
maxSnapshotChars, int maxRetainedMessages) {
+        this.ownerId = ownerId;
+        this.executionId = executionId;
+        this.maxSnapshotChars = maxSnapshotChars;
+        this.maxRetainedMessages = maxRetainedMessages;
+    }
+
+    String ownerId() {
+        return ownerId;
+    }
+
+    String executionId() {
+        return executionId;
+    }
+
+    long lastSeen() {
+        return lastSeen;
+    }
+
+    boolean isConnected() {
+        RemoteRuntimeConnection current = connection;
+        return current != null && current.isOpen();
+    }
+
+    boolean isReady() {
+        RemoteRuntimeConnection current = connection;
+        return current != null && current.isReady();
+    }
+
+    synchronized RemoteRuntimeConnection attach(RemoteRuntimeConnection next) {
+        RemoteRuntimeConnection previous = connection;
+        connection = next;
+        touch();
+        return previous;
+    }
+
+    synchronized boolean detach(RemoteRuntimeConnection expected) {
+        if (connection != expected) {
+            return false;
+        }
+        connection = null;
+        touch();
+        return true;
+    }
+
+    synchronized boolean isCurrent(RemoteRuntimeConnection candidate) {
+        return connection == candidate;
+    }
+
+    synchronized RemoteRuntimeConnection expireConnectionIfIdle(long now, long 
timeoutMillis) {
+        RemoteRuntimeConnection current = connection;
+        if (current != null && now - lastSeen > timeoutMillis) {
+            connection = null;
+            lastSeen = now;
+            return current;
+        }
+        return null;
+    }
+
+    synchronized void touch() {
+        lastSeen = System.currentTimeMillis();
+    }
+
+    /** Updates integration metadata; each connection independently enforces 
one hello frame. */
+    synchronized void updateHello(JsonObject frame) {
+        Long previousPid = runtimePid(hello);
+        Long newPid = runtimePid(frame);
+        // executionId survives an integration restart, but the connector's 
per-process UIDs restart too.
+        // Clear process-scoped snapshots only when the runtime PID proves a 
new process took over this identity.
+        if (previousPid != null && newPid != null && 
!previousPid.equals(newPid)) {
+            snapshots.clear();
+            traces.clear();
+            received.clear();
+        }
+        hello = new JsonObject(frame);
+        touch();
+    }
+
+    private static Long runtimePid(JsonObject hello) {
+        if (hello == null || !(hello.get("runtime") instanceof JsonObject 
runtime)) {
+            return null;
+        }
+        Object pid = runtime.get("pid");
+        return pid instanceof Number number ? number.longValue() : null;
+    }
+
+    synchronized void updateSnapshot(String kind, JsonObject data) {
+        if (data == null) {
+            throw new IllegalArgumentException("Snapshot data is required");
+        }
+        String collectionKey;
+        LinkedHashMap<Long, JsonObject> retained;
+        if ("trace".equals(kind)) {
+            collectionKey = "traces";
+            retained = traces;
+        } else if ("receive".equals(kind)) {
+            collectionKey = "messages";
+            retained = received;
+        } else {
+            String serialized = data.toJson();
+            if (serialized.length() > maxSnapshotChars) {
+                throw new IllegalArgumentException("Snapshot exceeds the 
configured size limit");
+            }
+            snapshots.put(kind, new JsonObject(data));
+            touch();
+            return;
+        }
+
+        List<JsonObject> batch = data.getCollection(collectionKey);
+        if (batch != null) {
+            for (JsonObject message : batch) {
+                Object uidValue = message.get("uid");
+                if (!(uidValue instanceof Number uid)) {
+                    throw new IllegalArgumentException("A " + kind + " message 
is missing its numeric uid");
+                }
+                retained.put(uid.longValue(), new JsonObject(message));
+                while (retained.size() > maxRetainedMessages) {
+                    retained.remove(retained.keySet().iterator().next());
+                }
+            }
+        }
+
+        JsonObject merged = new JsonObject(data);
+        merged.put(collectionKey, new JsonArray(new 
ArrayList<>(retained.values())));
+        while (!retained.isEmpty() && merged.toJson().length() > 
maxSnapshotChars) {
+            retained.remove(retained.keySet().iterator().next());
+            merged.put(collectionKey, new JsonArray(new 
ArrayList<>(retained.values())));
+        }
+        if (merged.toJson().length() > maxSnapshotChars) {
+            throw new IllegalArgumentException("Snapshot metadata exceeds the 
configured size limit");
+        }
+        snapshots.put(kind, merged);
+        touch();
+    }
+
+    synchronized JsonObject snapshot(String kind) {
+        JsonObject value = snapshots.get(kind);
+        return value != null ? new JsonObject(value) : null;
+    }
+
+    synchronized Map<String, JsonObject> snapshots() {
+        Map<String, JsonObject> copy = new LinkedHashMap<>();
+        snapshots.forEach((key, value) -> copy.put(key, new 
JsonObject(value)));
+        return Map.copyOf(copy);
+    }
+
+    JsonObject hello() {
+        JsonObject value = hello;
+        return value != null ? new JsonObject(value) : null;
+    }
+
+    synchronized RemoteRuntimeConnection connectionForShutdown() {
+        return connection;
+    }
+
+    JsonObject executeAction(JsonObject action, long timeoutMillis) throws 
java.io.IOException {
+        RemoteRuntimeConnection current = connection;

Review Comment:
   ⚠️ **Unsynchronized volatile read + TOCTOU** — `connection` is read into 
`current` without `synchronized`, while `attach()` / `detach()` / 
`expireConnectionIfIdle()` all synchronize on `this`. Another thread can 
`detach()` and close the connection between the `current == null` guard (line 
199) and the `current.executeAction()` call (line 202). Consider synchronizing 
`executeAction()` or at minimum wrapping the read + null-check in a 
`synchronized` block. Note: `connectionForShutdown()` is already synchronized, 
so the precedent is there.



##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RemoteRuntimeRegistry.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.camel.dsl.jbang.core.commands.mcp;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import jakarta.annotation.PreDestroy;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import org.jboss.logging.Logger;
+
+/**
+ * Registry of remote integrations. Identity is the authenticated owner 
namespace plus executionId, never the remote
+ * PID. Disconnected entries retain bounded last-known snapshots for a 
reconnect window.
+ */
+@ApplicationScoped
+public class RemoteRuntimeRegistry {
+
+    private static final Logger LOG = 
Logger.getLogger(RemoteRuntimeRegistry.class);
+    private static final long RESERVATION_TTL_MILLIS = 30_000L;
+    private static final int DEFAULT_MAX_CONNECTIONS = 16;
+    private static final int DEFAULT_MAX_RETAINED_RUNTIMES = 32;
+    private static final long DEFAULT_RETENTION_MILLIS = 3_600_000L;
+    private static final long DEFAULT_HEARTBEAT_TIMEOUT_MILLIS = 90_000L;
+
+    @Inject
+    RemoteRuntimeConfig config;
+
+    private final ConcurrentMap<Key, RemoteRuntimeEntry> entries = new 
ConcurrentHashMap<>();
+    private final Map<String, Reservation> reservations = new HashMap<>();
+
+    /** Reserves a capacity slot before the HTTP upgrade completes. Abandoned 
reservations expire automatically. */
+    synchronized String reserve(String ownerId, String executionId) {
+        cleanup();
+        Key key = new Key(ownerId, executionId);
+        Set<Key> occupied = new HashSet<>();
+        entries.forEach((entryKey, entry) -> {
+            if (entry.isConnected()) {
+                occupied.add(entryKey);
+            }
+        });
+        reservations.values().forEach(reservation -> 
occupied.add(reservation.key()));
+        // Only one pending upgrade may claim a given logical runtime at a 
time. An already-connected key may
+        // reconnect once, replacing its previous socket after the new 
handshake is accepted.
+        boolean keyReserved = 
reservations.values().stream().anyMatch(reservation -> 
reservation.key().equals(key));
+        if (keyReserved) {
+            return null;
+        }
+        RemoteRuntimeEntry existing = entries.get(key);
+        boolean replacingConnection = existing != null && 
existing.isConnected();
+        if (!replacingConnection && occupied.size() >= maxConnections()) {
+            return null;
+        }
+        if (existing == null && entries.size() >= maxRetainedRuntimes()) {
+            evictOldestDisconnected();
+            if (entries.size() >= maxRetainedRuntimes()) {
+                return null;
+            }
+        }
+        String id = UUID.randomUUID().toString();
+        reservations.put(id, new Reservation(key, System.currentTimeMillis() + 
RESERVATION_TTL_MILLIS));
+        return id;
+    }
+
+    /** Claims a pre-upgrade reservation and attaches the newly opened socket 
to the stable runtime entry. */
+    synchronized RemoteRuntimeEntry claim(String reservationId, 
RemoteRuntimeConnection connection) {
+        cleanup();
+        Reservation reservation = reservations.remove(reservationId);
+        if (reservation == null) {
+            throw new IllegalStateException("The WebSocket connection 
reservation is missing or expired");
+        }
+        Key key = reservation.key();
+        RemoteRuntimeEntry entry = entries.computeIfAbsent(key, k -> new 
RemoteRuntimeEntry(
+                k.ownerId(), k.executionId(), maxSnapshotChars(), 
maxRetainedMessages()));
+        RemoteRuntimeConnection previous = entry.attach(connection);
+        connection.attach(entry);
+        if (previous != null && previous != connection) {
+            previous.closeReplaced();
+            LOG.debugf("Replaced an older WebSocket session for remote 
integration %s", key.executionId());
+        }
+        return entry;
+    }
+
+    synchronized void cancelReservation(String reservationId) {
+        if (reservationId != null) {
+            reservations.remove(reservationId);
+        }
+    }
+
+    /**
+     * Detaches only the session that is still current; a late close from a 
replaced socket cannot remove its successor.
+     */
+    void disconnect(RemoteRuntimeEntry entry, RemoteRuntimeConnection 
connection) {
+        if (entry != null && connection != null && entry.detach(connection)) {
+            connection.markClosed("Remote integration disconnected");
+            LOG.debugf("Remote integration disconnected: %s", 
entry.executionId());
+        }
+    }
+
+    RemoteRuntimeEntry find(String ownerId, String executionId) {
+        cleanup();

Review Comment:
   ℹ️ **Locking clarification** — `find()`, `list()`, and `connectedCount()` 
call `synchronized cleanup()` (which protects the `reservations` `HashMap`), 
then operate on `entries` (`ConcurrentHashMap`) without a lock. This is correct 
since `ConcurrentHashMap` provides thread-safe reads and weakly-consistent 
iteration. A short Javadoc comment explaining the two-tier strategy 
(synchronized for `reservations`, concurrent for `entries`) would help future 
maintainers avoid mistakenly adding a lock here or assuming full atomicity 
across the two collections.



##########
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/RuntimeTarget.java:
##########
@@ -0,0 +1,59 @@
+/*
+ * 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.camel.dsl.jbang.core.common;
+
+/**
+ * An opaque reference to a running Camel runtime.
+ * <p>
+ * The {@code id} is the identity used by a {@link RuntimeAccess} 
implementation. It is not a PID and must not be
+ * derived from one by callers. A PID is optional metadata: it is available 
for local processes, but a remote runtime
+ * need not expose one, and PIDs are not globally unique.
+ *
+ * @param id          stable identifier within the runtime access scope
+ * @param pid         operating-system PID when the runtime is local or 
otherwise exposes one; may be {@code null}
+ * @param name        integration name; may be {@code null}
+ * @param contextName Camel context name; may be {@code null}
+ * @param transport   access transport such as {@code file} or {@code 
websocket}; may be {@code null}
+ */
+public record RuntimeTarget(String id, Long pid, String name, String 
contextName, String transport) {
+

Review Comment:
   ℹ️ **Missing `@since` tag** — `RuntimeTarget` is a new public API type. 
Please add `@since` to the type Javadoc.



##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RemoteRuntimeConfig.java:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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.camel.dsl.jbang.core.commands.mcp;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import jakarta.enterprise.context.ApplicationScoped;
+
+import org.eclipse.microprofile.config.inject.ConfigProperty;
+
+/** Configuration for the opt-in remote integration endpoint. */
+@ApplicationScoped
+public class RemoteRuntimeConfig {
+
+    @ConfigProperty(name = "camel.mcp.remote.enabled", defaultValue = "false")
+    boolean enabled;
+
+    @ConfigProperty(name = "camel.mcp.remote.token", defaultValue = "")
+    String token;
+
+    @ConfigProperty(name = "camel.mcp.remote.max-connections", defaultValue = 
"16")
+    int maxConnections;
+
+    @ConfigProperty(name = "camel.mcp.remote.max-retained-runtimes", 
defaultValue = "32")
+    int maxRetainedRuntimes;
+
+    @ConfigProperty(name = "camel.mcp.remote.retention-ms", defaultValue = 
"3600000")
+    long retentionMillis;
+
+    @ConfigProperty(name = "camel.mcp.remote.heartbeat-timeout-ms", 
defaultValue = "90000")
+    long heartbeatTimeoutMillis;
+
+    @ConfigProperty(name = "camel.mcp.remote.max-frame-chars", defaultValue = 
"16777216")
+    int maxFrameChars;
+
+    @ConfigProperty(name = "camel.mcp.remote.max-snapshot-chars", defaultValue 
= "1048576")
+    int maxSnapshotChars;
+
+    @ConfigProperty(name = "camel.mcp.remote.max-retained-messages", 
defaultValue = "500")
+    int maxRetainedMessages;
+
+    public boolean isEnabled() {
+        return enabled;
+    }
+
+    public boolean isTokenConfigured() {
+        return token != null && !token.isBlank();
+    }
+
+    /** Constant-time comparison of the configured shared bearer token. */
+    public boolean isAuthorized(String authorization) {
+        if (!isTokenConfigured() || authorization == null) {
+            return false;
+        }
+        byte[] expected = ("Bearer " + token).getBytes(StandardCharsets.UTF_8);
+        byte[] supplied = authorization.getBytes(StandardCharsets.UTF_8);
+        return MessageDigest.isEqual(expected, supplied);
+    }
+
+    /** A non-secret namespace for the one configured authentication 
principal. */
+    public String ownerId() {
+        if (!isTokenConfigured()) {

Review Comment:
   ℹ️ **SHA-256 recomputed on every call** — `ownerId()` creates a new 
`MessageDigest` and hashes `token` on every invocation. Since `ownerId()` 
appears in hot paths (`find()`, `list()`, etc.) and the token is immutable 
after startup, caching the computed value as a `private volatile String 
ownerIdCache` field (computed lazily) would avoid repeated cryptographic work.



##########
dsl/camel-jbang/camel-jbang-mcp/pom.xml:
##########
@@ -185,6 +190,18 @@
             <artifactId>camel-chaos</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.apache.camel</groupId>
+            <artifactId>camel-cli-connector</artifactId>

Review Comment:
   ⚠️ **Dependency scope missing** — `camel-cli-connector` is added without 
`<scope>`. It defaults to `compile`. Since its only production usage is 
`RepeatedSend.interval()` via `RemoteRuntimeAccess`, this may be intentional; 
but if the dependency is needed only at runtime, `<scope>runtime</scope>` would 
be more explicit.



##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RemoteRuntimeAccess.java:
##########
@@ -0,0 +1,450 @@
+/*
+ * 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.camel.dsl.jbang.core.commands.mcp;
+
+import java.io.IOException;
+import java.net.SocketTimeoutException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.StringJoiner;
+import java.util.regex.Pattern;
+
+import org.apache.camel.cli.connector.RepeatedSend;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolExecutionException;
+import org.apache.camel.dsl.jbang.core.common.CliException;
+import org.apache.camel.dsl.jbang.core.common.LocalRuntimeAccess;
+import org.apache.camel.dsl.jbang.core.common.RuntimeAccess;
+import org.apache.camel.dsl.jbang.core.common.RuntimeHelper;
+import org.apache.camel.dsl.jbang.core.common.RuntimeTarget;
+import org.apache.camel.util.FileUtil;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+
+/**
+ * Runtime access used by the MCP server. It combines the existing local 
file-IPC runtimes with remote WebSocket
+ * runtimes authenticated for this server's configured owner. Remote identity 
is always the connector executionId; a
+ * remote operating-system PID is deliberately not used as an identity or 
exposed as a local PID.
+ */
+final class RemoteRuntimeAccess implements RuntimeAccess {
+
+    private static final String REMOTE_PREFIX = "websocket:";
+
+    private final RuntimeAccess local;
+    private final RemoteRuntimeRegistry registry;
+    private final RemoteRuntimeConfig config;
+
+    RemoteRuntimeAccess(RemoteRuntimeRegistry registry, RemoteRuntimeConfig 
config) {
+        this(LocalRuntimeAccess.INSTANCE, registry, config);
+    }
+
+    RemoteRuntimeAccess(RuntimeAccess local, RemoteRuntimeRegistry registry, 
RemoteRuntimeConfig config) {
+        this.local = local;
+        this.registry = registry;
+        this.config = config;
+    }
+
+    @Override
+    public List<RuntimeTarget> discoverProcesses() {
+        List<RuntimeTarget> targets = new 
ArrayList<>(local.discoverProcesses());
+        if (remoteEnabled()) {
+            for (RemoteRuntimeEntry entry : registry.list(config.ownerId())) {
+                // Do not offer an integration until its hello has completed, 
or after its socket has gone away.
+                if (entry.isReady()) {
+                    targets.add(toTarget(entry));
+                }
+            }
+        }
+        targets.sort(Comparator.comparing(RuntimeTarget::displayName, 
String.CASE_INSENSITIVE_ORDER)
+                .thenComparing(RuntimeTarget::id));
+        return List.copyOf(targets);
+    }
+
+    @Override
+    public RuntimeTarget findProcess(String selector) {
+        List<RuntimeTarget> targets = discoverProcesses();
+        if (selector == null || selector.isBlank()) {
+            return targets.size() == 1 ? targets.get(0) : null;
+        }
+
+        String value = selector.trim();
+        List<RuntimeTarget> exact = targets.stream().filter(target -> 
matchesExact(target, value)).toList();
+        if (exact.size() == 1) {
+            return exact.get(0);
+        }
+        if (!exact.isEmpty()) {
+            return null;
+        }
+        // Numeric selectors are PIDs; a remote executionId is selected 
through its explicit runtime ID.
+        if (value.matches("\\d+")) {
+            return null;
+        }
+
+        List<RuntimeTarget> partial = targets.stream().filter(target -> 
matchesName(target.name(), value)
+                || !"CamelJBang".equals(target.contextName()) && 
matchesName(target.contextName(), value)
+                || matchesName(target.id(), value)).toList();
+        return partial.size() == 1 ? partial.get(0) : null;
+    }
+
+    private static boolean matchesExact(RuntimeTarget target, String value) {
+        if (target.id().equals(value) || !value.matches("\\d+") && 
target.id().equals(REMOTE_PREFIX + value)) {
+            return true;
+        }
+        if (target.pid() != null && Long.toString(target.pid()).equals(value)) 
{
+            return true;
+        }
+        String exactName = value.endsWith("!") ? value.substring(0, 
value.length() - 1) : value;
+        return exactName(target.name(), exactName)
+                || !"CamelJBang".equals(target.contextName()) && 
exactName(target.contextName(), exactName);
+    }
+
+    private static boolean exactName(String candidate, String selector) {
+        if (candidate == null) {
+            return false;
+        }
+        String fileName = FileUtil.onlyName(candidate);
+        return candidate.equalsIgnoreCase(selector) || fileName != null && 
fileName.equalsIgnoreCase(selector);
+    }
+
+    private static boolean matchesName(String candidate, String selector) {
+        if (candidate == null || selector.endsWith("!")) {
+            return false;
+        }
+        // Match ProcessFinder's name semantics: match the file name too; a 
plain name is a prefix.
+        String fileName = FileUtil.onlyName(candidate);
+        return matchesPattern(candidate, selector) || fileName != null && 
matchesPattern(fileName, selector);
+    }
+
+    private static boolean matchesPattern(String candidate, String selector) {
+        String pattern = selector.endsWith("*") ? selector : selector + "*";
+        StringBuilder regex = new StringBuilder("(?i)^");
+        for (int i = 0; i < pattern.length(); i++) {
+            char ch = pattern.charAt(i);
+            if (ch == '*') {
+                regex.append(".*");
+            } else if (ch == '?') {
+                regex.append('.');
+            } else {
+                regex.append(Pattern.quote(String.valueOf(ch)));
+            }
+        }
+        regex.append('$');
+        return candidate.matches(regex.toString());
+    }
+
+    @Override
+    public RuntimeTarget findChaosProcess() {
+        List<RuntimeTarget> targets = discoverProcesses();
+        if (targets.size() == 1) {
+            return targets.get(0);
+        }
+        if (targets.isEmpty()) {
+            throw CliException.usage(
+                    "No running Camel integrations: start one with chaos 
switched on (camel run --chaos)");
+        }
+        List<RuntimeTarget> chaosTargets = new ArrayList<>();
+        for (RuntimeTarget target : targets) {
+            if (hasChaos(readStatus(target))) {
+                chaosTargets.add(target);
+            }
+        }
+        if (chaosTargets.size() == 1) {
+            return chaosTargets.get(0);
+        }
+        StringJoiner available = new StringJoiner(", ");
+        for (RuntimeTarget target : targets) {
+            available.add(target.displayName() + " (" + target.identityLabel() 
+ ", "
+                          + (chaosTargets.contains(target) ? "chaos on" : 
"chaos off") + ")");
+        }
+        throw CliException.usage(targets.size() + " Camel integrations are 
running and "
+                                 + (chaosTargets.isEmpty() ? "none has" : 
chaosTargets.size() + " have")
+                                 + " chaos switched on: " + available + ". 
Give the name, PID, or runtime ID of one.");
+    }
+
+    private static boolean hasChaos(JsonObject status) {
+        return status != null && status.get("chaos") instanceof JsonObject 
chaos
+                && chaos.getBooleanOrDefault("enabled", false);
+    }
+
+    @Override
+    public RuntimeTarget targetForPid(long pid) {
+        return local.targetForPid(pid);
+    }
+
+    @Override
+    public JsonObject readStatus(RuntimeTarget target) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        return entry != null ? copySnapshot(entry, "status") : 
local.readStatus(target);
+    }
+
+    @Override
+    public ActionResult sendAction(RuntimeTarget target, JsonObject request, 
long timeoutMs) throws IOException {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        if (entry == null) {
+            return local.sendAction(target, request, timeoutMs);
+        }
+        try {
+            JsonObject frame = entry.executeAction(request, timeoutMs);
+            if (!Boolean.TRUE.equals(frame.get("ok"))) {
+                return new ActionResult(ActionStatus.ERROR, 
frame.getString("error"), frame.getString("reason"));
+            }
+            return new ActionResult(ActionStatus.OK, null, 
frame.getString("reason"));
+        } catch (SocketTimeoutException e) {
+            return new ActionResult(ActionStatus.TIMEOUT, e.getMessage(), 
null);
+        }
+    }
+
+    @Override
+    public String executeActionText(RuntimeTarget target, JsonObject request, 
long timeoutMs) throws IOException {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        if (entry == null) {
+            return local.executeActionText(target, request, timeoutMs);
+        }
+        final JsonObject frame;
+        try {
+            frame = entry.executeAction(request, timeoutMs);
+        } catch (SocketTimeoutException e) {
+            return null;
+        }
+        if (!Boolean.TRUE.equals(frame.get("ok"))) {
+            JsonObject failed = new JsonObject();
+            failed.put("status", "failed");
+            failed.put("error", frame.getString("error") != null ? 
frame.getString("error") : "Remote action failed");
+            return failed.toJson();
+        }
+        Object result = frame.get("result");
+        if (result instanceof JsonObject json) {
+            return json.toJson();
+        }
+        return result != null ? result.toString() : "{}";
+    }
+
+    @Override
+    public JsonObject readErrorFile(RuntimeTarget target) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        return entry != null ? copySnapshot(entry, "error") : 
local.readErrorFile(target);
+    }
+
+    @Override
+    public JsonObject readHistoryFile(RuntimeTarget target) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        return entry != null ? copySnapshot(entry, "history") : 
local.readHistoryFile(target);
+    }
+
+    @Override
+    public String receiveCursor(RuntimeTarget target) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        if (entry == null) {
+            return local.receiveCursor(target);
+        }
+        JsonObject receive = copySnapshot(entry, "receive");
+        long highest = 0;
+        if (receive != null) {
+            List<JsonObject> messages = receive.getCollection("messages");
+            if (messages != null) {
+                for (JsonObject message : messages) {
+                    Object uid = message.get("uid");
+                    if (uid instanceof Number number) {
+                        highest = Math.max(highest, number.longValue());
+                    }
+                }
+            }
+        }
+        return Long.toString(highest);
+    }
+
+    @Override
+    public List<JsonObject> readReceivedMessages(RuntimeTarget target, String 
cursor) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        if (entry == null) {
+            return local.readReceivedMessages(target, cursor);
+        }
+        final long after;
+        try {
+            after = cursor == null || cursor.isBlank() ? 0 : 
Long.parseLong(cursor);
+        } catch (NumberFormatException e) {
+            throw new IllegalArgumentException("Invalid remote receive cursor: 
" + cursor, e);
+        }
+        JsonObject receive = copySnapshot(entry, "receive");
+        if (receive == null) {
+            return List.of();
+        }
+        List<JsonObject> messages = receive.getCollection("messages");
+        if (messages == null || messages.isEmpty()) {
+            return List.of();
+        }
+        List<JsonObject> result = new ArrayList<>();
+        for (JsonObject message : messages) {
+            Object uid = message.get("uid");
+            if (uid instanceof Number number && number.longValue() > after) {
+                result.add(new JsonObject(message));
+            }
+        }
+        return List.copyOf(result);
+    }
+
+    @Override
+    public String stopApplication(RuntimeTarget target) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        if (entry == null) {
+            return local.stopApplication(target);
+        }
+        JsonObject request = new JsonObject();
+        request.put("action", "stop");
+        try {
+            JsonObject frame = entry.executeAction(request, 10_000L);
+            if (!Boolean.TRUE.equals(frame.get("ok"))) {
+                return frame.getString("error");
+            }
+            Object result = frame.get("result");
+            return result != null ? result.toString() : "Application stopping";
+        } catch (IOException e) {
+            throw new ToolExecutionException(
+                    "Cannot stop remote Camel integration " + target.id() + ": 
" + e.getMessage());
+        }
+    }
+
+    @Override
+    public JsonObject sendMessage(
+            RuntimeTarget target, String endpoint, String body, String 
headers, int repeat, String interval) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        if (entry == null) {
+            return local.sendMessage(target, endpoint, body, headers, repeat, 
interval);
+        }
+        JsonObject request = new JsonObject();
+        request.put("action", "send");
+        request.put("endpoint", endpoint);
+        if (body != null) {
+            request.put("body", body);
+        }
+        if (headers != null) {
+            request.put("headers", RuntimeHelper.parseKeyValues(headers, 
"Header"));
+        }
+        if (repeat > 0) {
+            request.put("repeat", repeat);
+        }
+        long[] pause = RepeatedSend.interval(interval);
+        if (pause[1] > 0) {
+            request.put("interval", pause[0]);
+            if (pause[1] > pause[0]) {
+                request.put("intervalMax", pause[1]);
+            }
+        }
+        return executeJsonAction(entry, request, 30_000L);
+    }
+
+    @Override
+    public JsonObject executeSqlQuery(
+            RuntimeTarget target, String sql, String datasource, int maxRows, 
int queryTimeout) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        if (entry == null) {
+            return local.executeSqlQuery(target, sql, datasource, maxRows, 
queryTimeout);
+        }
+        JsonObject request = new JsonObject();
+        request.put("action", "sql-query");
+        request.put("sql", sql);
+        if (datasource != null) {
+            request.put("datasource", datasource);
+        }
+        request.put("maxRows", maxRows);
+        request.put("queryTimeout", queryTimeout);
+        return executeJsonAction(entry, request, (queryTimeout + 10L) * 1000L);
+    }
+
+    private JsonObject executeJsonAction(RemoteRuntimeEntry entry, JsonObject 
request, long timeoutMs) {
+        try {
+            JsonObject frame = entry.executeAction(request, timeoutMs);
+            if (!Boolean.TRUE.equals(frame.get("ok"))) {
+                JsonObject failed = new JsonObject();
+                failed.put("status", "failed");
+                failed.put("error", frame.getString("error") != null
+                        ? frame.getString("error") : "Remote action failed");
+                return failed;
+            }
+            Object result = frame.get("result");
+            if (result instanceof JsonObject json) {
+                return json;
+            }
+            if (result != null) {
+                try {
+                    Object parsed = Jsoner.deserialize(result.toString());
+                    if (parsed instanceof JsonObject json) {
+                        return json;
+                    }
+                } catch (Exception e) {
+                    // Preserve plain-text action results in the same shape as 
local file IPC.
+                }
+                JsonObject wrapper = new JsonObject();
+                wrapper.put("result", result);
+                return wrapper;
+            }
+            return new JsonObject();
+        } catch (IOException e) {
+            throw new ToolExecutionException("Remote Camel integration is 
unavailable: " + e.getMessage());
+        }
+    }
+
+    @Override
+    public String runtimeVersion(RuntimeTarget target) {
+        RemoteRuntimeEntry entry = remoteEntry(target);
+        if (entry == null) {
+            return local.runtimeVersion(target);
+        }
+        JsonObject hello = entry.hello();
+        return hello != null ? hello.getString("camelVersion") : null;
+    }
+
+    private static JsonObject copySnapshot(RemoteRuntimeEntry entry, String 
kind) {
+        JsonObject snapshot = entry.snapshot(kind);

Review Comment:
   ℹ️ **Double copy in `copySnapshot()`** — `entry.snapshot(kind)` already 
returns `new JsonObject(value)` (a defensive shallow copy under the monitor). 
`copySnapshot()` then calls `Jsoner.deserialize(snapshot.toJson(), ...)` for a 
full JSON round-trip deep copy. The first shallow copy appears redundant since 
it is immediately serialized and re-parsed. If the deep copy in 
`copySnapshot()` is the intended isolation mechanism, `snapshot(kind)` could 
return the internal value directly for this call path. If both copies are 
intentional, a comment explaining why would help.



##########
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/LocalRuntimeAccess.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.camel.dsl.jbang.core.common;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+
+/**
+ * The existing local runtime implementation, using the Camel JBang file-based 
IPC protocol.
+ * <p>
+ * This adapter deliberately preserves the existing {@link RuntimeHelper} and 
{@link ActionClient} behaviour. It is
+ * stateless and safe to share between tool contexts.
+ *
+ */
+public final class LocalRuntimeAccess implements RuntimeAccess {
+

Review Comment:
   ℹ️ **Missing `@since` tag** — `LocalRuntimeAccess` is a new public class. 
Please add `@since` to the type Javadoc.



##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RemoteRuntimeConnection.java:
##########
@@ -0,0 +1,240 @@
+/*
+ * 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.camel.dsl.jbang.core.commands.mcp;
+
+import java.io.IOException;
+import java.net.SocketTimeoutException;
+import java.time.Duration;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import io.quarkus.websockets.next.WebSocketConnection;
+import org.apache.camel.util.json.JsonObject;
+import org.jboss.logging.Logger;
+
+/** One WebSocket session to an integration. The entry survives reconnects; 
this session does not. */
+final class RemoteRuntimeConnection {
+
+    private static final Logger LOG = 
Logger.getLogger(RemoteRuntimeConnection.class);
+    private static final int MAX_PENDING_ACTIONS = 64;
+    private static final int MAX_HELLO_CHARS = 64 * 1024;
+    private static final long SEND_TIMEOUT_SECONDS = 10;
+    private static final Set<String> SNAPSHOT_KINDS
+            = Set.of("status", "trace", "receive", "debug", "history", 
"error", "timeline");
+
+    private final WebSocketConnection socket;
+    private final RemoteRuntimeConfig config;
+    private final ConcurrentHashMap<String, CompletableFuture<JsonObject>> 
pending = new ConcurrentHashMap<>();
+    private final Semaphore actionSlots = new Semaphore(MAX_PENDING_ACTIONS);
+    private final AtomicBoolean closed = new AtomicBoolean();
+    private volatile RemoteRuntimeEntry entry;
+    private volatile boolean helloReceived;
+
+    RemoteRuntimeConnection(WebSocketConnection socket, RemoteRuntimeConfig 
config) {
+        this.socket = socket;
+        this.config = config;
+    }
+
+    void attach(RemoteRuntimeEntry entry) {
+        this.entry = entry;
+    }
+
+    boolean isOpen() {
+        return !closed.get() && socket.isOpen();
+    }
+
+    boolean isReady() {
+        return isOpen() && helloReceived;
+    }
+
+    void touch() {
+        RemoteRuntimeEntry current = entry;
+        if (current != null) {
+            current.touch();
+        }
+    }
+
+    void acceptText(String text) {
+        if (text == null || text.length() > config.maxFrameChars()) {
+            throw new IllegalArgumentException("WebSocket frame exceeds the 
configured size limit");
+        }
+        JsonObject frame = CliConnectorProtocol.parseFrame(text);
+        String type = frame.getString("type");
+        RemoteRuntimeEntry current = entry;
+        if (current == null) {
+            throw new IllegalStateException("WebSocket session is not 
registered");
+        }
+        if (!current.isCurrent(this)) {
+            throw new IllegalStateException("This WebSocket session has been 
replaced");
+        }
+        switch (type) {
+            case "hello" -> {
+                if (text.length() > MAX_HELLO_CHARS) {
+                    throw new IllegalArgumentException("The hello frame 
exceeds the configured size limit");
+                }
+                if (helloReceived) {
+                    throw new IllegalArgumentException("Duplicate hello 
frame");
+                }
+                requireText(frame, "camelVersion");
+                requireText(frame, "name");
+                requireText(frame, "transport");
+                if (!(frame.get("runtime") instanceof JsonObject)) {
+                    throw new IllegalArgumentException("The hello frame 
requires a runtime object");
+                }
+                current.updateHello(frame);
+                helloReceived = true;
+            }
+            case "snapshot" -> {
+                requireHello();
+                String kind = frame.getString("kind");
+                if (!SNAPSHOT_KINDS.contains(kind)) {
+                    throw new IllegalArgumentException("Unsupported snapshot 
kind: " + kind);
+                }
+                Object value = frame.get("data");
+                if (!(value instanceof JsonObject data)) {
+                    throw new IllegalArgumentException("Snapshot data must be 
a JSON object");
+                }
+                current.updateSnapshot(kind, data);
+            }
+            case "result" -> {
+                requireHello();
+                String requestId = frame.getString("requestId");
+                if (requestId == null || requestId.isBlank()) {
+                    throw new IllegalArgumentException("A result frame 
requires requestId");
+                }
+                CompletableFuture<JsonObject> future = 
pending.remove(requestId);
+                if (future != null) {
+                    future.complete(new JsonObject(frame));
+                }
+            }
+            default -> throw new IllegalArgumentException("Unsupported 
integration frame type: " + type);
+        }

Review Comment:
   ℹ️ **No explicit `cancel` case** — The `switch` handles `hello`, `snapshot`, 
and `result`. If the protocol evolves or an integration ever mirrors a `cancel` 
acknowledgment, this `default` branch throws `IllegalArgumentException` and 
closes the WebSocket. Even if `cancel` is strictly unidirectional 
(server→integration), adding `case "cancel" -> { /* server-initiated, ignored 
here */ }` with a comment makes the protocol contract explicit and prevents 
unexpected failures.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to