跪拜 Guibai
← Back to the summary

DeepSeek Harness: Webpack and Koa Were the Agent Framework All Along

DeepSeek Harness Turns Out to Be the Webpack and Middleware Model We Know

A front-end engineer's technical sharing after reading the Cordis source code

Target readers: front-end developers with React/Node experience but completely unfamiliar with Agent frameworks. Reading time: about 25 minutes. Environment: DeepSeek Harness v0.2.2-rc.2 / Cordis 4.1.0


I Thought I'd Have to Learn a Whole New Set of Things

The first time I opened the DeepSeek Harness (DSH) source code, I braced myself. An Agent framework, I figured, would be a pile of model calls, prompt engineering, and vector search, none of it relevant to my day-to-day React work.

But after reading the source of Cordis (the plugin framework under DSH), I found that:

The core of this thing, I recognize it all.

None of it is new. The only difference is that they're combined to drive an LLM loop.

This article explains exactly that: which familiar paradigms Cordis reuses, and where it does things we didn't expect.


Part 1: cordis.yml Is webpack.config.js

Look at the config file first

Webpack's config:

module.exports = {
  entry: './src/index.js',
  plugins: [
    new HtmlWebpackPlugin(),
    new MiniCssExtractPlugin(),
    new DefinePlugin({ ... }),
  ],
}

Cordis's config (cordis.yml):

- name: '@deepseek-ai/dsh-llm'
- name: '@deepseek-ai/dsh-session'
- name: '@deepseek-ai/dsh-tools'
- name: '@deepseek-ai/dsh-agent-loop'

The structure is completely isomorphic: one file lists a bunch of plugins, and the runtime assembles the app according to that list.

DSH's base composition package lists 99 entries in this way—model adapters, session logs, tool registries, sandboxes, approval, settings, telemetry, all written line by line.

The plugin shape is the same too

Webpack plugin:

class MyPlugin {
  apply(compiler) {
    compiler.hooks.emit.tap('MyPlugin', (compilation) => { ... })
  }
}

Cordis plugin:

export function apply(ctx: Context) {
  ctx.on('tools/pre-execute', (exec, next) => { ... })
}

It's the same apply function, receiving a "host object" and registering hooks on it.

The difference is Webpack passes you compiler, Cordis passes you ctx. ctx is much stronger than compiler—it's a service container + event bus + plugin registry + resource manager in one.

Key difference: who decides the order

This is the first thing that surprises front-end developers.

Webpack plugin execution order is determined by the position in the plugins array (plus things like stage/before/after).

Cordis doesn't look at array position.

I ran the experiment myself: swapping the order of greeter (provides a service) and consumer (consumes it) in cordis.yml produces identical results.

# This
- name: './consumer.ts'
- name: './greeter.ts'

# and this
- name: './greeter.ts'
- name: './consumer.ts'

# both output Hello, world! consistently

Why? Because entries in cordis.yml start concurrently. The docs say:

Entries are started concurrently, so their position in the list does not guarantee plugin order.

Order is determined by dependency declarations, not file position. Which leads to the next section—


Part 2: inject Is Dependency Injection, but Stronger Than import

The most familiar comparison for front-end developers

React Context:

const ThemeContext = createContext()

// provide
<ThemeContext.Provider value={theme}>
  <App />
</ThemeContext.Provider>

// consume
const theme = useContext(ThemeContext)

Cordis:

// provide (service)
class GreeterService extends Service {
  constructor(ctx) { super(ctx, 'greeter') }
}
ctx.plugin(GreeterService)

// consume (dependency injection)
export const inject = ['greeter']
export function apply(ctx) {
  ctx.greeter.greet('world')
}

Same "provide/consume" pattern, but Cordis adds two things:

  1. Compile-time type safety: declare module declaration merging gives type hints for ctx.greeter.
  2. Runtime scheduling guarantee: inject makes Cordis call apply only after dependencies are ready.

The second point is key, and it's why you can't use import.

Why can't you use import?

// ❌ Wrong
import { ToolsService } from '@deepseek-ai/dsh-tools'

Three reasons (from DSH's packages/client/AGENTS.md and docs/architecture.zh.md):

Reason Explanation Front-end analogy
Order import executes the module immediately, but the dependency service may not be registered yet Rendering before Context Provider exists
Replaceability ctx.tools may be any implementation; import hard-wires one implementation Hard-coding localStorage vs using an abstraction layer
Scope ctx.tools might be a registry scoped to a specific agent Global variable vs component-local Context

🎯 One sentence to remember: don't import, inject. Same principle as "don't use window.xxx directly, use React Context," just stricter.

A pit I fell into

Missing inject fails silently, and the symptom depends on how you access it:

// Method A: direct access
ctx.greeter.greet()
// → the plugin is skipped entirely; apply never runs

// Method B: safe query
ctx.get('greeter')?.greet()
// → runs but gets undefined

Worse: service names are strings, and TypeScript doesn't check them at all.

declare module { greeter: GreetingService }   // declared as greeter
super(ctx, 'gretter')                          // registered as gretter (extra t)
ctx.get('greeter')                             // looks up greeter → undefined, no error

I was stuck on this for half an hour.


Part 3: Middleware Model — The Most Interesting Part

If everything before was "as expected," the waterfall is the first design that surprised me.

The middleware we know

Koa:

app.use(async (ctx, next) => {
  const start = Date.now()
  await next()                          // ← calls next middleware
  ctx.set('X-Response-Time', Date.now() - start)
})

Express:

app.use((req, res, next) => {
  next()                                // ← same
})

Code before and after next() → onion model.

Cordis's waterfall is exactly the same

ctx.on('demo/transform', async (input, next) => {
  const downstream = await next()       // ← same as Koa
  return downstream.toUpperCase()       // ← take downstream result and transform
})

DSH's most core tools/pre-execute uses it this way:

ctx.on('tools/pre-execute', async (exec, next) => {
  if (needs rejection) return { kind: 'deny', reason: '...' }   // short-circuit
  return next()                                                  // pass through
})

Permission, sandbox, hooks all hang on this chain, using waterfall to "intercept or pass."

But I didn't expect: this thing is only 15 lines

I read the Cordis source (vendor/cordis/src/events.ts:246):

waterfall(...args: any[]) {
  const [thisArg, callbacks] = this._resolve('waterfall', args)
  const inner = args.pop()
  const dispatch = () => {
    const callback = callbacks.shift()          // ① take next listener
    if (!callback) return inner()               // ② none left → execute default
    let called = false
    const next = () => {
      if (called) throw new Error('next() called multiple times')
      called = true
      return dispatch()                          // ③ recursion!
    }
    return Reflect.apply(callback, thisArg, [...args, next])
  }
  return dispatch()
}

The core is just three things:

  1. shift() consumes listeners one by one (not by index, but by draining the array).
  2. next() equals recursively calling dispatch() — so code before and after it is yours.
  3. inner is the termination condition — if next() is never called, inner never runs.

💡 next() is not "jump to the next," it's "recurse into the next layer." That's the physical reason for the onion model.

Counterintuitive point: execution order and computation order are reversed

I ran an experiment:

const ls = [
  (n, next) => next() + 10,              // L1
  (n, next) => next() * 2,               // L2
  (n, next) => n > 100 ? -1 : next(),    // L3 (conditional short-circuit)
]

waterfall(ls, 5, () => 5)      // → 20
waterfall(ls, 500, () => 500)  // → 8

Listener execution order: L1 → L2 → L3. Value computation order: L3 → L2 → L1.

It's reversed! L1's +10 applies last, L3's short-circuit happens first.

I almost stepped on this when writing tools/post-execute—if you think "my plugin runs first so it handles first," the result will be completely wrong.

Another counterintuitive point: forgetting next() silently swallows everything

ctx.on('tools/pre-execute', (exec, next) => {
  return          // ← forgot next()
})

Result: all subsequent listeners are skipped, gate becomes undefined, and the pipeline crashes at undefined.kind.

So I set myself an iron rule:

🎯 Observational listeners must call next(). Not calling it means you think you're "passing through," but you're actually "vetoing."

Five dispatch modes: picking the wrong one is a semantic error

Cordis has five event dispatch modes, and DSH requires every event to annotate @mode:

Mode Semantics Front-end analogy DSH example
emit Synchronous broadcast, ignores return value dispatchEvent tools/result (final observation)
parallel Concurrent, waits for all Promise.all Parallel notifications
serial Sequential, first non-null return wins Array.find Sequential decisions
bail Synchronous version of serial Redux reducer Synchronous decisions
waterfall Wrapping middleware Koa middleware tools/pre-execute and others

Key distinction: tools/result is emit, not waterfall, because results are already deep-frozen—you can only observe, not modify.

🎯 emit is for broadcast observation, waterfall is for interception decisions.


Part 4: effect — Cleanup Stronger Than useEffect

Same concept

React:

useEffect(() => {
  const timer = setInterval(tick, 200)
  return () => clearInterval(timer)     // cleanup
}, [])

Cordis:

ctx.effect(() => {
  const timer = setInterval(tick, 200)
  return () => clearInterval(timer)     // disposer
})

Identical. The body runs on load, the returned function runs on unload.

But there's a essential difference

React's cleanup relies on developer discipline; forget to write it and you leak. Cordis's effect is runtime-enforced, the unload path always reaches the disposer.

I verified this difference by removing ctx.effect:

hearbeat plugin loading
tick tick tick
disposed            ← fiber already disposed
tick tick tick ...  ← still running!

And the process can't exit; you need Ctrl+C to stop it.

Root cause: fiber.dispose() only unloads the plugin, but nothing knows about that setInterval—without a disposer, clearInterval is never called.

💡 Cordis can only clean up what it knows about. What you don't register, it doesn't know and can't clean.

This explains why DSH is full of this kind of code

ctx.tools.register(defineTool({...}))   // registration is an effect; auto-unregistered on plugin unload
ctx.on('tools/pre-execute', handler)     // listener is an effect; auto-removed

You never see ctx.tools.unregister() or removeListener().

Plus: effects are the precondition for hot reload. If every registration didn't auto-revoke, a code change would add another registration, and it would crash after a few minutes.


Part 5: Dependency Injection Implementation — Epoch Fingerprint

This part I find the most unlike front-end.

Problem: how do you know when a plugin should start?

A plugin declares inject = ['tools', 'fs']. How does it know when those two services are ready?

Cordis's answer: compute a "dependency fingerprint" for each plugin

_refresh() {
  let epoch = `${this._revision}`
  for (const name of Object.keys(this.inject)) {
    const impl = this._store[name]
    if (!impl) {
      epoch = INACTIVE        // ← one missing dependency → INACTIVE
      break
    }
    epoch += ':' + impl.uid   // ← append each dependency's uid
  }
  this._setEpoch(epoch)
}

The epoch looks like:

"3:12:45:67"     // revision : uid₁ : uid₂ : uid₃

Whenever any dependency changes, the string changes. When the string changes, it triggers a reload:

if (epoch !== INACTIVE && oldEpoch === INACTIVE) {
  this._reload()      // ← this is where apply actually runs
}

This design brings an amazing capability

When a service is replaced, all plugins that depend on it reload automatically.

DSH uses this capability to the extreme:

The filesystem and process providers share the same execution world. Point them at a remote sandbox, and Bash, PTY, and LSP move over together, no provider-specific fork needed.

In plain terms: swap one provider and change the entire product.

# Local execution
- name: '@deepseek-ai/dsh-bash-local'

# Swap to sandbox execution (no other code changes)
- name: '@deepseek-ai/dsh-bash-sandbox'

This is the economic meaning of "everything is a plugin."

Architecture state machine

PENDING ──dependencies satisfied──> LOADING ──apply completes──> ACTIVE
   ↑                                                              │
   └────────────dependencies disappear────────────────────────────┘

apply is not called once at startup; it's called at the moment when dependencies go from missing to satisfied. Theoretically it can be called multiple times.


Part 6: So, What's Actually New About Agent Frameworks?

By now, all the mechanisms are familiar. So what's new?

The only new thing: that while loop

DSH's core code (packages/core/agent-loop/) is essentially:

while (there is work) {
  messages = assembleContext()
  response = callModel(messages)
  if (response has no tool call) break
  results = executeTools(response.tool_calls)
  log to session()
}

That's an Agent. A loop, plus "call model" and "execute tools."

Everything else—permissions, sandboxes, compression, planning, sub-agents, UI—is a plugin hanging on this loop's extension points.

Translate into our familiar language

DSH concept Front-end equivalent
agent-loop A Redux store + a while loop
session/event Redux action log (replayable)
tools/pre-execute Express middleware
ctx.tools A pluggable registry
inject React Context + dependency ordering
ctx.effect useEffect cleanup (enforced)
agent.ctx (scope) Component-level Context (not inherited by children)
cordis.yml webpack.config.js
Hot Reload Vite HMR

The genuinely new knowledge has only three pieces

  1. Streaming protocol: how StreamChunk assembles into a complete message, and why KV Cache requires "byte-for-byte consistency."
  2. Context engineering: context window is the hardest constraint for an Agent; how compression strategies are designed.
  3. Tool-calling protocol: how the model expresses "I want to call a tool," and how results are fed back.

Beyond that, your front-end knowledge is 100% transferable.


Conclusion: A Front-End Engineer's Takeaways

My biggest takeaway isn't "I learned Agent"

It's that excellent architecture ideas are cross-domain.

These are recombined in agent frameworks, and combined extremely rigorously.

Three suggestions for those who want to get started

① Don't start with architecture docs; run through the Cordis tutorial first

docs/cordis-tutorial/ has 7 chapters, each runnable independently. After the first 4, you'll have the foundation to understand everything.

② When you wonder "where does this feature belong," check this table

docs/architecture.zh.md has a table of "where new behaviors belong," mapping 20+ requirements to specific mechanisms. It's the most frequently consulted thing in the whole repo.

③ Don't be intimidated by README density

packages/core/agent-loop/README.zh.md is over 5,000 characters, but every concept in it you've now seen. Read what you understand first, then tackle what you don't.

Final sentence

Agent frameworks look like a new species; broken apart, they're old friends. Models will change, prompts will change, frameworks will change, but pluginization, middleware, dependency injection, and reversible side effects—these engineering paradigms won't.

Front-end developers transitioning to Agent development have the biggest advantage not in "writing UI," but in already being trained on these paradigms.