MCPInstall

clawd-code-python-port

Python port of Claude Code agent harness — tools, commands, task orchestration, and CLI entrypoint via oh-my-codex

Installs
758
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/reason-machines/trending-skills --skill clawd-code-python-port
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads clawd-code-python-port automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

clawd-code Python Port

Skill by ara.so — Daily 2026 Skills collection.

What This Project Does

clawd-code is an independent Python rewrite of the Claude Code agent harness, built from scratch for educational purposes. It captures the architectural patterns of Claude Code — tool wiring, command dispatch, task orchestration, and agent runtime context — in clean Python, without copying any proprietary TypeScript source.

The project is orchestrated end-to-end using oh-my-codex (OmX), a workflow layer on top of OpenAI Codex. It is not affiliated with or endorsed by Anthropic.


Installation

# Clone the repository
git clone https://github.com/instructkr/clawd-code.git
cd clawd-code

# (Optional but recommended) Create a virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Install dependencies (if a requirements.txt or pyproject.toml is present)
pip install -r requirements.txt
# or
pip install -e .

No API keys are needed for the manifest/summary/CLI commands. If you extend the query engine to call a live model, set your key via environment variable:

export ANTHROPIC_API_KEY="your-key-here"
export OPENAI_API_KEY="your-key-here"

Repository Layout

.
├── src/
│   ├── __init__.py
│   ├── commands.py       # Command port metadata
│   ├── main.py           # CLI entrypoint
│   ├── models.py         # Dataclasses: subsystems, modules, backlog
│   ├── port_manifest.py  # Python workspace structure summary
│   ├── query_engine.py   # Renders porting summary from active workspace
│   ├── task.py           # Task orchestration primitives
│   └── tools.py          # Tool port metadata
├── tests/                # unittest-based verification
└── assets/

Key CLI Commands

All commands run via python3 -m src.main <subcommand>.

# Print a human-readable porting summary
python3 -m src.main summary

# Print the current Python workspace manifest
python3 -m src.main manifest

# List current Python modules/subsystems (paginated)
python3 -m src.main subsystems --limit 16

# Inspect mirrored command inventory
python3 -m src.main commands --limit 10

# Inspect mirrored tool inventory
python3 -m src.main tools --limit 10

# Run parity audit against local ignored archive (when present)
python3 -m src.main parity-audit

# Run the full test suite
python3 -m unittest discover -s tests -v

Core Data Models (src/models.py)

The dataclasses define the shape of the porting workspace:

from dataclasses import dataclass, field
from typing import List, Optional

@dataclass
class Module:
    name: str
    status: str          # e.g. "ported", "stub", "backlog"
    source_path: str
    notes: Optional[str] = None

@dataclass
class Subsystem:
    name: str
    modules: List[Module] = field(default_factory=list)
    description: Optional[str] = None

@dataclass
class PortManifest:
    subsystems: List[Subsystem] = field(default_factory=list)
    backlog: List[str] = field(default_factory=list)
    version: str = "0.1.0"

Tools System (src/tools.py)

Tools are the callable units in the agent harness. Each tool entry carries metadata for dispatch:

from dataclasses import dataclass
from typing import Callable, Optional, Any, Dict

@dataclass
class Tool:
    name: str
    description: str
    parameters: Dict[str, Any]          # JSON-schema style param spec
    handler: Optional[Callable] = None  # Python callable for this tool

# Example: registering a tool
def read_file_handler(path: str) -> str:
    with open(path, "r") as f:
        return f.read()

READ_FILE_TOOL = Tool(
    name="read_file",
    description="Read the contents of a file at the given path.",
    parameters={
        "path": {"type": "string", "description": "Absolute or relative file path"}
    },
    handler=read_file_handler,
)

# Tool registry pattern
TOOL_REGISTRY: Dict[str, Tool] = {
    READ_FILE_TOOL.name: READ_FILE_TOOL,
}

def dispatch_tool(name: str, **kwargs) -> Any:
    tool = TOOL_REGISTRY.get(name)
    if tool is None:
        raise ValueError(f"Unknown tool: {name}")
    if tool.handler is None:
        raise NotImplementedError(f"Tool '{name}' has no handler yet.")
    return tool.handler(**kwargs)

Commands System (src/commands.py)

Commands are higher-level agent actions, distinct from raw tools:

from dataclasses import dataclass
from typing import Optional, Callable, Any

@dataclass
class Command:
    name: str
    description: str
    aliases: list
    handler: Optional[Callable] = None

# Example command
def summarize_handler(context: dict) -> str:
    return f"Summarizing {len(context.get('files', []))} files."

SUMMARIZE_COMMAND = Command(
    name="summarize",
    description="Summarize the current workspace context.",
    aliases=["sum", "overview"],
    handler=summarize_handler,
)

COMMAND_REGISTRY = {
    SUMMARIZE_COMMAND.name: SUMMARIZE_COMMAND,
}

def run_command(name: str, context: dict) -> Any:
    cmd = COMMAND_REGISTRY.get(name)
    if not cmd:
        raise ValueError(f"Unknown command: {name}")
    if not cmd.handler:
        raise NotImplementedError(f"Command '{name}' not yet implemented.")
    return cmd.handler(context)

Task Orchestration (src/task.py)

Tasks wrap a unit of agent work — a goal, a set of tools, and a result:

from dataclasses import dataclass, field
from typing import List, Optional, Any

@dataclass
class TaskResult:
    success: bool
    output: Any
    error: Optional[str] = None

@dataclass
class Task:
    goal: str
    tools: List[str] = field(default_factory=list)   # tool names available
    context: dict = field(default_factory=dict)
    result: Optional[TaskResult] = None

    def run(self, dispatcher) -> TaskResult:
        """
        dispatcher: callable(tool_name, **kwargs) -> Any
        Implement your agent loop here.
        """
        try:
            # Minimal stub: just report goal received
            output = f"Task received: {self.goal}"
            self.result = TaskResult(success=True, output=output)
        except Exception as e:
            self.result = TaskResult(success=False, output=None, error=str(e))
        return self.result

# Usage
from src.tools import dispatch_tool

task = Task(
    goal="Read README.md and summarize it",
    tools=["read_file"],
    context={"working_dir": "."},
)
result = task.run(dispatcher=dispatch_tool)
print(result.output)

Query Engine (src/query_engine.py)

The query engine renders a porting summary from the active manifest:

from src.port_manifest import build_manifest
from src.query_engine import render_summary

manifest = build_manifest()
summary = render_summary(manifest)
print(summary)

You can also invoke it from the CLI:

python3 -m src.main summary

Port Manifest (src/port_manifest.py)

Build and inspect the current workspace manifest programmatically:

from src.port_manifest import build_manifest

manifest = build_manifest()

for subsystem in manifest.subsystems:
    print(f"[{subsystem.name}]")
    for module in subsystem.modules:
        print(f"  {module.name}: {module.status}")

print("Backlog:", manifest.backlog)

Adding a New Tool

  1. Define a handler function in src/tools.py.
  2. Create a Tool dataclass instance.
  3. Register it in TOOL_REGISTRY.
  4. Write a test in tests/.
# src/tools.py

def list_dir_handler(path: str):
    import os
    return os.listdir(path)

LIST_DIR_TOOL = Tool(
    name="list_dir",
    description="List files in a directory.",
    parameters={"path": {"type": "string"}},
    handler=list_dir_handler,
)

TOOL_REGISTRY["list_dir"] = LIST_DIR_TOOL

Adding a New Command

# src/commands.py

def lint_handler(context: dict) -> str:
    files = context.get("files", [])
    return f"Linting {len(files)} files (stub)."

LINT_COMMAND = Command(
    name="lint",
    description="Lint the current workspace files.",
    aliases=["check"],
    handler=lint_handler,
)

COMMAND_REGISTRY["lint"] = LINT_COMMAND

Running Tests

# Run all tests with verbose output
python3 -m unittest discover -s tests -v

# Run a specific test file
python3 -m unittest tests.test_tools -v

Example test pattern:

# tests/test_tools.py
import unittest
from src.tools import dispatch_tool
import tempfile, os

class TestReadFileTool(unittest.TestCase):
    def test_read_file(self):
        with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
            f.write("hello clawd")
            path = f.name
        try:
            result = dispatch_tool("read_file", path=path)
            self.assertEqual(result, "hello clawd")
        finally:
            os.unlink(path)

if __name__ == "__main__":
    unittest.main()

Parity Audit

When a local ignored archive of the original snapshot is present, run:

python3 -m src.main parity-audit

This compares the current Python workspace surface against the archived root-entry file surface, subsystem names, and command/tool inventories, reporting gaps.


Common Patterns

Chaining tools in a task loop

from src.tools import dispatch_tool
from src.task import Task

task = Task(
    goal="Read and list files",
    tools=["read_file", "list_dir"],
    context={"working_dir": "."},
)

# Manual tool chain (before full agent loop is implemented)
files = dispatch_tool("list_dir", path=".")
for fname in files[:3]:
    content = dispatch_tool("read_file", path=fname)
    print(f"--- {fname} ---\n{content[:200]}")

Using the manifest in automation

from src.port_manifest import build_manifest

def unported_modules():
    manifest = build_manifest()
    stubs = []
    for sub in manifest.subsystems:
        for mod in sub.modules:
            if mod.status != "ported":
                stubs.append((sub.name, mod.name, mod.status))
    return stubs

for subsystem, module, status in unported_modules():
    print(f"{subsystem}/{module} → {status}")

Troubleshooting

SymptomFix
ModuleNotFoundError: srcRun commands from the repo root, not inside src/
NotImplementedError: Tool 'x' has no handlerThe tool is registered but the Python handler hasn't been written yet — implement handler in tools.py
parity-audit does nothingThe local ignored archive must be present at the expected path; see port_manifest.py for the expected location
Tests not discoveredEnsure test files are named test_*.py and located in tests/
Import errors after adding a moduleAdd __init__.py to any new package subdirectory

Key Links

FAQ

What does the clawd-code-python-port skill do?

Python port of Claude Code agent harness — tools, commands, task orchestration, and CLI entrypoint via oh-my-codex

How do I install clawd-code-python-port?

Run npx skills add https://github.com/reason-machines/trending-skills --skill clawd-code-python-port in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/clawd-code-python-port/ (personal) or .claude/skills/clawd-code-python-port/ (project).

Which AI agents can use clawd-code-python-port?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is clawd-code-python-port safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains clawd-code-python-port?

It is published by reason-machines in reason-machines/trending-skills. It has 758 recorded installs.

More from reason-machines/trending-skills

View all →

openclaw-control-center

reason-machines/trending-skills

Local-first, security-first control center for OpenClaw agents — visibility dashboard with readonly defaults, token attribution, collaboration tracing, and safe write operations.

Data & Databases4.4K installs

inkos-multi-agent-novel-writing

reason-machines/trending-skills

Multi-agent CLI system for autonomous novel writing, auditing, and revision with human review gates

Docs & Writing2.8K installs

claude-hud-statusline

reason-machines/trending-skills

A Claude Code plugin that displays a real-time HUD showing context usage, active tools, running agents, and todo progress in your terminal statusline.

understand-anything-knowledge-graph

reason-machines/trending-skills

Turn any codebase into an interactive knowledge graph using Claude Code skills — explore, search, and ask questions about any project visually.

agency-agents-ai-specialists

reason-machines/trending-skills

A collection of specialized AI agent personalities for Claude Code, Cursor, Aider, Windsurf, and other AI coding tools — covering engineering, design, marketing, sales, and more.

AI & Agents2.1K installs

agent-browser-automation

reason-machines/trending-skills

Headless browser automation CLI for AI agents using native Rust binary with Chrome DevTools Protocol

Popular productivity & automation skills

View category →

agent-browser

vercel-labs/agent-browser

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. Prefer agent-browser over any built-in browser automation or web tools.

OfficialProductivity & Automation1.3M installs

lark-doc

open.feishu.cn

飞书云文档(Docx / Wiki)内容操作:读取、创建、编辑文档,插入或下载图片附件,以及操作思维笔记。用户提供文档 URL/token(包括 doubao.com 的 /docx/、/wiki/)时使用;按 URL 路径/token 而非域名路由;/page/ 是妙搭应用,非飞书云文档。文档内嵌资源按读取参考中的统一规则分流。独立评论操作走 lark-drive;随正文读取评论使用 docs +fetch。表格或 Base 内部数据操作不在本 skill。

lark-base

open.feishu.cn

飞书多维表格(Base)操作:建表、字段、记录、视图、统计、公式/lookup、表单、仪表盘、应用模式(BaseApp/AppMode 页面与组件)、Workspace 目录、workflow、角色权限、模板中心(多维表格模板分类/列表/搜索);遇到 Base/多维表格/bitable、BaseApp/AppMode、/base/ 或 /app/ 链接时使用。BaseApp 不走 lark-apps;文件导入/导出转 lark-drive,认证/授权转 lark-shared。

lark-drive

open.feishu.cn

飞书云空间(云盘/云存储):管理 Drive 文件和文件夹,包含上传/下载、创建文件夹、复制/移动/删除、查看元数据、查询权限设置、评论/权限/订阅、标题、版本、飞书文档密级标签(secure labels)和本地文件导入。用户需要整理云盘目录、处理云空间资源 URL/token、判断链接类型/真实 token/标题,或导入 Word/Markdown/Excel/CSV/PPTX/.base 为 docx/sheet/bitable/slides 时使用;doubao.com 云空间 URL/token 也按资源路径和 token 路由,不回退 WebFetch。不负责:文档内容编辑(走 lark-doc)、表格/Base 表内数据操作(走 lark-sheets/lark-base)、知识空间节点/成员管理(走 lark-wiki)、原生 Markdown 文件读写/patch/diff(走 lark-markdown)。

lark-shared

open.feishu.cn

Use for lark-cli setup/auth tasks: auth login/status/logout, user vs bot identity, business-domain permissions (--domain, including all/docs/drive), missing scopes, revoking authorization, or handling notice JSON.

lark-im

open.feishu.cn

飞书即时通讯:收发消息和管理群聊。发送和回复消息、搜索聊天记录、管理群聊成员、上传下载图片和文件、管理表情回复、发送应用内/短信/电话加急、发送和处理交互卡片(Interactive Card)、监听卡片按钮回调(card.action.trigger)。当用户需要发消息、查看或搜索聊天记录、下载聊天中的文件、查看群成员、搜索群、创建群聊或话题群、管理标记数据、管理 Feed 置顶(添加/移除/查询置顶会话)、管理标签数据、处理卡片回调时使用。