refactor: simplify code formatting and improve readability across multiple files
This commit is contained in:
@@ -15,11 +15,7 @@ from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoes
|
||||
|
||||
from app.core.config import settings
|
||||
from app.integrations.openclaw_gateway import GatewayConfig as GatewayClientConfig
|
||||
from app.integrations.openclaw_gateway import (
|
||||
OpenClawGatewayError,
|
||||
ensure_session,
|
||||
openclaw_call,
|
||||
)
|
||||
from app.integrations.openclaw_gateway import OpenClawGatewayError, ensure_session, openclaw_call
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.agents import Agent
|
||||
@@ -414,7 +410,9 @@ async def _supported_gateway_files(config: GatewayClientConfig) -> set[str]:
|
||||
if not agent_id:
|
||||
return set(DEFAULT_GATEWAY_FILES)
|
||||
files_payload = await openclaw_call(
|
||||
"agents.files.list", {"agentId": agent_id}, config=config,
|
||||
"agents.files.list",
|
||||
{"agentId": agent_id},
|
||||
config=config,
|
||||
)
|
||||
if isinstance(files_payload, dict):
|
||||
files = files_payload.get("files") or []
|
||||
@@ -438,11 +436,14 @@ async def _reset_session(session_key: str, config: GatewayClientConfig) -> None:
|
||||
|
||||
|
||||
async def _gateway_agent_files_index(
|
||||
agent_id: str, config: GatewayClientConfig,
|
||||
agent_id: str,
|
||||
config: GatewayClientConfig,
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
try:
|
||||
payload = await openclaw_call(
|
||||
"agents.files.list", {"agentId": agent_id}, config=config,
|
||||
"agents.files.list",
|
||||
{"agentId": agent_id},
|
||||
config=config,
|
||||
)
|
||||
if isinstance(payload, dict):
|
||||
files = payload.get("files") or []
|
||||
@@ -486,18 +487,14 @@ def _render_agent_files(
|
||||
)
|
||||
heartbeat_path = _templates_root() / heartbeat_template
|
||||
if heartbeat_path.exists():
|
||||
rendered[name] = (
|
||||
env.get_template(heartbeat_template).render(**context).strip()
|
||||
)
|
||||
rendered[name] = env.get_template(heartbeat_template).render(**context).strip()
|
||||
continue
|
||||
override = overrides.get(name)
|
||||
if override:
|
||||
rendered[name] = env.from_string(override).render(**context).strip()
|
||||
continue
|
||||
template_name = (
|
||||
template_overrides[name]
|
||||
if template_overrides and name in template_overrides
|
||||
else name
|
||||
template_overrides[name] if template_overrides and name in template_overrides else name
|
||||
)
|
||||
path = _templates_root() / template_name
|
||||
if path.exists():
|
||||
@@ -596,8 +593,7 @@ def _heartbeat_entry_map(
|
||||
entries: list[tuple[str, str, dict[str, Any]]],
|
||||
) -> dict[str, tuple[str, dict[str, Any]]]:
|
||||
return {
|
||||
agent_id: (workspace_path, heartbeat)
|
||||
for agent_id, workspace_path, heartbeat in entries
|
||||
agent_id: (workspace_path, heartbeat) for agent_id, workspace_path, heartbeat in entries
|
||||
}
|
||||
|
||||
|
||||
@@ -694,9 +690,7 @@ async def _remove_gateway_agent_list(
|
||||
raise OpenClawGatewayError(msg)
|
||||
|
||||
new_list = [
|
||||
entry
|
||||
for entry in lst
|
||||
if not (isinstance(entry, dict) and entry.get("id") == agent_id)
|
||||
entry for entry in lst if not (isinstance(entry, dict) and entry.get("id") == agent_id)
|
||||
]
|
||||
if len(new_list) == len(lst):
|
||||
return
|
||||
@@ -841,7 +835,9 @@ async def provision_main_agent(
|
||||
raise ValueError(msg)
|
||||
client_config = GatewayClientConfig(url=gateway.url, token=gateway.token)
|
||||
await ensure_session(
|
||||
gateway.main_session_key, config=client_config, label="Main Agent",
|
||||
gateway.main_session_key,
|
||||
config=client_config,
|
||||
label="Main Agent",
|
||||
)
|
||||
|
||||
agent_id = await _gateway_default_agent_id(
|
||||
|
||||
@@ -38,10 +38,7 @@ def _status_weight_expr() -> ColumnElement[int]:
|
||||
|
||||
def _priority_weight_expr() -> ColumnElement[int]:
|
||||
"""Return a SQL expression that sorts task priorities by configured order."""
|
||||
whens = [
|
||||
(col(Task.priority) == key, weight)
|
||||
for key, weight in _PRIORITY_ORDER.items()
|
||||
]
|
||||
whens = [(col(Task.priority) == key, weight) for key, weight in _PRIORITY_ORDER.items()]
|
||||
return case(*whens, else_=99)
|
||||
|
||||
|
||||
@@ -106,11 +103,7 @@ async def _agent_names(
|
||||
tasks: list[Task],
|
||||
) -> dict[UUID, str]:
|
||||
"""Return agent names keyed by assigned agent ids in the provided tasks."""
|
||||
assigned_ids = {
|
||||
task.assigned_agent_id
|
||||
for task in tasks
|
||||
if task.assigned_agent_id is not None
|
||||
}
|
||||
assigned_ids = {task.assigned_agent_id for task in tasks if task.assigned_agent_id is not None}
|
||||
if not assigned_ids:
|
||||
return {}
|
||||
return dict(
|
||||
|
||||
@@ -10,11 +10,7 @@ from sqlmodel import col, select
|
||||
from app.core.agent_tokens import generate_agent_token, hash_agent_token
|
||||
from app.core.time import utcnow
|
||||
from app.integrations.openclaw_gateway import GatewayConfig as GatewayClientConfig
|
||||
from app.integrations.openclaw_gateway import (
|
||||
OpenClawGatewayError,
|
||||
ensure_session,
|
||||
send_message,
|
||||
)
|
||||
from app.integrations.openclaw_gateway import OpenClawGatewayError, ensure_session, send_message
|
||||
from app.models.agents import Agent
|
||||
from app.services.agent_provisioning import (
|
||||
DEFAULT_HEARTBEAT_CONFIG,
|
||||
|
||||
@@ -55,8 +55,7 @@ def _agent_to_read(agent: Agent, main_session_keys: set[str]) -> AgentRead:
|
||||
model = AgentRead.model_validate(agent, from_attributes=True)
|
||||
computed_status = _computed_agent_status(agent)
|
||||
is_gateway_main = bool(
|
||||
agent.openclaw_session_id
|
||||
and agent.openclaw_session_id in main_session_keys,
|
||||
agent.openclaw_session_id and agent.openclaw_session_id in main_session_keys,
|
||||
)
|
||||
return model.model_copy(
|
||||
update={
|
||||
@@ -84,11 +83,7 @@ def _task_to_card(
|
||||
) -> TaskCardRead:
|
||||
card = TaskCardRead.model_validate(task, from_attributes=True)
|
||||
approvals_count, approvals_pending_count = counts_by_task_id.get(task.id, (0, 0))
|
||||
assignee = (
|
||||
agent_name_by_id.get(task.assigned_agent_id)
|
||||
if task.assigned_agent_id
|
||||
else None
|
||||
)
|
||||
assignee = agent_name_by_id.get(task.assigned_agent_id) if task.assigned_agent_id else None
|
||||
depends_on_task_ids = deps_by_task_id.get(task.id, [])
|
||||
blocked_by_task_ids = blocked_by_dependency_ids(
|
||||
dependency_ids=depends_on_task_ids,
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from app.models.agents import Agent
|
||||
|
||||
# Mention tokens are single, space-free words (e.g. "@alex", "@lead").
|
||||
|
||||
@@ -79,7 +79,8 @@ async def get_member(
|
||||
|
||||
|
||||
async def get_first_membership(
|
||||
session: AsyncSession, user_id: UUID,
|
||||
session: AsyncSession,
|
||||
user_id: UUID,
|
||||
) -> OrganizationMember | None:
|
||||
"""Return the oldest membership for a user, if any."""
|
||||
return (
|
||||
@@ -99,7 +100,8 @@ async def set_active_organization(
|
||||
member = await get_member(session, user_id=user.id, organization_id=organization_id)
|
||||
if member is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="No org access",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No org access",
|
||||
)
|
||||
if user.active_organization_id != organization_id:
|
||||
user.active_organization_id = organization_id
|
||||
@@ -177,8 +179,7 @@ async def accept_invite(
|
||||
access_rows = list(
|
||||
await session.exec(
|
||||
select(OrganizationInviteBoardAccess).where(
|
||||
col(OrganizationInviteBoardAccess.organization_invite_id)
|
||||
== invite.id,
|
||||
col(OrganizationInviteBoardAccess.organization_invite_id) == invite.id,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -207,7 +208,8 @@ async def accept_invite(
|
||||
|
||||
|
||||
async def ensure_member_for_user(
|
||||
session: AsyncSession, user: User,
|
||||
session: AsyncSession,
|
||||
user: User,
|
||||
) -> OrganizationMember:
|
||||
"""Ensure a user has some membership, creating one if necessary."""
|
||||
existing = await get_active_membership(session, user)
|
||||
@@ -291,21 +293,27 @@ async def require_board_access(
|
||||
) -> OrganizationMember:
|
||||
"""Require board access for a user and return matching membership."""
|
||||
member = await get_member(
|
||||
session, user_id=user.id, organization_id=board.organization_id,
|
||||
session,
|
||||
user_id=user.id,
|
||||
organization_id=board.organization_id,
|
||||
)
|
||||
if member is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="No org access",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No org access",
|
||||
)
|
||||
if not await has_board_access(session, member=member, board=board, write=write):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Board access denied",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Board access denied",
|
||||
)
|
||||
return member
|
||||
|
||||
|
||||
def board_access_filter(
|
||||
member: OrganizationMember, *, write: bool,
|
||||
member: OrganizationMember,
|
||||
*,
|
||||
write: bool,
|
||||
) -> ColumnElement[bool]:
|
||||
"""Build a SQL filter expression for boards visible to a member."""
|
||||
if write and member_all_boards_write(member):
|
||||
|
||||
@@ -42,10 +42,7 @@ class SoulRef:
|
||||
def _parse_sitemap_soul_refs(sitemap_xml: str) -> list[SoulRef]:
|
||||
"""Parse sitemap XML and extract valid souls.directory handle/slug refs."""
|
||||
# Extract <loc> values without XML entity expansion.
|
||||
urls = [
|
||||
unescape(match.group(1)).strip()
|
||||
for match in _LOC_PATTERN.finditer(sitemap_xml)
|
||||
]
|
||||
urls = [unescape(match.group(1)).strip() for match in _LOC_PATTERN.finditer(sitemap_xml)]
|
||||
|
||||
refs: list[SoulRef] = []
|
||||
for url in urls:
|
||||
@@ -110,10 +107,7 @@ async def fetch_soul_markdown(
|
||||
normalized_slug = slug.strip().strip("/")
|
||||
if normalized_slug.endswith(".md"):
|
||||
normalized_slug = normalized_slug[: -len(".md")]
|
||||
url = (
|
||||
f"{SOULS_DIRECTORY_BASE_URL}/api/souls/"
|
||||
f"{normalized_handle}/{normalized_slug}.md"
|
||||
)
|
||||
url = f"{SOULS_DIRECTORY_BASE_URL}/api/souls/" f"{normalized_handle}/{normalized_slug}.md"
|
||||
|
||||
owns_client = client is None
|
||||
if client is None:
|
||||
|
||||
@@ -79,11 +79,7 @@ def blocked_by_dependency_ids(
|
||||
status_by_id: Mapping[UUID, str],
|
||||
) -> list[UUID]:
|
||||
"""Return dependency ids that are not yet in the done status."""
|
||||
return [
|
||||
dep_id
|
||||
for dep_id in dependency_ids
|
||||
if status_by_id.get(dep_id) != DONE_STATUS
|
||||
]
|
||||
return [dep_id for dep_id in dependency_ids if status_by_id.get(dep_id) != DONE_STATUS]
|
||||
|
||||
|
||||
async def blocked_by_for_task(
|
||||
|
||||
@@ -14,11 +14,7 @@ from sqlalchemy import func
|
||||
from sqlmodel import col, select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from app.core.agent_tokens import (
|
||||
generate_agent_token,
|
||||
hash_agent_token,
|
||||
verify_agent_token,
|
||||
)
|
||||
from app.core.agent_tokens import generate_agent_token, hash_agent_token, verify_agent_token
|
||||
from app.core.time import utcnow
|
||||
from app.integrations.openclaw_gateway import GatewayConfig as GatewayClientConfig
|
||||
from app.integrations.openclaw_gateway import OpenClawGatewayError, openclaw_call
|
||||
@@ -108,10 +104,7 @@ def _is_transient_gateway_error(exc: Exception) -> bool:
|
||||
|
||||
|
||||
def _gateway_timeout_message(exc: OpenClawGatewayError) -> str:
|
||||
return (
|
||||
"Gateway unreachable after 10 minutes (template sync timeout). "
|
||||
f"Last error: {exc}"
|
||||
)
|
||||
return "Gateway unreachable after 10 minutes (template sync timeout). " f"Last error: {exc}"
|
||||
|
||||
|
||||
class _GatewayBackoff:
|
||||
@@ -375,6 +368,7 @@ async def _rotate_agent_token(session: AsyncSession, agent: Agent) -> str:
|
||||
|
||||
async def _ping_gateway(ctx: _SyncContext, result: GatewayTemplatesSyncResult) -> bool:
|
||||
try:
|
||||
|
||||
async def _do_ping() -> object:
|
||||
return await openclaw_call("agents.list", config=ctx.config)
|
||||
|
||||
@@ -486,6 +480,7 @@ async def _sync_one_agent(
|
||||
if not auth_token:
|
||||
return False
|
||||
try:
|
||||
|
||||
async def _do_provision() -> None:
|
||||
await provision_agent(
|
||||
agent,
|
||||
@@ -533,10 +528,7 @@ async def _sync_main_agent(
|
||||
if main_agent is None:
|
||||
_append_sync_error(
|
||||
result,
|
||||
message=(
|
||||
"Gateway main agent record not found; "
|
||||
"skipping main agent template sync."
|
||||
),
|
||||
message=("Gateway main agent record not found; " "skipping main agent template sync."),
|
||||
)
|
||||
return True
|
||||
try:
|
||||
@@ -574,6 +566,7 @@ async def _sync_main_agent(
|
||||
return True
|
||||
stop_sync = False
|
||||
try:
|
||||
|
||||
async def _do_provision_main() -> None:
|
||||
await provision_main_agent(
|
||||
main_agent,
|
||||
|
||||
Reference in New Issue
Block a user