The world's first agentic reverse engineer.
rm inline imports
Amruth3ef303bb5d85
diff --git a/kong/__main__.py b/kong/__main__.pyindex db12a48..7731c1a 100644--- a/kong/__main__.py+++ b/kong/__main__.py@@ -19,6 +19,11 @@ from kong.config import GhidraConfig, KongConfig, LLMConfig, LLMProvider, Outputfrom kong.evals.harness import score as eval_scorefrom kong.ghidra.client import GhidraClient, GhidraClientErrorfrom kong.llm.usage import TokenUsage+from kong.banner import _ENV_VARS, _KEY_EXAMPLES, _KEY_URLS+from kong.llm.openai_client import OpenAIClient+from kong.llm.client import AnthropicClient+from kong.tui.app import KongApp+if TYPE_CHECKING:from kong.agent.analyzer import LLMClient@@ -37,9 +42,7 @@ def create_llm_client(config: LLMConfig) -> LLMClient:# will generalize further in the futuremodel = config.model or _DEFAULT_MODELS[config.provider]if config.provider is LLMProvider.OPENAI:- from kong.llm.openai_client import OpenAIClientreturn OpenAIClient(model=model, api_key=config.api_key)- from kong.llm.client import AnthropicClientreturn AnthropicClient(model=model, api_key=config.api_key)@@ -204,7 +207,6 @@ def analyze(_print_final_stats(supervisor, llm_client)client.close()else:- from kong.tui.app import KongAppapp = KongApp(supervisor)try:app.run()@@ -262,8 +264,6 @@ def setup() -> None:print_banner(console)console.print()- from kong.banner import _ENV_VARS, _KEY_EXAMPLES, _KEY_URLS-step = 1for provider in LLMProvider:env_var = _ENV_VARS[provider]diff --git a/kong/agent/analyzer.py b/kong/agent/analyzer.pyindex 977d70c..ad4a3c8 100644--- a/kong/agent/analyzer.py+++ b/kong/agent/analyzer.py@@ -19,6 +19,7 @@ from kong.agent.queue import WorkItemfrom kong.ghidra.client import GhidraClientfrom kong.ghidra.types import BinaryInfo, FunctionInfo, StringEntry, StructDefinitionfrom kong.normalizer.syntactic import normalize+from kong.agent.deobfuscator import classify_obfuscationif TYPE_CHECKING:from kong.agent.deobfuscator import Deobfuscator@@ -171,7 +172,6 @@ class Analyzer:model: str | None = None,) -> FunctionResult:"""Full analysis pipeline for one function."""- from kong.agent.deobfuscator import classify_obfuscationfunc = item.functioncontext = self._build_context(item, binary_info, known_results, strings, known_types)diff --git a/kong/evals/metrics.py b/kong/evals/metrics.pyindex 6ddc726..70c02d1 100644--- a/kong/evals/metrics.py+++ b/kong/evals/metrics.py@@ -4,6 +4,8 @@ from __future__ import annotationsimport re+from kong.evals.harness import match_functions+_SYNONYM_GROUPS: list[set[str]] = [{"search", "find", "lookup"},@@ -189,7 +191,6 @@ def overall_score(truth: list[dict[str, str]],) -> dict[str, float]:"""Compute aggregate symbol and type accuracy across matched functions."""- from kong.evals.harness import match_functionsmatches = match_functions(predicted, truth)diff --git a/kong/llm/openai_client.py b/kong/llm/openai_client.pyindex f8b9d6b..83b1f51 100644--- a/kong/llm/openai_client.py+++ b/kong/llm/openai_client.py@@ -144,9 +144,9 @@ class OpenAIClient:self._record_usage(response, self.model)choice = response.choices[0]+ last_text = choice.message.content or ""if choice.finish_reason != "tool_calls":- last_text = choice.message.content or ""result = Analyzer.parse_llm_json(last_text)result.input_tokens = total_inputresult.output_tokens = total_outputdiff --git a/tests/test_deobfuscator.py b/tests/test_deobfuscator.pyindex 50797ce..60da23d 100644--- a/tests/test_deobfuscator.py+++ b/tests/test_deobfuscator.py@@ -19,6 +19,11 @@ from kong.agent.deobfuscator import ()from kong.agent.models import FunctionResultfrom kong.ghidra.types import BinaryInfo, FunctionInfo+from kong.agent.prompts import DEOBFUSCATION_SYSTEM_PROMPT+from kong.llm.tools import DEOBFUSCATION_TOOLS+from kong.agent.analyzer import Analyzer+from kong.agent.queue import WorkItem+from kong.agent.deobfuscator import Deobfuscator_CFF_CODE = """\@@ -218,8 +223,6 @@ class TestDeobfuscator:assert "bogus_cf" in promptdef test_passes_deobfuscation_system_prompt(self, mock_ghidra, mock_llm):- from kong.agent.prompts import DEOBFUSCATION_SYSTEM_PROMPT-deob = Deobfuscator(mock_ghidra, mock_llm)context = _make_context()deob.deobfuscate(context, [ObfuscationType.BOGUS_CONTROL_FLOW])@@ -228,8 +231,6 @@ class TestDeobfuscator:assert system == DEOBFUSCATION_SYSTEM_PROMPTdef test_passes_tools(self, mock_ghidra, mock_llm):- from kong.llm.tools import DEOBFUSCATION_TOOLS-deob = Deobfuscator(mock_ghidra, mock_llm)context = _make_context()deob.deobfuscate(context, [ObfuscationType.INSTRUCTION_SUBSTITUTION])@@ -240,9 +241,6 @@ class TestDeobfuscator:class TestAnalyzerDeobfuscationIntegration:def test_obfuscated_function_delegates(self):- from kong.agent.analyzer import Analyzer- from kong.agent.queue import WorkItem-mock_ghidra = MagicMock()mock_ghidra.get_decompilation.return_value = _CFF_CODEmock_ghidra.get_xrefs_from.return_value = []@@ -254,7 +252,6 @@ class TestAnalyzerDeobfuscationIntegration:classification="crypto",)- from kong.agent.deobfuscator import Deobfuscatordeob = Deobfuscator(mock_ghidra, mock_llm)analyzer = Analyzer(mock_ghidra, mock_llm, deobfuscator=deob)@@ -277,8 +274,6 @@ class TestAnalyzerDeobfuscationIntegration:mock_llm.analyze_with_tools.assert_called_once()def test_clean_function_uses_normal_path(self):- from kong.agent.analyzer import Analyzer- from kong.agent.queue import WorkItemmock_ghidra = MagicMock()mock_ghidra.get_decompilation.return_value = _CLEAN_CODE@@ -291,7 +286,6 @@ class TestAnalyzerDeobfuscationIntegration:classification="math",)- from kong.agent.deobfuscator import Deobfuscatordeob = Deobfuscator(mock_ghidra, mock_llm)analyzer = Analyzer(mock_ghidra, mock_llm, deobfuscator=deob)diff --git a/tests/test_llm_tools.py b/tests/test_llm_tools.pyindex fd4bc8f..d64bd0a 100644--- a/tests/test_llm_tools.py+++ b/tests/test_llm_tools.py@@ -12,6 +12,7 @@ from kong.llm.tools import (ToolCallRecord,ToolExecutor,)+from kong.llm.client import AnthropicClientclass TestToolSchemas:@@ -135,7 +136,6 @@ class TestToolUseLoop:return msgdef test_no_tool_calls(self):- from kong.llm.client import AnthropicClientjson_response = json.dumps({"name": "simple_func",@@ -163,7 +163,6 @@ class TestToolUseLoop:assert response.confidence == 85def test_single_tool_call(self):- from kong.llm.client import AnthropicClientjson_response = json.dumps({"name": "deobfuscated_func",@@ -198,7 +197,6 @@ class TestToolUseLoop:assert mock_client.messages.create.call_count == 2def test_max_rounds_limit(self):- from kong.llm.client import AnthropicClienttool_msg = self._mock_tool_use_message("simplify_expression",diff --git a/tests/test_openai_client.py b/tests/test_openai_client.pyindex 36fcaa5..99e96d9 100644--- a/tests/test_openai_client.py+++ b/tests/test_openai_client.py@@ -253,6 +253,45 @@ class TestOpenAIToolUse:assert result.output_tokens == 60executor.execute.assert_called_once_with("simplify_expression", {"expression": "x + 0"})+ @patch("kong.llm.openai_client.openai.OpenAI")+ def test_max_rounds_exhausted_uses_last_content(self, mock_openai_cls):+ mock_client = MagicMock()+ mock_openai_cls.return_value = mock_client++ tool_call = MagicMock()+ tool_call.id = "call_abc"+ tool_call.function.name = "lookup"+ tool_call.function.arguments = '{"key": "val"}'++ def make_tool_response(content: str | None):+ resp = _mock_response("", prompt_tokens=50, completion_tokens=20)+ resp.choices[0].finish_reason = "tool_calls"+ resp.choices[0].message.content = content+ resp.choices[0].message.tool_calls = [tool_call]+ return resp++ mock_client.chat.completions.create.side_effect = [+ make_tool_response(None),+ make_tool_response('{"name": "last_round", "confidence": 60}'),+ ]++ executor = MagicMock()+ executor.execute.return_value = '{"result": "ok"}'++ tools = [{+ "name": "lookup",+ "description": "Look up a value.",+ "input_schema": {"type": "object", "properties": {"key": {"type": "string"}}},+ }]++ client = OpenAIClient(api_key="test-key")+ result = client.analyze_with_tools("prompt", "system", tools, executor, max_rounds=2)++ assert result.name == "last_round"+ assert result.confidence == 60+ assert result.input_tokens == 100+ assert result.output_tokens == 40+class TestConvertTools:def test_converts_anthropic_to_openai_format(self):diff --git a/tests/test_synthesis.py b/tests/test_synthesis.pyindex 641ef6e..a09b2b2 100644--- a/tests/test_synthesis.py+++ b/tests/test_synthesis.py@@ -7,7 +7,7 @@ from dataclasses import dataclassimport pytestfrom kong.agent.models import FunctionResult-from kong.synthesis.semantic import SemanticSynthesizer, SynthesisResult+from kong.synthesis.semantic import SemanticSynthesizer, SynthesisResult, SYNTHESIS_FUNCTION_CAP@dataclass@@ -183,7 +183,6 @@ Trailing text'''class TestSynthesisCap:def test_synthesis_caps_at_50_functions(self) -> None:- from kong.synthesis.semantic import SYNTHESIS_FUNCTION_CAPresults = [_make_result(i, f"func_{i}") for i in range(100)]decomps = {i: f"void func_{i}(void) {{ DAT_1000 = 1; }}" for i in range(100)}diff --git a/tests/test_type_recovery.py b/tests/test_type_recovery.pyindex 8dd916d..a31a36e 100644--- a/tests/test_type_recovery.py+++ b/tests/test_type_recovery.py@@ -27,6 +27,10 @@ from kong.ghidra.types import (StructDefinition,StructField,)+from kong.agent.events import EventType+from kong.agent.supervisor import Supervisor+from kong.config import KongConfig, OutputConfig+from kong.agent.queue import WorkItemdef _field(name: str, dtype: str, offset: int, size: int) -> StructFieldProposal:@@ -331,7 +335,6 @@ class TestAnalyzerContextTypes:)client.get_xrefs_from.return_value = []- from kong.agent.queue import WorkItemitem = WorkItem(function=FunctionInfo(address=0x1000, name="FUN_00001000", size=100,@@ -374,7 +377,6 @@ class TestAnalyzerContextTypes:)client.get_xrefs_from.return_value = []- from kong.agent.queue import WorkItemitem = WorkItem(function=FunctionInfo(address=0x1000, name="f", size=100,@@ -418,7 +420,6 @@ class TestAnalyzerStructProposalPassthrough:)client.get_xrefs_from.return_value = []- from kong.agent.queue import WorkItemitem = WorkItem(function=FunctionInfo(address=0x1000, name="f", size=100,@@ -440,10 +441,6 @@ class TestAnalyzerStructProposalPassthrough:class TestSupervisorCleanupIntegration:def test_cleanup_with_struct_proposals(self, tmp_path):- from kong.agent.events import EventType, Phase- from kong.agent.supervisor import Supervisor- from kong.config import KongConfig, OutputConfig-funcs = [FunctionInfo(address=0x1000, name="process", size=100,@@ -495,10 +492,6 @@ class TestSupervisorCleanupIntegration:assert EventType.CLEANUP_TYPE_CREATED in event_typesdef test_cleanup_without_struct_proposals(self, tmp_path):- from kong.agent.events import EventType- from kong.agent.supervisor import Supervisor- from kong.config import KongConfig, OutputConfig-funcs = [FunctionInfo(address=0x1000, name="f", size=100,@@ -535,10 +528,7 @@ class TestSupervisorCleanupIntegration:def test_cleanup_retries_failed_signatures(self, tmp_path):"""Signatures that fail during Phase 2 (type not yet created) get- retried after struct creation in cleanup."""- from kong.agent.events import EventType- from kong.agent.supervisor import Supervisor- from kong.config import KongConfig, OutputConfig+ retried after struct creation in cleanup."""funcs = [FunctionInfo(