Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

DeepSeek Harness Plugin Lifecycle: Fiber State Machine

DeepSeek Harness Plugin Lifecycle: Fiber State Machine

In the previous chapters, we have learned how to register event listeners and tools, and how to use ctx.effect() to manage resources.

But when do these registrations take effect? And how are event listeners and tools cleaned up when a plugin is unloaded?

DeepSeek Harness uses the Cordis plugin model to manage these processes. Each plugin instance has a corresponding Fiber, responsible for tracking plugin state, dependencies, and resources that need cleanup.

This section introduces the Fiber lifecycle, dependency-driven loading, automatic cleanup mechanisms, as well as manual unloading and hot replacement of plugins.

What is a Fiber?

A Fiber is an object in Cordis that represents a running instance of a plugin.

When a plugin is loaded, the framework creates a corresponding Fiber to manage the plugin's lifecycle.

A Fiber is mainly responsible for the following tasks:

can be used via ctx.fiber Get the Fiber the current plugin belongs to.

For example:

export function apply(ctx: Context) {

  const fiber = ctx.fiber



  console.log(fiber.state)

}

Wherefiber.state Indicates the current lifecycle state.

**Note:** a plugin module and a Fiber are not exactly the same. The same plugin can be applied to different contexts, and each loaded instance can have its own independent Fiber.

Fiber state machine

A Fiber uses a state machine to manage the process of a plugin from loading to unloading.

A plugin that loads normally and is eventually unloaded usually goes through the following states:

PENDING → LOADING → ACTIVE → UNLOADING → DISPOSED

If an error occurs during plugin loading, it may enter FAILED status.

DeepSeek Harness Fiber lifecycle state machine

The meaning of each state is as follows:

State Meaning When it occurs
PENDING Pending loading The plugin has been declared, but the required service dependencies are not all ready
LOADING Loading Dependencies are satisfied and the plugin's initialization logic is being executed
ACTIVE Active Plugin initialization is complete and it is in normal running state
FAILED Load failed An error occurred during plugin initialization or related configuration validation
UNLOADING Unloading The framework is revoking registrations and releasing plugin resources
DISPOSED Disposed The plugin instance has been disposed and related lifecycle resources have been cleaned up

For example, a normally loaded plugin first enters LOADING, and the code in the apply() for initialization, and after success enters ACTIVE。

When the plugin needs to be unloaded, it enters UNLOADING, performs the corresponding resource cleanup, and after completion enters DISPOSED。

If initialization fails, the plugin may enter FAILED. Specific errors need to be checked through logs or diagnostic interfaces provided by the framework, and not all loading failures should be understood as missing dependencies.

Dependency-driven loading

Cordis supports deciding the loading timing of plugins based on service dependencies.

A plugin can use inject to declare which services it depends on.

For example, a plugin needs to use the tool registration service tools and the large language model service llm。

Example

// File: scratch-plugin/src/my-plugin.ts

import

type

{

Context

}

from

'@deepseek-ai/cordis'

// Declare required service dependencies

export

const

inject

=

[

'tools'

,

'llm'

]

export

function

apply

(

ctx

:

Context

)

{

 

// The plugin only loads after required services are ready

  console.

log

(

'plugin starts loading'

)

 

// ctx.tools and ctx.llm can be used

  console.

log

(

'dependency services are ready'

)

}

When tools or llm When not yet ready, the plugin waits for dependencies and does not execute immediately apply()。

Only after all required services are ready will Cordis load the plugin.

This way developers do not need to manually write complex initialization sequences.

What happens when a dependency disappears?

Cordis's dependency mechanism affects not only the first loading of a plugin, but also plugins already running.

For example:

  1. The plugin depends on the tools and llm service.
  2. After both services are ready, the plugin enters the running state.
  3. During operation,llm the service is unloaded or replaced.
  4. Cordis automatically unloads plugins that depend on that service and cleans up old registrations.
  5. When the required service becomes ready again, the plugin can be reloaded.

This means that when a dependency service changes, the framework can automatically manage the unloading and re-initialization of related plugins.

Note that automatic reloading does not mean restoring all runtime data in the old plugin. If a plugin needs to preserve state after reloading, it should be achieved through appropriate external storage or state management mechanisms.

Automatic cleanup mechanism

At runtime, a plugin may register event listeners, tools, LLM adapters, or create timers or network connections.

If these resources are not cleaned up when unloading, it may lead to duplicate listeners, duplicate registrations, or resource leaks.

Cordis's lifecycle mechanism tracks resources created through managed registration APIs and revokes the corresponding registrations when the plugin is unloaded.

Common operations are as follows:

Registration operation Behavior on unload
ctx.on(event, handler) Automatically remove event listeners registered by the plugin
ctx.tools.register(tool) Revoke tools registered by the plugin
ctx.llm.registerAdapter(...) Revoke LLM adapters registered by the plugin
ctx.plugin(child) When a parent plugin is unloaded, associated child plugins are also disposed
ctx.effect(...) Execute registered resource release functions

Therefore, for registrations managed by the Cordis lifecycle, developers usually do not need to manually write corresponding unloading logic.

But for timers, file watchers, or network connections created directly using Node.js APIs, the framework may not be able to track them automatically, and need to use ctx.effect() for explicit management.

How ctx.effect() works

ctx.effect() Used to register operations with automatic cleanup capability.

It receives a function that is executed immediately upon registration and returns a disposer (Disposer) used to release resources.

For example:

Example

import

type

{

Context

}

from

'@deepseek-ai/cordis'

export

function

apply

(

ctx

:

Context

)

{

  console.

log

(

'plugin starts loading'

)

  ctx.

effect

(

(

)

=>

{

    console.

log

(

'resource initialized'

)

   

// Return the cleanup function

   

return

(

)

=>

{

      console.

log

(

'resource cleaned up'

)

   

}

 

}

)

}

Output when loading:

插件开始加载

资源初始化

Output when the plugin is unloaded:

资源已清理

Here we need to distinguish two execution timings:

Therefore,ctx.effect() is not a callback interface that is only executed at unload time.

Example: managing a timer

Below we use ctx.effect() to create a timer and automatically clean it up when the plugin is unloaded.

Example

// File: scratch-plugin/src/timer-plugin.ts

import

type

{

Context

}

from

'@deepseek-ai/cordis'

export

const

name

=

'timer-plugin'

export

function

apply

(

ctx

:

Context

)

{

  ctx.

effect

(

(

)

=>

{

   

// Create a timer

   

const

timer

=

setInterval

(

(

)

=>

{

      console.

log

(

'timer running'

)

   

}

,

1000

)

    console.

log

(

'timer started'

)

   

// Clean up when the plugin is unloaded

   

return

(

)

=>

{

      clearInterval

(

timer

)

      console.

log

(

'timer stopped'

)

   

}

 

}

)

}

After the plugin is loaded, the console will output:

timer started

timer running

timer running

...

When the plugin is unloaded, the cleanup function calls clearInterval(timer) to stop the timer and output:

timer stopped

This approach puts resource creation and release in the same place, reducing the risk of missing cleanup operations.

Execution order of disposers

A plugin may register multiple resources that need cleanup.

When a Fiber is unloaded, disposers start executing in reverse order of registration.

For example:

Example

import

type

{

Context

}

from

'@deepseek-ai/cordis'

export

function

apply

(

ctx

:

Context

)

{

  ctx.

effect

(

(

)

=>

{

    console.

log

(

'register resource A'

)

   

return

(

)

=>

{

      console.

log

(

'clean up resource A'

)

   

}

 

}

)

  ctx.

effect

(

(

)

=>

{

    console.

log

(

'register resource B'

)

   

return

(

)

=>

{

      console.

log

(

'clean up resource B'

)

   

}

 

}

)

}

Output when loading:

注册资源 A

注册资源 B

When unloading, the two synchronous disposers usually execute in the following order:

清理资源 B

清理资源 A

The rule here isstart cleanup in reverse order, not that all asynchronous cleanup tasks are strictly completed in series.

What should be noted about asynchronous cleanup?

If a disposer contains asynchronous operations, the framework waits for the related asynchronous cleanup tasks to complete, but multiple asynchronous disposers are not guaranteed to finish one by one in registration order.

For example, when you need to close a session first and then a database connection, the two steps should not be split into mutually independent asynchronous disposers.

A more reliable way is to put cleanup processes with sequential dependencies in the same disposer.

Example

import

type

{

Context

}

from

'@deepseek-ai/cordis'

// The following functions are for illustration and need to be provided by the actual application

declare

function

createConnection

(

)

:

{

  startSession

(

)

:

{

    close

(

)

:

Promise

<

void

}

close

(

)

:

Promise

<

void

}

export

function

apply

(

ctx

:

Context

)

{

  ctx.

effect

(

(

)

=>

{

   

// Create the connection and session

   

const

connection

=

createConnection

(

)

   

const

session

=

connection.

startSession

(

)

   

// Perform cleanup operations in order

   

return

async

(

)

=>

{

      await session.

close

(

)

      await connection.

close

(

)

   

}

 

}

)

}

In the above code:

  1. First execute session.close()。
  2. and wait for the session to finish closing.
  3. Then execute connection.close()。

Note thatcreateConnection() are illustrative functions, not built-in Cordis APIs.

Manually unloading a plugin

In addition to dependency changes and hot replacement, Cordis also supports actively unloading plugins.

Pass ctx.plugin() When loading a plugin, you can obtain the corresponding Fiber and call it when needed dispose()。

Example

import

type

{

Context

}

from

'@deepseek-ai/cordis'

function

myPlugin

(

ctx

:

Context

)

{

  console.

log

(

'child plugin loaded'

)

  ctx.

effect

(

(

)

=>

{

   

return

(

)

=>

{

      console.

log

(

'child plugin cleaned up'

)

   

}

 

}

)

}

// The following demonstrates loading and unloading a plugin in an existing Context

async

function

demo

(

ctx

:

Context

)

{

 

// Load the plugin to get the Fiber

 

const

fiber

=

ctx.

plugin

(

myPlugin

)

 

// Manually unload the plugin

  await fiber.

dispose

(

)

  console.

log

(

'child plugin disposed'

)

}

When the plugin has loaded normally and executed the above process, the output is:

child plugin loaded

child plugin cleaned up

child plugin disposed

fiber.dispose() returns a Promise, and waiting for that Promise to complete indicates that the related unloading and asynchronous cleanup operations have finished.

It also recursively disposes child plugins owned by that plugin.

Parent plugins and child plugins

Cordis allows plugins to ctx.plugin() load other plugins.

Each child plugin has its own Fiber, so it can manage its lifecycle and resources independently.

For example:

Example

import

type

{

Context

}

from

'@deepseek-ai/cordis'

function

childPlugin

(

ctx

:

Context

)

{

  console.

log

(

'child plugin loaded'

)

  ctx.

effect

(

(

)

=>

{

   

return

(

)

=>

{

      console.

log

(

'child plugin cleaned up'

)

   

}

 

}

)

}

export

function

apply

(

ctx

:

Context

)

{

  console.

log

(

'parent plugin loaded'

)

 

// Register the child plugin

  ctx.

plugin

(

childPlugin

)

}

A child plugin is created through the parent plugin's context, but has an independent running instance.

When a parent plugin is unloaded, the framework also disposes its associated child plugins, preventing them from continuing to occupy resources.

If a child plugin needs to be unloaded independently in advance, you can save the ctx.plugin() returned Fiber, and then call its dispose()。

Hot replacement (HMR) and lifecycle

HMR (Hot Module Replacement) allows developers to update running plugins after modifying plugin code, without having to manually restart the entire application every time.

In DeepSeek Harness, if you have already used cordis.yml to load and configure @deepseek-ai/dsh-hmr, after modifying the source code of a monitored plugin, hot replacement can be triggered.

A typical hot replacement includes the following steps:

  1. Detect changes in plugin source files.
  2. Unload the old plugin instance.
  3. Remove resources such as events and tools registered by the old instance.
  4. Load the updated plugin code.
  5. Re-execute the plugin's initialization logic.

For example, a plugin registers a tool my_tool, and then the developer modifies that tool's implementation.

If hot replacement succeeds, the framework first cleans up the old plugin's tool registration, then loads the new version of the tool, avoiding duplicate registration problems caused by the old registration not being released.

But note that hot replacement does not mean the plugin's internal state will be automatically persisted. For data that must be preserved, use independent state storage or recovery mechanisms.

Example: observing plugin loading and unloading

Below we use a minimal example to observe the logs when a plugin is loaded and cleaned up.

Example

// File: scratch-plugin/src/lifecycle-log.ts

import

type

{

Context

}

from

'@deepseek-ai/cordis'

export

const

name

=

'lifecycle-log'

export

function

apply

(

ctx

:

Context

)

{

  console.

log

(

'runoob plugin loading'

)

  ctx.

effect

(

(

)

=>

{

    console.

log

(

'runoob effect registered'

)

   

return

(

)

=>

{

      console.

log

(

'runoob effect cleaned up'

)

   

}

 

}

)

}

When the plugin is loaded normally, the output is:

runoob plugin loading

runoob effect registered

When the plugin is unloaded, the output is:

runoob effect cleaned up

From the output we can see:

You can further add timers, event listeners, or child plugins to this example to observe how resources are released at unload time.

Common questions

1. The plugin did not execute apply()?

First check whether injectis declared, and whether the corresponding required services are ready.

If dependencies are not yet ready, the plugin may stay in PENDING status.

If dependencies are satisfied, you should continue to check whether exceptions occurred during configuration validation and plugin initialization.

2. The timer is still running after the plugin is unloaded?

If the timer was created directly through setInterval() without registering a corresponding cleanup function, Cordis may not be able to manage it automatically.

The timer creation process should be put into ctx.effect(), and return a disposer that invokes clearInterval() the cleanup.

3. After calling ctx.effect(), when is the cleanup function executed?

ctx.effect() The execution function of it starts running immediately, while the returned disposer executes when the plugin is unloaded or the effect is released early.

Disposers are managed by the lifecycle mechanism, and the same resource will not be cleaned up repeatedly due to repeated disposal.

4. Does asynchronous cleanup complete in order?

Not guaranteed.

Although disposers start being called in reverse registration order, multiple asynchronous disposers may run concurrently.

If cleanup steps have sequential dependencies, put them in the same asynchronous disposer and use await to control the execution order.

5. After a dependency service recovers, do you need to manually reload the plugin?

Usually not. For plugins managed through the Cordis dependency mechanism, when required services recover, the framework can reload the related plugin instances.

However, if the plugin itself has configuration errors or initialization exceptions, the corresponding issues still need to be fixed.


Summary

Fiber is the core runtime object that DeepSeek Harness uses to manage plugin lifecycles based on Cordis.

It is responsible for tracking a plugin's loading state, dependent services, and registered resources, and performing cleanup when the plugin is unloaded.

To understand the Fiber lifecycle, you need to grasp the following key points:

For plugin developers, the most important practice is:When acquiring a resource, define how to release it at the same time.

As long as you correctly use the registration APIs provided by Cordis and ctx.effect(), you can reduce resource leak problems during plugin reloading, hot replacement, and unloading.

Official reference materials:

  • DeepSeek Harness:Plugins and Lifecycle
  • Cordis Fiber API
  • Cordis Lifecycle and Effect Tutorial