Repository navigation
ADFA-6268 | Add read_app_logs and read_ide_logs agent tools #113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d85ceda
feat(ai-core): add read_app_logs and read_ide_logs agent tools (ADFA-…
jatezzz 54b818b
fix(ai-core): address review on log tools (ADFA-6268)
jatezzz 61bb72c
fix(ai-core): address second review on log tools
jatezzz 78ecd26
fix(ai-core): return small log reads whole, anchor on crash when it fits
jatezzz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
97 changes: 97 additions & 0 deletions
97
...src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/handlers/LogWindowCalculator.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| package com.itsaky.androidide.plugins.aicore.tool.handlers | ||
|
|
||
| import com.itsaky.androidide.plugins.services.LogEntry | ||
| import com.itsaky.androidide.plugins.services.LogLevel | ||
|
|
||
| /** | ||
| * Selects the slice of a log the model needs, in whole lines and within [MAX_OUTPUT_CHARS] | ||
| * including the truncation markers. Only the kept lines are ever joined into a string. | ||
| */ | ||
| internal object LogWindowCalculator { | ||
| /** Maximum characters of log handed to the model, the same budget as build output. */ | ||
| const val MAX_OUTPUT_CHARS = 8000 | ||
|
jatezzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| private const val TRUNCATION_MARKER = "...[truncated]..." | ||
|
jatezzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| /** Markers of an app crash; the anchor prefers these over any earlier plain error. */ | ||
| private val CRASH_MARKERS = listOf("FATAL EXCEPTION", "Fatal signal") | ||
|
|
||
| /** | ||
| * A crash's exception and top frames sit where it starts, not in the tail of later chatter, | ||
| * so the window starts at the first crash line, else the first error line, and keeps the | ||
| * head of what follows. With neither, it keeps the newest lines. | ||
| */ | ||
| fun windowFor(entries: List<LogEntry>, hostTruncated: Boolean): OutputWindow { | ||
| val anchor = entries.indexOfFirst { isCrashLine(it) }.takeIf { it >= 0 } | ||
|
jatezzz marked this conversation as resolved.
Outdated
|
||
| ?: entries.indexOfFirst { it.level == LogLevel.ERROR }.takeIf { it >= 0 } | ||
| val text = if (anchor != null) { | ||
| head(entries.subList(anchor, entries.size), droppedBefore = hostTruncated || anchor > 0) | ||
| } else { | ||
| tail(entries, droppedBefore = hostTruncated) | ||
| } | ||
| return OutputWindow(text = text, anchoredOnError = anchor != null) | ||
| } | ||
|
|
||
| /** The oldest lines of [entries] that fit, marking what was dropped on either side. */ | ||
| private fun head(entries: List<LogEntry>, droppedBefore: Boolean): String { | ||
| val prefix = if (droppedBefore) "$TRUNCATION_MARKER\n" else "" | ||
| val room = MAX_OUTPUT_CHARS - prefix.length | ||
| if (fitCount(entries, room) == entries.size) return prefix + joined(entries) | ||
|
|
||
| val suffix = "\n$TRUNCATION_MARKER" | ||
| val kept = fitCount(entries, room - suffix.length) | ||
| val body = if (kept > 0) { | ||
| joined(entries.subList(0, kept)) | ||
| } else { | ||
| keepStart(entries.first().text, room - suffix.length) | ||
| } | ||
| return prefix + body + suffix | ||
| } | ||
|
|
||
| /** The newest lines of [entries] that fit, marking what was dropped before them. */ | ||
| private fun tail(entries: List<LogEntry>, droppedBefore: Boolean): String { | ||
| val prefix = "$TRUNCATION_MARKER\n" | ||
| val newestFirst = entries.asReversed() | ||
| if (!droppedBefore && fitCount(newestFirst, MAX_OUTPUT_CHARS) == entries.size) { | ||
| return joined(entries) | ||
| } | ||
|
|
||
| val room = MAX_OUTPUT_CHARS - prefix.length | ||
| val kept = fitCount(newestFirst, room) | ||
| val body = if (kept > 0) { | ||
| joined(entries.subList(entries.size - kept, entries.size)) | ||
| } else { | ||
| keepEnd(entries.last().text, room) | ||
| } | ||
| return prefix + body | ||
| } | ||
|
|
||
| /** How many of [entries], taken in order, fit in [room] characters once joined by newlines. */ | ||
| private fun fitCount(entries: List<LogEntry>, room: Int): Int { | ||
| var used = -1 // the first line needs no separator | ||
| var count = 0 | ||
| for (entry in entries) { | ||
| used += entry.text.length + 1 | ||
| if (used > room) break | ||
| count++ | ||
| } | ||
| return count | ||
| } | ||
|
|
||
| private fun joined(entries: List<LogEntry>): String = entries.joinToString("\n") { it.text } | ||
|
|
||
| /** The start of one oversized line, never splitting a surrogate pair. */ | ||
| private fun keepStart(text: String, room: Int): String { | ||
| val end = if (text[room - 1].isHighSurrogate()) room - 1 else room | ||
| return text.substring(0, end) | ||
| } | ||
|
|
||
| /** The end of one oversized line, never splitting a surrogate pair. */ | ||
| private fun keepEnd(text: String, room: Int): String { | ||
| val start = text.length - room | ||
| return text.substring(if (text[start].isLowSurrogate()) start + 1 else start) | ||
| } | ||
|
|
||
| private fun isCrashLine(entry: LogEntry): Boolean = | ||
| CRASH_MARKERS.any { entry.text.contains(it, ignoreCase = true) } | ||
| } | ||
149 changes: 149 additions & 0 deletions
149
...ore/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/handlers/ReadLogsHandler.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| package com.itsaky.androidide.plugins.aicore.tool.handlers | ||
|
|
||
| import com.itsaky.androidide.plugins.PluginContext | ||
| import com.itsaky.androidide.plugins.aicore.logging.AgentTrace | ||
| import com.itsaky.androidide.plugins.aicore.models.ToolResult | ||
| import com.itsaky.androidide.plugins.aicore.tool.ToolHandler | ||
| import com.itsaky.androidide.plugins.aicore.tool.ToolSchema | ||
| import com.itsaky.androidide.plugins.services.IdeLogService | ||
|
jatezzz marked this conversation as resolved.
|
||
| import com.itsaky.androidide.plugins.services.LogLevel | ||
| import com.itsaky.androidide.plugins.services.LogQuery | ||
| import com.itsaky.androidide.plugins.services.LogSource | ||
| import kotlinx.coroutines.CancellationException | ||
|
|
||
| /** | ||
| * Handler for reading one of the IDE's log tabs: App Logs (`read_app_logs`, the user's running | ||
| * app) or IDE Logs (`read_ide_logs`, CoGo and its plugins). Read-only, so it never asks. | ||
| */ | ||
| class ReadLogsHandler( | ||
| private val pluginContext: PluginContext, | ||
| private val source: LogSource, | ||
| ) : ToolHandler { | ||
| private val tab = tabFor(source) | ||
|
|
||
| override val toolName = tab.toolName | ||
| override val description = tab.description | ||
| override val requiresApproval = false | ||
| override val parametersSchema = ToolSchema.objectOf( | ||
| "min_level" to ToolSchema.string( | ||
| "Lowest level to include: verbose, debug, info, warning or error. Defaults to all levels." | ||
| ), | ||
| "filter" to ToolSchema.string( | ||
| "Case-insensitive text a line must contain, matched against its tag and message." | ||
| ), | ||
| ) | ||
|
|
||
| private val label = tab.label | ||
|
|
||
| override suspend fun execute(args: Map<String, Any?>): ToolResult { | ||
| val minLevel = args["min_level"]?.toString()?.trim().orEmpty() | ||
| val levels = if (minLevel.isEmpty()) { | ||
| emptySet() | ||
| } else { | ||
| levelsFrom(minLevel) ?: return ToolResult.failure( | ||
| "Unknown min_level '$minLevel'", | ||
| "Use one of: verbose, debug, info, warning, error." | ||
| ) | ||
| } | ||
| val filter = args["filter"]?.toString()?.trim().orEmpty() | ||
|
|
||
| return try { | ||
| val logService = pluginContext.services.get(IdeLogService::class.java) | ||
| if (logService == null) { | ||
| // A clear answer rather than a failure: the agent can say so and carry on. | ||
| AgentTrace.refusal("LOGS", "$toolName rejected", "IdeLogService not available") | ||
| return ToolResult.success( | ||
| message = "$label not available", | ||
| data = "(This version of Code on the Go does not let plugins read $label.)" | ||
| ) | ||
| } | ||
|
|
||
| val result = logService.readLogs( | ||
| source, | ||
| LogQuery(levels = levels, text = filter, maxLines = LogQuery.MAX_LINES), | ||
| ) | ||
| if (result.entries.isEmpty()) { | ||
| AgentTrace.detail("LOGS", "$toolName lines=0 levels=$levels filter=${filter.isNotEmpty()}") | ||
| ToolResult.success(message = "No $label", data = emptyMessage(filter, levels)) | ||
| } else { | ||
| val window = LogWindowCalculator.windowFor(result.entries, result.truncated) | ||
| AgentTrace.detail( | ||
| "LOGS", | ||
| "$toolName lines=${result.entries.size} chars=${window.text.length} " + | ||
| "anchoredOnError=${window.anchoredOnError} hostTruncated=${result.truncated}" | ||
| ) | ||
| ToolResult.success( | ||
| message = if (window.anchoredOnError) { | ||
| "$label from the first error (${window.text.length} characters)" | ||
| } else { | ||
| "$label (last ${window.text.length} characters)" | ||
| }, | ||
| data = window.text | ||
| ) | ||
| } | ||
| } catch (ce: CancellationException) { | ||
| // An Exception on the JVM, so the catch below would report Stop as a read failure. | ||
| throw ce | ||
| } catch (e: Exception) { | ||
| AgentTrace.refusal("LOGS", "$toolName failed", e.toString()) | ||
| pluginContext.logger.error("$toolName failed", e) | ||
| ToolResult.failure( | ||
| "Error reading $label", | ||
| "${e.message ?: "Unknown error"}\n\n${e.stackTraceToString()}" | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| private fun emptyMessage(filter: String, levels: Set<LogLevel>): String = | ||
| if (filter.isEmpty() && levels.isEmpty()) { | ||
| tab.emptyLog | ||
| } else { | ||
| "(No $label lines match that level or filter. Try again without them.)" | ||
| } | ||
|
|
||
| /** How the tool for one log tab is named and described, to the model and in messages. */ | ||
| private class LogTab( | ||
| val toolName: String, | ||
| val description: String, | ||
| val label: String, | ||
| val emptyLog: String, | ||
| ) | ||
|
|
||
| companion object { | ||
| private val ORDERED_LEVELS = listOf( | ||
| LogLevel.VERBOSE, LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARNING, LogLevel.ERROR, | ||
| ) | ||
|
|
||
| /** | ||
| * The levels at or above [name], which the host takes as an exact set. | ||
| * @param name a level name, case-insensitive; `warn` and `e`-style initials are accepted. | ||
| * @return the levels, or null when [name] is not a level. | ||
| */ | ||
| internal fun levelsFrom(name: String): Set<LogLevel>? { | ||
| val level = when (name.lowercase()) { | ||
| "verbose", "v" -> LogLevel.VERBOSE | ||
| "debug", "d" -> LogLevel.DEBUG | ||
| "info", "i" -> LogLevel.INFO | ||
| "warning", "warn", "w" -> LogLevel.WARNING | ||
| "error", "e" -> LogLevel.ERROR | ||
| else -> return null | ||
| } | ||
| return ORDERED_LEVELS.subList(ORDERED_LEVELS.indexOf(level), ORDERED_LEVELS.size).toSet() | ||
| } | ||
|
|
||
| private fun tabFor(source: LogSource): LogTab = when (source) { | ||
| LogSource.APP -> LogTab( | ||
| toolName = "read_app_logs", | ||
|
jatezzz marked this conversation as resolved.
|
||
| description = "Read the App Logs of the user's running app, from the first crash or error", | ||
| label = "App Logs", | ||
| emptyLog = "(App Logs are empty. Run the app with run_app first, then read them again.)", | ||
|
jatezzz marked this conversation as resolved.
Outdated
|
||
| ) | ||
| LogSource.IDE -> LogTab( | ||
| toolName = "read_ide_logs", | ||
| description = "Read the IDE Logs of Code on the Go and its plugins, from the first error", | ||
| label = "IDE Logs", | ||
| emptyLog = "(IDE Logs are empty.)", | ||
| ) | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.