Sandbox
@ivan-magda/swift-coding-agent

Swift Claude Code-style agent learning project

This repository rebuilds a Claude Code-style coding agent in Swift so you can see which parts of the architecture matter. It keeps the loop small, then adds tools, subagents, skill loading, context compaction, task state, and background tasks in stages.

178 stars11 forksSwiftUpdated 2mo ago
Who it's for

Builders who want to understand coding-agent design by working through a staged Swift implementation.

What it delivers

You can study and extend a small agent loop instead of treating coding agents as a black box.

What it does

Fixed agent loop

Implements the core request-response-tool-use loop against Anthropic's Messages API.

Small tool surface

Starts with a few focused tools like shell execution, file read/write, and file edits.

Subagents

Adds recursive agent runs with fresh context for delegated work.

Skill loading

Loads `.md` skill files and injects them into the agent flow.

Context compaction

Uses micro, auto, and manual compaction strategies to manage long runs.

Task system

Stores tasks as files and tracks dependencies with a DAG.

Background tasks

Runs long-lived work with `Task {}` and an actor-based notification queue.

README

swift-coding-agent

Exploring the architecture of coding agents by rebuilding a Claude Code-style CLI from scratch in Swift.

demo

Learning Series

A 9-part learning series covers the build on ivanmagda.dev.

Start the series →

Why This Exists

Claude Code works better than most coding agents I've used, and I think the reason is restraint. I studied its tool surface and traced its loop to isolate which design choices do the work.

My working theory: coding agents benefit more from a small set of excellent tools and a tight loop than from large orchestration layers.

Claude Code ships few tools, and the ones it has are simple: a search tool, a file editor. They work well. The system trusts the model and skips the scaffolding most agents pile on.

This project rebuilds those mechanics in Swift, one stage at a time, to find out how little architecture the job needs.

Hypothesis

This project tests a few specific ideas about coding agents:

  • A small number of high-quality tools beats a large tool catalog
  • The model should do the heavy lifting; orchestration stays thin
  • Explicit task state improves reliability more than prompt-only planning
  • Controlled context injection matters more than persistent memory
  • Context compaction is a product feature, not a token optimization

Each stage isolates one mechanism so I can see what it enables.

The Agent Loop

The whole thing boils down to one loop:

func run(query: String) async throws -> String {
    messages.append(.user(query))

    while true {
        let request = APIRequest(
            model: model, system: systemPrompt, messages: messages, tools: Self.toolDefinitions
        )
        let response = try await apiClient.createMessage(request)
        messages.append(Message(role: .assistant, content: response.content))

        guard response.stopReason == .toolUse else {
            return response.content.textContent
        }

        var results: [ContentBlock] = []
        for block in response.content {
            if case .toolUse(let id, let name, let input) = block {
                let output = await executeTool(name: name, input: input)
                results.append(.toolResult(toolUseId: id, content: output, isError: false))
            }
        }
        messages.append(Message(role: .user, content: results))
    }
}

The loop is fixed; the tools vary. Every stage adds entries to the tool handler dictionary and injection points before the API call, but the loop body itself stays identical.

Roadmap

Git tags track progress. The roadmap has two phases: core mechanics first, then product-level features.

Phase 1: Core Loop

The minimum viable agent: a loop and a small set of good tools.

StageWhat It AddsTag
00Bootstrap: SPM project, two-target layout, CI00-bootstrap
01Agent loop + bash tool01-agent-loop
02Tool dispatch: read_file, write_file, edit_file with path safety02-tool-dispatch
03Todo tracking with nag reminder injection03-todo-write

Phase 2: Product Mechanics

The features that make an agent feel like a usable product: context, memory management, and persistence.

StageWhat It AddsTag
04Subagents: recursive loop with fresh context04-subagents
05Skill loading: .md files injected as tool results05-skill-loading
06Context compaction: 3-layer strategy (micro, auto, manual)06-context-compaction
07Task system: file-based CRUD with dependency DAG07-task-system
08Background tasks: Task {} + actor-based notification queue08-background-tasks

Architecture

Two-target Swift Package Manager project:

Core is the library: API client, shell executor, agent loop, tools.

CLI is the entry point. The executable is named agent.

The agent talks to POST https://api.anthropic.com/v1/messages over raw HTTP, built on AsyncHTTPClient. It runs on macOS and Linux.

Non-Goals

This project is not:

  • A full Claude Code clone or drop-in replacement
  • A general-purpose multi-agent framework
  • Production-ready IDE tooling

It's a staged exploration of coding-agent architecture. The gaps are deliberate.

Tech Stack

  • Swift 6.2 with strict concurrency
  • AsyncHTTPClient (SwiftNIO-based) for cross-platform HTTP + streaming SSE
  • Foundation Process for shell command execution
  • macOS 10.15+ / Linux

Getting Started

git clone https://github.com/ivan-magda/swift-coding-agent.git
cd swift-coding-agent

# Set up your API key and model
cp .env.example .env
# Edit .env with your ANTHROPIC_API_KEY and MODEL_ID

swift build
swift run agent

References

License

MIT

Files in the repo

Repository payload14 top-level entries
  • .github
  • docs
  • skills
  • Sources
  • Tests
  • .env.example
  • .gitignore
  • .swift-format
  • .swiftlint.yml
  • demo.gif
  • LICENSE
  • Package.resolved
  • Package.swift
  • README.md

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More tutorials & guides

shareAI-lab/
learn-claude-code

Bash is all you need - A nano claude code–like 「agent harness」, built from 0 to 1

77k
luongnv89/
claude-howto
luongnv89/claude-howtoTutorials & Guides

A visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value.

41k
agentskills/
agentskills
agentskills/agentskillsTutorials & Guides

Specification and documentation for Agent Skills

25k