@sshirkit/dsh-orchestrator 0.8.5 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/supervise.js CHANGED
@@ -22,6 +22,36 @@
22
22
  * for the same parent can be recognized as already pending.
23
23
  */
24
24
  export const SUPERVISE_SOURCE_KIND = 'orchestrator-supervision'
25
+ export const SUPERVISION_NORMAL_TEXT = '巡检:正常'
26
+
27
+ /** Only plugin-authored supervision messages participate in a supervision turn. */
28
+ export function isSupervisionMessage(message) {
29
+ return message?.source?.kind === SUPERVISE_SOURCE_KIND
30
+ }
31
+
32
+ /** Prefer the complete id list, retaining the sender fallback for older notices. */
33
+ export function getSupervisionChildIds(message) {
34
+ const source = message?.source
35
+ const ids = Array.isArray(source?.childIds) ? source.childIds : [source?.senderSessionId]
36
+ return [...new Set(ids.filter((id) => typeof id === 'string' && id.trim() !== ''))]
37
+ }
38
+
39
+ /** Mixed inbox batches must retain the semantics of their ordinary messages. */
40
+ export function isPureSupervisionBatch(messages) {
41
+ return Array.isArray(messages) && messages.length > 0 && messages.every((message) => isSupervisionMessage(message))
42
+ }
43
+
44
+ /** Recognise a standalone declaration, never a sentence merely discussing it. */
45
+ export function hasNormalDeclarationText(assistantMessage) {
46
+ const content = assistantMessage?.content
47
+ if (!Array.isArray(content)) return false
48
+ const isDeclaration = (line) =>
49
+ line.trim().replace(/^[*_`]+/, '').replace(/[*_`。.!!]+$/, '').trim() === SUPERVISION_NORMAL_TEXT
50
+ return content.some((part) => {
51
+ if (part?.type !== 'text' || typeof part.text !== 'string') return false
52
+ return part.text.split(/\r?\n/).some(isDeclaration)
53
+ })
54
+ }
25
55
 
26
56
  /** Defaults, filled in by the module because config may be partial. */
27
57
  const DEFAULTS = Object.freeze({
@@ -46,10 +76,12 @@ const REPEAT_WINDOW = 20
46
76
  /** Candidate per-child text lengths tried before dropping children from a notice. */
47
77
  const TEXT_LIMITS = [LAST_TEXT_MAX, 240, 180, 120, 80, 40, 0]
48
78
 
49
- const NOTICE_HINT =
50
- '请对每个子代理作出决定——A) 方向正确则不干预;B) 跑偏或打转则用 send_message 给它具体纠偏指令;' +
51
- 'C) 需要终止则说明原因(终止工具是否可用由主代理自行判断)。' +
52
- '若无需干预,只回复一行「巡检:正常」并结束本回合,不要调用任何工具。'
79
+ const NOTICE_HINT = [
80
+ '请对每个子代理作出决定(以上子代理均仍在运行且尚未交付报告,本回合已硬禁止调用 todo_write):',
81
+ 'A) 方向正确(无需干预):严禁调用任何工具,仅回复一行「巡检:正常」并立刻结束本回合;',
82
+ 'B) 跑偏或打转:禁止回复「巡检:正常」,请直接用调研工具或 send_message 纠偏;',
83
+ 'C) 需中止或换路:禁止回复「巡检:正常」,请先说明原因并用中断/控制或已有工具调整执行路线。',
84
+ ].join('\n')
53
85
 
54
86
  // ---------------------------------------------------------------------------
55
87
  // Event adapters: the one place that knows the host field names.
@@ -337,13 +369,13 @@ function renderRow(row, number, textLimit, at, threshold) {
337
369
  const lastText = typeof row.lastText === 'string' ? row.lastText : ''
338
370
 
339
371
  const lines = [
340
- `${number}) 子代理 ${childId}`,
372
+ `${number}) 子代理 ${childId}(仍在运行,尚未交付报告)`,
341
373
  ` 任务:${label}`,
342
374
  ` 已运行 ${formatDuration(runMs)} | 轮次 ${turns} | 步骤 ${steps}`,
343
375
  ` 自上次巡检新增工具调用 ${toolCalls} 次 | 最近工具:${tool}`,
344
376
  ]
345
377
  if (lastText !== '' && textLimit > 0) {
346
- lines.push(` 最后输出:${clip(lastText, textLimit)}`)
378
+ lines.push(` 最后输出:${clip(lastText, textLimit)} [仅最新文本前${textLimit}字摘录,不代表最终成败]`)
347
379
  }
348
380
  if (repeated >= threshold) {
349
381
  lines.push(` ⚠ 检测到同一工具调用连续重复 ${repeated} 次,可能原地打转`)
@@ -438,7 +470,7 @@ function errorMessage(error) {
438
470
  * `intervalSeconds` is the minimum age of a child before it is reported.
439
471
  * - `now()`, `isParentAlive(parentId)`, `isChildAlive(childId)`,
440
472
  * `readEvents(childId)`, `hasPendingNotice(parentId)`,
441
- * `deliver(parentId, text, childIds)`, `logger`. The async ones may return a
473
+ * `deliver(parentId, text, childIds, { rows, composeMeta })`, `logger`. The async ones may return a
442
474
  * value or a Promise.
443
475
  *
444
476
  * `tick` never throws because of one child or parent: read, summarize, pending
@@ -651,7 +683,7 @@ export function createSupervisor(options = {}) {
651
683
  lastText: summary.lastText,
652
684
  newEvents: summary.newEvents,
653
685
  }))
654
- const text = composeNotice(rows, {
686
+ const composeMeta = {
655
687
  now: at,
656
688
  index,
657
689
  // `max: 0` renders "第 N 次" without a denominator, which is exactly what an
@@ -659,7 +691,8 @@ export function createSupervisor(options = {}) {
659
691
  max: config.unlimited ? 0 : config.maxNoticesPerChild,
660
692
  maxChars: config.noticeMaxChars,
661
693
  repeatThreshold: config.repeatThreshold,
662
- })
694
+ }
695
+ const text = composeNotice(rows, composeMeta)
663
696
 
664
697
  let result
665
698
  try {
@@ -669,6 +702,7 @@ export function createSupervisor(options = {}) {
669
702
  parentId,
670
703
  text,
671
704
  live.map(({ entry }) => entry.childId),
705
+ { rows, composeMeta },
672
706
  )
673
707
  : 'queued'
674
708
  } catch (error) {
@@ -677,8 +711,10 @@ export function createSupervisor(options = {}) {
677
711
  continue
678
712
  }
679
713
 
714
+ if (result === 'stale') continue
680
715
  if (result === 'queued') {
681
716
  for (const { entry, summary } of live) {
717
+ if (entries.get(entry.childId) !== entry) continue
682
718
  entry.noticesSent += 1
683
719
  // A tail window can report a lower max than a previous read; never go backwards.
684
720
  entry.lastSeq = Math.max(entry.lastSeq, summary.lastSeq)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sshirkit/dsh-orchestrator",
3
- "version": "0.8.5",
3
+ "version": "0.8.7",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
@@ -16,7 +16,7 @@
16
16
  "lib",
17
17
  "cordis.patch.yml",
18
18
  "README.md",
19
- "README.en.md",
19
+ "README.zh.md",
20
20
  "LICENSE",
21
21
  "docs/images"
22
22
  ],
package/README.en.md DELETED
@@ -1,164 +0,0 @@
1
- <div align="center">
2
-
3
- ##### Start from 28th October
4
-
5
- <div align="center">
6
-
7
- # DSH Orchestrator
8
-
9
- </div>
10
-
11
-
12
- #### **A powerful model plans, low-cost models do the work — the dispatch mode plugin with hard tool isolation for DeepSeek Harness**
13
-
14
- [![version](https://img.shields.io/badge/version-0.8.5-4176E6?style=flat-square)](https://github.com/SShiRkiT/dsh-orchestrator)
15
- [![dsh-plugin](https://img.shields.io/badge/DeepSeek%20Harness-dsh--plugin-4176E6?style=flat-square)](https://github.com/deepseek-ai/deepseek-harness)
16
- [![platform](https://img.shields.io/badge/platform-Web%20GUI%20%7C%20Desktop-5c6bc0?style=flat-square)](https://github.com/SShiRkiT/dsh-orchestrator)
17
- [![node](https://img.shields.io/badge/node-%3E%3D22-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org)
18
- [![module](https://img.shields.io/badge/module-ESM-F7DF1E?style=flat-square&logo=javascript&logoColor=black)](package.json)
19
- [![license](https://img.shields.io/badge/license-MIT-2ea44f?style=flat-square)](LICENSE)
20
- [![GitHub stars](https://img.shields.io/github/stars/SShiRkiT/dsh-orchestrator?style=flat-square&logo=github)](https://github.com/SShiRkiT/dsh-orchestrator/stargazers)
21
-
22
- [简体中文](README.md) | **English** · [Key differences](#why-do-you-need-this-plugin-alongside-native-subagent-and-agent-team) · [Core Features](#core-features) · [Installation](#installation) · [Configuration](#configuration)
23
-
24
- </div>
25
-
26
- ---
27
- <div align="center">
28
-
29
- ### Why Do You Need This Plugin Alongside Native `subagent` and `Agent Team`?
30
- </div>
31
- DSH includes native `subagent` / `workflow` tools, and the official `@deepseek-ai/dsh-experimental-agent-team-profile` (Agent Team) is also available. However, intensive development still exposes three pain points — the problems at the heart of **DSH Orchestrator**'s distinctive design:
32
-
33
- | Pain point | Native `subagent` / official `Agent Team` | DSH Orchestrator (unique to this plugin) |
34
- | --- | --- | --- |
35
- | **The main agent keeps doing the work itself** | **Relies on compliance with soft prompts**: the main agent / Team Lead still has the full set of tools, including `read`, `edit`, and `bash`. After a few turns, it often starts reading files and running commands itself, quickly filling the main context. | **Whitelist-Driven Hard Gate**: the main agent receives only 12 core planning and delegation tools by default (`allowedTools`). All other host file and terminal tools, plus any future MCP or third-party plugin tools, are automatically hidden and blocked at execution time (including nested calls through `run_code`), **enforcing a Main Agent dedicated entirely to planning and acceptance, with Subagents doing all the execution**. |
36
- | **Low-cost models get stuck or go off track** | **Runtime black box**: after dispatch, you can only wait for completion or timeout, or block and poll with `wait_agent`. | **Periodic background inspection of event logs + dynamic correction by the powerful model**: a background timer reads running Workers' session event logs directly (reading and summarizing make no model calls), summarizing elapsed time, rounds, new tool calls, and the latest output. A lightweight notice wakes the main agent when something looks abnormal or takes too long, so the powerful model can assess it and give targeted corrections. |
37
- | **Large batches of similar tasks** | Native `workflow` asks the model to write arbitrary JavaScript, which can get out of control and does not enforce consistent model routing. | **Declarative `orchestrate` pipelines**: structured `items × stages` fan-out and multistage pipelines, with per-item failure isolation and strict JSON Schema validation. Every Worker is forced onto the low-cost subagent route. |
38
-
39
- ---
40
- <div align="center">
41
-
42
- ## Core Features
43
- </div>
44
-
45
- ### 1. A powerful Main Agent and low-cost Subagents (independent panel, immediate updates)
46
-
47
- In the dedicated **Dispatch mode panel** below the composer, the main-agent and subagent model routes are fully independent:
48
- - **Main Agent**: choose your strongest flagship model (such as `gpt-astra-6` or `claude-opus-5.5`) to focus on clarifying requirements, splitting tasks, correcting course, and accepting final results.
49
- - **Subagent**: choose a slightly less capable but very inexpensive model with high throughput (such as `deepseek-v4.1-flash` or `gpt-luna-6`). **Every Worker launched through `delegate` or `orchestrate` must share this low-cost route**, unless the user explicitly names a different model for temporary use in the current message.
50
- - **Anti-burn protection**: dispatch fails with an error if no subagent model is configured
51
-
52
- ![Dispatch Mode Panel](docs/images/dispatch-panel.png)
53
-
54
- ### 2. A hard whitelist gate: the main agent plans and accepts results; subagents execute
55
-
56
- Instead of relying on prompts asking the main model to use subagents more often, the plugin installs two guards at DSH's tool-definition outlet (`tools.definitions`) and execution layer (`tools.guard`), using a **whitelist-driven** approach. The definition layer trims the tool table visible to the model in real time, treating global tools and tools in scopes such as `ops_*` equally; the execution layer rejects any calls that slip through. Both layers read the current configuration on every request or call, without creating `tools.restrict` event storms, avoiding tool-visibility churn and prompt-cache invalidation from the official tool-hiding mechanism.
57
- - **Main Agent stripped of all execution tools**:
58
- <div align="center">
59
-
60
- > ### DEFAULT_ALLOWED_TOOLS permits only 12 planning, delegation, and read-only session tools by default
61
- >
62
- > _`delegate`, `orchestrate`, `send_message`, `interrupt_agent`, `todo_write`, `ask_user_question`, `compress`, and five read-only session log tools._
63
- >
64
- > ### All file access, search, and terminal tools, plus any future MCP or third-party plugin tools, are automatically hidden and blocked at execution time
65
- >
66
- > _(`read` / `edit` / `write` / `apply_patch`), (`grep` / `glob`), (`bash` / `pwsh`), web fetching, and native `subagent` / `workflow`_
67
- >
68
- > ### Even nested calls through run_code are blocked. To allow additional tools, check them under Allowed Tools on the right of the panel.
69
- </div>
70
-
71
- - **Subagents retain the full toolchain**: dispatched Workers are exempt from the gate and read or write files, run tests, and inspect errors in their own contexts. When finished, they return only a concise conclusion for the main agent to review.
72
- - **Switch at any time**: when the main agent needs to act directly, turn off Enable dispatch mode in the panel to restore all its tools immediately, without reopening the session.
73
-
74
- ### 3. Periodic background inspection of event logs and correction by the powerful model
75
-
76
- Low-cost Subagents can occasionally get stuck on complex shell escaping or errors. The plugin includes a background inspector driven entirely by logs:
77
- - **Reading the logs makes no model calls**: a background timer directly reads running Workers' session event logs at the configured interval (600 seconds by default), summarizes elapsed time, rounds, new tool calls, and the latest output, then combines them into a notice that wakes the main agent. Reading and summarizing make no LLM requests
78
- - However, **waking the Main Agent for judgment and steering still consumes Main Agent tokens**: supervision compresses continuous polling into one summary plus one decision; it does not make the entire supervision feature free.
79
- - **The powerful model makes a quick assessment**: after receiving an inspection summary, the main agent needs only a small number of tokens to decide:
80
- - **A) Progress is normal**: reply with one line, `巡检:正常`, and end the turn while the subagent continues.
81
- - **B) Correct course**: call `send_message` to inject corrective instructions directly into the running subagent, specifying the right approach or telling it to skip a blocker.
82
- - **C) Stop wasted work promptly**: call `interrupt_agent` to interrupt a subagent that has gone off track. If it is later reactivated with `send_message`, supervision automatically resumes and resets its notice count.
83
-
84
- ![Example inspection notice and correction](docs/images/patrol-notice.png)
85
-
86
- *Inspection and correction in practice: a low-cost subagent got stuck on shell quotes and backslash escaping. After a scheduled inspection woke the main agent, it supplied the correct syntax directly through `send_message` to get the worker back on track.*
87
-
88
- ### 4. `delegate` and `orchestrate`, built for dispatch mode
89
-
90
- - **`delegate` (asynchronous tasks on demand / parallel fan-out)**:
91
- Dispatch self-contained, independent tasks (goal + allowed files + acceptance commands + fallback on failure). Multiple calls in the same turn start multiple Workers in parallel. The plugin injects a Simplified Chinese response instruction into every subagent's prompt and requires it to finish with a final summary in its reply, without calling `send_message` to report to its parent; the closing message is delivered to the main agent automatically.
92
- **`writeScope` (required, `string[]`)**: declare the files or directories this worker may modify. Supported forms are exact files (`src/index.js`), directories (`dir/` or `dir/**`), and the global root (`*`). Relative paths are normalized lexically against `cwd`, with case-insensitive deduplication on Windows. Omitting the field produces `write-scope-missing`; an empty array or invalid path produces `write-scope-invalid`.
93
- - **`orchestrate` (declarative batch pipelines)**:
94
- Process a batch of items (`items`, 1–64) through a fixed set of stages (`stages`, 1–8), with `maxConcurrency` (1–16, default 4) controlling concurrency. Supports single-stage parallel fan-out and multistage **per-item pipelines without a global barrier**: an item enters stage 2 as soon as its stage 1 finishes, without waiting for slower items. Supports strict stage-level JSON Schema validation and per-item failure isolation.
95
- **`writeScope` (required, `string[]`)**: one top-level declaration applies to the entire batch, which **holds its write scope atomically**. The normalized scope is injected into each stage's prompt as a boundary reminder.
96
- - **Single-writer exclusion (enforced before dispatch)**: `delegate` holds a lease per subagent; `orchestrate` holds one for the entire batch. Both share a process-wide lease table and check for overlaps across tools. Any overlap raises `write-scope-conflict` **before any subagent starts**, including the conflicting path, lease holder, expiration time, and `agentsStarted: 0`, preventing Workers from overwriting the same file concurrently. Leases are released idempotently on `subagent/end`, `agent/disposed`, in `orchestrate`'s `finally` (including errors and aborts), and when the plugin is unloaded, with a 30-minute TTL as a backstop against leaks.
97
-
98
- ---
99
-
100
- ## Requirements
101
-
102
- | Item | Requirement |
103
- | --- | --- |
104
- | **Host environment** | DeepSeek Harness Desktop / Web GUI |
105
- | **Node.js** | `>= 22` (bundled with the DSH Desktop runtime) |
106
- | **Plugin form** | Cordis backend service patch (`cordis.patch.yml`) + Web GUI client extension (`lib/client.js`) |
107
- | **UI language** | Adapts to Chinese / English (`zh-CN` / `en-US`) |
108
-
109
- ### DSH host version compatibility
110
-
111
- The plugin depends on host subagent interfaces (the `startActivation` spec shape, the retry delivery entry point, root-agent enumeration, and the tool registry). DSH `0.2.2-rc.2` introduced a breaking change to these interfaces, so **plugin and host versions must be chosen as a pair**:
112
-
113
- | Plugin version | Supported DSH host | Notes |
114
- | --- | --- | --- |
115
- | `@sshirkit/dsh-orchestrator >= 0.8.3` (current version: `0.8.5`) | **DSH `>= 0.2.2-rc.2`** | Verified against `0.2.2-rc.2` / `0.2.2-rc.3`. Since `0.2.2-rc.2`, the host has flattened the subagent spec, removed the `Symbol.for('dsh.subagent.deliverPrompt')` delivery entry point and `agents.roots()`, and added the `wait_agent` tool. It is therefore **incompatible with `0.2.2-rc.1` and earlier**. Note: although the host adds `wait_agent`, the plugin **intentionally keeps its default whitelist at 12 tools and excludes `wait_agent`**. Blocking polling can leave the main agent idling and misjudging timeouts; supervision already replaces polling with one summary plus one decision. If needed, manually check `wait_agent` in the panel's `allowedTools` list. |
116
- | `dsh-orchestrator 0.8.0 – 0.8.2` | **DSH `<= 0.2.2-rc.1`** | Tested against `0.2.1-rc.3` and `0.2.2-rc.1`. The `@deepseek-ai/dsh-tools` dependency was introduced in `0.8.0`. |
117
- | `dsh-orchestrator <= 0.7.3` | DSH releases predating plugin `0.8.0` | Early standalone tool-registration architecture, without a dependency on `@deepseek-ai/dsh-tools`. |
118
-
119
- > Check the host version before upgrading: see About in DSH or read `package.json` in the installation directory. **Plugin `0.8.3+` with a `0.2.2-rc.1` or older host fails outright when dispatching**; an older plugin with a `0.2.2-rc.2+` host is also unusable. If you cannot upgrade the host yet, stay on plugin `v0.8.2`.
120
-
121
- ---
122
-
123
- ## Installation
124
-
125
- Select Add from GitHub on the DSH plugin page. All three forms below are accepted; paste one into the input field. The first is recommended because it is the least likely to be misinterpreted by the client:
126
-
127
- ```text
128
- https://github.com/SShiRkiT/dsh-orchestrator
129
- github:SShiRkiT/dsh-orchestrator#main
130
- SShiRkiT/dsh-orchestrator#main
131
- ```
132
-
133
- ```bash
134
- # Equivalent CLI installation
135
- dsh plugin --profile desktop add https://github.com/SShiRkiT/dsh-orchestrator
136
- # npm installation (available after publication to npm)
137
- dsh plugin --profile desktop add @sshirkit/dsh-orchestrator
138
- ```
139
-
140
- > After installation, **fully quit and reopen DSH** (client plugins are composed at startup and do not support hot updates). When upgrading, **uninstall the old version** from the plugin page before adding this repository again or `@sshirkit/dsh-orchestrator` (available after publication to npm); two installed copies will compete over the same tool declarations.
141
-
142
- ---
143
-
144
- ## Configuration
145
-
146
- All configuration fields are volatile (dynamic configuration): changes in the panel take effect immediately, without restarting DSH:
147
-
148
- | Field | Default | Description |
149
- | --- | --- | --- |
150
- | `enabled` | `true` | Master switch for dispatch mode. Turning it off immediately restores all main-agent tools in the current session. |
151
- | `workerProvider` / `workerModel` | `""` | Default subagent model route (required; dispatch fails if unconfigured and never silently inherits the main-agent model). |
152
- | `workerReasoningEffort` | `""` | Subagent reasoning effort. Leave empty to let the selected model use its own default. |
153
- | `allowedTools` | 12 built-in tools | Whitelist-driven: the main agent may use only the listed tools; other host, MCP, and plugin tools are automatically hidden and disabled. Check or uncheck tools under Allowed Tools on the right of the panel to allow or disable them; changes apply on the next message. |
154
- | `superviseEnabled` | `true` | Master switch for background subagent inspection. |
155
- | `superviseIntervalSeconds` | `600` | Inspection interval in seconds, from 10 to 86400. Changes take effect immediately while workers are running. |
156
- | `superviseMaxNoticesPerChild` | `3` | Maximum inspection notices per subagent (0–20). `0` disables inspection; running subagents remain registered, and inspection resumes immediately when the value is raised above 0 or unlimited inspection is enabled. |
157
- | `superviseUnlimited` | `false` | Enables unlimited inspections. Ignores the `superviseMaxNoticesPerChild` limit (including `0`) and continues inspecting at each interval until the subagent stops, delivers, or ends. Notice titles omit the denominator (`第 N 次`). |
158
- | `superviseNotifyOnNoProgress` | `false` | Whether to notify even when the subagent log has no new activity (effectively always enabled when `superviseUnlimited` is on). |
159
-
160
- > Note: the main agent's default model is stored in the host's `agent-default-model`, read and written directly by the same Dispatch mode panel, and applies to newly created sessions. Subagent model changes apply to the next delegation.
161
-
162
- ## License
163
-
164
- [MIT](LICENSE) © 2026 [SShiRkiT](https://github.com/SShiRkiT)