You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2026/09/08 15:29:26 UTC

(camel) branch main updated (d202eff67b17 -> 1fd5519c6ca7)

This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


    from d202eff67b17 Camel TUI: Recommend qwen3.6:35b-a3b as the local Ollama model for the AI panel
     new f33abe089d7c CAMEL-24656: camel-jbang TUI - send a smaller, cache-friendly prompt from the AI panel to local models
     new 08bff85d5dc9 Camel TUI: TAB completes the model name after /model and the mode after /tools in the AI panel
     new 915e4829f647 CAMEL-24656: camel-jbang TUI - add an AI Tools row to the F2 Settings popup
     new 15bcdbe2f2a6 Camel TUI: Overview table export sends uptime as a duration, not the start timestamp
     new 79dee237aa11 CAMEL-24656: camel-jbang TUI - expose the status document as MCP resources and a tui_get_status tool
     new d0091452c389 CAMEL-24656: camel-jbang TUI - trim verbose tool descriptions and cap the AI panel history
     new 1fd5519c6ca7 CAMEL-24656: camel-jbang TUI - expose the integration log tail as an MCP resource

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../ROOT/pages/camel-4x-upgrade-guide-4_23.adoc    |   8 +
 .../modules/ROOT/pages/camel-jbang-tui.adoc        |  47 ++-
 .../camel/dsl/jbang/core/commands/LlmClient.java   |  67 +++-
 .../camel/dsl/jbang/core/commands/tui/AiPanel.java | 370 +++++++++++++++++----
 .../core/commands/tui/AiSlashCommandContext.java   |  11 +
 .../core/commands/tui/AiSlashCommandRegistry.java  |  14 +
 .../dsl/jbang/core/commands/tui/McpFacade.java     |  20 ++
 .../dsl/jbang/core/commands/tui/OverviewTab.java   |  11 +-
 .../dsl/jbang/core/commands/tui/SettingsPopup.java |  39 ++-
 .../jbang/core/commands/tui/StatusFileReader.java  | 153 +++++++++
 .../dsl/jbang/core/commands/tui/TuiMcpServer.java  | 211 +++++++++++-
 .../dsl/jbang/core/commands/tui/TuiSettings.java   |  16 +
 .../jbang/core/commands/tui/TuiToolRegistry.java   | 183 +++++-----
 .../commands/tui/AiPanelHistoryCompactionTest.java | 106 ++++++
 .../dsl/jbang/core/commands/tui/AiPanelTest.java   | 133 ++++++++
 .../commands/tui/AiSlashCommandRegistryTest.java   |  69 +++-
 .../core/commands/tui/OverviewTabRenderTest.java   |  20 ++
 .../jbang/core/commands/tui/SettingsPopupTest.java |  47 ++-
 .../core/commands/tui/StatusFileReaderTest.java    |  89 +++++
 .../commands/tui/TuiMcpServerResourcesTest.java    | 102 ++++++
 .../jbang/core/commands/tui/TuiSettingsTest.java   |   2 +
 .../commands/tui/TuiToolRegistryCoreToolsTest.java |  61 ++++
 22 files changed, 1617 insertions(+), 162 deletions(-)
 create mode 100644 dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReader.java
 create mode 100644 dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
 create mode 100644 dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReaderTest.java
 create mode 100644 dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServerResourcesTest.java
 create mode 100644 dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCoreToolsTest.java


(camel) 05/07: CAMEL-24656: camel-jbang TUI - expose the status document as MCP resources and a tui_get_status tool

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 79dee237aa11a8249b63be62c3f8a19fb210e187
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Tue Sep 8 17:17:37 2026 +0200

    CAMEL-24656: camel-jbang TUI - expose the status document as MCP resources and a tui_get_status tool
    
    camel-cli-connector writes a full status document per integration to
    ~/.camel/<pid>-status.json; the tabs only show a digest of it. Add
    StatusFileReader and expose the document through the TUI MCP server as
    resources (camel://status/<pid> for the whole document, camel://status/<pid>/<section>
    for one top-level section, with resources/list, resources/read and a URI
    template) so an external agent can fetch exactly the section it needs.
    
    The F8 agent loop only speaks tools, so add tui_get_status(section, pid) to
    the core set; section='sections' lists what the document contains. Also add
    a guideline that the panel's own tool calls are recorded in the AI log, not
    the MCP log, since the model claimed there was no way to see them.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
 .../modules/ROOT/pages/camel-jbang-tui.adoc        |  18 +++
 .../camel/dsl/jbang/core/commands/tui/AiPanel.java |   3 +
 .../dsl/jbang/core/commands/tui/McpFacade.java     |  20 +++
 .../jbang/core/commands/tui/StatusFileReader.java  |  86 +++++++++++++
 .../dsl/jbang/core/commands/tui/TuiMcpServer.java  | 137 ++++++++++++++++++++-
 .../jbang/core/commands/tui/TuiToolRegistry.java   |  49 +++++++-
 .../dsl/jbang/core/commands/tui/AiPanelTest.java   |   3 +-
 .../core/commands/tui/StatusFileReaderTest.java    |  69 +++++++++++
 .../commands/tui/TuiMcpServerResourcesTest.java    |  78 ++++++++++++
 9 files changed, 460 insertions(+), 3 deletions(-)

diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
index b5716f7eceb6..8039f5133e04 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
@@ -872,6 +872,24 @@ The server is bound to `127.0.0.1` only -- it never listens on external interfac
 When MCP is active, the TUI footer shows the connection status.
 Use *F2* -> _MCP Info_ to see server details and _MCP Log_ to view the tool call history.
 
+=== Status document resources
+
+Every running integration keeps a full status document in `~/.camel/<pid>-status.json`, written
+once a second by `camel-cli-connector`. The tabs show a digest of it; the MCP server exposes the
+whole document as resources so an agent can fetch exactly the section it needs instead of
+paging through tabs:
+
+* `camel://status/<pid>` -- the whole document
+* `camel://status/<pid>/<section>` -- one top-level section, for example `context` (name, version,
+  state, uptime, start timestamp, statistics), `runtime`, `routes`, `endpoints`, `healthChecks`,
+  `properties`, `main-configuration`, `routeController`, `memory`, `threads`, `gc` or `events`
+
+`resources/list` enumerates the document and its sections for every monitored integration, and a
+`resources/templates/list` template describes the URI shape. The same data is available to the
+F8 AI panel (and as an MCP tool) through `tui_get_status`, which takes a `section` argument and
+returns that section only; pass `sections` to list what the document contains. Sections such as
+`events` can be large, so ask for the one you need.
+
 === AI panel slash commands
 
 When the AI panel is open, input that starts with `/` runs a local panel command instead of sending a question to the configured AI provider. `/provider` and `/model` are unavailable while a response or command is already in progress; the panel shows a message asking you to wait.
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
index 0ec870f14ef1..a640ec44cc02 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
@@ -1787,6 +1787,9 @@ class AiPanel {
         sb.append("- Call tui_get_options only when unsure which tab holds the data you need\n");
         sb.append("- Use tui_get_state to learn which integration and tab is selected, if the question depends on it\n");
         sb.append("- Use tui_get_processor_detail to explain what a route does or how its steps are configured\n");
+        sb.append("- Use tui_get_status for data no tab shows (context, runtime, health checks, properties, ...)\n");
+        sb.append("- Your own tool calls are recorded in the AI log (tui_get_ai_log, F2 -> AI Log); ");
+        sb.append("the MCP log only records external clients\n");
         sb.append("- Be concise and actionable in your answers\n");
         sb.append("- When something looks wrong, explain what it means and suggest fixes\n");
         sb.append("- For stopping routes or applications, use tui_control for graceful shutdown\n");
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacade.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacade.java
index 3fc3a2c2f016..a39bcf1666bd 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacade.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacade.java
@@ -107,6 +107,7 @@ class McpFacade {
     private final MonitorBridge bridge;
 
     private volatile Supplier<List<AiPanel.LogEntry>> aiActivityLog;
+    private volatile StatusFileReader statusFiles = StatusFileReader.defaultReader();
     private volatile Supplier<List<TuiMcpServer.LogEntry>> mcpActivityLog;
     private volatile Supplier<Integer> mcpToolCallCount;
 
@@ -340,6 +341,25 @@ class McpFacade {
         return tab != null ? tab.isDetailFocused() : null;
     }
 
+    /**
+     * Reader for the per-process status documents; replaceable so tests can point it at a temporary directory.
+     */
+    StatusFileReader statusFiles() {
+        return statusFiles;
+    }
+
+    void setStatusFiles(StatusFileReader statusFiles) {
+        this.statusFiles = statusFiles;
+    }
+
+    /**
+     * Integrations currently monitored (vanished processes excluded), for callers that need pid and name.
+     */
+    List<IntegrationInfo> liveIntegrations() {
+        List<IntegrationInfo> all = data.get();
+        return all == null ? List.of() : all.stream().filter(i -> !i.vanishing).toList();
+    }
+
     List<String> getIntegrationNames() {
         return data.get().stream()
                 .filter(i -> !i.vanishing)
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReader.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReader.java
new file mode 100644
index 000000000000..906ebaafc919
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReader.java
@@ -0,0 +1,86 @@
+/*
+ * 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.tui;
+
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+
+/**
+ * Reads the full status document that camel-cli-connector writes for each running integration to
+ * {@code ~/.camel/<pid>-status.json}. The tabs show a digest of it; the AI tools and MCP resources hand out whole
+ * top-level sections so a model can fetch exactly the piece it needs.
+ */
+final class StatusFileReader {
+
+    static final String SECTION_LIST = "sections";
+
+    private final Path camelDir;
+
+    StatusFileReader(Path camelDir) {
+        this.camelDir = camelDir;
+    }
+
+    static StatusFileReader defaultReader() {
+        return new StatusFileReader(CommandLineHelper.getCamelDir());
+    }
+
+    Path statusFile(String pid) {
+        return camelDir.resolve(pid + "-status.json");
+    }
+
+    /**
+     * The parsed document, or {@code null} when there is no readable status file for the pid.
+     */
+    JsonObject read(String pid) {
+        if (pid == null || pid.isBlank()) {
+            return null;
+        }
+        Path file = statusFile(pid.trim());
+        if (!Files.isRegularFile(file)) {
+            return null;
+        }
+        try {
+            String text = Files.readString(file, StandardCharsets.UTF_8);
+            return (JsonObject) Jsoner.deserialize(text);
+        } catch (Exception e) {
+            // the connector rewrites the file every second, a torn read is expected now and then
+            return null;
+        }
+    }
+
+    /**
+     * Top-level section names of the document, in file order, or an empty list when it cannot be read.
+     */
+    List<String> sections(String pid) {
+        JsonObject doc = read(pid);
+        return doc == null ? List.of() : List.copyOf(doc.keySet());
+    }
+
+    /**
+     * One top-level section, or {@code null} when the document or the section does not exist.
+     */
+    Object section(String pid, String section) {
+        JsonObject doc = read(pid);
+        return doc == null || section == null ? null : doc.get(section);
+    }
+}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServer.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServer.java
index 82fc6eed794c..25edf336c4c5 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServer.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServer.java
@@ -177,11 +177,16 @@ class TuiMcpServer {
                 case "initialize" -> handleInitialize(request);
                 case "tools/list" -> handleToolsList();
                 case "tools/call" -> handleToolsCall(request);
+                case "resources/list" -> handleResourcesList();
+                case "resources/templates/list" -> handleResourceTemplatesList();
+                case "resources/read" -> handleResourcesRead(request);
                 case "ping" -> new JsonObject();
                 default -> null;
             };
 
-            if (result == null) {
+            if (result == null && "resources/read".equals(jsonrpcMethod)) {
+                sendError(exchange, request, -32002, "Resource not found: " + requestedUri(request));
+            } else if (result == null) {
                 sendError(exchange, request, -32601, "Method not found: " + jsonrpcMethod);
             } else {
                 String responseJson = sendResult(exchange, request, result);
@@ -224,6 +229,9 @@ class TuiMcpServer {
                 log(LogLevel.TOOL, "Tool call: " + toolName, requestBody, responseBody);
             }
             case "tools/list" -> log(LogLevel.INFO, "Tools listed", requestBody, responseBody);
+            case "resources/list" -> log(LogLevel.INFO, "Resources listed", requestBody, responseBody);
+            case "resources/templates/list" -> log(LogLevel.INFO, "Resource templates listed", requestBody, responseBody);
+            case "resources/read" -> log(LogLevel.TOOL, "Resource read: " + requestedUri(request), requestBody, responseBody);
             case "ping" -> log(LogLevel.INFO, "Ping", requestBody, responseBody);
             default -> log(LogLevel.INFO, jsonrpcMethod, requestBody, responseBody);
         }
@@ -250,6 +258,10 @@ class TuiMcpServer {
         JsonObject tools = new JsonObject();
         tools.put("listChanged", false);
         capabilities.put("tools", tools);
+        JsonObject resources = new JsonObject();
+        resources.put("subscribe", false);
+        resources.put("listChanged", false);
+        capabilities.put("resources", resources);
         result.put("capabilities", capabilities);
 
         return result;
@@ -269,6 +281,129 @@ class TuiMcpServer {
         return result;
     }
 
+    // ---- Resources: the per-process status document, whole or one section at a time ----
+
+    static final String STATUS_URI_PREFIX = "camel://status/";
+    private static final String JSON_MIME = "application/json";
+
+    /**
+     * Address of a status resource: {@code camel://status/<pid>} for the whole document, or
+     * {@code camel://status/<pid>/<section>} for one top-level section.
+     */
+    record StatusUri(String pid, String section) {
+
+        String uri() {
+            return STATUS_URI_PREFIX + pid + (section != null ? "/" + section : "");
+        }
+
+        /**
+         * Parses a resource URI, or returns {@code null} when it is not a status URI.
+         */
+        static StatusUri parse(String uri) {
+            if (uri == null || !uri.startsWith(STATUS_URI_PREFIX)) {
+                return null;
+            }
+            String rest = uri.substring(STATUS_URI_PREFIX.length());
+            if (rest.isEmpty()) {
+                return null;
+            }
+            int slash = rest.indexOf('/');
+            String pid = slash < 0 ? rest : rest.substring(0, slash);
+            String section = slash < 0 ? null : rest.substring(slash + 1);
+            if (pid.isEmpty() || !pid.chars().allMatch(Character::isDigit)
+                    || (section != null && (section.isEmpty() || section.contains("/")))) {
+                return null;
+            }
+            return new StatusUri(pid, section);
+        }
+    }
+
+    private JsonObject handleResourcesList() {
+        JsonObject result = new JsonObject();
+        result.put("resources", buildResourceList(facade.liveIntegrations(), facade.statusFiles()));
+        return result;
+    }
+
+    /**
+     * One resource per monitored integration for the whole document, followed by one per top-level section.
+     */
+    static JsonArray buildResourceList(List<IntegrationInfo> integrations, StatusFileReader reader) {
+        JsonArray resources = new JsonArray();
+        for (IntegrationInfo info : integrations) {
+            if (info.pid == null) {
+                continue;
+            }
+            List<String> sections = reader.sections(info.pid);
+            if (sections.isEmpty()) {
+                continue;
+            }
+            String name = info.name != null ? info.name : info.pid;
+            resources.add(resource(new StatusUri(info.pid, null).uri(), name + " status",
+                    "Full status document of " + name + " (PID " + info.pid + "): " + String.join(", ", sections)));
+            for (String section : sections) {
+                resources.add(resource(new StatusUri(info.pid, section).uri(), name + " " + section,
+                        "The '" + section + "' section of the status document of " + name + " (PID " + info.pid + ")"));
+            }
+        }
+        return resources;
+    }
+
+    private static JsonObject resource(String uri, String name, String description) {
+        JsonObject resource = new JsonObject();
+        resource.put("uri", uri);
+        resource.put("name", name);
+        resource.put("description", description);
+        resource.put("mimeType", JSON_MIME);
+        return resource;
+    }
+
+    private JsonObject handleResourceTemplatesList() {
+        JsonObject template = new JsonObject();
+        template.put("uriTemplate", STATUS_URI_PREFIX + "{pid}/{section}");
+        template.put("name", "Integration status section");
+        template.put("description", "One top-level section of the status document that camel-cli-connector writes "
+                                    + "for the integration with the given PID; omit /{section} for the whole document. "
+                                    + "Sections include context, runtime, routes, endpoints, healthChecks, properties, "
+                                    + "main-configuration, memory, threads, gc and events.");
+        template.put("mimeType", JSON_MIME);
+        JsonArray templates = new JsonArray();
+        templates.add(template);
+        JsonObject result = new JsonObject();
+        result.put("resourceTemplates", templates);
+        return result;
+    }
+
+    /**
+     * Returns the resource contents, or {@code null} when the URI does not name a readable status document or section
+     * (the caller turns that into a "resource not found" error).
+     */
+    private JsonObject handleResourcesRead(JsonObject request) {
+        StatusUri uri = StatusUri.parse(requestedUri(request));
+        if (uri == null) {
+            return null;
+        }
+        Object payload = uri.section() == null
+                ? facade.statusFiles().read(uri.pid())
+                : facade.statusFiles().section(uri.pid(), uri.section());
+        if (payload == null) {
+            return null;
+        }
+        JsonObject content = new JsonObject();
+        content.put("uri", uri.uri());
+        content.put("mimeType", JSON_MIME);
+        content.put("text", Jsoner.serialize(payload));
+        JsonArray contents = new JsonArray();
+        contents.add(content);
+        JsonObject result = new JsonObject();
+        result.put("contents", contents);
+        return result;
+    }
+
+    private static String requestedUri(JsonObject request) {
+        JsonObject params = (JsonObject) request.get("params");
+        return params != null && params.get("uri") instanceof String s ? s : null;
+    }
+
     @SuppressWarnings("unchecked")
     private JsonObject handleToolsCall(JsonObject request) {
         JsonObject params = (JsonObject) request.get("params");
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
index 03bbb0fc4caf..09bd8c1bcb21 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
@@ -89,7 +89,7 @@ class TuiToolRegistry {
             "tui_get_state", "tui_get_options", "tui_get_table", "tui_get_log", "tui_get_errors",
             "tui_get_diagram", "tui_get_topology", "tui_get_processor_detail", "tui_catalog_doc",
             "tui_get_history", "tui_get_spans", "tui_control", "tui_send_message", "tui_get_files",
-            "tui_get_readme", "tui_navigate", "tui_set_log_level", "tui_filter");
+            "tui_get_readme", "tui_navigate", "tui_set_log_level", "tui_filter", "tui_get_status");
 
     /**
      * Returns all tool definitions. The result is cached since it is immutable.
@@ -119,6 +119,7 @@ class TuiToolRegistry {
             case "tui_get_screen" -> callGetScreen(args);
             case "tui_get_events" -> callGetEvents(args);
             case "tui_get_state" -> callGetState();
+            case "tui_get_status" -> callGetStatus(args);
             case "tui_show_caption" -> callShowCaption(args);
             case "tui_navigate" -> callNavigate(args);
             case "tui_send_keys" -> callSendKeys(args);
@@ -392,6 +393,21 @@ class TuiToolRegistry {
                         "Tab name to get data from (e.g. 'Routes', 'Endpoints', 'Kafka'). "
                                                 + "Use tui_get_options to discover available tab names. "
                                                 + "If omitted, uses the active tab.")))));
+        tools.add(toToolDef(toolDef(
+                "tui_get_status",
+                "Returns one top-level section of the integration's full status document, the same JSON the Camel "
+                                  + "CLI reads from ~/.camel/<pid>-status.json. Use it for data the tabs do not show: "
+                                  + "'context' (name, version, state, uptime in millis, startTimestamp, statistics), "
+                                  + "'runtime' (pid, directory, java version), 'healthChecks', 'properties', "
+                                  + "'main-configuration', 'routeController', 'services', 'transformers', 'rests', "
+                                  + "'consumers', 'producers', 'endpoints', 'dataSources', 'memory', 'threads', 'gc', "
+                                  + "'classLoading', 'trace', 'events'. Pass section='sections' to list what the "
+                                  + "document contains. Sections can be large, so request only the one you need.",
+                Map.of("section", propDef("string",
+                        "Top-level section name, or 'sections' to list the available names"),
+                        "pid", propDef("string",
+                                "Process id of the integration; defaults to the selected integration")),
+                List.of("section"))));
         tools.add(toToolDef(toolDef(
                 "tui_action",
                 "Invokes a TUI action by name, bypassing fragile key sequences. "
@@ -1335,6 +1351,37 @@ class TuiToolRegistry {
         return Jsoner.serialize(data);
     }
 
+    private String callGetStatus(Map<String, Object> args) {
+        String section = args.get("section") instanceof String s ? s.trim() : "";
+        if (section.isEmpty()) {
+            return "Error: section is required (use 'sections' to list the available names)";
+        }
+        String pid = args.get("pid") instanceof String s && !s.isBlank() ? s.trim() : facade.getSelectedPid();
+        if (pid == null || pid.isBlank()) {
+            return "No integration selected";
+        }
+        StatusFileReader reader = facade.statusFiles();
+        List<String> sections = reader.sections(pid);
+        if (sections.isEmpty()) {
+            return "No status document available for PID " + pid;
+        }
+        if (StatusFileReader.SECTION_LIST.equals(section)) {
+            JsonObject result = new JsonObject();
+            result.put("pid", pid);
+            result.put("sections", new JsonArray(sections));
+            return Jsoner.serialize(result);
+        }
+        Object value = reader.section(pid, section);
+        if (value == null) {
+            return "Unknown section '" + section + "' for PID " + pid + ". Available: " + String.join(", ", sections);
+        }
+        JsonObject result = new JsonObject();
+        result.put("pid", pid);
+        result.put("section", section);
+        result.put("data", value);
+        return Jsoner.serialize(result);
+    }
+
     private String callAction(Map<String, Object> args) {
         String action = (String) args.get("action");
         if (action == null || action.isBlank()) {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
index 51b912a2564f..ad71a7d2ba4d 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
@@ -808,7 +808,8 @@ class AiPanelTest {
         assertTrue(panel.toolDefinitionsForTesting().stream()
                 .allMatch(def -> TuiToolRegistry.CORE_TOOLS.contains(def.name())));
         assertFalse(panel.systemPromptForTesting().contains("tui_draw_shape"));
-        assertTrue(panel.describeToolModeForTesting().startsWith("core (18 of "));
+        assertTrue(panel.describeToolModeForTesting()
+                .startsWith("core (" + TuiToolRegistry.CORE_TOOLS.size() + " of "));
     }
 
     @Test
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReaderTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReaderTest.java
new file mode 100644
index 000000000000..c75cd7166739
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReaderTest.java
@@ -0,0 +1,69 @@
+/*
+ * 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.tui;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class StatusFileReaderTest {
+
+    private static final String STATUS = """
+            {"runtime":{"pid":4711,"directory":"/tmp/app"},
+             "context":{"name":"timer-log","uptime":262307,"startTimestamp":1788879661524},
+             "routes":[{"routeId":"route1","state":"Started"}]}
+            """;
+
+    @Test
+    void readsSectionsInFileOrder(@TempDir Path dir) throws Exception {
+        Files.writeString(dir.resolve("4711-status.json"), STATUS);
+        StatusFileReader reader = new StatusFileReader(dir);
+
+        assertEquals(List.of("runtime", "context", "routes"), reader.sections("4711"));
+    }
+
+    @Test
+    void returnsOneSectionOrNull(@TempDir Path dir) throws Exception {
+        Files.writeString(dir.resolve("4711-status.json"), STATUS);
+        StatusFileReader reader = new StatusFileReader(dir);
+
+        JsonObject context = (JsonObject) reader.section("4711", "context");
+        assertEquals("timer-log", context.get("name"));
+        assertEquals(262307L, ((Number) context.get("uptime")).longValue());
+        assertNull(reader.section("4711", "nope"));
+        assertNull(reader.section("4711", null));
+    }
+
+    @Test
+    void missingOrCorruptFilesReadAsAbsent(@TempDir Path dir) throws Exception {
+        Files.writeString(dir.resolve("99-status.json"), "{ not json");
+        StatusFileReader reader = new StatusFileReader(dir);
+
+        assertNull(reader.read("4711"));
+        assertNull(reader.read("99"));
+        assertNull(reader.read(" "));
+        assertTrue(reader.sections("4711").isEmpty());
+    }
+}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServerResourcesTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServerResourcesTest.java
new file mode 100644
index 000000000000..9d6bf34720e8
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServerResourcesTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.tui;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+class TuiMcpServerResourcesTest {
+
+    @Test
+    void parsesWholeDocumentAndSectionUris() {
+        TuiMcpServer.StatusUri whole = TuiMcpServer.StatusUri.parse("camel://status/4711");
+        assertEquals("4711", whole.pid());
+        assertNull(whole.section());
+        assertEquals("camel://status/4711", whole.uri());
+
+        TuiMcpServer.StatusUri section = TuiMcpServer.StatusUri.parse("camel://status/4711/main-configuration");
+        assertEquals("4711", section.pid());
+        assertEquals("main-configuration", section.section());
+        assertEquals("camel://status/4711/main-configuration", section.uri());
+    }
+
+    @Test
+    void rejectsUrisThatAreNotStatusResources() {
+        assertNull(TuiMcpServer.StatusUri.parse(null));
+        assertNull(TuiMcpServer.StatusUri.parse("file:///etc/passwd"));
+        assertNull(TuiMcpServer.StatusUri.parse("camel://status/"));
+        assertNull(TuiMcpServer.StatusUri.parse("camel://status/abc"));
+        assertNull(TuiMcpServer.StatusUri.parse("camel://status/4711/"));
+        assertNull(TuiMcpServer.StatusUri.parse("camel://status/4711/a/b"));
+        assertNull(TuiMcpServer.StatusUri.parse("camel://status/../4711"));
+    }
+
+    @Test
+    void listsWholeDocumentThenEachSectionPerIntegration(@TempDir Path dir) throws Exception {
+        Files.writeString(dir.resolve("4711-status.json"),
+                "{\"runtime\":{\"pid\":4711},\"context\":{\"name\":\"timer-log\"}}");
+        IntegrationInfo running = new IntegrationInfo();
+        running.pid = "4711";
+        running.name = "timer-log";
+        IntegrationInfo gone = new IntegrationInfo();
+        gone.pid = "4712";
+        gone.name = "no-file";
+
+        JsonArray resources = TuiMcpServer.buildResourceList(List.of(running, gone), new StatusFileReader(dir));
+
+        assertEquals(3, resources.size());
+        JsonObject whole = (JsonObject) resources.get(0);
+        assertEquals("camel://status/4711", whole.get("uri"));
+        assertEquals("timer-log status", whole.get("name"));
+        assertEquals("application/json", whole.get("mimeType"));
+        assertEquals("camel://status/4711/runtime", ((JsonObject) resources.get(1)).get("uri"));
+        assertEquals("camel://status/4711/context", ((JsonObject) resources.get(2)).get("uri"));
+    }
+}


(camel) 03/07: CAMEL-24656: camel-jbang TUI - add an AI Tools row to the F2 Settings popup

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 915e4829f647f7b227b2c496ac696c88e5c1b161
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Tue Sep 8 16:29:24 2026 +0200

    CAMEL-24656: camel-jbang TUI - add an AI Tools row to the F2 Settings popup
    
    Cycles auto / core / full for the tool set the AI panel sends to the model,
    persisted as camel.tui.ai.tools like the /tools slash command. The panel
    re-reads the setting before each question so a change applies without a
    restart.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
 .../modules/ROOT/pages/camel-jbang-tui.adoc        |  7 ++--
 .../camel/dsl/jbang/core/commands/tui/AiPanel.java |  6 ++-
 .../dsl/jbang/core/commands/tui/SettingsPopup.java | 39 ++++++++++++++++--
 .../jbang/core/commands/tui/SettingsPopupTest.java | 47 ++++++++++++++++++++--
 4 files changed, 89 insertions(+), 10 deletions(-)

diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
index 49380e035949..b5716f7eceb6 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
@@ -557,7 +557,8 @@ edit the default folder, *Enter* to save, and *Esc* to cancel.
 Settings are stored under `camel.tui.*` keys (`camel.tui.theme`, `camel.tui.startTab`,
 `camel.tui.selectTab`, `camel.tui.confirmActions`, `camel.tui.defaultFolder`,
 `camel.tui.panelPosition`, `camel.tui.panelSpace`,
-`camel.tui.shell.history`, `camel.tui.ai.promptHistory`) in the Camel CLI configuration file. Each key is read from and
+`camel.tui.shell.history`, `camel.tui.ai.provider`, `camel.tui.ai.model`, `camel.tui.ai.url`,
+`camel.tui.ai.tools`, `camel.tui.ai.promptHistory`) in the Camel CLI configuration file. Each key is read from and
 written back to the file where it currently lives: a key present in the local
 `./camel-cli.properties` is treated as a project-level override and stays local, while every
 other key defaults to the global `~/.camel-cli.properties`. This means a project can
@@ -822,8 +823,8 @@ tools (state, tables, logs, errors, diagrams, topology, processor details, catal
 spans, route control, sending messages, source files, navigation, log level and filters) to Ollama
 and to any provider on `localhost`, which roughly halves the prompt. Hosted providers get every
 tool, including the drawing, animation and automation tools. Use `/tools full` in the panel to send
-all tools to a local model too, `/tools core` to trim the set for a hosted one, or set
-`camel.tui.ai.tools` in `.camel-cli.properties`. Ollama requests also ask the server to keep the
+all tools to a local model too, `/tools core` to trim the set for a hosted one, pick *AI Tools* in
+*F2 -> Settings*, or set `camel.tui.ai.tools` in `.camel-cli.properties`. Ollama requests also ask the server to keep the
 model loaded for 30 minutes and use a 32k context window (`OLLAMA_CONTEXT_LENGTH` overrides it),
 so follow-up questions reuse the cached prompt instead of reloading the model.
 
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
index 1aa3722125bf..0ec870f14ef1 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
@@ -964,7 +964,11 @@ class AiPanel {
         thinkingStartTime = System.currentTimeMillis();
         thinking.set(true);
 
-        // rebuild tools in case mcpFacade was wired after init
+        // re-read the tool mode so a change made in F2 -> Settings applies to the next question, and rebuild the
+        // tools in case mcpFacade was wired after init
+        if (!testingClientInjected) {
+            toolMode = normalizeToolMode(TuiSettings.load().getAiTools());
+        }
         tools = buildTuiToolDefinitions();
         String systemPrompt = buildSystemPrompt();
 
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopup.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopup.java
index 67e0d02e3505..aea9a61533c3 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopup.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopup.java
@@ -61,13 +61,16 @@ class SettingsPopup {
     private static final int ROW_AI_PROVIDER = 13;
     private static final int ROW_AI_MODEL = 14;
     private static final int ROW_AI_URL = 15;
-    private static final int ROW_AI_PROMPT_HISTORY = 16;
-    private static final int ROW_COUNT = 17;
+    private static final int ROW_AI_TOOLS = 16;
+    private static final int ROW_AI_PROMPT_HISTORY = 17;
+    private static final int ROW_COUNT = 18;
 
     private static final String[] LOG_PIN_OPTIONS = { "off", "25", "50", "75" };
     private static final String[] RATE_PER_OPTIONS = { "seconds", "minutes" };
     private static final String[] PANEL_POSITION_OPTIONS = { "bottom", "top" };
     private static final String[] PANEL_SPACE_OPTIONS = { "move", "overlay" };
+    private static final String[] AI_TOOLS_OPTIONS
+            = { AiPanel.TOOL_MODE_AUTO, AiPanel.TOOL_MODE_CORE, AiPanel.TOOL_MODE_FULL };
     private static final List<String> AI_PROVIDERS = buildAiProviderList();
 
     private static List<String> buildAiProviderList() {
@@ -93,6 +96,7 @@ class SettingsPopup {
     private int confirmActionsIndex;
     private int validateOnSaveIndex;
     private int aiProviderIndex;
+    private int aiToolsIndex;
     private TextInputState folderInput;
     private TextInputState proxyHostInput;
     private TextInputState proxyPortInput;
@@ -181,6 +185,9 @@ class SettingsPopup {
         aiProviderIndex = providerIdx >= 0 ? providerIdx : AI_PROVIDERS.indexOf("auto");
         aiModelInput = new TextInputState(settings.getAiModel() != null ? settings.getAiModel() : "");
         aiUrlInput = new TextInputState(settings.getAiUrl() != null ? settings.getAiUrl() : "");
+        String currentTools = AiPanel.normalizeToolMode(settings.getAiTools());
+        int toolsIdx = List.of(AI_TOOLS_OPTIONS).indexOf(currentTools != null ? currentTools : AiPanel.TOOL_MODE_AUTO);
+        aiToolsIndex = Math.max(0, toolsIdx);
         aiPromptHistoryInput = new TextInputState(
                 settings.getAiPromptHistory() != null ? settings.getAiPromptHistory() : "");
         selectedRow = ROW_THEME;
@@ -323,6 +330,14 @@ class SettingsPopup {
             handleTextInput(ke, aiUrlInput);
             return true;
         }
+        if (selectedRow == ROW_AI_TOOLS) {
+            if (ke.isChar(' ') || ke.isRight()) {
+                aiToolsIndex = (aiToolsIndex + 1) % AI_TOOLS_OPTIONS.length;
+            } else if (ke.isLeft()) {
+                aiToolsIndex = (aiToolsIndex - 1 + AI_TOOLS_OPTIONS.length) % AI_TOOLS_OPTIONS.length;
+            }
+            return true;
+        }
         if (selectedRow == ROW_AI_PROMPT_HISTORY) {
             handleTextInput(ke, aiPromptHistoryInput);
             return true;
@@ -368,6 +383,8 @@ class SettingsPopup {
         settings.setAiProvider(AI_PROVIDERS.get(aiProviderIndex));
         settings.setAiModel(stripControlChars(aiModelInput.text().trim()));
         settings.setAiUrl(stripControlChars(aiUrlInput.text().trim()));
+        String aiToolsValue = AI_TOOLS_OPTIONS[aiToolsIndex];
+        settings.setAiTools(AiPanel.TOOL_MODE_AUTO.equals(aiToolsValue) ? null : aiToolsValue);
         settings.setAiPromptHistory(stripControlChars(aiPromptHistoryInput.text().trim()));
         settings.save();
         if (Theme.mode().equals(selectedThemeId)) {
@@ -495,6 +512,10 @@ class SettingsPopup {
         renderTextInput(frame, innerX + labelW, rowY, fieldW, aiUrlInput, selectedRow == ROW_AI_URL, "(auto)");
         rowY++;
 
+        renderLabel(frame, innerX, rowY, labelW, "AI Tools:", selectedRow == ROW_AI_TOOLS);
+        renderValue(frame, innerX + labelW, rowY, fieldW, aiToolsLabel(), selectedRow == ROW_AI_TOOLS);
+        rowY++;
+
         renderLabel(frame, innerX, rowY, labelW, "AI History:", selectedRow == ROW_AI_PROMPT_HISTORY);
         renderTextInput(frame, innerX + labelW, rowY, fieldW, aiPromptHistoryInput,
                 selectedRow == ROW_AI_PROMPT_HISTORY, "(100)");
@@ -505,7 +526,7 @@ class SettingsPopup {
                 || selectedRow == ROW_LOG_PIN || selectedRow == ROW_RATE_PER
                 || selectedRow == ROW_PANEL_POSITION || selectedRow == ROW_PANEL_SPACE
                 || selectedRow == ROW_CONFIRM_ACTIONS || selectedRow == ROW_VALIDATE_ON_SAVE
-                || selectedRow == ROW_AI_PROVIDER) {
+                || selectedRow == ROW_AI_PROVIDER || selectedRow == ROW_AI_TOOLS) {
             hint(spans, "Space", "cycle");
         }
         hint(spans, "Enter", "save");
@@ -637,6 +658,18 @@ class SettingsPopup {
         return AI_PROVIDERS.get(aiProviderIndex);
     }
 
+    String selectedAiTools() {
+        return AI_TOOLS_OPTIONS[aiToolsIndex];
+    }
+
+    private String aiToolsLabel() {
+        return switch (AI_TOOLS_OPTIONS[aiToolsIndex]) {
+            case AiPanel.TOOL_MODE_CORE -> "core (troubleshooting only)";
+            case AiPanel.TOOL_MODE_FULL -> "full (all tools)";
+            default -> "auto (core if local model)";
+        };
+    }
+
     String aiModelText() {
         return aiModelInput != null ? aiModelInput.text() : "";
     }
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopupTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopupTest.java
index efba01b08d02..7dc071e4d1c4 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopupTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/SettingsPopupTest.java
@@ -32,6 +32,7 @@ import org.junit.jupiter.api.parallel.Isolated;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
@@ -216,6 +217,46 @@ class SettingsPopupTest {
         assertEquals("https://example.test", persisted.getAiUrl());
     }
 
+    @Test
+    void aiToolsRowCyclesModesAndPersistsNonDefault(@TempDir Path tempDir) {
+        useHome(tempDir);
+        SettingsPopup popup = new SettingsPopup();
+        popup.setTabEntries(tabs());
+        popup.open();
+
+        // navigate to AI Tools (row 16)
+        for (int i = 0; i < 16; i++) {
+            popup.handleKeyEvent(key(KeyCode.DOWN));
+        }
+        assertEquals(16, popup.selectedRow());
+        assertEquals("auto", popup.selectedAiTools());
+
+        popup.handleKeyEvent(KeyEvent.ofChar(' '));
+        assertEquals("core", popup.selectedAiTools());
+        popup.handleKeyEvent(key(KeyCode.RIGHT));
+        assertEquals("full", popup.selectedAiTools());
+        popup.handleKeyEvent(key(KeyCode.RIGHT));
+        assertEquals("auto", popup.selectedAiTools());
+        popup.handleKeyEvent(key(KeyCode.LEFT));
+        assertEquals("full", popup.selectedAiTools());
+
+        popup.handleKeyEvent(key(KeyCode.ENTER));
+        assertEquals("full", TuiSettings.load().getAiTools());
+
+        // auto is the default and is not written to the settings file
+        SettingsPopup reopened = new SettingsPopup();
+        reopened.setTabEntries(tabs());
+        reopened.open();
+        assertEquals("full", reopened.selectedAiTools());
+        for (int i = 0; i < 16; i++) {
+            reopened.handleKeyEvent(key(KeyCode.DOWN));
+        }
+        reopened.handleKeyEvent(key(KeyCode.RIGHT));
+        assertEquals("auto", reopened.selectedAiTools());
+        reopened.handleKeyEvent(key(KeyCode.ENTER));
+        assertNull(TuiSettings.load().getAiTools());
+    }
+
     @Test
     void historyFieldsPersistValues(@TempDir Path tempDir) {
         useHome(tempDir);
@@ -233,11 +274,11 @@ class SettingsPopupTest {
         }
         assertEquals("50", popup.shellHistoryText());
 
-        // navigate to AI Prompt History (row 14)
-        for (int i = 0; i < 4; i++) {
+        // navigate to AI Prompt History (row 17)
+        for (int i = 0; i < 5; i++) {
             popup.handleKeyEvent(key(KeyCode.DOWN));
         }
-        assertEquals(16, popup.selectedRow());
+        assertEquals(17, popup.selectedRow());
         for (char c : "200".toCharArray()) {
             popup.handleKeyEvent(KeyEvent.ofChar(c));
         }


(camel) 01/07: CAMEL-24656: camel-jbang TUI - send a smaller, cache-friendly prompt from the AI panel to local models

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit f33abe089d7c230d17a3766894d290bf30d07fcb
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Tue Sep 8 16:19:08 2026 +0200

    CAMEL-24656: camel-jbang TUI - send a smaller, cache-friendly prompt from the AI panel to local models
    
    The F8 panel sent ~8.1k tokens of static prefix on every request: 46 tool
    schemas plus a system prompt that repeated the whole tool list in prose and
    embedded the selected integration and PID. Local models process prompts
    slowly, and the PID line invalidated the prompt cache whenever the selection
    changed.
    
    - Add TuiToolRegistry.CORE_TOOLS (18 tools for Q&A and troubleshooting) and
      send only those to local providers (Ollama, or any provider on localhost)
      by default. /tools [auto|core|full] shows or switches the set and persists
      it as camel.tui.ai.tools.
    - Drop the prose tool list from the system prompt (the tool definitions
      already carry the descriptions) and keep it free of per-turn state; the
      selected integration now travels in the user message.
    - Ask Ollama to keep the model loaded for 30 minutes and use a 32k context
      (OLLAMA_CONTEXT_LENGTH overrides) so follow-up turns hit the prompt cache
      instead of reloading the model or truncating the prompt.
    
    Measured static prefix per request: ~8.1k tokens before, ~3.1k tokens for
    local providers and ~7.3k for hosted providers after.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
 .../ROOT/pages/camel-4x-upgrade-guide-4_23.adoc    |   8 +
 .../modules/ROOT/pages/camel-jbang-tui.adoc        |  16 ++
 .../camel/dsl/jbang/core/commands/LlmClient.java   |  67 +++++++-
 .../camel/dsl/jbang/core/commands/tui/AiPanel.java | 173 ++++++++++++++-------
 .../core/commands/tui/AiSlashCommandContext.java   |  11 ++
 .../core/commands/tui/AiSlashCommandRegistry.java  |  14 ++
 .../dsl/jbang/core/commands/tui/TuiSettings.java   |  16 ++
 .../jbang/core/commands/tui/TuiToolRegistry.java   |  22 ++-
 .../dsl/jbang/core/commands/tui/AiPanelTest.java   |  71 +++++++++
 .../commands/tui/AiSlashCommandRegistryTest.java   |  69 +++++++-
 .../jbang/core/commands/tui/TuiSettingsTest.java   |   2 +
 .../commands/tui/TuiToolRegistryCoreToolsTest.java |  61 ++++++++
 12 files changed, 466 insertions(+), 64 deletions(-)

diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
index fb25b895e6e9..d845030dfef8 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
@@ -612,6 +612,14 @@ shape. The `camel get variable` CLI command has already been updated accordingly
 
 === camel-jbang (TUI)
 
+The F8 AI panel now sends only a core subset of its `tui_*` tools to local providers (Ollama, or any
+provider on `localhost`); the drawing, animation and automation tools are left out to keep the
+prompt small for local models. Hosted providers are unaffected. Use `/tools full` in the panel, or
+set `camel.tui.ai.tools=full`, to restore the previous behaviour. Requests to Ollama now also set
+`keep_alive` to 30 minutes and `num_ctx` to 32768 (or `OLLAMA_CONTEXT_LENGTH` when that is set in the
+environment), which can cause a one-time model reload if the model was loaded with a different
+context size.
+
 `camel tui --record` is now rejected when combined with `--web`. The recording configuration applies
 to the whole process, so a browser session served by `--web` would be recorded into the same `.cast`
 file as the local session. Previously the combination was accepted, but recording never produced any
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
index 90c4d0b0f1ed..96cef22d9c49 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
@@ -814,6 +814,19 @@ NOTE: On Apple Silicon, use the default (GGUF) tags rather than the `-mlx` tags.
 engine cannot yet reuse the cached prompt for Qwen 3.x models, so every question re-processes the
 whole prompt, while the default engine reuses it and only processes what is new.
 
+==== Tool set for local models
+
+Every question sends the definitions of the `tui_*` tools the model may call, and a local model
+pays for each of them in prompt-processing time. The panel therefore sends only the core set of
+tools (state, tables, logs, errors, diagrams, topology, processor details, catalog docs, traces,
+spans, route control, sending messages, source files, navigation, log level and filters) to Ollama
+and to any provider on `localhost`, which roughly halves the prompt. Hosted providers get every
+tool, including the drawing, animation and automation tools. Use `/tools full` in the panel to send
+all tools to a local model too, `/tools core` to trim the set for a hosted one, or set
+`camel.tui.ai.tools` in `.camel-cli.properties`. Ollama requests also ask the server to keep the
+model loaded for 30 minutes and use a 32k context window (`OLLAMA_CONTEXT_LENGTH` overrides it),
+so follow-up questions reuse the cached prompt instead of reloading the model.
+
 ==== Using an OpenAI-compatible local server
 
 Set `LLM_API_KEY` and `LLM_BASE_URL` to connect to any OpenAI-compatible server
@@ -875,6 +888,9 @@ When the AI panel is open, input that starts with `/` runs a local panel command
 | `/model [model-name]` (`/m`)
 | Show the current model, or switch the session model.
 
+| `/tools [auto\|core\|full]` (`/t`)
+| Show which tool set is sent to the model, or switch it. `auto` (default) sends the core set to local providers and every tool to hosted ones; the choice is saved as `camel.tui.ai.tools`.
+
 | `/clear` (`/c`)
 | Clear the AI conversation, usage counters, and model context without changing the provider or model.
 
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java
index 1d8470f287e7..d472c0511bb4 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java
@@ -53,6 +53,18 @@ public class LlmClient {
     private static final String DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-4-6";
     private static final String DEFAULT_OPENAI_MODEL = "gpt-4o-mini";
     private static final String DEFAULT_OLLAMA_MODEL = "llama3.2";
+    /**
+     * Keep the model (and its prompt cache) loaded between turns of a conversation. Ollama's default of five minutes is
+     * shorter than a slow local answer plus the time the user spends reading it, after which the next request pays for
+     * a full model reload and re-processes the whole prompt.
+     */
+    private static final String OLLAMA_KEEP_ALIVE = "30m";
+    /**
+     * Context window requested from Ollama. The tool-calling system prompt alone is several thousand tokens, and older
+     * Ollama releases default to 4096 which silently truncates it; 32k leaves room for a long conversation with tool
+     * results while keeping the KV cache modest. {@code OLLAMA_CONTEXT_LENGTH} in the environment overrides it.
+     */
+    private static final int OLLAMA_NUM_CTX = 32768;
     private static final String DEFAULT_WATSONX_URL = "https://us-south.ml.cloud.ibm.com";
     private static final String DEFAULT_WATSONX_MODEL = "ibm/granite-4-1-8b-instruct";
     private static final String DEFAULT_AZURE_API_VERSION = "2024-10-21";
@@ -194,6 +206,27 @@ public class LlmClient {
         return url;
     }
 
+    /**
+     * Whether the model runs on this machine: the Ollama provider, or any provider whose endpoint host is a loopback
+     * address (LM Studio, llama.cpp server, vLLM and similar OpenAI-compatible servers). Local models process prompts
+     * far slower than hosted ones, so callers use this to trim what they send per request.
+     */
+    public boolean isLocalEndpoint() {
+        if (apiType == ApiType.ollama) {
+            return true;
+        }
+        if (url == null) {
+            return false;
+        }
+        try {
+            String host = URI.create(url).getHost();
+            return host != null && (host.equalsIgnoreCase("localhost") || host.equals("127.0.0.1")
+                    || host.equals("::1") || host.equals("[::1]") || host.equals("0.0.0.0"));
+        } catch (IllegalArgumentException e) {
+            return false;
+        }
+    }
+
     // -- Builder --
 
     public static LlmClient create() {
@@ -559,10 +592,8 @@ public class LlmClient {
         request.put("prompt", userPrompt);
         request.put("system", systemPrompt);
         request.put("stream", stream);
-
-        JsonObject options = new JsonObject();
-        options.put("temperature", temperature);
-        request.put("options", options);
+        request.put("keep_alive", OLLAMA_KEEP_ALIVE);
+        request.put("options", ollamaOptions());
 
         if (stream) {
             return sendStreamingRequest(url + "/api/generate", request, null, "response");
@@ -936,6 +967,28 @@ public class LlmClient {
         return parseOpenAiChatResponse(response);
     }
 
+    private JsonObject ollamaOptions() {
+        JsonObject options = new JsonObject();
+        options.put("temperature", temperature);
+        options.put("num_ctx", ollamaNumCtx());
+        return options;
+    }
+
+    static int ollamaNumCtx() {
+        String env = System.getenv("OLLAMA_CONTEXT_LENGTH");
+        if (env != null && !env.isBlank()) {
+            try {
+                int value = Integer.parseInt(env.trim());
+                if (value > 0) {
+                    return value;
+                }
+            } catch (NumberFormatException e) {
+                // fall through to the default
+            }
+        }
+        return OLLAMA_NUM_CTX;
+    }
+
     // ---- Ollama native chat with tools ----
 
     private ChatResponse chatOllamaFormat(String systemPrompt, List<Message> messages, List<ToolDef> tools) {
@@ -949,10 +1002,8 @@ public class LlmClient {
         if (jsonTools != null) {
             request.put("tools", jsonTools);
         }
-
-        JsonObject options = new JsonObject();
-        options.put("temperature", temperature);
-        request.put("options", options);
+        request.put("keep_alive", OLLAMA_KEEP_ALIVE);
+        request.put("options", ollamaOptions());
 
         if (stream) {
             request.put("stream", true);
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
index 19caf4aecfd1..5e0107cafffc 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
@@ -76,6 +76,9 @@ class AiPanel {
     private static final DateTimeFormatter TIME_FMT
             = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.systemDefault());
     private static final String INPUT_PROMPT = "❯ ";
+    static final String TOOL_MODE_AUTO = "auto";
+    static final String TOOL_MODE_CORE = "core";
+    static final String TOOL_MODE_FULL = "full";
     private static final List<String> THINKING_VERBS = List.of(
             "Herding thoughts", "Chewing the cud", "Crossing the desert", "Loading the caravan",
             "Sniffing out an oasis", "Trekking onward", "Kicking up sand", "Grazing on context",
@@ -133,6 +136,8 @@ class AiPanel {
     // Slash commands
     private final AiSlashCommandRegistry slashCommands = AiSlashCommandRegistry.defaults();
     private AiSlashCommandContext slashCommandContext = new PanelSlashCommandContext();
+    // auto | core | full, see useCoreTools(); loaded from camel.tui.ai.tools, null means auto
+    private volatile String toolMode;
     private final AiCliCommandExecutor cliCommandExecutor = new AiCliCommandExecutor();
     private volatile CompletableFuture<AiCliCommandExecutor.Result> activeCliCommand;
     private Runnable exitCallback;
@@ -307,6 +312,9 @@ class AiPanel {
                 TuiSettings settings = TuiSettings.load();
                 providerSelector.applyChoice(created, settings.getAiProvider(), settings.getAiModel(), settings.getAiUrl());
             }
+            if (toolMode == null) {
+                toolMode = normalizeToolMode(TuiSettings.load().getAiTools());
+            }
             client = created;
             if (!client.detectEndpoint()) {
                 initError
@@ -887,7 +895,7 @@ class AiPanel {
         if (messages == null) {
             messages = new ArrayList<>();
         }
-        messages.add(LlmClient.Message.user(question));
+        messages.add(LlmClient.Message.user(contextualize(question)));
 
         LlmClient.TokenUsage totalUsage = LlmClient.TokenUsage.EMPTY;
         for (int i = 0; i < MAX_ITERATIONS; i++) {
@@ -1661,67 +1669,31 @@ class AiPanel {
                 """;
     }
 
+    /**
+     * The static prefix sent with every request. It deliberately contains nothing that changes between turns (the
+     * selected integration travels in the user message instead) so a local model's prompt cache can reuse it, and it
+     * does not repeat the tool list because the tool definitions already carry every description.
+     */
     private String buildSystemPrompt() {
         StringBuilder sb = new StringBuilder();
         sb.append("You are an Apache Camel assistant running inside the Camel TUI terminal console. ");
         sb.append("You help users understand and troubleshoot their running Camel integrations.\n\n");
 
-        String selectedName = mcpFacade != null ? mcpFacade.getSelectedIntegrationName() : null;
-        String selectedPid = mcpFacade != null ? mcpFacade.getSelectedPid() : null;
-        if (selectedName != null && selectedPid != null) {
-            sb.append("The user is monitoring: ").append(selectedName);
-            sb.append(" (PID ").append(selectedPid).append(").\n\n");
-        }
-
-        sb.append("You have tui_* tools to observe and interact with the TUI:\n");
-        sb.append("- tui_get_state: see which tab is active and which integration is selected\n");
-        sb.append("- tui_get_table: get structured data from any tab WITHOUT navigating to it ");
-        sb.append("(Memory, Routes, Endpoints, Health, Process, Threads, Metrics, Startup, Heap Histogram, etc.)\n");
-        sb.append("- tui_get_log: read application logs with filtering, WITHOUT navigating to the Log tab\n");
-        sb.append("- tui_get_errors: get error details with stack traces, WITHOUT navigating to the Errors tab\n");
-        sb.append("- tui_get_diagram: view route diagrams as text, WITHOUT navigating to the Diagram tab\n");
-        sb.append("- tui_get_topology: see how routes connect to each other, WITHOUT navigating to the Topology tab\n");
-        sb.append("- tui_get_processor_detail: get configured options for all processors in a route as structured JSON. ");
-        sb.append("USE THIS to explain what a route does, walk through each step, or understand EIP/component configuration. ");
-        sb.append("Set includeDocs=true to get catalog documentation for each option\n");
-        sb.append("- tui_catalog_doc: look up Camel catalog documentation for any component, EIP, data format, or language\n");
-        sb.append("- tui_get_ai_log: view the AI panel's own activity log (questions, tool calls, responses)\n");
-        sb.append("- tui_get_mcp_log: view the MCP server's tool call log (external client connections and requests)\n");
-        sb.append("- tui_get_history: trace exchange processing steps, WITHOUT navigating to the History tab\n");
-        sb.append("- tui_get_spans: OpenTelemetry span data, WITHOUT navigating to the Spans tab\n");
-        sb.append("- tui_navigate: switch tabs, select integrations, select routes ");
-        sb.append("- ONLY use when the user explicitly wants to change the view\n");
-        sb.append("- tui_control: stop/start routes, restart or stop integrations\n");
-        sb.append("- tui_send_message: send test messages to endpoints\n");
-        sb.append("- tui_filter: set or clear text filters on any tab\n");
-        sb.append("- tui_execute_sql: run SQL queries against a DataSource in the integration\n");
-        sb.append("- tui_set_log_level: change the runtime log level\n");
-        sb.append("- tui_draw_shape: draw shapes (box, highlight, arrow, underline, text) on screen to annotate problems\n");
-        sb.append("- tui_draw_clear: clear drawing overlay\n");
-        sb.append("- tui_locate: find elements on screen by text or diagram node ID, returns coordinates for drawing\n");
-        sb.append("- tui_show_caption: display a message to the user on screen\n");
-        sb.append("- tui_action: invoke TUI actions (reset-stats, screenshot, toggle-theme, etc.)\n");
-        sb.append("- tui_get_themes / tui_set_theme: list and switch TUI themes\n");
-        sb.append("- tui_get_files / tui_get_readme: read source files and README from integrations\n");
-        sb.append("- tui_update_row: update a database row via PreparedStatement\n");
-        sb.append("- tui_set_input: set input field values on tabs directly\n");
-        sb.append("- tui_toggle_trace_display: control which sections show in History detail view\n");
-        sb.append("- tui_canvas_open / tui_canvas_close: open/close a blank canvas for free-form drawing\n");
-        sb.append("- tui_animate: run built-in animations on the canvas\n");
-        sb.append("- tui_send_keys: send key presses to the TUI\n");
-        sb.append("- tui_get_events: see recent user interaction events\n");
-        sb.append("- tui_tape_start / tui_tape_stop: record TUI interactions as .tape files\n");
-        sb.append("- tui_wait_for_idle / tui_sleep: timing tools for pacing interactions\n\n");
+        sb.append("You have tui_* tools to observe and interact with the TUI; the tool definitions describe each one. ");
+        sb.append("All tui_get_* tools fetch data directly from any tab without changing what the user sees.\n\n");
         sb.append("Guidelines:\n");
-        sb.append("- NEVER call tui_navigate just to read data ");
-        sb.append("- all tui_get_* tools fetch data directly from any tab without changing the active tab\n");
+        sb.append("- NEVER call tui_navigate just to read data - use the tui_get_* tools instead\n");
         sb.append("- Prefer tui_get_table over tui_get_screen for structured data ");
-        sb.append("- it fetches from any tab directly using the tab parameter, no navigation needed\n");
-        sb.append("- Use tui_get_state first to understand context before acting, if needed\n");
+        sb.append("- it fetches from any tab using the tab parameter, no navigation needed\n");
+        sb.append("- Call tui_get_options only when unsure which tab holds the data you need\n");
+        sb.append("- Use tui_get_state to learn which integration and tab is selected, if the question depends on it\n");
+        sb.append("- Use tui_get_processor_detail to explain what a route does or how its steps are configured\n");
         sb.append("- Be concise and actionable in your answers\n");
         sb.append("- When something looks wrong, explain what it means and suggest fixes\n");
         sb.append("- For stopping routes or applications, use tui_control for graceful shutdown\n");
-        sb.append("- Use tui_locate + tui_draw_shape to visually highlight problems on screen for the user\n");
+        if (!useCoreTools()) {
+            sb.append("- Use tui_locate + tui_draw_shape to visually highlight problems on screen for the user\n");
+        }
         if (mcpServerActive) {
             sb.append("\nThe TUI MCP server is available at http://localhost:")
                     .append(mcpServerPort).append("/mcp for external AI agents.");
@@ -1729,12 +1701,54 @@ class AiPanel {
         return sb.toString();
     }
 
+    /**
+     * Prefixes the question with the integration the user is looking at. This used to live in the system prompt, but
+     * there it invalidated the model's cached prompt prefix every time the selection changed.
+     */
+    private String contextualize(String question) {
+        String selectedName = mcpFacade != null ? mcpFacade.getSelectedIntegrationName() : null;
+        String selectedPid = mcpFacade != null ? mcpFacade.getSelectedPid() : null;
+        if (selectedName != null && selectedPid != null) {
+            return "[Monitoring " + selectedName + " (PID " + selectedPid + ")]\n" + question;
+        }
+        return question;
+    }
+
+    /**
+     * Whether only the {@link TuiToolRegistry#CORE_TOOLS} are sent: always in {@code core} mode, never in {@code full}
+     * mode, and for local providers in {@code auto} mode.
+     */
+    private boolean useCoreTools() {
+        String mode = toolMode == null ? TOOL_MODE_AUTO : toolMode;
+        if (TOOL_MODE_CORE.equals(mode)) {
+            return true;
+        }
+        if (TOOL_MODE_FULL.equals(mode)) {
+            return false;
+        }
+        return client != null && client.isLocalEndpoint();
+    }
+
+    private String describeToolMode() {
+        if (toolRegistry == null) {
+            return "no tools available";
+        }
+        int total = toolRegistry.getToolDefinitions().size();
+        int active = useCoreTools() ? toolRegistry.getCoreToolDefinitions().size() : total;
+        String mode = toolMode == null ? TOOL_MODE_AUTO : toolMode;
+        String detail = TOOL_MODE_AUTO.equals(mode)
+                ? (useCoreTools() ? " (local provider)" : " (hosted provider)") : "";
+        return (useCoreTools() ? "core" : "full") + " (" + active + " of " + total + " tools), mode " + mode + detail;
+    }
+
     private List<LlmClient.ToolDef> buildTuiToolDefinitions() {
         if (toolRegistry == null) {
             return List.of();
         }
         List<LlmClient.ToolDef> defs = new ArrayList<>();
-        for (TuiToolRegistry.ToolDef td : toolRegistry.getToolDefinitions()) {
+        List<TuiToolRegistry.ToolDef> source
+                = useCoreTools() ? toolRegistry.getCoreToolDefinitions() : toolRegistry.getToolDefinitions();
+        for (TuiToolRegistry.ToolDef td : source) {
             defs.add(new LlmClient.ToolDef(td.name(), td.description(), td.inputSchema()));
         }
         return defs;
@@ -1841,6 +1855,41 @@ class AiPanel {
         return inputBuffer.toString();
     }
 
+    /**
+     * Maps a configured tool mode to {@code auto}, {@code core} or {@code full}; blank means {@code auto}, anything
+     * else is rejected with {@code null}.
+     */
+    static String normalizeToolMode(String mode) {
+        if (mode == null || mode.isBlank()) {
+            return TOOL_MODE_AUTO;
+        }
+        String value = mode.trim().toLowerCase();
+        return switch (value) {
+            case TOOL_MODE_AUTO, TOOL_MODE_CORE, TOOL_MODE_FULL -> value;
+            default -> null;
+        };
+    }
+
+    void setToolRegistryForTesting(TuiToolRegistry registry) {
+        this.toolRegistry = registry;
+    }
+
+    void setToolModeForTesting(String mode) {
+        this.toolMode = normalizeToolMode(mode);
+    }
+
+    String systemPromptForTesting() {
+        return buildSystemPrompt();
+    }
+
+    List<LlmClient.ToolDef> toolDefinitionsForTesting() {
+        return buildTuiToolDefinitions();
+    }
+
+    String describeToolModeForTesting() {
+        return describeToolMode();
+    }
+
     void setExitCallbackForTestingOrRuntime(Runnable callback) {
         this.exitCallback = callback;
     }
@@ -1918,6 +1967,24 @@ class AiPanel {
             return ctx != null ? ctx.selectedName() : null;
         }
 
+        @Override
+        public String describeToolMode() {
+            return AiPanel.this.describeToolMode();
+        }
+
+        @Override
+        public boolean switchToolMode(String mode) {
+            String normalized = normalizeToolMode(mode);
+            if (normalized == null) {
+                return false;
+            }
+            toolMode = normalized;
+            TuiSettings settings = TuiSettings.load();
+            settings.setAiTools(TOOL_MODE_AUTO.equals(normalized) ? null : normalized);
+            settings.save();
+            return true;
+        }
+
         @Override
         public CompletableFuture<AiCliCommandExecutor.Result> executeCli(AiCliCommandExecutor.Request request) {
             return cliCommandExecutor.executeAsync(request);
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandContext.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandContext.java
index 98e6b7adee33..3afa1cc4b74b 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandContext.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandContext.java
@@ -42,6 +42,17 @@ interface AiSlashCommandContext {
 
     String selectedProcessName();
 
+    /**
+     * Describes the tool set currently sent to the model, for example {@code core (18 of 46 tools), mode auto}.
+     */
+    String describeToolMode();
+
+    /**
+     * Switches the tool mode to {@code auto}, {@code core} or {@code full} and persists it. Returns {@code false} when
+     * the mode is not one of those values.
+     */
+    boolean switchToolMode(String mode);
+
     CompletableFuture<AiCliCommandExecutor.Result> executeCli(AiCliCommandExecutor.Request request);
 
     void cancelCli();
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandRegistry.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandRegistry.java
index 12b1a3f6481d..9b4f580c83fd 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandRegistry.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandRegistry.java
@@ -68,6 +68,9 @@ final class AiSlashCommandRegistry {
         commands.add(new Descriptor(
                 "model", List.of("m"), "Show or switch the AI model", "<model>",
                 AiSlashCommandRegistry::executeModel));
+        commands.add(new Descriptor(
+                "tools", List.of("t"), "Show or switch the tool set sent to the model", "[auto|core|full]",
+                AiSlashCommandRegistry::executeTools));
         commands.add(new Descriptor(
                 "clear", List.of("c"), "Clear the conversation", null,
                 (context, arguments) -> {
@@ -296,6 +299,17 @@ final class AiSlashCommandRegistry {
         return CommandResult.listModels();
     }
 
+    private static CommandResult executeTools(AiSlashCommandContext context, String arguments) {
+        if (arguments.isBlank()) {
+            return CommandResult.system("Tool set: " + context.describeToolMode());
+        }
+        String mode = arguments.trim().toLowerCase();
+        if (!context.switchToolMode(mode)) {
+            return CommandResult.error("Unknown tool mode '" + arguments.trim() + "'. Use auto, core or full.");
+        }
+        return CommandResult.system("Tool set: " + context.describeToolMode());
+    }
+
     private static int firstWhitespace(String value) {
         for (int i = 0; i < value.length(); i++) {
             if (Character.isWhitespace(value.charAt(i))) {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettings.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettings.java
index 542aba850790..c6ababc82217 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettings.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettings.java
@@ -39,6 +39,7 @@ final class TuiSettings {
     static final String PROP_AI_PROVIDER = "camel.tui.ai.provider";
     static final String PROP_AI_MODEL = "camel.tui.ai.model";
     static final String PROP_AI_URL = "camel.tui.ai.url";
+    static final String PROP_AI_TOOLS = "camel.tui.ai.tools";
     static final String PROP_PROXY_HOST = "camel.tui.proxyHost";
     static final String PROP_PROXY_PORT = "camel.tui.proxyPort";
     static final String PROP_SHELL_HISTORY = "camel.tui.shell.history";
@@ -59,6 +60,7 @@ final class TuiSettings {
     private String aiProvider;
     private String aiModel;
     private String aiUrl;
+    private String aiTools;
     private String shellHistory;
     private String aiPromptHistory;
     private String confirmActions;
@@ -154,6 +156,18 @@ final class TuiSettings {
         this.aiUrl = aiUrl;
     }
 
+    /**
+     * Which tui_* tools the AI panel sends to the model: {@code auto} (default: the core set for local providers, all
+     * tools otherwise), {@code core} or {@code full}.
+     */
+    String getAiTools() {
+        return aiTools;
+    }
+
+    void setAiTools(String aiTools) {
+        this.aiTools = aiTools;
+    }
+
     String getShellHistory() {
         return shellHistory;
     }
@@ -247,6 +261,7 @@ final class TuiSettings {
             settings.aiProvider = trimToNull(TuiUserConfig.read(PROP_AI_PROVIDER));
             settings.aiModel = trimToNull(TuiUserConfig.read(PROP_AI_MODEL));
             settings.aiUrl = trimToNull(TuiUserConfig.read(PROP_AI_URL));
+            settings.aiTools = trimToNull(TuiUserConfig.read(PROP_AI_TOOLS));
             settings.shellHistory = trimToNull(TuiUserConfig.read(PROP_SHELL_HISTORY));
             settings.aiPromptHistory = trimToNull(TuiUserConfig.read(PROP_AI_PROMPT_HISTORY));
             settings.confirmActions = trimToNull(TuiUserConfig.read(PROP_CONFIRM_ACTIONS));
@@ -277,6 +292,7 @@ final class TuiSettings {
             TuiUserConfig.write(PROP_AI_PROVIDER, aiProvider);
             TuiUserConfig.write(PROP_AI_MODEL, aiModel);
             TuiUserConfig.write(PROP_AI_URL, aiUrl);
+            TuiUserConfig.write(PROP_AI_TOOLS, aiTools);
             TuiUserConfig.write(PROP_SHELL_HISTORY, shellHistory);
             TuiUserConfig.write(PROP_AI_PROMPT_HISTORY, aiPromptHistory);
             TuiUserConfig.write(PROP_CONFIRM_ACTIONS, confirmActions);
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
index c1263c518536..03bbb0fc4caf 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
@@ -19,6 +19,7 @@ package org.apache.camel.dsl.jbang.core.commands.tui;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import dev.tamboui.buffer.Buffer;
@@ -79,7 +80,19 @@ class TuiToolRegistry {
     }
 
     /**
-     * Returns all 42 tool definitions. The result is cached since it is immutable.
+     * The tools needed to answer questions and troubleshoot from the built-in AI panel. The remaining tools drive the
+     * screen (drawing, animation, key presses, tape recording, themes) and exist for external MCP agents. Every tool
+     * schema is sent on every request, and a local model pays for that in prompt-processing time, so the AI panel sends
+     * only this subset to local providers unless configured otherwise.
+     */
+    static final Set<String> CORE_TOOLS = Set.of(
+            "tui_get_state", "tui_get_options", "tui_get_table", "tui_get_log", "tui_get_errors",
+            "tui_get_diagram", "tui_get_topology", "tui_get_processor_detail", "tui_catalog_doc",
+            "tui_get_history", "tui_get_spans", "tui_control", "tui_send_message", "tui_get_files",
+            "tui_get_readme", "tui_navigate", "tui_set_log_level", "tui_filter");
+
+    /**
+     * Returns all tool definitions. The result is cached since it is immutable.
      */
     List<ToolDef> getToolDefinitions() {
         List<ToolDef> tools = cachedTools;
@@ -91,6 +104,13 @@ class TuiToolRegistry {
         return tools;
     }
 
+    /**
+     * Returns only the {@link #CORE_TOOLS} definitions, in registry order.
+     */
+    List<ToolDef> getCoreToolDefinitions() {
+        return getToolDefinitions().stream().filter(t -> CORE_TOOLS.contains(t.name())).toList();
+    }
+
     /**
      * Executes a tool by name, returns result string.
      */
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
index 41dee94aa795..9da0a15db472 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
@@ -728,6 +728,67 @@ class AiPanelTest {
         assertEquals("/clear-history", panel.inputBufferForTesting());
     }
 
+    // ---- tool set and system prompt tests ----
+
+    @Test
+    void localProviderGetsCoreToolsAndHostedProviderGetsAll() {
+        AiPanel panel = new AiPanel();
+        panel.setToolRegistryForTesting(new TuiToolRegistry(null));
+        RecordingLlmClient client = new RecordingLlmClient("ok");
+        panel.setClientForTesting(client);
+
+        // auto mode: a hosted provider gets every tool
+        assertEquals(new TuiToolRegistry(null).getToolDefinitions().size(), panel.toolDefinitionsForTesting().size());
+        assertTrue(panel.systemPromptForTesting().contains("tui_draw_shape"));
+
+        // auto mode: a local provider only gets the core set, and the prompt no longer suggests drawing tools
+        client.withApiType(LlmClient.ApiType.ollama);
+        assertEquals(TuiToolRegistry.CORE_TOOLS.size(), panel.toolDefinitionsForTesting().size());
+        assertTrue(panel.toolDefinitionsForTesting().stream()
+                .allMatch(def -> TuiToolRegistry.CORE_TOOLS.contains(def.name())));
+        assertFalse(panel.systemPromptForTesting().contains("tui_draw_shape"));
+        assertTrue(panel.describeToolModeForTesting().startsWith("core (18 of "));
+    }
+
+    @Test
+    void explicitToolModeOverridesProviderDetection() {
+        AiPanel panel = new AiPanel();
+        panel.setToolRegistryForTesting(new TuiToolRegistry(null));
+        RecordingLlmClient client = new RecordingLlmClient("ok");
+        client.withApiType(LlmClient.ApiType.ollama);
+        panel.setClientForTesting(client);
+
+        panel.setToolModeForTesting("full");
+        assertEquals(new TuiToolRegistry(null).getToolDefinitions().size(), panel.toolDefinitionsForTesting().size());
+
+        panel.setToolModeForTesting("core");
+        client.withApiType(LlmClient.ApiType.openai);
+        assertEquals(TuiToolRegistry.CORE_TOOLS.size(), panel.toolDefinitionsForTesting().size());
+    }
+
+    @Test
+    void systemPromptIsStableAndDoesNotRepeatTheToolList() {
+        AiPanel panel = new AiPanel();
+        panel.setToolRegistryForTesting(new TuiToolRegistry(null));
+        panel.setClientForTesting(new RecordingLlmClient("ok"));
+
+        String prompt = panel.systemPromptForTesting();
+
+        // the tool definitions already describe every tool, so the prompt must not list them again
+        assertFalse(prompt.contains("- tui_get_table:"));
+        assertFalse(prompt.contains("The user is monitoring"));
+        assertEquals(prompt, panel.systemPromptForTesting());
+    }
+
+    @Test
+    void normalizeToolModeAcceptsKnownValuesOnly() {
+        assertEquals("auto", AiPanel.normalizeToolMode(null));
+        assertEquals("auto", AiPanel.normalizeToolMode("  "));
+        assertEquals("core", AiPanel.normalizeToolMode("Core"));
+        assertEquals("full", AiPanel.normalizeToolMode("FULL"));
+        assertNull(AiPanel.normalizeToolMode("bogus"));
+    }
+
     // ---- paste tests ----
 
     @Test
@@ -853,6 +914,16 @@ class AiPanelTest {
 
     static final class FakeSlashContext implements AiSlashCommandContext {
 
+        @Override
+        public String describeToolMode() {
+            return "full (46 of 46 tools), mode auto";
+        }
+
+        @Override
+        public boolean switchToolMode(String mode) {
+            return true;
+        }
+
         boolean exitRequested;
         boolean cancelRequested;
         boolean providerSwitchRequested;
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandRegistryTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandRegistryTest.java
index 37f18f37375f..30ecddcfaba9 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandRegistryTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiSlashCommandRegistryTest.java
@@ -33,7 +33,9 @@ class AiSlashCommandRegistryTest {
     void descriptorsKeepStableOrder() {
         AiSlashCommandRegistry registry = AiSlashCommandRegistry.defaults();
 
-        assertEquals(List.of("help", "provider", "model", "clear", "clear-history", "close", "quit", "run", "infra", "send"),
+        assertEquals(
+                List.of("help", "provider", "model", "tools", "clear", "clear-history", "close", "quit", "run", "infra",
+                        "send"),
                 registry.descriptors().stream().map(AiSlashCommandRegistry.Descriptor::name).toList());
     }
 
@@ -73,7 +75,7 @@ class AiSlashCommandRegistryTest {
     void completionsIncludeAllCommandsForBareSlash() {
         AiSlashCommandRegistry registry = AiSlashCommandRegistry.defaults();
 
-        assertEquals(10, registry.completionsFor("/").size());
+        assertEquals(11, registry.completionsFor("/").size());
         assertFalse(registry.completionsFor("/").stream().anyMatch(descriptor -> "exit".equals(descriptor.name())));
     }
 
@@ -272,8 +274,71 @@ class AiSlashCommandRegistryTest {
         }
     }
 
+    @Test
+    void toolsWithoutArgumentsDescribesCurrentToolSet() {
+        AiSlashCommandRegistry registry = AiSlashCommandRegistry.defaults();
+        ToolModeContext context = new ToolModeContext();
+
+        AiSlashCommandRegistry.CommandResult result = registry.execute("/tools", context);
+
+        assertEquals("Tool set: core (18 of 46 tools), mode auto", result.text());
+        assertNull(context.switchedTo);
+    }
+
+    @Test
+    void toolsSwitchesModeCaseInsensitively() {
+        AiSlashCommandRegistry registry = AiSlashCommandRegistry.defaults();
+        ToolModeContext context = new ToolModeContext();
+
+        AiSlashCommandRegistry.CommandResult result = registry.execute("/t Full", context);
+
+        assertEquals("full", context.switchedTo);
+        assertEquals(AiRole.SYSTEM, result.role());
+    }
+
+    @Test
+    void toolsRejectsUnknownMode() {
+        AiSlashCommandRegistry registry = AiSlashCommandRegistry.defaults();
+        ToolModeContext context = new ToolModeContext();
+
+        AiSlashCommandRegistry.CommandResult result = registry.execute("/tools bogus", context);
+
+        assertEquals(AiRole.ERROR, result.role());
+        assertTrue(result.text().contains("bogus"));
+        assertNull(context.switchedTo);
+    }
+
+    private static final class ToolModeContext extends NoopSlashContext {
+
+        private String switchedTo;
+
+        @Override
+        public String describeToolMode() {
+            return "core (18 of 46 tools), mode auto";
+        }
+
+        @Override
+        public boolean switchToolMode(String mode) {
+            if (!List.of("auto", "core", "full").contains(mode)) {
+                return false;
+            }
+            switchedTo = mode;
+            return true;
+        }
+    }
+
     private static class NoopSlashContext implements AiSlashCommandContext {
 
+        @Override
+        public String describeToolMode() {
+            return "";
+        }
+
+        @Override
+        public boolean switchToolMode(String mode) {
+            return false;
+        }
+
         @Override
         public void closePanel() {
         }
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettingsTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettingsTest.java
index 53da3f8a7649..00ba4ad323fe 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettingsTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiSettingsTest.java
@@ -63,6 +63,7 @@ class TuiSettingsTest {
         settings.setAiProvider("gemini");
         settings.setAiModel("gemini-3.5-flash");
         settings.setAiUrl("https://generativelanguage.googleapis.com");
+        settings.setAiTools("core");
         settings.setShellHistory("25");
         settings.setAiPromptHistory("50");
         settings.setPanelPosition("top");
@@ -76,6 +77,7 @@ class TuiSettingsTest {
         assertThat(loaded.getAiProvider()).isEqualTo("gemini");
         assertThat(loaded.getAiModel()).isEqualTo("gemini-3.5-flash");
         assertThat(loaded.getAiUrl()).isEqualTo("https://generativelanguage.googleapis.com");
+        assertThat(loaded.getAiTools()).isEqualTo("core");
         assertThat(loaded.getShellHistory()).isEqualTo("25");
         assertThat(loaded.getAiPromptHistory()).isEqualTo("50");
         assertThat(loaded.getPanelPosition()).isEqualTo("top");
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCoreToolsTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCoreToolsTest.java
new file mode 100644
index 000000000000..b38d749ce48f
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCoreToolsTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.tui;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class TuiToolRegistryCoreToolsTest {
+
+    @Test
+    void everyCoreToolExistsInTheRegistry() {
+        TuiToolRegistry registry = new TuiToolRegistry(null);
+        Set<String> all = registry.getToolDefinitions().stream()
+                .map(TuiToolRegistry.ToolDef::name).collect(Collectors.toSet());
+
+        assertTrue(all.containsAll(TuiToolRegistry.CORE_TOOLS),
+                "core tools missing from registry: " + TuiToolRegistry.CORE_TOOLS.stream()
+                        .filter(name -> !all.contains(name)).toList());
+    }
+
+    @Test
+    void coreDefinitionsAreTheCoreSubsetInRegistryOrder() {
+        TuiToolRegistry registry = new TuiToolRegistry(null);
+        List<TuiToolRegistry.ToolDef> core = registry.getCoreToolDefinitions();
+        List<TuiToolRegistry.ToolDef> all = registry.getToolDefinitions();
+
+        assertEquals(TuiToolRegistry.CORE_TOOLS.size(), core.size());
+        assertTrue(core.size() < all.size());
+        assertTrue(core.stream().allMatch(def -> TuiToolRegistry.CORE_TOOLS.contains(def.name())));
+        assertEquals(all.stream().filter(def -> TuiToolRegistry.CORE_TOOLS.contains(def.name())).toList(), core);
+    }
+
+    @Test
+    void coreSetLeavesOutScreenAutomationTools() {
+        Set<String> automation = Set.of("tui_draw", "tui_draw_shape", "tui_animate", "tui_send_keys", "tui_sleep",
+                "tui_tape_start", "tui_canvas_open", "tui_set_theme");
+
+        assertFalse(TuiToolRegistry.CORE_TOOLS.stream().anyMatch(automation::contains));
+    }
+}


(camel) 02/07: Camel TUI: TAB completes the model name after /model and the mode after /tools in the AI panel

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 08bff85d5dc99ec875cb00b9a5f6842ef7b58e95
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Tue Sep 8 16:21:17 2026 +0200

    Camel TUI: TAB completes the model name after /model and the mode after /tools in the AI panel
    
    The model list comes from the provider (the same call the bare /model listing
    uses), fetched once in the background on the first TAB and cached until the
    provider or client changes. Completion follows the existing rules: longest
    common prefix first, then cycling, Shift+TAB backward.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
 .../modules/ROOT/pages/camel-jbang-tui.adoc        |   6 ++
 .../camel/dsl/jbang/core/commands/tui/AiPanel.java | 107 +++++++++++++++++++--
 .../dsl/jbang/core/commands/tui/AiPanelTest.java   |  61 ++++++++++++
 3 files changed, 168 insertions(+), 6 deletions(-)

diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
index 96cef22d9c49..49380e035949 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
@@ -875,6 +875,12 @@ Use *F2* -> _MCP Info_ to see server details and _MCP Log_ to view the tool call
 
 When the AI panel is open, input that starts with `/` runs a local panel command instead of sending a question to the configured AI provider. `/provider` and `/model` are unavailable while a response or command is already in progress; the panel shows a message asking you to wait.
 
+Press *Tab* to complete a command name. After `/model ` *Tab* completes the model name against the
+models the current provider reports (the list is fetched in the background on the first press, so
+press *Tab* again once it has arrived), and after `/tools ` it completes `auto`, `core` or `full`.
+With several matches *Tab* fills in the common prefix and then cycles through them; *Shift+Tab*
+cycles backward.
+
 [cols="1,3",options="header"]
 |===
 | Command | Description
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
index 5e0107cafffc..1aa3722125bf 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
@@ -116,6 +116,13 @@ class AiPanel {
     private List<String> completionMatches;
     private int completionCycleIndex = -1;
     private String completionSnapshot;
+    // Buffer offset of the token being completed: 1 for a command name (after the slash), or the start of the
+    // first argument for commands that complete arguments (/model, /tools).
+    private int completionStart = 1;
+    // Models offered by TAB after "/model ". Fetched once in the background (a provider round trip) on the first TAB
+    // and reset whenever the client or provider changes.
+    private volatile List<String> modelCompletionCache;
+    private final AtomicBoolean modelCompletionFetch = new AtomicBoolean();
 
     // Conversation display. CopyOnWriteArrayList because entries are appended from the agent thread and the
     // CLI-command-completion callback while the render thread iterates the list concurrently.
@@ -300,6 +307,7 @@ class AiPanel {
     }
 
     private void initClient() {
+        modelCompletionCache = null;
         try {
             LlmClient created = LlmClient.create()
                     .withTemperature(0.3)
@@ -641,6 +649,13 @@ class AiPanel {
      * reachable with TAB alone). A single match is completed fully and a trailing space is appended. Shift+TAB cycles
      * backward. TAB is a no-op unless the buffer is a partial command name (starts with {@code /}, no arguments yet).
      */
+    /**
+     * Completes the slash command name at the cursor, or the first argument of {@code /model} (against the models the
+     * provider reports) and {@code /tools} (auto, core, full). With multiple matches, TAB first fills in the longest
+     * common prefix; once no further prefix can be added it cycles forward through the matches (wrapping so every match
+     * is reachable with TAB alone). A single match is completed fully and a trailing space is appended. Shift+TAB
+     * cycles backward.
+     */
     private void handleTabCompletion(boolean backward) {
         String text = inputBuffer.toString();
         boolean continuing = text.equals(completionSnapshot) && completionMatches != null && completionMatches.size() > 1;
@@ -657,9 +672,20 @@ class AiPanel {
             return;
         }
 
-        List<String> names = slashCommands.completionsFor(text).stream()
-                .map(AiSlashCommandRegistry.Descriptor::name)
-                .toList();
+        List<String> names;
+        String currentToken;
+        ArgumentCompletion argument = argumentCompletion(text);
+        if (argument != null) {
+            names = argument.candidates();
+            currentToken = argument.token();
+            completionStart = argument.start();
+        } else {
+            names = slashCommands.completionsFor(text).stream()
+                    .map(AiSlashCommandRegistry.Descriptor::name)
+                    .toList();
+            currentToken = text.length() > 1 ? text.substring(1) : "";
+            completionStart = 1;
+        }
         if (names.isEmpty()) {
             completionMatches = null;
             completionCycleIndex = -1;
@@ -674,7 +700,6 @@ class AiPanel {
             completionSnapshot = null;
             return;
         }
-        String currentToken = text.substring(1);
         String prefix = longestCommonPrefix(names);
         completionMatches = names;
         if (prefix.length() > currentToken.length()) {
@@ -686,9 +711,78 @@ class AiPanel {
         }
     }
 
+    private record ArgumentCompletion(int start, String token, List<String> candidates) {
+    }
+
+    /**
+     * Returns the argument completion for {@code /model <prefix>} or {@code /tools <prefix>} (aliases included), or
+     * {@code null} when the buffer is not at the first argument of one of those commands. The model list comes from the
+     * provider, so the first TAB kicks off a background fetch and returns nothing; TAB again once it is loaded.
+     */
+    private ArgumentCompletion argumentCompletion(String text) {
+        if (!text.startsWith("/")) {
+            return null;
+        }
+        int separator = -1;
+        for (int i = 1; i < text.length(); i++) {
+            if (Character.isWhitespace(text.charAt(i))) {
+                separator = i;
+                break;
+            }
+        }
+        if (separator < 0) {
+            return null;
+        }
+        Optional<AiSlashCommandRegistry.Descriptor> descriptor = slashCommands.lookup(text.substring(1, separator));
+        if (descriptor.isEmpty()) {
+            return null;
+        }
+        int start = separator;
+        while (start < text.length() && Character.isWhitespace(text.charAt(start))) {
+            start++;
+        }
+        String token = text.substring(start);
+        if (token.chars().anyMatch(Character::isWhitespace)) {
+            return null;
+        }
+        List<String> candidates = switch (descriptor.get().name()) {
+            case "model" -> modelCompletionCandidates();
+            case "tools" -> List.of(TOOL_MODE_AUTO, TOOL_MODE_CORE, TOOL_MODE_FULL);
+            default -> null;
+        };
+        if (candidates == null) {
+            return null;
+        }
+        String lower = token.toLowerCase();
+        List<String> matches = candidates.stream()
+                .filter(candidate -> candidate.toLowerCase().startsWith(lower))
+                .toList();
+        return new ArgumentCompletion(start, token, matches);
+    }
+
+    private List<String> modelCompletionCandidates() {
+        List<String> cached = modelCompletionCache;
+        if (cached != null) {
+            return cached;
+        }
+        if (client != null && modelCompletionFetch.compareAndSet(false, true)) {
+            conversation.add(new ConversationEntry(AiRole.SYSTEM, "Fetching available models, press TAB again..."));
+            Thread worker = new Thread(() -> {
+                try {
+                    modelCompletionCache = slashCommandContext.availableModels();
+                } finally {
+                    modelCompletionFetch.set(false);
+                }
+            }, "tui-ai-model-completion");
+            worker.setDaemon(true);
+            worker.start();
+        }
+        return List.of();
+    }
+
     private void applyCompletionToken(String token, boolean trailingSpace) {
-        inputBuffer.setLength(0);
-        inputBuffer.append('/').append(token);
+        inputBuffer.setLength(completionStart);
+        inputBuffer.append(token);
         if (trailingSpace) {
             inputBuffer.append(' ');
         }
@@ -781,6 +875,7 @@ class AiPanel {
         conversation.add(new ConversationEntry(AiRole.SYSTEM, "Fetching available models..."));
         Thread worker = new Thread(() -> {
             List<String> models = slashCommandContext.availableModels();
+            modelCompletionCache = models;
             conversation.add(new ConversationEntry(
                     AiRole.SYSTEM,
                     AiSlashCommandRegistry.formatModelListing(slashCommandContext.currentModel(), models)));
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
index 9da0a15db472..51b912a2564f 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelTest.java
@@ -728,6 +728,67 @@ class AiPanelTest {
         assertEquals("/clear-history", panel.inputBufferForTesting());
     }
 
+    // ---- argument completion tests ----
+
+    @Test
+    void tabCompletesModelNameFromProviderList() {
+        AiPanel panel = new AiPanel();
+        panel.setClientForTesting(new ModelListingLlmClient(List.of("qwen3.6:35b-a3b", "llama3.3:70b")));
+        panel.open();
+        type(panel, "/model qw");
+
+        // The first TAB only starts the background fetch of the model list; once it has arrived TAB completes.
+        tab(panel);
+        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
+            tab(panel);
+            assertEquals("/model qwen3.6:35b-a3b ", panel.inputBufferForTesting());
+        });
+    }
+
+    @Test
+    void tabCyclesModelsSharingAPrefixAndHonoursAliases() {
+        AiPanel panel = new AiPanel();
+        panel.setClientForTesting(new ModelListingLlmClient(List.of("qwen2.5:14b", "qwen2.5:32b", "hermes3:8b")));
+        panel.open();
+        type(panel, "/m q");
+
+        tab(panel);
+        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
+            tab(panel);
+            assertEquals("/m qwen2.5:", panel.inputBufferForTesting());
+        });
+
+        // No further common prefix, so TAB cycles through the matches and wraps around.
+        tab(panel);
+        assertEquals("/m qwen2.5:14b", panel.inputBufferForTesting());
+        tab(panel);
+        assertEquals("/m qwen2.5:32b", panel.inputBufferForTesting());
+        tab(panel);
+        assertEquals("/m qwen2.5:14b", panel.inputBufferForTesting());
+    }
+
+    @Test
+    void tabCompletesToolModeArgument() {
+        AiPanel panel = new AiPanel();
+        panel.open();
+        type(panel, "/tools c");
+
+        tab(panel);
+
+        assertEquals("/tools core ", panel.inputBufferForTesting());
+    }
+
+    @Test
+    void tabDoesNotCompleteArgumentsOfOtherCommands() {
+        AiPanel panel = new AiPanel();
+        panel.open();
+        type(panel, "/run --exam");
+
+        tab(panel);
+
+        assertEquals("/run --exam", panel.inputBufferForTesting());
+    }
+
     // ---- tool set and system prompt tests ----
 
     @Test


(camel) 06/07: CAMEL-24656: camel-jbang TUI - trim verbose tool descriptions and cap the AI panel history

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit d0091452c3892300f9f5c40b44847c9e812138a5
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Tue Sep 8 17:22:56 2026 +0200

    CAMEL-24656: camel-jbang TUI - trim verbose tool descriptions and cap the AI panel history
    
    Shorten the descriptions and schemas of the largest tools (tui_draw,
    tui_draw_shape, tui_catalog_doc, tui_navigate, tui_get_state, tui_get_options,
    tui_get_status) without dropping any parameter; tui_draw no longer repeats the
    tui_draw_shape vocabulary, and tui_get_options no longer tells the model to
    call it first on every task. The full tool set drops from ~7.3k to ~6.6k
    tokens and the core set to ~2.7k.
    
    The model history is now bounded: a tool result is capped at 16k characters
    when it enters the history (the AI log keeps the full text), tool results from
    turns before the previous one are compacted to their first 400 characters
    once a turn is answered, and the oldest turns are dropped beyond 20 questions.
    Whole turns are removed so tool calls never lose their matching results.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
 .../camel/dsl/jbang/core/commands/tui/AiPanel.java |  81 ++++++++++++-
 .../jbang/core/commands/tui/TuiToolRegistry.java   | 130 +++++++--------------
 .../commands/tui/AiPanelHistoryCompactionTest.java | 106 +++++++++++++++++
 3 files changed, 227 insertions(+), 90 deletions(-)

diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
index a640ec44cc02..a11279f6aace 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
@@ -72,6 +72,21 @@ import org.apache.camel.util.json.JsonObject;
 class AiPanel {
 
     private static final int MAX_ITERATIONS = 10;
+    /**
+     * Longest tool result handed to the model. The AI log keeps the full text; the model gets the head plus a note,
+     * because a single log or table dump can otherwise be larger than the whole system prompt.
+     */
+    static final int MAX_TOOL_RESULT_CHARS = 16_000;
+    /**
+     * Tool results from turns before the previous one are shrunk to this many characters once the turn is answered. The
+     * model's own answer already summarises them, and the whole history is re-sent (and re-processed by a local model)
+     * on every request.
+     */
+    static final int COMPACT_TOOL_RESULT_CHARS = 400;
+    /**
+     * Oldest turns are dropped beyond this many user questions in one conversation.
+     */
+    static final int MAX_HISTORY_TURNS = 20;
     private static final int MAX_LOG_ENTRIES = 200;
     private static final DateTimeFormatter TIME_FMT
             = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.systemDefault());
@@ -1035,7 +1050,7 @@ class AiPanel {
                     log(LogLevel.TOOL, toolCall.name(), toolCall.arguments().toJson());
                     String result = executeTuiTool(toolCall.name(), toolCall.arguments());
                     log(LogLevel.RESULT, toolCall.name(), result);
-                    results.add(new LlmClient.ToolResult(toolCall.id(), result));
+                    results.add(new LlmClient.ToolResult(toolCall.id(), truncateToolResult(result)));
                 }
                 messages.add(LlmClient.Message.toolResults(results));
             } else {
@@ -1055,6 +1070,7 @@ class AiPanel {
                 }
                 scrollOffset = 0;
                 messages.add(LlmClient.Message.assistantWithToolCalls(text, List.of()));
+                compactHistory(messages, MAX_HISTORY_TURNS, COMPACT_TOOL_RESULT_CHARS);
                 return;
             }
         }
@@ -1856,6 +1872,69 @@ class AiPanel {
         return defs;
     }
 
+    /**
+     * Caps a tool result before it enters the model history; the AI log keeps the full text.
+     */
+    static String truncateToolResult(String result) {
+        if (result == null || result.length() <= MAX_TOOL_RESULT_CHARS) {
+            return result;
+        }
+        return result.substring(0, MAX_TOOL_RESULT_CHARS)
+               + "\n... [truncated, " + (result.length() - MAX_TOOL_RESULT_CHARS)
+               + " more characters; narrow the request (filter, limit, section) to see the rest]";
+    }
+
+    /**
+     * Keeps the model history bounded after a turn is answered: tool results from turns before the previous one are
+     * shrunk to their head, and the oldest turns are dropped beyond {@code maxTurns} user questions. The previous turn
+     * is kept intact so an immediate follow-up can still refer to what was just fetched. Whole turns are removed (user
+     * message through the final answer) so assistant tool calls never lose their matching results.
+     */
+    static void compactHistory(List<LlmClient.Message> history, int maxTurns, int compactChars) {
+        if (history == null || history.isEmpty()) {
+            return;
+        }
+        List<Integer> userIndexes = new ArrayList<>();
+        for (int i = 0; i < history.size(); i++) {
+            LlmClient.Message m = history.get(i);
+            if ("user".equals(m.role()) && m.toolCalls() == null && m.toolResults() == null) {
+                userIndexes.add(i);
+            }
+        }
+        if (userIndexes.size() > maxTurns) {
+            int keepFrom = userIndexes.get(userIndexes.size() - maxTurns);
+            history.subList(0, keepFrom).clear();
+            int dropped = userIndexes.size() - maxTurns;
+            userIndexes = userIndexes.subList(dropped, userIndexes.size()).stream()
+                    .map(index -> index - keepFrom).toList();
+        }
+        // everything before the previous turn (i.e. before the second-last user message) is compacted
+        if (userIndexes.size() < 2) {
+            return;
+        }
+        int compactBefore = userIndexes.get(userIndexes.size() - 2);
+        for (int i = 0; i < compactBefore; i++) {
+            LlmClient.Message m = history.get(i);
+            if (m.toolResults() == null || m.toolResults().isEmpty()) {
+                continue;
+            }
+            boolean changed = false;
+            List<LlmClient.ToolResult> compacted = new ArrayList<>(m.toolResults().size());
+            for (LlmClient.ToolResult tr : m.toolResults()) {
+                String content = tr.content();
+                if (content != null && content.length() > compactChars) {
+                    content = content.substring(0, compactChars)
+                              + "\n... [earlier result compacted; call the tool again for the full data]";
+                    changed = true;
+                }
+                compacted.add(new LlmClient.ToolResult(tr.toolCallId(), content));
+            }
+            if (changed) {
+                history.set(i, LlmClient.Message.toolResults(compacted));
+            }
+        }
+    }
+
     private String executeTuiTool(String name, JsonObject args) {
         if (toolRegistry == null) {
             return "Error: TUI tools not available";
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
index 09bd8c1bcb21..1ab25da7511f 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
@@ -187,14 +187,9 @@ class TuiToolRegistry {
                 Map.of("limit", propDef("integer", "Maximum number of events to return (default 50)")))));
         tools.add(toToolDef(toolDef(
                 "tui_get_state",
-                "Returns the current TUI navigation state: active tab, selected integration, "
-                                 + "and integration count. "
-                                 + "Includes a 'selection' field with structured metadata about the active list/table. "
-                                 + "captionVisible indicates if a caption overlay is on screen. "
-                                 + "keystrokesVisible indicates if the keystroke overlay is on. "
-                                 + "detailFocused (boolean, present on tabs with master/detail panels) indicates "
-                                 + "which panel has focus: true=detail panel, false=table panel. "
-                                 + "Press Tab to toggle focus. Up/Down and PgUp/PgDn operate on the focused panel.",
+                "Current TUI navigation state: active tab, selected integration and PID, integration count, the "
+                                 + "active list/table selection, overlay flags and (on master/detail tabs) which "
+                                 + "panel has focus.",
                 Map.of())));
         tools.add(toToolDef(toolDef(
                 "tui_show_caption",
@@ -208,20 +203,14 @@ class TuiToolRegistry {
                 List.of("text"))));
         tools.add(toToolDef(toolDef(
                 "tui_navigate",
-                "Navigates the TUI: switch tabs and/or select an integration. "
-                                + "All parameters are optional — set whichever you want to change. "
-                                + "Tab names: Overview, Log, Activity, Diagram, Routes, Endpoints, HTTP, Inspect, "
-                                + "Circuit Breaker, Health, Spans, Process. "
-                                + "Use 'route' to select a route in the Diagram topology, "
-                                + "and 'node' to drill down into a route and select a specific processor/EIP node. "
-                                + "Returns screen content and selection metadata after navigating.",
-                Map.of("tab", propDef("string", "Tab to switch to (e.g. 'Routes', 'Activity', 'Diagram')"),
+                "Changes what the user sees: switch tab, select an integration, select a route in the Diagram "
+                                + "tab, or drill into a processor node. Every parameter is optional. Returns the screen "
+                                + "and selection afterwards. Do not use it just to read data; the tui_get_* tools do that.",
+                Map.of("tab", propDef("string", "Tab to switch to, e.g. Routes, Log, Diagram (see tui_get_options)"),
                         "integration", propDef("string", "Integration name or PID to select"),
-                        "route", propDef("string",
-                                "Route ID to select in the Diagram tab topology (e.g. 'order-dispatcher')"),
+                        "route", propDef("string", "Route ID to select in the Diagram tab"),
                         "node", propDef("string",
-                                "Processor/EIP node ID to select within a drilled-down route (e.g. 'multicast1'). "
-                                                  + "If 'route' is also provided, drills into that route first")))));
+                                "Processor/EIP node ID to select inside the route (drills into 'route' first when given)")))));
 
         tools.add(toToolDef(toolDef(
                 "tui_send_keys",
@@ -239,13 +228,9 @@ class TuiToolRegistry {
                 List.of("keys"))));
         tools.add(toToolDef(toolDef(
                 "tui_get_options",
-                "IMPORTANT: Call this FIRST before any other tui_ tool when starting a new task. "
-                                   + "Returns all available tabs with descriptions and running integrations. "
-                                   + "Each tab description says what data it provides — match the user's question "
-                                   + "keywords to tab descriptions to find the right data source in one step "
-                                   + "(e.g. 'kafka offset' → find Kafka tab → tui_get_table(tab='Kafka')). "
-                                   + "This avoids wasting calls piecing data from logs, spans, and endpoints "
-                                   + "when a dedicated tab already has exactly the needed information.",
+                "Lists every tab with a description of the data it provides, plus the running integrations. "
+                                   + "Use it when unsure which tab holds the data for a question (e.g. 'kafka offset' "
+                                   + "-> Kafka tab), then read that tab with tui_get_table.",
                 Map.of())));
         tools.add(toToolDef(toolDef(
                 "tui_wait_for_idle",
@@ -281,36 +266,18 @@ class TuiToolRegistry {
                 List.of("seconds"))));
         tools.add(toToolDef(toolDef(
                 "tui_draw",
-                "Draws characters at specific screen coordinates as an overlay on top of the TUI. "
-                            + "Use this to highlight areas, annotate the screen for the human, "
-                            + "draw shapes, or create fun emoji art. "
-                            + "All cells are sent in a single call to avoid chatty networking. "
-                            + "Coordinates are 0-based and match the screen grid from tui_get_screen. "
-                            + "Characters can be any unicode including emoji. "
-                            + "The drawing overlays on top of existing content without modifying it. "
-                            + "Use with tui_show_caption to explain what you drew.",
+                "Draws an overlay on top of the TUI screen in one call: many shapes (batch of the tui_draw_shape "
+                            + "parameters) and/or individual characters, including emoji. Coordinates are 0-based and "
+                            + "match tui_get_screen. Use with tui_show_caption to explain what you drew.",
                 Map.of("cells", propDef("array",
-                        "Array of cell objects to draw. Each cell has: "
-                                                 + "x (integer, column), y (integer, row), "
-                                                 + "char (string, character to draw), "
-                                                 + "fg (string, optional foreground color: red/green/blue/yellow/cyan/magenta/white/gray/black), "
-                                                 + "bg (string, optional background color, same values), "
-                                                 + "bold (boolean, optional)"),
+                        "Cell objects: x, y, char, optional fg/bg color name, optional bold"),
                         "shapes", propDef("array",
-                                "Array of shape objects to draw (batch mode). Each shape has: "
-                                                   + "shape (string, required: box/highlight/underline/arrow-down/arrow-up/arrow-left/arrow-right/text), "
-                                                   + "x (integer, column), y (integer, row), "
-                                                   + "width (integer, for box/highlight/underline), "
-                                                   + "height (integer, for box/highlight), "
-                                                   + "length (integer, for arrows), "
-                                                   + "text (string, for text shape), "
-                                                   + "color (string: red/green/blue/yellow/cyan/magenta/white/gray/black). "
-                                                   + "Use shapes instead of cells for high-level drawing in a single call."),
+                                "Shape objects with the same fields as tui_draw_shape: shape, x, y, width, height, "
+                                                   + "length, text, color"),
                         "duration", propDef("integer",
-                                "Auto-dismiss drawing after this many seconds. "
-                                                       + "If omitted, drawing stays until cleared with tui_draw_clear or replaced by another tui_draw call."),
+                                "Auto-dismiss after this many seconds; otherwise stays until tui_draw_clear or the next tui_draw"),
                         "append", propDef("boolean",
-                                "If true, add cells to the existing drawing instead of replacing it. Default false.")),
+                                "Add to the existing drawing instead of replacing it (default false)")),
                 List.of())));
         tools.add(toToolDef(toolDef(
                 "tui_draw_clear",
@@ -320,13 +287,10 @@ class TuiToolRegistry {
 
         tools.add(toToolDef(toolDef(
                 "tui_draw_shape",
-                "Draws a predefined shape on the TUI screen overlay. "
-                                  + "Much easier than constructing individual cells with tui_draw. "
-                                  + "Combine with tui_locate for precise positioning.",
+                "Draws one shape on the TUI screen overlay. Combine with tui_locate for precise positioning.",
                 Map.of("shape", propDef("string",
-                        "Shape to draw: box (rectangle border), highlight (background color on existing text like a marker pen), "
-                                                  + "underline (horizontal line), arrow-down, arrow-up, arrow-left, arrow-right, "
-                                                  + "text (draw text string at position)"),
+                        "box (border), highlight (marker-pen background), underline, arrow-down, arrow-up, "
+                                                  + "arrow-left, arrow-right, or text"),
                         "x", propDef("integer", "X coordinate (column) of the shape origin"),
                         "y", propDef("integer", "Y coordinate (row) of the shape origin"),
                         "width", propDef("integer", "Width of the shape (for box, highlight, underline)"),
@@ -334,11 +298,10 @@ class TuiToolRegistry {
                         "length", propDef("integer", "Length of arrows"),
                         "text", propDef("string", "Text content to draw (for text shape)"),
                         "color", propDef("string",
-                                "Color: red, green, blue, yellow, cyan, magenta, white, gray, black. Default: red for box/underline/arrow, yellow for highlight."),
-                        "duration",
-                        propDef("integer", "Auto-dismiss after this many seconds. If omitted, stays until cleared."),
-                        "append", propDef("boolean",
-                                "If true, add to existing drawing instead of replacing it. Default false.")),
+                                "red, green, blue, yellow, cyan, magenta, white, gray or black (default red, "
+                                                   + "yellow for highlight)"),
+                        "duration", propDef("integer", "Auto-dismiss after this many seconds; otherwise stays until cleared"),
+                        "append", propDef("boolean", "Add to the existing drawing instead of replacing it (default false)")),
                 List.of("shape", "x", "y"))));
 
         tools.add(toToolDef(toolDef(
@@ -395,14 +358,12 @@ class TuiToolRegistry {
                                                 + "If omitted, uses the active tab.")))));
         tools.add(toToolDef(toolDef(
                 "tui_get_status",
-                "Returns one top-level section of the integration's full status document, the same JSON the Camel "
-                                  + "CLI reads from ~/.camel/<pid>-status.json. Use it for data the tabs do not show: "
-                                  + "'context' (name, version, state, uptime in millis, startTimestamp, statistics), "
-                                  + "'runtime' (pid, directory, java version), 'healthChecks', 'properties', "
-                                  + "'main-configuration', 'routeController', 'services', 'transformers', 'rests', "
-                                  + "'consumers', 'producers', 'endpoints', 'dataSources', 'memory', 'threads', 'gc', "
-                                  + "'classLoading', 'trace', 'events'. Pass section='sections' to list what the "
-                                  + "document contains. Sections can be large, so request only the one you need.",
+                "One top-level section of the integration's full status document (~/.camel/<pid>-status.json). "
+                                  + "Use it for data no tab shows: context (name, version, state, uptime millis, "
+                                  + "startTimestamp, statistics), runtime (pid, directory, java), healthChecks, "
+                                  + "properties, main-configuration, routeController, services, transformers, rests, "
+                                  + "consumers, producers, endpoints, dataSources, memory, threads, gc, classLoading, "
+                                  + "trace, events. section='sections' lists them. Request only the section you need.",
                 Map.of("section", propDef("string",
                         "Top-level section name, or 'sections' to list the available names"),
                         "pid", propDef("string",
@@ -609,26 +570,17 @@ class TuiToolRegistry {
 
         tools.add(toToolDef(toolDef(
                 "tui_catalog_doc",
-                "Get documentation for a Camel catalog artifact (component, data format, language, EIP) "
-                                   + "including description, options, and Maven coordinates. "
-                                   + "Use optionsFilter to search options by keyword (e.g., 'security', 'ssl', 'timeout'). "
-                                   + "This enables queries like 'what options are there on kafka about security'. "
-                                   + "Set includeDoc=true to get the full AsciiDoc documentation for deep-dive questions. "
-                                   + "Uses the Camel version from the selected integration.",
-                Map.of("name", propDef("string",
-                        "Artifact name (e.g., kafka, json-jackson, simple, timer, choice, split)"),
+                "Camel catalog documentation for a component, data format, language or EIP: description, options "
+                                   + "and Maven coordinates, for the Camel version of the selected integration. "
+                                   + "Use optionsFilter for questions like 'which kafka options are about security'.",
+                Map.of("name", propDef("string", "Artifact name, e.g. kafka, json-jackson, simple, timer, choice, split"),
                         "kind", propDef("string",
-                                "Artifact kind: component, dataformat, language, or eip. "
-                                                  + "If omitted, auto-detects by trying component first, then dataformat, then language, then eip."),
-                        "includeOptions", propDef("boolean",
-                                "Whether to include configuration options in the response (default: true). "
-                                                             + "Set to false for a lightweight response with just metadata."),
+                                "component, dataformat, language or eip; auto-detected in that order when omitted"),
+                        "includeOptions", propDef("boolean", "Include the configuration options (default true)"),
                         "includeDoc", propDef("boolean",
-                                "Whether to include the full AsciiDoc documentation text in the response (default: false). "
-                                                         + "Useful for deep-dive questions about usage, examples, and configuration patterns."),
+                                "Include the full AsciiDoc page for usage examples and patterns (default false)"),
                         "optionsFilter", propDef("string",
-                                "Filter options by keyword in name or description (case-insensitive substring match). "
-                                                           + "Only used when includeOptions is true.")),
+                                "Case-insensitive keyword to match in option names or descriptions")),
                 List.of("name"))));
 
         tools.add(toToolDef(toolDef(
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
new file mode 100644
index 000000000000..a5e842baed3e
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
@@ -0,0 +1,106 @@
+/*
+ * 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.tui;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.dsl.jbang.core.commands.LlmClient;
+import org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class AiPanelHistoryCompactionTest {
+
+    private static final String BIG = "x".repeat(5000);
+
+    /** One question answered with a tool call: user, assistant(tool call), tool result, assistant(answer). */
+    private static List<LlmClient.Message> turn(String question, String toolResult) {
+        List<LlmClient.Message> turn = new ArrayList<>();
+        turn.add(LlmClient.Message.user(question));
+        turn.add(LlmClient.Message.assistantWithToolCalls(null,
+                List.of(new LlmClient.ToolCall("call-" + question, "tui_get_log", new JsonObject()))));
+        turn.add(LlmClient.Message.toolResults(List.of(new LlmClient.ToolResult("call-" + question, toolResult))));
+        turn.add(LlmClient.Message.assistantWithToolCalls("answer to " + question, List.of()));
+        return turn;
+    }
+
+    private static String toolResultContent(LlmClient.Message message) {
+        return message.toolResults().get(0).content();
+    }
+
+    @Test
+    void truncatesOversizedToolResultsButKeepsShortOnes() {
+        String small = "ok";
+        assertSame(small, AiPanel.truncateToolResult(small));
+
+        String huge = "y".repeat(AiPanel.MAX_TOOL_RESULT_CHARS + 1234);
+        String truncated = AiPanel.truncateToolResult(huge);
+
+        assertTrue(truncated.startsWith("y".repeat(AiPanel.MAX_TOOL_RESULT_CHARS)));
+        assertTrue(truncated.contains("[truncated, 1234 more characters"));
+    }
+
+    @Test
+    void compactsToolResultsOfOlderTurnsButKeepsThePreviousTurnIntact() {
+        List<LlmClient.Message> history = new ArrayList<>();
+        history.addAll(turn("q1", BIG));
+        history.addAll(turn("q2", BIG));
+        history.addAll(turn("q3", BIG));
+
+        AiPanel.compactHistory(history, 20, 400);
+
+        assertEquals(12, history.size());
+        String first = toolResultContent(history.get(2));
+        assertTrue(first.startsWith("x".repeat(400)));
+        assertTrue(first.contains("[earlier result compacted"));
+        // the previous turn (q2) and the current turn (q3) keep their full results
+        assertEquals(BIG, toolResultContent(history.get(6)));
+        assertEquals(BIG, toolResultContent(history.get(10)));
+        // structure is untouched: the tool call ids still match their results
+        assertEquals("call-q1", history.get(2).toolResults().get(0).toolCallId());
+    }
+
+    @Test
+    void dropsWholeOldestTurnsBeyondTheLimit() {
+        List<LlmClient.Message> history = new ArrayList<>();
+        for (int i = 1; i <= 5; i++) {
+            history.addAll(turn("q" + i, "r" + i));
+        }
+
+        AiPanel.compactHistory(history, 3, 400);
+
+        assertEquals(12, history.size());
+        assertEquals("q3", history.get(0).content());
+        assertEquals("user", history.get(0).role());
+        assertEquals("answer to q5", history.get(11).content());
+    }
+
+    @Test
+    void singleTurnAndEmptyHistoryAreLeftAlone() {
+        List<LlmClient.Message> history = new ArrayList<>(turn("q1", BIG));
+
+        AiPanel.compactHistory(history, 20, 400);
+        AiPanel.compactHistory(new ArrayList<>(), 20, 400);
+        AiPanel.compactHistory(null, 20, 400);
+
+        assertEquals(BIG, toolResultContent(history.get(2)));
+    }
+}


(camel) 04/07: Camel TUI: Overview table export sends uptime as a duration, not the start timestamp

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 15bcdbe2f2a68e7f372d5b800096a12e8db6209b
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Tue Sep 8 17:05:14 2026 +0200

    Camel TUI: Overview table export sends uptime as a duration, not the start timestamp
    
    tui_get_table(Overview) put the process start time (epoch millis) under
    "uptime", so an AI reading the row converted it as a duration and answered
    with hours of uptime for an app started minutes ago. Export the same elapsed
    duration the screen shows, plus uptimeMillis and startedAt for the raw values.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
 .../dsl/jbang/core/commands/tui/OverviewTab.java     | 11 ++++++++++-
 .../core/commands/tui/OverviewTabRenderTest.java     | 20 ++++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)

diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTab.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTab.java
index 990053c91c7b..d5ed6dc88cc4 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTab.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTab.java
@@ -16,6 +16,7 @@
  */
 package org.apache.camel.dsl.jbang.core.commands.tui;
 
+import java.time.Instant;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
@@ -49,6 +50,7 @@ import dev.tamboui.widgets.table.Cell;
 import dev.tamboui.widgets.table.Row;
 import dev.tamboui.widgets.table.Table;
 import dev.tamboui.widgets.table.TableState;
+import org.apache.camel.util.TimeUtils;
 import org.apache.camel.util.json.JsonArray;
 import org.apache.camel.util.json.JsonObject;
 
@@ -1399,7 +1401,14 @@ class OverviewTab extends AbstractTab {
             row.put("platform", info.platform);
             row.put("state", info.state);
             row.put("ready", info.ready);
-            row.put("uptime", info.uptime);
+            // info.uptime holds the process start time (epoch millis), which the screen shows as an elapsed
+            // duration; export the same duration plus the raw values with unambiguous names so an AI reading
+            // the row does not mistake the timestamp for a duration
+            row.put("uptime", info.ago != null ? info.ago : (info.uptime > 0 ? TimeUtils.printSince(info.uptime) : ""));
+            if (info.uptime > 0) {
+                row.put("uptimeMillis", Math.max(0, System.currentTimeMillis() - info.uptime));
+                row.put("startedAt", Instant.ofEpochMilli(info.uptime).toString());
+            }
             row.put("exchangesTotal", info.exchangesTotal);
             row.put("failed", info.failed);
             row.put("inflight", info.inflight);
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTabRenderTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTabRenderTest.java
index 2d83070df68b..894ec99f0f32 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTabRenderTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/OverviewTabRenderTest.java
@@ -16,6 +16,7 @@
  */
 package org.apache.camel.dsl.jbang.core.commands.tui;
 
+import java.time.Instant;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -31,6 +32,8 @@ import dev.tamboui.tui.event.KeyEvent;
 import dev.tamboui.tui.event.KeyModifiers;
 import dev.tamboui.tui.event.MouseButton;
 import dev.tamboui.tui.event.MouseEvent;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -81,6 +84,23 @@ class OverviewTabRenderTest {
         assertTrue(rendered.contains("TOTAL"), "Should show TOTAL header");
     }
 
+    @Test
+    void tableDataExportsUptimeAsDurationNotStartTimestamp() {
+        info.state = 5;
+        info.uptime = System.currentTimeMillis() - 2 * 60 * 1000;
+        info.ago = "2m0s";
+
+        OverviewTab tab = new OverviewTab(ctx, new MetricsCollector(), new HashSet<>(), () -> {
+        });
+        JsonObject data = tab.getTableDataAsJson();
+        JsonObject row = (JsonObject) ((JsonArray) data.get("rows")).get(0);
+
+        assertEquals("2m0s", row.get("uptime"), "uptime must be the elapsed duration shown on screen");
+        long millis = ((Number) row.get("uptimeMillis")).longValue();
+        assertTrue(millis >= 2 * 60 * 1000 && millis < 3 * 60 * 1000, "uptimeMillis was " + millis);
+        assertEquals(Instant.ofEpochMilli(info.uptime).toString(), row.get("startedAt"));
+    }
+
     @Test
     void renderShowsIntegrationData() {
         info.state = 5;


(camel) 07/07: CAMEL-24656: camel-jbang TUI - expose the integration log tail as an MCP resource

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 1fd5519c6ca798614742d4e2b96902fb52db89f9
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Tue Sep 8 17:27:34 2026 +0200

    CAMEL-24656: camel-jbang TUI - expose the integration log tail as an MCP resource
    
    camel://log/<pid> returns the last 200 lines of ~/.camel/<pid>.log, and
    camel://log/<pid>?lines=<n> a different tail length (up to 5000), read from
    the end of the file so a large log is never loaded whole. Listed next to the
    status resources and described by a URI template. The Log tab only shows a
    window of the file, so the template points agents at tui_get_screen when they
    need to know which lines the user is looking at.
    
    Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
    Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
 .../modules/ROOT/pages/camel-jbang-tui.adoc        |  8 +-
 .../jbang/core/commands/tui/StatusFileReader.java  | 67 ++++++++++++++++
 .../dsl/jbang/core/commands/tui/TuiMcpServer.java  | 90 ++++++++++++++++++++--
 .../core/commands/tui/StatusFileReaderTest.java    | 20 +++++
 .../commands/tui/TuiMcpServerResourcesTest.java    | 34 ++++++--
 5 files changed, 204 insertions(+), 15 deletions(-)

diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
index 8039f5133e04..7ab129ae3ad2 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
@@ -879,13 +879,17 @@ once a second by `camel-cli-connector`. The tabs show a digest of it; the MCP se
 whole document as resources so an agent can fetch exactly the section it needs instead of
 paging through tabs:
 
+* `camel://log/<pid>` -- the last 200 lines of the integration's log (`~/.camel/<pid>.log`);
+  `camel://log/<pid>?lines=<n>` for a different tail length (up to 5000). The Log tab shows only a
+  window of this file, so an agent that needs to know which lines the user is looking at should
+  use the `tui_get_screen` tool instead.
 * `camel://status/<pid>` -- the whole document
 * `camel://status/<pid>/<section>` -- one top-level section, for example `context` (name, version,
   state, uptime, start timestamp, statistics), `runtime`, `routes`, `endpoints`, `healthChecks`,
   `properties`, `main-configuration`, `routeController`, `memory`, `threads`, `gc` or `events`
 
-`resources/list` enumerates the document and its sections for every monitored integration, and a
-`resources/templates/list` template describes the URI shape. The same data is available to the
+`resources/list` enumerates the log, the document and its sections for every monitored
+integration, and `resources/templates/list` describes the URI shapes. The same data is available to the
 F8 AI panel (and as an MCP tool) through `tui_get_status`, which takes a `section` argument and
 returns that section only; pass `sections` to list what the document contains. Sections such as
 `events` can be large, so ask for the one you need.
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReader.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReader.java
index 906ebaafc919..53cbbf3b4e50 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReader.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReader.java
@@ -16,6 +16,7 @@
  */
 package org.apache.camel.dsl.jbang.core.commands.tui;
 
+import java.io.RandomAccessFile;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
@@ -33,6 +34,8 @@ import org.apache.camel.util.json.Jsoner;
 final class StatusFileReader {
 
     static final String SECTION_LIST = "sections";
+    static final int DEFAULT_LOG_LINES = 200;
+    static final int MAX_LOG_LINES = 5000;
 
     private final Path camelDir;
 
@@ -48,6 +51,70 @@ final class StatusFileReader {
         return camelDir.resolve(pid + "-status.json");
     }
 
+    Path logFile(String pid) {
+        return camelDir.resolve(pid + ".log");
+    }
+
+    boolean hasLog(String pid) {
+        return pid != null && !pid.isBlank() && Files.isRegularFile(logFile(pid.trim()));
+    }
+
+    /**
+     * The last {@code lines} lines of the process log ({@code ~/.camel/<pid>.log}), read from the end of the file so a
+     * large log is not loaded whole; {@code null} when there is no log file. {@code lines} is clamped to
+     * {@link #MAX_LOG_LINES}.
+     */
+    String tailLog(String pid, int lines) {
+        if (!hasLog(pid)) {
+            return null;
+        }
+        int wanted = Math.max(1, Math.min(lines, MAX_LOG_LINES));
+        Path file = logFile(pid.trim());
+        try (RandomAccessFile raf = new RandomAccessFile(file.toFile(), "r")) {
+            long length = raf.length();
+            if (length == 0) {
+                return "";
+            }
+            // read backwards in chunks until the buffer holds more line breaks than lines wanted (or the whole file)
+            int chunk = 64 * 1024;
+            byte[] tail = new byte[0];
+            long position = length;
+            while (position > 0 && countNewlines(tail) <= wanted) {
+                int size = (int) Math.min(chunk, position);
+                position -= size;
+                raf.seek(position);
+                byte[] merged = new byte[size + tail.length];
+                raf.readFully(merged, 0, size);
+                System.arraycopy(tail, 0, merged, size, tail.length);
+                tail = merged;
+            }
+            // skip the final line break, then step back over 'wanted' line breaks
+            int cut = tail.length;
+            if (cut > 0 && tail[cut - 1] == '\n') {
+                cut--;
+            }
+            int seen = 0;
+            for (int i = cut - 1; i >= 0; i--) {
+                if (tail[i] == '\n' && ++seen == wanted) {
+                    return new String(tail, i + 1, tail.length - i - 1, StandardCharsets.UTF_8);
+                }
+            }
+            return new String(tail, StandardCharsets.UTF_8);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    private static int countNewlines(byte[] bytes) {
+        int count = 0;
+        for (byte b : bytes) {
+            if (b == '\n') {
+                count++;
+            }
+        }
+        return count;
+    }
+
     /**
      * The parsed document, or {@code null} when there is no readable status file for the pid.
      */
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServer.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServer.java
index 25edf336c4c5..a49bb1aff14f 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServer.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServer.java
@@ -284,7 +284,9 @@ class TuiMcpServer {
     // ---- Resources: the per-process status document, whole or one section at a time ----
 
     static final String STATUS_URI_PREFIX = "camel://status/";
+    static final String LOG_URI_PREFIX = "camel://log/";
     private static final String JSON_MIME = "application/json";
+    private static final String TEXT_MIME = "text/plain";
 
     /**
      * Address of a status resource: {@code camel://status/<pid>} for the whole document, or
@@ -318,6 +320,49 @@ class TuiMcpServer {
         }
     }
 
+    /**
+     * Address of a process log resource: {@code camel://log/<pid>} for the last
+     * {@link StatusFileReader#DEFAULT_LOG_LINES} lines, or {@code camel://log/<pid>?lines=<n>} for a different tail
+     * length.
+     */
+    record LogUri(String pid, int lines) {
+
+        String uri() {
+            return LOG_URI_PREFIX + pid + (lines != StatusFileReader.DEFAULT_LOG_LINES ? "?lines=" + lines : "");
+        }
+
+        /**
+         * Parses a log resource URI, or returns {@code null} when it is not one.
+         */
+        static LogUri parse(String uri) {
+            if (uri == null || !uri.startsWith(LOG_URI_PREFIX)) {
+                return null;
+            }
+            String rest = uri.substring(LOG_URI_PREFIX.length());
+            int query = rest.indexOf('?');
+            String pid = query < 0 ? rest : rest.substring(0, query);
+            if (pid.isEmpty() || !pid.chars().allMatch(Character::isDigit)) {
+                return null;
+            }
+            int lines = StatusFileReader.DEFAULT_LOG_LINES;
+            if (query >= 0) {
+                String param = rest.substring(query + 1);
+                if (!param.startsWith("lines=")) {
+                    return null;
+                }
+                try {
+                    lines = Integer.parseInt(param.substring("lines=".length()));
+                } catch (NumberFormatException e) {
+                    return null;
+                }
+                if (lines < 1) {
+                    return null;
+                }
+            }
+            return new LogUri(pid, Math.min(lines, StatusFileReader.MAX_LOG_LINES));
+        }
+    }
+
     private JsonObject handleResourcesList() {
         JsonObject result = new JsonObject();
         result.put("resources", buildResourceList(facade.liveIntegrations(), facade.statusFiles()));
@@ -338,22 +383,32 @@ class TuiMcpServer {
                 continue;
             }
             String name = info.name != null ? info.name : info.pid;
+            if (reader.hasLog(info.pid)) {
+                resources.add(resource(new LogUri(info.pid, StatusFileReader.DEFAULT_LOG_LINES).uri(), name + " log",
+                        "Last " + StatusFileReader.DEFAULT_LOG_LINES + " log lines of " + name + " (PID " + info.pid
+                                                                                                                      + "); append ?lines=<n> for a longer or shorter tail (max "
+                                                                                                                      + StatusFileReader.MAX_LOG_LINES
+                                                                                                                      + ")",
+                        TEXT_MIME));
+            }
             resources.add(resource(new StatusUri(info.pid, null).uri(), name + " status",
-                    "Full status document of " + name + " (PID " + info.pid + "): " + String.join(", ", sections)));
+                    "Full status document of " + name + " (PID " + info.pid + "): " + String.join(", ", sections),
+                    JSON_MIME));
             for (String section : sections) {
                 resources.add(resource(new StatusUri(info.pid, section).uri(), name + " " + section,
-                        "The '" + section + "' section of the status document of " + name + " (PID " + info.pid + ")"));
+                        "The '" + section + "' section of the status document of " + name + " (PID " + info.pid + ")",
+                        JSON_MIME));
             }
         }
         return resources;
     }
 
-    private static JsonObject resource(String uri, String name, String description) {
+    private static JsonObject resource(String uri, String name, String description, String mimeType) {
         JsonObject resource = new JsonObject();
         resource.put("uri", uri);
         resource.put("name", name);
         resource.put("description", description);
-        resource.put("mimeType", JSON_MIME);
+        resource.put("mimeType", mimeType);
         return resource;
     }
 
@@ -366,8 +421,17 @@ class TuiMcpServer {
                                     + "Sections include context, runtime, routes, endpoints, healthChecks, properties, "
                                     + "main-configuration, memory, threads, gc and events.");
         template.put("mimeType", JSON_MIME);
+        JsonObject logTemplate = new JsonObject();
+        logTemplate.put("uriTemplate", LOG_URI_PREFIX + "{pid}{?lines}");
+        logTemplate.put("name", "Integration log tail");
+        logTemplate.put("description", "The last lines of the log of the integration with the given PID "
+                                       + "(" + StatusFileReader.DEFAULT_LOG_LINES + " by default, lines=<n> up to "
+                                       + StatusFileReader.MAX_LOG_LINES + "). The Log tab shows only a window of this "
+                                       + "file; use the tui_get_screen tool to see which lines the user is looking at.");
+        logTemplate.put("mimeType", TEXT_MIME);
         JsonArray templates = new JsonArray();
         templates.add(template);
+        templates.add(logTemplate);
         JsonObject result = new JsonObject();
         result.put("resourceTemplates", templates);
         return result;
@@ -378,7 +442,13 @@ class TuiMcpServer {
      * (the caller turns that into a "resource not found" error).
      */
     private JsonObject handleResourcesRead(JsonObject request) {
-        StatusUri uri = StatusUri.parse(requestedUri(request));
+        String requested = requestedUri(request);
+        LogUri logUri = LogUri.parse(requested);
+        if (logUri != null) {
+            String tail = facade.statusFiles().tailLog(logUri.pid(), logUri.lines());
+            return tail == null ? null : contents(logUri.uri(), TEXT_MIME, tail);
+        }
+        StatusUri uri = StatusUri.parse(requested);
         if (uri == null) {
             return null;
         }
@@ -388,10 +458,14 @@ class TuiMcpServer {
         if (payload == null) {
             return null;
         }
+        return contents(uri.uri(), JSON_MIME, Jsoner.serialize(payload));
+    }
+
+    private static JsonObject contents(String uri, String mimeType, String text) {
         JsonObject content = new JsonObject();
-        content.put("uri", uri.uri());
-        content.put("mimeType", JSON_MIME);
-        content.put("text", Jsoner.serialize(payload));
+        content.put("uri", uri);
+        content.put("mimeType", mimeType);
+        content.put("text", text);
         JsonArray contents = new JsonArray();
         contents.add(content);
         JsonObject result = new JsonObject();
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReaderTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReaderTest.java
index c75cd7166739..302efd5efe26 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReaderTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/StatusFileReaderTest.java
@@ -56,6 +56,26 @@ class StatusFileReaderTest {
         assertNull(reader.section("4711", null));
     }
 
+    @Test
+    void tailsTheLogFromTheEndWithoutLoadingItWhole(@TempDir Path dir) throws Exception {
+        StringBuilder log = new StringBuilder();
+        for (int i = 1; i <= 3000; i++) {
+            log.append("2026-09-08 line ").append(i).append(" ").append("padding ".repeat(20)).append('\n');
+        }
+        Files.writeString(dir.resolve("4711.log"), log.toString());
+        StatusFileReader reader = new StatusFileReader(dir);
+
+        assertTrue(reader.hasLog("4711"));
+        String tail = reader.tailLog("4711", 3);
+        assertTrue(tail.startsWith("2026-09-08 line 2998 "), tail.substring(0, 40));
+        assertEquals(3, tail.strip().split("\n").length);
+        assertTrue(tail.strip().endsWith("line 3000 " + "padding ".repeat(20).strip()));
+
+        // more lines than the file has yields the whole file
+        assertEquals(log.toString(), reader.tailLog("4711", StatusFileReader.MAX_LOG_LINES));
+        assertNull(reader.tailLog("9999", 10));
+    }
+
     @Test
     void missingOrCorruptFilesReadAsAbsent(@TempDir Path dir) throws Exception {
         Files.writeString(dir.resolve("99-status.json"), "{ not json");
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServerResourcesTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServerResourcesTest.java
index 9d6bf34720e8..aab18ff1be51 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServerResourcesTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiMcpServerResourcesTest.java
@@ -55,9 +55,29 @@ class TuiMcpServerResourcesTest {
     }
 
     @Test
-    void listsWholeDocumentThenEachSectionPerIntegration(@TempDir Path dir) throws Exception {
+    void parsesLogUrisWithOptionalLineCount() {
+        TuiMcpServer.LogUri plain = TuiMcpServer.LogUri.parse("camel://log/4711");
+        assertEquals("4711", plain.pid());
+        assertEquals(StatusFileReader.DEFAULT_LOG_LINES, plain.lines());
+        assertEquals("camel://log/4711", plain.uri());
+
+        TuiMcpServer.LogUri sized = TuiMcpServer.LogUri.parse("camel://log/4711?lines=50");
+        assertEquals(50, sized.lines());
+        assertEquals("camel://log/4711?lines=50", sized.uri());
+        assertEquals(StatusFileReader.MAX_LOG_LINES, TuiMcpServer.LogUri.parse("camel://log/4711?lines=999999").lines());
+
+        assertNull(TuiMcpServer.LogUri.parse("camel://log/"));
+        assertNull(TuiMcpServer.LogUri.parse("camel://log/abc"));
+        assertNull(TuiMcpServer.LogUri.parse("camel://log/4711?lines=0"));
+        assertNull(TuiMcpServer.LogUri.parse("camel://log/4711?tail=5"));
+        assertNull(TuiMcpServer.LogUri.parse("camel://status/4711"));
+    }
+
+    @Test
+    void listsLogThenWholeDocumentThenEachSectionPerIntegration(@TempDir Path dir) throws Exception {
         Files.writeString(dir.resolve("4711-status.json"),
                 "{\"runtime\":{\"pid\":4711},\"context\":{\"name\":\"timer-log\"}}");
+        Files.writeString(dir.resolve("4711.log"), "hello\n");
         IntegrationInfo running = new IntegrationInfo();
         running.pid = "4711";
         running.name = "timer-log";
@@ -67,12 +87,16 @@ class TuiMcpServerResourcesTest {
 
         JsonArray resources = TuiMcpServer.buildResourceList(List.of(running, gone), new StatusFileReader(dir));
 
-        assertEquals(3, resources.size());
-        JsonObject whole = (JsonObject) resources.get(0);
+        assertEquals(4, resources.size());
+        JsonObject log = (JsonObject) resources.get(0);
+        assertEquals("camel://log/4711", log.get("uri"));
+        assertEquals("timer-log log", log.get("name"));
+        assertEquals("text/plain", log.get("mimeType"));
+        JsonObject whole = (JsonObject) resources.get(1);
         assertEquals("camel://status/4711", whole.get("uri"));
         assertEquals("timer-log status", whole.get("name"));
         assertEquals("application/json", whole.get("mimeType"));
-        assertEquals("camel://status/4711/runtime", ((JsonObject) resources.get(1)).get("uri"));
-        assertEquals("camel://status/4711/context", ((JsonObject) resources.get(2)).get("uri"));
+        assertEquals("camel://status/4711/runtime", ((JsonObject) resources.get(2)).get("uri"));
+        assertEquals("camel://status/4711/context", ((JsonObject) resources.get(3)).get("uri"));
     }
 }