instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add verbose docstrings with examples
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from typing import Dict, List, Optional from fastapi import APIRouter, HTTPException, Request from pydantic import BaseModel, Field from ..download_task_store import ( DownloadTask, DownloadTaskStatus, get_task, ...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""API endpoints for Ollama model management. + +This router mirrors the local_models router but delegates lifecycle operations +(list / pull / delete) to the Ollama daemon via OllamaModelManager. Downloads +run in the background and their status can be polled by the fr...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/ollama_models.py
Add docstrings that explain purpose and usage
# -*- coding: utf-8 -*- from __future__ import annotations import re def _escape_html(text: str) -> str: return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") def markdown_to_telegram_html(text: str) -> str: if not text: return text placeholders: list[str] = [] def _...
--- +++ @@ -1,14 +1,39 @@ # -*- coding: utf-8 -*- +"""Convert standard Markdown to Telegram-compatible HTML. + +Telegram Bot API supports a subset of HTML tags: + <b>, <i>, <u>, <s>, <code>, <pre>, <a>, <tg-spoiler>, <blockquote> + +Standard Markdown (as produced by LLMs) uses **bold**, *italic*, `code`, +```code bloc...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/telegram/format_html.py
Generate docstrings with examples
# -*- coding: utf-8 -*- # pylint: disable=too-many-return-statements from __future__ import annotations import os from typing import Any, Optional from urllib.parse import urlparse from urllib.request import url2pathname def file_url_to_local_path(url: str) -> Optional[str]: if not url or not isinstance(url, str...
--- +++ @@ -1,5 +1,9 @@ # -*- coding: utf-8 -*- # pylint: disable=too-many-return-statements +""" +Bridge between channels and AgentApp process: factory to build +ProcessHandler from runner. Shared helpers for channels (e.g. file URL). +""" from __future__ import annotations import os @@ -9,6 +13,17 @@ def fil...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/utils.py
Add return value explanations in docstrings
# -*- coding: utf-8 -*- import asyncio import json import logging from pathlib import Path from fastapi import APIRouter, Body, HTTPException, Request from fastapi import Path as PathParam from pydantic import BaseModel from ...config.config import ( AgentProfileConfig, AgentProfileRef, load_agent_config, ...
--- +++ @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*- +"""Multi-agent management API. + +Provides RESTful API for managing multiple agent instances. +""" import asyncio import json import logging @@ -25,6 +29,7 @@ class AgentSummary(BaseModel): + """Agent summary information.""" id: str name: str @@ -33...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/agents.py
Create structured documentation for my script
# -*- coding: utf-8 -*- import re def ensure_list_spacing(text: str) -> str: lines = text.split("\n") out = [] for i, line in enumerate(lines): is_numbered = re.match(r"^\d+\.\s", line.strip()) is not None if is_numbered and i > 0: prev = lines[i - 1] prev_is_empt...
--- +++ @@ -1,9 +1,24 @@ # -*- coding: utf-8 -*- +"""DingTalk Markdown normalization helpers.""" import re def ensure_list_spacing(text: str) -> str: + """ + Ensure there is a blank line before numbered list items (e.g. "1. ..."), + to avoid DingTalk merging the list item into the previous paragraph an...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/dingtalk/markdown.py
Write docstrings that follow conventions
# -*- coding: utf-8 -*- from __future__ import annotations import collections import logging import secrets from typing import Any, Dict, Optional from ..base import BaseChannel, OnReplySent, ProcessHandler from .session import CallSessionManager from .twilio_manager import TwilioManager logger = logging.getLogger(_...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Voice Channel: Twilio ConversationRelay + Cloudflare Tunnel.""" from __future__ import annotations import collections @@ -14,6 +15,12 @@ class VoiceChannel(BaseChannel): + """CoPaw Voice channel backed by Twilio ConversationRelay. + + ``uses_manager_queu...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/voice/channel.py
Add docstrings to existing functions
# -*- coding: utf-8 -*- from __future__ import annotations from typing import Optional from uuid import uuid4 from fastapi import APIRouter, Depends, HTTPException, Query, Request from agentscope.memory import InMemoryMemory from .session import SafeJSONSession from .manager import ChatManager from .models import ( ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Chat management API.""" from __future__ import annotations from typing import Optional from uuid import uuid4 @@ -18,6 +19,7 @@ async def get_workspace(request: Request): + """Get the workspace for the active agent.""" from ..agent_context import get_ag...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/api.py
Create docstrings for all classes and functions
# -*- coding: utf-8 -*- import json import logging import shutil from pathlib import Path from ..config.config import ( AgentProfileConfig, AgentProfileRef, AgentsConfig, AgentsRunningConfig, AgentsLLMRoutingConfig, ) from ..constant import WORKING_DIR from ..config.utils import load_config, save_c...
--- +++ @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*- +"""Configuration migration utilities for multi-agent support. + +Handles migration from legacy single-agent config to new multi-agent structure. +""" import json import logging import shutil @@ -20,6 +24,18 @@ def migrate_legacy_workspace_to_default_agent() -> boo...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/migration.py
Write docstrings for utility functions
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from dataclasses import dataclass from datetime import datetime, timezone from typing import Any, Dict, Optional from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger from a...
--- +++ @@ -145,6 +145,11 @@ self._scheduler.resume_job(job_id) async def reschedule_heartbeat(self) -> None: + """Reload heartbeat config and update or remove the heartbeat job. + + Note: CronManager should always be started during workspace + initialization, so this method assu...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/crons/manager.py
Add well-formatted docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from pathlib import Path from typing import Callable, Optional, TYPE_CHECKING, Dict from .manager import MCPClientManager if TYPE_CHECKING: from ...config.config import MCPConfig logger = logging.getLogger(__name__) # How...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""Independent watcher for MCP configuration changes. + +This module provides a self-contained config watcher specifically for MCP, +without coupling to the main ConfigWatcher or other components. +""" from __future__ import annotations @@ -19,6 +24,11 @@ class ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/mcp/watcher.py
Include argument descriptions in docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import base64 import binascii import re from typing import Any, Optional from urllib.parse import parse_qs, urlparse from agentscope_runtime.engine.schemas.agent_schemas import ( AudioContent, FileContent, ImageContent, VideoContent, ) from ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""DingTalk content parsing and session helpers.""" from __future__ import annotations @@ -30,6 +31,7 @@ def dingtalk_content_from_type(mapped: str, url: str) -> Any: + """Build runtime Content from DingTalk type and download URL.""" if mapped == "image"...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/dingtalk/content_utils.py
Add documentation for all methods
# -*- coding: utf-8 -*- from pathlib import Path from typing import Optional # Magic bytes -> suffix for .file fallback (DingTalk URLs often return .file). # AMR-NB voice: "#!AMR\n" DINGTALK_MAGIC_SUFFIX: list[tuple[bytes, str]] = [ (b"%PDF", ".pdf"), (b"PK\x03\x04", ".zip"), (b"PK\x05\x06", ".zip"), ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""DingTalk channel helpers (media suffix guess, etc.).""" from pathlib import Path from typing import Optional @@ -20,6 +21,7 @@ def guess_suffix_from_file_content(path: Path) -> Optional[str]: + """Guess suffix from file magic bytes. Returns e.g. '.pdf' or N...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/dingtalk/utils.py
Document this script properly
# -*- coding: utf-8 -*- from typing import Optional from pydantic import BaseModel, Field from ...config.config import ActiveHoursConfig class HeartbeatBody(BaseModel): enabled: bool = False every: str = "6h" target: str = "main" active_hours: Optional[ActiveHoursConfig] = Field( default=N...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Request/response schemas for config API endpoints.""" from typing import Optional @@ -8,6 +9,7 @@ class HeartbeatBody(BaseModel): + """Request body for PUT /config/heartbeat.""" enabled: bool = False every: str = "6h" @@ -17,4 +19,4 @@ ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/schemas_config.py
Add docstrings to clarify complex logic
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging import re from datetime import datetime, time, timezone from pathlib import Path from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from typing import Any, Dict, Optional from ...config import ( get_heartbeat_config, ge...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +""" +Heartbeat: run agent with HEARTBEAT.md as query at interval. +Uses config functions (get_heartbeat_config, get_heartbeat_query_path, +load_config) for paths and settings. +""" from __future__ import annotations import asyncio @@ -26,6 +31,7 @@ def parse_hear...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/crons/heartbeat.py
Add docstrings including usage examples
# -*- coding: utf-8 -*- from __future__ import annotations from typing import List from fastapi import ( APIRouter, HTTPException, Path, Request, ) from pydantic import BaseModel, Field from ...config import load_config router = APIRouter(prefix="/tools", tags=["tools"]) class ToolInfo(BaseModel)...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""API routes for built-in tools management.""" from __future__ import annotations @@ -18,6 +19,7 @@ class ToolInfo(BaseModel): + """Tool information for API responses.""" name: str = Field(..., description="Tool function name") enabled: bool = Fi...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/tools.py
Fully document this Python code with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import json import logging import re import uuid from pathlib import Path from typing import AsyncGenerator, Union from fastapi import APIRouter, File, HTTPException, Query, Request, UploadFile from starlette.responses import FileResponse, StreamingResponse ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Console APIs: push messages, chat, and file upload for chat.""" from __future__ import annotations import json @@ -23,11 +24,16 @@ def _safe_filename(name: str) -> str: + """Safe basename, alphanumeric/./-/_, max 200 chars.""" base = Path(name).name if...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/console.py
Add docstrings for internal functions
# -*- coding: utf-8 -*- from fastapi import APIRouter, Request from starlette.middleware.base import ( BaseHTTPMiddleware, RequestResponseEndpoint, ) from starlette.responses import Response class AgentContextMiddleware(BaseHTTPMiddleware): async def dispatch( self, request: Request, ...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""Agent-scoped router that wraps existing routers under /agents/{agentId}/ + +This provides agent isolation by injecting agentId into request.state, +allowing downstream APIs to access the correct agent context. +""" from fastapi import APIRouter, Request from starlet...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/agent_scoped.py
Generate docstrings for each module
# -*- coding: utf-8 -*- from __future__ import annotations from datetime import datetime from typing import Any, Dict, Literal, Optional from pydantic import ( BaseModel, ConfigDict, Field, field_validator, model_validator, ) from ..channels.schema import DEFAULT_CHANNEL # ----------------------...
--- +++ @@ -35,6 +35,11 @@ def _crontab_dow_to_name(field: str) -> str: + """Convert the day-of-week field from crontab numbers to abbreviations. + + Handles: ``*``, single values, comma-separated lists, and ranges. + Already-named values (``mon``, ``tue``, …) are passed through unchanged. + """ if...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/crons/models.py
Document this code for team use
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from typing import Dict, List, Optional from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from ..download_task_store import ( DownloadTask, DownloadTaskStatus, cancel_task, clear...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""API endpoints for local model management.""" from __future__ import annotations @@ -127,6 +128,7 @@ async def download_model( body: DownloadRequest, ) -> DownloadTaskResponse: + """Start a background download. Returns a task_id immediately.""" try: ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/local_models.py
Generate docstrings with examples
# -*- coding: utf-8 -*- from __future__ import annotations import os from fastapi import APIRouter, HTTPException, Request from pydantic import BaseModel from ..auth import ( authenticate, has_registered_users, is_auth_enabled, register_user, verify_token, ) router = APIRouter(prefix="/auth", ta...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Authentication API endpoints.""" from __future__ import annotations import os @@ -39,6 +40,7 @@ @router.post("/login") async def login(req: LoginRequest): + """Authenticate with username and password.""" if not is_auth_enabled(): return LoginRe...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/auth.py
Write documentation strings for class attributes
# -*- coding: utf-8 -*- from __future__ import annotations import json import logging from typing import TYPE_CHECKING, Any from agentscope_runtime.engine.schemas.agent_schemas import ( ContentType, MessageType, RunStatus, ) from fastapi import WebSocketDisconnect from .session import CallSessionManager...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""ConversationRelay WebSocket handler for a single call.""" from __future__ import annotations import json @@ -26,6 +27,19 @@ class ConversationRelayHandler: + """Handle one call's WebSocket session with Twilio ConversationRelay. + + Twilio -> CoPaw messag...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/voice/conversation_relay.py
Document all public functions with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import time import uuid from enum import Enum from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field class DownloadTaskStatus(str, Enum): PENDING = "pending" DOWNLOADING = "downloading" COMPLETED = "com...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""In-memory store for tracking background model download tasks. + +Multiple downloads can run concurrently. Completed/failed results are retained +until explicitly cleared so the frontend can poll for the final state. +""" from __future__ import annotations import a...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/download_task_store.py
Create documentation strings for testing functions
# -*- coding: utf-8 -*- from __future__ import annotations import logging from fastapi import ( APIRouter, Depends, Request, Response, WebSocket, WebSocketDisconnect, ) logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Twilio...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""Voice channel router. + +Exports ``voice_router`` with Twilio-facing endpoints mounted at the app root: +``/voice/incoming``, ``/voice/ws``, ``/voice/status-callback``. +""" from __future__ import annotations import logging @@ -21,6 +26,7 @@ def _get_voice_cha...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/voice.py
Generate docstrings for each module
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from typing import Any, Callable, Dict, List, Optional import dingtalk_stream from dingtalk_stream import CallbackMessage, ChatbotMessage from agentscope_runtime.engine.schemas.agent_schemas import ( TextContent, ) from ..b...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""DingTalk Stream callback handler: message -> native dict -> reply.""" from __future__ import annotations @@ -36,6 +37,8 @@ class DingTalkChannelHandler(dingtalk_stream.ChatbotHandler): + """Internal handler: convert DingTalk message to native dict, enqueue...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/dingtalk/handler.py
Write docstrings including parameters and return values
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from typing import Any, Dict, List, TYPE_CHECKING from agentscope.mcp import HttpStatefulClient, StdIOStatefulClient if TYPE_CHECKING: from ...config.config import MCPClientConfig, MCPConfig logger = logging.getLogger(__na...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""MCP client manager for hot-reloadable client lifecycle management. + +This module provides centralized management of MCP clients with support +for runtime updates without restarting the application. +""" from __future__ import annotations @@ -15,12 +20,27 @@ ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/mcp/manager.py
Create docstrings for each class method
# -*- coding: utf-8 -*- from __future__ import annotations from datetime import datetime, timezone from typing import Any, Dict from uuid import uuid4 from pydantic import BaseModel, Field from agentscope_runtime.engine.schemas.agent_schemas import Message from ..channels.schema import DEFAULT_CHANNEL class ChatSp...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Chat models for runner with UUID management.""" from __future__ import annotations from datetime import datetime, timezone @@ -12,6 +13,10 @@ class ChatSpec(BaseModel): + """Chat specification with UUID identifier. + + Stored in Redis and can be persiste...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/models.py
Write reusable docstrings
# -*- coding: utf-8 -*- import asyncio import logging from typing import Dict, Set from .workspace import Workspace from ..config.utils import load_config logger = logging.getLogger(__name__) class MultiAgentManager: def __init__(self): self.agents: Dict[str, Workspace] = {} self._lock = asynci...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""MultiAgentManager: Manages multiple agent workspaces with lazy loading. + +Provides centralized management for multiple Workspace objects, +including lazy loading, lifecycle management, and hot reloading. +""" import asyncio import logging from typing import Dict, ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/multi_agent_manager.py
Replace inline comments with docstrings
# -*- coding: utf-8 -*- import asyncio import logging from fastapi import APIRouter, Body, HTTPException, Request from pydantic import BaseModel, Field from ...config import ( load_config, save_config, AgentsRunningConfig, ) from ...config.config import load_agent_config, save_agent_config from ...agents...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Agent file management API.""" import asyncio import logging @@ -20,6 +21,7 @@ class MdFileInfo(BaseModel): + """Markdown file metadata.""" filename: str = Field(..., description="File name") path: str = Field(..., description="File path") @@ -29...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/agent.py
Add docstrings explaining edge cases
# -*- coding: utf-8 -*- from __future__ import annotations import re from typing import List def format_markdown_tables(text: str) -> str: lines = text.split("\n") result: List[str] = [] i = 0 in_code_fence = False while i < len(lines): line = lines[i] stripped = line.strip() ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""WeCom channel utilities.""" from __future__ import annotations import re @@ -6,6 +7,17 @@ def format_markdown_tables(text: str) -> str: + """Format GFM markdown tables for WeCom compatibility. + + WeCom requires table columns to be properly aligned. + ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/wecom/utils.py
Expand my code with proper documentation strings
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import io import shutil import tempfile import zipfile from datetime import datetime, timezone from pathlib import Path from fastapi import APIRouter, HTTPException, UploadFile, File, Request from fastapi.responses import StreamingResponse r...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Workspace API – download / upload the entire WORKING_DIR as a zip.""" from __future__ import annotations @@ -18,6 +19,7 @@ def _dir_stats(root: Path) -> tuple[int, int]: + """Return (file_count, total_size) for *root* recursively.""" count = 0 si...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/workspace.py
Create documentation for each function signature
# -*- coding: utf-8 -*- from __future__ import annotations from abc import ABC, abstractmethod from typing import Optional from ..models import CronJobSpec, JobsFile class BaseJobRepository(ABC): @abstractmethod async def load(self) -> JobsFile: raise NotImplementedError @abstractmethod as...
--- +++ @@ -8,13 +8,16 @@ class BaseJobRepository(ABC): + """Abstract repository for cron job specs persistence.""" @abstractmethod async def load(self) -> JobsFile: + """Load all jobs from storage.""" raise NotImplementedError @abstractmethod async def save(self, jobs_fil...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/crons/repo/base.py
Help me add docstrings to my project
# -*- coding: utf-8 -*- # pylint: disable=too-many-statements,too-many-branches # pylint: disable=too-many-return-statements,unused-argument from __future__ import annotations import base64 import asyncio import json import logging import mimetypes import re import sys import threading import time import types from c...
--- +++ @@ -1,6 +1,14 @@ # -*- coding: utf-8 -*- # pylint: disable=too-many-statements,too-many-branches # pylint: disable=too-many-return-statements,unused-argument +"""Feishu (Lark) Channel. + +Uses lark-oapi (https://github.com/larksuite/oapi-sdk-python) WebSocket +long connection to receive events (no public IP)....
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/feishu/channel.py
Insert docstrings into my code
# -*- coding: utf-8 -*- import asyncio import logging import threading import time import uuid from enum import Enum from typing import Any from pathlib import Path from fastapi import APIRouter, HTTPException, Request from fastapi.responses import JSONResponse from pydantic import BaseModel, Field from ...agents.skill...
--- +++ @@ -26,6 +26,7 @@ def _scan_error_response(exc: SkillScanError) -> JSONResponse: + """Build a 422 response with structured scan findings.""" result = exc.result return JSONResponse( status_code=422, @@ -122,6 +123,7 @@ async def list_skills( request: Request, ) -> list[SkillSpec]...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/skills.py
Add docstrings for internal functions
# -*- coding: utf-8 -*- from __future__ import annotations import logging from typing import List, Literal, Optional from copy import deepcopy from fastapi import APIRouter, Body, Depends, HTTPException, Path, Request from pydantic import BaseModel, Field from ..agent_context import get_agent_for_request from ...co...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""API routes for LLM providers and models.""" from __future__ import annotations @@ -28,6 +29,11 @@ def get_provider_manager(request: Request) -> ProviderManager: + """Get the provider manager from app state. + + Args: + request: FastAPI request ob...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/providers.py
Document this module using docstrings
# -*- coding: utf-8 -*- # pylint: disable=too-many-branches from __future__ import annotations import asyncio import html import logging import re import uuid from pathlib import Path from typing import Any, Optional, Union from telegram import BotCommand from telegram.constants import ParseMode from telegram.error ...
--- +++ @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- # pylint: disable=too-many-branches +"""Telegram channel: Bot API with polling; receive/send via chat_id.""" from __future__ import annotations @@ -67,9 +68,11 @@ class _FileTooLargeError(Exception): + """Raised when a local media file exceeds Telegram's uplo...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/telegram/channel.py
Generate docstrings for script automation
# -*- coding: utf-8 -*- import json import re from typing import Any, Dict, List, Optional from .constants import FEISHU_SESSION_ID_SUFFIX_LEN def short_session_id_from_full_id(full_id: str) -> str: n = FEISHU_SESSION_ID_SUFFIX_LEN return full_id[-n:] if len(full_id) >= n else full_id def sender_display_s...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Feishu channel helpers (session id, sender display, markdown, table).""" import json import re @@ -8,6 +9,7 @@ def short_session_id_from_full_id(full_id: str) -> str: + """Use last N chars of full_id (chat_id or open_id) as session_id.""" n = FEISHU_SE...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/feishu/utils.py
Add docstrings to my Python code
# -*- coding: utf-8 -*- from __future__ import annotations import json import logging import os import tempfile import traceback from datetime import datetime, timezone from typing import Any from ..channels.schema import DEFAULT_CHANNEL logger = logging.getLogger(__name__) def _safe_json_serialize(obj: object) ->...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Write query-handler error log and agent/memory state to a temp JSON file.""" from __future__ import annotations import json @@ -15,6 +16,7 @@ def _safe_json_serialize(obj: object) -> object: + """Convert object to JSON-serializable form; use str() for unkno...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/query_error_dump.py
Fully document this Python code with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import logging from typing import AsyncIterator from typing import TYPE_CHECKING from agentscope.message import Msg, TextBlock from .daemon_commands import ( DaemonContext, DaemonCommandHandlerMixin, parse_daemon_query, ) from ...agents.command_h...
--- +++ @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*- +"""Command dispatch: run command path without creating CoPawAgent. + +Yields (Msg, last) compatible with query_handler stream. +""" from __future__ import annotations import logging @@ -22,6 +26,7 @@ def _get_last_user_text(msgs) -> str | None: + """Extract la...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/command_dispatch.py
Write docstrings for data processing functions
# -*- coding: utf-8 -*- # pylint: disable=too-many-return-statements from __future__ import annotations import logging from dataclasses import dataclass from pathlib import Path from typing import Any, Callable, Optional, TYPE_CHECKING from agentscope.message import Msg, TextBlock from ...constant import WORKING_DIR...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""Daemon command execution layer and DaemonCommandHandlerMixin. + +Shared by in-chat /daemon <sub> and CLI `copaw daemon <sub>`. +Logs: tail WORKING_DIR / "copaw.log". Restart: in-process reload of channels, +cron and MCP (no process exit); works on Mac/Windows without...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/daemon_commands.py
Improve my code by adding docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import time import uuid from typing import Any, Dict, List # Single list: each item has id, text, ts, session_id and optional metadata. # Bounded by count and age. _list: List[Dict[str, Any]] = [] _lock = asyncio.Lock() _MAX_AGE_SECONDS = 60 _M...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""In-memory store for console channel push messages (e.g. cron text). + +Bounded: at most _MAX_MESSAGES kept; messages older than _MAX_AGE_SECONDS +are dropped when reading. Frontend dedupes by id and caps its seen set. +""" from __future__ import annotations import...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/console_push_store.py
Add docstrings that explain inputs and outputs
# -*- coding: utf-8 -*- # pylint: disable=too-many-statements,too-many-branches # pylint: disable=too-many-return-statements from __future__ import annotations import asyncio import base64 import hashlib import json import logging import mimetypes import os import threading import time from pathlib import Path from t...
--- +++ @@ -1,6 +1,16 @@ # -*- coding: utf-8 -*- # pylint: disable=too-many-statements,too-many-branches # pylint: disable=too-many-return-statements +"""DingTalk Channel. + +Why only one reply by default: DingTalk Stream callback is request-reply. +The handler process() is awaited until reply_future is set once, +th...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/dingtalk/channel.py
Add detailed documentation for each class
# -*- coding: utf-8 -*- # flake8: noqa: E501 import json import logging from fastapi import APIRouter from fastapi.responses import StreamingResponse from pydantic import BaseModel, Field from ...agents.model_factory import create_model_and_formatter logger = logging.getLogger(__name__) def get_model(): try: ...
--- +++ @@ -1,5 +1,8 @@ # -*- coding: utf-8 -*- # flake8: noqa: E501 +""" +Streaming AI skill optimization API +""" import json import logging @@ -14,6 +17,11 @@ def get_model(): + """Get the active chat model instance. + + Returns: + Chat model instance or None if not configured + """ try...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/skills_stream.py
Improve documentation using docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import json import logging import uuid from typing import Any, Dict, List, Optional, TYPE_CHECKING import aiohttp from agentscope_runtime.engine.schemas.agent_schemas import ( ContentType, TextContent, ) from ....config.config import...
--- +++ @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*- +"""XiaoYi Channel implementation. + +XiaoYi uses A2A (Agent-to-Agent) protocol over WebSocket. +""" from __future__ import annotations @@ -46,6 +50,11 @@ class XiaoYiChannel(BaseChannel): + """XiaoYi channel using A2A protocol over WebSocket. + + This chan...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/xiaoyi/channel.py
Fully document this Python code with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import base64 import hashlib import hmac import time from typing import Dict def generate_signature(sk: str, timestamp: str) -> str: hmac_obj = hmac.new(sk.encode(), timestamp.encode(), hashlib.sha256) return base64.b64encode(hmac_obj.digest()).deco...
--- +++ @@ -1,4 +1,7 @@ # -*- coding: utf-8 -*- +""" +XiaoYi authentication using AK/SK mechanism. +""" from __future__ import annotations @@ -10,11 +13,32 @@ def generate_signature(sk: str, timestamp: str) -> str: + """Generate HMAC-SHA256 signature. + + Format: Base64(HMAC-SHA256(secretKey, timestamp))...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/xiaoyi/auth.py
Please document this code using docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from datetime import datetime, timezone from typing import Optional from .models import ChatSpec from .repo import BaseChatRepository from ..channels.schema import DEFAULT_CHANNEL logger = logging.getLogger(__name__) class Cha...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Chat manager for managing chat specifications.""" from __future__ import annotations import asyncio @@ -14,12 +15,24 @@ class ChatManager: + """Manages chat specifications in repository. + + Only handles ChatSpec CRUD operations. + Does NOT manage Red...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/manager.py
Document my Python code with docstrings
# -*- coding: utf-8 -*- from datetime import date, timedelta from fastapi import APIRouter, Query from ...token_usage import get_token_usage_manager, TokenUsageSummary router = APIRouter(prefix="/token-usage", tags=["token-usage"]) def _parse_date(s: str | None) -> date | None: if not s: return None ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Token usage API for console and skill tool.""" from datetime import date, timedelta @@ -10,6 +11,7 @@ def _parse_date(s: str | None) -> date | None: + """Parse YYYY-MM-DD string to date.""" if not s: return None try: @@ -45,6 +47,7 @@ ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/token_usage.py
Add minimal docstrings for each function
# -*- coding: utf-8 -*- from __future__ import annotations import csv import io import json import re import subprocess import sys from typing import Optional _PORT_ARG_PATTERN = re.compile(r"(?:^|\s)--port(?:=|\s+)(\d+)(?=\s|$)") def _coerce_optional_int(value: object) -> Optional[int]: if value is None: ...
--- +++ @@ -14,6 +14,7 @@ def _coerce_optional_int(value: object) -> Optional[int]: + """Best-effort conversion of JSON-decoded values to integers.""" if value is None: return None if isinstance(value, int): @@ -29,6 +30,7 @@ def _parse_windows_process_snapshot_json( payload: str, ) -> d...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/process_utils.py
Generate docstrings for script automation
# -*- coding: utf-8 -*- from __future__ import annotations import click from ..envs import load_envs, set_env_var, delete_env_var @click.group("env") def env_group() -> None: # --------------------------------------------------------------- # list # --------------------------------------------------------------- ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""CLI commands for environment variable management.""" from __future__ import annotations import click @@ -8,6 +9,7 @@ @click.group("env") def env_group() -> None: + """Manage environment variables.""" # ---------------------------------------------------...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/env_cmd.py
Please document this code using docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio from typing import Optional import click from ..providers.ollama_manager import OllamaModelManager from ..providers.provider import ModelInfo, Provider, ProviderInfo from ..providers.provider_manager import ProviderManager from .utils import p...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""CLI commands for managing LLM providers.""" from __future__ import annotations import asyncio @@ -68,6 +69,7 @@ *, default_pid: str = "", ) -> str: + """Prompt user to pick a provider. Returns provider_id.""" manager = _manager() all_provide...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/providers_cmd.py
Write reusable docstrings
# -*- coding: utf-8 -*- from __future__ import annotations from pathlib import Path import click from ..agents.skills_manager import SkillService, list_available_skills from ..constant import WORKING_DIR from ..config import load_config from .utils import prompt_checkbox, prompt_confirm def _get_agent_workspace(ag...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""CLI skill: list and interactively enable/disable skills.""" from __future__ import annotations from pathlib import Path @@ -12,6 +13,7 @@ def _get_agent_workspace(agent_id: str) -> Path: + """Get agent workspace directory.""" try: config = loa...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/skills_cmd.py
Generate docstrings with examples
# -*- coding: utf-8 -*- from datetime import datetime, timezone from typing import Any, List from fastapi import APIRouter, Body, HTTPException, Path, Request from pydantic import BaseModel from ...config import ( load_config, save_config, ChannelConfig, ChannelConfigUnion, get_available_channels...
--- +++ @@ -62,6 +62,7 @@ description="Retrieve configuration for all available channels", ) async def list_channels(request: Request) -> dict: + """List all channel configs (filtered by available channels).""" from ..agent_context import get_agent_for_request agent = await get_agent_for_request(re...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/config.py
Write documentation strings for class attributes
# -*- coding: utf-8 -*- from __future__ import annotations import logging from dataclasses import dataclass from datetime import datetime, timezone from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from .conversation_relay import ConversationRelayHandler logger = logging.getLogger(__name__) @datacla...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Call session management for the Voice channel.""" from __future__ import annotations import logging @@ -14,6 +15,7 @@ @dataclass class CallSession: + """One active or ended phone call.""" call_sid: str from_number: str @@ -24,6 +26,7 @@ class...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/channels/voice/session.py
Add docstrings for better understanding
# -*- coding: utf-8 -*- from __future__ import annotations from typing import Dict, List, Optional, Literal from fastapi import APIRouter, Body, HTTPException, Path, Request from pydantic import BaseModel, Field from ...config.config import MCPClientConfig router = APIRouter(prefix="/mcp", tags=["mcp"]) class MC...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""API routes for MCP (Model Context Protocol) clients management.""" from __future__ import annotations @@ -13,6 +14,7 @@ class MCPClientInfo(BaseModel): + """MCP client information for API responses.""" key: str = Field(..., description="Unique clien...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/mcp.py
Please document this code using docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import shutil import re from pathlib import Path import click from ..constant import WORKING_DIR # Directories created by the installer (relative to WORKING_DIR). _INSTALLER_DIRS = ("venv", "bin") # Shell profiles to clean up. _SHELL_PROFILES = ( Path...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""copaw uninstall — remove the CoPaw environment and CLI wrapper.""" from __future__ import annotations import shutil @@ -22,6 +23,9 @@ def _remove_path_entry(profile: Path) -> bool: + """ + Remove CoPaw PATH lines from a shell profile. Returns True if cha...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/uninstall_cmd.py
Add docstrings to make code maintainable
# -*- coding: utf-8 -*- from __future__ import annotations from typing import Dict, List from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from ...envs import load_envs, save_envs, delete_env_var router = APIRouter(prefix="/envs", tags=["envs"]) # ---------------------------------...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""API endpoints for environment variable management.""" from __future__ import annotations from typing import Dict, List @@ -17,6 +18,7 @@ class EnvVar(BaseModel): + """Single environment variable.""" key: str = Field(..., description="Variable name") ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/routers/envs.py
Include argument descriptions in docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import json import os import signal import shutil import subprocess import sys import time from dataclasses import asdict, dataclass from importlib import metadata from pathlib import Path from typing import Any from urllib.parse import urlparse import click ...
--- +++ @@ -33,6 +33,12 @@ def _subprocess_text_kwargs() -> dict[str, Any]: + """Return robust text-decoding settings for subprocess output. + + Package installers may emit UTF-8 regardless of the active Windows code + page. Using replacement for undecodable bytes prevents the update worker + from crash...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/update_cmd.py
Can you add docstrings to this Python file?
# -*- coding: utf-8 -*- from __future__ import annotations from abc import ABC, abstractmethod from typing import Optional from ..models import ChatSpec, ChatsFile from ...channels.schema import DEFAULT_CHANNEL class BaseChatRepository(ABC): @abstractmethod async def load(self) -> ChatsFile: raise ...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Chat repository for storing chat/session specs.""" from __future__ import annotations from abc import ABC, abstractmethod @@ -9,22 +10,34 @@ class BaseChatRepository(ABC): + """Abstract repository for chat specs persistence.""" @abstractmethod a...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/repo/base.py
Add inline docstrings for readability
# -*- coding: utf-8 -*- from __future__ import annotations import os from datetime import datetime, timezone from typing import Optional def _is_iana(name: Optional[str]) -> bool: return bool(name and "/" in name) def detect_system_timezone() -> str: try: return _detect_system_timezone_inner() ...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""Detect the system IANA timezone. + +Kept in its own module to avoid circular imports between config.py and +utils.py. Uses only the standard library; always returns a valid string +(falls back to ``"UTC"``). +""" from __future__ import annotations @@ -8,10 +14,...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/config/timezone.py
Write proper docstrings for these functions
# -*- coding: utf-8 -*- from __future__ import annotations import json import os import plistlib import subprocess import sys from pathlib import Path from typing import Optional, Tuple from ..constant import ( HEARTBEAT_FILE, JOBS_FILE, CHATS_FILE, PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH_ENV, RUNNING...
--- +++ @@ -28,6 +28,13 @@ def _normalize_working_dir_bound_paths(data: object) -> object: + """Normalize legacy ~/.copaw-bound paths to current WORKING_DIR. + + This keeps COPAW_WORKING_DIR effective even if user config files contain + older hard-coded paths like "~/.copaw/media" or + "/Users/x/.copaw/...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/config/utils.py
Add docstrings for utility scripts
# -*- coding: utf-8 -*- import os import json from pathlib import Path from typing import Optional, Union, Dict, List, Literal from pydantic import BaseModel, Field, ConfigDict, model_validator import shortuuid from .timezone import detect_system_timezone from ..constant import ( HEARTBEAT_DEFAULT_EVERY, HEAR...
--- +++ @@ -17,10 +17,16 @@ def generate_short_agent_id() -> str: + """Generate a 6-character short UUID for agent identification. + + Returns: + 6-character short UUID string + """ return shortuuid.ShortUUID().random(length=6) class BaseChannelConfig(BaseModel): + """Base for channel c...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/config/config.py
Add docstrings that explain purpose and usage
# -*- coding: utf-8 -*- from __future__ import annotations from pathlib import Path from typing import Optional import click import questionary def prompt_confirm(question: str, *, default: bool = False) -> bool: items = [ questionary.Choice("Yes", value=True), questionary.Choice("No", value=Fals...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""Shared interactive prompt helpers used by CLI commands. + +All terminal interaction with *questionary* is centralised here so that +the rest of the CLI code never imports questionary directly. +""" from __future__ import annotations from pathlib import Path from ty...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/utils.py
Add documentation for all methods
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import json import logging import weakref from dataclasses import dataclass, field from typing import Any, AsyncGenerator, Callable, Coroutine logger = logging.getLogger(__name__) _QUEUE_MAX_SIZE = 4096 _SENTINEL = None @dataclass class _Run...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""Task tracker for background runs: streaming, reconnect, multi-subscriber. + +run_key is ChatSpec.id (chat_id). Per run: task, queues, event buffer. +Reconnects get buffer replay + new events. Cleanup when task completes. +""" from __future__ import annotations imp...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/task_tracker.py
Document helper functions with docstrings
# -*- coding: utf-8 -*- # pylint: disable=unused-argument too-many-branches too-many-statements from __future__ import annotations import asyncio import json import logging import time from pathlib import Path from typing import TYPE_CHECKING from agentscope.message import Msg, TextBlock from agentscope.pipeline impo...
--- +++ @@ -56,9 +56,19 @@ self.memory_manager: MemoryManager | None = None def set_chat_manager(self, chat_manager): + """Set chat manager for auto-registration. + + Args: + chat_manager: ChatManager instance + """ self._chat_manager = chat_manager def set...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/runner.py
Annotate my code with docstrings
# -*- coding: utf-8 -*- import os import re import json import logging from typing import Union, Sequence import aiofiles from agentscope.session import SessionBase logger = logging.getLogger(__name__) # Characters forbidden in Windows filenames _UNSAFE_FILENAME_RE = re.compile(r'[\\/:*?"<>|]') def sanitize_file...
--- +++ @@ -1,4 +1,11 @@ # -*- coding: utf-8 -*- +"""Safe JSON session with filename sanitization for cross-platform +compatibility. + +Windows filenames cannot contain: \\ / : * ? " < > | +This module wraps agentscope's SessionBase so that session_id and user_id +are sanitized before being used as filenames. +""" imp...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/session.py
Fully document this Python code with docstrings
# -*- coding: utf-8 -*- import json import logging import platform import os from datetime import datetime, timezone from typing import List, Optional, Union from urllib.parse import urlparse from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from agentscope.message import Msg from agentscope_runtime.engine.schemas....
--- +++ @@ -34,6 +34,18 @@ working_dir: Optional[str] = None, add_hint: bool = True, ) -> str: + """ + Build environment context with current request context prepended. + + Args: + session_id: Current session ID + user_id: Current user ID + channel: Current channel name + ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/utils.py
Add docstrings for internal functions
# -*- coding: utf-8 -*- from __future__ import annotations from abc import ABC, abstractmethod from typing import Any, Iterator, Optional, Type from pydantic import BaseModel class LocalBackend(ABC): @abstractmethod def __init__(self, model_path: str, **kwargs: Any) -> None: @abstractmethod def c...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Abstract base class for local model inference backends.""" from __future__ import annotations @@ -9,9 +10,21 @@ class LocalBackend(ABC): + """Abstract interface for a local model inference backend. + + Each backend wraps a specific library (llama-cpp-py...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/local_models/backends/base.py
Help me comply with documentation standards
# -*- coding: utf-8 -*- import os from pathlib import Path class EnvVarLoader: @staticmethod def get_bool(env_var: str, default: bool = False) -> bool: val = os.environ.get(env_var, str(default)).lower() return val in ("true", "1", "yes") @staticmethod def get_float( env_var:...
--- +++ @@ -4,9 +4,14 @@ class EnvVarLoader: + """Utility to load and parse environment variables with type safety + and defaults. + """ @staticmethod def get_bool(env_var: str, default: bool = False) -> bool: + """Get a boolean environment variable, + interpreting common truthy v...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/constant.py
Create docstrings for all classes and functions
# -*- coding: utf-8 -*- from contextvars import ContextVar from pathlib import Path # Context variable to store the current agent's workspace directory current_workspace_dir: ContextVar[Path | None] = ContextVar( "current_workspace_dir", default=None, ) def get_current_workspace_dir() -> Path | None: ret...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""Context variable for agent workspace directory. + +This module provides a context variable to pass the agent's workspace +directory to tool functions, allowing them to resolve relative paths +correctly in a multi-agent environment. +""" from contextvars import Conte...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/config/context.py
Document all public functions with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import json import logging import os import shutil from pathlib import Path from typing import Optional logger = logging.getLogger(__name__) _BOOTSTRAP_WORKING_DIR = ( Path(os.environ.get("COPAW_WORKING_DIR", "~/.copaw")) .expanduser() .resolve()...
--- +++ @@ -1,4 +1,13 @@ # -*- coding: utf-8 -*- +"""Reading and writing environment variables. + +Persistence strategy (two layers): + +1. **envs.json** – canonical store, survives process restarts. +2. **os.environ** – injected into the current Python process so that + ``os.getenv()`` and child subprocesses (``subp...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/envs/store.py
Document my Python code with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import json import logging import re import uuid from dataclasses import dataclass, field logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Constants # --------------------------------------...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""Parse special tags from model-generated text. + +Handles ``<think>...</think>`` (reasoning) and +``<tool_call>...</tool_call>`` (function calling) tags that local models +like Qwen3-Instruct embed in their raw text output. +""" from __future__ import annotations ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/local_models/tag_parser.py
Write proper docstrings for these functions
# -*- coding: utf-8 -*- from __future__ import annotations import json import shutil from pathlib import Path from .base import BaseChatRepository from ..models import ChatsFile class JsonChatRepository(BaseChatRepository): def __init__(self, path: Path | str): if isinstance(path, str): pat...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""JSON-based chat repository.""" from __future__ import annotations import json @@ -10,17 +11,37 @@ class JsonChatRepository(BaseChatRepository): + """chats.json repository (single-file storage). + + Stores chat_id (UUID) -> session_id mappings in a JSON f...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/runner/repo/json_repo.py
Write beginner-friendly docstrings
# -*- coding: utf-8 -*- from __future__ import annotations from typing import Any, List from agentscope.model import ChatModelBase from google import genai from google.genai import errors as genai_errors from google.genai import types as genai_types from copaw.providers.provider import ModelInfo, Provider class G...
--- +++ @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +"""A Google Gemini provider implementation using AgentScope's native +GeminiChatModel.""" from __future__ import annotations @@ -13,6 +15,7 @@ class GeminiProvider(Provider): + """Provider implementation for Google Gemini API.""" def _client(self, time...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/gemini_provider.py
Add docstrings to improve collaboration
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from dataclasses import dataclass, field from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Set, Union, ) if TYPE_CHECKING: from .workspace import Workspace...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""Service management system for Workspace components. + +Provides unified registration, lifecycle management, and dependency handling +for all workspace services (MemoryManager, ChatManager, etc.). +""" from __future__ import annotations import asyncio @@ -24,6 +29,...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/workspace/service_manager.py
Add docstrings for production code
# -*- coding: utf-8 -*- from __future__ import annotations import json from typing import Any, List from agentscope.model import ChatModelBase import anthropic from copaw.providers.provider import ModelInfo, Provider DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1" CODING_DASHSCOPE_BASE_URL...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""An Anthropic provider implementation.""" from __future__ import annotations @@ -15,6 +16,7 @@ class AnthropicProvider(Provider): + """Provider implementation for Anthropic API.""" def _client(self, timeout: float = 5) -> anthropic.AsyncAnthropic: ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/anthropic_provider.py
Add return value explanations in docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import json from datetime import datetime from types import SimpleNamespace from typing import Any, AsyncGenerator, Type from agentscope.model import OpenAIChatModel from agentscope.model._model_response import ChatResponse from pydantic import BaseModel d...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""OpenAI chat model compatibility wrappers.""" from __future__ import annotations @@ -13,12 +14,14 @@ def _clone_with_overrides(obj: Any, **overrides: Any) -> Any: + """Clone a stream object into a mutable namespace with overrides.""" data = dict(getatt...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/openai_chat_model_compat.py
Add docstrings to existing functions
# -*- coding: utf-8 -*- import logging from pathlib import Path from typing import Optional, TYPE_CHECKING from .service_manager import ServiceDescriptor, ServiceManager from .service_factories import ( create_mcp_service, create_chat_service, create_channel_service, create_agent_config_watcher, cr...
--- +++ @@ -1,4 +1,15 @@ # -*- coding: utf-8 -*- +"""Workspace: Encapsulates a complete independent agent runtime. + +Each Workspace represents a standalone agent workspace with its own: +- Runner (request processing) +- ChannelManager (communication channels) +- MemoryManager (conversation memory) +- MCPClientManager ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/workspace/workspace.py
Add docstrings following best practices
# -*- coding: utf-8 -*- from __future__ import annotations from enum import Enum from typing import Optional from pydantic import BaseModel, Field class BackendType(str, Enum): LLAMACPP = "llamacpp" MLX = "mlx" class DownloadSource(str, Enum): HUGGINGFACE = "huggingface" MODELSCOPE = "modelscope"...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Data models for local model management.""" from __future__ import annotations @@ -19,6 +20,7 @@ class LocalModelInfo(BaseModel): + """Metadata for a single downloaded local model.""" id: str = Field(..., description="Unique ID: <repo_id>/<filename>"...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/local_models/schema.py
Write clean docstrings for readability
# -*- coding: utf-8 -*- from __future__ import annotations import json from typing import Any, List from agentscope.model import ChatModelBase from openai import APIError, AsyncOpenAI from copaw.providers.provider import ModelInfo, Provider DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1" C...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""An OpenAI provider implementation.""" from __future__ import annotations @@ -15,6 +16,7 @@ class OpenAIProvider(Provider): + """Provider implementation for OpenAI API and compatible endpoints.""" def _client(self, timeout: float = 5) -> AsyncOpenAI:...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/openai_provider.py
Document helper functions with docstrings
# -*- coding: utf-8 -*- from abc import ABC, abstractmethod from typing import Dict, List, Type, Any from pydantic import BaseModel, Field from agentscope.model import ChatModelBase class ModelInfo(BaseModel): id: str = Field(..., description="Model identifier used in API calls") name: str = Field(..., desc...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Definition of Provider.""" from abc import ABC, abstractmethod from typing import Dict, List, Type, Any @@ -63,12 +64,15 @@ class Provider(ProviderInfo, ABC): + """Represents a provider instance with its configuration.""" @abstractmethod async d...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/provider.py
Add docstrings that explain logic
# -*- coding: utf-8 -*- from __future__ import annotations from concurrent import futures import hashlib import json import logging import os import threading from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from typing import Any from .models import ( Find...
--- +++ @@ -1,4 +1,32 @@ # -*- coding: utf-8 -*- +""" +Skill security scanner for CoPaw. + +Scans skills for security threats before they are activated or installed. + +Architecture +~~~~~~~~~~~~ + +The scanner follows a lightweight, extensible design: + +* **BaseAnalyzer** - abstract interface every analyzer must impl...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/skill_scanner/__init__.py
Document all public functions with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations from abc import ABC, abstractmethod from pathlib import Path from typing import TYPE_CHECKING from ..models import Finding, SkillFile if TYPE_CHECKING: from ..scan_policy import ScanPolicy class BaseAnalyzer(ABC): def __init__( self, ...
--- +++ @@ -1,4 +1,11 @@ # -*- coding: utf-8 -*- +"""Abstract base class for all security analyzers. + +Every analyzer must subclass :class:`BaseAnalyzer` and implement +:meth:`analyze`. The interface is intentionally minimal so that +new detection engines (e.g. LLM-based, behavioural dataflow) can be +added as drop-i...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/skill_scanner/analyzers/__init__.py
Generate docstrings with examples
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging from typing import Any, AsyncGenerator from agentscope.model import ChatModelBase from agentscope.model._model_response import ChatResponse from ..constant import LLM_BACKOFF_BASE, LLM_BACKOFF_CAP, LLM_MAX_RETRIES logger = log...
--- +++ @@ -1,4 +1,14 @@ # -*- coding: utf-8 -*- +"""Retry wrapper for ChatModelBase instances. + +Transparently retries LLM API calls on transient errors (rate-limit, +timeout, connection) with configurable exponential back-off. + +Configuration via environment variables (or use defaults from constant.py): + COPAW_...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/retry_chat_model.py
Add docstrings for better understanding
# -*- coding: utf-8 -*- import asyncio import os from typing import Dict, List import logging import json from pydantic import BaseModel from agentscope.model import ChatModelBase from copaw.providers.provider import ( ModelInfo, DefaultProvider, Provider, ProviderInfo, ) from copaw.providers.models...
--- +++ @@ -1,4 +1,7 @@ # -*- coding: utf-8 -*- +"""A Manager class to handle all providers, including built-in and custom ones. +It provides a unified interface to manage providers, such as listing available +providers, adding/removing custom providers, and fetching provider details.""" import asyncio import os @@...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/providers/provider_manager.py
Generate consistent documentation across files
# -*- coding: utf-8 -*- from __future__ import annotations import logging import re import uuid from pathlib import Path from typing import Any import yaml from ..models import GuardFinding, GuardSeverity, GuardThreatCategory from . import BaseToolGuardian logger = logging.getLogger(__name__) # Default rules direc...
--- +++ @@ -1,4 +1,25 @@ # -*- coding: utf-8 -*- +"""YAML-signature rule-based tool-call guardian. + +Loads security rules from YAML files (see ``rules/``) and performs fast +regex matching against the **string representation** of each tool +parameter value. + +Rule format (one YAML file per threat category):: + + -...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/tool_guard/guardians/rule_guardian.py
Improve my code by adding docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import logging import time from pathlib import Path from .analyzers import BaseAnalyzer from .analyzers.pattern_analyzer import PatternAnalyzer from .models import Finding, ScanResult, SkillFile from .scan_policy import ScanPolicy logger = logging.getLogger(...
--- +++ @@ -1,4 +1,20 @@ # -*- coding: utf-8 -*- +"""Skill security scanner orchestrator. + +:class:`SkillScanner` discovers files in a skill directory, runs all +registered :class:`BaseAnalyzer` instances and collects their findings +into a single :class:`ScanResult`. + +Usage:: + + scanner = SkillScanner() ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/skill_scanner/scanner.py
Fully document this Python code with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import logging import re from pathlib import Path from typing import Any import yaml from ..models import Finding, Severity, SkillFile, ThreatCategory from ..scan_policy import ScanPolicy from . import BaseAnalyzer logger = logging.getLogger(__name__) # Ma...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""YAML-signature pattern matching analyzer. + +Loads security rules from YAML files (see ``rules/signatures/``) and +performs fast, line-based regex matching with a multiline fallback for +patterns that intentionally span newlines. +""" from __future__ import annotati...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/skill_scanner/analyzers/pattern_analyzer.py
Write clean docstrings for readability
# -*- coding: utf-8 -*- from typing import TYPE_CHECKING import logging if TYPE_CHECKING: from .workspace import Workspace logger = logging.getLogger(__name__) async def create_mcp_service(ws: "Workspace", mcp): # pylint: disable=protected-access if ws._config.mcp: try: await mcp.in...
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- +"""Service factory functions for workspace components. + +Factory functions are used by Workspace._register_services() to create +and initialize service components. Extracted from local functions to +improve testability and code organization. +""" from typing import ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/app/workspace/service_factories.py
Add concise docstrings to each method
# -*- coding: utf-8 -*- from __future__ import annotations from dataclasses import dataclass, field from datetime import datetime, timezone from enum import Enum from pathlib import Path from typing import Any # --------------------------------------------------------------------------- # Enums # -------------------...
--- +++ @@ -1,4 +1,7 @@ # -*- coding: utf-8 -*- +"""Data models for skill scanning results. + +""" from __future__ import annotations from dataclasses import dataclass, field @@ -14,6 +17,7 @@ class Severity(str, Enum): + """Severity levels for security findings.""" CRITICAL = "CRITICAL" HIGH = "...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/skill_scanner/models.py
Generate docstrings for each module
# -*- coding: utf-8 -*- # pylint:disable=too-many-branches,too-many-statements,consider-using-with from __future__ import annotations import logging import os import socket import subprocess import sys import threading import time import traceback import webbrowser import click from ..constant import LOG_LEVEL_ENV f...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""CLI command: run CoPaw app on a free port in a native webview window.""" # pylint:disable=too-many-branches,too-many-statements,consider-using-with from __future__ import annotations @@ -26,14 +27,17 @@ class WebViewAPI: + """API exposed to the webview for ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/desktop_cmd.py
Auto-generate documentation strings for this file
# -*- coding: utf-8 -*- import io import logging import logging.handlers import os import platform import sys from pathlib import Path # Rotating file handler limits (idempotent add avoids duplicate handlers) _COPAW_LOG_MAX_BYTES = 5 * 1024 * 1024 # 5 MiB _COPAW_LOG_BACKUP_COUNT = 3 _LEVEL_MAP = { "critical": l...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Logging setup for CoPaw: console output and optional file handler.""" import io import logging import logging.handlers @@ -25,6 +26,7 @@ def _enable_windows_ansi() -> None: + """Enable ANSI escape code support on Windows 10+.""" if platform.system() != ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/utils/logging.py
Include argument descriptions in docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import json import logging import platform import subprocess import sys import time import uuid from pathlib import Path from typing import Any, Callable logger = logging.getLogger(__name__) TELEMETRY_ENDPOINT = "https://copaw-telemetry-xissagieap.cn-hangzho...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Telemetry collection for installation analytics.""" from __future__ import annotations import json @@ -18,6 +19,7 @@ def _safe_get(func: Callable[[], str], default: str = "unknown") -> str: + """Safely get value from function, return default on error.""" ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/utils/telemetry.py
Generate docstrings with examples
# -*- coding: utf-8 -*- from __future__ import annotations import json import logging import shutil from pathlib import Path from typing import Optional from ..constant import MODELS_DIR from .schema import ( BackendType, DownloadSource, LocalModelInfo, LocalModelsManifest, ) logger = logging.getLog...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Local model download, listing, and deletion.""" from __future__ import annotations @@ -51,6 +52,7 @@ def list_local_models( backend: Optional[BackendType] = None, ) -> list[LocalModelInfo]: + """Return all downloaded local models, optionally filtered by ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/local_models/manager.py
Generate descriptive docstrings automatically
# -*- coding: utf-8 -*- from __future__ import annotations import logging import os import time from typing import Any from .guardians import BaseToolGuardian from .guardians.rule_guardian import RuleBasedToolGuardian from .models import ToolGuardResult logger = logging.getLogger(__name__) _TRUE_STRINGS = {"true", ...
--- +++ @@ -1,4 +1,20 @@ # -*- coding: utf-8 -*- +"""Tool guard engine – orchestrates all registered guardians. + +:class:`ToolGuardEngine` follows the same lazy-singleton pattern used by +the skill scanner. It discovers and runs all active :class:`BaseToolGuardian` +instances and aggregates their findings into a :cla...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/tool_guard/engine.py
Create Google-style docstrings for my code
# -*- coding: utf-8 -*- from __future__ import annotations import logging import os from typing import TYPE_CHECKING, Iterable if TYPE_CHECKING: from .models import ToolGuardResult logger = logging.getLogger(__name__) _DEFAULT_GUARDED_TOOLS = frozenset( { "execute_shell_command", }, ) def _par...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""Tool-guard utility helpers. + +* Configuration resolution – which tools to guard and which to deny. +* Structured logging for guard findings. +""" from __future__ import annotations import logging @@ -18,6 +23,10 @@ def _parse_guarded_tokens(tokens: Iterable[s...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/security/tool_guard/utils.py
Generate docstrings for each module
# -*- coding: utf-8 -*- # pylint:disable=too-many-branches,too-many-statements from __future__ import annotations import asyncio import json import logging from datetime import datetime from typing import Any, AsyncGenerator, Literal, Optional, Type from pydantic import BaseModel from agentscope.model._model_base i...
--- +++ @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- # pylint:disable=too-many-branches,too-many-statements +"""LocalChatModel — ChatModelBase implementation for local backends.""" from __future__ import annotations @@ -28,6 +29,7 @@ def _json_loads_safe(s: str) -> dict: + """Safely parse JSON string, returning...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/local_models/chat_model.py
Add docstrings to improve readability
# -*- coding: utf-8 -*- # flake8: noqa: E501 from __future__ import annotations import click from rich.console import Console from rich.panel import Panel from .channels_cmd import configure_channels_interactive from .env_cmd import configure_env_interactive from .providers_cmd import configure_providers_interactive ...
--- +++ @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- # flake8: noqa: E501 +"""CLI init: interactively create working_dir config.json and HEARTBEAT.md.""" from __future__ import annotations import click @@ -70,6 +71,7 @@ def _echo_security_warning_box() -> None: + """Print SECURITY_WARNING in a rich panel with bl...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/init_cmd.py
Add docstrings including usage examples
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio from pathlib import Path import click from ..app.runner.daemon_commands import ( DaemonContext, run_daemon_logs, run_daemon_reload_config, run_daemon_restart, run_daemon_status, run_daemon_version, ) from ..constant imp...
--- +++ @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*- +"""CLI daemon subcommands: status, restart, reload-config, version, logs. + +Shares execution with in-chat /daemon <sub> via daemon_commands. +""" from __future__ import annotations import asyncio @@ -19,6 +23,7 @@ def _get_agent_workspace(agent_id: str) -> Path:...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/daemon_cmd.py
Annotate my code with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import asyncio import logging import re from dataclasses import dataclass from datetime import datetime, timezone from typing import Optional from .binary_manager import BinaryManager logger = logging.getLogger(__name__) # Pattern to extract the public URL ...
--- +++ @@ -1,4 +1,9 @@ # -*- coding: utf-8 -*- +"""Cloudflare Quick Tunnel driver. + +Runs ``cloudflared tunnel --url http://localhost:<port>`` and exposes +the generated ``*.trycloudflare.com`` URL. +""" from __future__ import annotations import asyncio @@ -18,6 +23,7 @@ @dataclass class TunnelInfo: + """In...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/tunnel/cloudflare.py
Document helper functions with docstrings
# -*- coding: utf-8 -*- from __future__ import annotations import hashlib import logging import os import platform import shutil import stat import tempfile from pathlib import Path import httpx from ..constant import WORKING_DIR logger = logging.getLogger(__name__) _DOWNLOAD_TIMEOUT = 90 # seconds _BIN_DIR = Pa...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Auto-download cloudflared binary if not in PATH.""" from __future__ import annotations import hashlib @@ -70,6 +71,7 @@ url: str, dest: str, ) -> None: + """Stream-download *url* to *dest*.""" try: async with client.stream("GET", url, fo...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/tunnel/binary_manager.py
Add docstrings with type hints explained
# -*- coding: utf-8 -*- from __future__ import annotations from types import SimpleNamespace from pathlib import Path import click from ..config import ( get_config_path, load_config, save_config, ) from ..config.config import ( Config, ConsoleConfig, DiscordConfig, TelegramConfig, Di...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""CLI channel: list and interactively configure channels in config.json.""" from __future__ import annotations from types import SimpleNamespace @@ -143,6 +144,7 @@ def _get_channel_names() -> dict[str, str]: + """Return channel key -> display name (built-in ...
https://raw.githubusercontent.com/agentscope-ai/CoPaw/HEAD/src/copaw/cli/channels_cmd.py