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

DeeSeek Harness Defensive Programming: Result Reporting, Cleanup and Credentials

DeeSeek Harness Defensive Programming: Result Reporting, Cleanup and Credentials

After writing so many plugins, you may encounter a class of edge-case bugs that 'can't be reproduced in tests but blow up in production'.

The official docs summarize them as 'hard-won bug class rules'—each one is a defect that actually shipped or nearly shipped.

This article covers the five most important defensive programming patterns: result reporting, dispose coming to a full stop, credential scrubbing, link deletion, callback isolation.

In short: these patterns prevent 'a simple edge case from taking down the whole Agent'.


First, a comparison diagram

The figure below compares bad and good examples side by side, each from a real bug class.

Defensive programming bad vs. good example comparison diagram

The official docs call these the rules to 'read before writing lifecycle, concurrency, subprocess or cleanup code'.


Report orthogonal results independently

A result can have multiple properties at once: a process may have timed out yet still exit with code 0 because it caught the termination signal.

Each independent fact (timedOut、signal、exitCode) should be reported separately.

Never nest the reporting of one flag inside a branch of another, or the caller may misjudge an early-terminated run as a normal success.

Example

// File path: packages/my-shell/src/run.ts

// Run a child process and report three independent facts orthogonally: timedOut, signal, exitCode.

import

{

spawn

,

type ChildProcess

}

from

'node:child_process'

export

interface

RunResult

{

  timedOut

:

boolean

     

// Independent fact 1: whether it timed out

  signal

:

NodeJS.

Signals

|

null

// Independent fact 2: whether it was terminated by a signal

  exitCode

:

number

|

null

     

// Independent fact 3: exit code

  stdout

:

string

  stderr

:

string

}

export

function

run

(

argv

:

string

[

]

,

timeoutMs

:

number

)

:

Promise

<

RunResult

{

return

new

Promise

(

(

resolve

,

reject

)

=>

{

const

child

:

ChildProcess

=

spawn

(

argv

[

0

]

,

argv.

slice

(

1

)

,

{

      stdio

:

[

'ignore'

,

'pipe'

,

'pipe'

]

,

   

}

)

    let stdout

=

''

    let stderr

=

''

    child.

stdout

.

on

(

'data'

,

(

d

:

Buffer

)

=>

(

stdout

+=

d

)

)

    child.

stderr

.

on

(

'data'

,

(

d

:

Buffer

)

=>

(

stderr

+=

d

)

)

   

// Independent fact 1 maintained separately: timeout is a flag, unrelated to the exit code.

    let timedOut

=

false

   

const

timer

=

setTimeout

(

(

)

=>

{

      timedOut

=

true

      child.

kill

(

'SIGTERM'

)

// Timeout triggers termination

   

}

,

timeoutMs

)

    child.

on

(

'close'

,

(

code

,

signal

)

=>

{

      clearTimeout

(

timer

)

     

// The three fields are returned independently: a process may have timedOut=true and exitCode=0,

     

// because it caught SIGTERM after timeout and exited with 0.

      resolve

(

{

timedOut

,

signal

,

exitCode

:

code

,

stdout

,

stderr

}

)

   

}

)

    child.

on

(

'error'

,

reject

)

 

}

)

}

With this approach the caller can combine decisions:timedOut is true but exitCode is 0, meaning 'killed by force but the process masked it with 0'.

With nested reporting this combination can never be expressed.


dispose must come to a complete stop

If cleanup only sends a termination or abort signal and returns without waiting for the work to actually stop, orphan processes are left behind.

Cleanup logic should use an async flow and wait for the child process to exit (after sending the termination signal, wait for done)。

It should also close the listener registry and notification registry before terminating the process, keeping late completion events silent.

Example

// File path: packages/my-shell/src/dispose.ts

// dispose must come to a complete stop: signal then wait for the child to exit, rather than signal and return.

import

{

once

}

from

'node:events'

import

type

{

ChildProcess

}

from

'node:child_process'

export

async

function

disposeQuiescent

(

child

:

ChildProcess

)

:

Promise

<

void

{

// 1. Remove listeners first so late completion events stay silent.

  child.

removeAllListeners

(

)

 

// 2. Request stop: send the termination signal.

  child.

kill

(

'SIGTERM'

)

 

// 3. Wait for the child to actually exit; if it still doesn't after timeout, escalate to SIGKILL.

 

// Promise.race ensures dispose is never hung forever by a child that refuses to exit.

 

const

forceKill

=

new

Promise

<

void

(

(

resolve

)

=>

{

setTimeout

(

(

)

=>

{

      child.

kill

(

'SIGKILL'

)

      resolve

(

)

   

}

,

5

_000

)

 

}

)

  await Promise.

race

(

[

once

(

child

,

'exit'

)

.

then

(

(

)

=>

undefined

)

,

forceKill

]

)

}

This way, when dispose returns, the child has either exited or been forcibly killed by SIGKILL.


Credential scrubbing: never expose environment variables to untrusted output

Commands launched should use scrubbed environment variables, removing entries whose names match *KEY*、*SECRET*、*TOKEN* or *PASSWORD* .

Otherwise harness credentials may leak through command output,env or spill files.

Temporary files and spill files should be placed in private directories with mode 0700, use random filenames and be opened exclusively and owner-only accessible ('wx'、0o600)。

Example

// File path: packages/my-shell/src/env.ts

// Scrub environment variables before launching commands to prevent harness credentials leaking via command output or env.

// Sensitive items matching KEY SECRET TOKEN PASSWORD are all removed.

const

SENSITIVE_NAME

=

/.(?:KEY|SECRET|TOKEN|PASSWORD)./i

export

function

scrubEnv

(

env

:

NodeJS.

ProcessEnv

)

:

Record

<

string

,

string

{

const

clean

:

Record

<

string

,

string

=

{

}

for

(

const

[

key

,

value

]

of

Object

.

entries

(

env

)

)

{

   

if

(

SENSITIVE_NAME.

test

(

key

)

)

continue

// Skip sensitive keys directly

   

if

(

value

!==

undefined

)

clean

[

key

]

=

value

 

}

 

return

clean

}

// Usage: spawn(argv[0], argv.slice(1), { env: scrubEnv(process.env), ... })

In the runoob environment,DEEPSEEK_API_KEY such variables must go through this scrubbing path.

Letting command output,env or spill files carry it is equivalent to handing the secret to anything that can read the output.


Delete symlinks with unlink

Paths that may be symlinks or Windows junctions should first be tested with lstatSync().isSymbolicLink() , then deleted with unlinkSync .

unlink only removes the link itself and refuses real directories, so it never follows the link into its target.

Calling a junction on Windows rmSync(link) throws ERR_FS_EISDIR; recursive deletion may pass through a junction into its target.

Only real directories should use rmSync with recursive recursive 's rmSync。

Example

// File path: packages/my-fs/src/remove.ts

// Delete link-shaped paths with unlink, never recursively following the link into its target.

import

{

lstatSync

,

rmSync

,

unlinkSync

}

from

'node:fs'

export

function

removePath

(

p

:

string

)

:

void

{

 

// First determine whether it is a symlink (or Windows junction).

 

if

(

lstatSync

(

p

)

.

isSymbolicLink

(

)

)

{

   

// unlink only removes the link itself and refuses real directories; it does not follow links.

    unlinkSync

(

p

)

   

return

 

}

 

// Only after confirming a real directory use rmSync with recursive.

  rmSync

(

p

,

{

recursive

:

true

}

)

}


Isolating callback exceptions in the dispatcher

If a user-provided listener throws, it must not cause its promise to be rejected nor starve listeners queued after it.

Wrap the dispatch loop in try/catch and log.

A misbehaving subscriber must never break the core lifecycle.

Example

// File path: packages/my-events/src/dispatch.ts

// The dispatcher isolates callback exceptions: one bad subscriber cannot break the core lifecycle.

export

function

dispatch

(

listeners

:

ReadonlyArray

<

(

)

=>

void

)

:

void

{

 

for

(

const

listener of listeners

)

{

   

try

{

      listener

(

)

   

}

catch

(

err

)

{

     

// Log and continue dispatching, never reject, never starve later listeners.

      console.

error

(

'[dispatch] a listener failed:'

,

err

)

   

}

 

}

}

This pattern is everywhere inside dsh:session/event observers' failures are logged and isolated without failing a committed append.

It ensures that 'a plugin writing a broken listener' does not stall the whole Agent loop.


More patterns at a glance

The official docs also record two others worth remembering:

Mode Rule
Both sides must honor the public contract When receiving multiple representations of the same result, normalize before returning via the public API; consumers shouldn't have to guess whether an exception came from the provider, the wrapper or their own assembly logic
Async state is not sync state Do not confuse agent/status or whenIdle() as the result of a certain followup() ; the caller that truly owns a run must define the interval explicitly

The testing counterparts of these rules (real entry paths, verifying actual results, resource ownership) are expanded in testing.md, mentioned in the next article.


Summary and self-test

Defensive programming plugs the pits that 'easily cause crashes at boundaries' in advance: orthogonal result reporting, dispose coming to a full stop, credential scrubbing, safe link deletion, callback exception isolation.

Self-test questions:

Problem Reference
A process timed out but exited with code 0—what does that mean? It may have caught the termination signal and exited with 0 on its own; timedOut and exitCode are two independent facts
When cleaning up a child process, what's the risk of just sending SIGTERM and returning? Leaves an orphan process; wait for exit and escalate to SIGKILL on timeout
To delete a path that may be a symlink, what should you use? First lstatSync to check, then unlinkSync; use rmSync recursive only for real directories