Skip to content

Commit 3ce6bfc

Browse files
committed
chore: apply pre-commit formatting fixes
Normalize formatting after running the project pre-commit hooks and fix the remaining ruff warnings. Made-with: Cursor
1 parent 20705d5 commit 3ce6bfc

36 files changed

Lines changed: 777 additions & 384 deletions

cli/cli_app.py

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -406,9 +406,7 @@ async def _handle_at_shortcut(self, target: str) -> str:
406406
case the user already saw an error toast).
407407
"""
408408
if not target:
409-
self.cli.print_status(
410-
"Usage: @<file-path> or @<url>", "warning"
411-
)
409+
self.cli.print_status("Usage: @<file-path> or @<url>", "warning")
412410
return ""
413411

414412
# Strip optional surrounding quotes (clipboard pastes often
@@ -422,24 +420,18 @@ async def _handle_at_shortcut(self, target: str) -> str:
422420

423421
# URL branch — anything starting with http(s)://
424422
if lowered.startswith(("http://", "https://")):
425-
self.cli.print_status(
426-
f"@-shortcut → URL: {target}", "info"
427-
)
423+
self.cli.print_status(f"@-shortcut → URL: {target}", "info")
428424
await self.process_input(target, "url")
429425
return "u"
430426

431427
# File branch — accept ``file://`` prefix and existence check.
432-
raw_path = target[len("file://"):] if lowered.startswith("file://") else target
428+
raw_path = target[len("file://") :] if lowered.startswith("file://") else target
433429
if not os.path.exists(raw_path):
434-
self.cli.print_status(
435-
f"Path not found: {raw_path}", "error"
436-
)
430+
self.cli.print_status(f"Path not found: {raw_path}", "error")
437431
return ""
438432

439433
abspath = os.path.abspath(raw_path)
440-
self.cli.print_status(
441-
f"@-shortcut → File: {abspath}", "info"
442-
)
434+
self.cli.print_status(f"@-shortcut → File: {abspath}", "info")
443435
await self.process_input(f"file://{abspath}", "file")
444436
return "f"
445437

@@ -465,9 +457,7 @@ def _handle_slash_command(self, raw: str) -> None:
465457
from core.observability import current_session_id, set_session
466458
from core.sessions import get_default_store
467459
except Exception as exc:
468-
self.cli.print_status(
469-
f"Session subsystem unavailable: {exc}", "error"
470-
)
460+
self.cli.print_status(f"Session subsystem unavailable: {exc}", "error")
471461
return
472462

473463
parts = raw.strip().split(maxsplit=1)
@@ -483,9 +473,7 @@ def _handle_slash_command(self, raw: str) -> None:
483473
if cmd in ("/session", "/whoami"):
484474
sid = current_session_id()
485475
session = store.get_session(sid) if sid else None
486-
self.cli.print_active_session(
487-
sid, session.title if session else None
488-
)
476+
self.cli.print_active_session(sid, session.title if session else None)
489477
return
490478

491479
if cmd in ("/resume", "/sessions", "/load"):
@@ -497,9 +485,7 @@ def _handle_slash_command(self, raw: str) -> None:
497485
if session is None:
498486
# Treat input as a prefix — try to disambiguate against
499487
# the listed summaries before giving up.
500-
candidates = [
501-
s for s in summaries if s.session_id.startswith(picked)
502-
]
488+
candidates = [s for s in summaries if s.session_id.startswith(picked)]
503489
if len(candidates) == 1:
504490
session = store.get_session(candidates[0].session_id)
505491
elif len(candidates) > 1:
@@ -510,9 +496,7 @@ def _handle_slash_command(self, raw: str) -> None:
510496
)
511497
return
512498
if session is None:
513-
self.cli.print_status(
514-
f"Session '{picked}' not found.", "error"
515-
)
499+
self.cli.print_status(f"Session '{picked}' not found.", "error")
516500
return
517501
set_session(session.session_id)
518502
self.cli.print_status(
@@ -578,9 +562,7 @@ async def run_interactive_session(self):
578562
# ask_continue check below behaves the same as if the
579563
# user had picked [F] / [U] from the menu.
580564
if choice_raw.startswith("@"):
581-
effective = await self._handle_at_shortcut(
582-
choice_raw[1:].strip()
583-
)
565+
effective = await self._handle_at_shortcut(choice_raw[1:].strip())
584566
if effective in ("f", "u"):
585567
choice = effective
586568
else:

cli/cli_interface.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -301,8 +301,7 @@ def pick_session_interactive(self, summaries) -> Optional[str]:
301301
f"({len(summaries)} total){Colors.ENDC}"
302302
)
303303
header = (
304-
f" {'#':<3} {'ID':<10} {'Updated':<26} "
305-
f"{'Tasks':<6} {'Msgs':<6} Title"
304+
f" {'#':<3} {'ID':<10} {'Updated':<26} " f"{'Tasks':<6} {'Msgs':<6} Title"
306305
)
307306
print(f"{Colors.BOLD}{header}{Colors.ENDC}")
308307
print(" " + "-" * (len(header) - 2))

cli/main_cli.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,9 @@ def handle_session_command(args):
303303
if sub == "show":
304304
target = args.session_arg or args.session
305305
if not target:
306-
print(f"{Colors.FAIL}Usage: deepcode session show <session_id>{Colors.ENDC}")
306+
print(
307+
f"{Colors.FAIL}Usage: deepcode session show <session_id>{Colors.ENDC}"
308+
)
307309
return 1
308310
session = store.get_session(target)
309311
if session is None:
@@ -315,7 +317,9 @@ def handle_session_command(args):
315317
if sub == "resume":
316318
target = args.session_arg or args.session
317319
if not target:
318-
print(f"{Colors.FAIL}Usage: deepcode session resume <session_id>{Colors.ENDC}")
320+
print(
321+
f"{Colors.FAIL}Usage: deepcode session resume <session_id>{Colors.ENDC}"
322+
)
319323
return 1
320324
session = store.get_session(target)
321325
if session is None:
@@ -338,7 +342,9 @@ def handle_session_command(args):
338342
if sub == "delete":
339343
target = args.session_arg
340344
if not target:
341-
print(f"{Colors.FAIL}Usage: deepcode session delete <session_id>{Colors.ENDC}")
345+
print(
346+
f"{Colors.FAIL}Usage: deepcode session delete <session_id>{Colors.ENDC}"
347+
)
342348
return 1
343349
if store.delete_session(target):
344350
print(f"{Colors.OKGREEN}Deleted session {target}{Colors.ENDC}")

core/agent_runtime/helpers.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,9 @@ def _bucket_mtime(path: Path) -> float:
121121

122122

123123
def _cleanup_tool_result_buckets(root: Path, current_bucket: Path) -> None:
124-
siblings = [path for path in root.iterdir() if path.is_dir() and path != current_bucket]
124+
siblings = [
125+
path for path in root.iterdir() if path.is_dir() and path != current_bucket
126+
]
125127
cutoff = time.time() - _TOOL_RESULT_RETENTION_SECS
126128
for path in siblings:
127129
if _bucket_mtime(path) < cutoff:
@@ -205,7 +207,9 @@ def build_assistant_message(
205207
if tool_calls:
206208
msg["tool_calls"] = tool_calls
207209
if reasoning_content is not None or thinking_blocks:
208-
msg["reasoning_content"] = reasoning_content if reasoning_content is not None else ""
210+
msg["reasoning_content"] = (
211+
reasoning_content if reasoning_content is not None else ""
212+
)
209213
if thinking_blocks:
210214
msg["thinking_blocks"] = thinking_blocks
211215
return msg

core/agent_runtime/hook.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ async def before_execute_tools(self, context: AgentHookContext) -> None:
5050
async def after_iteration(self, context: AgentHookContext) -> None:
5151
pass
5252

53-
def finalize_content(self, context: AgentHookContext, content: str | None) -> str | None:
53+
def finalize_content(
54+
self, context: AgentHookContext, content: str | None
55+
) -> str | None:
5456
return content
5557

5658

@@ -66,7 +68,9 @@ def __init__(self, hooks: list[AgentHook]) -> None:
6668
def wants_streaming(self) -> bool:
6769
return any(h.wants_streaming() for h in self._hooks)
6870

69-
async def _for_each_hook_safe(self, method_name: str, *args: Any, **kwargs: Any) -> None:
71+
async def _for_each_hook_safe(
72+
self, method_name: str, *args: Any, **kwargs: Any
73+
) -> None:
7074
for h in self._hooks:
7175
if getattr(h, "_reraise", False):
7276
await getattr(h, method_name)(*args, **kwargs)
@@ -75,7 +79,9 @@ async def _for_each_hook_safe(self, method_name: str, *args: Any, **kwargs: Any)
7579
try:
7680
await getattr(h, method_name)(*args, **kwargs)
7781
except Exception:
78-
logger.exception("AgentHook.{} error in {}", method_name, type(h).__name__)
82+
logger.exception(
83+
"AgentHook.{} error in {}", method_name, type(h).__name__
84+
)
7985

8086
async def before_iteration(self, context: AgentHookContext) -> None:
8187
await self._for_each_hook_safe("before_iteration", context)
@@ -92,7 +98,9 @@ async def before_execute_tools(self, context: AgentHookContext) -> None:
9298
async def after_iteration(self, context: AgentHookContext) -> None:
9399
await self._for_each_hook_safe("after_iteration", context)
94100

95-
def finalize_content(self, context: AgentHookContext, content: str | None) -> str | None:
101+
def finalize_content(
102+
self, context: AgentHookContext, content: str | None
103+
) -> str | None:
96104
for h in self._hooks:
97105
content = h.finalize_content(context, content)
98106
return content

core/agent_runtime/runner.py

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,9 @@ def _merge_message_content(left: Any, right: Any) -> str | list[dict[str, Any]]:
123123
def _to_blocks(value: Any) -> list[dict[str, Any]]:
124124
if isinstance(value, list):
125125
return [
126-
item if isinstance(item, dict) else {"type": "text", "text": str(item)}
126+
item
127+
if isinstance(item, dict)
128+
else {"type": "text", "text": str(item)}
127129
for item in value
128130
]
129131
if value is None:
@@ -213,7 +215,11 @@ async def _drain_injections(self, spec: AgentRunSpec) -> list[dict[str, Any]]:
213215
return []
214216
injected_messages: list[dict[str, Any]] = []
215217
for item in items:
216-
if isinstance(item, dict) and item.get("role") == "user" and "content" in item:
218+
if (
219+
isinstance(item, dict)
220+
and item.get("role") == "user"
221+
and "content" in item
222+
):
217223
injected_messages.append(item)
218224
continue
219225
text = getattr(item, "content", str(item))
@@ -248,12 +254,18 @@ async def run(self, spec: AgentRunSpec) -> AgentRunResult:
248254
for iteration in range(spec.max_iterations):
249255
try:
250256
messages_for_model = self._drop_orphan_tool_results(messages)
251-
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
257+
messages_for_model = self._backfill_missing_tool_results(
258+
messages_for_model
259+
)
252260
messages_for_model = self._microcompact(messages_for_model)
253-
messages_for_model = self._apply_tool_result_budget(spec, messages_for_model)
261+
messages_for_model = self._apply_tool_result_budget(
262+
spec, messages_for_model
263+
)
254264
messages_for_model = self._snip_history(spec, messages_for_model)
255265
messages_for_model = self._drop_orphan_tool_results(messages_for_model)
256-
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
266+
messages_for_model = self._backfill_missing_tool_results(
267+
messages_for_model
268+
)
257269
except Exception as exc:
258270
logger.warning(
259271
"Context governance failed on turn {} for {}: {}; applying minimal repair",
@@ -263,12 +275,16 @@ async def run(self, spec: AgentRunSpec) -> AgentRunResult:
263275
)
264276
try:
265277
messages_for_model = self._drop_orphan_tool_results(messages)
266-
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
278+
messages_for_model = self._backfill_missing_tool_results(
279+
messages_for_model
280+
)
267281
except Exception:
268282
messages_for_model = messages
269283
context = AgentHookContext(iteration=iteration, messages=messages)
270284
await hook.before_iteration(context)
271-
response = await self._request_model(spec, messages_for_model, hook, context)
285+
response = await self._request_model(
286+
spec, messages_for_model, hook, context
287+
)
272288
raw_usage = self._usage_dict(response.usage)
273289
context.response = response
274290
context.usage = dict(raw_usage)
@@ -335,7 +351,10 @@ async def run(self, spec: AgentRunSpec) -> AgentRunResult:
335351
context.error = error
336352
context.stop_reason = stop_reason
337353
await hook.after_iteration(context)
338-
should_continue, injection_cycles = await self._try_drain_injections(
354+
(
355+
should_continue,
356+
injection_cycles,
357+
) = await self._try_drain_injections(
339358
spec,
340359
messages,
341360
None,
@@ -401,7 +420,9 @@ async def run(self, spec: AgentRunSpec) -> AgentRunResult:
401420
)
402421
if hook.wants_streaming():
403422
await hook.on_stream_end(context, resuming=False)
404-
response = await self._request_finalization_retry(spec, messages_for_model)
423+
response = await self._request_finalization_retry(
424+
spec, messages_for_model
425+
)
405426
retry_usage = self._usage_dict(response.usage)
406427
self._accumulate_usage(usage, retry_usage)
407428
raw_usage = self._merge_usage(raw_usage, retry_usage)
@@ -529,7 +550,10 @@ async def run(self, spec: AgentRunSpec) -> AgentRunResult:
529550
template = spec.max_iterations_message or _DEFAULT_MAX_ITERATIONS_MESSAGE
530551
final_content = template.format(max_iterations=spec.max_iterations)
531552
self._append_final_message(messages, final_content)
532-
drained_after_max_iterations, injection_cycles = await self._try_drain_injections(
553+
(
554+
drained_after_max_iterations,
555+
injection_cycles,
556+
) = await self._try_drain_injections(
533557
spec,
534558
messages,
535559
None,
@@ -775,7 +799,9 @@ async def _emit_checkpoint(
775799
await callback(payload)
776800

777801
@staticmethod
778-
def _append_final_message(messages: list[dict[str, Any]], content: str | None) -> None:
802+
def _append_final_message(
803+
messages: list[dict[str, Any]], content: str | None
804+
) -> None:
779805
if not content:
780806
return
781807
if (
@@ -873,7 +899,9 @@ def _backfill_missing_tool_results(
873899
if tid:
874900
fulfilled.add(str(tid))
875901

876-
missing = [(ai, cid, name) for ai, cid, name in declared if cid not in fulfilled]
902+
missing = [
903+
(ai, cid, name) for ai, cid, name in declared if cid not in fulfilled
904+
]
877905
if not missing:
878906
return messages
879907

@@ -905,7 +933,9 @@ def _microcompact(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
905933
if len(compactable_indices) <= _MICROCOMPACT_KEEP_RECENT:
906934
return messages
907935

908-
stale = compactable_indices[: len(compactable_indices) - _MICROCOMPACT_KEEP_RECENT]
936+
stale = compactable_indices[
937+
: len(compactable_indices) - _MICROCOMPACT_KEEP_RECENT
938+
]
909939
updated: list[dict[str, Any]] | None = None
910940
for idx in stale:
911941
msg = messages[idx]
@@ -949,7 +979,9 @@ def _snip_history(
949979
if not messages or not spec.context_window_tokens:
950980
return messages
951981

952-
provider_max_tokens = getattr(getattr(self.provider, "generation", None), "max_tokens", 4096)
982+
provider_max_tokens = getattr(
983+
getattr(self.provider, "generation", None), "max_tokens", 4096
984+
)
953985
max_output = (
954986
spec.max_tokens
955987
if isinstance(spec.max_tokens, int)

core/agent_runtime/runtime.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ def external_lookup_signature(tool_name: str, arguments: dict[str, Any]) -> str
6161
if url:
6262
return f"web_fetch:{url.lower()}"
6363
if tool_name == "web_search":
64-
query = str(arguments.get("query") or arguments.get("search_term") or "").strip()
64+
query = str(
65+
arguments.get("query") or arguments.get("search_term") or ""
66+
).strip()
6567
if query:
6668
return f"web_search:{query.lower()}"
6769
return None

0 commit comments

Comments
 (0)