@kangyishuai/dsh-advisor 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kangyishuai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,186 @@
1
- # Temporary Holding Version
1
+ # @kangyishuai/dsh-advisor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > A separately configured advisor model the main model can consult when _it_ decides to — before committing to an approach, when an error keeps recurring, before declaring a task done. Advisory only: it reads the conversation, returns structured advice, and never approves, blocks or runs anything.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@kangyishuai/dsh-advisor?color=cb3837&logo=npm)](https://www.npmjs.com/package/@kangyishuai/dsh-advisor) [![DSH](https://img.shields.io/badge/verified%20on%20DSH-0.2.2--rc.1-4b6bfb)](#compatibility) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
6
+
7
+ [中文](./README.zh-CN.md)
8
+
9
+ Unofficial plugin for [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness). Not affiliated with DeepSeek.
10
+
11
+ > **Status: early.** Verified against the current target DSH version — see the [Compatibility](#compatibility) table. The tool, the picker and the model lookup sit on host seams that are semi-public at best, so a DSH upgrade can silently disable them (read [Side effects, limitations & risks](#side-effects-limitations--risks) first). Young software — start in `shadow` mode and keep an eye on the ledger.
12
+
13
+ ## What it does
14
+
15
+ This is an **on-demand** advisor, not a passive reviewer. The main model decides when a second opinion is worth a call; the plugin does not re-read every turn on a schedule, so cost and latency grow with the number of _decisions_, not with the length of the conversation.
16
+
17
+ - **A tool the model calls.** The plugin registers one tool, `advisor` (no required parameters; an optional `focus` string names the specific doubt). The tool description tells the main model to consult before substantive work, when the same error keeps recurring, before changing approach after a failure, and before declaring the task done — and to stop calling on short reactive tasks.
18
+ - **A second model reads the whole conversation.** On a consultation the plugin renders the session transcript — user messages, assistant messages, **tool calls and their results** — into one bounded text and sends it to the advisor route you configured. Advisor and main model can be the same model, another model on the same route, or a different provider.
19
+ - **Structured advice, in the same turn.** The advisor answers with one JSON object: a verdict (`reviewed` / `declined`), a severity (`nit` / `concern` / `blocker`), advice capped at 900 characters, up to five risks, up to five acceptance checks, and evidence anchors (tool-call ids, message ids, paths). "Nothing to add" is a valid answer. The result comes back as a normal tool result, so the main model continues without a new turn.
20
+ - **Advisory only.** The advisor cannot approve, deny or run tools, and its output never authorizes an action. The main model still decides and still owns the result.
21
+ - **`off` / `shadow` / `advisory`.** Off by default. `shadow` runs one consultation after each normally completed turn and records it without injecting it; `advisory` is the live mode.
22
+ - **Cross-provider by design.** The advisor route is independent of the main model. Different model families miss different things, which is the point of a second opinion — but read [Cost & privacy](#cost--privacy) before pointing it at another vendor.
23
+ - **Budgets and a ledger.** Per turn, per session, per hour and a per-day cost ceiling, plus a token ledger at `<DSH_HOME>/advisor/usage.jsonl`. DSH does not record usage for extra model calls, so the plugin records it itself.
24
+
25
+ ### What it is not
26
+
27
+ | Not this | Why |
28
+ | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
29
+ | A per-turn reviewer that re-checks every answer | Cost and latency would scale with the conversation, and repeated "looks fine" reviews add noise, not signal. |
30
+ | A permission or approval gate | Advisory means advisory: nothing here can block or allow a tool call. |
31
+ | A multi-model voting panel | One advisor, one answer — no aggregation rules to argue with. |
32
+ | A model router | It never switches the main model; it only answers. |
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ dsh plugin --profile desktop add @kangyishuai/dsh-advisor
38
+ ```
39
+
40
+ To run the working tree instead of a published version, pack it first — `link:` installs do not work (the host's `@deepseek-ai/*` resolution only covers packages whose real path is inside the profile):
41
+
42
+ ```bash
43
+ cd packages/advisor
44
+ pnpm pack --pack-destination /tmp
45
+ dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz
46
+ ```
47
+
48
+ Re-run `pnpm pack` + `add` after changing the code. The plugin has a host half and a thin client half: **restart the DSH desktop app** for host changes and **refresh the page** for client changes. Nothing is sent anywhere until you configure an advisor route and turn the plugin on.
49
+
50
+ ## Configure
51
+
52
+ **The advisor model's base URL, API key and wire protocol are not managed by this plugin.** Configure them in DSH _Settings → Models_ — the `dsh-llm-pi-ai` `providers` map, where each key is one route. This plugin only stores the **route name** and a model id; it never reads or writes credentials.
53
+
54
+ Settings live in one JSON file, `<DSH_HOME>/advisor.settings.json` (`DSH_HOME` defaults to `~/.dsh`; the plugin's `dataRoot` config overrides it). The host re-reads the file before each consultation (1 s cache), so editing it applies to the next call without a restart. Unknown keys are dropped, out-of-range numbers are clamped, and a corrupt file falls back to the defaults. **The default is `off`** — a plugin that spends money and sends conversation content stays opt-in.
55
+
56
+ | Key | Default | Range / values | Meaning |
57
+ | -------------------- | ----------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
58
+ | `mode` | `"off"` | `off` / `shadow` / `advisory` | Whether the plugin may call the advisor at all. |
59
+ | `provider` | `""` | route name from Settings → Models, up to 300 chars | Advisor route. Empty means never call. |
60
+ | `model` | `""` | model id under that route, up to 300 chars | Advisor model. Empty means never call. |
61
+ | `reasoningEffort` | `""` | an effort id from the model, `""` = model default | Thinking effort for the advisor. An unsupported value is retried once without an effort; `doctor` warns about it. |
62
+ | `maxTokens` | `4096` | 256–32000 | Output cap per consultation. |
63
+ | `temperature` | `null` | 0–2, `null` = not sent | `null` lets the model adapter decide. |
64
+ | `maxCallsPerTurn` | `1` | 0–8, `0` = unlimited | Consultations per turn. |
65
+ | `maxCallsPerSession` | `32` | 0–1000, `0` = unlimited | Consultations per session. |
66
+ | `maxCallsPerHour` | `12` | 0–500, `0` = unlimited | Sliding one-hour window. |
67
+ | `maxCostPerDayUsd` | `0` | 0–10000, `0` = unlimited | Daily spend ceiling in USD. Only meaningful once the two prices below are set. |
68
+ | `priceInputPerMTok` | `0` | 0–1000 | Your advisor model's input price, USD per million tokens. `0` = do not estimate money. |
69
+ | `priceOutputPerMTok` | `0` | 0–1000 | Output price, USD per million tokens. |
70
+ | `privacyScope` | `"summary"` | `full` / `summary` / `off` | How much of the conversation is sent — see [Cost & privacy](#cost--privacy). |
71
+ | `redact` | `true` | boolean | Best-effort scrubbing of token-shaped strings before anything is sent. |
72
+ | `immuneTurns` | `3` | 0–20 | Turns to stay quiet after a delivery. Used by shadow delivery; reserved in this MVP — see the note below. |
73
+ | `dedupe` | `true` | boolean | Suppress repeated suggestions. Used by shadow delivery; reserved for the tool path — see the note below. |
74
+ | `sessionCap` | `24` | 0–200 | Max advice items delivered per session; once reached only `blocker` still gets through. |
75
+ | `tiers` | `{}` | map of `"provider/model"` → number | Capability ranks for the pairing check. Without an entry the pairing is reported as unverified, never as passed. |
76
+ | `pairingEnforcement` | `"warn"` | `warn` / `block` | What to do when the advisor's declared tier is lower than the main model's. |
77
+ | `timeoutMs` | `90000` | 5000–600000 | Per-consultation timeout; `/advisor cancel` aborts sooner. |
78
+ | `maxInputChars` | `60000` | 4000–400000 | Total transcript budget; excess in the middle is elided and head/tail are kept. |
79
+
80
+ > **Note on `sessionCap`, `dedupe`, `immuneTurns`:** `sessionCap` is enforced — after that many delivered items in one session only `blocker` advice is still returned. `dedupe` and `immuneTurns` are persisted and used by the shadow path, but the tool path does not suppress a consultation because of them (you asked for it explicitly). The ceilings that stop _calls_ altogether are `maxCallsPerTurn` / `maxCallsPerSession` / `maxCallsPerHour` / `maxCostPerDayUsd`.
81
+
82
+ Example (placeholder route and model names — use the ones the picker shows you):
83
+
84
+ ```json
85
+ {
86
+ "mode": "shadow",
87
+ "provider": "my-router",
88
+ "model": "large-model",
89
+ "priceInputPerMTok": 3,
90
+ "priceOutputPerMTok": 15
91
+ }
92
+ ```
93
+
94
+ **Evidence anchors.** Each advice item may cite `{kind, ref}` anchors (a tool-call id, a message id, a file path). The plugin checks every ref against the session and marks the item unverified when nothing matches; if **none** of the cited anchors exist, the severity is downgraded one step and the advice says so. This is how a hallucinated "that failing command" gets caught.
95
+
96
+ **Advice line and report.** Each consultation is recorded as a session plugin record (not part of the model-visible surface), so the turn gets a compact advisor line in the chat and `/advisor report` can attribute adoption over time. Attribution is deliberately conservative: no signal, no credit.
97
+
98
+ **Picking a model.** `/advisor` opens a picker listing the routes and models already configured in DSH, plus _off_ and _add / configure provider_. Choosing a model switches `mode` to `advisory`. `/advisor doctor` tells you line by line what is still missing.
99
+
100
+ ## Commands
101
+
102
+ | Command | What it does |
103
+ | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
104
+ | `/advisor` | Opens the model picker (client half). Routes and models are re-read every time; nothing is cached across openings. |
105
+ | `/advisor status` | Mode, chosen route, consultations this session and this turn against the limits, cumulative tokens, the last result, and why the last consultation was skipped. |
106
+ | `/advisor on` | Sets `advisory`. Refuses with a pointer to the picker when no advisor model is configured. |
107
+ | `/advisor off` | Sets `off`: no consultation is made, no request is sent. |
108
+ | `/advisor shadow` | Sets `shadow`: consult after each completed turn and record it, without feeding it back. |
109
+ | `/advisor ask` | Runs one consultation **now** and returns the advice as command output. |
110
+ | `/advisor cancel` | Aborts the in-flight consultation — the request is aborted, not merely ignored. |
111
+ | `/advisor report` | Per-session advice report: how many were delivered, how many were **adopted** (heuristic: a path / backticked command / anchored ref from the advice shows up in later events), and how many evidence anchors verified. |
112
+ | `/advisor doctor` | Self-check: host `llm` service, registered routes, route resolution and context window, supported efforts, mode, session budget, ledger state, last failure. Each line states its conclusion and, where relevant, the next step. |
113
+ | `/advisor <provider>/<model> [effort]` | Sets the advisor route directly, with the same validation as the picker (unknown route, missing credentials and unsupported effort are rejected with a readable reason). |
114
+
115
+ The `advisor` **tool** is separate from the command: the model calls it, not you. It takes no required arguments; its optional `focus` is one sentence naming the doubt you want settled — not the task itself, because the transcript always is.
116
+
117
+ ## Cost & privacy
118
+
119
+ This is the section to read before turning it on.
120
+
121
+ - **Every consultation is an extra model call**, billed by the advisor route against that provider's quota. The main model's own usage is unaffected.
122
+ - **Token accounting is ours.** DSH records usage only for the main loop's assistant messages, so the plugin writes its own ledger: `<DSH_HOME>/advisor/usage.jsonl`, one JSON object per consultation (time, session id, trigger `tool` / `shadow` / `manual`, provider, model, effort, verdict, severity, input/output/cache tokens, estimated cost, duration, error code). The file is append-only, rolls over to `usage.jsonl.1` at 2 MiB, and totals are restored from its tail on startup.
123
+ - **Money needs your prices.** DSH's model metadata has no price field. Set `priceInputPerMTok` and `priceOutputPerMTok`; with zeros the ledger records tokens only and no dollar amount is shown. The plugin never guesses prices.
124
+ - **The daily budget counts spend already recorded**, so the one consultation that crosses the ceiling still completes and is charged.
125
+ - **Conversation content leaves the machine when the advisor route is external.** The transcript — with tool calls and results, bounded by `privacyScope` and `maxInputChars` — is sent to whatever base URL that route points at. If that is another vendor, your conversation leaves this machine. Only a route pointing at a local gateway keeps it local. The plugin sends nothing else: no telemetry, no analytics, no network access besides the consultation itself.
126
+ - **`privacyScope` decides how much is sent.** `summary` (default): each text block up to 2,000 characters, tool arguments up to 300, tool results up to 700. `off`: user and assistant text only, up to 1,200 characters, with no tool traffic at all. `full`: text up to 4,000, tool arguments up to 1,200, tool results up to 3,500. The rendered transcript is then capped at `maxInputChars` (60,000 by default): the first 30% and the tail are kept and the middle is replaced by an elision marker.
127
+ - **Redaction is best-effort.** With `redact: true` (default) the plugin scrubs common token-shaped strings, `Authorization` headers, `KEY=` / `TOKEN:`-style assignments, credentials embedded in URLs and PEM private-key blocks **before** clipping. It is a heuristic filter, **not a secret scanner**: it will miss things, it cannot guarantee that a secret never leaves, and it is no substitute for deciding whether this repository may be sent to that provider at all.
128
+ - **Start in `shadow`.** It answers "what would it have said, and what would that have cost" without putting model output back into your session. Read the ledger for a few days, then switch to `advisory`.
129
+
130
+ ## Compatibility
131
+
132
+ | DSH version | Status |
133
+ | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
134
+ | 0.2.2-rc.1 | Verified on this version: unit tests (settings clamping, route selection and pairing, budget guard, transcript rendering, redaction, output contract) and `pnpm probe:runtime`; the desktop read-only regression is `pnpm smoke:advisor-desktop`. Other DSH versions are not verified. |
135
+
136
+ The plugin declares no `engines.dsh` and no `@deepseek-ai/*` peer range: DSH is pre-release and semver ranges over prereleases are unreliable (see [ADR 0005](../../docs/adr/0005-dsh-version-compatibility.md)). Treat this table as the compatibility statement. After a DSH upgrade run `pnpm probe:runtime`, `pnpm smoke:advisor-desktop` and the unit tests, then check `/advisor doctor`.
137
+
138
+ ## Side effects, limitations & risks
139
+
140
+ **What it writes**
141
+
142
+ | Path | What |
143
+ | ----------------------------------------- | ----------------------------------------------------------------------------------------- |
144
+ | `<DSH_HOME>/advisor.settings.json` | Plugin settings; written by `/advisor` and the picker, re-read before every consultation. |
145
+ | `<DSH_HOME>/advisor/usage.jsonl` (+ `.1`) | One line per consultation; append-only, rotated at 2 MiB. |
146
+
147
+ Nothing else: no workspace files, no session-log records of its own (a consultation shows up as an ordinary tool call and tool result in the transcript), no telemetry.
148
+
149
+ - **The advice is model output.** It can be wrong, vague, or confidently wrong. The plugin validates the _shape_ — a JSON object, a known verdict and severity, length caps, declared evidence anchors — not the content. Weigh it and verify it; the main model still owns the decision.
150
+ - **Semi-public host seams.** `llm.prepareCall`, `llm.resolveModelInfo`, `session.deriveMessages`, `tools.register`, `commands.register` and `session/event` on the host side, and `commandUi.decorate` (the picker) on the client side, are not a stable public API. A DSH upgrade can silently disable the tool, the picker or the command. Run `pnpm probe:runtime` after every upgrade; installation failures are logged rather than thrown, so check `/advisor doctor` and the host logs.
151
+ - **Pairing needs your declaration.** DSH has no cross-vendor capability catalog, so "is the advisor at least as strong as the main model" can only come from your `tiers`. Without an entry the result says **unverified** and the consultation proceeds; it never pretends the check passed. With `pairingEnforcement: "block"` a lower declared tier rejects the consultation.
152
+ - **Token counts can be low on an aborted call.** If a consultation is cancelled or times out, no usage chunk may arrive; the ledger then records the call with zero tokens and a cost budget can lag real spend. Treat the ledger as a good estimate, not an invoice.
153
+ - **The advisor route can be broken from outside this plugin** (wrong base URL, missing key, rate limit). Every failure becomes a structured tool result (`MISSING_CREDENTIAL`, `rate_limited`, `overloaded`, `prompt_too_long`, `timeout`, `aborted`, …) and never breaks the turn.
154
+ - **No settings card in this MVP.** Configuration is the JSON file plus the picker; there is no Settings → General page yet.
155
+ - **Partially enforced knobs.** `sessionCap` caps delivered advice per session (blockers exempt); `dedupe` / `immuneTurns` only matter on the shadow path — see [Configure](#configure).
156
+ - **One attempt, not a retry loop.** A malformed advisor answer is reported as unavailable rather than retried; an unsupported thinking effort is retried exactly once without an effort.
157
+ - **`shadow` mode still spends quota.** It skips the injection, not the call. And while `shadow` is on, an explicit `advisor` tool call still returns its advice: the mode suppresses the automatic end-of-turn review, not a model-initiated consultation. Use `off` to stop all calls.
158
+ - **Subagent sessions** are skipped by the automatic shadow review; only top-level turns are reviewed.
159
+
160
+ ## Testing & verification
161
+
162
+ ```bash
163
+ pnpm verify # repo-wide gates: lint, typecheck, plugin conventions, docs, unit tests
164
+ cd packages/advisor && pnpm test # unit tests for this plugin (node --test)
165
+ pnpm smoke:advisor-desktop # desktop (Electron) read-only regression over CDP
166
+ pnpm smoke:agent-tool # repo-wide real-model tool smoke (needs credentials; SKIPs without them)
167
+ ```
168
+
169
+ - `pnpm verify` is the release gate and must pass before a PR.
170
+ - `pnpm smoke:advisor-desktop` is the desktop (Electron) read-only regression, required because the plugin has a client half. It attaches to the running app over CDP, confirms the plugin's client half actually loaded, and never triggers a paid consultation. Pass `--require` in release gates so an unreachable debug port fails instead of silently skipping. It expects the app started with `open -a "DeepSeek Harness" --args --remote-debugging-port=9222 --remote-debugging-address=127.0.0.1`.
171
+ - `pnpm smoke:agent-tool` exercises a registered tool with a real model in a throwaway DSH home. It needs model credentials and exits as SKIP without them — a SKIP is not a pass.
172
+
173
+ Manual end-to-end check, the only way to confirm a real advisor call:
174
+
175
+ 1. `cd packages/advisor && pnpm pack --pack-destination /tmp`, then `dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz`.
176
+ 2. Restart the DSH desktop app; configure the advisor route in _Settings → Models_ if you have not already.
177
+ 3. `/advisor doctor` should explain every line; `/advisor` lists your models; choose one.
178
+ 4. `/advisor shadow`, then work one normal turn. Confirm a line appeared in `<DSH_HOME>/advisor/usage.jsonl` and that no advice was injected.
179
+ 5. `/advisor on` (or `/advisor ask` for a single consultation). Confirm the advice arrives in the tool card / command output and that `/advisor status` counters move.
180
+ 6. `/advisor off` when done. `dsh plugin --profile desktop remove @kangyishuai/dsh-advisor` uninstalls the code; the settings file and ledger stay.
181
+
182
+ Test layers, assertions and the full manual GUI checklist: [docs/testing/advisor.md](../../docs/testing/advisor.md) (Chinese, like the rest of the repository docs). Design notes: [ADR 0010](../../docs/adr/0010-advisor-architecture.md).
183
+
184
+ ## License
185
+
186
+ MIT. Source, issues and release notes: [kangyishuai/dsh-plugins → packages/advisor](https://github.com/kangyishuai/dsh-plugins/tree/main/packages/advisor).
@@ -0,0 +1,181 @@
1
+ # @kangyishuai/dsh-advisor
2
+
3
+ > 给主模型配一个单独配置的顾问模型,由**主模型自己决定**什么时候值得问:动手之前、反复失败时、宣告完成之前。顾问只给建议:它读整段对话、返回结构化答复,不批准、不拦截、不执行任何动作。
4
+
5
+ [![npm](https://img.shields.io/npm/v/@kangyishuai/dsh-advisor?color=cb3837&logo=npm)](https://www.npmjs.com/package/@kangyishuai/dsh-advisor) [![DSH](https://img.shields.io/badge/verified%20on%20DSH-0.2.2--rc.1-4b6bfb)](#兼容性) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
6
+
7
+ [English](./README.md)
8
+
9
+ 非官方 [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness) 插件,与 DeepSeek 无关。
10
+
11
+ > **状态:早期。** 已针对当前目标 DSH 版本验证——见[兼容性](#兼容性)表格。工具、选择器和模型元数据查询都依赖半公开的宿主 seam,DSH 升级可能让它们静默失效(请先读[副作用、限制与风险](#副作用限制与风险))。插件还年轻——建议先用 `shadow` 模式跑几天,盯着账本再决定是否开启。
12
+
13
+ ## 它做什么
14
+
15
+ 这是一个**按需**顾问,不是被动复查器。要不要花这一次调用,由主模型判断;插件不会按轮次自动重读整段对话,所以成本和延迟随**决策次数**增长,而不是随对话长度增长。
16
+
17
+ - **一个由模型调用的工具。** 插件只注册一个工具 `advisor`(没有必填参数,可选一个 `focus` 字符串说明这次想解决的疑点)。工具描述会告诉主模型:在实质动手前、同一个错误反复出现时、失败后准备换方案前、以及宣告任务完成前徵询;短平快的反应式任务则不要反复调用。
18
+ - **第二个模型读整段对话。** 一次徵询时,插件把会话渲染成一段有长度上限的文本——用户消息、助手消息、**工具调用及其结果**——发给配置的顾问路由。顾问与主模型可以是同一个模型、同一路由下的另一个模型,也可以是另一家 provider。
19
+ - **结构化建议,仍在同一个回合里。** 顾问返回一个 JSON 对象:结论(`reviewed` / `declined`)、严重度(`nit` / `concern` / `blocker`)、不超过 900 字符的建议、最多 5 条风险、最多 5 条验收项,以及证据锚点(工具调用 id、消息 id、路径)。「没什么可说的」是合法回答。结果作为普通工具结果回到主模型,不新起一个回合。
20
+ - **只建议,不裁决。** 顾问不能批准、不能拒绝、不能运行工具,它的输出也从不授权任何动作。做决定的仍然是主模型。
21
+ - **`off` / `shadow` / `advisory` 三种模式。** 默认 `off`。`shadow` 在每个正常完成的回合后徵询一次并记账,但不把建议回灌;`advisory` 是正式模式。
22
+ - **天生可跨厂商。** 顾问路由独立于主模型。不同模型族的盲区不一样,这正是「第二意见」的意义——但指向另一家之前,请先读[成本与隐私](#成本与隐私)。
23
+ - **有预算,有账本。** 每回合、每会话、每小时三个次数上限,外加每日金额上限;token 记在 `<DSH_HOME>/advisor/usage.jsonl`。DSH 不会为这种额外模型调用记 usage,所以插件自己记。
24
+
25
+ ### 它不是什么
26
+
27
+ | 不是这个 | 为什么 |
28
+ | ----------------------------- | ---------------------------------------------------------------------- |
29
+ | 每答一轮就复查一遍的 reviewer | 成本和延迟会随对话叠加,重复的「看起来没问题」只会增加噪音,不是信号。 |
30
+ | 权限 / 审批闸门 | 它只是建议:这里没有任何东西能放行或阻止一次工具调用。 |
31
+ | 多模型投票面板 | 一个顾问、一个答案,没有聚合规则可吵。 |
32
+ | 模型路由器 | 它从不切换主模型,只负责回答。 |
33
+
34
+ ## 安装
35
+
36
+ ```bash
37
+ dsh plugin --profile desktop add @kangyishuai/dsh-advisor
38
+ ```
39
+
40
+ 想在本地跑工作区里的源码,先打包再装——`link:` 装法不可用(宿主解析 `@deepseek-ai/*` 时只覆盖真实路径位于 profile 内的包):
41
+
42
+ ```bash
43
+ cd packages/advisor
44
+ pnpm pack --pack-destination /tmp
45
+ dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz
46
+ ```
47
+
48
+ 改完代码要重新 `pnpm pack` 再 `add`。插件有 host 半和一层很薄的 client 半:**host 改动重启 DSH 桌面版**,**client 改动刷新页面**。在你配置好顾问路由并正式开启之前,它不会把任何内容发出去。
49
+
50
+ ## 配置
51
+
52
+ **顾问模型的 baseURL、API key 和线路协议都不归本插件管。** 去 DSH 的*设置 → 模型*里配——也就是 `dsh-llm-pi-ai` 的 `providers` 字典,每个键是一条路由。本插件只保存**路由名**和模型 id,从不读写凭据。
53
+
54
+ 插件设置只有一个 JSON 文件:`<DSH_HOME>/advisor.settings.json`(`DSH_HOME` 默认 `~/.dsh`,插件配置里的 `dataRoot` 可覆盖)。宿主在每次徵询前重读(1 秒缓存),所以改文件对下一次调用立即生效,不用重启。未知键会被丢弃,越界的数字会被夹紧到区间,文件损坏则回落到默认值。**默认是 `off`**——一个会花钱、会把会话内容发出去的插件必须显式开启。
55
+
56
+ | 键 | 默认 | 范围 / 取值 | 说明 |
57
+ | -------------------- | ----------- | -------------------------------------- | ------------------------------------------------------------------- |
58
+ | `mode` | `"off"` | `off` / `shadow` / `advisory` | 是否允许调用顾问。 |
59
+ | `provider` | `""` | 设置 → 模型里的路由名,最长 300 字符 | 顾问路由。留空 = 永不调用。 |
60
+ | `model` | `""` | 该路由下的模型 id,最长 300 字符 | 顾问模型。留空 = 永不调用。 |
61
+ | `reasoningEffort` | `""` | 模型支持的思考档 id,`""` = 用模型默认 | 顾问的思考档。填了不支持的值会去掉思考档重试一次,`doctor` 会告警。 |
62
+ | `maxTokens` | `4096` | 256–32000 | 单次徵询的输出上限。 |
63
+ | `temperature` | `null` | 0–2,`null` = 不传 | `null` 表示交给模型 adapter 决定。 |
64
+ | `maxCallsPerTurn` | `1` | 0–8,`0` = 不限 | 每回合徵询次数。 |
65
+ | `maxCallsPerSession` | `32` | 0–1000,`0` = 不限 | 每会话徵询次数。 |
66
+ | `maxCallsPerHour` | `12` | 0–500,`0` = 不限 | 滚动一小时内。 |
67
+ | `maxCostPerDayUsd` | `0` | 0–10000,`0` = 不限 | 每日金额上限(美元)。只有下面两个单价填了才有意义。 |
68
+ | `priceInputPerMTok` | `0` | 0–1000 | 顾问模型的输入单价,美元 / 百万 token。`0` = 不算钱。 |
69
+ | `priceOutputPerMTok` | `0` | 0–1000 | 输出单价,美元 / 百万 token。 |
70
+ | `privacyScope` | `"summary"` | `full` / `summary` / `off` | 发送多少内容——见[成本与隐私](#成本与隐私)。 |
71
+ | `redact` | `true` | 布尔 | 发送前对密钥形态的字符串做尽力而为的脱敏。 |
72
+ | `immuneTurns` | `3` | 0–20 | 投递后保持安静的回合数。shadow 投递用;工具路径不据此拦截。 |
73
+ | `dedupe` | `true` | 布尔 | 抑制重复建议。shadow 投递用;工具路径不据此拦截。 |
74
+ | `sessionCap` | `24` | 0–200 | 单会话最多投递多少条建议;到顶后只有 `blocker` 继续投递。 |
75
+ | `tiers` | `{}` | `"provider/model"` → 数字的映射 | 配对校验用的能力档位。没有条目时结论是「未校验」,不会假装通过。 |
76
+ | `pairingEnforcement` | `"warn"` | `warn` / `block` | 顾问声明的档位低于主模型时怎么办。 |
77
+ | `timeoutMs` | `90000` | 5000–600000 | 单次徵询超时;`/advisor cancel` 可以更早中止。 |
78
+ | `maxInputChars` | `60000` | 4000–400000 | 会话文本总预算;超出部分折叠中间、保留首尾。 |
79
+
80
+ > **关于 `sessionCap`、`dedupe`、`immuneTurns`:** `sessionCap` 会生效——单会话投递到上限后,只有 `blocker` 级建议还会返回。`dedupe` 与 `immuneTurns` 会被保存并用于 shadow 路径,但工具路径不会因为它们跳过徵询(是模型显式要求的)。真正会拦住**调用本身**的是 `maxCallsPerTurn` / `maxCallsPerSession` / `maxCallsPerHour` / `maxCostPerDayUsd`。
81
+
82
+ 示例(路由名和模型名是占位,请用选择器里看到的真实值):
83
+
84
+ ```json
85
+ {
86
+ "mode": "shadow",
87
+ "provider": "my-router",
88
+ "model": "large-model",
89
+ "priceInputPerMTok": 3,
90
+ "priceOutputPerMTok": 15
91
+ }
92
+ ```
93
+
94
+ **选模型。** `/advisor` 会打开选择器,列出 DSH 里已经配好的路由与模型,外加*关闭*和*添加 / 配置 provider*。选中一个模型会把 `mode` 切成 `advisory`。还缺什么,`/advisor doctor` 会逐条告诉你。
95
+
96
+ ## 命令
97
+
98
+ | 命令 | 行为 |
99
+ | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
100
+ | `/advisor` | 打开模型选择器(client 半)。每次打开都重新取路由和模型,不跨次缓存。 |
101
+ | `/advisor status` | 模式、顾问路由、本会话 / 本回合已用与上限、累计 token、最近一次结果,以及最近一次「为什么没徵询」。 |
102
+ | `/advisor on` | 切到 `advisory`。还没配置顾问模型时拒绝执行,并指向选择器。 |
103
+ | `/advisor off` | 切到 `off`:不徵询,不发请求。 |
104
+ | `/advisor shadow` | 切到 `shadow`:每个完成的回合后徵询一次并记账,但不回灌。 |
105
+ | `/advisor ask` | **立刻**徵询一次,并把建议作为命令输出返回。 |
106
+ | `/advisor cancel` | 中止在途徵询——请求会被真正 abort,不只是忽略结果。 |
107
+ | `/advisor doctor` | 逐项自检:宿主 `llm` 服务、已注册路由、路由解析与上下文窗口、支持的思考档、模式、会话预算、账本状态、最近一次失败。每行给出结论,必要时给出下一步。 |
108
+ | `/advisor <provider>/<model> [effort]` | 直接指定顾问路由,校验规则与选择器一致(未知路由、缺凭据、不支持的思考档都会给可读原因)。 |
109
+
110
+ `advisor` **工具**和命令是两回事:工具由模型调用,不是你。它没有必填参数;可选的 `focus` 是一句话,用来说明你想让顾问解决的疑点——不是任务本身,任务永远是整段对话。
111
+
112
+ ## 成本与隐私
113
+
114
+ 这一节请在开启前读完。
115
+
116
+ - **每次徵询都是一次额外的模型调用**,按顾问路由计费,走那家 provider 的额度。主模型自身的 usage 不受影响。
117
+ - **token 由插件自己记账。** DSH 只为主动环里的 assistant 消息记 usage,所以插件单写一份账本:`<DSH_HOME>/advisor/usage.jsonl`,一次徵询一行 JSON(时间、会话 id、触发方式 `tool` / `shadow` / `manual`、provider、model、思考档、结论、严重度、输入 / 输出 / 缓存 token、估算金额、耗时、错误码)。文件只追加,超过 2 MiB 滚动到 `usage.jsonl.1`,启动时从文件尾部恢复累计数。
118
+ - **算钱需要你填单价。** DSH 的模型元数据没有价格字段。填 `priceInputPerMTok` 和 `priceOutputPerMTok`;都留 0 时账本只记 token,界面不显示金额。插件从不猜价格。
119
+ - **每日预算统计的是已经记下的花费**,所以跨过上限的那一次徵询仍会完成并计费。
120
+ - **顾问路由在外部时,会话内容会离开本机。** 渲染后的会话文本(含工具调用与结果,受 `privacyScope` 和 `maxInputChars` 限制)会发到该路由指向的 baseURL。如果那是另一家厂商,你的对话就离开了这台机器;只有指向本地网关的路由才留在本机。除此之外插件什么都不发:没有遥测,没有统计,除了徵询本身不访问网络。
121
+ - **`privacyScope` 决定发多少。** `summary`(默认):每个文本块最多 2,000 字符,工具参数最多 300,工具结果最多 700。`off`:只发用户与助手的文本(最多 1,200 字符),完全不发工具往来。`full`:文本最多 4,000,工具参数最多 1,200,工具结果最多 3,500。渲染完再按 `maxInputChars`(默认 60,000)封顶:保留前 30% 和结尾,中间替换成省略标记。
122
+ - **脱敏是尽力而为。** `redact: true`(默认)会在**截断之前**清掉常见的密钥形态字符串、`Authorization` 头、`KEY=` / `TOKEN:` 形式的赋值、URL 里内嵌的凭据,以及 PEM 私钥块。它是启发式过滤,**不是密钥扫描器**:一定会漏,也无法保证密钥绝不外发;更不能替代「这个仓库是否允许发给那家 provider」这个判断。
123
+ - **先开 `shadow`。** 它回答的是「它本来会说什么、本来要花多少」,但不把模型输出塞回你的会话。看几天账本,再切到 `advisory`。
124
+
125
+ ## 兼容性
126
+
127
+ | 已验证的 DSH 版本 | 状态 |
128
+ | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
129
+ | 0.2.2-rc.1 | 已在该版本验证:单测(设置夹紧、选路与配对、预算守卫、会话渲染、脱敏、输出契约)与 `pnpm probe:runtime`;桌面端只读回归为 `pnpm smoke:advisor-desktop`。其他 DSH 版本未验证。 |
130
+
131
+ 插件不声明 `engines.dsh`,也不声明 `@deepseek-ai/*` 的 peer 范围:DSH 还在预发布阶段,semver 对预发布版本不可靠(见 [ADR 0005](../../docs/adr/0005-dsh-version-compatibility.md))。这张表就是兼容性声明。DSH 升级后请跑 `pnpm probe:runtime`、`pnpm smoke:advisor-desktop` 和单测,再看 `/advisor doctor`。
132
+
133
+ ## 副作用、限制与风险
134
+
135
+ **它会写什么**
136
+
137
+ | 路径 | 内容 |
138
+ | ------------------------------------------ | ------------------------------------------------------ |
139
+ | `<DSH_HOME>/advisor.settings.json` | 插件设置;由 `/advisor` 和选择器写入,每次徵询前重读。 |
140
+ | `<DSH_HOME>/advisor/usage.jsonl`(+ `.1`) | 一次徵询一行;只追加,超过 2 MiB 滚动。 |
141
+
142
+ 没有别的:不写工作区文件,不往会话日志里塞自己的记录(一次徵询就是普通的工具调用与工具结果),没有遥测。
143
+
144
+ - **建议是模型输出。** 它可能错、可能空泛、可能一本正经地错。插件校验的是*形状*——是 JSON 对象、结论与严重度在闭集内、长度封顶、证据锚点格式合法——不是内容。请自己掂量、自己核实;做决定的仍然是主模型。
145
+ - **半公开的宿主 seam。** host 侧的 `llm.prepareCall`、`llm.resolveModelInfo`、`session.deriveMessages`、`tools.register`、`commands.register`、`session/event`,以及 client 侧的 `commandUi.decorate`(选择器),都不是稳定的公开 API。DSH 升级可能静默地让工具、选择器或命令失效。每次升级后跑 `pnpm probe:runtime`;安装失败只写日志不抛错,所以还要看 `/advisor doctor` 和宿主日志。
146
+ - **配对档位需要你自己声明。** DSH 没有跨厂商的能力目录,所以「顾问是不是至少和主模型一样强」只能来自你填的 `tiers`。没有条目时结论是**未校验**,徵询照常进行;它不会假装校验通过。把 `pairingEnforcement` 设成 `"block"` 时,档位更低的顾问会被拒绝。
147
+ - **被中止的调用 token 可能记少。** 徵询被取消或超时时,可能收不到 usage chunk;账本会把这次记成 0 token,金额预算可能落后于真实花费。把账本当可靠估算,别当账单。
148
+ - **顾问路由可能因为插件之外的原因坏掉**(baseURL 写错、缺密钥、限流)。所有失败都会变成结构化的工具结果(`MISSING_CREDENTIAL`、`rate_limited`、`overloaded`、`prompt_too_long`、`timeout`、`aborted`…),不会把回合弄断。
149
+ - **本 MVP 没有设置页卡片。** 配置就是 JSON 文件加选择器,还没有「设置 → 通用」里的卡片。
150
+ - **部分生效的旋钮。** `sessionCap` 会限制单会话投递条数(blocker 豁免);`dedupe` / `immuneTurns` 只在 shadow 路径上有意义——见[配置](#配置)。
151
+ - **只试一次,没有重试循环。** 顾问输出解析失败会报 unavailable,不重试;不支持的思考档只会去掉思考档重试一次。
152
+ - **`shadow` 模式照样花钱。** 它省掉的是回灌,不是调用。而且 `shadow` 期间,模型主动调用 `advisor` 工具仍会拿到建议:这个模式抑制的是回合结束后的自动复查,不是模型发起的徵询。要彻底停调用请用 `off`。
153
+ - **子代理会话**不会被自动 shadow 复查;只有顶层会话的回合会被复查。
154
+
155
+ ## 测试与验证
156
+
157
+ ```bash
158
+ pnpm verify # 仓库级门禁:lint、类型、插件规范、文档一致性、单测
159
+ cd packages/advisor && pnpm test # 本插件的单测(node --test)
160
+ pnpm smoke:advisor-desktop # 桌面版(Electron)只读回归,走 CDP
161
+ pnpm smoke:agent-tool # 仓库级真实模型工具冒烟(需要凭据,没有就 SKIP)
162
+ ```
163
+
164
+ - `pnpm verify` 是发版门禁,提 PR 之前必须通过。
165
+ - `pnpm smoke:advisor-desktop` 是桌面版(Electron)只读回归;插件有 client 半,所以这是硬性要求。它通过 CDP 连上正在运行的应用、确认 client 半真的加载,**不会**触发需要付费的徵询。发版门禁里加 `--require`,这样连不上调试端口会失败而不是静默跳过。它要求应用用 `open -a "DeepSeek Harness" --args --remote-debugging-port=9222 --remote-debugging-address=127.0.0.1` 启动。
166
+ - `pnpm smoke:agent-tool` 在一次性 DSH 目录里用真实模型驱动一个已注册工具。需要模型凭据;没有凭据时以 SKIP 退出——SKIP 不等于通过。
167
+
168
+ 真机端到端验证(确认「真的发生过一次顾问调用」只能靠这一步):
169
+
170
+ 1. `cd packages/advisor && pnpm pack --pack-destination /tmp`,然后 `dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz`。
171
+ 2. 重启 DSH 桌面版;如果还没配,先在*设置 → 模型*里配好顾问路由。
172
+ 3. `/advisor doctor` 每一行都应有解释;`/advisor` 能列出你的模型,选一个。
173
+ 4. `/advisor shadow`,然后正常做一轮任务。确认 `<DSH_HOME>/advisor/usage.jsonl` 多了一行,且建议没有被注入会话。
174
+ 5. `/advisor on`(或 `/advisor ask` 单次徵询)。确认工具卡 / 命令输出里有建议,且 `/advisor status` 的计数在动。
175
+ 6. 用完 `/advisor off`。`dsh plugin --profile desktop remove @kangyishuai/dsh-advisor` 卸载代码;设置文件和账本会保留。
176
+
177
+ 测试分层、断言明细与完整的手工 GUI 清单见 [docs/testing/advisor.md](../../docs/testing/advisor.md);设计取舍见 [ADR 0010](../../docs/adr/0010-advisor-architecture.md)。
178
+
179
+ ## License
180
+
181
+ MIT。源码、issue 与发版记录:[kangyishuai/dsh-plugins → packages/advisor](https://github.com/kangyishuai/dsh-plugins/tree/main/packages/advisor)。
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: advisor
3
+ name: "@kangyishuai/dsh-advisor"
@@ -0,0 +1,81 @@
1
+ // @ts-check
2
+ // 采纳归因:顾问给了建议之后,主模型到底有没有照做?
3
+ //
4
+ // 不依赖模型自觉回写(那样覆盖率注定很低)。做法是**启发式追踪信号**:从建议里抽出
5
+ // 可追踪的东西(路径、反引号里的命令、证据 ref),看之后的会话事件里有没有出现。
6
+ // 宁可判「未判定」,也不要把「碰巧提到同一个文件」算成采纳。
7
+ import { extractPaths } from "./anchors.js";
8
+
9
+ /**
10
+ * 从一条建议里抽可追踪信号。
11
+ * @param {{ advice?: string, evidence?: Array<{ ref?: string }> }} data
12
+ * @returns {string[]}
13
+ */
14
+ export function signalsOf(data) {
15
+ const adviceText = typeof data?.advice === "string" ? data.advice : "";
16
+ /** @type {Set<string>} */
17
+ const signals = new Set(extractPaths(adviceText));
18
+ for (const match of adviceText.matchAll(/`([^`]{3,120})`/gu)) signals.add(match[1].trim());
19
+ for (const item of Array.isArray(data?.evidence) ? data.evidence : []) {
20
+ if (typeof item?.ref === "string" && item.ref.trim() !== "") signals.add(item.ref.trim());
21
+ }
22
+ // 太短的信号("a"、"ok")没有区分度,丢掉。
23
+ return [...signals].filter((signal) => signal.length >= 3);
24
+ }
25
+
26
+ /**
27
+ * 判一条建议是否被采纳。
28
+ * @param {any[]} events 会话全量事件
29
+ * @param {number} fromIndex 建议记录所在的事件下标
30
+ * @param {any} data 建议记录的数据
31
+ * @returns {{ verdict: "adopted"|"unknown", why: string }}
32
+ */
33
+ export function attributeAdoption(events, fromIndex, data) {
34
+ const signals = signalsOf(data);
35
+ if (signals.length === 0) return { verdict: "unknown", why: "建议里没有可追踪的信号" };
36
+ const list = Array.isArray(events) ? events : [];
37
+ for (let index = fromIndex + 1; index < list.length; index += 1) {
38
+ const haystack = JSON.stringify(list[index]?.data ?? "");
39
+ for (const signal of signals) {
40
+ if (haystack.includes(signal)) return { verdict: "adopted", why: signal };
41
+ }
42
+ }
43
+ return { verdict: "unknown", why: "后续没有出现建议里的信号" };
44
+ }
45
+
46
+ /**
47
+ * 汇总一批建议记录(供 `/advisor report` 与未来的设置页使用)。
48
+ * @param {any[]} events
49
+ * @param {Array<{ index: number, data: any }>} records
50
+ * @returns {{ total: number, adopted: number, unknown: number, anchorsChecked: number, anchorsVerified: number, items: Array<{ severity: string, summary: string, verdict: string, why: string, adviceId: string }> }}
51
+ */
52
+ export function summarizeAdoption(events, records) {
53
+ let adopted = 0;
54
+ let anchorsChecked = 0;
55
+ let anchorsVerified = 0;
56
+ /** @type {Array<{ severity: string, summary: string, verdict: string, why: string, adviceId: string }>} */
57
+ const items = [];
58
+ for (const { index, data } of Array.isArray(records) ? records : []) {
59
+ const outcome = attributeAdoption(events, index, data);
60
+ if (outcome.verdict === "adopted") adopted += 1;
61
+ anchorsChecked += Number(data?.anchors?.checked ?? 0) || 0;
62
+ anchorsVerified += Number(data?.anchors?.verified ?? 0) || 0;
63
+ items.push({
64
+ severity: String(data?.severity ?? "nit"),
65
+ summary: String(data?.summary ?? data?.advice ?? "")
66
+ .replace(/\s+/gu, " ")
67
+ .slice(0, 80),
68
+ verdict: outcome.verdict,
69
+ why: outcome.why,
70
+ adviceId: String(data?.adviceId ?? ""),
71
+ });
72
+ }
73
+ return {
74
+ total: items.length,
75
+ adopted,
76
+ unknown: items.length - adopted,
77
+ anchorsChecked,
78
+ anchorsVerified,
79
+ items,
80
+ };
81
+ }