Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
9e8b40b
CAMEL-23978: Add AI panel slash command registry
ammachado Jul 10, 2026
87df544
CAMEL-23978: Add TUI AI CLI command executor
ammachado Jul 10, 2026
cd08b0b
CAMEL-23978: Wire local AI panel slash commands
ammachado Jul 10, 2026
6d4ce48
CAMEL-23978: Show AI slash command placeholders
ammachado Jul 10, 2026
9d3f6ea
CAMEL-23978: Document AI panel slash commands
ammachado Jul 10, 2026
266cad5
CAMEL-23978: Harden AI panel slash command behavior
ammachado Jul 10, 2026
450d54c
CAMEL-23978: Wire AI provider switch popup to /provider command
ammachado Jul 10, 2026
5e7598b
CAMEL-23978: Improve AI panel slash command help and hints
ammachado Jul 10, 2026
a5245fe
CAMEL-23978: Align AI slash command help columns
ammachado Jul 10, 2026
a0143e7
CAMEL-23978: Persist TUI AI settings
ammachado Jul 9, 2026
cd47e70
CAMEL-23978: Polish AI panel thinking state
ammachado Jul 9, 2026
6699a3a
CAMEL-23978: Add AI provider quick switch
ammachado Jul 9, 2026
1040922
CAMEL-23978: Randomize AI panel thinking verb, apply formatter fix
ammachado Jul 9, 2026
22fef85
CAMEL-23978: Fix AI provider switch bugs and agent thread races
ammachado Jul 10, 2026
3675d86
CAMEL-23978: Restore agent thread test hook after rebase
ammachado Jul 10, 2026
dfb18f9
CAMEL-23978: Remove local superpowers dev artifact
ammachado Jul 10, 2026
a2fef2a
CAMEL-23978: Fix AI panel slash command review findings
ammachado Jul 10, 2026
f2a116f
CAMEL-23978: Document stopAgentThread() cancellation join limitation
ammachado Jul 10, 2026
2a83126
CAMEL-23978: Extract AiProviderSelector from AiPanel
ammachado Jul 10, 2026
592c18d
CAMEL-23978: Implement /model listing via provider APIs
ammachado Jul 10, 2026
312bd2a
CAMEL-23978: Restore thinking dots animation, list all AI providers
ammachado Jul 10, 2026
3681485
CAMEL-23978: Fix SettingsPopup AI-provider row test after rebase
ammachado Jul 11, 2026
a881374
CAMEL-23978: Show AI slash command placeholders
ammachado Jul 10, 2026
134b843
CAMEL-23978: Address PR review feedback
ammachado Jul 11, 2026
04d3d5a
CAMEL-23978: Remove duplicate placeholder block in AiPanel.renderInput
ammachado Jul 11, 2026
1ae8f66
CAMEL-23978: Launch /run and /infra run as tracked background processes
ammachado Jul 11, 2026
f2d67a2
CAMEL-23978: Persist /model selection across TUI restarts
ammachado Jul 11, 2026
cae9f29
CAMEL-23978: Add TAB completion and fix clipped AI output
ammachado Jul 11, 2026
ba40132
CAMEL-23978: Harden AI model selection
ammachado Jul 11, 2026
d97d48f
CAMEL-23978: Address latest AI panel review feedback
ammachado Jul 11, 2026
f6008c3
CAMEL-23978: Serialize AI CLI execution
ammachado Jul 11, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,42 @@ 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.

=== 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.

[cols="1,3",options="header"]
|===
| Command | Description

| `/help` (`/h`)
| Show the available slash commands.

| `/provider` (`/p`)
| Open the provider switcher.

| `/model [model-name]` (`/m`)
| Show the current model, or switch the session model.

| `/clear` (`/c`)
| Clear the AI conversation, usage counters, and model context without changing the provider or model.

| `/close`
| Close the AI panel.

| `/quit` (`/exit`, `/q`, `/x`)
| Exit the TUI.

| `/run <camel run args>` (`/r`)
| Run `camel run` with the provided arguments.

| `/infra <camel infra args>` (`/i`)
| Run `camel infra` with the provided arguments.

| `/send <endpoint> <message text \| @file>` (`/s`)
| Send a message through `camel cmd send`. A body that is exactly one `@file` token is sent as `file:<path>`; inline `@file` text is sent literally.
|===

=== Connecting an AI Agent

To connect Claude Code to the TUI, add the MCP server to your project configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,30 +347,31 @@ public void printf(String format, Object... fmtArgs) {
CamelJBangMain main = (CamelJBangMain) commandLine.getCommand();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
PrintWriter originalOut = commandLine.getOut();
PrintWriter originalErr = commandLine.getErr();
commandLine.setOut(pw);
commandLine.setErr(pw);

Printer originalPrinter = main.getOut();
main.setOut(capturingPrinter);
try {
int exitCode = commandLine.execute(cmdArgs);
pw.flush();
String output = captured.toString() + sw.toString();
if (output.isBlank() && exitCode != 0) {
return "Command exited with code " + exitCode;
}
if (output.length() > 32768) {
output = output.substring(0, 32768) + "\n... (truncated)";
synchronized (CamelJBangMain.class) {
PrintWriter originalOut = commandLine.getOut();
PrintWriter originalErr = commandLine.getErr();
Printer originalPrinter = main.getOut();
commandLine.setOut(pw);
commandLine.setErr(pw);
main.setOut(capturingPrinter);
try {
int exitCode = commandLine.execute(cmdArgs);
pw.flush();
String output = captured.toString() + sw.toString();
if (output.isBlank() && exitCode != 0) {
return "Command exited with code " + exitCode;
}
if (output.length() > 32768) {
output = output.substring(0, 32768) + "\n... (truncated)";
}
return output;
} catch (Exception e) {
return "Error executing command: " + e.getMessage();
} finally {
main.setOut(originalPrinter);
commandLine.setOut(originalOut);
commandLine.setErr(originalErr);
}
return output;
} catch (Exception e) {
return "Error executing command: " + e.getMessage();
} finally {
main.setOut(originalPrinter);
commandLine.setOut(originalOut);
commandLine.setErr(originalErr);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
public class LlmClient {

private static final String DEFAULT_OLLAMA_URL = "http://localhost:11434";
private static final String OLLAMA_ROOT_RESPONSE = "Ollama is running";
private static final String DEFAULT_ANTHROPIC_URL = "https://api.anthropic.com";
private static final String ANTHROPIC_VERSION = "2023-06-01";
private static final String VERTEX_ANTHROPIC_VERSION = "vertex-2023-10-16";
Expand Down Expand Up @@ -287,6 +288,94 @@ public ChatResponse chatWithTools(String systemPrompt, List<Message> messages, L
};
}

// -- Model listing --

/**
* Lists model identifiers available from the configured provider: Ollama's {@code /api/tags}, or the
* OpenAI-compatible/Anthropic {@code /v1/models}. Vertex AI has no equivalent listing endpoint (models come from
* the Vertex AI model garden, not the Anthropic API surface), so it always returns an empty list. Best-effort: any
* failure (unreachable endpoint, non-200 response, unexpected JSON shape) yields an empty list rather than
* throwing, since this only feeds the informational {@code /model} listing in the AI panel.
*/
public List<String> listModels() {
if (apiType == null || url == null || url.isBlank()) {
Comment thread
ammachado marked this conversation as resolved.
return List.of();
}
return switch (apiType) {
case ollama -> listOllamaModels();
case openai -> listOpenAiModels();
case anthropic -> isVertexAi() ? List.of() : listAnthropicModels();
};
}

private List<String> listOllamaModels() {
JsonObject response = sendGetRequest(url + "/api/tags", Map.of());
return extractStringList(response, "models", "name");
}

private List<String> listOpenAiModels() {
Map<String, String> headers = new HashMap<>();
String key = resolveApiKey();
if (key != null) {
headers.put("Authorization", "Bearer " + key);
}
JsonObject response = sendGetRequest(normalizeOpenAiModelsUrl(url), headers);
return extractStringList(response, "data", "id");
}

private List<String> listAnthropicModels() {
String base = url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
JsonObject response = sendGetRequest(base + "/v1/models", buildAnthropicHeaders());
return extractStringList(response, "data", "id");
}

private static List<String> extractStringList(JsonObject response, String arrayField, String nameField) {
if (response == null) {
return List.of();
}
if (!(response.get(arrayField) instanceof JsonArray items)) {
return List.of();
}
List<String> names = new ArrayList<>();
for (Object obj : items) {
if (obj instanceof JsonObject item) {
String name = item.getString(nameField);
if (name != null) {
names.add(name);
}
}
}
return names;
}

String normalizeOpenAiModelsUrl(String endpoint) {
String u = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint;
if (!u.endsWith("/v1/models")) {
u = u.endsWith("/v1") ? u : u + "/v1";
u = u + "/models";
}
return u;
}

private JsonObject sendGetRequest(String requestUrl, Map<String, String> headers) {
try {
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(requestUrl))
.timeout(Duration.ofSeconds(HEALTH_CHECK_TIMEOUT_SECONDS))
.GET();
for (Map.Entry<String, String> h : headers.entrySet()) {
builder.header(h.getKey(), h.getValue());
}
HttpResponse<String> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return (JsonObject) Jsoner.deserialize(response.body());
}
return null;
} catch (Exception e) {
return null;
}
}

// ---- Ollama generate ----

private String generateOllama(String systemPrompt, String userPrompt) {
Expand Down Expand Up @@ -1126,11 +1215,43 @@ private String sendAnthropicStreamingRequest(String requestUrl, JsonObject body,

// ---- Endpoint detection helpers ----

// Order matters: /api/tags is checked before /v1/models, matching the original priority.
private static final List<Map.Entry<String, ApiType>> EXPLICIT_URL_HEALTH_CHECK_SUFFIXES = List.of(
Comment thread
ammachado marked this conversation as resolved.
Map.entry("/api/tags", ApiType.ollama),
Map.entry("/v1/models", ApiType.openai));

private boolean tryExplicitUrl() {
if (url == null || url.isBlank()) {
return false;
}
return isEndpointReachable(url);
if (apiType != null) {
return isEndpointReachable(url);
}
for (Map.Entry<String, ApiType> check : EXPLICIT_URL_HEALTH_CHECK_SUFFIXES) {
if (tryHealthCheck(url + check.getKey())) {
apiType = check.getValue();
return true;
}
}
if (isOllamaRoot(url)) {
apiType = ApiType.ollama;
return true;
}
return false;
}

private boolean isOllamaRoot(String endpoint) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endpoint))
.timeout(Duration.ofSeconds(HEALTH_CHECK_TIMEOUT_SECONDS))
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return response.statusCode() == 200 && OLLAMA_ROOT_RESPONSE.equals(response.body().trim());
} catch (Exception e) {
return false;
}
}

private boolean tryAnthropicApiKey() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* 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;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Verifies {@link LlmClient#listModels()} against each provider's real response shape (Ollama's {@code /api/tags},
* OpenAI/Anthropic's {@code /v1/models}) using a local {@link HttpServer} instead of mocking the HTTP client, so the
* request path, auth headers, and JSON parsing are all exercised together.
*/
class LlmClientListModelsTest {

private HttpServer server;

@AfterEach
void stopServer() {
if (server != null) {
server.stop(0);
}
}

private String startServer(String path, int status, String body, AtomicReference<String> capturedHeader, String headerName)
throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext(path, exchange -> {
if (capturedHeader != null) {
capturedHeader.set(exchange.getRequestHeaders().getFirst(headerName));
}
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
});
server.start();
return "http://127.0.0.1:" + server.getAddress().getPort();
}

private String startRootServer(String body) throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
int status = "/".equals(exchange.getRequestURI().getPath()) ? 200 : 404;
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
});
server.start();
return "http://127.0.0.1:" + server.getAddress().getPort();
}

@Test
void detectsOllamaFromRootResponseOnNonDefaultPort() throws IOException {
String baseUrl = startRootServer("Ollama is running");
LlmClient client = LlmClient.create().withUrl(baseUrl);

assertTrue(client.detectEndpoint());
assertEquals(LlmClient.ApiType.ollama, client.apiType());
}

@Test
void listsOllamaModelsFromApiTags() throws IOException {
String baseUrl = startServer("/api/tags", 200,
"{\"models\":[{\"name\":\"llama3.2:latest\"},{\"name\":\"qwen3\"}]}", null, null);
LlmClient client = LlmClient.create().withApiType(LlmClient.ApiType.ollama).withUrl(baseUrl);

assertEquals(List.of("llama3.2:latest", "qwen3"), client.listModels());
}

@Test
void listsOpenAiModelsFromV1ModelsWithBearerAuth() throws IOException {
AtomicReference<String> authHeader = new AtomicReference<>();
String baseUrl = startServer("/v1/models", 200,
"{\"data\":[{\"id\":\"gpt-4o\"},{\"id\":\"gpt-4o-mini\"}]}", authHeader, "Authorization");
LlmClient client = LlmClient.create().withApiType(LlmClient.ApiType.openai).withUrl(baseUrl).withApiKey("sk-test");

assertEquals(List.of("gpt-4o", "gpt-4o-mini"), client.listModels());
assertEquals("Bearer sk-test", authHeader.get());
}

@Test
void listsAnthropicModelsFromV1ModelsWithApiKeyHeader() throws IOException {
AtomicReference<String> apiKeyHeader = new AtomicReference<>();
String baseUrl = startServer("/v1/models", 200,
"{\"data\":[{\"id\":\"claude-sonnet-4-6\"}]}", apiKeyHeader, "x-api-key");
LlmClient client
= LlmClient.create().withApiType(LlmClient.ApiType.anthropic).withUrl(baseUrl).withApiKey("sk-ant-test");

assertEquals(List.of("claude-sonnet-4-6"), client.listModels());
assertEquals("sk-ant-test", apiKeyHeader.get());
}

@Test
void returnsEmptyListOnNonOkStatus() throws IOException {
String baseUrl = startServer("/api/tags", 500, "{\"error\":\"boom\"}", null, null);
LlmClient client = LlmClient.create().withApiType(LlmClient.ApiType.ollama).withUrl(baseUrl);

assertTrue(client.listModels().isEmpty());
}

@Test
void returnsEmptyListWhenModelListHasUnexpectedShape() throws IOException {
String baseUrl = startServer("/api/tags", 200, "{\"models\":{}}", null, null);
LlmClient client = LlmClient.create().withApiType(LlmClient.ApiType.ollama).withUrl(baseUrl);

assertTrue(client.listModels().isEmpty());
}

@Test
void returnsEmptyListWhenEndpointUnreachable() {
LlmClient client = LlmClient.create().withApiType(LlmClient.ApiType.ollama).withUrl("http://127.0.0.1:1");

assertTrue(client.listModels().isEmpty());
}

@Test
void returnsEmptyListWhenApiTypeNotYetDetected() {
LlmClient client = LlmClient.create();

assertTrue(client.listModels().isEmpty());
}
}
Loading