dsh-switchman 1.3.1 → 1.6.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/README.md CHANGED
@@ -2,61 +2,82 @@
2
2
 
3
3
  **English** | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md)
4
4
 
5
- > **The switchman family**, same author, same orchestration: [opencode-switchman](https://github.com/mrzturn/opencode-switchman) (the OpenCode original) · [zcode-switchman](https://github.com/mrzturn/zcode-switchman) (the ZCode port) · **dsh-switchman** (this repo, for DeepSeek Harness).
5
+ > **The switchman family**, same author, same dispatch doctrine: [opencode-switchman](https://github.com/mrzturn/opencode-switchman) (the OpenCode original) · [zcode-switchman](https://github.com/mrzturn/zcode-switchman) (the ZCode port) · **dsh-switchman** (this repo, the DeepSeek Harness edition).
6
6
 
7
- ![dsh-switchman — the context water level drives the switchman and throws the route](docs/assets/hero.svg)
7
+ ![dsh-switchman — the context watermark throws the switches and drops each task into the right lane](docs/assets/hero.svg)
8
8
 
9
- > Context on a meter. Tasks dispatch themselves.
9
+ > A water meter on the context; every task finds its own lane.
10
10
 
11
- A plugin for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH). Once installed, your primary model stops doing everything itself and becomes a dispatcher: measure the water level, pick the lane, hand out the task, check the work. Four things:
11
+ ## Why you need it
12
12
 
13
- **1. Context water-level control.** Every turn measures live session tokens. Soft (default 50k) advises delegating, hard (90k) tightens the per-turn read budget and nudges wrap-up, force (130k) backs the session up and hands it over to compaction — automatically. Run a session all day; your context never drowns in its own history. Every dispatched subagent carries its own hard cap and exits with a HANDOFF summary when it's reached.
13
+ Two pains creep in once you've worked in DSH for a while. First, sessions get heavier the longer they run: history bloats the context into hundreds of thousands of tokens, the model starts forgetting, slowing down, costing more — and a manual /compact loses detail. Second, the main model does everything itself: chasing files, running tests, reconciling data — most of that work belongs on a cheaper model.
14
14
 
15
- **2. Six-lane dispatch.** economy / mechanical / main / hard / vision / review — six cognitive lanes. Pick candidate models per lane in the settings page, rank them strongest-first (optional S/A/B/C tier anchoring), and pin a reasoning effort per route — the dropdown lists the levels each model *actually* supports, not a generic three. A `[SWITCHMAN:POOLS]` table ships with every prompt so the model knows who to call; `enforce` mode rejects out-of-pool models outright.
15
+ dsh-switchman is a plugin for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH). Once installed, the main model stops doing and starts dispatching: measure the watermark, pick a lane, hand out tasks, check acceptance. It's not a new model — it's a dispatch doctrine hooked onto DSH plus a settings page, and it does seven things:
16
16
 
17
- **3. Language preferences.** One dropdown each for replies, code comments, and authored docs. Unset? You get asked once, it's remembered forever, and every later session follows it.
17
+ **1. Context watermark: long sessions don't blow up.** Every turn counts session tokens in real time, and three escalating lines tighten the screws: 50k (soft, adjustable) nudges "time to delegate"; 90k (hard) shrinks the single-read budget and steers toward wrap-up; 130k (force) hands over automatically — forks the session for the record, compacts the context, wakes the fork to continue, task unbroken. Background subagents still running at handover aren't lost either: their ids, tasks, and report paths go into the handover document, so the resumed session knows where to collect reports and never dispatches twice. Every subagent carries its own hard cap and exits after writing its HANDOFF summary. When the automatic intervention doesn't suit you, take over manually: `/ctx-pause` stops all watermark actions (measurement keeps running, the banner switches to paused — it just stops acting), `/ctx-resume` restores them at any time — after a DSH restart the enforcement also comes back on its own, a temporary let-go, not a permanent off; `/ctx-handover` doesn't wait for the watermark to hit the ceiling and starts the same handover on demand: fork a backup, compact the context, wake the continuation (the session is first steered to an idle boundary, so the result can take a few minutes).
18
18
 
19
- **4. Delegate-by-default doctrine.** Replaces DSH's shipped conservative team policy ("only create teammates when asked"): trivia stays hands-on (<200 lines read, <50 changed), real work gets delegated by default; every change gets verified — >20 lines goes to a tester, >300 lines or core logic goes to a reviewer. Say "don't use teams" and it steps aside instantly.
19
+ **2. Six dispatch pools: the right model for every job.** Economy (batch small chores), mechanical (template rewrites), main (day-to-day coding), hard (hard reasoning and large refactors), vision (images), review (independent verification). On the settings page you tick candidates, order priorities, grade S/A/B/C, and pin a per-route thinking effort — the effort dropdown lists the levels that model actually supports, not a generic three. Every turn's prompt carries a `[SWITCHMAN:POOLS]` recommendation table, and the main model dispatches by it. Three enforcement modes: off / advice / force (force = out-of-pool models get rejected outright).
20
20
 
21
- Only one model? Still worth it — water-level control and the doctrine don't care how many models you have.
21
+ **3. Agent Teams mode: from solo to a team.** Off by default — after install it's lightweight subagent dispatch. Two independent toggles on the settings page:
22
+
23
+ - **Agent teams** — once on, the team doctrine is injected (delegate by default + tiered verification + shared task-board discipline) and DSH's Agent Teams is enabled automatically: the main model can pull standing teammates (`spawn_teammate`), put work on a shared task board (`team_task_*`), and message teammates. When to form a team follows clear discipline: parallelizable independent subtasks, bulky self-contained work, high main-context watermark, need for role separation; one-off single-point investigations still go to a subagent. Turn the toggle off and the team clauses vanish without residue, and team tools are never yanked from sessions still running.
24
+ - **Subagent model whitelist sync** — DSH keeps an authorization whitelist "allow agents to pick models for subagents": routes chosen in a pool but not authorized get rejected when dispatched by name (marked ⚠ in teams mode). Flip this toggle and the union of all six pools is written into that whitelist wholesale — switchman becomes the single source of truth, no double configuration. The whitelist takes effect as a per-new-session snapshot; the sync only affects sessions started afterwards.
25
+
26
+ The session header gives at-a-glance feedback: the ⚡ "autonomous team" badge and ◇ with the session's actual model; while an auto-handover runs, a live indicator shows "handover in progress · backup session / compacting context / waking the successor".
27
+
28
+ **4. Language preferences: ask once, remember forever.** One dropdown each for replies, code comments, and documents; scope is global or per-project (`.switchman/lang.json`). Skipping is fine — on first use you're asked once in your DSH interface language, and every session obeys the answer afterwards.
29
+
30
+ **5. Interface language: the plugin itself speaks your language.** In the "Interface" section atop the settings page sits the "Interface language" dropdown (setting key `uiLocale`): Auto (default, follows the DeepSeek Harness app language), or any built-in interface language picked by hand — options always appear under the language's own endonym, never translated. It switches only the plugin's own interface (badge, home panel, settings page), never the DSH app language: selecting previews live with no restart, the choice is remembered after save and restored on the next launch, and any failure falls back to the app language; the dictionaries ship inline in the plugin bundle, nothing to download.
31
+
32
+ **6. Tiered verification: every change gets checked.** Changes over 20 lines go to a tester; over 300 lines, or touching core / security / data-consistency logic, additionally to an independent reviewer. The review model is picked anchored on the model of "the agent that wrote the diff", avoiding it where possible; when the pool can't, the conclusion declares DOWNGRADED. Say "don't use the team" once and it drops back to solo instantly.
33
+
34
+ **7. `/vision`: text-only models can still handle images.** When the main model can't read images, DSH rejects image-bearing messages at the gate. Paste the image, type `/vision what's wrong with this image`, and the image goes to a vision-pool model; the verdict comes back into the current session. A heads-up "current model can't read images" appears above the input box; when a direct image send is rejected, the message is rewritten as `/vision` and resent automatically — no manual redo; with no vision pool configured the command refuses and points to the settings.
35
+
36
+ Worth installing even with a single model — watermark control and tiered verification don't care how many models you have, and long single-model sessions benefit just the same.
22
37
 
23
38
  ## Bundled skills
24
39
 
25
- - **db-query** — read-only MySQL/Redis verification: run SQL to check records, cache keys / TTLs, cross-store consistency. Refuses all writes. One-time setup below.
26
- - **git-commit-message** — convention-compliant commit text. Text only; never touches git.
27
- - **requirement-docs** — one spec for requirements / PRD / design docs, archived to `docs/requirements-and-design/`.
40
+ - **db-query** — read-only MySQL / Redis verification: run SQL to reconcile data, inspect cache keys / TTL, cross-database consistency checks; every write refused. Needs one-time initialization before first use (see below).
41
+ - **git-commit-message** — generates disciplined commit messages; text only, never runs git for you.
42
+ - **requirement-docs** — the house standard for requirement analysis / PRD / design docs; output is archived to `docs/requirements-and-design/`.
28
43
 
29
44
  ## Quick start
30
45
 
31
- 1. **Install** — from any agent session, or the Web plugin manager:
46
+ 1. **Install** — have an agent run it in any session, or use the Web plugin management page:
32
47
 
33
48
  ```
34
49
  plugin_manager: install_bundle target=dsh-switchman
35
50
  ```
36
51
 
37
- or from a local checkout (linked; re-run `remove_bundle` + `install_bundle` after pulling changes):
52
+ Or install from a local checkout (link mode; after an update, `remove_bundle` + `install_bundle` again):
38
53
 
39
54
  ```
40
55
  plugin_manager: install_bundle target=/path/to/dsh-switchman
41
56
  ```
42
57
 
43
- 2. **Restart DSH** — quit the app entirely and reopen (a page reload is not enough) so the client-module table picks up the bundle.
58
+ Or with the `dsh` CLI in a terminal — pick the profile matching how you run it:
44
59
 
45
- 3. **Open the settings page** — Settings → dsh-switchman. The first screen is language preferences: one dropdown each for replies / comments / docs, each with a live `current: …` line. Skip them if you like — you'll be asked once and remembered.
46
-
47
- ![Settings page and language preferences](docs/assets/conf-demo1.png)
60
+ ```bash
61
+ dsh plugin --profile web add dsh-switchman # Web GUI
62
+ dsh plugin --profile desktop add dsh-switchman # desktop app
63
+ ```
48
64
 
49
- 4. **Fill the six pools** — each pool card lists candidates grouped by provider; tick the ones you want. Tick **manual order** and the card becomes a numbered priority list with ↑ ↓ × controls. The effort dropdown beside each selected route defaults to *follow lane*; pinning it lists the levels that model actually supports (Low / High / Max…). A summary line tracks progress live: “6/6 pools set · 3 ranked · mode advice”.
65
+ 2. **Restart DSH** — quit the app completely and reopen it (a page refresh doesn't count); only then does the client module table recognize the bundle.
50
66
 
51
- ![Dispatch pools](docs/assets/conf-demo2.png)
67
+ 3. **Configure** — Settings → dsh-switchman, or "Switchman Dispatch Center" in the home sidebar. It's a single page of config and looks like this — walk it top to bottom and you're done:
52
68
 
53
- 5. **Ranking and watermark** — the ranking table's order is capability order (strongest first), with optional S/A/B/C tiers; execution mode is `off` / advice / enforce (enforce = out-of-pool models are rejected). Below it, the watermark section tightens behavior by token usage: three thresholds, a per-call read budget, hard-mode behavior (cap / deny), an auto-handover toggle, and a separate cap for subagents. The bottom line carries the commands: `/ctx-pause` to stop intervening · `/ctx-resume` to resume · `/ctx-handover` to back up and hand over now.
69
+ ![The dsh-switchman settings page in full: interface language, language preferences, six dispatch pools, capability ranking and enforcement mode, team toggles, context watermark and commands](docs/assets/conf-interface-en.png)
54
70
 
55
- ![Ranking and context watermark](docs/assets/conf-demo3.png)
71
+ - **Interface** — the plugin's own UI language. The dropdown in the shot sits at English — a live preview of switching; the shipped default is Auto (follows the DSH app language). Picking a language flips the whole page on the spot and is remembered after save; switch back to Auto anytime.
72
+ - **Languages** — the languages of agent output. The scope in the shot is "Global (this profile)" (per-project works too, each reading `.switchman/lang.json`); the reply / code comments / documents dropdowns in the shot all sit at English, each displayed as "endonym (tag)" — e.g. "English (en)" — with a "current: …" status line beneath each. Leaving all three unset is fine too: asked once on first use, remembered from then on.
73
+ - **Dispatch pools** — six cards in two rows of three: economy, mechanical, main on top; hard, vision, review below. Tick candidate models grouped by provider; tick "manual order" and a card becomes a numbered priority list reorderable with ↑ ↓ ×; every route can pin a thinking effort (default "follow lane"). The summary line at the top updates live — in the shot: "4/6 pools configured · 2 ranked · mode advice".
74
+ - **Capability ranking + enforcement mode** — the union of selected models across the six pools, ranked by capability, strongest first (the shot anchors glm-5.3 at S and glm-5.3-flash at A), reorderable and removable; enforcement mode advice / force (force = out-of-pool models rejected outright).
75
+ - **Agent teams** — the two toggles for team mode and whitelist sync, both off by default; in the shot they're on, with a sync status line beneath the toggle.
76
+ - **Context watermark** — the three thresholds (50000 / 90000 / 130000 in the shot), the single-read budget (1500), hard-tier behavior (throttle-pass / block), the auto-handover toggle, and subagent independent caps all live here. Bottom command row: `/ctx-pause` pause intervention · `/ctx-resume` resume · `/ctx-handover` back up and hand over now (it steers the session to an idle boundary before compacting — the result can take a few minutes).
56
77
 
57
- 6. **Verify** — the ⚡ badge appears beside the preset chip in any session header; ask the model “what does the last section of your system prompt say?” — it should mention the dsh-switchman doctrine.
78
+ 4. **Verify** — the ⚡ "autonomous team" badge appears in the session header (with ◇ beside it showing the session's current model); or simply ask the model "what's the heading of the last section of your system prompt" — the answer should mention the dsh-switchman doctrine.
58
79
 
59
- **db-query one-time setup** (script dependencies live inside the skill directory):
80
+ **db-query one-time initialization** (script dependencies install inside the skill directory, nothing pollutes your project):
60
81
 
61
82
  ```bash
62
83
  bash <install-dir>/skills/db-query/scripts/setup.sh
@@ -64,15 +85,16 @@ bash <install-dir>/skills/db-query/scripts/setup.sh
64
85
 
65
86
  ## How it works
66
87
 
67
- - The Host half (`index.js` + `host/`) injects three dynamic system-prompt sections, the read-budget and enforce gates, automatic answer capture, and three slash commands. All settings are volatile fields — saved changes apply to the next prompt assembly, no restart.
68
- - The Client half (`client.js`) renders the ⚡ badge beside the preset chip and the settings page, through official settings-form services.
69
- - `cordis.patch.yml` restates each shipped preset's plugin list verbatim and only extends the persona suffix; the Agent Teams tools themselves still come from the shipped `@deepseek-ai/dsh-experimental-agent-team-profile`.
88
+ - The host half (`index.js` + `host/`) injects the dynamic system-prompt sections (language / lanes / watermark / teams), the read-budget plus enforce double gate, and four slash commands (the ctx trio + `/vision`). A saved setting takes effect at the very next prompt assembly — no restart.
89
+ - The client half (`client.js`) renders the settings page, the ⚡ badge and ◇ model marker in the session header, and the live handover indicator; config snapshots are read and written through the Host route family.
90
+ - The "Switchman Dispatch Center" entry in the home sidebar opens that same settings page as a center panel in one click; the original settings entry stays.
91
+ - `cordis.patch.yml` keeps the factory preset plugin list fully intact and only extends the persona suffix; the Agent Teams tools themselves come from the factory bundle and switch on automatically with teams mode.
70
92
 
71
- ## Maintenance
93
+ ## Maintenance notes
72
94
 
73
- - After a DSH upgrade that changes shipped preset plugin lists, re-sync `cordis.patch.yml` from the new `presets/*.patch.yml` (keep the doctrine suffix), then reinstall.
74
- - Model-facing protocol lines (`[SWITCHMAN:LANG|POOLS|WATERMARK]`) are deliberately English and byte-stable — do not localize them.
75
- - `npm pack --dry-run` must stay at the audited 43-file / ~138 kB shape (the `docs/` screenshots never ship).
95
+ - After a DSH upgrade, if the factory preset plugin list changed, re-sync `cordis.patch.yml` from the new `presets/*.patch.yml` (keeping the doctrine suffix), then reinstall.
96
+ - Protocol lines (`[SWITCHMAN:LANG|POOLS|WATERMARK|TEAMS]`) are deliberately English and byte-stable — don't localize them.
97
+ - `npm pack --dry-run` should keep the audited 50-file / ~205 kB shape (`docs/` screenshots stay out of the package).
76
98
 
77
99
  ## License
78
100
 
package/README.pt.md CHANGED
@@ -2,27 +2,42 @@
2
2
 
3
3
  [English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | **Português** | [Русский](./README.ru.md)
4
4
 
5
- > **A família switchman**, mesmo autor, mesma orquestração: [opencode-switchman](https://github.com/mrzturn/opencode-switchman) (o original para OpenCode) · [zcode-switchman](https://github.com/mrzturn/zcode-switchman) (o port para ZCode) · **dsh-switchman** (este repositório, para DeepSeek Harness).
5
+ > **A família switchman**, mesmo autor, mesma orquestração: [opencode-switchman](https://github.com/mrzturn/opencode-switchman) (o original para OpenCode) · [zcode-switchman](https://github.com/mrzturn/zcode-switchman) (o port para ZCode) · **dsh-switchman** (este repositório, a edição DeepSeek Harness).
6
6
 
7
7
  ![dsh-switchman — o nível de água do contexto comanda o switchman, que desvia a rota](docs/assets/hero.svg)
8
8
 
9
- > Contexto no medidor. Tarefas que se distribuem sozinhas.
9
+ > Contexto no medidor: cada tarefa encontra sozinha a faixa certa.
10
10
 
11
- Um plugin para o [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH). Depois de instalado, seu modelo primário para de fazer tudo sozinho e vira um dispatcher: mede o nível da água, escolhe a faixa, entrega a tarefa, confere o trabalho. Quatro coisas:
11
+ ## Por que você precisa disso
12
12
 
13
- **1. Controle do nível de água do contexto.** A cada turno mede os tokens ao vivo da sessão. Soft (50k por padrão) recomenda delegar, hard (90k) aperta o orçamento de leitura por turno e empurra para encerrar, force (130k) faz backup da sessão e a entrega à compactação — automaticamente. Rode uma sessão o dia inteiro; seu contexto nunca se afoga na própria história. Cada subagent despachado carrega o próprio hard cap e sai com um resumo HANDOFF ao atingi-lo.
13
+ Se você trabalha com o DSH, com o tempo esbarra em duas coisas: a sessão fica cada vez mais pesada — o histórico empurra o contexto para centenas de milhares de tokens, o modelo começa a esquecer, fica lento e caro, e o /compact manual compacta perdendo detalhes no processo; e o modelo principal faz tudo sozinho — consultar um arquivo, rodar um teste, conferir dados: é sempre ele que mastiga tudo, lento e caro, sendo que a maior parte desse trabalho caberia a um modelo barato.
14
14
 
15
- **2. Dispatch em seis faixas.** economy / mechanical / main / hard / vision / review — seis faixas cognitivas. Escolha os modelos candidatos por faixa na página de configurações, ordine-os do mais forte (ancoragem opcional em tiers S/A/B/C) e fixe um reasoning effort por rota — o dropdown lista os níveis que cada modelo *realmente* suporta, não três níveis genéricos. Uma tabela `[SWITCHMAN:POOLS]` vai junto com cada prompt para o modelo saber a quem chamar; o modo `enforce` rejeita na hora modelos fora do pool.
15
+ dsh-switchman é um plugin para o [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH). Depois de instalado, o modelo principal deixa de “fazer tudo sozinho” e vira um dispatcher: mede o nível de água, escolhe a faixa, entrega as tarefas, confere o resultado. Não é um modelo novo: é um regulamento de despacho plugado ao DSH mais uma interface de configuração. Em concreto, ele faz sete coisas:
16
16
 
17
- **3. Preferências de idioma.** Um dropdown para respostas, um para comentários de código e um para documentos escritos. Não definiu? Perguntam uma vez, fica guardado para sempre e toda sessão seguinte o segue.
17
+ **1. Nível de água do contexto: sessões longas não estouram.** A cada turno ele conta os tokens da sessão em tempo real, e três limiares apertam em degraus: 50k (soft, ajustável) lembra que “é hora de delegar”; 90k (hard) aperta o orçamento de leitura por chamada e empurra para encerrar; 130k (force) dispara o handover automático — fork da sessão como cópia de segurança, contexto compactado, continuação despertada: a tarefa não cai no meio. Nem os subagents em segundo plano que ainda estiverem rodando no momento da entrega se perdem: id, descrição da tarefa e caminho do relatório vão para o documento de handover, e a sessão retomada sabe onde coletar os relatórios em vez de despachar o mesmo trabalho de novo. Cada subagent enviado carrega um teto próprio e independente e, ao atingi-lo, sai depois de escrever o resumo HANDOFF. Se a intervenção automática não estiver do seu jeito, assuma o comando manualmente a qualquer momento: `/ctx-pause` interrompe todas as ações do nível (a medição continua rodando, o aviso muda para paused — só deixa de agir), `/ctx-resume` retoma a qualquer momento — depois de reiniciar o DSH a intervenção também volta sozinha, você tira o pé por um tempo, não desliga de vez; `/ctx-handover` não espera o nível encher e dispara sob demanda o mesmo handover: fork de uma cópia de segurança, compactação do contexto, despertar da continuação (a sessão é conduzida primeiro até o limite de inatividade, então o resultado pode demorar alguns minutos).
18
18
 
19
- **4. Doutrina delegate-by-default.** Substitui a política de equipe conservadora de fábrica do DSH ("crie teammates apenas quando pedido"): o trabalho miúdo fica nas suas mãos (<200 linhas lidas, <50 alteradas), o trabalho de verdade é delegado por padrão; toda alteração é verificada — acima de 20 linhas vai para um tester, acima de 300 linhas ou lógica central vai para um reviewer. Diga "não use equipes" e ela sai de cena na hora.
19
+ **2. Seis pools de despacho: a cada trabalho, o seu modelo.** Pool leve (economy, trabalho pequeno em lote), pool mecânico (mechanical, reescritas de molde), pool principal (main, codificação do dia a dia), pool difícil (hard, raciocínio pesado e refatoração em grande escala), pool multimodal (vision, leitura de imagens), pool de revisão (review, verificação independente). Na página de configurações você marca os candidatos, ordena as prioridades (com níveis opcionais S/A/B/C) e fixa um reasoning effort por rota — o dropdown lista os níveis que aquele modelo realmente suporta, não três níveis genéricos. A cada turno, o prompt do modelo principal carrega uma tabela de recomendações `[SWITCHMAN:POOLS]`: o trabalho é despachado seguindo a tabela. O modo de execução tem três estados: off / advice / enforce (enforce = modelos fora do pool são recusados na hora).
20
20
 
21
- Só um modelo? Ainda vale a pena — o controle de nível de água e a doutrina não ligam para quantos modelos você tem.
21
+ **3. Modo Agent Teams: do trabalho solo para comandar uma equipe.** Desligado por padrão: recém-instalado, o trabalho corre no despacho leve via subagent. Na página de configurações, duas chaves independentes:
22
+
23
+ - **Modo Agent Teams** — ao ligar, injeta a doutrina de equipe (delegar por padrão + verificação em níveis + disciplina do quadro de tarefas compartilhado) e habilita automaticamente os Agent Teams do DSH: o modelo principal pode recrutar colegas permanentes (`spawn_teammate`), despachar trabalho para o quadro compartilhado (`team_task_*`) e trocar mensagens com eles. Há uma disciplina clara sobre quando formar a equipe: subtarefas independentes paralelizáveis, trabalho volumoso e autossuficiente, nível de água do contexto principal já alto, necessidade de separar papéis; investigações pontuais de uma vez só continuam pelo subagent. Desligando a chave de novo, as cláusulas de equipe somem sem resíduo, e as ferramentas de equipe nas sessões em andamento não são recolhidas.
24
+ - **Sincronização da whitelist de modelos de subagent** — o DSH tem uma whitelist de autorização “Permitir que os agents escolham modelos para os subagents”: rotas escolhidas nos pools mas não autorizadas são recusadas quando o modelo principal as nomeia explicitamente (no modo equipe, são marcadas com ⚠). Com esta chave ligada, a união dos seis pools é gravada de uma vez nessa whitelist — sem configurar dos dois lados: o switchman é a única fonte da verdade. A whitelist vale como snapshot por “nova sessão”: a sincronização só alcança as sessões abertas depois.
25
+
26
+ O cabeçalho da sessão dá um retorno imediato: badge ⚡ “Equipe autônoma”, ◇ modelo em uso na sessão atual; durante um handover automático aparece um aviso em tempo real do tipo “Handover em andamento · backup da sessão / compactação do contexto / despertar da continuação”.
27
+
28
+ **4. Preferências de idioma: pergunta uma vez, lembra para sempre.** Um dropdown para cada um dos três idiomas — respostas, comentários de código, documentos — com escopo à escolha: global ou por projeto (`.switchman/lang.json`). Pode deixar em branco: no primeiro uso perguntam uma vez, no idioma da interface do DSH, e daí em diante toda sessão segue sozinha.
29
+
30
+ **5. Idioma da interface: o plugin também fala o seu idioma.** No topo da página de configurações entra uma nova seção “Interface” com um dropdown “Idioma da interface” (chave de configuração `uiLocale`): Automático (padrão — segue o idioma do app DeepSeek Harness) ou qualquer um dos idiomas da interface do plugin, sempre pelo endônimo, nunca traduzido. Ele troca só a interface do próprio plugin — o badge do cabeçalho, o painel da página inicial e a página de configurações —, não o idioma do app DSH: a prévia é imediata, sem reinício; ao salvar, a escolha fica guardada; o próximo início a restaura; qualquer falha volta ao idioma do app; e todos os dicionários vêm dentro do bundle, sem download.
31
+
32
+ **6. Verificação em níveis: mudou, testa.** Alterações acima de 20 linhas vão para um tester validar; acima de 300 linhas, ou quando tocam lógica central / segurança / consistência de dados, entra também um reviewer com revisão independente. O modelo do reviewer é escolhido ancorando no modelo do “agent que escreveu o diff”, evitando-o sempre que possível; se no pool não dá para evitá-lo, a conclusão declara DOWNGRADED. Basta dizer “não use equipes” e ele volta na hora a trabalhar sozinho.
33
+
34
+ **7. `/vision`: até modelo somente texto lida com imagens.** Quando o modelo principal não sabe ler imagens, o DSH recusa na entrada as mensagens que as trazem. Você anexa a imagem e digita `/vision onde está o erro nesta imagem`: a imagem é entregue à leitura de um modelo do pool multimodal, e a conclusão volta para a sessão atual. Acima da caixa de entrada aparece antes o aviso “o modelo atual não suporta leitura de imagens”; se um envio direto da imagem for recusado, a mensagem é reescrita uma vez para `/vision` e reenviada sozinha, sem precisar refazer à mão; sem pool multimodal configurado, o comando recusa e indica como configurar.
35
+
36
+ Só um modelo? Ainda vale a pena instalar — o controle do nível de água e a verificação em níveis não ligam para quantos modelos você tem, e sessões longas de modelo único se beneficiam do mesmo jeito.
22
37
 
23
38
  ## Skills embutidas
24
39
 
25
- - **db-query** — verificação somente leitura em MySQL/Redis: rode SQL para checar registros, chaves de cache / TTLs, consistência entre stores. Recusa qualquer escrita. Configuração única abaixo.
40
+ - **db-query** — verificação somente leitura em MySQL/Redis: rode SQL para checar registros, chaves de cache / TTLs, consistência entre stores. Recusa qualquer escrita. Inicialização no primeiro uso (veja abaixo).
26
41
  - **git-commit-message** — texto de commit dentro das convenções. Só texto; nunca toca no git.
27
42
  - **requirement-docs** — uma especificação única para requisitos / PRD / documentos de design, arquivada em `docs/requirements-and-design/`.
28
43
 
@@ -40,23 +55,29 @@ Só um modelo? Ainda vale a pena — o controle de nível de água e a doutrina
40
55
  plugin_manager: install_bundle target=/path/to/dsh-switchman
41
56
  ```
42
57
 
43
- 2. **Reinicie o DSH** — feche o app por completo e reabra (recarregar a página não basta) para que a tabela de módulos do cliente reconheça o bundle.
58
+ ou pelo terminal via CLI `dsh` — escolha o perfil que corresponde a como você executa o DSH:
44
59
 
45
- 3. **Abra a página de configurações** — Settings → dsh-switchman. A primeira tela é a preferência de idioma: um dropdown para respostas / comentários / documentos, cada um com uma linha ao vivo `current: …`. Pode pular — perguntam uma vez e fica guardado.
46
-
47
- ![Página de configurações e preferência de idioma](docs/assets/conf-demo1.png)
60
+ ```bash
61
+ dsh plugin --profile web add dsh-switchman # Web GUI
62
+ dsh plugin --profile desktop add dsh-switchman # app desktop
63
+ ```
48
64
 
49
- 4. **Preencha os seis pools** — cada card de pool lista os candidatos agrupados por provider; marque os que quiser. Marque **manual order** e o card vira uma lista de prioridade numerada com controles ↑ ↓ ×. O dropdown de effort ao lado de cada rota selecionada vem em *follow lane* por padrão; ao fixá-lo, ele lista os níveis que aquele modelo realmente suporta (Low / High / Max…). Uma linha de resumo acompanha o progresso ao vivo: “6/6 pools definidos · 3 ranqueados · modo advice”.
65
+ 2. **Reinicie o DSH** — feche o app por completo e reabra (recarregar a página não basta), para que a tabela de módulos do cliente reconheça o bundle.
50
66
 
51
- ![Pools de dispatch](docs/assets/conf-demo2.png)
67
+ 3. **Configure** — Configurações → dsh-switchman, ou a entrada “Switchman Control Center” na barra lateral da página inicial. A configuração cabe numa página só; ela é esta — um passeio de cima a baixo e está pronto:
52
68
 
53
- 5. **Ranking e watermark** — a ordem da tabela de ranking é a ordem de capacidade (mais forte primeiro), com tiers opcionais S/A/B/C; o modo de execução é `off` / advice / enforce (enforce = modelos fora do pool são rejeitados). Abaixo, a seção de watermark endurece o comportamento conforme o uso de tokens: três limiares, um orçamento de leitura por chamada, o comportamento do modo hard (cap / deny), uma chave de handover automático e um cap separado para subagents. A linha de baixo traz os comandos: `/ctx-pause` para parar de intervir · `/ctx-resume` para retomar · `/ctx-handover` para fazer backup e entregar agora.
69
+ ![Visão completa da página de configuração do dsh-switchman: idioma da interface, preferências de idioma, seis pools de despacho, ranking de capacidade e modo de execução, chaves de equipe, nível de água do contexto e comandos](docs/assets/conf-interface-pt.png)
54
70
 
55
- ![Ranking e watermark de contexto](docs/assets/conf-demo3.png)
71
+ - **Interface** — o idioma da interface do próprio plugin. Na captura está selecionado “Português”: é a prévia imediata, a página inteira troca na hora; por padrão fica “Automático”, que segue o idioma do app DSH. A escolha fica guardada ao salvar, e dá para voltar a “Automático” a qualquer momento.
72
+ - **Idioma** — o idioma do que o agente produz. O escopo na captura é “Global (este perfil)” (dá para ser por projeto também, cada um lê o próprio `.switchman/lang.json`); os três dropdowns de respostas / comentários de código / documentos estão todos fixados em “Português (pt)”, cada um com uma linha de status “Atual: …” embaixo. Pode deixar tudo em branco: no primeiro uso perguntam uma vez e fica guardado.
73
+ - **Pools de despacho** — seis cards em duas fileiras de três: em cima leve / mecânico / principal; embaixo difícil / multimodal / revisão. Em cada card você marca os candidatos agrupados por provider; marque “ordem manual” e ele vira uma lista de prioridade numerada, reordenável com ↑ ↓ ×; ao lado de cada rota dá para fixar o reasoning effort (padrão “seguir a faixa”). A linha de resumo no topo se atualiza em tempo real; na captura: “4/6 pools configurados · 2 no ranking · modo advice”.
74
+ - **Ranking de capacidade + modo de execução** — a união dos modelos escolhidos nos seis pools, ordenada por capacidade com os mais fortes na frente (na captura glm-5.3 ancorado em S e glm-5.3-flash ancorado em A); dá para reordenar e cortar; o modo de execução vai de advice / enforce (enforce = modelos fora do pool são recusados na hora).
75
+ - **Equipe de agentes** — as duas chaves, modo equipe e sincronização da whitelist, começam desligadas; na captura estão ligadas, e abaixo de cada uma há uma linha de status de sincronização.
76
+ - **Nível de água do contexto** — os três limiares (na captura 50000 / 90000 / 130000), o orçamento de leitura por chamada (1500), o comportamento do limiar hard (deixa passar com limitação / bloqueia), a chave do handover automático e o teto independente dos subagents ficam todos nesta área. Uma linha de comandos embaixo: `/ctx-pause` pausa as intervenções · `/ctx-resume` retoma · `/ctx-handover` faz backup e entrega na hora (ele conduz a sessão até o limite de inatividade antes de compactar: o resultado pode levar alguns minutos).
56
77
 
57
- 6. **Verifique** — o badge ⚡ aparece ao lado do chip de preset no cabeçalho de qualquer sessão; pergunte ao modelo “o que diz a última seção do seu system prompt?” — ele deve mencionar a doutrina dsh-switchman.
78
+ 4. **Verifique** — no cabeçalho da sessão aparece o badge ⚡ “Equipe autônoma” (ao lado, o ◇ mostra o modelo da sessão atual); ou pergunte direto ao modelo “qual é o título da última seção do seu system prompt?” — a resposta deve mencionar a doutrina dsh-switchman.
58
79
 
59
- **Configuração única do db-query** (as dependências dos scripts vivem dentro do diretório da skill):
80
+ **Inicialização do db-query no primeiro uso** (as dependências dos scripts vivem dentro do diretório da skill, sem sujar o projeto):
60
81
 
61
82
  ```bash
62
83
  bash <install-dir>/skills/db-query/scripts/setup.sh
@@ -64,15 +85,16 @@ bash <install-dir>/skills/db-query/scripts/setup.sh
64
85
 
65
86
  ## Como funciona
66
87
 
67
- - A metade Host (`index.js` + `host/`) injeta três seções dinâmicas no system prompt, os gates de orçamento de leitura e enforce, a captura automática de respostas e três comandos slash. Todas as configurações são campos voláteis — mudanças salvas valem a partir da próxima montagem de prompt, sem reinício.
68
- - A metade Client (`client.js`) renderiza o badge ⚡ ao lado do chip de preset e a página de configurações, pelos serviços oficiais de settings-form.
69
- - `cordis.patch.yml` reafirma verbatim a lista de plugins de cada preset de fábrica e só estende o sufixo de persona; as ferramentas Agent Teams em si continuam vindo do `@deepseek-ai/dsh-experimental-agent-team-profile` de fábrica.
88
+ - A metade Host (`index.js` + `host/`) injeta as seções dinâmicas do system prompt (idiomas / faixas / nível de água / equipe), a dupla trava de orçamento de leitura + enforce e os quatro comandos slash (o trio ctx mais `/vision`). Toda configuração salva já vale na montagem do prompt seguinte, sem reinício.
89
+ - A metade Client (`client.js`) renderiza a página de configurações, o badge ⚡ e o identificador ◇ do modelo no cabeçalho da sessão e o aviso dinâmico durante o handover; os snapshots de configuração são lidos e gravados pela família de rotas Host.
90
+ - A entrada “Switchman Control Center” na barra lateral da página inicial abre com um clique esta mesma página de configuração como painel central; a entrada nas configurações permanece.
91
+ - `cordis.patch.yml` conserva integralmente a lista de plugins dos presets de fábrica e intervém só no persona suffix; as ferramentas Agent Teams em si vêm do bundle de fábrica e são habilitadas automaticamente ao ligar o modo equipe.
70
92
 
71
93
  ## Manutenção
72
94
 
73
- - Depois de um upgrade do DSH que mude as listas de plugins dos presets de fábrica, ressincronize `cordis.patch.yml` a partir dos novos `presets/*.patch.yml` (mantenha o sufixo da doutrina) e reinstale.
74
- - As linhas de protocolo voltadas ao modelo (`[SWITCHMAN:LANG|POOLS|WATERMARK]`) são deliberadamente em inglês e estáveis a byte — não as localize.
75
- - `npm pack --dry-run` deve continuar na forma auditada de 34 arquivos / ~111 kB (os screenshots de `docs/` nunca vão no pacote).
95
+ - Depois de um upgrade do DSH que mude a lista de plugins dos presets de fábrica, ressincronize `cordis.patch.yml` a partir dos novos `presets/*.patch.yml` (mantenha o doctrine suffix) e reinstale.
96
+ - As linhas de protocolo (`[SWITCHMAN:LANG|POOLS|WATERMARK|TEAMS]`) ficam deliberadamente em inglês e estáveis a byte — não as localize.
97
+ - `npm pack --dry-run` deve continuar na forma auditada de 50 arquivos / ~205 kB (os screenshots de `docs/` não vão no pacote).
76
98
 
77
99
  ## License
78
100
 
package/README.ru.md CHANGED
@@ -2,61 +2,82 @@
2
2
 
3
3
  [English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | **Русский**
4
4
 
5
- > **Семейство switchman**, один автор, одна оркестрация: [opencode-switchman](https://github.com/mrzturn/opencode-switchman) (оригинал для OpenCode) · [zcode-switchman](https://github.com/mrzturn/zcode-switchman) (порт для ZCode) · **dsh-switchman** (этот репозиторий, для DeepSeek Harness).
5
+ > **Семейство switchman**, один автор, одна и та же философия диспетчеризации: [opencode-switchman](https://github.com/mrzturn/opencode-switchman) (оригинал для OpenCode) · [zcode-switchman](https://github.com/mrzturn/zcode-switchman) (порт для ZCode) · **dsh-switchman** (этот репозиторий, версия для DeepSeek Harness).
6
6
 
7
- ![dsh-switchman — уровень воды в контексте управляет стрелочником, и тот переводит маршрут](docs/assets/hero.svg)
7
+ ![dsh-switchman — уровень воды в контексте дёргает стрелку, и задачи уходят на нужный путь](docs/assets/hero.svg)
8
8
 
9
- > Контекст под счётчиком. Задачи распределяются сами.
9
+ > Контекст под счётчиком. Задачи сами находят свою полосу.
10
10
 
11
- Плагин для [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH). После установки ваша основная модель перестаёт всё делать сама и становится диспетчером: измеряет уровень воды, выбирает полосу, раздаёт задачи, проверяет работу. Четыре вещи:
11
+ ## Зачем это нужно
12
12
 
13
- **1. Контроль уровня воды в контексте.** Каждый ход замеряет фактическое потребление токенов сессии. Soft (по умолчанию 50k) советует делегировать, hard (90k) урезает бюджет чтения на ход и подталкивает к завершению, force (130k) делает бэкап сессии и передаёт её компакции — автоматически. Держите сессию открытой хоть весь день; ваш контекст не утонет в собственной истории. Каждый отправленный субагент несёт собственный hard cap и по его достижении выходит с резюме HANDOFF.
13
+ Если работать в DSH подольше, рано или поздно упираешься в две вещи: сессия тяжелеет с каждым сообщением — история раздувает контекст до сотен тысяч токенов, модель начинает забывать, тормозить и дорожать, а ручной /compact при каждом сжатии ещё и теряет детали; и главная модель всё делает сама — прочитать файл, прогнать тест, сверить данные: всё она грызёт сама, медленно и дорого, хотя большая часть этой работы по праву досталась бы дешёвой модели.
14
14
 
15
- **2. Диспетчеризация по шести полосам.** economy / mechanical / main / hard / vision / review — шесть когнитивных полос. Выберите модели-кандидаты по каждой полосе на странице настроек, расставьте от сильнейшей (опциональная привязка к tier-ам S/A/B/C) и зафиксируйте reasoning effort для каждого маршрута — в выпадающем списке те уровни, которые каждая модель *реально* поддерживает, а не три универсальных. Таблица `[SWITCHMAN:POOLS]` уходит с каждым промптом, чтобы модель знала, кого вызывать; режим `enforce` наотрез отвергает модели вне пула.
15
+ dsh-switchman — плагин для [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH). После установки главная модель перестаёт «делать всё сама» и становится диспетчером: замеряет уровень воды, выбирает полосу, раздаёт задачи, принимает работу. Это не новая модель, а свод правил диспетчеризации, пристёгнутый к DSH, плюс страница настроек. Конкретно он делает семь вещей:
16
16
 
17
- **3. Языковые предпочтения.** По одному выпадающему списку для ответов, комментариев в коде и создаваемых документов. Не задано? Спросят один раз, запомнят навсегда, и каждая следующая сессия будет этому следовать.
17
+ **1. Уровень воды в контексте: длинная сессия не переполняется.** Каждый ход подсчитывает токены сессии в реальном времени, и три линии уровня ужесточаются по нарастающей: 50k (soft, настраивается) подсказывает «пора делегировать»; 90k (hard) урезает бюджет разового чтения и подталкивает к завершению; 130k (force) запускает автоматическую передачу — форкает копию сессии в архив, сжимает контекст и будит продолжение, работа не обрывается. Фоновые субагенты, которые ещё бегут в момент передачи, тоже не теряются: id, описания задач и пути к отчётам записываются в документ передачи, и продолжившаяся сессия знает, куда идти за отчётами, а не раздаёт работу заново. У каждого отправленного субагента свой жёсткий потолок: доработав до него, он завершается резюме HANDOFF. Если автоматическое вмешательство работает не так, как вам нужно, возьмите управление в свои руки в любой момент: `/ctx-pause` останавливает все действия по уровню (замер продолжает работать, баннер переключается на paused — вмешательство просто перестаёт действовать), `/ctx-resume` всё возвращает в любой момент — после перезапуска DSH вмешательство тоже вернётся само, вы временно отпускаете, а не выключаете навсегда; `/ctx-handover` не ждёт, пока уровень дойдёт до верха, и запускает ту же передачу по требованию — форкнуть копию, сжать контекст, разбудить продолжение (сессию сначала подводят к границе простоя, поэтому результат может занять несколько минут).
18
18
 
19
- **4. Доктрина delegate-by-default.** Заменяет поставляемую в DSH консервативную политику команд («создавайте teammates только по прямой просьбе»): мелочёвка остаётся ручной работой (<200 прочитанных строк, <50 изменённых), настоящая работа по умолчанию делегируется; каждое изменение проверяется — больше 20 строк уходит тестировщику, больше 300 строк или ядро логики — ревьюеру. Скажите «не использовать команды» — и она мгновенно отойдёт в сторону.
19
+ **2. Шесть пулов диспетчеризации: под каждую работу — своя модель.** Лёгкий пул (economy — мелкие массовые задачи), механический (mechanical — шаблонные переработки), основной (main — повседневный кодинг), пул высокой сложности (hard — тяжёлые рассуждения и крупные рефакторинги), мультимодальный (vision — чтение картинок), пул ревью (review — независимая проверка). На странице настроек отмечаете кандидатов, расставляете приоритеты (можно с привязкой к ступеням S/A/B/C) и для каждого маршрута отдельно фиксируете reasoning effort — выпадающий список ступеней берётся из уровней, которые модель реально поддерживает, а не из трёх универсальных. Каждый ход промпт главной модели несёт с собой таблицу рекомендаций `[SWITCHMAN:POOLS]`, и работа раздаётся по ней. У режима исполнения три состояния: off / advice / enforce (enforce = модель вне пула просто отклоняется).
20
20
 
21
- Всего одна модель? Всё равно стоит — контролю уровня воды и доктрине всё равно, сколько у вас моделей.
21
+ **3. Режим Agent Teams: от работы в одиночку — к своей команде.** По умолчанию выключен: сразу после установки это просто лёгкая диспетчеризация через subagent. На странице настроек два независимых переключателя:
22
+
23
+ - **Режим команды агентов** — при включении внедряет командный регламент (делегирование по умолчанию + многоуровневая проверка + дисциплина общей доски задач) и автоматически включает Agent Teams в DSH: главная модель может нанимать постоянных товарищей по команде (`spawn_teammate`), ставить им задачи на общей доске (`team_task_*`) и обмениваться с ними сообщениями. Когда заводить команду, решает чёткая дисциплина: параллельные независимые подзадачи, объёмная самодостаточная работа, уже высокий уровень воды в главном контексте, потребность разделить роли; разовая точечная разведка по-прежнему идёт через subagent. Если выключить переключатель обратно, от командных пунктов не останется и следа, а инструменты команды из уже работающих сессий не изымаются.
24
+ - **Синхронизация белого списка моделей субагентов** — в DSH есть белый список авторизации «разрешить агентам выбирать модели для субагентов»: если маршрут выбран в пуле, но не авторизован, явное назначение его главной моделью будет отклонено (в командном режиме он помечается ⚠). Включите этот переключатель — и объединение шести пулов целиком запишется в белый список: настраивать дважды не нужно, switchman остаётся единственным источником истины. Белый список применяется по снимку «новая сессия»: синхронизация действует только на сессии, открытые после неё.
25
+
26
+ В шапке сессии — наглядная обратная связь: значок ⚡ «автономная команда», ◇ с фактической моделью текущей сессии; когда идёт автоматическая передача, появляется живая подсказка «идёт передача · резервная сессия / сжатие контекста / пробуждение продолжения».
27
+
28
+ **4. Языковые предпочтения: спросит один раз — запомнит навсегда.** Три выпадающих списка: язык ответов, комментариев в коде и документов; область действия — глобальная или по проекту (`.switchman/lang.json`). Настраивать не обязательно: при первом использовании спросят один раз — на языке интерфейса вашего DSH — и запомнят; дальше каждая сессия соблюдает выбор автоматически.
29
+
30
+ **5. Язык интерфейса: плагин говорит и на вашем языке.** В самом верху страницы настроек появился раздел «Интерфейс» с выпадающим списком «Язык интерфейса» (ключ настройки `uiLocale`): «Авто» (по умолчанию — следует языку приложения DeepSeek Harness) или любой из языков интерфейса плагина, всегда под своим эндонимом, без перевода. Переключается только интерфейс самого плагина — значок в шапке, панель главной страницы и страница настроек, — но не язык приложения DSH: предпросмотр мгновенный, без перезапуска; сохранение запоминает выбор; следующий запуск восстанавливает его; любой сбой возвращает язык приложения; а все словари лежат внутри бандла — ничего скачивать не нужно.
31
+
32
+ **6. Многоуровневая проверка: изменено — проверено.** Изменения больше 20 строк уходят тестировщику на проверку; изменения больше 300 строк или затрагивающие ядро / безопасность / согласованность данных — дополнительно независимому ревьюеру. Модель ревьюера подбирают, привязываясь к модели агента, написавшего этот diff, и стараются её обойти; если пул другого выхода не оставляет, в заключении прямо заявляется DOWNGRADED. Скажете «не использовать команду» — всё мгновенно вернётся к одиночной работе.
33
+
34
+ **7. `/vision`: картинки по зубам даже чисто текстовой модели.** Когда главная модель не читает изображения, DSH прямо на входе отклоняет сообщения с картинками. Прикрепите картинку и введите `/vision что не так на этой картинке` — изображение будет отдано на чтение модели из мультимодального пула, а вывод вернётся в текущую сессию. Над полем ввода заранее подсказывают: «текущая модель не умеет читать изображения»; если прямая отправка картинки отклонена, она один раз автоматически переоформляется в `/vision` и уходит повторно — вручную ничего переписывать не нужно; если мультимодальный пул не настроен, команда откажется и подскажет, что настроить.
35
+
36
+ Всего одна модель? Всё равно стоит поставить — контроль уровня воды и многоуровневая проверка от числа моделей не зависят, и длинная сессия на одной модели выигрывает от них ничуть не меньше.
22
37
 
23
38
  ## Встроенные навыки
24
39
 
25
- - **db-query** — верификация MySQL/Redis только на чтение: выполните SQL, чтобы проверить записи, ключи кэша / TTL, согласованность между хранилищами. Отклоняет любую запись. Разовая настройка — ниже.
26
- - **git-commit-message** — текст коммита по конвенции. Только текст; git не трогает.
27
- - **requirement-docs** — единая спецификация для требований / PRD / дизайн-документов, архивируется в `docs/requirements-and-design/`.
40
+ - **db-query** — верификация MySQL / Redis только на чтение: выполнить SQL для сверки данных, проверить ключи кэша / TTL и согласованность между хранилищами; любую запись отклоняет. При первом использовании нужна инициализация (см. ниже).
41
+ - **git-commit-message** — генерирует выдержанный в конвенциях текст коммита: только текст, git за вас не трогает.
42
+ - **requirement-docs** — единая спецификация для анализа требований / PRD / проектных документов; результаты архивируются в `docs/requirements-and-design/`.
28
43
 
29
44
  ## Быстрый старт
30
45
 
31
- 1. **Установите** — из любой сессии агента или через веб-менеджер плагинов:
46
+ 1. **Установите** — попросите agent выполнить установку в любой сессии, или откройте веб-страницу управления плагинами:
32
47
 
33
48
  ```
34
49
  plugin_manager: install_bundle target=dsh-switchman
35
50
  ```
36
51
 
37
- или из локального checkout'а (в режиме link; после подтягивания изменений снова выполните `remove_bundle` + `install_bundle`):
52
+ или установите из локального checkout'а (режим link; после обновления нужно переустановить: `remove_bundle` + `install_bundle`):
38
53
 
39
54
  ```
40
55
  plugin_manager: install_bundle target=/path/to/dsh-switchman
41
56
  ```
42
57
 
43
- 2. **Перезапустите DSH** — полностью закройте приложение и откройте заново (перезагрузки страницы недостаточно), чтобы таблица клиентских модулей подхватила бандл.
58
+ или установите из терминала командой `dsh` — профиль выбирайте по способу запуска:
44
59
 
45
- 3. **Откройте страницу настроек** — Settings → dsh-switchman. Первый экран — языковые предпочтения: по выпадающему списку на ответы / комментарии / документы, у каждого живая строка `current: …`. Можете пропустить — спросят один раз и запомнят.
46
-
47
- ![Страница настроек и языковые предпочтения](docs/assets/conf-demo1.png)
60
+ ```bash
61
+ dsh plugin --profile web add dsh-switchman # Web GUI
62
+ dsh plugin --profile desktop add dsh-switchman # десктоп-приложение
63
+ ```
48
64
 
49
- 4. **Заполните шесть пулов** — каждая карточка пула перечисляет кандидатов, сгруппированных по провайдеру; отметьте нужные. Отметьте **manual order**, и карточка станет нумерованным списком приоритетов с кнопками ↑ ↓ ×. Выпадающий список effort рядом с каждым выбранным маршрутом по умолчанию стоит на *follow lane*; если его зафиксировать, он покажет уровни, которые эта модель реально поддерживает (Low / High / Max…). Строка сводки в реальном времени показывает прогресс: «6/6 пулов задано · 3 в рейтинге · режим advice».
65
+ 2. **Перезапустите DSH** — полностью закройте приложение и откройте снова (перезагрузка страницы не считается) — только тогда таблица клиентских модулей распознает этот bundle.
50
66
 
51
- ![Пулы диспетчеризации](docs/assets/conf-demo2.png)
67
+ 3. **Настройте** — Настройки → dsh-switchman, или пункт «Диспетчерская Switchman» в боковой панели главной страницы. Вся конфигурация умещается на одной странице; вот она — проход сверху вниз, и всё готово:
52
68
 
53
- 5. **Рейтинг и watermark** — порядок в таблице рейтинга — это порядок по возможностям (сильнейшие первыми), с опциональными tier-ами S/A/B/C; режим исполнения — `off` / advice / enforce (enforce = модели вне пула отклоняются). Ниже секция watermark ужесточает поведение по мере расхода токенов: три порога, бюджет чтения на вызов, поведение жёсткого режима (cap / deny), переключатель автоматической передачи управления и отдельный лимит для субагентов. Нижняя строка несёт команды: `/ctx-pause` — прекратить вмешательство · `/ctx-resume` — возобновить · `/ctx-handover` — сделать бэкап и передать управление прямо сейчас.
69
+ ![Полный вид страницы настроек dsh-switchman: язык интерфейса, языковые предпочтения, шесть пулов диспетчеризации, рейтинг по способностям и режим исполнения, переключатели команды, уровень воды в контексте и команды](docs/assets/conf-interface-ru.png)
54
70
 
55
- ![Рейтинг и watermark контекста](docs/assets/conf-demo3.png)
71
+ - **Интерфейс** — язык интерфейса самого плагина. На снимке выбран «Русский»: это мгновенный предпросмотр, вся страница переключается на месте; по умолчанию стоит «Авто» — следует языку приложения DSH. Выбор запоминается при сохранении, вернуться к «Авто» можно в любой момент.
72
+ - **Язык** — язык того, что производит агент. Область действия на снимке — «Глобально (этот profile)» (можно и по проектам, каждый читает свой `.switchman/lang.json`); три выпадающих списка — ответы / комментарии в коде / документы — на снимке стоят на «Русский (ru)», под каждым строка состояния «сейчас: …». Можно не настраивать ничего: при первом использовании спросят один раз и запомнят.
73
+ - **Пулы диспетчеризации** — шесть карточек в два ряда по три: сверху лёгкий / механический / основной; снизу высокосложный / мультимодальный / рецензентский. На каждой карточке отмечаются кандидаты, сгруппированные по поставщикам; отметьте «ручной порядок» — карточка станет нумерованным списком приоритетов, порядок меняется кнопками ↑ ↓ ×; рядом с каждым маршрутом можно зафиксировать reasoning effort (по умолчанию «следовать полосе»). Сводная строка сверху обновляется в реальном времени; на снимке: «пулов настроено: 4/6 · позиций в рейтинге: 2 · режим advice».
74
+ - **Рейтинг по способностям + режим исполнения** — объединение моделей, выбранных в шести пулах, отсортировано по способности, сильнейшие впереди (на снимке glm-5.3 закреплён на ступени S, glm-5.3-flash — на A); порядок можно менять, лишние убирать; режим исполнения — advice / enforce (enforce = модель вне пула просто отклоняется).
75
+ - **Команда агентов** — оба переключателя, командный режим и синхронизация белого списка, по умолчанию выключены; на снимке включены, под каждым — строка состояния синхронизации.
76
+ - **Уровень воды в контексте** — три порога (на снимке 50000 / 90000 / 130000), бюджет разового чтения (1500), поведение жёсткого порога (пропустить с ограничением / заблокировать), переключатель автоматической передачи и отдельный потолок для субагентов — всё в этом разделе. Внизу строка команд: `/ctx-pause` приостановить вмешательство · `/ctx-resume` возобновить · `/ctx-handover` сделать резервную копию и передать управление прямо сейчас (команда подводит сессию к границе простоя и только потом сжимает контекст, результат может занять несколько минут).
56
77
 
57
- 6. **Проверьте** — значок ⚡ появляется рядом с чипом пресета в шапке любой сессии; спросите у модели «что написано в последней секции твоего системного промпта?» — она должна упомянуть доктрину dsh-switchman.
78
+ 4. **Проверьте** — в шапке сессии появился значок ⚡ «автономная команда» (рядом ◇ показывает модель текущей сессии); либо спросите модель напрямую: «как называется последний раздел твоего системного промпта?» — в ответе должен прозвучать регламент dsh-switchman.
58
79
 
59
- **Разовая настройка db-query** (зависимости скриптов живут внутри каталога навыка):
80
+ **Инициализация db-query при первом использовании** (зависимости скриптов ставятся внутрь каталога навыка и не засоряют проект):
60
81
 
61
82
  ```bash
62
83
  bash <install-dir>/skills/db-query/scripts/setup.sh
@@ -64,15 +85,16 @@ bash <install-dir>/skills/db-query/scripts/setup.sh
64
85
 
65
86
  ## Как это работает
66
87
 
67
- - Host-половина (`index.js` + `host/`) внедряет три динамические секции системного промпта, шлюзы бюджета чтения и enforce, автоматический захват ответов и три слэш-команды. Все настройки — volatile-поля: сохранённые изменения вступают в силу при следующей сборке промпта, без перезапуска.
68
- - Client-половина (`client.js`) отрисовывает значок ⚡ рядом с чипом пресета и страницу настроек — через официальные сервисы settings-form.
69
- - `cordis.patch.yml` дословно повторяет список плагинов каждого штатного пресета и расширяет только суффикс персоны; сами инструменты Agent Teams по-прежнему приходят из штатного `@deepseek-ai/dsh-experimental-agent-team-profile`.
88
+ - Host-половина (`index.js` + `host/`) внедряет динамические секции системного промпта (язык / полосы / уровень воды / команда), двойной шлюз бюджета чтения и enforce и четыре слэш-команды (ctx-тройка + `/vision`). Все настройки после сохранения вступают в силу при следующей сборке промпта — без перезапуска.
89
+ - Client-половина (`client.js`) отрисовывает страницу настроек, значок ⚡ и метку модели ◇ в шапке сессии, живую подсказку во время передачи управления; снимки конфигурации читаются и записываются через семейство маршрутов Host.
90
+ - Пункт «Диспетчерская Switchman» в боковой панели главной страницы: один клик открывает эту же страницу настроек в виде центральной панели; прежний вход в настройки остаётся на месте.
91
+ - `cordis.patch.yml` целиком сохраняет список плагинов заводских пресетов и расширяет только persona suffix; сами инструменты Agent Teams приходят из заводского bundle и автоматически включаются вместе с командным режимом.
70
92
 
71
93
  ## Обслуживание
72
94
 
73
- - После обновления DSH, меняющего списки плагинов штатных пресетов, пересинхронизируйте `cordis.patch.yml` из новых `presets/*.patch.yml` (сохраните суффикс доктрины) и переустановите.
74
- - Строки протокола, адресованные модели (`[SWITCHMAN:LANG|POOLS|WATERMARK]`), намеренно на английском и стабильны побайтово — не локализуйте их.
75
- - `npm pack --dry-run` должен оставаться в аудитированной форме: 34 файла / ~111 kB (скриншоты из `docs/` в пакет никогда не попадают).
95
+ - Если после обновления DSH изменился список плагинов заводских пресетов, пересинхронизируйте `cordis.patch.yml` из новых `presets/*.patch.yml` (сохранив doctrine suffix) и переустановите.
96
+ - Строки протокола (`[SWITCHMAN:LANG|POOLS|WATERMARK|TEAMS]`) намеренно оставлены на английском и стабильны побайтово — не локализуйте их.
97
+ - `npm pack --dry-run` должен сохранять аудированную форму: 50 файлов / ~205 kB (скриншоты из `docs/` в пакет не входят).
76
98
 
77
99
  ## License
78
100