ac5d209fce
ci / JVM build + tests (push) Failing after 2m5s
Standalone refactor — modularity + correctness improvements after
STANDALONE-REVIEW findings. Touches ~30 files. Build green, 178 tests pass.
(1) Module extractions — generic components out of :standalone:
• :llm-tools (new KMP module, package pw.binom.agentik.llm.tools)
- LlmReflector, SkillMiner, LlmMemoryReviewer, LiteLlmContextCompactor
- Parsers: ReflectionParser, SkillMiningParser, ReviewDecisionParser
- Prompts: ReflectionPrompts, SkillMiningPrompts, ReviewPrompts
• :mcp-bridge (new JVM module, package pw.binom.agentik.mcp.bridge)
- McpConfig, McpRegistry, McpLiteToolAdapter
• NamedTool moved from :standalone to :agent-toolsets/commonMain
- Generic (name + LiteTool) wrapper, used by both :mcp-bridge
and :standalone's tool dispatcher
:standalone loses ~1400 lines, depends on the two new modules.
(2) Background work → event-driven (no more interval-polling):
• New :standalone/agent/BackgroundEvents.kt — internal event bus:
- ToolCallEvent.Succeeded/Failed (emitted by ToolDispatcher after invoke)
- CompactionEvent.Triggered (emitted by CompactionCoordinator pre-delete)
- ConversationLifecycleEvent.Closing (emitted by ConversationLoop.close)
• BackgroundScheduler rewritten as event subscriber:
- On Closing: final reflection + skill mining (last-chance extraction)
- On Compaction (turnsToDelete > 10): skill mining (debounced 60s)
- On ToolFailure x2 in 60s window: reflection (debounced 5min)
- Dropped: maybeScheduleReview/Reflection/SkillMining (interval-based)
- Dropped config: memoryReviewInterval, reflectionInterval, skillMiningInterval
• ToolDispatcher emits ToolCallEvent after each invoke.
• CompactionCoordinator emits CompactionEvent before workingMemory.compact().
• ConversationLoop.close() emits Closing BEFORE agentScope.cancel() so the
subscription gets to run final reflection/mining.
Net effect: typical 30-turn conversation runs ~38 LLM calls (was: 30 main +
3 review + 3 reflection + 2 mining). With event-driven, review/mining only fire
when their triggers actually make sense (compaction about to delete, or
conversation closing).
(3) AppConfig single source of truth:
• Replaces AgentikConfig + LlmConfig.fromEnv + McpConfig.fromEnv with one
AppConfig.fromEnv() that reads all ~25 env vars in a single pass.
• Sections: AgentSection, LlmSection, McpSection, MemorySection,
EmbeddingSection, ReflectionSection, SkillMiningSection, DebugSection.
• OPENAI_CONTEXT_WINDOW / AGENTIK_GOOGLE_CONTEXT_WINDOW no longer
read twice (was a bug per STANDALONE-REVIEW E3).
(4) Other fixes inherited from earlier waves:
• Hardening — size caps on user-input boundaries:
MAX_MEMORY_CONTENT_LEN=32KB, MAX_SKILL_BODY_LEN=64KB,
MAX_MCP_CONFIG_BYTES=1MB, MAX_A2A_REPLY_LEN=10MB, MAX_PORT=65535,
blank-rejection in LlmConfig.requireEnv, URL/command validation.
• Single scope — :standalone/agent/ConversationLoop has one
agentScope (was: scope + backgroundScope).
• liteConvRef race fix — capture-then-use pattern replaces !!-after-read;
close() + runTurn.finally race on LiteConv JNI handled via
AtomicReference.getAndSet.
• SkillMiner.maxTurns / LlmReflector.maxTurns exposed as public (needed
by BackgroundScheduler for prompt sizing).
• Tests: MemoryWiringTest updated for new compaction-triggered review
behavior; all parser/test imports updated for new packages.
Test results: 178/178 in :standalone, 36/36 in :agent-toolsets — all green.
164 lines
7.5 KiB
Kotlin
164 lines
7.5 KiB
Kotlin
@file:OptIn(org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi::class)
|
||
|
||
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
||
import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget
|
||
|
||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||
import org.gradle.api.artifacts.ConfigurationContainer
|
||
|
||
plugins {
|
||
alias(libs.plugins.kotlin.multiplatform)
|
||
alias(libs.plugins.kotlin.serialization)
|
||
alias(libs.plugins.shadow)
|
||
}
|
||
|
||
// CI-флаг: при -PskipVectorMemory=true :memory-vector не подключается как
|
||
// зависимость — нужно для CI runner'а (text-embedding-kmp ещё не опубликован
|
||
// в caffeine). Подробнее см. memory-vector/build.gradle.kts.
|
||
val skipVectorMemory: Boolean =
|
||
(project.findProperty("skipVectorMemory") == "true") ||
|
||
System.getenv("SKIP_VECTOR_MEMORY") == "1"
|
||
|
||
kotlin {
|
||
jvmToolchain(21)
|
||
|
||
jvm {
|
||
binaries {
|
||
executable {
|
||
mainClass.set("pw.binom.agentik.standalone.MainKt")
|
||
}
|
||
}
|
||
}
|
||
|
||
sourceSets {
|
||
commonMain.dependencies {
|
||
implementation(project(":proto"))
|
||
implementation(project(":server"))
|
||
|
||
// Commons
|
||
implementation(libs.kotlinx.coroutines.core)
|
||
implementation(libs.kotlinx.serialization.json)
|
||
|
||
// litert-kmp: контракт (commonMain)
|
||
api(libs.litert.api)
|
||
|
||
// litert-openai: JVM-реализация
|
||
implementation(libs.litert.openai)
|
||
}
|
||
|
||
jvmMain.dependencies {
|
||
// Парсер и загрузчик скилов (YAML frontmatter + markdown body).
|
||
implementation(project(":skills"))
|
||
|
||
// Долговременная память (Hermes-style MD-бэкенд) + хранилище истории.
|
||
implementation(project(":memory-api"))
|
||
implementation(project(":memory-md"))
|
||
if (!skipVectorMemory) {
|
||
implementation(project(":memory-vector"))
|
||
}
|
||
implementation(project(":storage-core"))
|
||
implementation(project(":storage-sqlite"))
|
||
implementation(project(":agent-toolsets"))
|
||
// Generic LLM-side tools (LlmReflector, SkillMiner, LlmMemoryReviewer,
|
||
// ContextCompactor, парсеры/промпты). Вынесены из :standalone.
|
||
implementation(project(":llm-tools"))
|
||
// Generic MCP-bridge (McpConfig, McpRegistry, McpLiteToolAdapter).
|
||
// Вынесен из :standalone — generic мост между MCP-SDK и LiteTool.
|
||
implementation(project(":mcp-bridge"))
|
||
|
||
// litert-google: встроенный LiteRT-LM движок, нужен только на runtime
|
||
runtimeOnly(libs.litert.google)
|
||
|
||
// Ktor server (для :server facade + a2aServer)
|
||
// Используем CIO вместо Netty — он KMP (jvm + linuxX64/ios/...), нам нужен
|
||
// для будущей native-сборки; на JVM работает идентично для нашего сценария.
|
||
implementation(libs.ktor.server.core)
|
||
implementation(libs.ktor.server.sse)
|
||
implementation(libs.ktor.server.cio)
|
||
implementation(libs.ktor.server.content.negotiation)
|
||
implementation(libs.ktor.serialization.kotlinx.json)
|
||
|
||
// Транспортные фасады (A2A остаётся заготовкой; на v1 не подключается в Main.kt —
|
||
// см. docs/ARCHITECTURE.md §3).
|
||
implementation(libs.a2a.server)
|
||
|
||
// MCP (Model Context Protocol) клиент — подключение внешних/внутренних MCP-серверов
|
||
implementation(libs.mcp.sdk.client)
|
||
implementation(libs.ktor.client.core)
|
||
implementation(libs.ktor.client.cio)
|
||
implementation(libs.ktor.client.content.negotiation)
|
||
implementation(libs.ktor.serialization.kotlinx.json)
|
||
|
||
// Логирование: kotlin-logging (тонкая обёртка slf4j-api) + logback-classic
|
||
// (binding для JVM; без него slf4j-api NOP-логирует и не падает).
|
||
implementation(libs.kotlin.logging)
|
||
implementation(libs.logback.classic)
|
||
}
|
||
|
||
commonTest.dependencies {
|
||
implementation(libs.kotlinx.coroutines.core)
|
||
implementation(libs.kotlin.test)
|
||
}
|
||
|
||
jvmTest.dependencies {
|
||
implementation(libs.kotlinx.coroutines.core)
|
||
implementation(libs.kotlinx.serialization.json)
|
||
implementation(libs.kotlin.test)
|
||
// Ktor test engine для smoke-тестов HTTP
|
||
implementation(libs.ktor.server.test.host)
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- Fatjar (uberjar) ---
|
||
//
|
||
// :standalone — KMP jvm-only бэкенд. Стандартный KMP `jvmJar` содержит только
|
||
// наши классы и требует подтянуть все зависимости на runtime через classpath.
|
||
// Для дистрибутива нужен self-contained `*-all.jar`, который содержит и наш
|
||
// код, и runtime classpath. Делается это Shadow-плагином:
|
||
//
|
||
// 1. shadowJar расширяет `jvmJar` (через from(tasks.named("jvmJar")))
|
||
// 2. Добавляет все артефакты из jvmRuntimeClasspath как `zipTree`
|
||
// 3. Корректно сливает META-INF/services (через ServiceFileTransformer)
|
||
// 4. Прописывает Main-Class в манифесте
|
||
//
|
||
// Результат: `build/libs/standalone-*-all.jar` запускается как
|
||
// java -jar standalone-0.1.0-all.jar
|
||
//
|
||
// KMP-сборка под ios/lin/macos не затрагивается — задача живёт только в jvm.
|
||
// Shadow 8.x не авторегистрирует shadowJar в KMP-проектах (нет стандартного `jar`),
|
||
// поэтому регистрируем явно через tasks.register.
|
||
//
|
||
// В Gradle 9 KGP подменяет `configurations` на сгенерированный dependency-accessor
|
||
// (он возвращает List), поэтому используем прямой доступ к Project API.
|
||
val shadowJarTask = tasks.register<ShadowJar>("shadowJar") {
|
||
archiveBaseName.set("standalone")
|
||
archiveClassifier.set("all")
|
||
description = "Self-contained fatjar with all runtime dependencies bundled."
|
||
group = "build"
|
||
|
||
from(tasks.named("jvmJar"))
|
||
// javaClass-каст через Any? чтобы вытащить реальный ConfigurationContainer
|
||
// из любого типа, который сейчас прикидывается `configurations`.
|
||
val cc = try {
|
||
@Suppress("UNCHECKED_CAST")
|
||
configurations as org.gradle.api.artifacts.ConfigurationContainer
|
||
} catch (_: ClassCastException) {
|
||
// KGP-generated dependency accessor; обходим через raw project.
|
||
@Suppress("UNCHECKED_CAST")
|
||
(project as org.gradle.api.Project).configurations as org.gradle.api.artifacts.ConfigurationContainer
|
||
}
|
||
from(cc.getByName("jvmRuntimeClasspath"))
|
||
|
||
mergeServiceFiles()
|
||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||
|
||
manifest {
|
||
attributes["Main-Class"] = "pw.binom.agentik.standalone.MainKt"
|
||
attributes["Implementation-Title"] = "agentik-standalone"
|
||
attributes["Implementation-Version"] = project.version.toString()
|
||
}
|
||
|
||
includeEmptyDirs = false
|
||
}
|