ChatGPTClaudeGrok / X / CursorGemini

Nested DSH plugins: ctx.plugin() and child fibers

Plugin DevelopmentPublished 2026-11-05Author: DeepSeek Plugin Market
DSH pluginctx.pluginFiberlifecycleDeepSeek Harness
When a plugin grows, should part of it become a child plugin? A concrete double-registration bug explains what ctx.plugin() creates and how unloads cascade.

A plugin goes from a hundred lines to eight hundred, and the first question is not performance. It is whether this block of logic belongs somewhere else. Splitting is fine, but split the wrong way and hot reload starts duplicating tools and timers.

A DSH plugin pattern that registers twice

A DSH plugin that registers twice is missing ctx, not structure. Start with a structure that looks reasonable and is quietly broken. The parent registers a tool and starts its own interval:

ts
export const name = 'report-plugin'
export const inject = ['tools']

export function apply(ctx: Context) {
  ctx.tools.register(defineTool({
    name: 'report',
    description: 'Generate a report.',
    parameters: {},
    async execute() { return 'ok' },
  }))
  setInterval(() => ctx.logger?.info?.('tick'), 5000)
}

The tool registration goes through ctx, so it is cleaned up. The interval does not, so every reload adds one more. That is usually the moment someone decides to split the code into a child plugin — but if the split still manages resources by hand, the problem just moves.

What ctx.plugin() actually creates

It creates a child fiber, not just a function call. The child inherits the parent context but keeps its own state and registration table.

  • Inherits: the child sees services provided above it;
  • Independent: it has its own state machine and can fail or unload alone;
  • Attached: when the parent unloads, the child follows.

The state machine matches a top-level plugin: PENDING, LOADING, ACTIVE, FAILED, UNLOADING, DISPOSED. The difference is the parent: not the root context, but the plugin that mounted it.

The one check that tells you whether you did it right: was the child mounted with the ctx the parent received, or with a separately created context? Only the former gets cascade unload; the latter starts a second, independent tree.

Splitting a DSH plugin: three ways, pick one

A DSH plugin has three ways to split, chosen by lifecycle boundary rather than line count. Splitting is not synonymous with "mount a child plugin". Three approaches solve different problems:

ApproachGood forCost
Extract plain functionsThe file is just longLifecycle stays shared
Mount an internal pluginThe block has its own deps or configAn extra context to debug
Publish a separate packageOther plugins will reuse itVersions, dependencies, releases

If the only problem is length, plain functions are enough. Mount a child plugin only when one of these is true:

  1. It needs its own inject, for example the parent does not need llm but the child does;
  2. It must be unloadable on its own, for example a background job behind a feature switch.

Why a DSH plugin unload cascades

The parent-child link is a scope relationship, not inheritance. Unloading works in four steps:

  1. The parent enters UNLOADING and revokes its own ctx-based registrations;
  2. Child plugins are unloaded recursively, each revoking its own;
  3. Grandchildren continue the recursion;
  4. Only then does the dispose() promise resolve.

Two details get skipped. First, disposers run in reverse registration order, but multiple async disposers run concurrently, not one after another; cleanup steps with ordering requirements must live inside one ctx.effect disposer that awaits them in sequence. Second, recursive unload only covers relationships built through ctx: connections created at module top level or listeners attached to globalThis fall outside it.

So before splitting, ask which resources in this block never touched ctx. If any exist, add ctx.effect first, then split.

A minimal DSH plugin example to verify

To verify a nested DSH plugin, count resources after five reloads, not whether it runs once. The example below moves a background task into a child plugin; the parent only assembles. Load it with --patch from scratch-plugin/src/:

ts
// parent.ts
export const name = 'report-parent'
export function apply(ctx: Context) { ctx.plugin(heartbeat) }

// heartbeat.ts
export const name = 'heartbeat'
export function apply(ctx: Context) {
  ctx.effect(() => {
    const timer = setInterval(() => console.log('[heartbeat] tick'), 5000)
    return () => clearInterval(timer)
  })
}

Verify in four steps, each with an observable result:

  1. Start with pnpm dsh web --patch ./scratch-plugin/cordis.yml and watch for heartbeat output;
  2. Change the interval in heartbeat.ts, save, and confirm the old timer stopped and the new interval applies;
  3. Remove the parent's patch row, restart, and confirm the heartbeat disappears with no residue;
  4. Trigger five reloads in a row and confirm exactly one heartbeat per interval, not five.

Step four is the important one. It proves idempotence — that loading repeatedly still leaves one copy — which is precisely what a mis-split child plugin breaks.

Four common DSH plugin mistakes

Most DSH plugin child-plugin mistakes are about ownership: registration, instances, dependencies, and decoupling. First, registering the child's tool in the parent as well. The child already did it; the parent adds a second copy and the model sees duplicate names.

Second, mounting the same module twice. Two ctx.plugin(heartbeat) calls mean two instances and two timers. For a singleton, provide a service once and let others inject it.

Third, a child depending on a parent service without declaring inject. The service may register after the child loads, and the child reads undefined inside apply.

Fourth, treating "extracted" as "decoupled". If the parent imports the child's internal functions, they are still one unit; real decoupling happens through services and events.

The value of a child plugin is a lifecycle boundary, not fewer lines. Draw the boundary wrong and you have only added a harder stack trace. For the basics of Context and inject, read Cordis primer; for the plugin-shape checklist, read DSH plugin development spec.

ChatGPTClaudeGrok / X / CursorGemini

FAQ

After hot reload, why does a child plugin registered with ctx.plugin() show two copies of its tool?

Because the child plugin was mounted on a context the parent does not own. Reloading clears only the parent's registrations. A child mounted through the parent's ctx is disposed with the parent; one mounted on a separate root context is not.

Do tools and timers inside a child plugin get cleaned up when the parent unloads?

It does, provided the child plugin was mounted with the parent ctx. Dispose recursively unloads child plugins, and their ctx-based registrations are revoked. Third-party listeners and global singletons are outside that mechanism and still need a ctx.effect disposer.

Does calling ctx.plugin() twice with the same module create two instances?

Calling ctx.plugin() twice creates two independent plugin instances, each with its own fiber and registrations. If you need a singleton, mount it once and let other plugins depend on the service it provides instead of mounting the module again.

If a child plugin's apply throws, does the parent fail too?

The child plugin's fiber enters FAILED while the parent itself keeps running, but the capability that child provided is missing. Check the startup log for the failing module, then confirm whether it was mounted as a child.

Related Terms

Fiber
A fiber is the runtime scope Cordis assigns to each loaded plugin, tracking its state and every registration it owns so they can be revoked together.— DeepSeek Harness docs
ctx.plugin()
ctx.plugin() is the API that mounts another plugin inside the current context, creating a child fiber that inherits the parent context and unloads with it.— DeepSeek Harness docs
dispose
dispose is the operation that ends a plugin instance, removing all its registrations, recursively unloading child plugins, and resolving only after async cleanup finishes.— DeepSeek Harness docs
inject
inject is the plugin field that declares required services; the framework waits for them before running apply and unloads the plugin if a required service disappears.— DeepSeek Harness docs

Sources