mimran-khan/claude-code-source: The loop that turns Claude Code into a coding agent

A deep dive into the agentic core, from context compaction and tool permissions to the transport and telemetry layer that keeps a terminal assistant coherent across long tasks.

14 min read • View on GitHub • More from mimran-khan

A terminal control room with a central loop feeding input through model, tools, and summary buffers. It explains that Claude Code behaves like a persistent control system rather than a single prompt and response exchange.
Claude Code is easier to understand as a managed loop than as a chat box with terminal access.

Anthropic accidentally shipped a source map in their npm package, exposing 512,000+ lines of TypeScript. This is the most advanced AI coding assistant ever built — and now we can see exactly how it works.

Mohammed Imran Khan, Creator · Claude Code source article
Key Takeaways

The real product is the loop

The most revealing thing in mimran-khan/claude-code-source is not that Claude Code exists. It is that Claude Code behaves like a managed process, not a one-shot assistant. It streams model output, dispatches tools, folds the results back into state, and then starts the next turn with a slimmer but still usable memory of what just happened.

That changes the mental model. A normal terminal helper answers questions. A looped agent has to survive drift, failures, partial tool results, and long sessions without losing the thread. The repository shows the engineering required to make that possible.

How Claude Code keeps its thread

The loop is the product. Everything else exists to keep the loop coherent.

At the center is `QueryEngine.ts`, which coordinates the turn cycle. The engine pulls in app state, messages, and tools, then decides whether to continue, compact, or hand work off to a tool call. The important move is not generation. It is bookkeeping.

while (session.isActive) {
  const turn = await queryLoop(appState, messages, tools)

  if (turn.needsCompaction) {
    appState = compactHistory(appState, turn.summary)
  }

  const results = await runToolCalls(turn.toolCalls, permissions)
  appState = commitTurn(appState, turn, results)
}

That sketch is simplified, but it matches the architecture. The source points to compaction helpers such as `snipCompact.js` and `snipProjection.js`, which suggests the system does not merely truncate history when the context window fills up. It compresses the past into a smaller working summary and keeps the thread alive.

A dense stack of note cards is compressed into a thinner bundle while a thread continues through the new summary. It visualizes how long sessions stay coherent when history is compacted instead of simply truncated.
Compaction is not deletion. It is repacking the conversation so the next turn still knows where it left off.

Tools are not features, they are side effects

Once the loop is clear, the tool system reads differently. `Tool.ts` does not just list capabilities. It exposes a permission model with explicit buckets such as `alwaysAllow`, `alwaysAsk`, and `alwaysDeny`. That is a control plane, not a feature list.

The same logic shows up in task handling. The source distinguishes between local shell work, remote execution, and a background planning mode. In other words, Claude Code is not blindly allowed to act. It is constantly deciding what kind of action is safe, what kind is visible, and what kind should be blocked.

A gatehouse with three lanes that routes tool requests into separate allow, ask, and deny paths. A tool-shaped hand reaches toward the gate while a ledger records every decision, showing that agent actions are governed by explicit permissions.
Tool use becomes a security problem the moment an assistant can edit files or run commands.

This is why Claude Code feels more serious than a wrapper around an LLM. It is designed to keep side effects legible. Tool calls are not just outputs. They are auditable state changes.

The hidden infrastructure under the CLI

The plumbing is broader than the terminal surface suggests. The repository points to Bun and strict TypeScript, plus transport layers for WebSockets, SSE, and hybrid streaming. That matters because a coding agent is only as good as its ability to keep talking when terminals reconnect, sessions drift, or the network gets flaky.

The state layer is equally revealing. The source tracks things like `totalCostUSD`, `modelUsage`, and `turnToolCount`, and it uses attributed counters for telemetry. That tells you the system is instrumented as a managed service, not just a local CLI. Reliability is measured, not assumed.

There is also a quiet security signal in the implementation details. The task ID generator uses a 36-character alphabet to reduce symlink risk. That kind of choice says the system was built by people who expected hostile edges, not just happy-path demos.

Why the source map mattered

The reason this repository became such a useful artifact is simple. The source map exposed a production-grade agentic system that was built to hide its own machinery. Once the source was visible, the real story was no longer the leak itself. It was the design philosophy underneath it.

A hedcut portrait of Mohammed Imran Khan based on his verified GitHub avatar. The image identifies the creator of the analysis and grounds the attribution in a real public reference.

That sentence is a bit breathless, but the underlying point holds. The repository is valuable because it turns a black box into a case study. You can see how a modern agent preserves context, gates actions, and tracks cost while it works.

What Claude Code is compared with other agents

ProjectSurfaceAutonomyContext handlingStrengthWhy it differs from Claude Code
Claude CodeTerminal and CLILoop-first and supervisedCompaction plus session stateDeep, persistent task executionIt treats control flow as the product
AiderGit-centric CLIHuman-ledConversation plus repo contextPrecise file editingIt optimizes for editing, not orchestration
ContinueIDE extensionIDE-assistedEditor context and retrievalInline coding inside the IDEIt lives in the editor, not the terminal loop
Open InterpreterLocal runtimeHigh autonomySession memory around executionRuns code and automates tasksIt is runtime-first, not coding workflow first
MentatTerminal assistantGuided agentTask-oriented contextCommand-line collaborationIt is closer to a helper than a full control loop

The comparison that matters is not model access. It is control flow. Claude Code, as revealed here, is built around repeated turns, explicit gates, and recovery from partial progress. That is a different philosophy from tools that center the editor, the runtime, or the single edit operation.

What builders should steal from this design