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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion .idea/kotlinc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 32 additions & 0 deletions app/openai-bridge/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /work

COPY . .

RUN chmod +x ./gradlew && ./gradlew --no-daemon :app:openai-bridge:installDist -x test

FROM eclipse-temurin:21-jdk
ENV DEBIAN_FRONTEND=noninteractive
WORKDIR /opt

RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates unzip \
&& rm -rf /var/lib/apt/lists/*

ENV CODEQL_VERSION=2.16.6
RUN mkdir -p /opt/codeql \
&& curl -L "https://github.com/github/codeql-action/releases/download/codeql-bundle-v${CODEQL_VERSION}/codeql-bundle-linux64.tar.gz" \
-o /tmp/codeql.tgz \
&& tar -xzf /tmp/codeql.tgz -C /opt/codeql --strip-components=1 \
&& rm /tmp/codeql.tgz
ENV PATH="/opt/codeql:${PATH}"

COPY --from=builder /work/app/openai-bridge/build/install/openai-bridge /opt/openai-bridge

ENV PORT="8080"
ENV OLLAMA_BASE_URL="http://host.docker.internal:11434"
ENV OLLAMA_KEEP_ALIVE="5m"

EXPOSE 8080

ENTRYPOINT ["/opt/openai-bridge/bin/openai-bridge"]
58 changes: 58 additions & 0 deletions app/openai-bridge/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# OpenAPI Bridge Server
This module contains the HTTP server. It exposes a minimal OpenAI-style `POST /v1/chat/completions` endpoint backed by the SecureCoder engine.

## Run with Docker

### Configuration
- OpenRouter mode:
- `OPENROUTER_KEY` — your OpenRouter API key
- `MODEL` — model ID (e.g.: `openai/gpt-oss-20b`)
- Ollama mode (used when `OPENROUTER_KEY` is not set):
- `MODEL` — Ollama model name (e.g.: `gpt-oss:20`)
- `OLLAMA_BASE_URL` — base URL to Ollama (default: 11434 on the host)
- `OLLAMA_KEEP_ALIVE` — keep-alive duration (default: `5m`)

### Build and run
Make sure you have Docker installed and are in the project root directory.
```
docker build -f app/openai-bridge/Dockerfile -t openai-bridge:latest .
```

Run with Ollama on the host (macOS/Windows):
```
docker run --rm -p 8080:8080 \
-e MODEL="gpt-oss:20b" \
openai-bridge:latest
```

Run with Ollama on the host (Linux):
```
docker run --rm -p 8080:8080 \
--add-host=host.docker.internal:host-gateway \
-e MODEL="gpt-oss:20b" \
openai-bridge:latest
```

Run using OpenRouter instead of Ollama:
```
docker run --rm -p 8080:8080 \
-e OPENROUTER_KEY=... \
-e MODEL=openai/gpt-oss-20b \
openai-bridge:latest
```

## Endpoint
- `POST /v1/chat/completions` — accepts a minimal OpenAI-style request and returns a single choice with the SecureCoder engine’s response.

Example request (from host):
```
curl -X POST "http://localhost:8080/v1/chat/completions" \
-H "Content-Type: application/json" \
-d '{
"model": "llama3.1:8b",
"messages": [
{"role": "user", "content": "Create a Java class named Hello with a main method that prints Hello"}
],
"stream": false
}'
```
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,5 @@ dependencies {
}

application {
mainClass.set("de.tuda.stg.securecoder.openapibridge.MainKt")
}

tasks.named<JavaExec>("run") {
val keys = listOf(
"OPENROUTER_KEY",
"MODEL",
"OLLAMA_BASE_URL",
"OLLAMA_KEEP_ALIVE",
"PORT"
)
keys.forEach { key ->
System.getProperty(key)?.let { value ->
systemProperty(key, value)
}
}
mainClass.set("de.tuda.stg.securecoder.openaibridge.MainKt")
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package de.tuda.stg.securecoder.openapibridge
package de.tuda.stg.securecoder.openaibridge

import de.tuda.stg.securecoder.engine.Engine
import de.tuda.stg.securecoder.engine.file.edit.ApplyChanges.applyEdits
Expand All @@ -14,7 +14,7 @@ class AgentService(private val engine: Engine) {
val fileSystem = InMemoryFileSystem()
val userPrompt = messages.lastOrNull { it.role == "user" }?.content ?: ""
val result = engine.run(
prompt = userPrompt,
prompt = "$userPrompt\nOnly create ONE file!",
filesystem = fileSystem,
onEvent = { event ->
println("Internal Agent Event: $event")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package de.tuda.stg.securecoder.openapibridge
package de.tuda.stg.securecoder.openaibridge

import de.tuda.stg.securecoder.engine.Engine
import de.tuda.stg.securecoder.engine.llm.LlmClient
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package de.tuda.stg.securecoder.openapibridge
package de.tuda.stg.securecoder.openaibridge

import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package de.tuda.stg.securecoder.openapibridge
package de.tuda.stg.securecoder.openaibridge

import io.ktor.server.request.*
import io.ktor.server.response.*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package de.tuda.stg.securecoder.openapibridge
package de.tuda.stg.securecoder.openaibridge

import kotlinx.serialization.Serializable

Expand Down
63 changes: 0 additions & 63 deletions app/openapi-bridge/README.md

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ object ApplyChanges {
return when (match) {
is Success.Append -> original + action.replaceText
is Success.Match -> buildString {
if (match.end > original.length) {
throw IllegalStateException(
"Match end index (${match.end}) is out of bounds for string of length ${original.length}. "
+ "Range: [${match.start}, ${match.end}), Replacement: '${action.replaceText}'"
)
}
append(original, 0, match.start)
append(action.replaceText)
append(original, match.end, original.length)
Expand All @@ -41,7 +47,7 @@ object ApplyChanges {
}
}

fun match(text: String, search: Changes.SearchedText): MatchResult {
fun match(text: String?, search: Changes.SearchedText): MatchResult {
return Matcher.RootMatcher.match(text, search)
}

Expand All @@ -50,8 +56,8 @@ object ApplyChanges {
val headerMessage: String = when (matchResult) {
is Error.NoMatch ->
"your *SEARCH* pattern not found in file $file"
is Error.ReplaceOnEmpty ->
"can only append to file $file as it is empty or does not exist but your *SEARCH* pattern is not empty"
is Error.ReplaceOnNotExistent ->
"can only append to file $file as it is does not exist but your *SEARCH* pattern is not empty"
is Error.MultipleMatch ->
"your *SEARCH* pattern has several matches in $file"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import de.tuda.stg.securecoder.engine.llm.ChatMessage.Role
import de.tuda.stg.securecoder.engine.llm.LlmClient
import de.tuda.stg.securecoder.filesystem.FileSystem
import de.tuda.stg.securecoder.engine.llm.ChatExchange
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlin.collections.plusAssign

class EditFilesLlmWrapper(
Expand Down Expand Up @@ -45,15 +48,14 @@ class EditFilesLlmWrapper(
attempts: Int = 3
): ChatResult {
val messages = messages.toMutableList()
messages += ChatMessage(Role.System, prompt)
appendPromptToLastSystem(messages)
repeat(attempts) {
val llmInput = messages.toList()
val response = llmClient.chat(llmInput, params)
messages += ChatMessage(Role.Assistant, response)
when (val result = parse(response, fileSystem)) {
is ParseResult.Ok -> return ChatResult(messages, result.value)
is ParseResult.Err -> {
println("LLM parse failed: ${result.buildMessage()}")
messages += ChatMessage(Role.User, result.buildMessage())
onParseError(result.messages, ChatExchange(llmInput, response))
}
Expand Down Expand Up @@ -91,7 +93,24 @@ class EditFilesLlmWrapper(
val matches = editsRegex.findAll(contentCopy).toList()

if (matches.isEmpty()) {
allErrors += "Did not find any *SEARCH/REPLACE* block within the `<EDIT>` tag"
allErrors += """
Could not find any edit blocks in the response.
Example for the expected format:
<EDIT1>
<FILE_PATH>src/Main.java</FILE_PATH>
<SEARCH>
...exact old text...
</SEARCH>
<REPLACE>
...new text...
</REPLACE>
</EDIT1>
<EDIT2>
<FILE_PATH>src/new.java</FILE_PATH>
<SEARCH></SEARCH>
<REPLACE>append</REPLACE>
</EDIT2>
""".trimIndent()
return ParseResult.Err(allErrors)
}

Expand Down Expand Up @@ -123,7 +142,7 @@ class EditFilesLlmWrapper(
continue
}
val replace = Changes.SearchReplace(currentFileName, SearchedText(searchPart ?: ""), replacePart ?: "")
val content = fileSystem.getFile(currentFileName)?.content() ?: ""
val content = fileSystem.getFile(currentFileName)?.content()
val match = ApplyChanges.match(content, replace.searchedText)
if (match is Matcher.MatchResult.Error) {
allErrors += ApplyChanges.buildErrorMessage(currentFileName, searchPart ?: "", match)
Expand All @@ -145,12 +164,26 @@ class EditFilesLlmWrapper(
}

private fun getTextByXMLTag(container: String, tag: String): String? {
val regex = Regex("<$tag>(.*?)</$tag>", setOf(RegexOption.MULTILINE, RegexOption.DOT_MATCHES_ALL))
val regex = Regex(
"<$tag>(.*?)</$tag>",
setOf(RegexOption.MULTILINE, RegexOption.DOT_MATCHES_ALL)
)
return regex.find(container)?.groups?.get(1)?.value
}

private fun removeStartingEmptyLine(content: String?): String? {
if (content == null) return null
return content.replaceFirst(Regex("^\\n"), "")
}

private fun appendPromptToLastSystem(messages: MutableList<ChatMessage>) {
val lastSystemIndex = messages.indexOfLast { it.role == Role.System }
if (lastSystemIndex >= 0) {
val existing = messages[lastSystemIndex]
val combined = "${existing.content}\n\n$prompt"
messages[lastSystemIndex] = ChatMessage(Role.System, combined)
} else {
messages += ChatMessage(Role.System, prompt)
}
}
}
Loading