Skip to content
DeepSeek Harness: Ship Your First dsh Plugin Bundle — ContentBuffer guide

DeepSeek Harness: Ship Your First dsh Plugin Bundle

K
Kodetra Technologies··15 min read Intermediate

Summary

Build a custom tool plugin for DeepSeek's new open-source agent harness, then ship it as a bundle.

DeepSeek open-sourced DeepSeek Harness on August 13, 2026, and the repo went vertical almost immediately — one tracker clocked 95,000+ stars inside two days, and it has kept climbing since. Most of the coverage stopped at "run npx @deepseek-ai/dsh web and look, a free coding agent." That misses the interesting part.

The interesting part is the architecture. In dsh, everything is a plugin — the model adapter, the tool registry, the session log, and the agent loop itself. There is no privileged core to fork. You extend the harness by mounting a plugin beside the others, and every registration is a reversible effect that unwinds when its plugin unloads. That means a capability you add is a first-class citizen, not a monkey patch.

This guide walks the whole path for a real capability: a changelog_add tool that lets the agent append entries to your project's CHANGELOG. You will register it, make it configurable, give it a UI card, then package it as an installable bundle and mount it in a profile. Everything here is checked against the official repository docs as of August 18, 2026.

What you will build

A three-file npm package called dsh-changelog that any dsh user can install with one command. The agent gets a tool that:

  • takes an entry plus a section (Added / Changed / Fixed / Removed)
  • inserts a bullet into the ## [Unreleased] block of a Markdown changelog
  • returns a structured value — { file, section, line } — not prose the caller has to parse
  • reads its file path and allowed sections from user configuration, so two deployments can differ without a code edit
  • cancels cleanly when the agent aborts the turn

The same shape works for anything you would otherwise bolt on with a shell script: a ticket creator, an internal search, a deploy trigger, a schema linter.

Prerequisites

  • Node.js 22.19+ or 24+. CI covers 22.19, 24, and 26.
  • pnpm through Corepack. The repo pins pnpm@11.7.0; run corepack enable if pnpm --version does not resolve through Corepack.
  • Git 2.26+ — the install hooks use Git's worktree-specific configuration extension.
  • A DeepSeek API key in DEEPSEEK_API_KEY (env var or a gitignored .env at the repo root). DEEPSEEK_BASE_URL is optional and defaults to the public API.
  • Working TypeScript knowledge. Cordis knowledge is not assumed — the parts you need are explained below.

Step 1 — Get a source checkout running

npx @deepseek-ai/dsh web is the fastest way to see the product, but plugin development wants a checkout so you can iterate against local source:

git clone https://github.com/deepseek-ai/deepseek-harness.git
cd deepseek-harness
pnpm install
pnpm run build

pnpm install also wires up worktree-local Lefthook hooks and a translation merge driver. If dependencies came from cache and postinstall was skipped, run node scripts/install-lefthook.mjs yourself.

Confirm the toolchain before you write a line of plugin code:

pnpm run typecheck   # must exit 0
pnpm dsh web         # opens http://127.0.0.1:3080

Now look at what your machine actually boots. This is the single most useful debugging command in the whole system:

pnpm dsh --profile web --dump-config

It prints the composed plugin tree — every row, with its id and config. Any row it prints can be replaced by a patch of your own. Keep that output open in a second terminal; when your plugin misbehaves, the first question is always "is my row actually in the tree, and with what config?"

Step 2 — The plugin contract in 8 lines

A Harness plugin is a TypeScript module that exports an apply function. The framework calls it at load time and hands you a ctx through which you register capabilities. Create a scratch project at the repo root:

mkdir -p scratch-plugin/src

scratch-plugin/src/changelog.ts, minimal version:

import type { Context } from '@deepseek-ai/cordis'

export const name = 'changelog-tool'

export function apply(ctx: Context) {
  console.log('[changelog-tool] loaded')
}

To mount it, write a patch overlay. Run pwd at the repo root first — the plugin path must be absolute. Create scratch-plugin/cordis.yml:

- insert:
    - id: changelog
      name: '/absolute/path/to/deepseek-harness/scratch-plugin/src/changelog.ts'
pnpm dsh web --patch ./scratch-plugin/cordis.yml

The terminal prints [changelog-tool] loaded during startup. That is the whole loading contract. Two properties matter later:

  • Registrations are effects. Event listeners, tools, and timers registered through ctx are torn down when the plugin unloads. You never call removeListener.
  • Foreign resources need ctx.effect(). For anything Cordis does not own — a socket, an interval — return a disposer: ctx.effect(() => { const t = setInterval(fn, 5000); return () => clearInterval(t) }).

Step 3 — Register a real tool

Tools go on ctx.tools. Declaring inject = ['tools'] makes Cordis wait for the registry before calling apply, so ctx.tools is guaranteed present. defineTool gives you typed args inferred from your parameter schema and validates model-generated arguments before execute ever runs.

Here is the full tool. Replace scratch-plugin/src/changelog.ts:

import { readFile, writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import type { Context } from '@deepseek-ai/cordis'
import { defineTool } from '@deepseek-ai/dsh-tools'

export const name = 'changelog-tool'
export const inject = ['tools']

const FILE = 'CHANGELOG.md'
const SECTIONS = ['Added', 'Changed', 'Fixed', 'Removed']
const UNRELEASED = '## [Unreleased]'

export function apply(ctx: Context) {
  ctx.tools.register(defineTool({
    name: 'changelog_add',
    description:
      'Append one bullet to the Unreleased section of the project CHANGELOG. ' +
      `Allowed sections: ${SECTIONS.join(', ')}.`,
    parameters: {
      entry: {
        type: 'string',
        required: true,
        description: 'One line, imperative mood, no leading dash',
      },
      section: {
        type: 'string',
        required: true,
        description: `One of: ${SECTIONS.join(', ')}`,
      },
    },
    output: {
      schema: {
        type: 'object',
        properties: {
          file: { type: 'string' },
          section: { type: 'string' },
          line: { type: 'number' },
        },
      },
      render: (args, value) => [{
        type: 'text',
        text: `Added to ${value.file} under ${value.section} at line ${value.line}: ${args.entry}`,
      }],
    },

    async execute(args, exec) {
      // The DSL validated types and required keys. Cross-field and
      // "non-empty string" rules are still yours to check.
      const section = args.section.trim()
      if (!SECTIONS.includes(section)) {
        throw new Error(`Unknown section "${section}". Allowed: ${SECTIONS.join(', ')}`)
      }
      const entry = args.entry.trim().replace(/^[-*]\s*/, '')
      if (!entry) throw new Error('entry must not be empty')

      const file = resolve(process.cwd(), FILE)
      const text = await readFile(file, { encoding: 'utf8', signal: exec.signal })
      const lines = text.split('\n')

      const head = lines.findIndex((l) => l.trim() === UNRELEASED)
      if (head === -1) throw new Error(`${FILE} has no "${UNRELEASED}" heading`)

      // Find the section heading inside the Unreleased block, then skip
      // past any bullets already under it so we append rather than prepend.
      let at = -1
      for (let i = head + 1; i < lines.length; i++) {
        if (lines[i].startsWith('## ')) break            // next release block
        if (lines[i].trim() !== `### ${section}`) continue
        at = i + 1
        while (at < lines.length && lines[at].trim().startsWith('-')) at++
        break
      }
      if (at === -1) {                                    // section absent: create it
        lines.splice(head + 1, 0, '', `### ${section}`)
        at = head + 3
      }

      lines.splice(at, 0, `- ${entry}`)
      await writeFile(file, lines.join('\n'), { encoding: 'utf8', signal: exec.signal })

      return { file: FILE, section, line: at + 1 }
    },
  }))
}

Restart with the same --patch flag and ask the agent in the Web UI:

Add a changelog entry under Fixed: retry token refresh on 401 instead of failing the request.

What you should see

Given a CHANGELOG.md that starts like this:

# Changelog

## [Unreleased]

### Added
- streaming responses on the /chat endpoint

## [1.4.0] - 2026-07-30

...the tool result rendered back to the model is:

Added to CHANGELOG.md under Fixed at line 9: retry token refresh on 401 instead of failing the request

...and the file becomes:

# Changelog

## [Unreleased]

### Fixed
- retry token refresh on 401 instead of failing the request

### Added
- streaming responses on the /chat endpoint

## [1.4.0] - 2026-07-30

Why the return value is an object, not a sentence

This is the design rule most people get wrong on their first tool. execute returns one canonical JSON value matching output.schema. The registry snapshots it as lossless JSON, validates it, freezes it, and only then hands it to output.render to produce the model-facing text.

Keeping those separate buys you something concrete: in Code Mode, every visible registered tool is callable as await tools.changelog_add(args) with zero extra integration, and the call resolves to the canonical value — { file, section, line } — not to rendered prose. Generated ToolArgsMap and ToolOutputMap types come from the same schema. If you had returned a sentence, every programmatic caller would be writing a regex.

Design output.schema as a real API. Return handles and fields. Keep the human explanation in render.

Step 4 — Make it configurable

Harness has an explicit rule here: anything two deployments might want to set differently must be a configuration field. The test is whether cordis.yml can change the value without a code edit. Our hardcoded FILE, SECTIONS, and UNRELEASED all fail that test.

Export a Config type and a same-named Schemastery schema with the defaults on the fields:

import Schema from '@deepseek-ai/schemastery'

export const name = 'changelog-tool'
export const inject = ['tools']

export interface Config {
  file: string
  sections: string[]
  unreleasedHeading: string
}

export const Config: Schema<Config> = Schema.object({
  file: Schema.string().default('CHANGELOG.md'),
  sections: Schema.array(Schema.string()).default(['Added', 'Changed', 'Fixed', 'Removed']),
  unreleasedHeading: Schema.string().default('## [Unreleased]'),
})

export function apply(ctx: Context, config: Config) {
  ctx.tools.register(defineTool({
    name: 'changelog_add',
    description:
      'Append one bullet to the Unreleased section of the project CHANGELOG. ' +
      `Allowed sections: ${config.sections.join(', ')}.`,
    // ...parameters and output as before, reading config.sections
    async execute(args, exec) {
      const file = resolve(process.cwd(), config.file)
      // ...same body, using config.unreleasedHeading and config.sections
    },
  }))
}

Then set values on the row:

- insert:
    - id: changelog
      name: '/absolute/path/to/deepseek-harness/scratch-plugin/src/changelog.ts'
      config:
        file: docs/CHANGELOG.md
        sections: [Added, Fixed, Security]

Cordis validates against your schema at load time and fills defaults. Invalid config fails the load with an actionable error instead of surfacing as a mystery at turn 40. Note the interaction with hot reload: editing config hot-replaces the plugin — the old instance unloads and a new one loads — and because registrations are effects, the old tool registration does not survive.

One trap: do not export a plain object as Config. Cordis requires the Standard Schema interface, which a bare object does not implement.

Step 5 — Give the tool a UI card

output.render produces what the model sees. What the user sees in the Web UI is a separate concern, declared with optional presentCall and presentResult methods that return a card-tagged render intent. A tool with no presentation falls back to a generic card showing the tool name and raw args.

Three card kinds ship today: generic, terminal (your call is a shell command), and diff (your call creates or modifies a file). A changelog edit is tempting to render as a diff, but there is a hard constraint that rules it out — see below. Use a generic card with a file location:

presentCall: (args) => ({
  card: 'generic',
  title: `changelog: ${args.section}`,
  kind: 'edit',
  locations: [{ path: config.file }],
}),

The purity rule. Presenters run on live streaming and on session-log replay, so they must be pure functions of their arguments. No I/O, no session state, no clock, no random. That is why tool-fs's write emits oldText: null in its diff — a call-time presenter has no prior file content. If you want a true before/after diff for the changelog, the old text has to reach the result card as durable metadata via output.presentationMeta(args, value), which the core persists on tool/result so replay reproduces it. Reaching for readFile inside presentCall will pass in dev and corrupt every replay afterward.

Second rule worth internalizing: UI-only formatting stays out of the model result. A fenced console block or a relativized path does not belong in the canonical value just to make a card look nice.

Step 6 — Package it as a bundle

--patch overlays are for development. To distribute, you ship a bundle: an npm package that contributes a configuration layer. Two concepts, both described by package.json, answering different questions:

  • A bundle declares dsh.bundle — "what does this package contribute?" A patch file that inserts or overrides plugin rows.
  • A profile is a directory under $DSH_HOME/profiles/<name> declaring dsh.profile — "which bundles compose this setup, in what order?"

You author bundles. Users boot profiles. Nothing is both, and you never hand-write a profile manifest — dsh plugin maintains it.

dsh-changelog/
├── package.json       # declares dsh.bundle
├── cordis.patch.yml   # the layer applied when a profile lists this bundle
└── index.js           # the plugin module the patch rows reference
{
  "name": "dsh-changelog",
  "version": "0.1.0",
  "type": "module",
  "main": "index.js",
  "files": ["index.js", "cordis.patch.yml"],
  "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
}

The patch is the same YAML shape as your dev overlay, except rows reference the package name instead of an absolute source path, so Node resolution finds the installed code:

- insert:
    - id: changelog
      name: dsh-changelog
      config:
        file: CHANGELOG.md
        sections: [Added, Changed, Fixed, Removed]

A package without dsh.bundle still installs, but only as a plain dependency — dsh plugin warns and activates no layer. That is the right format for a library other plugins import, not for a plugin users enable.

Install into a profile

dsh plugin --profile <name> <args...> forwards to pnpm inside the profile directory, so every pnpm verb works:

dsh plugin --profile demo add ./dsh-changelog
dsh --profile demo --dump-config    # look for a "# == dsh-changelog" layer
dsh --profile demo

First use initializes the profile with @deepseek-ai/dsh-base as its first bundle, links your checkout, and appends your bundle to dsh.profile.bundles. Removal is symmetric: dsh plugin --profile demo remove dsh-changelog drops both the dependency and the layer.

The layer order (memorize this)

Effective configuration composes over an empty root in this order:

  1. each bundle patch in dsh.profile.bundles order — @deepseek-ai/dsh-base first
  2. the profile's own cordis.patch.yml
  3. the home-level $DSH_HOME/cordis.patch.yml (machine-local preferences, shared by every profile)
  4. each --patch <path> overlay, in argv order

Later layers win per row. Critically, a patch replaces a row's entire config value — it does not deep-merge keys. If you override a row to change one field, restate every key that row needs. This is exactly how dsh-web-app overrides dsh-base rows, and it is the number one source of "my plugin lost its settings" confusion.

Step 7 — Run it headless in CI

The headless profile is a one-shot runner with no HTTP server, no Web runtime, and no listening port. It rides directly over dsh-base, supplies the coding persona, disables HMR, and mounts Code Mode's worker.

export DEEPSEEK_API_KEY=sk-...
pnpm dsh --profile headless --patch ./scratch-plugin/cordis.yml \
  "Add a changelog entry under Fixed for the 401 retry bug fixed in src/auth.ts" 

The runner creates one fresh persisted agent, submits your task as an ordinary user message, waits for quiescence, writes the last non-empty assistant text to stdout, and exits. Exit code is 0 when the final turn/end completed and 1 otherwise; a terminal error also writes its code and message to stderr. A successful run leaves stderr empty — which makes it clean to gate a CI job on.

Two limits to plan around: the runner accepts exactly one task with no interactive follow-up, and ctx.appExit is launcher-owned, so booting the headless profile outside the dsh launcher fails loudly at activation.


Pitfalls that will bite you

Most of these come from the docs' own "hard rules" sections, which exist because people hit them.

  • Relative plugin paths in a --patch overlay silently fail to resolve. A patch file contributes configuration but does not change the profile directory the loader resolves module paths from. Use absolute paths in dev overlays; use package names in bundle patches.
  • Exporting a plain object as Config. It does not implement Standard Schema and Cordis will not accept it. Use Schemastery.
  • Assuming config deep-merges. It does not. A patch replaces the whole config value for a row id.
  • Mutating the tool definition after registration. Registration borrows your readonly definition; a same-process typed contribution is not a serialization boundary. To hot-swap a tool, dispose its owning effect and register the replacement. Mutable state inside your callback's closure is fine — it is ordinary plugin state.
  • Treating args as writable. The registry materializes arguments as detached lossless JSON and freezes them before policy runs. callId, name, arguments, agent, and token stay immutable through dispatch.
  • Returning content blocks from execute. Return the canonical value; render makes content. Throwing, or returning a value that fails schema validation, marks the call isError.
  • Confusing infrastructure failure with domain outcome. Throw for infrastructure failures. A successful call with a non-ideal result — a non-zero process exit, a section that had to be created — belongs in the canonical value, with the renderer explaining it.
  • Impure presenters. No I/O, no clock, no random in presentCall/presentResult. They run on replay. If you need result-time facts, project them through output.presentationMeta.
  • Ignoring exec.signal. It is a required field on every execution. Thread it into your I/O calls and cancel in-flight work when it fires.
  • Fire-and-forget background work. Use ctx.jobs.start({ kind, label, owner: exec.agent, run }) and return a typed handle like { kind: 'background', jobId }. Once the job id is published, outer-call cancellation stops waiting but does not kill the work — job_kill, owner disposal, and service teardown own that lifetime.
  • Expecting agent.inject() to wake an idle agent. It appends durable context the next model request will see. An idle agent stays idle. Wrap it in try/catch against disposed agents.
  • Baking deployment policy into the tool. Allow/deny/ask belongs in tools/pre-execute; a final non-reversible deny belongs in ctx.tools.guard(); deadlines, retries, and metrics belong in tools/execute.
  • Installing a bundle straight from GitHub without reading the fine print. A git install fetches sources, not build output, so a TypeScript package arrives with no lib/ and fails to load. Authors ship a self-contained prepare script; users must allowlist it in the profile's pnpm-workspace.yaml under allowBuilds. Be clear-eyed about what that allowance is: permission to execute the package's code on your machine at install time, outside any sandbox the agent runs under. Pin a commit SHA (github:you/pkg#<sha>) so a later push cannot silently change what runs. Publishing prebuilt to npm, or shipping a pnpm pack tarball, needs no build permission at all.
  • Forgetting this is a developer preview. The README says it plainly: there will be compatibility-breaking changes. Pin your dsh version and read the changelog before upgrading.

Quick reference

Where new behavior attaches, straight from the architecture map:

GoalMechanism
Add a model-facing capabilityctx.tools.register(defineTool(...)) — schema joins prompt assembly
Add a model providerregister its adapter on ctx.llm
Add a human command (no model turn)register on ctx.commands
Add background workctx.jobs.start(...); job_* tools collect or stop it
Add shell executionregister a ctx.shell backend
Add filesystem access or policyregister a ctx.fs provider or listen to fs/*
Confine spawned processesuse a ctx.sandbox backend
Intercept a request, tool, or turnagent/* or tools/* events; agent/turn-stopping stops a turn
Add model-facing contextagent.inject() — lands in the next admitted request
Add durable session stateextend SessionEventMap; render and replay from the log
Fork a live sessionctx.sessions.fork(source, boundary?, childSessionId?)
Scope a registration to one agentuse that agent's agent.ctx

Commands worth keeping in muscle memory:

CommandWhat it does
npx @deepseek-ai/dsh webWeb UI on http://127.0.0.1:3080
pnpm dsh web --patch ./x/cordis.ymlboot with a local dev overlay
dsh --profile web --dump-configprint the composed plugin tree
dsh plugin --profile demo add ./pkginstall a bundle into a profile
dsh plugin --profile demo remove pkgdrop the dependency and the layer
dsh --profile headless "task"one-shot run, last assistant text to stdout

And the turn flow, so you know which event you actually want:

turn/start
  claim next-step input + one queued message
  assemble prompt sections + tool schemas
  -> agent/pre-step            reject | enter(messages)
     step/start
     agent/request -> llm/stream -> assistant/chunk* -> assistant/message
     tool/call* -> tools/pre-execute -> tools/execute -> tools/post-execute -> tool/result*
     step/end
  -> agent/turn-stopping
turn/end

agent/pre-step, agent/request, llm/stream, and the three tools/* events are waterfalls — listeners must call next() to delegate. agent/turn-stopping is serial and has no next().


Next steps

  • Add a policy gate. Listen on tools/pre-execute to require approval before changelog_add touches a protected branch's file. Keep the policy out of the tool.
  • Split the capability into three packages. Service Definition, Service Provider, Consumer. That is what makes one provider swap change the whole product — point the filesystem and subprocess providers at a remote sandbox and Bash, PTY, and LSP move with them.
  • Write an LLM adapter. Register on ctx.llm and run the harness against a model DeepSeek never shipped support for.
  • Publish it. Add the dsh-plugin topic to your repo for discoverability, then pnpm publish with lib/ built so users skip the build-permission dance entirely.

The bet DeepSeek is making with this architecture is that the harness — tool definitions, filesystem and shell access, memory and context management, sub-agent orchestration, loop control, and critically when execution stops — matters at least as much as the model. Whether that bet pays off is an open question. But it does mean the extension surface is unusually honest: if the agent loop itself is a plugin, then so is anything you want to replace about it.


Sources

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get