instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Document this code for team use
from __future__ import annotations import logging from typing import ( TYPE_CHECKING, Annotated, Any, NotRequired, Protocol, cast, runtime_checkable, ) from langchain.agents.middleware.types import ( AgentMiddleware, AgentState, ModelRequest, ModelResponse, PrivateStat...
--- +++ @@ -1,3 +1,10 @@+"""Middleware for injecting local context into system prompt. + +Detects git state, project structure, package managers, runtimes, and +directory layout by running a bash script via the backend. Because the +script executes inside the backend (local shell or remote sandbox), the +same detection...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/local_context.py
Document this code for team use
from __future__ import annotations import asyncio from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from deepagents.backends.protocol import SandboxBackendProtocol class SandboxError(Exception): @property def original_exc(self) -> BaseException | None: ...
--- +++ @@ -1,3 +1,4 @@+"""Sandbox provider interface used by the deepagents CLI.""" from __future__ import annotations @@ -10,16 +11,20 @@ class SandboxError(Exception): + """Base error for sandbox provider operations.""" @property def original_exc(self) -> BaseException | None: + """Ret...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/integrations/sandbox_provider.py
Annotate my code with docstrings
import re import sys import tomllib from pathlib import Path PACKAGES = [ ("libs/deepagents/pyproject.toml", "libs/deepagents/deepagents/_version.py"), ("libs/cli/pyproject.toml", "libs/cli/deepagents_cli/_version.py"), ] _VERSION_RE = re.compile(r'^__version__\s*=\s*"([^"]+)"', re.MULTILINE) def _get_pypr...
--- +++ @@ -1,3 +1,9 @@+"""Check that pyproject.toml and _version.py versions stay in sync. + +Prevents releases with mismatched version numbers across the SDK and CLI +packages. Used by the CI workflow in .github/workflows/check_versions.yml +and as a pre-commit hook. +""" import re import sys @@ -13,6 +19,14 @@ ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/.github/scripts/check_version_equality.py
Document this module using docstrings
# ruff: noqa: E501 import asyncio import concurrent.futures import mimetypes import warnings from collections.abc import Awaitable, Callable from pathlib import Path from typing import Annotated, Any, Literal, NotRequired, cast from langchain.agents.middleware.types import ( AgentMiddleware, AgentState, C...
--- +++ @@ -1,3 +1,4 @@+"""Middleware for providing filesystem tools to an agent.""" # ruff: noqa: E501 import asyncio @@ -71,6 +72,29 @@ def _file_data_reducer(left: dict[str, FileData] | None, right: dict[str, FileData | None]) -> dict[str, FileData]: + """Merge file updates with support for deletions. + +...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/middleware/filesystem.py
Help me comply with documentation standards
from __future__ import annotations import asyncio import json import logging import subprocess # noqa: S404 from concurrent.futures import ThreadPoolExecutor from typing import Any from deepagents_cli.model_config import DEFAULT_CONFIG_DIR logger = logging.getLogger(__name__) _HOOKS_PATH = DEFAULT_CONFIG_DIR / "h...
--- +++ @@ -1,3 +1,18 @@+"""Lightweight hook dispatch for external tool integration. + +Loads hook configuration from `~/.deepagents/hooks.json` and fires matching +commands with JSON payloads on stdin. Subprocess work is offloaded to a +background thread so the caller's event loop is never stalled. Failures are +logge...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/hooks.py
Add docstrings for internal functions
from __future__ import annotations import os from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING from deepagents_cli._server_constants import ENV_PREFIX as _ENV_PREFIX if TYPE_CHECKING: from collections.abc import Mapping import logging logger = logging.getLogger(__name...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for project root detection and project-specific configuration.""" from __future__ import annotations @@ -18,11 +19,22 @@ @dataclass(frozen=True) class ProjectContext: + """Explicit user/project path context for project-sensitive behavior. + + Attributes: + user_...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/project_utils.py
Add clean documentation to messy code
from __future__ import annotations import re from typing import TYPE_CHECKING, TypedDict import yaml if TYPE_CHECKING: from pathlib import Path class SubagentMetadata(TypedDict): name: str """Unique identifier for the subagent, used with the task tool.""" description: str """What this subage...
--- +++ @@ -1,3 +1,24 @@+"""Subagent loader for CLI. + +Loads custom subagent definitions from the filesystem. Subagents are defined +as markdown files with YAML frontmatter in the agents/ directory. + +Directory structure: + .deepagents/agents/{agent_name}/AGENTS.md + +Example file (researcher/AGENTS.md): + --- ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/subagents.py
Add professional docstrings to my codebase
import os import re import warnings from collections.abc import Sequence from datetime import UTC, datetime from pathlib import Path, PurePosixPath from typing import Any, Literal, overload import wcmatch.glob as wcglob from deepagents.backends.protocol import FileData, FileInfo as _FileInfo, GrepMatch as _GrepMatch...
--- +++ @@ -1,3 +1,9 @@+"""Shared utility functions for memory backend implementations. + +This module contains both user-facing string formatters and structured +helpers used by backends and the composite router. Structured helpers +enable composition without fragile string parsing. +""" import os import re @@ -66...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/backends/utils.py
Generate descriptive docstrings automatically
from __future__ import annotations import functools import shutil from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: import argparse from collections.abc import Callable from deepagents.middleware.skills import SkillMetadata from deepagents_cli.output import OutputForm...
--- +++ @@ -1,3 +1,11 @@+"""CLI commands for skill management. + +These commands are registered with the CLI via main.py: +- deepagents skills list [options] +- deepagents skills create <name> [options] +- deepagents skills info <name> [options] +- deepagents skills delete <name> [options] +""" from __future__ impor...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/skills/commands.py
Add docstrings that explain inputs and outputs
from __future__ import annotations import os import subprocess import uuid import warnings from typing import TYPE_CHECKING from deepagents.backends.filesystem import FilesystemBackend from deepagents.backends.protocol import ExecuteResponse, SandboxBackendProtocol if TYPE_CHECKING: from pathlib import Path D...
--- +++ @@ -1,3 +1,9 @@+"""`LocalShellBackend`: Filesystem backend with unrestricted local shell execution. + +This backend extends FilesystemBackend to add shell command execution on the local +host system. It provides NO sandboxing or isolation - all operations run directly +on the host machine with full system acces...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/backends/local_shell.py
Write docstrings for this repository
# ruff: noqa: E402 # Imports placed after warning filters to suppress deprecation warnings # Suppress deprecation warnings from langchain_core (e.g., Pydantic V1 on Python 3.14+) import warnings warnings.filterwarnings("ignore", module="langchain_core._api.deprecation") import argparse import asyncio import context...
--- +++ @@ -1,3 +1,4 @@+"""Main entry point and CLI loop for deepagents.""" # ruff: noqa: E402 # Imports placed after warning filters to suppress deprecation warnings @@ -39,6 +40,7 @@ def check_cli_dependencies() -> None: + """Check if CLI optional dependencies are installed.""" missing = [] if ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/main.py
Add docstrings to make code maintainable
from __future__ import annotations import re from typing import TYPE_CHECKING, Any from textual.containers import Vertical from textual.content import Content from textual.widgets import Static from deepagents_cli.config import get_glyphs, is_ascii_mode if TYPE_CHECKING: from textual.app import ComposeResult ...
--- +++ @@ -1,3 +1,4 @@+"""Enhanced diff widget for displaying unified diffs.""" from __future__ import annotations @@ -15,6 +16,15 @@ def format_diff_textual(diff: str, max_lines: int | None = 100) -> Content: + """Format a unified diff with line numbers and colors. + + Args: + diff: Unified diff...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/diff.py
Please document this code using docstrings
from __future__ import annotations import asyncio import contextlib import json import logging import os import signal import subprocess # noqa: S404 import sys import tempfile import time from pathlib import Path from typing import TYPE_CHECKING, Any, Self if TYPE_CHECKING: from collections.abc import Callable...
--- +++ @@ -1,3 +1,8 @@+"""LangGraph server lifecycle management for the CLI. + +Handles starting/stopping a `langgraph dev` server process and generating the +required `langgraph.json` configuration file. +""" from __future__ import annotations @@ -27,6 +32,15 @@ def _port_in_use(host: str, port: int) -> bool...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/server.py
Generate consistent docstrings
from __future__ import annotations import argparse import json import sys from typing import Literal OutputFormat = Literal["text", "json"] """Accepted internal output modes for CLI subcommands.""" def add_json_output_arg( parser: argparse.ArgumentParser, *, default: OutputFormat | None = None ) -> None: i...
--- +++ @@ -1,3 +1,8 @@+"""Machine-readable JSON output helpers for CLI subcommands. + +This module deliberately stays stdlib-only so it can be imported from CLI +startup paths without pulling in unnecessary dependency trees. +""" from __future__ import annotations @@ -13,6 +18,14 @@ def add_json_output_arg( ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/output.py
Add detailed documentation for each class
from __future__ import annotations from typing import TYPE_CHECKING, Any, ClassVar from textual.binding import Binding, BindingType from textual.containers import Container, Vertical, VerticalScroll from textual.content import Content from textual.message import Message from textual.widgets import Static if TYPE_CH...
--- +++ @@ -1,3 +1,4 @@+"""Approval widget for HITL - using standard Textual patterns.""" from __future__ import annotations @@ -39,6 +40,16 @@ class ApprovalMenu(Container): + """Approval menu using standard Textual patterns. + + Key design decisions (following mistral-vibe reference): + - Container ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/approval.py
Generate descriptive docstrings automatically
#!/usr/bin/env python3 import sys from pathlib import Path MAX_SKILL_NAME_LENGTH = 64 SKILL_TEMPLATE = """--- name: {skill_name} description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger i...
--- +++ @@ -1,4 +1,17 @@ #!/usr/bin/env python3 +"""Skill Initializer - Creates a new skill from template. + +Usage: + init_skill.py <skill-name> --path <path> + +Examples: + init_skill.py my-new-skill --path skills/public + init_skill.py my-api-helper --path skills/private + init_skill.py custom-skill --path /custom/l...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/built_in_skills/skill-creator/scripts/init_skill.py
Write docstrings describing functionality
from __future__ import annotations from typing import TYPE_CHECKING, ClassVar from textual.binding import Binding, BindingType from textual.containers import Vertical, VerticalScroll from textual.content import Content from textual.events import ( Click, # noqa: TC002 - needed at runtime for Textual event dispa...
--- +++ @@ -1,3 +1,4 @@+"""Read-only MCP server and tool viewer modal.""" from __future__ import annotations @@ -21,6 +22,7 @@ class MCPToolItem(Static): + """A selectable tool item in the MCP viewer.""" def __init__( self, @@ -30,6 +32,14 @@ *, classes: str = "", ) -> ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/mcp_viewer.py
Add docstrings that explain purpose and usage
from __future__ import annotations import atexit import logging import sys import traceback from typing import Any from deepagents_cli._server_config import ServerConfig from deepagents_cli.project_utils import ProjectContext, get_server_project_context logger = logging.getLogger(__name__) # Module-level sandbox s...
--- +++ @@ -1,3 +1,14 @@+"""Server-side graph entry point for `langgraph dev`. + +This module is referenced by the generated `langgraph.json` and exposes the CLI +agent graph as a module-level variable that the LangGraph server can load +and serve. + +The graph is created at module import time via `make_graph()`, which...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/server_graph.py
Generate consistent documentation across files
from __future__ import annotations import json import logging import time from typing import TYPE_CHECKING from deepagents_cli._version import __version__ if TYPE_CHECKING: from pathlib import Path from deepagents_cli.model_config import DEFAULT_CONFIG_DIR logger = logging.getLogger(__name__) PYPI_URL = "http...
--- +++ @@ -1,3 +1,9 @@+"""Background update check for deepagents-cli. + +Compares the installed version against PyPI and caches the result +(see `CACHE_TTL`). All errors are silently swallowed to avoid disrupting +user experience. +""" from __future__ import annotations @@ -21,10 +27,26 @@ def _parse_version(...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/update_check.py
Generate docstrings for exported functions
from __future__ import annotations import logging import re from pathlib import PurePosixPath from typing import TYPE_CHECKING, Annotated import yaml from langchain.agents.middleware.types import PrivateStateAttr if TYPE_CHECKING: from collections.abc import Awaitable, Callable from langchain_core.runnable...
--- +++ @@ -1,3 +1,92 @@+"""Skills middleware for loading and exposing agent skills to the system prompt. + +This module implements Anthropic's agent skills pattern with progressive disclosure, +loading skills from backend storage via configurable sources. + +## Architecture + +Skills are loaded from one or more **sour...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/middleware/skills.py
Generate helpful docstrings for debugging
from __future__ import annotations import json from dataclasses import dataclass from typing import TYPE_CHECKING, Any from uuid import uuid4 from acp import ( Agent as ACPAgent, InitializeResponse, NewSessionResponse, PromptResponse, SetSessionModeResponse, run_agent as run_acp_agent, st...
--- +++ @@ -1,3 +1,4 @@+"""ACP server implementation for Deep Agents.""" from __future__ import annotations @@ -71,12 +72,14 @@ @dataclass(frozen=True, slots=True) class AgentSessionContext: + """Context for an agent session, including working directory and mode.""" cwd: str mode: str class ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/acp/deepagents_acp/server.py
Add clean documentation to messy code
from __future__ import annotations import logging import sys import threading import time from dataclasses import dataclass, field from datetime import UTC, datetime from pathlib import Path from typing import TYPE_CHECKING, Any, cast from langchain.agents.middleware.human_in_the_loop import ActionRequest, HITLReque...
--- +++ @@ -1,3 +1,21 @@+"""Non-interactive execution mode for deepagents CLI. + +Provides `run_non_interactive` which runs a single user task against the +agent graph, streams results to stdout, and exits with an appropriate code. + +The agent runs inside a `langgraph dev` server subprocess, connected via +the `Remote...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/non_interactive.py
Add standardized docstrings across the file
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from deepagents._models import model_matches_spec # noqa: PLC2701 from langchain.agents.middleware.types import ( AgentMiddleware, ModelRequest, ModelResponse, ) from typing_extensions import TypedDict if TYPE_CHECK...
--- +++ @@ -1,3 +1,9 @@+"""CLI middleware for runtime model selection via LangGraph runtime context. + +Allows switching the model per invocation by passing a `CLIContext` via +`context=` on `agent.astream()` / `agent.invoke()` without recompiling +the graph. +""" from __future__ import annotations @@ -20,6 +26,11...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/configurable_model.py
Generate documentation strings for clarity
import json from contextlib import suppress from pathlib import Path from typing import Any from deepagents.backends import DEFAULT_EXECUTE_TIMEOUT from deepagents_cli.config import MAX_ARG_LENGTH, get_glyphs from deepagents_cli.unicode_security import strip_dangerous_unicode _HIDDEN_CHAR_MARKER = " [hidden chars r...
--- +++ @@ -1,3 +1,10 @@+"""Formatting utilities for tool call display in the CLI. + +This module handles rendering tool calls and tool messages for the TUI. + +Imported at runtime (not at CLI startup), so it can safely depend +on heavier modules like `backends`. +""" import json from contextlib import suppress @@ ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/tool_display.py
Write docstrings describing functionality
import argparse from collections.abc import Callable from rich.markup import escape from deepagents_cli._version import __version__ from deepagents_cli.config import ( COLORS, DOCS_URL, _get_editable_install_path, _is_editable_install, console, ) _JSON_OPTION_LINE = " --json Em...
--- +++ @@ -1,3 +1,8 @@+"""Help screens and argparse utilities for the CLI. + +This module is imported at CLI startup to wire `-h` actions into the +argparse tree. It must stay lightweight — no SDK or langchain imports. +""" import argparse from collections.abc import Callable @@ -21,12 +26,33 @@ help_fn: Call...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/ui.py
Add return value explanations in docstrings
from __future__ import annotations import difflib from typing import TYPE_CHECKING, Any from deepagents_cli.widgets.tool_widgets import ( EditFileApprovalWidget, GenericApprovalWidget, WriteFileApprovalWidget, ) if TYPE_CHECKING: from deepagents_cli.widgets.tool_widgets import ToolApprovalWidget c...
--- +++ @@ -1,3 +1,4 @@+"""Tool renderers for approval widgets - registry pattern.""" from __future__ import annotations @@ -15,15 +16,25 @@ class ToolRenderer: + """Base renderer for tool approval widgets.""" @staticmethod def get_approval_widget( tool_args: dict[str, Any], ) -> t...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/tool_renderers.py
Add docstrings to incomplete code
from __future__ import annotations import asyncio import logging import sqlite3 from contextlib import asynccontextmanager from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, NamedTuple, NotRequired, TypedDict, cast if TYPE_CHECKING: from collections.abc import AsyncIterator ...
--- +++ @@ -1,3 +1,4 @@+"""Thread management using LangGraph's built-in checkpoint persistence.""" from __future__ import annotations @@ -31,6 +32,11 @@ def _patch_aiosqlite() -> None: + """Patch aiosqlite.Connection with `is_alive()` if missing. + + Required by langgraph-checkpoint>=2.1.0. + See: htt...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/sessions.py
Turn comments into proper docstrings
from __future__ import annotations import importlib import json import logging import os import re import shlex import sys import threading from dataclasses import dataclass from enum import StrEnum from importlib.metadata import PackageNotFoundError, distribution from pathlib import Path from typing import TYPE_CHEC...
--- +++ @@ -1,3 +1,4 @@+"""Configuration, constants, and model creation for the CLI.""" from __future__ import annotations @@ -28,6 +29,14 @@ def _find_dotenv_from_start_path(start_path: Path) -> Path | None: + """Find the nearest `.env` file from an explicit start path upward. + + Args: + start_p...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/config.py
Document classes and their methods
from __future__ import annotations import contextlib import hashlib import logging import os import tempfile from pathlib import Path from typing import Any logger = logging.getLogger(__name__) _DEFAULT_CONFIG_DIR = Path.home() / ".deepagents" _DEFAULT_CONFIG_PATH = _DEFAULT_CONFIG_DIR / "config.toml" def compute...
--- +++ @@ -1,3 +1,12 @@+"""Trust store for project-level MCP server configurations. + +Manages persistent approval of project-level MCP configs that contain stdio +servers (which execute local commands). Trust is fingerprint-based: if the +config content changes, the user must re-approve. + +Trust entries are stored i...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/mcp_trust.py
Document functions with detailed explanations
from __future__ import annotations import contextlib import logging import os import time from typing import TYPE_CHECKING, Any from deepagents.backends.protocol import ( ExecuteResponse, FileDownloadResponse, FileUploadResponse, SandboxBackendProtocol, ) from deepagents.backends.sandbox import BaseS...
--- +++ @@ -1,3 +1,4 @@+"""LangSmith sandbox backend implementation.""" from __future__ import annotations @@ -30,16 +31,40 @@ class LangSmithBackend(BaseSandbox): + """LangSmith backend implementation conforming to SandboxBackendProtocol. + + This implementation inherits all file operation methods from ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/integrations/langsmith.py
Include argument descriptions in docstrings
from __future__ import annotations import contextlib import importlib import importlib.util import logging import os import shlex import string import time from contextlib import contextmanager from pathlib import Path from typing import TYPE_CHECKING, Any from rich.markup import escape as escape_markup from deepag...
--- +++ @@ -1,3 +1,4 @@+"""Sandbox lifecycle management with provider abstraction.""" from __future__ import annotations @@ -31,6 +32,16 @@ def _run_sandbox_setup(backend: SandboxBackendProtocol, setup_script_path: str) -> None: + """Run users setup script in sandbox with env var expansion. + + Args: + ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/integrations/sandbox_factory.py
Replace inline comments with docstrings
from __future__ import annotations import logging from typing import TYPE_CHECKING, cast from deepagents.backends.filesystem import FilesystemBackend if TYPE_CHECKING: from pathlib import Path from deepagents.middleware.skills import ( SkillMetadata, _list_skills as list_skills_from_backend, # noqa: PL...
--- +++ @@ -1,3 +1,13 @@+"""Skill loader for CLI commands. + +This module provides filesystem-based skill discovery for CLI operations +(list, create, info, delete). It wraps the prebuilt middleware functionality from +deepagents.middleware.skills and adapts it for direct filesystem access +needed by CLI commands. + +F...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/skills/load.py
Generate docstrings for each module
from __future__ import annotations import base64 import logging import os import pathlib from typing import TYPE_CHECKING from deepagents_cli.config import get_glyphs logger = logging.getLogger(__name__) if TYPE_CHECKING: from textual.app import App _PREVIEW_MAX_LENGTH = 40 def _copy_osc52(text: str) -> Non...
--- +++ @@ -1,3 +1,4 @@+"""Clipboard utilities for deepagents-cli.""" from __future__ import annotations @@ -18,6 +19,7 @@ def _copy_osc52(text: str) -> None: + """Copy text using OSC 52 escape sequence (works over SSH/tmux).""" encoded = base64.b64encode(text.encode("utf-8")).decode("ascii") osc5...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/clipboard.py
Turn comments into proper docstrings
from __future__ import annotations import json import logging import shutil from contextlib import AsyncExitStack from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from langchain_core.tools import BaseTool from langchain_mcp_adapters.cli...
--- +++ @@ -1,3 +1,10 @@+"""MCP (Model Context Protocol) tools loader for deepagents CLI. + +This module provides async functions to load and manage MCP servers using +`langchain-mcp-adapters`, supporting Claude Desktop style JSON configs. +It also supports automatic discovery of `.mcp.json` files from user-level +and ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/mcp_tools.py
Add concise docstrings to each method
from __future__ import annotations import logging from dataclasses import dataclass from datetime import UTC, datetime from typing import TYPE_CHECKING, Any from langchain_core.messages import get_buffer_string from langchain_core.messages.utils import count_tokens_approximately from deepagents_cli.config import cr...
--- +++ @@ -1,3 +1,8 @@+"""Business logic for the /offload command. + +Extracts the core offload workflow from the UI layer so it can be +tested independently of the Textual app. +""" from __future__ import annotations @@ -29,6 +34,7 @@ @dataclass(frozen=True) class OffloadResult: + """Successful offload res...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/offload.py
Provide clean and structured docstrings
from __future__ import annotations import logging import uuid from dataclasses import dataclass, field from enum import StrEnum from time import time from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from textual.widget import Widget logger = logging.getLogger(__name__) # Fields on MessageData that calle...
--- +++ @@ -1,3 +1,13 @@+"""Message store for virtualized chat history. + +This module provides data structures and management for message virtualization, +allowing the CLI to handle large message histories efficiently by keeping only +a sliding window of widgets in the DOM while storing all message data as +lightweigh...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/message_store.py
Add docstrings following best practices
from __future__ import annotations import asyncio import logging import uuid import warnings from datetime import UTC, datetime from typing import TYPE_CHECKING, Annotated, Any, NotRequired, cast from langchain.agents.middleware.summarization import ( _DEFAULT_MESSAGES_TO_KEEP, _DEFAULT_TRIM_TOKEN_LIMIT, ...
--- +++ @@ -1,3 +1,51 @@+"""Summarization middleware for automatic and tool-based conversation compaction. + +This module provides two middleware classes and a convenience factory: + +- `SummarizationMiddleware` — automatically compacts the conversation when token + usage exceeds a configurable threshold. + + Old...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/middleware/summarization.py
Add docstrings to improve readability
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import AsyncIterator, Callable from deepagents_cli._debug import configure_debug_logging logger = logging.getLogger(__name__) configure_debug_logging(logger) def _require_thread_id(c...
--- +++ @@ -1,3 +1,10 @@+"""Remote agent client — thin wrapper around LangGraph's `RemoteGraph`. + +Delegates streaming, state management, and SSE handling to +`langgraph.pregel.remote.RemoteGraph`. The only added logic is converting raw +message dicts from the server into LangChain message objects that the CLI's +Text...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/remote_client.py
Add concise docstrings to each method
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, ClassVar from textual.binding import Binding, BindingType from textual.containers import Container, Vertical, VerticalScroll from textual.content import Content from textual.events import ( Click, # noqa: TC002 - needed at ...
--- +++ @@ -1,3 +1,4 @@+"""Interactive model selector screen for /model command.""" from __future__ import annotations @@ -33,6 +34,7 @@ class ModelOption(Static): + """A clickable model option in the selector.""" def __init__( self, @@ -44,6 +46,18 @@ has_creds: bool | None = True, ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/model_selector.py
Create documentation strings for testing functions
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, ClassVar, Literal from textual.binding import Binding, BindingType from textual.containers import Container, Vertical from textual.content import Content from textual.message import Message from textual.widgets import Input, Sta...
--- +++ @@ -1,3 +1,4 @@+"""Ask user widget for interactive questions during agent execution.""" from __future__ import annotations @@ -32,6 +33,11 @@ class AskUserMenu(Container): + """Interactive widget for asking the user questions. + + Supports text input and multiple choice questions. Multiple choice...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/ask_user.py
Provide clean and structured docstrings
import base64 from typing import TYPE_CHECKING, Any from deepagents.backends.protocol import ( BackendProtocol, EditResult, FileData, FileDownloadResponse, FileFormat, FileInfo, FileUploadResponse, GlobResult, GrepResult, LsResult, ReadResult, WriteResult, ) from deepag...
--- +++ @@ -1,3 +1,4 @@+"""StateBackend: Store files in LangGraph agent state (ephemeral).""" import base64 from typing import TYPE_CHECKING, Any @@ -33,6 +34,16 @@ class StateBackend(BackendProtocol): + """Backend that stores files in agent state (ephemeral). + + Uses LangGraph's state management and che...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/backends/state.py
Add professional docstrings to my codebase
import sys import tomllib from pathlib import Path from re import compile as re_compile # Matches the package name at the start of a PEP 508 dependency string. # Handles both hyphenated and underscored names (PEP 503 normalizes these). _NAME_RE = re_compile(r"^([A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?)") def _norma...
--- +++ @@ -1,3 +1,10 @@+"""Check that optional extras stay in sync with required dependencies (openai). + +When a package appears in both [project.dependencies] and +[project.optional-dependencies], we ensure their version constraints match. +This prevents silent version drift (e.g. bumping a required dep but +forgett...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/.github/scripts/check_extras_sync.py
Write beginner-friendly docstrings
from __future__ import annotations import logging from contextlib import suppress from pathlib import Path from typing import TYPE_CHECKING, Any from textual.containers import Horizontal from textual.content import Content from textual.css.query import NoMatches from textual.reactive import reactive from textual.wid...
--- +++ @@ -1,3 +1,4 @@+"""Status bar widget for deepagents-cli.""" from __future__ import annotations @@ -24,17 +25,37 @@ class ModelLabel(Widget): + """A label that displays a model name, right-aligned with smart truncation. + + When the full `provider:model` text doesn't fit, the provider is dropped +...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/status.py
Document functions with clear intent
from collections.abc import Callable, Sequence from typing import Any from langchain.agents import create_agent from langchain.agents.middleware import HumanInTheLoopMiddleware, InterruptOnConfig, TodoListMiddleware from langchain.agents.middleware.types import AgentMiddleware from langchain.agents.structured_output ...
--- +++ @@ -1,3 +1,4 @@+"""Deep Agents come with planning, filesystem, and subagents.""" from collections.abc import Callable, Sequence from typing import Any @@ -68,6 +69,11 @@ def get_default_model() -> ChatAnthropic: + """Get the default model for deep agents. + + Returns: + `ChatAnthropic` inst...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/graph.py
Auto-generate documentation strings for this file
from __future__ import annotations import logging import webbrowser from typing import TYPE_CHECKING from deepagents_cli.unicode_security import check_url_safety, strip_dangerous_unicode if TYPE_CHECKING: from textual.events import Click logger = logging.getLogger(__name__) def open_style_link(event: Click) ...
--- +++ @@ -1,3 +1,4 @@+"""Shared link-click handling for Textual widgets.""" from __future__ import annotations @@ -14,6 +15,24 @@ def open_style_link(event: Click) -> None: + """Open the URL from a Rich link style on click, if present. + + Rich `Style(link=...)` embeds OSC 8 terminal hyperlinks, but Te...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/_links.py
Create simple docstrings for beginners
from __future__ import annotations from time import time from typing import TYPE_CHECKING from textual.containers import Horizontal from textual.content import Content from textual.widgets import Static from deepagents_cli.config import get_glyphs if TYPE_CHECKING: from textual.app import ComposeResult class...
--- +++ @@ -1,3 +1,4 @@+"""Loading widget with animated spinner for agent activity.""" from __future__ import annotations @@ -15,25 +16,42 @@ class Spinner: + """Animated spinner using charset-appropriate frames.""" def __init__(self) -> None: + """Initialize spinner.""" self._positio...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/loading.py
Add docstrings with type hints explained
import logging import re import shlex from dataclasses import dataclass from pathlib import Path from typing import Literal from urllib.parse import unquote, urlparse from rich.markup import escape as escape_markup from deepagents_cli.config import console from deepagents_cli.media_utils import ImageData, VideoData ...
--- +++ @@ -1,3 +1,4 @@+"""Input handling utilities including image/video tracking and file mention parsing.""" import logging import re @@ -89,20 +90,44 @@ @dataclass(frozen=True) class ParsedPastedPathPayload: + """Unified parse result for dropped-path payload detection. + + Attributes: + paths: R...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/input.py
Help me comply with documentation standards
from __future__ import annotations import asyncio import random from typing import TYPE_CHECKING, Any from textual.color import Color as TColor from textual.content import Content from textual.style import Style as TStyle from textual.widgets import Static if TYPE_CHECKING: from textual.events import Click fro...
--- +++ @@ -1,3 +1,4 @@+"""Welcome banner widget for deepagents-cli.""" from __future__ import annotations @@ -41,6 +42,7 @@ class WelcomeBanner(Static): + """Welcome banner displayed at startup.""" # Disable Textual's auto_links to prevent a flicker cycle: Style.__add__ # calls .copy() for link...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/welcome.py
Write docstrings for algorithm functions
from __future__ import annotations import shlex from typing import TYPE_CHECKING if TYPE_CHECKING: from acp.schema import ( AudioContentBlock, EmbeddedResourceContentBlock, ImageContentBlock, ResourceContentBlock, TextContentBlock, ) def convert_text_block_to_content...
--- +++ @@ -1,3 +1,4 @@+"""Utility functions for converting ACP content blocks to LangChain formats.""" from __future__ import annotations @@ -15,10 +16,12 @@ def convert_text_block_to_content_blocks(block: TextContentBlock) -> list[dict[str, str]]: + """Convert an ACP text block to LangChain content blocks...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/acp/deepagents_acp/utils.py
Write proper docstrings for these functions
from __future__ import annotations import asyncio import json import logging import os import shlex import signal import sys import time import uuid import webbrowser from collections import deque from contextlib import suppress from dataclasses import dataclass, field from pathlib import Path from typing import TYPE...
--- +++ @@ -1,3 +1,4 @@+"""Textual UI application for deepagents-cli.""" from __future__ import annotations @@ -129,6 +130,11 @@ def _write_iterm_escape(sequence: str) -> None: + """Write an iTerm2 escape sequence to stderr. + + Silently fails if the terminal is unavailable (redirected, closed, broken + ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/app.py
Add minimal docstrings for each function
from __future__ import annotations import json import os SET0: list[str] = [ # Anthropic "anthropic:claude-haiku-4-5-20251001", "anthropic:claude-sonnet-4-20250514", "anthropic:claude-sonnet-4-5-20250929", "anthropic:claude-sonnet-4-6", "anthropic:claude-opus-4-1", "anthropic:claude-opus-...
--- +++ @@ -1,3 +1,15 @@+"""Output the eval matrix JSON for the GitHub Actions evals workflow. + +Prints a single line: matrix={"model":["provider:model-name", ...]} +suitable for appending to $GITHUB_OUTPUT. + +Reads the EVAL_MODELS env var to determine which models to include: + - "all" (default): every model across...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/.github/scripts/get_eval_models.py
Write docstrings for algorithm functions
from __future__ import annotations import asyncio import logging import time from pathlib import Path from typing import TYPE_CHECKING, Any, ClassVar from textual.binding import Binding from textual.containers import Horizontal, Vertical, VerticalScroll from textual.content import Content from textual.css.query impo...
--- +++ @@ -1,3 +1,4 @@+"""Chat input widget for deepagents-cli with autocomplete and history support.""" from __future__ import annotations @@ -38,6 +39,11 @@ def _default_history_path() -> Path: + """Return the default history file path. + + Extracted as a function so tests can monkeypatch it to a temp...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/chat_input.py
Add minimal docstrings for each function
import warnings from collections.abc import Awaitable, Callable, Sequence from typing import Annotated, Any, NotRequired, TypedDict, Unpack, cast from langchain.agents import create_agent from langchain.agents.middleware import HumanInTheLoopMiddleware, InterruptOnConfig from langchain.agents.middleware.types import ...
--- +++ @@ -1,3 +1,4 @@+"""Middleware for providing subagents to an agent via a `task` tool.""" import warnings from collections.abc import Awaitable, Callable, Sequence @@ -19,6 +20,38 @@ class SubAgent(TypedDict): + """Specification for an agent. + + When using `create_deep_agent`, subagents automatical...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/middleware/subagents.py
Generate missing documentation strings
import base64 import io import logging import os import pathlib import shutil # S404: subprocess needed for clipboard access via pngpaste/osascript import subprocess # noqa: S404 import sys import tempfile from dataclasses import dataclass from typing import TYPE_CHECKING if TYPE_CHECKING: from langchain_core.m...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for handling image and video media from clipboard and files.""" import base64 import io @@ -50,17 +51,31 @@ def _get_executable(name: str) -> str | None: + """Get full path to an executable using shutil.which(). + + Args: + name: Name of the executable to find +...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/media_utils.py
Turn comments into proper docstrings
import base64 import json import logging import os import re import subprocess import warnings from datetime import datetime from pathlib import Path import wcmatch.glob as wcglob from deepagents.backends.protocol import ( BackendProtocol, EditResult, FileDownloadResponse, FileInfo, FileUploadRes...
--- +++ @@ -1,3 +1,4 @@+"""`FilesystemBackend`: Read and write files directly from the filesystem.""" import base64 import json @@ -35,6 +36,52 @@ class FilesystemBackend(BackendProtocol): + """Backend that reads and writes files directly from the filesystem. + + Files are accessed using their actual file...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/backends/filesystem.py
Create simple docstrings for beginners
from __future__ import annotations import asyncio import contextlib import shutil # S404: subprocess is required for git ls-files to get project file list import subprocess # noqa: S404 from difflib import SequenceMatcher from enum import StrEnum from pathlib import Path from typing import TYPE_CHECKING, Protocol ...
--- +++ @@ -1,3 +1,8 @@+"""Autocomplete system for @ mentions and / commands. + +This is a custom implementation that handles trigger-based completion +for slash commands (/) and file mentions (@). +""" from __future__ import annotations @@ -16,6 +21,11 @@ def _get_git_executable() -> str | None: + """Get f...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/autocomplete.py
Add inline docstrings for readability
# ruff: noqa: E501 # Long prompt strings in MEMORY_SYSTEM_PROMPT from __future__ import annotations import logging from typing import TYPE_CHECKING, Annotated, NotRequired, TypedDict if TYPE_CHECKING: from collections.abc import Awaitable, Callable from langchain_core.runnables import RunnableConfig fr...
--- +++ @@ -1,4 +1,52 @@ # ruff: noqa: E501 # Long prompt strings in MEMORY_SYSTEM_PROMPT +"""Middleware for loading agent memory/context from AGENTS.md files. + +This module implements support for the AGENTS.md specification (https://agents.md/), +loading memory/context from configurable sources and injecting into th...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/middleware/memory.py
Document this script properly
from __future__ import annotations from typing import Any from langchain.chat_models import init_chat_model from langchain_core.language_models import BaseChatModel def resolve_model(model: str | BaseChatModel) -> BaseChatModel: if isinstance(model, BaseChatModel): return model if model.startswith(...
--- +++ @@ -1,3 +1,4 @@+"""Shared helpers for resolving and inspecting chat models.""" from __future__ import annotations @@ -8,6 +9,19 @@ def resolve_model(model: str | BaseChatModel) -> BaseChatModel: + """Resolve a model string to a `BaseChatModel`. + + If `model` is already a `BaseChatModel`, returns...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/_models.py
Write reusable docstrings
from __future__ import annotations import asyncio import contextlib import logging import sqlite3 from typing import TYPE_CHECKING, ClassVar, cast from rich.cells import cell_len from textual.binding import Binding, BindingType from textual.color import Color as TColor from textual.containers import Horizontal, Vert...
--- +++ @@ -1,3 +1,4 @@+"""Interactive thread selector screen for /threads command.""" from __future__ import annotations @@ -109,6 +110,13 @@ def _apply_column_width( cell: Static, key: str, column_widths: Mapping[str, int | None] ) -> None: + """Apply an explicit width to a table cell when one is config...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/thread_selector.py
Add standardized docstrings across the file
from __future__ import annotations import asyncio import json import logging from typing import TYPE_CHECKING, Annotated, Any, NotRequired, TypedDict from langchain.agents.middleware.types import AgentMiddleware, AgentState, ContextT, ModelResponse, ResponseT from langchain.tools import ToolRuntime # noqa: TC002 fr...
--- +++ @@ -1,3 +1,10 @@+"""Middleware for async subagents running on remote LangGraph servers. + +Async subagents use the LangGraph SDK to launch background runs on remote +LangGraph deployments. Unlike synchronous subagents (which block until +completion), async subagents return a job ID immediately, allowing the mai...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/middleware/async_subagents.py
Replace inline comments with docstrings
from __future__ import annotations import base64 import json import shlex from abc import ABC, abstractmethod from deepagents.backends.protocol import ( EditResult, ExecuteResponse, FileDownloadResponse, FileInfo, FileUploadResponse, GlobResult, GrepMatch, GrepResult, LsResult, ...
--- +++ @@ -1,3 +1,11 @@+"""Base sandbox implementation with execute() as the only abstract method. + +This module provides a base class that implements all SandboxBackendProtocol +methods using shell commands executed via execute(). Concrete implementations +only need to implement the execute() method. + +It also defi...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/backends/sandbox.py
Add concise docstrings to each method
from langchain_core.messages import ContentBlock, SystemMessage def append_to_system_message( system_message: SystemMessage | None, text: str, ) -> SystemMessage: new_content: list[ContentBlock] = list(system_message.content_blocks) if system_message else [] if new_content: text = f"\n\n{text...
--- +++ @@ -1,3 +1,4 @@+"""Utility functions for middleware.""" from langchain_core.messages import ContentBlock, SystemMessage @@ -6,8 +7,17 @@ system_message: SystemMessage | None, text: str, ) -> SystemMessage: + """Append text to a system message. + + Args: + system_message: Existing sys...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/middleware/_utils.py
Add detailed docstrings explaining each function
from __future__ import annotations import difflib import logging from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any, Literal from deepagents.backends.utils import perform_string_replacement from deepagents_cli.config import settings logger = logging.getLogger(__...
--- +++ @@ -1,3 +1,4 @@+"""Helpers for tracking file operations and computing diffs for CLI display.""" from __future__ import annotations @@ -21,6 +22,7 @@ @dataclass class ApprovalPreview: + """Data used to render HITL previews.""" title: str details: list[str] @@ -30,6 +32,11 @@ def _safe_...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/file_ops.py
Generate docstrings for script automation
from __future__ import annotations import logging import os from pathlib import Path def configure_debug_logging(target: logging.Logger) -> None: if not os.environ.get("DEEPAGENTS_DEBUG"): return debug_path = Path( os.environ.get( "DEEPAGENTS_DEBUG_FILE", "/tmp/deepa...
--- +++ @@ -1,3 +1,10 @@+"""Shared debug-logging configuration for verbose file-based tracing. + +When the `DEEPAGENTS_DEBUG` environment variable is set, modules that handle +streaming or remote communication can enable detailed file-based logging. This +helper centralizes the setup so the env-var name, file path, and...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/_debug.py
Add missing documentation to my Python functions
# This module has complex streaming logic ported from execution.py from __future__ import annotations import asyncio import json import logging import time import uuid from dataclasses import dataclass, field from datetime import UTC, datetime from pathlib import Path from typing import TYPE_CHECKING, Any, Literal i...
--- +++ @@ -1,3 +1,4 @@+"""Textual UI adapter for agent execution.""" # This module has complex streaming logic ported from execution.py from __future__ import annotations @@ -58,6 +59,13 @@ @dataclass class ModelStats: + """Token stats for a single model within a session. + + Attributes: + request_...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/textual_adapter.py
Document classes and their methods
import abc import asyncio import inspect import logging import warnings from collections.abc import Callable from dataclasses import dataclass from functools import lru_cache from typing import Any, Literal, NotRequired, TypeAlias from langchain.tools import ToolRuntime from typing_extensions import TypedDict FileFo...
--- +++ @@ -1,3 +1,9 @@+"""Protocol definition for pluggable memory backends. + +This module defines the BackendProtocol that all backend implementations +must follow. Backends can store files in different locations (state, filesystem, +database, etc.) and provide a uniform interface for file operations. +""" import...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/deepagents/deepagents/backends/protocol.py
Insert docstrings into my code
from __future__ import annotations import json import logging from typing import TYPE_CHECKING if TYPE_CHECKING: from pathlib import Path logger = logging.getLogger(__name__) class HistoryManager: def __init__(self, history_file: Path, max_entries: int = 100) -> None: self.history_file = history_...
--- +++ @@ -1,3 +1,4 @@+"""Command history manager for input persistence.""" from __future__ import annotations @@ -12,8 +13,19 @@ class HistoryManager: + """Manages command history with file persistence. + + Uses append-only writes for concurrent safety. Multiple agents can + safely write to the same...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/history.py
Add docstrings following best practices
from __future__ import annotations import json import logging import os from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any from deepagents_cli._server_constants import ENV_PREFIX as _ENV_PREFIX if TYPE_CHECKING: from deepagents_cli.project_utils import ProjectContex...
--- +++ @@ -1,3 +1,12 @@+"""Typed configuration for the CLI-to-server subprocess communication channel. + +The CLI spawns a `langgraph dev` subprocess and passes configuration via +environment variables prefixed with `DA_SERVER_`. This module provides a single +`ServerConfig` dataclass that both sides share so that the...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/_server_config.py
Write docstrings for backend logic
from __future__ import annotations import logging import os import re import shutil import tempfile import tomllib from pathlib import Path from typing import TYPE_CHECKING, Any from deepagents import create_deep_agent from deepagents.backends import CompositeBackend, LocalShellBackend from deepagents.backends.files...
--- +++ @@ -1,3 +1,4 @@+"""Agent management and creation for the CLI.""" from __future__ import annotations @@ -65,6 +66,26 @@ def load_async_subagents(config_path: Path | None = None) -> list[AsyncSubAgent]: + """Load async subagent definitions from `config.toml`. + + Reads the `[async_subagents]` secti...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/agent.py
Add docstrings that explain inputs and outputs
from __future__ import annotations from typing import TYPE_CHECKING, Any, Literal if TYPE_CHECKING: from tavily import TavilyClient _UNSET = object() _tavily_client: TavilyClient | object | None = _UNSET def _get_tavily_client() -> TavilyClient | None: global _tavily_client # noqa: PLW0603 # Module-leve...
--- +++ @@ -1,3 +1,4 @@+"""Custom tools for the CLI agent.""" from __future__ import annotations @@ -11,6 +12,11 @@ def _get_tavily_client() -> TavilyClient | None: + """Get or initialize the lazy Tavily client singleton. + + Returns: + TavilyClient instance, or None if API key is not configured. ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/tools.py
Add docstrings to improve readability
from __future__ import annotations from dataclasses import dataclass from enum import StrEnum class BypassTier(StrEnum): ALWAYS = "always" """Execute regardless of any busy state, including mid-thread-switch.""" CONNECTING = "connecting" """Bypass only during initial server connection, not during ...
--- +++ @@ -1,3 +1,9 @@+"""Unified slash-command registry. + +Every slash command is declared once as a `SlashCommand` entry in `COMMANDS`. +Bypass-tier frozensets and autocomplete tuples are derived automatically — no +other file should hard-code command metadata. +""" from __future__ import annotations @@ -6,6 +...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/command_registry.py
Generate docstrings with parameter types
from __future__ import annotations import logging import os import shutil import tempfile from contextlib import asynccontextmanager from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import AsyncIterator from deepagents_cli.mcp_tools import MCPSessionManag...
--- +++ @@ -1,3 +1,17 @@+"""Server lifecycle orchestration for the CLI. + +Provides `start_server_and_get_agent` which handles the full flow of: + +1. Building a `ServerConfig` from CLI arguments +2. Writing config to env vars via `ServerConfig.to_env()` +3. Scaffolding a workspace (langgraph.json, checkpointer, pyproj...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/server_manager.py
Document classes and their methods
from __future__ import annotations import contextlib import logging import os import shlex import subprocess # noqa: S404 import sys import tempfile from pathlib import Path logger = logging.getLogger(__name__) GUI_WAIT_FLAG: dict[str, str] = { "code": "--wait", "cursor": "--wait", "zed": "--wait", ...
--- +++ @@ -1,3 +1,4 @@+"""External editor support for composing prompts.""" from __future__ import annotations @@ -27,6 +28,14 @@ def resolve_editor() -> list[str] | None: + """Resolve editor command from environment. + + Checks $VISUAL, then $EDITOR, then falls back to platform default. + + Returns:...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/editor.py
Document this code for team use
from __future__ import annotations import ast import json import logging import re from dataclasses import dataclass from pathlib import Path from time import time from typing import TYPE_CHECKING, Any from textual.containers import Vertical from textual.content import Content from textual.widgets import Markdown, S...
--- +++ @@ -1,3 +1,4 @@+"""Message widgets for deepagents-cli.""" from __future__ import annotations @@ -36,6 +37,14 @@ def _show_timestamp_toast(widget: Static | Vertical) -> None: + """Show a toast with the message's creation timestamp. + + No-ops silently if the widget is not mounted or has no associa...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/messages.py
Generate docstrings with examples
from __future__ import annotations import ipaddress import unicodedata from dataclasses import dataclass from typing import Any from urllib.parse import urlparse _DANGEROUS_CODEPOINTS: frozenset[int] = frozenset( { # BiDi directional formatting controls (embeddings, overrides, pop) *range(0x202A,...
--- +++ @@ -1,3 +1,8 @@+"""Unicode security helpers for deceptive text and URL checks. + +This module is intentionally lightweight so it can be imported in display and +approval paths without affecting startup performance. +""" from __future__ import annotations @@ -78,6 +83,14 @@ @dataclass(frozen=True, slots=T...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/unicode_security.py
Write docstrings for data processing functions
from __future__ import annotations from typing import TYPE_CHECKING, Any from textual.containers import Vertical from textual.content import Content from textual.widgets import Markdown, Static if TYPE_CHECKING: from textual.app import ComposeResult # Constants for display limits _MAX_VALUE_LEN = 200 _MAX_LINE...
--- +++ @@ -1,3 +1,4 @@+"""Tool-specific approval widgets for HITL display.""" from __future__ import annotations @@ -18,18 +19,31 @@ class ToolApprovalWidget(Vertical): + """Base class for tool approval widgets.""" def __init__(self, data: dict[str, Any]) -> None: + """Initialize the tool app...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/cli/deepagents_cli/widgets/tool_widgets.py
Improve documentation using docstrings
from __future__ import annotations import math def wilson_ci( successes: int, total: int, *, z: float = 1.96, ) -> tuple[float, float]: if total == 0: return (0.0, 0.0) p = successes / total z2 = z * z denom = 1 + z2 / total center = (p + z2 / (2 * total)) / denom ma...
--- +++ @@ -1,3 +1,8 @@+"""Statistical utilities for eval score reporting. + +Provides Wilson score confidence intervals and minimum detectable effect +estimation, as recommended by Anthropic's infrastructure noise research. +""" from __future__ import annotations @@ -10,6 +15,20 @@ *, z: float = 1.96, )...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/harbor/deepagents_harbor/stats.py
Add docstrings explaining edge cases
import hashlib import uuid def create_example_id_from_instruction(instruction: str, seed: int = 42) -> str: # Normalize the instruction: strip leading/trailing whitespace normalized = instruction.strip() # Prepend seed as bytes to the instruction for hashing seeded_data = seed.to_bytes(8, byteorder=...
--- +++ @@ -1,9 +1,22 @@+"""LangSmith integration for Harbor Deep Agents.""" import hashlib import uuid def create_example_id_from_instruction(instruction: str, seed: int = 42) -> str: + """Create a deterministic UUID from an instruction string. + + Normalizes the instruction by stripping whitespace and ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/harbor/deepagents_harbor/tracing.py
Add docstrings to clarify complex logic
from __future__ import annotations import json import logging import re from enum import Enum from typing import Any logger = logging.getLogger(__name__) class FailureCategory(Enum): CAPABILITY = "capability" """Model produced wrong answer, incomplete solution, or logic error.""" INFRA_OOM = "infra_o...
--- +++ @@ -1,3 +1,8 @@+"""Failure classification for eval trial results. + +Categorizes failures as infrastructure (OOM, timeout, sandbox) vs. model +capability using exit codes and text pattern matching. +""" from __future__ import annotations @@ -11,6 +16,10 @@ class FailureCategory(Enum): + """Classific...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/harbor/deepagents_harbor/failure.py
Add detailed docstrings explaining each function
from __future__ import annotations import importlib.metadata import json import logging import os import uuid from datetime import UTC, datetime from typing import TYPE_CHECKING, Any from deepagents import create_deep_agent from deepagents.graph import get_default_model from deepagents_cli.agent import create_cli_ag...
--- +++ @@ -1,3 +1,4 @@+"""A wrapper for Deep Agents to run in Harbor environments.""" from __future__ import annotations @@ -66,6 +67,10 @@ class DeepAgentsWrapper(BaseAgent): + """Harbor agent implementation using LangChain Deep Agents. + + Wraps Deep Agents to execute tasks in Harbor environments. + ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/harbor/deepagents_harbor/deepagents_wrapper.py
Help me add docstrings to my project
import asyncio import base64 import json import logging import shlex from deepagents.backends.protocol import ( EditResult, ExecuteResponse, FileInfo, GlobResult, GrepMatch, GrepResult, LsResult, ReadResult, SandboxBackendProtocol, WriteResult, ) from deepagents.backends.utils ...
--- +++ @@ -1,3 +1,4 @@+"""Harbor sandbox backend for executing commands in Harbor environments.""" import asyncio import base64 @@ -44,8 +45,14 @@ class HarborSandbox(SandboxBackendProtocol): + """A sandbox implementation using shell commands. + + Note: The edit operation requires python3 for JSON parsin...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/harbor/deepagents_harbor/backend.py
Write beginner-friendly docstrings
#!/usr/bin/env python3 import argparse import asyncio import json from dataclasses import dataclass from enum import Enum from pathlib import Path from typing import Optional from deepagents_harbor.failure import ( FailureCategory, classify_failure, extract_exit_codes, ) from deepagents_harbor.stats impor...
--- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3 +"""Analyze job trials from a jobs directory. + +Scans through trial directories, extracts trajectory data and success metrics. +""" import argparse import asyncio @@ -19,6 +23,15 @@ def scan_dataset_for_solutions(dataset_path: Path) -> dict[str, Path]: + """Sca...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/harbor/scripts/analyze.py
Help me add docstrings to my project
from __future__ import annotations import logging import os import platform from dataclasses import asdict, dataclass, field from datetime import UTC, datetime from typing import Any, Protocol, runtime_checkable @runtime_checkable class SandboxLike(Protocol): environment: Any """Harbor environment instance...
--- +++ @@ -1,3 +1,8 @@+"""Infrastructure metadata collection for eval trials. + +Captures host and sandbox environment details (CPU, memory, OS) to enable +post-hoc analysis of infrastructure noise in eval results. +""" from __future__ import annotations @@ -11,6 +16,11 @@ @runtime_checkable class SandboxLike(...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/harbor/deepagents_harbor/metadata.py
Create docstrings for each class method
#!/usr/bin/env python3 import argparse import asyncio import datetime import json import os import tempfile from pathlib import Path import aiohttp import toml from dotenv import load_dotenv from harbor.models.dataset_item import DownloadedDatasetItem from harbor.registry.client import RegistryClientFactory from lang...
--- +++ @@ -1,4 +1,12 @@ #!/usr/bin/env python3 +""" +CLI for LangSmith integration with Harbor. + +Provides commands for: +- Creating LangSmith datasets from Harbor tasks +- Creating experiment sessions +- Adding feedback from Harbor job results to LangSmith traces +""" import argparse import asyncio @@ -31,6 +39,...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/harbor/scripts/harbor_langsmith.py
Auto-generate documentation strings for this file
from __future__ import annotations from collections.abc import Callable from typing import TYPE_CHECKING, Annotated, Any import quickjs from deepagents.middleware._utils import append_to_system_message from langchain.agents.middleware.types import ( AgentMiddleware, AgentState, ContextT, ModelRequest...
--- +++ @@ -1,3 +1,4 @@+"""Middleware for providing a QuickJS-backed repl tool to an agent.""" from __future__ import annotations @@ -51,6 +52,7 @@ class QuickJSMiddleware(AgentMiddleware[AgentState[Any], ContextT, ResponseT]): + """Provide a QuickJS-backed `repl` tool to an agent.""" def __init__( ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/partners/quickjs/langchain_quickjs/middleware.py
Write clean docstrings for readability
from __future__ import annotations import time from collections.abc import Callable from typing import cast from uuid import uuid4 import daytona from daytona import FileDownloadRequest, FileUpload, SessionExecuteRequest from deepagents.backends.protocol import ( ExecuteResponse, FileDownloadResponse, Fi...
--- +++ @@ -1,3 +1,4 @@+"""Daytona sandbox backend implementation.""" from __future__ import annotations @@ -20,6 +21,11 @@ class DaytonaSandbox(BaseSandbox): + """Daytona sandbox implementation conforming to SandboxBackendProtocol. + + This implementation inherits all file operation methods from BaseSan...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/partners/daytona/langchain_daytona/sandbox.py
Write beginner-friendly docstrings
from __future__ import annotations import contextlib import modal from deepagents.backends.protocol import ( ExecuteResponse, FileDownloadResponse, FileUploadResponse, ) from deepagents.backends.sandbox import BaseSandbox class ModalSandbox(BaseSandbox): def __init__(self, *, sandbox: modal.Sandbo...
--- +++ @@ -1,3 +1,4 @@+"""Modal sandbox implementation.""" from __future__ import annotations @@ -13,8 +14,10 @@ class ModalSandbox(BaseSandbox): + """Modal sandbox implementation conforming to SandboxBackendProtocol.""" def __init__(self, *, sandbox: modal.Sandbox) -> None: + """Create a bac...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/partners/modal/langchain_modal/sandbox.py
Add documentation for all methods
from __future__ import annotations import contextlib import inspect from typing import TYPE_CHECKING, Any, get_args, get_origin, get_type_hints from langchain_core.tools import BaseTool if TYPE_CHECKING: from collections.abc import Callable _ELLIPSIS_TUPLE_ARG_COUNT = 2 def _format_basic_annotation(annotatio...
--- +++ @@ -1,3 +1,11 @@+"""Render compact prompt-facing documentation for QuickJS foreign functions. + +QuickJS foreign functions are Python callables or LangChain tools exposed inside +JavaScript. The model needs a concise description of their names, argument +shapes, return types, and any referenced structured types...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/partners/quickjs/langchain_quickjs/_foreign_function_docs.py
Add docstrings that explain inputs and outputs
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from runloop_api_client.sdk import Devbox from deepagents.backends.protocol import ( ExecuteResponse, FileDownloadResponse, FileUploadResponse, ) from deepagents.backends.sandbox import BaseSandbox class RunloopS...
--- +++ @@ -1,3 +1,4 @@+"""Runloop sandbox implementation.""" from __future__ import annotations @@ -15,21 +16,35 @@ class RunloopSandbox(BaseSandbox): + """Sandbox backend that operates on a Runloop devbox.""" def __init__( self, *, devbox: Devbox, ) -> None: + ...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/partners/runloop/langchain_runloop/sandbox.py
Add standardized docstrings across the file
from __future__ import annotations import asyncio import inspect import json import threading from typing import TYPE_CHECKING, Any, Literal from langchain_core.tools import BaseTool from langchain_core.tools.base import ( _is_injected_arg_type, get_all_basemodel_annotations, ) if TYPE_CHECKING: from co...
--- +++ @@ -1,3 +1,11 @@+"""Bridge Python foreign functions into QuickJS with transparent JSON round-tripping. + +The QuickJS Python binding can pass primitive return values directly, but complex +Python values like lists and dicts do not automatically become JavaScript arrays +or objects. This module adds a small brid...
https://raw.githubusercontent.com/langchain-ai/deepagents/HEAD/libs/partners/quickjs/langchain_quickjs/_foreign_functions.py
Add docstrings to my Python code
import urllib from py12306.config import Config from py12306.helpers.api import * from py12306.helpers.request import Request from py12306.log.common_log import CommonLog class Notification(): session = None def __init__(self): self.session = Request() @classmethod def voice_code(cls, phone...
--- +++ @@ -7,6 +7,9 @@ class Notification(): + """ + 通知类 + """ session = None def __init__(self): @@ -56,6 +59,11 @@ self.push_to_bark(content) def send_voice_code_of_yiyuan(self, phone, name='', content=''): + """ + 发送语音验证码 + 购买地址 https://market.aliyun.com/...
https://raw.githubusercontent.com/pjialin/py12306/HEAD/py12306/helpers/notification.py
Write docstrings describing functionality
import asyncio import urllib # from py12306.config import UserType from pyppeteer import launch from py12306.config import Config from py12306.helpers.api import * from py12306.helpers.func import * from py12306.helpers.notification import Notification from py12306.helpers.type import UserType, SeatType from py12306....
--- +++ @@ -31,11 +31,13 @@ super().__init__() def request_init_slide(self, session, html): + """ 处理滑块,拿到 session_id, sig """ OrderLog.add_quick_log('正在识别滑动验证码...').flush() return asyncio.get_event_loop_policy().new_event_loop().run_until_complete( self.__request_ini...
https://raw.githubusercontent.com/pjialin/py12306/HEAD/py12306/order/order.py
Can you add docstrings to this Python file?
from datetime import timedelta from datetime import datetime from py12306.app import app_available_check from py12306.cluster.cluster import Cluster from py12306.config import Config from py12306.helpers.api import LEFT_TICKETS from py12306.helpers.station import Station from py12306.helpers.type import OrderSeatType,...
--- +++ @@ -16,6 +16,9 @@ class Job: + """ + 查询任务 + """ id = 0 is_alive = True job_name = None @@ -108,6 +111,12 @@ self.start() def start(self): + """ + 处理单个任务 + 根据日期循环查询, 展示处理时间 + :param job: + :return: + """ while True and ...
https://raw.githubusercontent.com/pjialin/py12306/HEAD/py12306/query/job.py
Add docstrings to incomplete code
# This file is part of beets. # Copyright 2016, Adrian Sampson. # Copyright 2024, Arav K. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation...
--- +++ @@ -13,6 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""Simple library to work out if a file is hidden on different platforms.""" import ctypes import os @@ -22,6 +23,9 @@ def is_hidden(path: bytes | Path...
https://raw.githubusercontent.com/beetbox/beets/HEAD/beets/util/hidden.py
Add detailed documentation for each class
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
--- +++ @@ -12,6 +12,9 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""Matches existing metadata with canonical information to identify +releases and tracks. +""" from __future__ import annotations @@ -46,6 +49,9 @@ cl...
https://raw.githubusercontent.com/beetbox/beets/HEAD/beets/autotag/match.py
Write proper docstrings for these functions
# This file is part of beets. # Copyright 2025, Sarunas Nejus, Henry Oberholtzer. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rig...
--- +++ @@ -12,6 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""Dataclasses for managing artist credits and tracklists from Discogs.""" from __future__ import annotations @@ -37,8 +38,22 @@ @dataclass class Artis...
https://raw.githubusercontent.com/beetbox/beets/HEAD/beetsplug/discogs/states.py
Write docstrings for backend logic
# This file is part of beets. # Copyright 2016 # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, pu...
--- +++ @@ -12,6 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""Open metadata information in a text editor to let the user edit it.""" import codecs import os @@ -38,9 +39,13 @@ class ParseError(Exception): + ...
https://raw.githubusercontent.com/beetbox/beets/HEAD/beetsplug/edit.py
Generate docstrings with examples
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
--- +++ @@ -12,6 +12,9 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""A wrapper for the GStreamer Python bindings that exposes a simple +music player. +""" import _thread import copy @@ -44,8 +47,27 @@ class GstPlayer:...
https://raw.githubusercontent.com/beetbox/beets/HEAD/beetsplug/bpd/gstplayer.py
Please document this code using docstrings
# This file is part of beets. # Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy,...
--- +++ @@ -12,6 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""Provides the %bucket{} function for path formatting.""" import re import string @@ -28,14 +29,17 @@ def pairwise(iterable): + "s -> (s0,s1), (s1,...
https://raw.githubusercontent.com/beetbox/beets/HEAD/beetsplug/bucket.py
Create simple docstrings for beginners
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
--- +++ @@ -12,6 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""Glue between metadata sources and the matching logic.""" from __future__ import annotations @@ -36,6 +37,7 @@ # Classes used to represent candidate o...
https://raw.githubusercontent.com/beetbox/beets/HEAD/beets/autotag/hooks.py