Skip to main content
A harness runtime is the coordination layer that sits between a user prompt and the underlying AI model. It wires together tool inventories, orchestrates multi-turn execution, manages runtime context, and persists session state. Claw Code implements this layer in Python, mirroring the architecture of Claude Code’s original TypeScript harness.

Components overview

CLI entrypoint

main.py — parses arguments, selects a subcommand, and hands off to the appropriate runtime path.

PortRuntime

runtime.py — routes prompts against the command/tool inventory, builds sessions, runs turn loops, and infers permission denials.

QueryEnginePort

query_engine.py — the stateful orchestration layer. Holds session ID, conversation messages, usage tracking, and the transcript store.

Commands inventory

commands.py — loads PORTED_COMMANDS from a JSON snapshot; exposes lookup, filtering, and execution shims.

Tools inventory

tools.py — loads PORTED_TOOLS from a JSON snapshot; supports simple mode, MCP filtering, and permission-context filtering.

Session store

session_store.py — serialises StoredSession objects to .port_sessions/<id>.json and reloads them on demand.

TranscriptStore

transcript.py — an in-memory ordered log of conversation entries that supports compaction and flush.

PortContext

context.py — captures workspace paths (source, tests, assets, archive) and file counts at bootstrap time.

Module structure

src/
├── main.py               # CLI entrypoint
├── runtime.py            # PortRuntime — routing and session bootstrap
├── query_engine.py       # QueryEnginePort — turn-loop orchestration
├── commands.py           # PORTED_COMMANDS inventory
├── tools.py              # PORTED_TOOLS inventory
├── permissions.py        # ToolPermissionContext
├── models.py             # Shared dataclasses (PermissionDenial, UsageSummary, …)
├── session_store.py      # StoredSession persistence
├── transcript.py         # TranscriptStore
├── history.py            # HistoryLog for session events
├── context.py            # PortContext workspace snapshot
├── port_manifest.py      # PortManifest — workspace file inventory
├── bootstrap_graph.py    # BootstrapGraph — ordered startup stages
├── command_graph.py      # CommandGraph — built-in / plugin / skill segmentation
├── tool_pool.py          # ToolPool — assembled filtered tool set
├── execution_registry.py # Dispatch registry for command and tool shims
└── reference_data/
    ├── commands_snapshot.json
    └── tools_snapshot.json

Request/response cycle

1

CLI dispatch

main() in main.py parses the subcommand (bootstrap, turn-loop, route, etc.) and instantiates PortRuntime.
2

Context and workspace bootstrap

PortRuntime.bootstrap_session() calls build_port_context() to snapshot workspace paths and run_setup() to gather platform details. A HistoryLog is created to record events through the lifecycle.
3

Prompt routing

PortRuntime.route_prompt() tokenises the prompt and scores every entry in PORTED_COMMANDS and PORTED_TOOLS against the name, source_hint, and responsibility fields. The top-scoring command and tool are selected first, then remaining slots are filled by score.
4

Permission inference

_infer_permission_denials() inspects the matched tools and gates any whose name contains bash, appending a PermissionDenial with the reason "destructive shell execution remains gated in the Python port".
5

Streaming and turn submission

QueryEnginePort.stream_submit_message() emits structured SSE-style events (message_start, command_match, tool_match, permission_denial, message_delta, message_stop) before calling submit_message() to produce a TurnResult.
6

Session persistence

engine.persist_session() flushes the TranscriptStore and writes a StoredSession JSON file under .port_sessions/. The path is stored on the RuntimeSession for inspection.

Bootstrap graph

The BootstrapGraph in bootstrap_graph.py documents the ordered startup stages that mirror the original TypeScript harness:
stages = (
    "top-level prefetch side effects",
    "warning handler and environment guards",
    "CLI parser and pre-action trust gate",
    "setup() + commands/agents parallel load",
    "deferred init after trust",
    "mode routing: local / remote / ssh / teleport / direct-connect / deep-link",
    "query engine submit loop",
)
Inspect the graph at any time with:
python3 -m src.main bootstrap-graph

Command graph

CommandGraph (in command_graph.py) segments the full command inventory into three buckets:
BucketSource hint criterion
builtinsNo plugin or skills in source_hint
plugin_likeplugin appears in source_hint
skill_likeskills appears in source_hint
python3 -m src.main command-graph

Python port vs. TypeScript original

The Python port is a structural mirror, not a line-for-line translation. It preserves the same component boundaries and data shapes while using idiomatic Python constructs (dataclasses, lru_cache, argparse) in place of TypeScript classes and Zod schemas.
Key correspondences:
TypeScript conceptPython equivalent
QueryEngine classQueryEnginePort dataclass
Tool registry objectPORTED_TOOLS tuple + ToolPool
Command registryPORTED_COMMANDS tuple + CommandGraph
Session storageStoredSession + save_session() / load_session()
Stream eventsstream_submit_message() generator
Permission callbacksToolPermissionContext.blocks()

Build docs developers (and LLMs) love