Introduction

Agent engineering is splitting into two distinct architectural directions as the ecosystem matures. A deep dive into DeepSeek Harness reveals a bold design philosophy: nearly every component, including the core agent loop, is built as a swappable plugin. By contrast, Codex retains privileged core modules that act as fixed anchors within its runtime. This article dissects the underlying architecture of DeepSeek Harness, built on the Cordis plugin framework. We break down its reusable design patterns, identify hidden pitfalls, and compare it against Codex’s paradigm to evaluate the long-term tradeoffs of each approach.

To understand Harness, developers must first master the five foundational concepts of Cordis. Harness is built as a secondary layer atop Cordis, so all plugin behaviors and runtime mechanics stem from this underlying framework. Without grasping these core abstractions, reading Harness source code becomes unintelligible.

1. Five Foundational Concepts of Cordis

1.1 Plugins: Objects That Implement the Service Interface

At its core, every Cordis plugin is a class that implements the Service type. Plugins leverage inject and apply lifecycle hooks to integrate into the runtime context. This uniform pattern applies across all components: model adapters, tool registries, conversation loggers, and even the main agent loop. There are no privileged core modules. Every component lives on equal footing and can be replaced.

In many traditional agent runtimes, the main loop is a tightly coupled core component. Modifying any part of the loop risks breaking the whole system. In Cordis, the agent main loop is just another plugin. It can be swapped out independently from tooling or model adapters.

1.2 Context: A Service Registry Container

The ctx context object acts as a shared service repository. Each service binds to a fixed key inside ctx, for example ctx.tools or ctx.llm. When plugins need to consume a service, they reference the key rather than importing concrete implementation code.

This delivers strong decoupling benefits. Developers can swap out the underlying LLM implementation without changing a single line of calling code, because the caller depends only on ctx.llm, not a specific model class. In monolithic projects, changing low-level implementations often triggers cascading dependency updates for upstream consumers. The Cordis context pattern eliminates that burden.

1.3 Dependency Declaration via Inject: Automatic Loading Order

Dependencies are declared inside the inject field. Cordis automatically resolves service dependencies and starts plugins in the correct sequence. Developers do not manually define long startup sequences or troubleshoot ordering conflicts.

Large-scale projects frequently suffer from hidden dependency bugs during initialization. Incorrect startup ordering triggers null pointer exceptions, which can take hours to diagnose. The inject declaration removes this class of operational risk.

1.4 Typed Event Communication: Dispatch Modes Codified as Contracts

Event communication and dispatch logic are formalized as part of the framework contract, not informal developer conventions. Cordis defines four native dispatch modes with explicit behavior specifications.

Dispatch ModeAwait RequiredDispatch OrderReturn Values
emit (Broadcast)NoRegistration orderNone
waterfallNoRegistration orderYes
parallelYesAll listeners run concurrentlyNone
serialYesRegistration orderYes

New events are annotated with @mode tags in documentation. Tooling automatically validates consistency between declared behavior and actual implementation. In many legacy systems, event behavior relies on tribal knowledge, which creates silent regressions whenever code changes. Formal contracts eliminate this ambiguity.

1.5 Reversible Plugin Registration

All registration actions — prompt segments, tool schemas, event listeners — are registered through ctx.effect() or ctx.on(). Plugins can be unregistered cleanly, rolling back all side effects along the original path.

Most plugin systems support one-way installation only. Once loaded, plugins cannot be unmounted at runtime. Hot reloading or dynamic feature toggles become impossible. Cordis’s reversible registration unlocks full two-way extension management.

2. Plugin Structure: Five Core Contract Fields

Harness plugins are native Cordis plugins. They do not rely on custom base classes or complex decorators. A plugin interface defines five optional fields in TypeScript:

export interface Plugin<T = any> {
  /** Display name for logging, diagnostics, fiber */
  name: string;
  /** Config schema validator, runs at plugin startup */
  config?: any;
  /** Dependencies this plugin requires */
  inject?: Inject;
  /** Services this plugin provides */
  provide?: string | string[];
}

One important breaking change: Cordis 4 removed the reusable field. Developers referencing older documentation often hit this pitfall when writing plugins.

2.1 Conditional Injection: Where Dependencies Are Declared

Dependencies are not always declared at the top-level inject array. Some dependencies are injected conditionally inside the apply function.

export const name = 'tool-presentation';
export const inject = ['tools'];
export interface Config {
  mode: ToolPresentationMode
}
export function apply(ctx: Context, config: Config) {
  const mode = config.mode
  if (mode === 'native') {
    // inject code runtime only for native mode
  }
}

In this example, codeRuntime is only required when native mode is active. Declaring it in the top-level inject array would force the dependency to load even for other modes, causing runtime failures. This pattern requires audit logging so missing dependencies are visible rather than silently ignored.

2.2 Configuration Is Also Part of the Contract

All adjustable parameters must live inside the config field and validated against Cordis schemas. Constants related to protocol behavior or security rules are hardcoded and cannot be modified at runtime.

This boundary is critical. Many projects blur this separation, embedding security-critical values as editable configuration. If an operator accidentally modifies security parameters, troubleshooting root causes becomes extremely difficult.

3. Capability Chaining: Why Plugins Do Not Fragment the Core

A natural question arises: when everything becomes a plugin, how can the system avoid collapsing into disjoint components? The answer is the capability chaining contract. A formal capability pipeline defines three roles for every interface: Service Definition, Service Provider, and Consumer.

This contract enforces separation of concerns. Interfaces define what can be done, providers implement the logic, and consumers invoke the interface without coupling to concrete implementations. This is the foundation of Harness’s composable extension model.

4. Agent Loop: Interceptable Extension Points

Codex splits agent execution into three discrete phases. Harness organizes execution into rounds and steps, inserting interceptable extension hooks between stages. Two key definitions clarify the runtime model:

  1. Step: A single model request plus all associated tool calls.
  2. Round: One or more steps. A round opens when input arrives and closes once the task finishes.

Zero-step rounds are valid. If a request is rejected immediately, an empty round record is persisted to logs. Many alternative systems discard rejected requests entirely, leaving no trace for debugging. This design preserves auditability even when requests are blocked before model invocation.

Harness splits events into three categories for scoped extension development:

  1. Conversation events: Persist across restarts, including message creation and tool invocation records.
  2. Lifecycle events: Triggered at the start and completion of rounds and steps.
  3. Internal events: Used for plugin coordination and not persisted.

Developers must carefully select event scopes. Writing state changes into the wrong event category can corrupt logs and break replay workflows.

5. Tool Execution Pipeline: Ten Carefully Designed Stages

The tool invocation workflow is one of Harness’s most sophisticated designs. It defines ten sequential stages with strict boundaries for what each stage may and may not modify.

5.1 Stage 1: Parameter Freeze

At the tool::call event, invocation parameters are written to logs and rendered as visual cards. After this stage, pre-processing logic cannot alter parameters. Once logged, the record is immutable. All subsequent execution must use the logged parameters. If parameters could mutate after logging, the visible audit record would diverge from actual runtime behavior, creating falsified logs. Modifications must happen before this freeze stage.

5.2 Stage 3: Polarity Guard — Reject Only, Never Modify

The polarity guard can only reject execution. It cannot alter request content. Once this stage completes, the result is frozen. Later stages observe the frozen result but cannot rewrite it. This creates a hard boundary: edits must occur before the guard, and observation occurs after freezing.

6. Conversation Logs: Anything Visible to the Model Must Be Recorded

Harness enforces a strict rule for persistence: any data sent to the model must be reconstructable purely from conversation logs. If new input types are introduced, they must first be appended to the conversation log.

This eliminates a common class of flaky bugs. Many agent systems suffer from replay divergence: when re-running past conversations, outputs differ from the original execution, caused by state that existed in memory but was never written to logs. Harness’s rule prevents this category of bug by design.

Context compression triggers at 80% of the token window threshold. When overflow occurs, the system preserves the original prompt, compresses a copy, and retries. Compression ratios are bounded to avoid truncating critical context.

7. Context Compression: Carefully Tuned Mechanics

There are two trigger conditions for compression: proactive pre-compression and overflow emergency compression. Compression requests reuse the same system and tools prompt headers as the primary request. Only the message body changes. This shared prefix enables KV cache hits on the server side.

Counterintuitively, dedicated independent prompts for compression often reduce cache utilization. Reusing the main request prefix improves cache hits and reduces overall token consumption. This optimization demonstrates the value of designing auxiliary operations as frontline variants of the primary request.

8. Profile and Composition: Art of Layered Assembly

Harness supports layered configuration merging. Operators can dump the final resolved configuration with a command:

dsh --profile web --dump-config

All output configuration entries can be patched individually. Every configurable value in the entire system exists as a retrievable entry. This transparency avoids black-box configuration behavior.

9. Host and Client: Two Boundary Gates

Two isolation layers enforce boundary safety:

  1. Project reference isolation: Scans scripts to validate import references.
  2. Client build isolation: Blocks imports of non-whitelisted packages during bundling.

Plain lint checks are insufficient here. These boundaries validate runtime dependencies that only surface during packaging, not static syntax analysis.

10. Sub-Agents: The Same Interface Can Wrap a Different Product

Sub-agents in Harness are ordinary plugins. They can spawn child agents, forward conversation state, or delegate tasks to external agent systems such as Codex and Claude Code via SDK.

The interface abstraction is clean enough that the caller cannot distinguish whether the sub-agent implementation comes from Harness itself or an external third-party agent product. This interoperability is valuable for multi-model systems. In production environments, teams often use an API gateway to standardize authentication and routing for diverse agent backends, and Treerouter fulfills this role.

11. Summary: Seven Most Valuable Design Lessons

Developers building custom agent platforms can adopt these seven design priorities, derived from Harness and Cordis:

  1. Reversible registration: Plugins can be unmounted cleanly, returning disposers to roll back side effects.
  2. Model-visible logging: All data sent to LLM must live in logs, eliminating replay divergence.
  3. Three-role capability contracts: Interface definition, provider implementation, and consumer invocation are strictly separated.
  4. Immutable parameters after freeze: Guards can reject execution, but cannot mutate requests.
  5. Structured artifact generation: Dependencies and directory layouts are generated from code rather than manual judgement.
  6. Transparent layered configuration: Dump commands expose fully resolved runtime configs, eliminating opaque black-box behavior.
  7. Auxiliary requests reuse primary prompt prefixes, improving cache efficiency.

Tradeoffs: No Free Lunch

This fully pluggable architecture carries unavoidable costs:

  1. Steep learning curve: Developers must master the five Cordis core concepts before extending the system.
  2. Boundary complexity: The separation between Host and Client arises from type system constraints rather than business requirements.
  3. Visibility overhead: Without dump commands, tracing the final merged configuration becomes difficult.
  4. Compatibility burden: Every plugin must maintain compatibility across framework upgrades.

Codex and DeepSeek Harness are not simply competing products. They represent opposite architectural choices. Codex retains privileged core modules to optimize raw execution speed. Harness trades some performance for full internal modularity and extensibility. The right choice depends on which components your team needs to lock in versus freely modify.

Learn more:https://treerouter.com