Skip to content

Commit f9da4b0

Browse files
loghmanzadehclaude
andcommitted
Fix all ruff lint and format errors to unblock CI
- Remove unused variables (final_usage, finish_reason, bash_tool, new_table, collection_name) - Fix module docstrings placed after `from __future__ import annotations` (E402) - Add `from e`/`from None` to bare raises in except blocks (B904) - Fix misleading .rstrip("```") → .removesuffix("```") (B005) - Sort imports in grok_client.py and multi_agent.py (I001) - Remove quoted return type annotation in GrokClient.__aenter__ (UP037) - Split semicolon-separated statements in repl.py logo builder (E702) - Prefix unused loop variable url → _url (B007) - Fix MCP dispatcher closure to properly bind loop variable (B023) - Apply ruff format to all 21 affected files Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 195dbf2 commit f9da4b0

24 files changed

Lines changed: 531 additions & 314 deletions

grokcode/agent/agent.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,6 @@ async def run(
114114
# Accumulate the full response from streaming
115115
accumulated_content = ""
116116
accumulated_tool_calls = []
117-
final_usage: TokenUsage | None = None
118-
finish_reason: str | None = None
119117

120118
try:
121119
async for chunk in self.client.chat(messages, tools=tools, stream=stream):
@@ -124,15 +122,11 @@ async def run(
124122
yield ThinkingEvent(text=chunk.content)
125123
if chunk.tool_calls:
126124
accumulated_tool_calls = chunk.tool_calls
127-
finish_reason = chunk.finish_reason
128125
if chunk.usage:
129-
final_usage = chunk.usage
130126
total_usage = TokenUsage(
131127
input_tokens=total_usage.input_tokens + chunk.usage.input_tokens,
132128
output_tokens=total_usage.output_tokens + chunk.usage.output_tokens,
133129
)
134-
if chunk.finish_reason:
135-
finish_reason = chunk.finish_reason
136130

137131
except Exception as exc:
138132
yield ErrorEvent(message=f"API error: {exc}")
@@ -192,7 +186,9 @@ async def run(
192186

193187
# Exhausted max iterations
194188
self.message_history = [Message(**m) for m in messages[1:]]
195-
yield ErrorEvent(message=f"Max iterations ({MAX_ITERATIONS}) reached without completing task.")
189+
yield ErrorEvent(
190+
message=f"Max iterations ({MAX_ITERATIONS}) reached without completing task."
191+
)
196192

197193

198194
async def _get_git_branch() -> str | None:

grokcode/agent/grok_client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import httpx
1010

11-
from grokcode.agent.types import GrokResponse, RawToolCall, ToolCall, TokenUsage
11+
from grokcode.agent.types import GrokResponse, RawToolCall, TokenUsage, ToolCall
1212

1313
logger = logging.getLogger(__name__)
1414

@@ -37,7 +37,7 @@ def __init__(self, api_key: str, model: str = "grok-3-mini", max_tokens: int = 8
3737
async def close(self) -> None:
3838
await self._client.aclose()
3939

40-
async def __aenter__(self) -> "GrokClient":
40+
async def __aenter__(self) -> GrokClient:
4141
return self
4242

4343
async def __aexit__(self, *_: Any) -> None:

grokcode/agent/multi_agent.py

Lines changed: 50 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,20 @@ async def run_multi_agent(
4545
from grokcode.agent.grok_client import GrokClient
4646
from grokcode.agent.tool_registry import ToolRegistry
4747
from grokcode.tools.bash import BashTool
48-
from grokcode.tools.fs import FS_TOOL_SCHEMAS, edit_file, glob_files, grep_files, read_directory, read_file, write_file
48+
from grokcode.tools.fs import (
49+
FS_TOOL_SCHEMAS,
50+
edit_file,
51+
glob_files,
52+
grep_files,
53+
read_directory,
54+
read_file,
55+
write_file,
56+
)
4957
from grokcode.utils.ui import console
5058

51-
async with GrokClient(api_key=api_key, model=config.model, max_tokens=config.max_tokens) as client:
59+
async with GrokClient(
60+
api_key=api_key, model=config.model, max_tokens=config.max_tokens
61+
) as client:
5262
# Step 1: Orchestrator decomposes the task
5363
console.print(" [cyan]●[/cyan] Orchestrator: decomposing task...")
5464
subtasks = await _decompose_task(task, config, client)
@@ -84,17 +94,42 @@ async def locked_write_file(path: str, content: str) -> str:
8494

8595
async def run_subtask(subtask: SubtaskPlan) -> list[str]:
8696
async with semaphore:
87-
console.print(f" [yellow]→[/yellow] Starting sub-agent: {subtask.description[:60]}")
88-
bash_tool = BashTool(auto_confirm=auto_confirm)
97+
console.print(
98+
f" [yellow]→[/yellow] Starting sub-agent: {subtask.description[:60]}"
99+
)
89100
registry = ToolRegistry()
90101
registry.register("read_file", lambda path: read_file(path), FS_TOOL_SCHEMAS[0])
91-
registry.register("read_directory", lambda path, recursive=False: read_directory(path, recursive), FS_TOOL_SCHEMAS[1])
92-
registry.register("write_file", lambda path, content: locked_write_file(path, content), FS_TOOL_SCHEMAS[2])
93-
registry.register("edit_file", lambda path, old_str, new_str: locked_edit_file(path, old_str, new_str), FS_TOOL_SCHEMAS[3])
94-
registry.register("glob_files", lambda pattern, directory=".": glob_files(pattern, directory), FS_TOOL_SCHEMAS[5])
95-
registry.register("grep_files", lambda pattern, directory=".", file_glob="**/*": grep_files(pattern, directory, file_glob), FS_TOOL_SCHEMAS[6])
96-
97-
async with GrokClient(api_key=api_key, model=config.model, max_tokens=config.max_tokens) as sub_client:
102+
registry.register(
103+
"read_directory",
104+
lambda path, recursive=False: read_directory(path, recursive),
105+
FS_TOOL_SCHEMAS[1],
106+
)
107+
registry.register(
108+
"write_file",
109+
lambda path, content: locked_write_file(path, content),
110+
FS_TOOL_SCHEMAS[2],
111+
)
112+
registry.register(
113+
"edit_file",
114+
lambda path, old_str, new_str: locked_edit_file(path, old_str, new_str),
115+
FS_TOOL_SCHEMAS[3],
116+
)
117+
registry.register(
118+
"glob_files",
119+
lambda pattern, directory=".": glob_files(pattern, directory),
120+
FS_TOOL_SCHEMAS[5],
121+
)
122+
registry.register(
123+
"grep_files",
124+
lambda pattern, directory=".", file_glob="**/*": grep_files(
125+
pattern, directory, file_glob
126+
),
127+
FS_TOOL_SCHEMAS[6],
128+
)
129+
130+
async with GrokClient(
131+
api_key=api_key, model=config.model, max_tokens=config.max_tokens
132+
) as sub_client:
98133
agent = Agent(config=config, tool_registry=registry, grok_client=sub_client)
99134
files: list[str] = []
100135
async for event in agent.run(
@@ -105,7 +140,9 @@ async def run_subtask(subtask: SubtaskPlan) -> list[str]:
105140
if hasattr(event, "files_touched"):
106141
files.extend(event.files_touched) # type: ignore[attr-defined]
107142
if isinstance(event, DoneEvent):
108-
console.print(f" [green]✓[/green] Sub-agent done: {subtask.description[:50]}")
143+
console.print(
144+
f" [green]✓[/green] Sub-agent done: {subtask.description[:50]}"
145+
)
109146
elif isinstance(event, ErrorEvent):
110147
console.print(f" [red]✗[/red] Sub-agent error: {event.message[:80]}")
111148
return files
@@ -165,7 +202,7 @@ async def _decompose_task(
165202
full_response += chunk.content
166203

167204
# Strip markdown fences
168-
cleaned = re.sub(r"```(?:json)?\s*", "", full_response).strip().rstrip("```").strip()
205+
cleaned = re.sub(r"```(?:json)?\s*", "", full_response).strip().removesuffix("```").strip()
169206

170207
try:
171208
data = json.loads(cleaned)

grokcode/cli/config_cmd.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ def config_set(
3838
if key == "xai_api_key":
3939
try:
4040
set_api_key(value)
41-
print_success(f"API key stored securely in system keychain.")
41+
print_success("API key stored securely in system keychain.")
4242
except RuntimeError as e:
4343
print_error(str(e))
44-
raise typer.Exit(1)
44+
raise typer.Exit(1) from e
4545
# Also persist masked reference so config show works
4646
user_config.xai_api_key = value[:8] + "..." if len(value) > 8 else value
4747
save_user_config(user_config)
@@ -63,7 +63,7 @@ def config_set(
6363
coerced = value
6464
except ValueError:
6565
print_error(f"Invalid value {value!r} for key {key!r}")
66-
raise typer.Exit(1)
66+
raise typer.Exit(1) from None
6767

6868
setattr(user_config, key, coerced)
6969
save_user_config(user_config)
@@ -94,12 +94,15 @@ def config_show() -> None:
9494
ws = config.workspace_config
9595
table.add_row("workspace", ws.workspace, "grokcode.workspace.json")
9696
table.add_row("team_id", ws.team_id, "grokcode.workspace.json")
97-
table.add_row("collection_id", ws.collection_id or "[dim]not set[/dim]", "grokcode.workspace.json")
97+
table.add_row(
98+
"collection_id", ws.collection_id or "[dim]not set[/dim]", "grokcode.workspace.json"
99+
)
98100
table.add_row("rules count", str(len(ws.rules)), "grokcode.workspace.json")
99101
table.add_row("mcp_servers", str(len(ws.mcp_servers)), "grokcode.workspace.json")
100102

101103
console.print(table)
102104

103105
from grokcode.config.config import USER_CONFIG_DIR
106+
104107
console.print(f"\n [dim]Config dir:[/dim] {USER_CONFIG_DIR}")
105108
console.print(f" [dim]Audit log:[/dim] {USER_CONFIG_DIR / 'audit.log'}")

0 commit comments

Comments
 (0)