clawd-code-python-port
Python port of Claude Code agent harness — tools, commands, task orchestration, and CLI entrypoint via oh-my-codex
What this skill does
# clawd-code Python Port
> Skill by [ara.so](https://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)](https://github.com/Yeachan-Heo/oh-my-codex), a workflow layer on top of OpenAI Codex. It is **not affiliated with or endorsed by Anthropic**.
---
## Installation
```bash
# 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:
```bash
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>`.
```bash
# 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:
```python
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:
```python
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:
```python
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:
```python
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:
```python
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:
```bash
python3 -m src.main summary
```
---
## Port Manifest (`src/port_manifest.py`)
Build and inspect the current workspace manifest programmatically:
```python
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/`.
```python
# 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
```python
# src/commands.py
def lint_handler(context: dict) -> str:
files = context.get("files", [])
return f"Linting {len(files)} fiRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.