Lesson 1: What Is a Harness? — The AI Agent Landscape
Why This Matters
In 2025–2026, the AI coding agent space exploded. You can point the same model — say, DeepSeek V4 or Claude — at a codebase, and the harness that wraps it determines whether it succeeds or fails. One benchmark study found the same model scoring 16 points higher in a different harness on SWE-bench. The harness is not just plumbing — it is the agent's operating system.
This lesson defines what a harness is, surveys the landscape, and builds the vocabulary you need for the rest of the tutorial.
What Is an Agent Harness?
An agent harness is the runtime that turns a raw LLM into a capable coding agent. It provides:
| Concern | What the harness does |
|---|---|
| Agent Loop | Drives the cycle: receive input → assemble prompt → call model → execute tools → repeat. |
| Tool System | Registers, validates, and executes tools (file I/O, shell, search, web fetch). |
| Sandbox | Confines the model's actions so it cannot rm -rf / your machine. |
| Session Model | Tracks conversation history, tool results, and state across turns. |
| Subagent Delegation | Spawns child agents for isolated subtasks. |
| Context Management | Compacts or prunes history when the context window fills. |
| UI Surfaces | Presents the conversation — terminal, web, IDE, or headless API. |
| Extensibility | Lets you add tools, models, and policies without forking the core. |
A harness is not an SDK. An SDK gives you a client library to call an LLM API. A harness gives you the entire runtime: the loop, the tools, the sandbox, the UI. You can build an SDK into a harness, but the harness is the bigger thing.
Pi Agent's perspective: The Pi team explicitly describes Pi as "not another agent SDK." It is a harness — a runtime that owns the full agent lifecycle. DSH takes the same stance but goes further: in DSH, even the agent loop itself is a plugin.
The Coding Agent Landscape (2025–2026)
Here are the major open-source harnesses:
| Harness | Language | Plugin Model | UI Surfaces | Session Model | Notable Trait |
|---|---|---|---|---|---|
| DSH (DeepSeek) | TypeScript | Cordis (everything is a plugin) | Web, TUI, headless | Event-sourced log | Plugin composition via profiles/bundles |
| Pi Agent | Python | pip packages + extension points | TUI, CLI | Stateful | Minimal, Pythonic, "not an SDK" |
| Claude Code | TypeScript | Hooks + config | TUI, IDE | Internal | Tight Anthropic integration, polished |
| Codex CLI (OpenAI) | TypeScript | Unknown | TUI, CLI | Internal | OpenAI-native, sandbox-first |
| OpenHands | Python | Plugin system | Web | Stateful | Web-first, Docker sandbox |
Key Differentiators
DSH is unique in its commitment to plugin architecture. Every part of the product — the model adapter, the tool registry, the session log, and the agent loop itself — is a Cordis plugin. There is no privileged core to patch. You extend DSH by mounting a plugin beside the others, and registrations are effects that unwind when their plugin unloads.
Pi Agent takes a more traditional Python approach: it has a clear agent loop, a tool registry, and subagent support, but the architecture is monolithic relative to DSH. Pi's plugin system is based on pip-installable packages that register through extension points — powerful, but less granular than DSH's per-service plugin model.
Claude Code is the most polished end-user experience. Its architecture is less documented publicly, but source analysis reveals a sophisticated subagent system, hook-based extensibility, and tight context-window management. It's the fastest harness on some benchmarks but also the most expensive.
The Shared Architecture: What Every Harness Has
Despite their differences, all harnesses share a common skeleton:
flowchart TD
User["User Input"] --> Inbox["Message Inbox"]
Inbox --> Loop["Agent Loop"]
Loop --> Prompt["Prompt Assembly"]
Prompt --> LLM["LLM Call"]
LLM --> Parse["Parse Response"]
Parse -->|"text"| Reply["Stream Reply"]
Parse -->|"tool_call"| Tools["Tool Pipeline"]
Tools -->|"result"| Prompt
Reply --> User
-
Agent Loop: The infinite (or bounded) cycle of claim → prompt → call → execute → repeat. In DSH this is
ctx.agentLoop; in Pi Agent it'sagent.py; in Claude Code it's the internal turn driver. -
Tool System: A registry of named capabilities the model can invoke. Every harness has read/write/edit/search/execute tools. DSH adds a guarded pipeline with pre-execute approval, post-execute rewriting, and scoped per-agent visibility.
-
Sandbox: Filesystem and process confinement. DSH uses Landlock on Linux and a Windows sandbox policy; Claude Code and Pi Agent use similar OS-level confinement.
-
Subagents: Child agents for isolated work. DSH has in-process subagents (share the same runtime) and forked subagents (fresh context). Claude Code has a similar child-runtime model. Pi Agent supports subagent delegation through its router.
-
Context Management: When the conversation grows too long, the harness must compact or prune. DSH has a compaction subsystem with multiple strategies.
DSH's Core Vocabulary
Before we dive into DSH's architecture in Lesson 2, here are the terms you will encounter everywhere. (They are defined formally in the DSH Glossary.)
| Term | Definition |
|---|---|
| Turn | One drain of admitted input, ending after the model and its tools stop. A turn contains zero or more steps. |
| Step | One model request plus the tool executions caused by its response. |
| Round | An outer policy iteration containing a turn (e.g., a goal round). |
| Session | The append-only event log — the single source of truth. |
| Plugin | A Cordis object that contributes services, events, and effects to a context. |
Context (ctx) |
A repository of services. ctx.tools, ctx.llm, ctx.sessions, etc. |
| Seam | A swappable capability with three roles: Service Definition, Provider, Consumer. |
| Scope | Per-agent registration: a tool registered in an agent's scope is visible only to that agent. |
| Profile | A named composition of bundles stored in the Harness home. |
| Bundle | A distribution format for Cordis config rows and the code they mount. |
Hands-On Experiment: Survey the Landscape
Before installing DSH, spend 15 minutes surveying the competition:
-
Read the UBC comparison: Coding Agents: Harness Architecture Comparison — this is the best single overview of the harness design space.
-
Skim the Pi Agent README: github.com/earendil-works/pi — note how it describes its architecture vs. what you see in DSH's docs.
-
Read "The Harness Effect": Same Model, Different Tool, Different Score — this will convince you the harness matters.
-
Open the DSH Architecture doc: architecture.md — just read the first three sections. We will cover the rest in Lesson 2.
Question to answer: What is the one architectural decision in DSH that you think would be hardest to replicate in Pi Agent's Python codebase? Keep this in mind as we go through the next lessons.
Compare With…
Pi Agent: Pi describes itself as "not an SDK." It has a clear agent loop (
agent.py), tool registry, TUI, and subagent support. Its plugin system is extension-point-based: you install a pip package and it registers tools, models, or hooks. DSH's Cordis plugin model is more granular — every service is a plugin, and plugins compose through profiles and bundles rather than a flat extension registry.Claude Code: Claude Code is the most polished end-user product. Its architecture is less documented, but its hook system lets you intercept tool calls and model requests — similar to DSH's waterfall events. Claude Code's subagent model is a child-runtime pattern (each subagent is a separate process), while DSH offers both in-process and forked subagents.
Next: Lesson 2 — DSH Architecture: "Everything Is a Plugin"
In Lesson 2, we install DSH, explore its plugin composition model, and learn how Cordis makes "everything is a plugin" a practical reality rather than a slogan.
Lesson 2: DSH Architecture — "Everything Is a Plugin"
The Big Idea
DSH's architecture rests on one radical claim: every part of the product is a plugin. The model adapter, the tool registry, the session log, the agent loop, the sandbox, the UI — every single one is a Cordis plugin. There is no privileged core to patch.
This is not just a slogan. It means:
- You can swap the LLM provider without touching the loop.
- You can add a tool without forking the harness.
- You can replace the filesystem backend (local → remote sandbox) and the shell, PTY, and LSP move with it.
- You can intercept any tool call, model request, or turn boundary with a plugin listener.
This lesson explains how that works, starting with the Cordis framework and building up to profiles and bundles.
Cordis in Five Ideas
Cordis is the vendored plugin framework underneath DSH. It is small — five ideas:
1. A Plugin Is an Object That Implements Service
A plugin can be a function with optional inject and apply(ctx) fields, or a Service subclass. When mounted, Cordis calls its lifecycle methods to integrate it into the running context.
// Simplest possible plugin: a function
const myPlugin = (ctx: Context) => {
// Register something, listen to events, etc.
}
2. A Context Is a Repository of Services
A context (ctx) is a key-value store of services. A service claims a stable key like ctx.tools, ctx.llm, or ctx.sessions. Other plugins find services by key instead of importing a concrete implementation.
// Access the tool registry from any plugin
const tools = ctx.tools // → ToolRuntime
// Access the LLM adapter registry
const llm = ctx.llm // → LlmRuntime
This is dependency inversion at the framework level: you depend on the interface, not the implementation.
3. Declare Service Dependency via inject
A plugin that needs a service declares it through inject. Cordis waits until those services exist before activating the plugin, so load order is expressed through service requirements rather than manual boot sequencing.
const myPlugin = {
inject: ['tools', 'llm'], // Wait for these to exist
apply(ctx: Context) {
// ctx.tools and ctx.llm are guaranteed available
ctx.tools.register(myToolDefinition)
}
}
4. Typed Events for Communication
Services communicate through typed events. Cordis supports four dispatch modes:
| Mode | Awaited? | Order | Has Return Value? | Use Case |
|---|---|---|---|---|
emit |
No | Registration order | No | Notifications ("a tool was registered") |
waterfall |
No | Registration order | Yes | Interception with short-circuit ("allow/deny this tool call") |
parallel |
Yes | All listeners run concurrently | No | Fan-out ("notify all listeners in parallel") |
serial |
Yes | Registration order | Yes | Ordered processing ("run these hooks one at a time") |
The dispatch mode is part of the event's public contract. DSH uses waterfall heavily for interception points:
// A waterfall: listeners can short-circuit or delegate
ctx.waterfall('tools/pre-execute', exec, async (exec, next) => {
// Check permission, then either:
return { kind: 'deny', reason: 'not allowed' } // short-circuit
// or
return await next() // delegate to the next listener
})
5. Registrations Are Reversible Effects
Prompt sections, tool schemas, adapters, providers, and listeners are installed through ctx.effect() or ctx.on(). When a plugin unloads, Cordis unwinds its effects — so teardown is predictable and automatic.
ctx.effect(() => {
const disposer = ctx.tools.register(myTool)
return () => disposer() // Called when plugin unloads
})
Profiles and Bundles: How DSH Composes Itself
A running dsh is a plugin tree composed at boot from ordered layers.
Profiles
A profile is a named composition stored in the Harness home. It lists the bundles it stacks, holds any out-of-tree plugins it installs, and keeps the user's own cordis.patch.yml. web and headless ship as templates.
Bundles
A bundle is a distribution format for Cordis config rows and the code they mount. Whatever a bundle inserts stays patchable by the layers above it.
The layering order is:
[empty entry list]
→ each bundle in the profile's listed order
→ the profile's cordis.patch.yml
→ the home-level patch
→ any --patch overlay
Each layer can patch a row from a lower layer by its id, replacing its whole config, or insert new rows. The result is a fully composed plugin tree.
The Default Bundles
DSH ships with two primary bundles:
dsh-base: model adapters, tools, persistence, sandbox and approval policy, settings, credentials, telemetry. This is the foundation every profile builds on.dsh-web-app: adds the browser application on top ofdsh-base.dsh-headless: adds a one-shot runner with no server at all.
flowchart TD
subgraph "web profile"
base["dsh-base"] --> web["dsh-web-app"]
web --> patch["cordis.patch.yml"]
end
subgraph "headless profile"
base2["dsh-base"] --> headless["dsh-headless"]
headless --> patch2["cordis.patch.yml"]
end
The Package Hierarchy
DSH's monorepo is organized into ~100+ packages under packages/. Here are the key directories:
| Directory | What it holds |
|---|---|
packages/core/ |
The spine: session, system-prompt, tools, agent, agent-loop, scope |
packages/llm/ |
LLM adapter seam and built-in adapters (DeepSeek, OpenAI, Anthropic, replay) |
packages/fs/ |
Filesystem seam, local provider, sandbox, search tools, edit tools |
packages/shell/ |
Shell execution seam, local bash, PTY, terminal |
packages/subagent/ |
Subagent providers (in-process, forked) |
packages/goal/ |
Goal system for long-running objectives |
packages/workflow/ |
Workflow orchestration engine |
packages/compaction/ |
Context compaction strategies |
packages/credentials/ |
Credential storage seam |
packages/settings/ |
User settings seam |
packages/client/ |
Web UI components (React), TUI, HMR |
packages/boot/ |
App boot, command-line parsing, profiles |
packages/bundle/ |
The three bundles: base, web-app, headless |
packages/extensions/ |
Cordis runner extensions |
apps/ |
CLI entry point (apps/cli), Web shell (apps/web) |
examples/ |
Demo agents (ACP, headless, JSON-RPC, agent-spine) |
The Core Spine: Six Packages, One Loop
The six packages/core/ packages form the spine every DSH composition boots:
flowchart LR
session["session\n(event log)"] --> tools["tools\n(registry)"]
tools --> system-prompt["system-prompt\n(assembly)"]
system-prompt --> agent["agent\n(interface)"]
agent --> agent-loop["agent-loop\n(driver)"]
agent-loop --> scope["scope\n(per-agent)"]
| Package | ctx key |
Role |
|---|---|---|
session |
ctx.sessions |
Append-only SessionEvent log — the single source of truth |
system-prompt |
ctx.systemPrompt |
Prompt-section and tool-schema assembly |
tools |
ctx.tools |
Scoped tool registry and guarded execution pipeline |
agent |
ctx.agents |
Agent interface, live registry, agent/* events |
agent-loop |
ctx.agentLoop |
Concrete driver implementing the Agent contract |
scope |
(library) | Per-agent scoped-registration primitive |
The agent-loop package is the only concrete implementation of the Agent contract. Extension plugins depend on agent — never on agent-loop directly — so the loop itself stays swappable.
The Turn Flow at a Glance
Here is the high-level turn flow (we will go deep in Lesson 3):
turn/start
→ claim next-step input + one queued message
→ assemble prompt sections + tool schemas
→ agent/pre-step (waterfall: reject or enter)
→ step/start
→ append user/message
→ derive model history from log
→ agent/request → llm/stream → assistant/chunk* → assistant/message
→ tool/call* → tools/pre-execute → tools/execute → tools/post-execute → tool/result*
→ step/end
→ (tools owe another request, or next-step input arrived → next step)
→ agent/turn-stopping
turn/end
Every turn/*, step/*, user/message, assistant/*, and tool/* event is a durable session event — it persists in the log. The agent/* and tools/* events are live extension points — they let plugins intercept and modify behavior without touching the log.
Hands-On Experiment: Install DSH and Explore
Prerequisites
- Node.js 22.19+ or 24+
- Corepack-enabled pnpm (the repo pins
pnpm@11.7.0) - Git 2.26+
Step 1: Clone and Install
git clone https://github.com/deepseek-ai/deepseek-harness.git
cd deepseek-harness
pnpm install
pnpm run typecheck
Step 2: Dump the Config
# See what your web profile actually boots
dsh --profile web --dump-config
This prints every Cordis row in the composed tree. Each row has an id — you can patch any of them.
Step 3: Explore the Package Graph
# List all packages
ls packages/core/
ls packages/llm/
ls packages/fs/
# Read a bundle's README
cat packages/bundle/base/README.md
Step 4: Read the Core Spine Source
Open these files in your editor and skim the exports:
packages/core/agent/src/index.ts— theAgentRegistryservicepackages/core/tools/src/index.ts— theToolRuntimeservicepackages/core/session/src/types.ts— theSessionEventMap
Tip: The DSH docs are designed to be read by an agent. Ask your DSH agent: "Explain the relationship between
ctx.agentsandctx.agentLoop."
Step 5: Answer These Questions
- What happens if you remove
dsh-web-appfrom the web profile and add your own bundle? - Look at
--dump-configoutput. Find the row for the DeepSeek LLM adapter. What is itsid? - How would you use a
cordis.patch.ymlto replace the default model?
Compare With…
Pi Agent: Pi Agent's architecture is more monolithic. It has a clear agent loop, tool registry, and plugin system, but plugins are pip-installable packages that register at extension points — not granular services you can individually swap. There is no equivalent to DSH's profile/bundle composition: you configure Pi through CLI flags and config files, not through a layered plugin tree.
Claude Code: Claude Code's architecture is less documented but follows a similar pattern: hooks for interception, a tool registry, and a subagent system. However, Claude Code's hooks are limited to specific interception points (PreToolUse, PostToolUse, etc.) while DSH's waterfall events are a general-purpose mechanism available at every extension point. Claude Code's plugin model is less granular — you cannot, for example, swap the session persistence backend independently of the rest of the system.
Key Takeaways
- Everything is a Cordis plugin — the model adapter, tools, sandbox, loop, and UI.
- Profiles and bundles compose plugins at boot through ordered layers, each patchable.
- The six core packages (
session,tools,system-prompt,agent,agent-loop,scope) form the spine. - Waterfall events are the primary interception mechanism — listeners can short-circuit or delegate.
- Registrations are reversible effects — teardown is automatic and predictable.
Next: Lesson 3 — The Agent Loop: Turns, Steps, and the Event-Sourced Log
In Lesson 3, we dive into the turn flow: how the agent loop claims input, assembles prompts, streams model responses, dispatches tools, and records everything in the event-sourced session log.
Lesson 3: The Agent Loop — Turns, Steps, and the Event-Sourced Log
The Central Question
How does DSH turn a user message into a model response, tool calls, and final output — and how does it record every bit of that process so it can replay, fork, or resume it later?
The answer is the agent loop and the event-sourced session log. This lesson walks the full turn flow, step by step, and explains why DSH stores events rather than messages.
The Hierarchy: Turn → Step → Round
DSH uses three nested time units, defined in the glossary:
Round (outer policy iteration)
└─ Turn (one drain of admitted input)
└─ Step (one model request + its tool executions)
└─ Tool Call (one tool invocation)
| Unit | Definition | Example |
|---|---|---|
| Turn | One drain of admitted input, ending after the model and its tools stop or a terminal policy intervenes. | User says "fix the bug" → agent reads files, edits, runs tests → turn ends. |
| Step | One model request plus the tool executions caused by its response. A turn contains zero or more steps. | Model responds with 3 tool calls → those 3 tools execute → that's one step. The model then makes another request → that's step 2. |
| Round | An outer policy iteration containing a turn. Used by the goal system and Ralph loop. Not every turn is a round. | A goal continuation cycle is one round. |
A turn can have zero steps — if agent/pre-step rejects the proposed step, the turn opens and closes with no model call at all. The log still records it.
The Session Log: Event-Sourced Truth
DSH does not store conversation history as a list of messages. Instead, it stores an append-only log of typed events — the SessionEvent stream. The LLM message history is derived from the log via deriveMessages(), never stored separately.
Why Event Sourcing?
| Benefit | How DSH achieves it |
|---|---|
| Replay | Re-derive messages from the same events → identical model context. |
| Fork | Copy the log up to a boundary, replay into a new session. |
| Resume | Load the persisted log, replay into a live agent. |
| Audit | Every model-visible fact is in the log. An invariant asserts it. |
| UI Fidelity | Raw assistant/chunk events preserve token-level streaming. |
| Extensibility | Plugins add event types via declaration merging on SessionEventMap. |
The Event Vocabulary
The core events — defined in SessionEventMap — are:
| Event | Carries | Purpose |
|---|---|---|
turn/start |
{ turn: number } |
Opens a turn |
turn/end |
{ turn: number, reason: TurnEndReason } |
Closes a turn with why it ended |
step/start |
{ turn: number, step: number } |
Opens a step |
step/end |
{ turn: number, step: number } |
Closes a step |
user/message |
UserMessage (role, content, source) |
A user-role message on the model-visible surface |
assistant/chunk |
{ turn, step, chunk: StreamChunk } |
Raw streaming token — for replay fidelity |
assistant/message |
{ turn, step, message, usage? } |
Assembled assistant message for derived history |
tool/call |
{ turn, step, callId, name, arguments } |
Model requested a tool |
tool/result |
{ turn, step, callId, content, error?, meta? } |
Tool execution completed |
Every event carries a monotonic seq, a time, and a type-discriminated data payload. The log is the single source of truth — model-visible means logged.
The Agent Interface
The Agent is the public handle every plugin (UI, hooks, orchestrators) programs against. You get it from ctx.agents.get(id). Here are its key methods:
interface Agent {
readonly id: SessionId
readonly session: Session // the durable event log
readonly inbox: Inbox // pending messages
readonly status: AgentStatus // 'idle' | 'running'
readonly ctx: Context // agent-scoped context
followup(message: UserMessage): void // queue a normal turn
steer(message: UserMessage): void // submit mid-turn steering
inject(message: UserMessage): void // queue context without waking
cancel(cause: AgentCancelCause, options?: CancelOptions): void
whenIdle(): Promise<void>
}
The Inbox
The agent's inbox has two ordered lists:
| Target | Purpose |
|---|---|
next-turn |
Messages that each become their own turn. A followup() lands here. |
next-step |
Messages consumed at the next step boundary within the current turn. steer() and inject() land here. |
The loop claims next-step input at every step boundary, plus one next-turn message when starting a new turn.
The Full Turn Flow
Here is the complete sequence, adapted from the architecture docs and the agent lifecycle diagram:
sequenceDiagram
participant User
participant Agent
participant Driver
participant Hooks
participant LLM
participant Tools
participant Session
User->>Agent: followup(content)
Agent->>Driver: queued work wakes driver
Driver->>Session: turn/start
Note over Driver: claim next-step input + one next-turn message
Driver->>Hooks: agent/pre-step (waterfall)
Hooks-->>Driver: reject OR enter(messages)
alt rejected
Note over Driver: turn closes, no step
else entered
Driver->>Session: step/start
Driver->>Session: user/message (per entered message)
Driver->>LLM: agent/request → llm/stream
LLM-->>Driver: StreamChunk*
Driver->>Session: assistant/chunk*
Driver->>Session: assistant/message
loop each tool call
Driver->>Session: tool/call
Driver->>Tools: pre-execute → execute → post-execute
Tools-->>Session: tool/result
end
Driver->>Session: step/end
opt tools owe another request
Note over Driver: claim next-step input → next step
end
end
Driver->>Hooks: agent/turn-stopping (serial)
Driver->>Session: turn/end
Walkthrough
-
Wake: A
followup()call queues a message innext-turnand wakes the driver. Status goesidle→running. -
Turn Open:
turn/startis appended to the log. -
Claim: The driver claims all
next-stepinput plus onenext-turnmessage. Claimed messages are removed from the inbox. -
Pre-Step Waterfall:
agent/pre-stepfires. Listeners receive the claimed messages and can: - Reject ({ kind: 'reject' }): the turn closes with no step. The claimed messages are gone — they are neither discarded nor re-emitted. - Enter ({ kind: 'enter', messages }): the step proceeds with these messages (possibly rewritten by a listener). -
Step Open:
step/startis logged, followed byuser/messagefor each entered message. -
Prompt Assembly: The system prompt is assembled from registered sections. Tool schemas are projected from the visible tool set. History is derived from the log via
deriveMessages(). -
Model Request:
agent/request(waterfall — listeners can replace the call config) →llm/stream(waterfall — listeners can wrap the stream). Raw chunks are logged asassistant/chunk. The assembled message is logged asassistant/message. -
Tool Execution: For each tool call in the model's response: -
tool/callis logged -tools/pre-executewaterfall: allow, deny, or ask - Monotonic guards run -tools/executewaterfall: around-dispatch wrappers - Tool body executes -tools/post-executewaterfall: inspect/replace the result -finalizeContentcallback -tool/resultis logged -
Continuation Check: If the model's response included tool calls, the driver checks whether another step is owed. If
next-stepinput is pending, it claims it and starts a new step within the same turn. -
Turn Stop:
agent/turn-stoppingfires (serial — one listener at a time, nonext()). This is the terminal checkpoint before the turn closes. -
Turn End:
turn/endis logged with theTurnEndReason. Status goesrunning→idle.
Two Kinds of Events
DSH distinguishes between durable and live events:
| Kind | Examples | Dispatched on | Purpose |
|---|---|---|---|
| Durable | turn/start, user/message, assistant/message, tool/call, tool/result |
session/event |
Facts that survive reload. Replay, fork, and audit depend on them. |
| Live | agent/pre-step, agent/request, tools/pre-execute, tools/execute, tools/post-execute, agent/turn-stopping |
agent/* or tools/* |
Extension points for interception and policy. Not persisted. |
The rule: model-visible means logged. Anything that reaches a model request must be reconstructable from the log. A runtime invariant asserts this.
Cancellation and Error Recovery
The agent loop has a structured cancellation model:
type AgentCancelCause =
| { kind: 'user' } // human pressed stop
| { kind: 'parent' } // parent agent cancelled child
| { kind: 'hook' } // a hook listener cancelled
| { kind: 'disposed' } // agent is being torn down
cancel() aborts the active turn. With keepInbox: true, pending messages survive for a later turn. The durable turn/end records { kind: 'aborted' } as the coarse outcome.
For model request failures, agent/request-error (waterfall) lets listeners attempt recovery. A listener returns { kind: 'retry' } without calling next(); the default undefined leaves the failure terminal.
Hands-On Experiment: Trace a Turn
Step 1: Start a Headless Session
cd deepseek-harness
# Start a headless agent with a simple prompt
dsh --profile headless --prompt "List the files in packages/core/agent/src/"
Step 2: Observe the Session Events
If you have the Web GUI running (pnpm run dev:web from the checkout, then open http://127.0.0.1:3080), open a session and watch the Network tab. Each session/event dispatch carries the full event stream.
Step 3: Read the Session Log from Code
The session log is persisted (by default as JSONL). Find your session files:
# Look for session storage
ls ~/.dsh/sessions/
Step 4: Answer These Questions
- How many
step/startevents does a single-turn "hello" prompt produce? - What is the
TurnEndReasonfor a turn that the model ended naturally? - If
agent/pre-steprejects a step, what durable events are still logged? - What happens to
steer()messages if the driver is idle?
Compare With…
Pi Agent: Pi Agent's agent loop follows a similar pattern: claim input → call model → execute tools → repeat. However, Pi Agent stores conversation history as a message list, not as an event log. This means fork/resume requires copying the message list, and there is no distinction between durable facts and live extension points. DSH's event sourcing is a fundamentally different approach to state management.
Claude Code: Claude Code's turn driver is comparable in sophistication. It has a similar step/turn hierarchy, tool-use loop, and cancellation model. However, Claude Code's hook system (
PreToolUse,PostToolUse, etc.) is a fixed set of interception points, while DSH's waterfall events are a general mechanism — any plugin can declare new waterfall events, and any plugin can listen to existing ones.
Key Takeaways
- Turn → Step → Round: three nested time units. A turn drains admitted input; a step is one model call + its tools.
- Event-sourced log: the session is an append-only stream of typed events. Messages are derived, not stored.
- Model-visible means logged: an invariant enforces that anything the model sees is reconstructable from the log.
- Durable vs. live events: durable events persist for replay; live events are extension points.
- Waterfall interception:
agent/pre-step,agent/request,tools/pre-execute,tools/execute,tools/post-executeare all waterfalls — listeners can short-circuit or delegate.
Next: Lesson 4 — Tools and the Guarded Execution Pipeline
In Lesson 4, we dive into the tool system: how tools are defined, registered, scoped, approved, executed, and presented — and how the guarded pipeline gives you fine-grained control over every tool call.
Lesson 4: Tools and the Guarded Execution Pipeline
The Tool System at a Glance
Tools are how the model acts on the world. In DSH, every tool — file read, shell command, web search, subagent spawn — goes through the same guarded execution pipeline. This pipeline is the harness's central security and policy boundary.
This lesson covers: how tools are defined, how they are registered and scoped, the full execution pipeline, and how tools present themselves in the UI.
ToolDefinition: What a Tool Is
A tool in DSH is a ToolDefinition — a model-facing schema plus an execution function, output contract, and optional presentation callbacks:
interface ToolDefinition extends ToolSchema {
// Model-facing fields (inherited from ToolSchema):
name: string
description: string
parameters: JsonSchemaNode // JSON Schema for arguments
// Execution:
output: ToolOutputDefinition // canonical output schema + renderer
execute(args: unknown, exec: ToolRunContext): Promise<unknown>
// Optional:
finalizeContent?(exec, result): ContentBlock[] | undefined
timeoutMs?: number
isConcurrencySafe?(args: unknown): boolean
// UI presentation:
presentCall?(args: unknown): ToolCallView | undefined
presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined
}
The key insight: ToolSchema (name, description, parameters) is what the model sees. Everything else — execute, output, finalizeContent, timeoutMs, isConcurrencySafe, presentCall, presentResult — is host-only metadata that schemas() strips before projecting the model-facing view. The model never sees your execution logic.
The defineTool DSL
You rarely write a ToolDefinition by hand. DSH provides defineTool(), a typed DSL:
import { defineTool } from '@deepseek-ai/dsh-tools'
const myTool = defineTool({
name: 'count_lines',
description: 'Count the number of lines in a file.',
parameters: {
path: { type: 'string', description: 'Path to the file', required: true }
},
output: {
schema: { type: 'object', properties: { lines: { type: 'integer' } } },
render(args, value) {
return [{ type: 'text', text: `File has ${value.lines} lines.` }]
}
},
async execute(args, exec) {
// args is typed: { path: string }
const content = await readFile(args.path)
return { lines: content.split('\n').length }
}
})
The DSL infers types from your schema declarations:
parameters→InferArgs<P>gives you typedargsinexecuteoutput.schema→InferValue<S>gives you the typed return valuerenderreceives the typedargsandvalue
The schema DSL supports string, number, integer, boolean, null, array, object, json (unconstrained), and oneOf. A parameter mismatch throws ToolArgsError; an invalid body throws ToolOutputError.
Registration and Scope
Tools are registered on ctx.tools:
// Global tool — visible to every agent
ctx.tools.register(myTool)
// Scoped tool — visible only to one agent
agent.ctx.tools.register(myTool)
Scope Rules
The scope system gives DSH per-agent tool visibility:
| Registration site | Visibility |
|---|---|
ctx.tools.register() (global context) |
All agents |
agent.ctx.tools.register() (agent scope) |
That agent only |
| Scoped tool shadows global tool with same name | That agent sees the scoped version |
Tool Restrictions
A scope can also restrict inherited global tools:
// Only allow read_file and write_file for this agent
agent.ctx.tools.restrict({
allow: ['read_file', 'write_file']
})
// Deny shell execution
agent.ctx.tools.restrict({
deny: ['bash']
})
Restrictions intersect — multiple restrictions combine. Scope-local registrations are exempt from restrictions, so a child agent always keeps the tools it was explicitly given.
The Guarded Execution Pipeline
When the model calls a tool, the call goes through a six-stage pipeline:
flowchart TD
Call["tool/call logged"] --> PreExec["tools/pre-execute\n(waterfall: allow/deny/ask)"]
PreExec -->|"allowed"| Guards["Monotonic Guards\n(can only deny)"]
PreExec -->|"denied"| Denied["Error result"]
PreExec -->|"ask"| Approval["Approval Service"]
Approval -->|"granted"| Guards
Approval -->|"denied"| Denied
Guards -->|"passed"| Execute["tools/execute\n(waterfall: wrappers)"]
Guards -->|"denied"| Denied
Execute --> Body["Tool Body\n(execute function)"]
Body --> PostExec["tools/post-execute\n(waterfall: inspect/replace)"]
PostExec --> Finalize["finalizeContent\n(tool-owned callback)"]
Finalize --> Result["tools/result\n(emit: observers)"]
Result --> Log["tool/result logged"]
Stage-by-Stage
1. tools/pre-execute — Waterfall
Listeners receive (exec, next) and return a PreToolDecision:
type PreToolDecision =
| { kind: 'allow' }
| { kind: 'deny'; reason: string }
| { kind: 'ask'; reason?: string }
allow: proceed. Callnext()to delegate to the next listener, or return{ kind: 'allow' }to short-circuit.deny: the call fails with the given reason. No further listeners run.ask: requires user approval. If no approval channel is available, it becomes a denial. If the user grantsallowed-once, the call proceeds.
This is where you implement permission policies, rate limits, and confirmation dialogs.
2. Monotonic Guards
After the pre-execute waterfall, monotonic guards run. A guard is a function that returns a denial reason or undefined:
type ToolGuard = (execution: Readonly<ToolExecution>) => string | undefined
The key word is monotonic: guards can only deny. They cannot force-allow a call that the waterfall denied. Registration order also cannot turn a denial back into permission — later guards cannot undo earlier ones.
Register a guard globally or per-agent:
ctx.tools.guard((exec) => {
if (exec.name === 'bash' && isDestructive(exec.arguments)) {
return 'Destructive shell commands are not allowed'
}
})
3. tools/execute — Waterfall
Around-dispatch wrappers. Listeners receive (exec, next) where exec.signal is mutable — a wrapper can replace the abort signal to add a timeout. The registry re-fuses the original caller signal before the body, so replacement cannot detach caller cancellation.
Common use cases: timeout enforcement, retry logic, metrics collection.
4. Tool Body
The execute(args, exec) function runs. It receives typed arguments, an AbortSignal, and a ToolRunContext with two extra methods:
exec.deferContext(context): attach context to this execution's result (e.g., a composite tool ferrying nested-dispatch context)exec.concludeTurn(): mark this successful result as terminal — the agent loop stops after committing it
5. tools/post-execute — Waterfall
Inspect or replace the result. Listeners receive (exec, result, next) and return a PostToolDecision:
type PostToolDecision =
| { kind: 'accept'; content?: ContentBlock[] } // replace content
| { kind: 'accept'; value: JsonValue } // replace value (revalidated)
| { kind: 'block'; feedback: ContentBlock[] } // turn into error
- Content replacement preserves the canonical value and metadata — it's a presentation change.
- Value replacement is revalidated against the output schema and recomputes content/metadata.
- A block removes the value and becomes an
isErrorresult with corrective feedback.
6. finalizeContent and tools/result
The tool's own finalizeContent callback runs (synchronous, last-mile transform). Then the frozen result is emitted on tools/result for observers. Finally, tool/result is appended to the session log.
Tool Presentation: UI Cards
Tools describe how they want to appear in a UI through presentCall (pending state) and presentResult (completed state). Both return a card-tagged render intent — a discriminated union:
Call-Time Cards (Pending)
| Card | Use Case | Key Fields |
|---|---|---|
generic |
Default fallback | title, kind?, rawInput?, content?, locations? |
terminal |
Shell command about to run | title, description?, cwd? |
diff |
File mutation pending | title, diffs: { path, oldText, newText }[] |
Result-Time Cards (Completed)
| Card | Use Case | Key Fields |
|---|---|---|
generic |
Default fallback | title?, content? |
terminal |
Shell command completed | title?, output?, exitCode?, signal? |
diff |
File mutation applied | title?, diffs |
search |
grep/glob results | shape: 'matches' \| 'paths', total, truncated |
read |
File read result | path, offset, lines, totalLines, lang?, content? |
web |
Web search/fetch result | kind: 'search' \| 'fetch', sources, statusCode? |
These are provider-neutral: a tool describes itself without depending on any client protocol. The Web GUI, TUI, and any future UI each project this vocabulary into their own views.
Code Mode: The run_code Transport
DSH has a special transport mode called Code Mode. Instead of the model calling tools directly, the model writes code that calls tools through a run_code function. The bridge executes the code in a sandboxed runtime, dispatches each tool call through the same pipeline, and returns the collected results.
This is how DSH supports models that are better at writing code than at structured tool-call JSON. The code runs in a worker-thread runtime with access to the same tools.
The tools/code-dispatch-log waterfall lets you replace the durable log content of sub-dispatches (e.g., truncating oversized results).
Hands-On Experiment: Build and Inspect a Tool
Step 1: Register a Custom Tool
Create a file my-tool.ts in a scratch directory:
import { defineTool } from '@deepseek-ai/dsh-tools'
export const weatherTool = defineTool({
name: 'get_weather',
description: 'Get the current weather for a city.',
parameters: {
city: { type: 'string', description: 'City name', required: true },
units: {
type: 'string',
description: 'Temperature units',
enum: ['celsius', 'fahrenheit']
}
},
output: {
schema: {
type: 'object',
properties: {
temperature: { type: 'number' },
condition: { type: 'string' },
humidity: { type: 'integer' }
}
},
render(args, value) {
return [{
type: 'text',
text: `${args.city}: ${value.temperature}°${args.units === 'fahrenheit' ? 'F' : 'C'}, ${value.condition}, humidity ${value.humidity}%`
}]
}
},
async execute(args, exec) {
// Simulate an API call
return {
temperature: args.units === 'fahrenheit' ? 72 : 22,
condition: 'sunny',
humidity: 45
}
},
presentCall(args) {
return {
card: 'generic',
title: `Weather: ${args.city}`,
kind: 'fetch',
content: [{ type: 'text', text: `Fetching weather for ${args.city}...` }]
}
},
presentResult(args, result) {
return {
card: 'generic',
title: `Weather: ${args.city}`,
content: result.content
}
}
})
Step 2: Trace the Pipeline
For each of these scenarios, predict what the pipeline does:
- A
tools/pre-executelistener returns{ kind: 'deny', reason: 'no weather access' }forget_weather. What happens to the call? - A
tools/post-executelistener returns{ kind: 'block', feedback: [{ type: 'text', text: 'Outdated data' }] }. What does the model see? - A
tools/executewrapper replacesexec.signalwith a 5-second timeout signal. The tool takes 10 seconds. What happens?
Step 3: Read the Tool Source
Open these files and trace a real tool through the pipeline:
packages/fs/tool-fs/src/read_file.ts—read_fileimplementationpackages/shell/tool-bash/src/index.ts—bashtool implementation
Note how each tool uses defineTool, handles exec.signal, and provides presentCall/presentResult.
Compare With…
Pi Agent: Pi Agent's tool system is simpler. Tools are Python functions decorated with schema metadata. There is no pre-execute/post-execute waterfall — permissions are checked at the tool body level. Pi Agent lacks the card-based UI presentation vocabulary: tool results are rendered as plain text or structured data, and the TUI formats them directly. DSH's separation of execution pipeline from presentation is a design choice that enables multiple UI surfaces (Web, TUI, headless) from the same tool definitions.
Claude Code: Claude Code has a tool system with hooks (
PreToolUse,PostToolUse) that are similar to DSH'stools/pre-executeandtools/post-executewaterfalls. However, Claude Code's hooks are fixed-named events, not a general waterfall mechanism. Claude Code's tool descriptions are also simpler — they don't have DSH's card-based presentation vocabulary. Claude Code'srun_codeequivalent (the analysis tool) is less configurable than DSH's Code Mode.
Key Takeaways
ToolDefinitionseparates model-facing schema from host-only execution logic.defineToolprovides a typed DSL with inferred arguments and output types.- The pipeline has six stages: pre-execute → guards → execute → body → post-execute → finalize → result.
- Waterfalls at every stage let you intercept, deny, approve, wrap, replace, or block any tool call.
- Monotonic guards can only deny — listener ordering cannot undo a denial.
- Scope gives per-agent tool visibility: scoped tools shadow globals, restrictions filter globals.
- Presentation cards are provider-neutral UI descriptions — the same tool definition renders in Web, TUI, and headless.
Next: Lesson 5 — Capability Seams: Swappable Everything
In Lesson 5, we explore DSH's seam architecture: how filesystem, shell, LLM, and sandbox providers are swappable behind stable interfaces, and why one provider swap changes the entire product.
Lesson 5: Capability Seams — Swappable Everything
The Problem
Most agent frameworks have a hardcoded filesystem, a hardcoded shell, and a hardcoded LLM client. To change one, you fork the codebase or hope there's a config flag. DSH takes a different approach: every major capability is a seam — a stable interface with swappable implementations. Change the provider, and every consumer moves with it.
This lesson explains the seam pattern, walks through the major seams, and shows why one provider swap changes the entire product.
What Is a Seam?
A seam is a swappable capability with three roles:
| Role | What it is | Example |
|---|---|---|
| Service Definition | Declares the interface and claims a ctx.<key> |
ctx.fs — the filesystem service |
| Service Provider | Implements the interface | dsh-fs-local — local disk; dsh-fs-e2b — remote sandbox |
| Consumer | Uses the service, typically a model-facing tool | dsh-tool-fs — read_file, write_file, edit |
The three roles are normally in separate packages because they evolve independently. A package may own multiple roles when they are one concern — dsh-llm owns both the Service Definition and the Consumer for LLM adapters.
The seam is the complete capability, never one role. Reserve the term for that meaning.
The Seam Graph
Here is a simplified view of DSH's major seams and their providers:
flowchart TD
subgraph "Service Definitions"
FS["ctx.fs\nFilesystem"]
SHELL["ctx.shell\nShell Execution"]
LLM["ctx.llm\nLLM Adapters"]
SUBPROCESS["ctx.subprocess\nProcess Spawning"]
SANDBOX["ctx.sandbox\nProcess Confinement"]
PERSISTENCE["ctx.sessionPersistence\nSession Storage"]
CREDENTIALS["ctx.credentials\nCredential Storage"]
SUBAGENTS["ctx.subagents\nSubagent Providers"]
end
subgraph "Providers (examples)"
FS --> FS_LOCAL["fs-local\n(local disk)"]
FS --> FS_E2B["fs-e2b\n(remote sandbox)"]
SHELL --> BASH_LOCAL["bash-local\n(local shell)"]
SHELL --> BASH_SANDBOX["bash-sandbox\n(confined shell)"]
LLM --> LLM_DEEPSEEK["llm-deepseek"]
LLM --> LLM_OPENAI["llm-openai"]
LLM --> LLM_ANTHROPIC["llm-anthropic"]
LLM --> LLM_REPLAY["llm-replay\n(deterministic testing)"]
SUBPROCESS --> SP_LOCAL["subprocess-local"]
SUBPROCESS --> SP_E2B["subprocess-e2b"]
SANDBOX --> SB_LOCAL["sandbox-local\n(Landlock/Seatbelt/ACL)"]
PERSISTENCE --> P_JSONL["session-persistence-jsonl"]
PERSISTENCE --> P_SQLITE["session-persistence-sqlite"]
end
subgraph "Consumers (examples)"
FS --> TOOL_FS["tool-fs\n(read_file, write_file, edit)"]
SHELL --> TOOL_BASH["tool-bash\n(bash)"]
SHELL --> TOOL_TERMINAL["tool-terminal\n(persistent PTY)"]
LLM --> AGENT_LOOP["agent-loop\n(model requests)"]
SUBPROCESS --> BASH_LOCAL
SANDBOX --> BASH_SANDBOX
end
The critical design property: filesystem and subprocess providers share one execution world. If you point ctx.fs and ctx.subprocess at a remote sandbox, bash, PTY, and LSP move with them — no provider forks.
The Filesystem Seam
The filesystem seam (ctx.fs) is one of the most important. It defines the operations every file tool uses:
interface FileSystem {
readFile(path: string): Promise<string>
writeFile(path: string, content: string): Promise<void>
// ... plus stat, readdir, mkdir, rm, etc.
}
Providers:
| Provider | Where files live | Use case |
|---|---|---|
fs-local |
Local disk | Normal development |
fs-e2b |
E2B remote sandbox | Cloud execution |
fs-sandbox |
Local disk with policy enforcement | Guarded development |
The fs-observation-policy plugin sits between the consumer and provider, enforcing read-before-write rules: you must read a file before you can edit it. This is a policy plugin, not a provider — it listens to fs/* events rather than implementing the ctx.fs service.
The Shell Seam
The shell seam (ctx.shell) is simpler than the filesystem seam: it allows exactly one executor per context (unlike subagents, which allow multiple named providers).
interface ShellExecutor {
execute(command: string, options: ShellOptions): Promise<ShellResult>
}
Providers:
| Provider | Execution environment |
|---|---|
bash-local |
Direct subprocess on the host |
bash-sandbox |
Wraps argv through ctx.sandbox before spawning |
The bash-sandbox provider consumes ctx.sandbox — it's a provider AND a consumer. This is a common pattern: one seam wraps another.
The LLM Seam
The LLM seam (ctx.llm) is a named registry — multiple adapters coexist, each registered by name:
// Register an adapter
ctx.llm.register('deepseek', deepseekAdapter)
ctx.llm.register('openai', openaiAdapter)
// The agent selects one by provider name
agent.options.provider = 'deepseek'
Built-in adapters:
| Adapter | Model family |
|---|---|
llm-deepseek |
DeepSeek V3, V4, R1 |
llm-openai |
GPT-4o, GPT-4.1 |
llm-anthropic |
Claude Sonnet, Opus |
llm-replay |
Deterministic replay for testing |
The llm-replay adapter is especially useful: it replays recorded responses for deterministic tests and benchmarks.
The Subprocess Seam
The subprocess seam (ctx.subprocess) abstracts process spawning. It's consumed by the shell providers, not directly by model-facing tools:
interface SubprocessExecutor {
spawn(command: string, args: string[], options: SpawnOptions): Promise<SpawnResult>
}
Providers: subprocess-local (direct child_process.spawn) and subprocess-e2b (remote process in E2B sandbox).
The Sandbox Seam
The sandbox seam (ctx.sandbox) wraps a subprocess argv in a file-effect policy. It has three modes:
| Mode | Filesystem access |
|---|---|
read-only |
No writes except /dev/null |
workspace-write |
Writes under workspace root + temp area |
danger-full-access |
No confinement (bypasses ctx.sandbox entirely) |
On Linux, the sandbox-local provider uses Landlock (kernel 5.13+) or bwrap. On macOS, it uses Seatbelt (sandbox-exec). On Windows, it uses ACL restricted tokens. Enforcement is reported as full or partial — older kernels may not support every Landlock rule.
The sandbox policy is resolved per-call from the session's workspace root. You can escalate a single call to workspace-write (for an approved retry) without changing the session's default mode.
Why Seams Matter: The Remote Sandbox Scenario
Imagine you want to run DSH agents in a cloud sandbox instead of locally. With seams, you:
- Swap
fs-local→fs-e2b - Swap
subprocess-local→subprocess-e2b
That's it. Every tool — read_file, write_file, bash, terminal, glob, grep — moves to the remote sandbox. No tool code changes. No provider forks. The consumers don't know they're remote.
This is the power of the seam pattern: one provider swap changes the whole product.
Adding Your Own Seam
The extension cookbook in Lesson 7 covers the mechanics. The pattern is:
- Declare the Service Definition: a Cordis
Serviceclass with the interface methods. - Declare the
ctxkey: merge it into theContextinterface. - Implement a Provider: a plugin that provides the service.
- Implement a Consumer: a tool or plugin that injects the service.
The key rule: the Service Definition, Provider, and Consumer are separate packages when they evolve independently. This is what lets you swap providers without touching consumers.
Hands-On Experiment: Swap a Provider
Step 1: Identify the Current LLM Provider
dsh --profile web --dump-config | grep -A5 "llm"
Find the row for the DeepSeek adapter. Note its id.
Step 2: Add an OpenAI Adapter
If you have an OpenAI API key, configure a second adapter in your cordis.patch.yml:
# In ~/.dsh/cordis.patch.yml
- id: openai-adapter
plugin: '@deepseek-ai/dsh-llm-openai'
config:
apiKey: '$OPENAI_API_KEY'
Step 3: Switch Models Mid-Session
In the Web GUI, use the model selector to switch from DeepSeek to OpenAI. The agent's next request uses the new provider — no restart, no configuration change.
Step 4: Try the Replay Adapter
The llm-replay adapter is available for testing. Configure it and observe that every request returns the same recorded response.
Compare With…
Pi Agent: Pi Agent has a unified LLM API that abstracts over multiple providers, similar to DSH's
ctx.llm. However, Pi Agent does not have a formal seam pattern for filesystem, shell, or sandbox. These are typically hardcoded to local execution. Pi Agent's sandboxing is done through OS-level tools (likebwrap) configured at the CLI level, not through a swappable provider interface.Claude Code: Claude Code's architecture is more monolithic. Its filesystem, shell, and model adapters are internal. You can configure different models through the API, but you cannot swap the filesystem or shell backend independently. Claude Code's sandbox is built into its execution model rather than exposed as a swappable seam.
Key Takeaways
- A seam has three roles: Service Definition, Provider, Consumer — normally in separate packages.
- Filesystem and subprocess share one execution world — swap them together and everything moves.
- The LLM seam is a named registry — multiple adapters coexist, and the agent selects one by name.
- The sandbox seam has three modes (read-only, workspace-write, danger-full-access) and per-call policy resolution.
- One provider swap changes the whole product — consumers don't know which provider they're using.
Next: Lesson 6 — Subagents, Workflows, and Long-Running Goals
In Lesson 6, we explore how DSH delegates work: subagents for isolated subtasks, workflows for parallel orchestration, and the goal system for long-running autonomous objectives.
Lesson 6: Subagents, Workflows, and Long-Running Goals
The Delegation Spectrum
DSH gives you three ways to delegate work, each at a different level of abstraction:
| Mechanism | What it does | Granularity | Persistence |
|---|---|---|---|
| Subagent | Spawns a child agent for an isolated subtask | One task, one child | One-shot or continuable |
| Workflow | Runs a model-written orchestration script that fans out across many subagents | Many tasks, many children | One run |
| Goal | Drives a same-session objective across multiple autonomous rounds | One objective, many turns | Durable, resumable |
This lesson explains all three and how they compose.
Subagents
A subagent is a child agent spawned by a parent agent to handle an isolated subtask. The parent delegates, the child works, the parent receives the result.
The Subagent Seam
Unlike the shell seam (one executor), the subagent seam (ctx.subagents) is a named registry — multiple provider implementations coexist:
// Subagent providers are registered by name
ctx.subagents.register('in-process', inProcessProvider)
ctx.subagents.register('fork', forkProvider)
ctx.subagents.register('acp', acpProvider)
Provider Types
| Provider | How it runs the child | Best for |
|---|---|---|
in-process |
Child agent in the same Node.js process, sharing the plugin tree | Fast, lightweight subtasks |
fork |
Fresh child agent in a new process, no shared context | Isolated, untrusted subtasks |
acp |
Child agent via Agent Client Protocol (remote) | Cross-machine delegation |
codex |
Child agent in a Codex CLI process | Codex-native workflows |
claude-code |
Child agent in a Claude Code process | Claude Code-native workflows |
One-Shot vs. Continuable
Subagents come in two flavors:
One-shot (subagent tool): The parent sends a prompt, the child runs to completion, the parent receives the result. The child's session is ephemeral — it exists only for this run.
// The model calls the subagent tool
{
name: 'subagent',
arguments: {
description: 'Fix the login bug',
prompt: 'Find and fix the null-pointer in auth.ts'
}
}
// The child runs, returns its result, and is disposed
Continuable (subagent_fork tool): The child persists as its own session. The parent can send follow-up messages (send_message), list its children (list_agents), and interrupt them (interrupt_agent). The child can also report back to the parent (report).
sequenceDiagram
participant Parent
participant Child
Parent->>Child: subagent_fork("Fix the login bug")
Note over Child: Child runs autonomously...
Child-->>Parent: report("Found the bug in auth.ts line 42")
Parent->>Child: send_message("Great, now fix it")
Note over Child: Child fixes the bug...
Child-->>Parent: report("Fixed. Ready for review.")
Note over Child: Child settles, manager delivers notice
Continuable Lifecycle
A continuable child has three states from the parent's perspective:
| State | What it means | followup behavior |
|---|---|---|
running |
Agent has an active turn or waking inbox work | Enqueue in the same Activation |
waiting |
Agent is quiescent but owns live children | Wake the same Activation |
settled |
Quiescent with all children disposed | Cold-resume a new Activation |
Scope and Tool Inheritance
When a parent creates an in-process child, the child can join the parent's composition via composeFrom:
// In the child's setup:
agentPresets.composeFrom(childCtx, parentCtx)
This gives the child the exact same plugin instances as the parent — same tool registrations, same prompt sections, same listeners. The child does not re-read the roster; it gets the parent's live generation. This is a bind, not a mount: it's synchronous and has no composition failure mode.
The parent can also restrict the child's tools:
// The child gets only read-only tools
subagentStartRequest.toolFilter = {
allow: ['read_file', 'glob', 'grep']
}
Workflows
A workflow is a model-written JavaScript script that orchestrates many subagents. It's a higher-level abstraction: instead of the model calling subagent one at a time, the model writes a script that coordinates the whole operation.
The Workflow Script
The script runs in a node:worker_threads sandbox. It has access to these hooks:
// The script body — plain JavaScript, top-level await allowed
const results = await pipeline(files,
// Stage 1: analyze each file in parallel
async (prev, file, index) => {
return await agent(`Analyze ${file} for security issues`)
},
// Stage 2: fix issues found (with barrier between stages)
async (prev, file, index) => {
if (prev.issues.length > 0) {
return await agent(`Fix the security issues in ${file}: ${prev.issues.join(', ')}`)
}
return prev
}
)
return { analyzed: results.length, fixed: results.filter(Boolean).length }
Available Hooks
| Hook | What it does |
|---|---|
agent(prompt, opts?) |
Run one subagent to completion. Returns its final text, or a validated object if opts.schema is provided. |
pipeline(items, ...stages) |
Run each item through stages independently with NO barrier between stages. An item that throws in a stage becomes null and skips remaining stages. |
parallel(thunks) |
Run zero-argument functions concurrently and await ALL of them (a barrier). |
phase(title) |
Start a named progress phase for observers. |
log(message) |
Emit a progress log message. |
args |
The tool call's args input, verbatim. |
Pipeline vs. Parallel
The critical distinction:
pipeline: items flow through stages independently. Item 1 can enter stage 2 before item 2 finishes stage 1. No barrier between stages. Use this for most multi-stage work.parallel: all thunks must finish before the next line runs. A barrier. Use only when a stage genuinely needs every prior result.
The Meta Block
Every workflow carries a meta identity block (provided as plain JSON data, not code):
{
"name": "security-audit",
"description": "Audit all source files for security vulnerabilities and fix them",
"whenToUse": "When the user asks for a security review",
"phases": [
{ "title": "Scanning", "detail": "Discover files and scan for issues" },
{ "title": "Fixing", "detail": "Apply fixes to identified issues" }
]
}
The engine validates meta against its schema before the script runs — no script text is ever evaluated to obtain it.
Goals: Long-Running Autonomous Objectives
A goal is a durable completion objective attached to an existing session. It's designed for work that takes more than one turn — "fix all the TypeScript errors in this project," "migrate this codebase to the new API."
Goal Lifecycle
stateDiagram-v2
[*] --> active: create_goal
active --> active: goal round completes
active --> paused: pause
active --> blocked: same condition persists 3+ rounds
active --> complete: objective achieved
paused --> active: resume
blocked --> active: resume (human clears blocker)
complete --> [*]
Key Concepts
| Concept | Definition |
|---|---|
| Goal | One durable completion objective with a revisioned phase (active / paused / blocked / complete) and a round cap. |
| Goal Round | One continuation cycle admitted for the current goal. Materialized as one goal-sourced turn. |
| Activation | Process-local permission for a continuation consumer to admit another round. Either armed or disarmed. |
A goal is state, not a scheduler. The session log remains its source of truth. The goal does not create a separate conversation — it drives continuation turns within the same session.
Why Activation Exists
Activation is deliberately not persisted. When you fork or resume a session, the goal's phase and round count survive, but activation is disarmed. A human must explicitly re-arm it (via /goal or the model tool) before automatic work resumes. This prevents a forked session from immediately continuing autonomous work without human authorization.
The Ralph Loop
The Ralph loop is a specialized goal variant: a foreground fresh-agent workflow run toward an immutable objective. Each Ralph round opens a fresh child session with no parent or prior-child conversation seed. The shared workspace and a bounded structured handoff report carry cross-round state.
Round 1: fresh child → workspace → handoff report
Round 2: fresh child (sees workspace + handoff, no prior conversation) → workspace → handoff
Round 3: ...
Ralph is for objectives where the model benefits from starting fresh each round while retaining file-level state.
How They Compose
These three mechanisms compose:
- A goal drives autonomous continuation across rounds.
- Each round can use subagents for isolated subtasks.
- A complex subtask can use a workflow to fan out across many subagents.
Goal: "Fix all bugs in this project"
Round 1:
Turn 1: Model spawns subagent("Find bugs in auth/")
Turn 2: Model spawns workflow("Fix and verify each bug found")
Workflow:
pipeline(bugs,
stage1: agent("Fix bug X"),
stage2: agent("Verify fix for bug X")
)
Round 2:
Turn 1: Model spawns subagent("Find bugs in api/")
...
Hands-On Experiment: Create a Subagent
Step 1: Observe a Subagent in the Web GUI
Open the Web GUI (http://127.0.0.1:3080). Send a prompt that naturally triggers subagent creation:
"I need you to analyze two things in parallel: check
packages/core/agent/src/index.tsfor missing JSDoc, and checkpackages/core/tools/src/index.tsfor the same. Spawn a subagent for each."
Watch the sidebar — you'll see child agents appear. Use list_agents to see them.
Step 2: Trace the Continuation
If a child is continuable, send it a follow-up message:
"send_message to the subagent that analyzed agent/src: also check for missing error handling."
Observe the child wake up and process the new message.
Step 3: Read the Subagent Source
Open these files:
packages/subagent/subagent/src/types.ts— theSubagentStartRequestandSubagentCapabilitiestypespackages/subagent/tool-subagent/src/index.ts— thesubagenttool definition
Step 4: Try a Workflow
Send a prompt that triggers a workflow:
"I have a list of files that need their copyright headers updated. Write a workflow that processes them in parallel."
The model will write a workflow script. Observe the phases and parallel execution.
Compare With…
Pi Agent: Pi Agent supports subagent delegation through its router and subagent packages. The model is simpler: spawn a child, wait for the result. Pi Agent does not have DSH's continuable subagent model (send_message, interrupt, report) or the workflow orchestration engine. Pi Agent's subagents are always one-shot.
Claude Code: Claude Code has a sophisticated subagent system with child runtimes. Its subagent model is similar to DSH's fork provider: each subagent is a separate process. Claude Code also has a
/goal-like mechanism for long-running tasks, but it's less formalized than DSH's goal domain with revisioned phases, activation, and round caps. Claude Code's dynamic workflows inspired DSH's workflow system, but DSH's workflow engine is integrated into the harness rather than being a separate tool.
Key Takeaways
- Subagents come in one-shot and continuable flavors. Continuable children persist as sessions, accept follow-ups, and can report back.
- The subagent seam is a named registry — multiple providers (in-process, fork, ACP, Codex, Claude Code) coexist.
composeFromgives a child the parent's exact plugin instances — a synchronous bind, not a re-mount.- Workflows are model-written orchestration scripts.
pipelinefor independent stages,parallelfor barriers. - Goals are durable, revisioned objectives with phases and activation. They drive autonomous continuation within the same session.
- The Ralph loop is fresh-agent iteration — each round starts a new child with only the workspace and handoff as cross-round state.
Next: Lesson 7 — Extending DSH: Build Your Own Plugin
In Lesson 7, we put everything together: you'll learn how to add a package, a tool, an LLM adapter, and a conversation node to DSH — following the extension cookbook step by step.
Lesson 7: Extending DSH — Build Your Own Plugin
The Extension Philosophy
DSH's architecture doc has a table called "Where new behavior goes." It maps every kind of extension to the exact mechanism and ctx key. Here it is, adapted from the architecture:
| Goal | Mechanism |
|---|---|
| Add a model provider | Register its adapter on ctx.llm |
| Add a model-facing capability | Register on ctx.tools; its schema joins prompt assembly |
| Give one session a different capability set | Compose an agent preset; a service row there needs an isolate realm |
| Add shell execution | Register a ctx.shell backend |
| Add a human command | Register on ctx.commands; it dispatches without a model turn |
| Add background work | Register on ctx.jobs; job_* tools collect or stop it |
| Add filesystem access or policy | Register a ctx.fs provider or listen to fs/* events |
| Intercept a request, tool, or turn | Use its agent/* or tools/* event |
| Add model-facing context | Call agent.inject(); it lands in the next admitted request |
| Add UI or editor integration | Drive ctx.agents and render from session/event |
| Add a Web Client Chat node | Register a ConversationNodeDefinition + keyed renderer |
This lesson walks through the three most common extensions: a tool, a permission hook, and an LLM adapter. Each follows the same pattern: declare what you need (inject), register it on the right ctx key, and return a disposer for teardown.
Pattern 1: Adding a Tool
A tool plugin is the simplest extension. It registers a ToolDefinition on ctx.tools:
import type { Context } from '@deepseek-ai/cordis'
import { defineTool } from '@deepseek-ai/dsh-tools'
export const name = 'my-tool-plugin'
export const inject = ['tools'] // wait for ctx.tools
export function apply(ctx: Context) {
ctx.tools.register(defineTool({
name: 'read_file',
description: 'Read a file from disk.',
parameters: {
path: { type: 'string', required: true, description: 'Absolute path' },
limit: { type: 'number' },
},
output: {
schema: { type: 'string' },
render: (_args, value) => [{ type: 'text', text: value }],
},
async execute(args, exec) {
// args is TYPED: { path: string; limit?: number }
// exec.signal is the AbortSignal — honor it
return readFile(args.path, { encoding: 'utf8', signal: exec.signal })
},
}))
}
That's it. The tool appears in the model's prompt automatically. The schemas() method on ctx.tools projects only the model-facing fields (name, description, parameters) — your execute function and output.render never leak to the model.
Key Rules from the Tool Authoring Reference
-
Args are validated for you.
defineToolvalidates model-generated arguments against the schema beforeexecuteruns. You still hand-check constraints the DSL can't express (non-empty strings, positive numbers, cross-field rules). -
Return one canonical JSON value.
output.schemadeclares the type.executereturns only the value; the registry snapshots, validates, freezes, and passes it tooutput.render. -
Throwing means
isError. The registry catches throws and produces an error result. Throw for infrastructure failures. Represent domain outcomes (like a non-zero exit code) in the canonical value. -
Honor
exec.signal. Cancel in-flight work when the signal fires. -
Registration is an effect. Disposing the plugin fiber unregisters the tool. No manual cleanup needed.
Adding UI Presentation
Add presentCall and presentResult for rich UI cards:
presentCall(args) {
return {
card: 'generic',
title: `Read: ${args.path}`,
kind: 'read',
locations: [{ path: args.path }]
}
},
presentResult(args, result) {
if (result.isError) return undefined // fall back to generic
return {
card: 'read',
title: args.path,
path: args.path,
offset: 1,
lines: result.content,
totalLines: result.content.length
}
}
Pattern 2: Adding a Permission Hook
A permission hook intercepts tool calls before they execute. It listens to the tools/pre-execute waterfall:
import type { Context } from '@deepseek-ai/cordis'
import type { PreToolDecision, ToolExecution } from '@deepseek-ai/dsh-tools'
export const name = 'permission-gate'
export function apply(ctx: Context) {
ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
if (exec.name === 'bash' && isDestructive(exec.arguments)) {
return { kind: 'ask', reason: 'This shell command may be destructive.' }
}
return next() // delegate to the next listener
})
}
Choosing the Right Extension Point
The extension cookbook gives this selection rule:
| Extension Point | Use When |
|---|---|
tools/pre-execute |
You need reorderable allow/deny/ask policy. Other listeners can override. |
ctx.tools.guard() |
You need a monotonic final denial. No listener can undo it. |
tools/execute |
You need to wrap the dispatch lifetime (timeouts, retries, metrics). Only exec.signal is replaceable. |
tools/post-execute |
You need to transform the result, attach context, or block it. |
tools/result |
You need contained observation of the immutable final outcome. |
Monotonic Guard Example
A guard is simpler but cannot be overridden:
ctx.tools.guard((exec) => {
if (exec.name === 'write_file' && isOutsideWorkspace(exec.arguments)) {
return 'Cannot write outside the workspace.'
}
// return undefined → allow
})
Pattern 3: Adding an LLM Adapter
An LLM adapter registers on ctx.llm. It translates DSH's internal LlmCallConfig into a provider-specific API call and streams back StreamChunk events:
import type { Context } from '@deepseek-ai/cordis'
export const name = 'my-llm-adapter'
export const inject = ['llm']
export function apply(ctx: Context) {
ctx.llm.register('my-provider', {
async stream(config, signal) {
// config: LlmCallConfig (messages, tools, max_tokens, etc.)
const response = await fetch('https://api.my-provider.com/v1/chat', {
method: 'POST',
headers: { 'Authorization': `Bearer ${config.apiKey}` },
body: JSON.stringify({
model: config.model,
messages: config.messages,
tools: config.tools,
max_tokens: config.maxTokens,
stream: true,
}),
signal,
})
// Return an async iterable of StreamChunk events
return parseStreamToChunks(response.body)
},
})
}
The adapter is selected by the agent's options.provider field. The agent loop calls ctx.llm.stream(provider, config, signal) and the registry routes to the matching adapter.
The Two Type Patterns You'll Use
Every DSH extension uses one or both of these patterns, documented in core.md:
1. The …Map → derived-union Pattern
Extensible sum types are declared as a map interface, then the union is derived from it. Plugins add variants via declaration merging — no edit to the owning package:
// In dsh-llm (the owning package):
interface ContentBlockMap {
'text': { type: 'text'; text: string }
'tool_use': { type: 'tool_use'; id: string; name: string; input: object }
}
type ContentBlock = ContentBlockMap[keyof ContentBlockMap]
// In your plugin (declaration merge):
declare module '@deepseek-ai/dsh-llm' {
interface ContentBlockMap {
'my_custom_block': { type: 'my_custom_block'; data: unknown }
}
}
Six canonical maps use this pattern: ContentBlockMap, MessageSourceMap, FinishReasonMap, TurnTriggerMap, TurnEndReasonMap, and SessionEventMap.
2. Branded IDs
IDs are structurally strings but non-interchangeable at the type level:
type SessionId = Branded<'session'>
type CallId = Branded<'call'>
type JobId = Branded<'job'>
// A SessionId cannot be passed where a CallId is expected
function getCall(id: CallId): Call { ... }
getCall(sessionId) // TypeScript error!
Plugin Lifecycle
Every plugin follows the same lifecycle:
export const name = 'my-plugin' // unique id for the plugin tree
export const inject = ['tools', 'llm'] // wait for these services
export function apply(ctx: Context) {
// SETUP: register tools, listeners, providers
const disposer = ctx.tools.register(myTool)
// EFFECT: return a cleanup function (or use ctx.effect)
ctx.effect(() => {
const listener = ctx.on('tools/result', (exec, result) => {
console.log(`Tool ${exec.name} completed`)
})
return () => {
listener() // unregister the listener
disposer() // unregister the tool
}
})
}
When the plugin is unloaded (profile change, HMR, disposal), Cordis calls every disposer in reverse registration order. You never manually track cleanup.
Hands-On Experiment: Build a Plugin
Step 1: Create the Package Structure
mkdir -p packages/my-plugins/hello-tool/src
Create packages/my-plugins/hello-tool/package.json:
{
"name": "@deepseek-ai/dsh-hello-tool",
"version": "0.0.1",
"private": true,
"main": "./src/index.ts",
"dsh": {
"plugin": true
}
}
Create packages/my-plugins/hello-tool/src/index.ts:
import type { Context } from '@deepseek-ai/cordis'
import { defineTool } from '@deepseek-ai/dsh-tools'
export const name = 'hello-tool'
export const inject = ['tools']
export function apply(ctx: Context) {
ctx.tools.register(defineTool({
name: 'hello',
description: 'Say hello to someone.',
parameters: {
name: { type: 'string', description: 'Who to greet', required: true }
},
output: {
schema: { type: 'string' },
render: (_args, value) => [{ type: 'text', text: value }]
},
async execute(args) {
return `Hello, ${args.name}!`
}
}))
}
Step 2: Mount It in Your Profile
Add the plugin to your cordis.patch.yml:
- id: hello-tool
plugin: '@deepseek-ai/dsh-hello-tool'
Step 3: Verify It Works
Start DSH and ask the agent:
"Use the hello tool to greet Alice."
The agent should call hello({ name: 'Alice' }) and receive "Hello, Alice!".
Step 4: Add a Permission Hook
Create a second plugin that restricts hello to certain names:
export const name = 'hello-guard'
export function apply(ctx: Context) {
ctx.tools.guard((exec) => {
if (exec.name === 'hello' && (exec.arguments as any).name === 'Bob') {
return 'Bob is not allowed to be greeted.'
}
})
}
Mount it and try greeting Bob. The call should be denied.
Compare With…
Pi Agent: Pi Agent's extension model is based on pip-installable packages that register at extension points. You write a Python module, declare entry points in
setup.py, and Pi discovers and loads them. The pattern is similar to DSH's plugin model but less granular — Pi Agent does not have DSH's service-injection system (inject), effect-based teardown, or the waterfall dispatch model for interception. Adding a tool in Pi Agent means writing a function with a decorator; adding a permission hook means registering a callback.Claude Code: Claude Code's extensibility is primarily through hooks (PreToolUse, PostToolUse, etc.) and custom slash commands. Hooks are configured in JSON/YAML files, not code plugins. There is no equivalent to DSH's
ctx.llm.register()for adding model providers — Claude Code is tightly coupled to Anthropic's API. Claude Code's plugin architecture is less programmable than DSH's.
Key Takeaways
- Every extension follows the same pattern:
injectwhat you need, register on the rightctxkey, return disposers. - Tools are the simplest extension:
defineTool+ctx.tools.register(). - Permission hooks use
tools/pre-execute(reorderable) orctx.tools.guard()(monotonic). - LLM adapters register on
ctx.llmand translate internal config to provider-specific API calls. - Declaration merging lets you extend core types without editing the owning package.
- Effect-based teardown means Cordis unwinds your registrations when your plugin unloads — no manual cleanup.
Next: Lesson 8 — DSH vs. The World: Comparative Deep-Dive
In the final lesson, we put everything in perspective: a detailed comparison of DSH, Pi Agent, Claude Code, and Codex CLI — their architectures, strengths, weaknesses, and when you should use each one.
Lesson 8: DSH vs. The World — Comparative Deep-Dive
The Harness Effect
In April 2026, Daniel Vaughan published a striking finding: the same model scored 16 points higher on SWE-bench in a different harness. The harness is not just packaging — it changes what the model can do.
This lesson compares DSH against the three other major open-source harnesses — Pi Agent, Claude Code, and Codex CLI — across the dimensions that matter: architecture, plugin model, tool system, subagent delegation, sandboxing, and extensibility.
Comparison Matrix
| Dimension | DSH | Pi Agent | Claude Code | Codex CLI |
|---|---|---|---|---|
| Language | TypeScript | Python | TypeScript | TypeScript |
| Plugin Model | Cordis (everything is a plugin) | pip packages + extension points | Hooks + slash commands | Unknown |
| Session Model | Event-sourced log | Message list | Internal | Internal |
| UI Surfaces | Web, TUI, headless | TUI, CLI | TUI, IDE | TUI, CLI |
| Tool Pipeline | 6-stage guarded waterfall | Direct execution | PreToolUse/PostToolUse hooks | Internal |
| Subagents | One-shot + continuable, multi-provider | One-shot via router | Child-runtime processes | Unknown |
| Workflow Engine | JS scripts with pipeline/parallel | None | Dynamic workflows (separate) | None |
| Goal System | Durable, revisioned, activation-gated | None | /goal-like (less formal) | None |
| Sandbox | Landlock/Seatbelt/ACL, swappable | OS-level (bwrap) | Built-in | Sandbox-first |
| Provider Swaps | FS, shell, LLM, subprocess, sandbox | LLM only | LLM only | LLM only |
| Open Source | Yes (Apache 2.0) | Yes (MIT) | No (source-available) | Yes (Apache 2.0) |
DSH vs. Pi Agent
Architecture
Pi Agent describes itself as "not an SDK". It provides a unified LLM API, an agent loop, a TUI, and a tool system — all in Python. It's designed to be simple and Pythonic.
DSH is designed for maximum composability. Every part of DSH is a Cordis plugin. Pi Agent's architecture is more monolithic: it has a clear agent loop, tool registry, and plugin system, but plugins are pip-installable packages that register at extension points — not granular services you can individually swap.
Plugin Model
Pi Agent: Plugins are Python packages with entry points. You install a pip package, and Pi discovers and loads it. The plugin can register tools, models, or hooks. This is straightforward and familiar to Python developers.
DSH: Plugins are Cordis services that declare dependencies via inject, register through ctx.effect(), and unwind automatically on teardown. The profile/bundle composition system layers plugins at boot. This is more powerful but has a steeper learning curve.
Session Model
Pi Agent: Conversation history is stored as a message list. Fork and resume require copying the list.
DSH: The session is an event-sourced log. Messages are derived, not stored. This enables replay, fork, resume, and audit from a single source of truth. The invariant "model-visible means logged" ensures consistency.
Tool System
Pi Agent: Tools are Python functions with schema decorators. Permissions are checked at the tool body level. There is no pre-execute/post-execute waterfall.
DSH: Tools go through a six-stage guarded pipeline. The waterfall model lets you interpose policy, approval, metrics, and transformation at every stage. Tool presentation is separated from execution via the card-based UI vocabulary.
When to Use Pi Agent
- You work primarily in Python and want a simple, familiar setup.
- You need quick prototyping with minimal configuration.
- You don't need swappable filesystem/shell/sandbox providers.
- You don't need continuable subagents or workflow orchestration.
When to Use DSH
- You need full control over every component (swap FS, shell, LLM, sandbox independently).
- You need multiple UI surfaces (Web + TUI + headless) from the same harness.
- You need continuable subagents with send_message/interrupt/report.
- You need workflow orchestration for parallel fan-out tasks.
- You need durable, revisioned goals for autonomous long-running work.
- You want event-sourced sessions for audit, replay, and fork.
DSH vs. Claude Code
Architecture
Claude Code is the most polished end-user coding agent. Its architecture is less documented, but source analysis reveals a sophisticated system with a turn driver, tool registry, hook system, and subagent runtime.
DSH's architecture is more modular. Where Claude Code has a fixed hook system (PreToolUse, PostToolUse, etc.), DSH has general-purpose waterfall events at every extension point. Where Claude Code has a built-in subagent model, DSH has a multi-provider subagent seam.
Subagent Delegation
Claude Code: Subagents are child-runtime processes. Each subagent runs in a separate process with its own context. This provides strong isolation but is heavier than DSH's in-process subagents.
DSH: Offers both in-process subagents (lightweight, share the plugin tree) and forked subagents (isolated, separate process). Also supports continuable subagents with send_message, interrupt, and report — a model Claude Code does not have in the same form.
Extensibility
Claude Code: Hooks (PreToolUse, PostToolUse, Notification, etc.) + custom slash commands. Hooks are configured in JSON/YAML, not code. You cannot add a new LLM provider — Claude Code is tightly coupled to Anthropic's API.
DSH: Full programmatic extensibility. Add tools, LLM adapters, filesystem providers, shell providers, sandbox providers, UI components, protocol drivers, and more. Everything is a plugin.
Context Management
Claude Code: Has sophisticated context-window management with compaction and summarization. The analysis tool is a code-execution sandbox similar to DSH's Code Mode.
DSH: Has a compaction subsystem with multiple strategies (basic compaction, tool-result pruning). The compaction seam is itself swappable — you can add new compaction strategies as plugins.
When to Use Claude Code
- You want the most polished, fastest end-user experience.
- You are deeply invested in the Anthropic ecosystem.
- You don't need to swap LLM providers or filesystem backends.
- You don't need workflow orchestration or durable goals.
When to Use DSH Instead
- You need to use non-Anthropic models (DeepSeek, OpenAI, etc.).
- You need programmatic extensibility beyond hooks.
- You need continuable subagents with bidirectional communication.
- You need the event-sourced session model for audit/replay/fork.
- You need multiple UI surfaces (Web GUI for collaboration, TUI for terminal, headless for CI).
DSH vs. Codex CLI
Architecture
Codex CLI (OpenAI) is the newest entrant. It's OpenAI-native and sandbox-first. Its architecture is less documented than DSH's, but it shares the same basic pattern: agent loop, tool system, sandbox, and subagents.
Sandboxing
Codex CLI: Sandbox-first design. Every execution is confined by default. OpenAI's approach to sandboxing is a core differentiator.
DSH: Sandbox is a swappable seam. You can run without a sandbox for trusted code, with Landlock for Linux, Seatbelt for macOS, or ACL for Windows. The sandbox mode is per-call: read-only, workspace-write, or danger-full-access.
When to Use Codex CLI
- You are deeply invested in the OpenAI ecosystem.
- You want sandbox-first execution by default.
- You prefer OpenAI's coding agent UX.
When to Use DSH Instead
- You need multi-model support (DeepSeek, OpenAI, Anthropic simultaneously).
- You need the plugin composition model for custom deployments.
- You need the Web GUI for team collaboration.
- You need the event-sourced session model.
The Dimensions That Matter
When choosing a harness, evaluate across these dimensions:
1. Composability
How much can you swap without forking? DSH leads here: every capability is a seam. Pi Agent and Claude Code swap only the LLM provider. Codex CLI is OpenAI-only.
2. Session Model
Do you need audit, replay, and fork? DSH's event-sourced log is unique. Other harnesses store message lists — simpler but less powerful.
3. Delegation
Do you need subagents that persist, accept follow-ups, and report back? DSH's continuable subagent model is the most sophisticated. Claude Code has isolated child processes. Pi Agent has one-shot subagents.
4. Orchestration
Do you need to fan out work across many agents? DSH's workflow engine (pipeline, parallel) is the only one that's integrated into the harness. Claude Code has dynamic workflows as a separate tool.
5. Autonomy
Do you need long-running autonomous objectives? DSH's goal system (durable, revisioned, activation-gated) is the most formal. Claude Code has a /goal-like mechanism. Pi Agent has none.
6. UI Surfaces
Do you need Web, TUI, and headless? DSH is the only harness that provides all three from the same tool definitions. Pi Agent has TUI. Claude Code has TUI and IDE integration.
7. Ecosystem Lock-in
Are you tied to one model provider? DSH and Pi Agent are provider-agnostic. Claude Code is Anthropic-only. Codex CLI is OpenAI-only.
The Bottom Line
| If you want… | Choose… |
|---|---|
| Maximum composability, event-sourced sessions, multi-UI, continuable subagents, workflows, goals | DSH |
| Simple Python setup, quick prototyping, familiar ecosystem | Pi Agent |
| Polished end-user experience, tight Anthropic integration, fastest execution | Claude Code |
| OpenAI-native, sandbox-first execution | Codex CLI |
DSH is the most architecturally ambitious harness. Its commitment to "everything is a plugin" means every part of the system is replaceable. Its event-sourced session model means every interaction is replayable. Its subagent, workflow, and goal systems mean it scales from a single prompt to multi-day autonomous runs.
The cost is complexity: DSH has a steeper learning curve than Pi Agent or Claude Code. But if you need the power, DSH is the harness that gives it to you.
Further Reading
- Coding Agents: Harness Architecture Comparison — the definitive survey of harness design patterns
- The Harness Effect — same model, different harness, different score
- Pi Is Not Another Agent SDK — Pi Agent's design philosophy
- Claude Code Architecture — community-driven architecture analysis
- Awesome AI Anatomy — source-code teardowns of 15 AI coding agents
- DSH Architecture — the official DSH architecture doc
Course Complete
You've completed the 8-lesson DSH tutorial. You now understand:
- What a harness is and how it differs from an SDK (Lesson 1)
- DSH's plugin architecture — Cordis, profiles, bundles, and the core spine (Lesson 2)
- The agent loop — turns, steps, the event-sourced session log (Lesson 3)
- The tool system — the six-stage guarded pipeline, defineTool DSL, UI cards (Lesson 4)
- Capability seams — swappable filesystem, shell, LLM, sandbox providers (Lesson 5)
- Subagents, workflows, and goals — one-shot and continuable delegation, orchestration, autonomous objectives (Lesson 6)
- Extending DSH — building tools, hooks, and LLM adapters (Lesson 7)
- Comparative analysis — DSH vs. Pi Agent, Claude Code, and Codex CLI (Lesson 8)
The best way to solidify this knowledge: build something. Pick one of the hands-on experiments from any lesson and extend it. Add a custom tool. Write a permission hook. Swap a provider. The harness is yours to shape.