- Início
- Plugins
- Fluxos e automação
- dsh-leader
dsh-leader
feigo313/dsh-leader
Injects a leader contract into the root session so the main agent plans, slices the work, delegates to subagents and verifies their output; checks the \[ROUTE] header and the declared model/effort of every dispatch (off, audit or enforce), watches for the main agent doing implementation work itself, and records it all in an audit log. Ships a plugin-detail settings surface (subagent guide with one-click access to DSH's official Subagent page, gate strictness, archive and input-bar toggle-visibility cards), a one-click robot toggle in the chat input bar to enable or disable per-session orchestration, and a local HTTP API. Its HTTP routes have no DSH access check, so a web page open in your browser could call them.
Instalar
dsh plugin --profile web add github:feigo313/dsh-leaderREADME
dsh-leader
A plugin for DeepSeek Harness. It injects a leader contract into the root session's system prompt: the main agent plans, splits the work, dispatches subagents, and checks what comes back, while implementation work runs in those subagents. Subagents and nested sessions are not injected, so the contract never recurses.
Outside the injection, the plugin provides two observability channels — event accounting and call-level dispatch auditing — plus a plugin-detail settings surface: a subagent guide card, a gate strictness card, an archive card, a local HTTP API, and a runtime config layer. It has no runtime dependencies and uses only Node built-ins. It is ESM and requires Node.js 22 or newer.
Changes are recorded in CHANGELOG.md.
What gets injected
The injected text is a contract for how the main agent divides work. Its main points:
- Role. The main agent is the leader of this session: understand the goal, plan, slice the work, dispatch, audit, integrate, report. Implementation work goes to subagents by default; the leader edits only what cannot be split.
- When to delegate. Any of: two or more files; three or more tool calls of research, verification, or debugging; independent branches that can run in parallel; more than 200 lines of code or heavy reading; more than one deliverable.
- The
[ROUTE]header. Every dispatch prompt opens with a[ROUTE]header. Field names may be Chinese or English —form/reason/write-scope/output/acceptancemap to形态/理由/写入范围/产出/验收— the gate normalizes aliases before parsing them literally; values are free text.model=andeffort=are optional. - Slicing. Parallel work is split into non-overlapping slices. One owner per output path; public files (README, package.json, entry files, lock files) are handled once; every slice carries its own acceptance criteria.
- Verification separation. Whoever wrote the code does not sign it off. The host has no verifier role, so sign-off is one ordinary peer subagent whose prompt constrains it to read-only work and a pass/fail verdict plus evidence; the leader may also check the diff, the numbers, and the rollback path directly.
- Never idle. A returned subagent is integrated and the remaining work is re-examined for further parallel slices; waiting with free capacity is a contract violation, not patience.
- Anti-bypass. "Finish the work first, summarize afterwards" is explicitly not allowed.
The contract text is external. $DSH_HOME/dsh-leader/protocol.md (user override) wins over the packaged protocol.default.md. Both are read hot by mtime+size, so an edit applies on the next turn without a restart. The text ships in English (the default), because an English contract measures about 24% fewer tokens than the Chinese one under a modern tokenizer; protocol.zh.md ships alongside for reference, and either file can be dropped in at the override path as a whole.
Channels (three)
| # | Channel | Does | Does not |
|---|---|---|---|
| 1 | systemPrompt.section injection | Puts the contract into the root session's system prompt; skips subagents and nested sessions | Does not touch tool permissions; does not append messages |
| 2 | Event observation | Listens to subagent/start and subagent/end (0 tokens), runs a silence-alert timer, keeps the counters behind /leader status | Does not block; does not wait on subagents; does not decide for the user |
| 3 | tools/pre-execute call-level audit / soft deny | Reads the [ROUTE] header from exec.arguments.prompt; audit records, enforce returns deny for a missing header or a slice conflict | Does not remove the tool; does not rewrite arguments; does not gate concurrency; is not a physical limit |
Channel 3 is a call-level soft deny. The tool stays visible and the arguments pass through unchanged; deny rejects this one call only, and the model can try again. The plugin can verify that a declaration exists and does not conflict with another one; it cannot verify that a declaration is true (see Boundaries).
Behavior
- Injection. Contract text is returned for the root session only. Sessions with
origin=subagent,delegationDepth>0, or aparentSession(Id)get an empty string. - Switch. Follows the configured
enabledby default. With a session id and writable session state,/leader on|offchanges only that session; without one it falls back to a runtime global switch (not written to the cordis config, lost on restart) and reportssessionScoped:false. - Dispatch gate. Only the
promptargument ofsubagent,subagent_fork, andsubagent_ompis parsed.routeGate=auditrecords a missing header and allows the call;enforcereturnsdenywith a reason that points back to the dispatch contract;offdoes not parse. - Model and effort check.
routeModelCheck=offskips it.auditrecords any difference between themodel=/effort=declared in[ROUTE]and the actual dispatch arguments (provider/model/reasoning_effort) in thedispatchevent, then allows the call;enforcereturnsdenyon a mismatch. An undeclared field is not an error.modelacceptsprovider/modelor a bare model name;effortcomparison ignores case. - Slice registry. A per-session scope table. An output path has one owner at a time, decided from declarations. Public files (README, package.json, index.js, lock files) are single-owner by default. Under
enforce, a later conflicting call is rejected as a whole; calls that were already dispatched are not revoked. - Lifecycle.
subagent/endrecords runId, child session id, parent session id, stopReason, and duration;activeCountis kept per parent session. Automatic archiving is on by default: a finished subagent is archived afterreuseWindowMinutes(archiveOnComplete=true, timerunrefed). Automatic archives callarchiveSession(childId, {stopActivity:false}), so the plugin never asks the host to stop activity;/leader close <agent>usesstopActivity:true, with separate messages for active and unknown sessions. Each automatic timer captures its run's generation and prunes only records of that generation, so an in-flight archive for a child id leaves a newer run's records and timer alone (superseded). Two more archiving points:session/disposedarchives the tracked direct subagents of the closed session; withteamArchiveOnRetire=true, a successfulagent_teams_remove_memberarchives that member's session when its id resolves from arguments, results, or theteam/membermap, and otherwise recordsdegradedand skips. - Silence alert timer (watchdog). A self-maintained,
unrefed timer, not an agent and not a group watchdog. When subagents are active and nothing happens forwatchdog.silentMinutes, it records an event and increments a counter. It never blocks or adjudicates. No confirmed host API exists for injecting a reminder, so this build only records. - Fail-open. Exceptions are recorded, never thrown. A failing
applydoes not keep the host from loading.
Self-execution check
The same pre-execute hook watches for the main agent doing implementation work itself instead of dispatching. Every call belongs to exactly one class: direct dispatch and read calls are handled first; otherwise mutation outranks a literal-payload dispatch (v2.2), which outranks run.
- Scope and exemption. Root session only and contract enabled. Exemption comes only from a real dispatch: the host's
subagent/startwhoseparentSessionIdis this session exempts it while that subagent is live plus 10 minutes after the lastsubagent/end. Allowing a[ROUTE]dispatch does not grant exemption — an empty dispatch is not a bypass. - Modes. Two independent keys:
selfExecCheck(off/audit/enforce, defaultenforce) covers mutation calls;selfExecReadRun(off/audit/enforce, defaultenforce) covers run actions. - Reads are free. Read-only tools (
read,read_files,grep,glob,ops_read_*,ops_stat,list_*) never count, never reset and are never rejected. - Mutation accounting. Write tools, arguments that carry
file_path/pathorwrite, shell commands that write (redirection,tee,sed -i,dd of=, git write subcommands, PowerShell write cmdlets), andrun_code/code/pythonpayloads that call fs write APIs (fs.writeFile,writeFileSync,appendFile,rename,copyFile,unlink,mkdir,createWriteStream, Pythonopen(..., 'w'),write_text,shutil.copy,os.remove). Distinct paths accumulate per session, so editing the same file again counts once; nestededits[]and patch bodies (+++headers,*** Update File:,diff --git) contribute every file, and Windows paths fold case. A mutating call whose path cannot be resolved counts as one unknown path. - Run accounting.
shell/pwsh/ops_bash/terminal_send/run_codecalls that are neither mutating nor dispatching count one run action each in a sliding window ofselfExecRunWindowMinutes(default 10). There is no command whitelist:npm testandgit statuscount the same. Denied calls are not counted and the window self-heals when it expires. - Dispatching from a code payload (v2.2). A
run_code/code/python/nodepayload that actually calls a dispatch tool —tools.subagent(...),tools.subagent_fork(...),tools.subagent_omp(...), thetools.agent_teams_*dispatch family,tools.team_task_create,tools.ralph— is classified asdispatch: not counted, never blocked, outside the run window. A payload that also writes staysmutation, and a name that only appears in a string or a comment does not qualify. The classification grants no exemption — only a realsubagent/startdoes. - Thresholds. The second distinct mutation path, or the third run action inside the window (
selfExecRunThreshold, default 3). - Outcome.
auditwrites aself-executionevent toaudit.jsonland lets the call through.enforcedenies that call: it is not counted as executed, the tool stays visible, and a retry is denied again. Dispatching a subagent is never blocked by this check, so it cannot deadlock the session. After a rejection, do not retry the same call, wait for the window, or reset the gate: if tools are still needed, dispatch for real immediately; when the dispatch runs throughrun_code, its code must execute a literal dispatch-tool call, not just mention one. - Switch. Not rendered on the settings page (it is not a per-use choice). Write
$DSH_HOME/dsh-leader/config.jsonwith{"selfExecCheck":"off"}or{"selfExecReadRun":"off"}, or remove the key to return to the default./leader resetclears this session's counters and exemption state.
Settings page and HTTP API
The settings surface registers under the host's plugins.detail.section only (there is no separate settings.section page), titled "Leader Contract / Leader 合同", and holds three cards. The surface follows the DSH GUI locale.
- Subagent guide card (first card on the plugin detail section). One read-only card explains that subagent recursion depth, concurrency and allowed models are configured in DSH's official Subagent page, with an Open plugin page button: it opens the official Subagent page directly when the host's internal navigation is available, falls back to the Plugins panel otherwise, and hides itself when no navigation service is available. The plugin does not own a concurrency slider, a dispatch gate, or a default-model takeover; it only adds a parallel cost/quota reminder.
- Gate strictness card. One knob controls all four gate keys (
routeGate/routeModelCheck/selfExecCheck/selfExecReadRun), with loose / standard / strict tiers. - Subagent archive card. Toggles archive-on-complete and sets the reuse window in minutes.
Host routes, loopback only, method allowlist, request body up to 64 KB, JSON errors throughout:
| Method | Path | Purpose |
|---|---|---|
| GET | /dsh-leader/api/state | Effective state and counters: activeCount, effortSource, globalOverride and auditCounts.auditWriteFailures |
| GET | /dsh-leader/api/models | Official subagent allow-list (models, source, enabled, selectionDisabled, defaultModel, note, degraded). Each model carries efforts / declared (host-declared reasoning efforts; [] + false when the host declares none) and effortSource tells whether that came from the host (host-llm), could not be read (unavailable) or was not read yet (pending) |
| PATCH | /dsh-leader/api/config | Partial config write; returns {ok, config, errors} and allows partial success |
| DELETE | /dsh-leader/api/config | Delete config keys from the runtime layer: body {"keys":[…]}. Whitelisted keys only; returns {ok, config, errors, removed}. Use this — not PATCH null — to return a key to the cordis/default value |
| POST | /dsh-leader/api/config/reset | Same implementation as DELETE /config |
| GET | /dsh-leader/api/protocol | Contract text in effect and its source (override or default) |
| PUT | /dsh-leader/api/protocol | Write the override file (a .bak is written first) |
| DELETE | /dsh-leader/api/protocol | Delete the override file, back to the packaged text |
| GET | /dsh-leader/api/session?sessionId=… | Per-session switch state |
| POST | /dsh-leader/api/session | Write the per-session switch |
Install
dsh-leader is a DeepSeek Harness plugin package. It declares a bundle patch (cordis.patch.yml) and a web client, has no runtime dependencies, and needs no build step. Node.js 22 or newer.
From the plugin marketplace: install the dsh-leader listing. DSH adds the dependency and the bundle entry, and the bundled patch starts the plugin with enabled: true and order: 8000.
From a local checkout, edit your DSH profile's package.json in two places:
dependencies: add"dsh-leader": "link:<path-to-this-checkout>"dsh.profile.bundles: add"dsh-leader"
Install the profile's dependencies with the package manager the profile uses, then reload DSH.
Either way, /leader status in a root session and the "Leader 合同" settings page should both respond.
Configuration (cordis.patch.yml)
| Config | Default | Meaning |
|---|---|---|
enabled | true | Master switch for the contract (per-session override above) |
order | 8000 | Section order |
routeGate | audit | off / audit / enforce: checks that the prompt header exists and that slices do not conflict |
routeModelCheck | audit | off / audit / enforce: compares the model= / effort= declared in [ROUTE] with the actual dispatch arguments |
selfExecCheck | enforce | off / audit / enforce: the main agent's own mutating calls before it dispatches (second distinct path is denied under enforce) |
selfExecReadRun | enforce | off / audit / enforce: the main agent's run actions in a sliding window (selfExecRunThreshold-th call is denied); read-only tools are free |
selfExecRunThreshold | 3 | Positive integer: how many run actions inside the window trigger the run gate |
selfExecRunWindowMinutes | 10 | Positive number of minutes for the sliding run window |
routeHeaderRequired | true | The contract requires a [ROUTE] header on every dispatch; the gate always parses it, and this key does not change the decision |
archiveOnComplete | true | Archive a finished subagent after the reuse window with stopActivity:false (reversible) |
reuseWindowMinutes | 15 | Only applies when archiveOnComplete=true |
showInputToggle | true | Whether the input-bar robot button is rendered (UI visibility only — it does not enable/disable the plugin; clicking that button still toggles per-session orchestration via POST /api/session) |
teamArchiveOnRetire | false | Archive a retired team member (listens to agent_teams_remove_member; skips when no id resolves) |
teamNotice | auto | auto / off: when the host team switch is off or unreadable, auto appends one reminder line to the contract; off never probes or appends |
watchdog.enabled | true | Event listening (0 tokens) |
watchdog.silentMinutes | 10 | Silence threshold |
auditLogMaxMB | 5 | audit.jsonl rotation limit (current plus two archives) |
Illegal values fall back to defaults in normalizeConfig; unknown keys are kept and do not raise errors.
Runtime config layer. $DSH_HOME/dsh-leader/config.json takes precedence over the cordis config, which takes precedence over the factory defaults. It is read hot by mtime+size and written atomically (tmp + rename). Delete the file to fall back to the cordis config.
Note on precedence: /leader on|off without a session id writes a runtime global override, which also outranks config.json. PATCH /config with a boolean enabled afterwards clears that override and takes effect immediately (globalOverride in GET /state shows the diagnosis).
Commands
/leader [status|show|on|off|close <agent>|reset]
-
status: a readable summary, then one machine-readable JSON line:{"enabled":true,"source":"default","lines":78,"order":8000,"isRoot":true,"sessionScoped":true,"activeCount":0}sourceisoverride(session override or runtime global override) ordefault(the configured value). -
show: print the contract text currently in effect. -
on/off: per-session first; falls back to the runtime global switch. -
close <agent>: accepts a subagent session id or arunIdand callsworkspaceRegistry.archiveSessionwithstopActivity:true. Archiving is UI management; it frees no disk and can be undone withunarchive. -
reset: clear this session's overrides and slice registry; with no session id, fall back to the configured defaults.
The command registers optionally through ctx.inject(['commands']); when the service is missing it is not registered and no error is raised. Return values follow the host CommandResult ({kind:'success'|'error', text}); {kind:'text'} is not the dsh-commands contract and raises TypeError at the host boundary.
Text sources
$DSH_HOME/dsh-leader/protocol.md— user override, the file to edit- packaged
protocol.default.md— factory fallback
Both are cached by mtime+size. Edits apply on the next turn; no restart.
Audit and state files
$DSH_HOME/dsh-leader/audit.jsonl: append-only JSONL, rotated byauditLogMaxMB(current plus two archives). Events:dispatch,route-gate,slice-conflict,subagent-start,subagent-end,session-disposed,team-retire,team-unavailable,archive,watchdog,degraded,self-execution. Append failures are counted independently and exposed asGET /state→auditCounts.auditWriteFailures.$DSH_HOME/dsh-leader/session-state.json: per-session switches (atomic writes).$DSH_HOME/dsh-leader/runs.json: tracked-subagent ledger for the startup idle sweep; every tracked run with a session id is written (no fixed row cap).
Boundaries
- It does not remove tools, rewrite arguments, or pretend to be a physical limit.
denyis not a sandbox. - Conflicts are judged from declarations only: it does not read the disk and does not verify that a declaration is true.
- Team-retire archiving is best effort: it archives only when a session id resolves from arguments, results, or the
team/membermap; otherwise it recordsdegradedinstead of guessing. - No model menu row (
conversation.input.model.options): per-session switching is/leader on|offorPOST /dsh-leader/api/session. Subagent depth, concurrency and allowed models are configured in DSH's official Subagent page; the plugin neither duplicates the allow-list nor takes over default models.
What it does not do
- No worktree isolation. It does not create branches or worktrees for subagents and does not review or merge their output; use the host or another plugin for isolation.
- No team runtime. No roster, task DAG, mailboxes, or scheduler of its own; team structure belongs to the host's AgentTeams (or a dedicated team runtime plugin). The host exposes only peer subagents: no verifier kind and no physical groups.
- No context compaction or disk cleanup. Archiving affects the UI and wake-up gating only and frees no disk. Compaction belongs to the context plugin, and this plugin keeps no second copy.
Development
npm test
The tests run on Node's built-in test runner (node --test test/*.test.mjs). There is nothing to build.