Zum Hauptinhalt springen
F

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.

Installation

dsh plugin --profile web add github:feigo313/dsh-leader

README

dsh-leader

English | 中文

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/acceptance map to 形态/理由/写入范围/产出/验收 — the gate normalizes aliases before parsing them literally; values are free text. model= and effort= 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)

#ChannelDoesDoes not
1systemPrompt.section injectionPuts the contract into the root session's system prompt; skips subagents and nested sessionsDoes not touch tool permissions; does not append messages
2Event observationListens to subagent/start and subagent/end (0 tokens), runs a silence-alert timer, keeps the counters behind /leader statusDoes not block; does not wait on subagents; does not decide for the user
3tools/pre-execute call-level audit / soft denyReads the [ROUTE] header from exec.arguments.prompt; audit records, enforce returns deny for a missing header or a slice conflictDoes 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 a parentSession(Id) get an empty string.
  • Switch. Follows the configured enabled by default. With a session id and writable session state, /leader on|off changes only that session; without one it falls back to a runtime global switch (not written to the cordis config, lost on restart) and reports sessionScoped:false.
  • Dispatch gate. Only the prompt argument of subagent, subagent_fork, and subagent_omp is parsed. routeGate=audit records a missing header and allows the call; enforce returns deny with a reason that points back to the dispatch contract; off does not parse.
  • Model and effort check. routeModelCheck=off skips it. audit records any difference between the model= / effort= declared in [ROUTE] and the actual dispatch arguments (provider / model / reasoning_effort) in the dispatch event, then allows the call; enforce returns deny on a mismatch. An undeclared field is not an error. model accepts provider/model or a bare model name; effort comparison 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/end records runId, child session id, parent session id, stopReason, and duration; activeCount is kept per parent session. Automatic archiving is on by default: a finished subagent is archived after reuseWindowMinutes (archiveOnComplete=true, timer unrefed). Automatic archives call archiveSession(childId, {stopActivity:false}), so the plugin never asks the host to stop activity; /leader close <agent> uses stopActivity: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/disposed archives the tracked direct subagents of the closed session; with teamArchiveOnRetire=true, a successful agent_teams_remove_member archives that member's session when its id resolves from arguments, results, or the team/member map, and otherwise records degraded and 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 for watchdog.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 apply does 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/start whose parentSessionId is this session exempts it while that subagent is live plus 10 minutes after the last subagent/end. Allowing a [ROUTE] dispatch does not grant exemption — an empty dispatch is not a bypass.
  • Modes. Two independent keys: selfExecCheck (off / audit / enforce, default enforce) covers mutation calls; selfExecReadRun (off / audit / enforce, default enforce) 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 / path or write, shell commands that write (redirection, tee, sed -i, dd of=, git write subcommands, PowerShell write cmdlets), and run_code / code / python payloads that call fs write APIs (fs.writeFile, writeFileSync, appendFile, rename, copyFile, unlink, mkdir, createWriteStream, Python open(..., 'w'), write_text, shutil.copy, os.remove). Distinct paths accumulate per session, so editing the same file again counts once; nested edits[] 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_code calls that are neither mutating nor dispatching count one run action each in a sliding window of selfExecRunWindowMinutes (default 10). There is no command whitelist: npm test and git status count 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 / node payload that actually calls a dispatch tool — tools.subagent(...), tools.subagent_fork(...), tools.subagent_omp(...), the tools.agent_teams_* dispatch family, tools.team_task_create, tools.ralph — is classified as dispatch: not counted, never blocked, outside the run window. A payload that also writes stays mutation, and a name that only appears in a string or a comment does not qualify. The classification grants no exemption — only a real subagent/start does.
  • Thresholds. The second distinct mutation path, or the third run action inside the window (selfExecRunThreshold, default 3).
  • Outcome. audit writes a self-execution event to audit.jsonl and lets the call through. enforce denies 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 through run_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.json with {"selfExecCheck":"off"} or {"selfExecReadRun":"off"}, or remove the key to return to the default. /leader reset clears 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:

MethodPathPurpose
GET/dsh-leader/api/stateEffective state and counters: activeCount, effortSource, globalOverride and auditCounts.auditWriteFailures
GET/dsh-leader/api/modelsOfficial 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/configPartial config write; returns {ok, config, errors} and allows partial success
DELETE/dsh-leader/api/configDelete 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/resetSame implementation as DELETE /config
GET/dsh-leader/api/protocolContract text in effect and its source (override or default)
PUT/dsh-leader/api/protocolWrite the override file (a .bak is written first)
DELETE/dsh-leader/api/protocolDelete the override file, back to the packaged text
GET/dsh-leader/api/session?sessionId=…Per-session switch state
POST/dsh-leader/api/sessionWrite 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:

  1. dependencies: add "dsh-leader": "link:<path-to-this-checkout>"
  2. 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)

ConfigDefaultMeaning
enabledtrueMaster switch for the contract (per-session override above)
order8000Section order
routeGateauditoff / audit / enforce: checks that the prompt header exists and that slices do not conflict
routeModelCheckauditoff / audit / enforce: compares the model= / effort= declared in [ROUTE] with the actual dispatch arguments
selfExecCheckenforceoff / audit / enforce: the main agent's own mutating calls before it dispatches (second distinct path is denied under enforce)
selfExecReadRunenforceoff / audit / enforce: the main agent's run actions in a sliding window (selfExecRunThreshold-th call is denied); read-only tools are free
selfExecRunThreshold3Positive integer: how many run actions inside the window trigger the run gate
selfExecRunWindowMinutes10Positive number of minutes for the sliding run window
routeHeaderRequiredtrueThe contract requires a [ROUTE] header on every dispatch; the gate always parses it, and this key does not change the decision
archiveOnCompletetrueArchive a finished subagent after the reuse window with stopActivity:false (reversible)
reuseWindowMinutes15Only applies when archiveOnComplete=true
showInputToggletrueWhether 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)
teamArchiveOnRetirefalseArchive a retired team member (listens to agent_teams_remove_member; skips when no id resolves)
teamNoticeautoauto / off: when the host team switch is off or unreadable, auto appends one reminder line to the contract; off never probes or appends
watchdog.enabledtrueEvent listening (0 tokens)
watchdog.silentMinutes10Silence threshold
auditLogMaxMB5audit.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}
    

    source is override (session override or runtime global override) or default (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 a runId and calls workspaceRegistry.archiveSession with stopActivity:true. Archiving is UI management; it frees no disk and can be undone with unarchive.

  • 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

  1. $DSH_HOME/dsh-leader/protocol.md — user override, the file to edit
  2. 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 by auditLogMaxMB (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 as GET /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. deny is 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/member map; otherwise it records degraded instead of guessing.
  • No model menu row (conversation.input.model.options): per-session switching is /leader on|off or POST /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.

Ähnliche Plugins