dsh-autotier 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.
Files changed (60) hide show
  1. package/AGENTS.md +93 -0
  2. package/CHANGELOG.md +85 -0
  3. package/LICENSE +201 -0
  4. package/README.es.md +247 -0
  5. package/README.hi.md +241 -0
  6. package/README.md +245 -0
  7. package/README.pt.md +246 -0
  8. package/README.zh.md +221 -0
  9. package/SECURITY.md +55 -0
  10. package/THIRD_PARTY_NOTICES.md +63 -0
  11. package/cordis.patch.yml +125 -0
  12. package/docs/preset-row.md +61 -0
  13. package/docs/supporting-lanes.md +45 -0
  14. package/lib/index.js +2848 -0
  15. package/lib/types/command.d.ts +17 -0
  16. package/lib/types/command.d.ts.map +1 -0
  17. package/lib/types/config.d.ts +94 -0
  18. package/lib/types/config.d.ts.map +1 -0
  19. package/lib/types/guard-rules.d.ts +97 -0
  20. package/lib/types/guard-rules.d.ts.map +1 -0
  21. package/lib/types/guard.d.ts +70 -0
  22. package/lib/types/guard.d.ts.map +1 -0
  23. package/lib/types/index.d.ts +60 -0
  24. package/lib/types/index.d.ts.map +1 -0
  25. package/lib/types/intent.d.ts +179 -0
  26. package/lib/types/intent.d.ts.map +1 -0
  27. package/lib/types/judge.d.ts +50 -0
  28. package/lib/types/judge.d.ts.map +1 -0
  29. package/lib/types/policy.d.ts +109 -0
  30. package/lib/types/policy.d.ts.map +1 -0
  31. package/lib/types/routing.d.ts +135 -0
  32. package/lib/types/routing.d.ts.map +1 -0
  33. package/lib/types/schema.d.ts +134 -0
  34. package/lib/types/schema.d.ts.map +1 -0
  35. package/lib/types/service.d.ts +67 -0
  36. package/lib/types/service.d.ts.map +1 -0
  37. package/lib/types/state.d.ts +46 -0
  38. package/lib/types/state.d.ts.map +1 -0
  39. package/lib/types/tiers.d.ts +103 -0
  40. package/lib/types/tiers.d.ts.map +1 -0
  41. package/lib/types/tools.d.ts +26 -0
  42. package/lib/types/tools.d.ts.map +1 -0
  43. package/lib/types/types.d.ts +96 -0
  44. package/lib/types/types.d.ts.map +1 -0
  45. package/package.json +179 -0
  46. package/src/command.ts +73 -0
  47. package/src/config.ts +358 -0
  48. package/src/guard-rules.ts +303 -0
  49. package/src/guard.ts +285 -0
  50. package/src/index.ts +149 -0
  51. package/src/intent.ts +484 -0
  52. package/src/judge.ts +150 -0
  53. package/src/policy.ts +246 -0
  54. package/src/routing.ts +575 -0
  55. package/src/schema.ts +295 -0
  56. package/src/service.ts +131 -0
  57. package/src/state.ts +134 -0
  58. package/src/tiers.ts +212 -0
  59. package/src/tools.ts +128 -0
  60. package/src/types.ts +120 -0
package/AGENTS.md ADDED
@@ -0,0 +1,93 @@
1
+ # AGENTS.md
2
+
3
+ Standalone DeepSeek Harness plugin repository (`dsh-autotier`). Development
4
+ follows the dsh-plugin-guide skill and the official plugin contract; this file
5
+ records repo-local decisions.
6
+
7
+ ## Layout
8
+
9
+ - `src/index.ts` — function-plugin contract (`name`/`inject`/`Config`/`apply`; NO
10
+ default export). Injects `settings`, `llm`, `tools`, `commands` and `sessions`
11
+ (plural — the host service is `ctx.sessions`); `agents`, `planMode`,
12
+ `sessionProjections` and `sandboxPolicy` are read with `ctx.get()` and degrade
13
+ when absent.
14
+ - `src/schema.ts` — the Schemastery schema and the raw (partial) config
15
+ interfaces it resolves. Kept free of executable logic so a schema module never
16
+ mixes function values into its declarations (the plugin-doctor K4 rule).
17
+ - `src/config.ts` — the explicit `resolveConfig` judge (no hidden `?? default`
18
+ in callers) and the resolved interfaces. Object defaults are COMPLETE objects;
19
+ the adapter-owned effort vocabulary is `off | low | high | max` (there is no
20
+ `medium`).
21
+ - `src/service.ts` — `ctx.autotier` (`status()` and the live settings scope).
22
+ - `src/types.ts` — shared vocabulary (tier ids, effort ids, routing modes,
23
+ scenarios, route/status shapes).
24
+ - `tests/` — vitest over the REAL published `0.1.2-rc.1` host packages
25
+ (`Context`, `SessionStore`, `SystemPrompt`, `ToolRuntime`, `CommandRuntime`,
26
+ in-memory `SettingsProvider`) plus one real Loader composition.
27
+
28
+ ## Hard rules applied here
29
+
30
+ - **Tier landing seam**: `agent/request` waterfall, registered at load time on
31
+ the root scope with `{ prepend: true }`; always `await next()` exactly once and
32
+ return a replacement `LlmCallConfig` (provider/model/effort), preserving the
33
+ sampling scalars (`temperature`, `maxTokens`, `stop`) the session already
34
+ chose. Never return `undefined` from the listener.
35
+ - **`inject` names are verified against the checkout**, not guessed: `sessions`
36
+ (plural), `tools`, `commands`, `llm`, `settings`. A wrong name leaves the
37
+ plugin PENDING forever.
38
+ - **No `agent.options` mutation**: agent options are readonly and read cyclically
39
+ by the loop; the request waterfall is the only supported landing.
40
+ - **Guard is defence in depth**: it never weakens `dsh-defend`, the approval
41
+ service or the sandbox policy. A guard that throws escalates the call instead
42
+ of allowing it.
43
+ - **Fail loud**: invalid configuration throws at mount or at the settings write,
44
+ never silently disables routing.
45
+ - **Model-visible ⟺ logged**: the only model-visible content is the `/tier`
46
+ output and the guard's corrective denial. No custom session event is appended
47
+ (that vocabulary is fail-closed on `0.1.2-alpha.1` and later); the trail is the
48
+ plugin logger plus the live `autotier/tier-changed` bus event, and the sole
49
+ append is the `plan/mode` fallback when the plan-mode service is absent.
50
+ - **Registration is an effect**: every listener, command, tool, service and
51
+ settings namespace rides the plugin fiber and disappears on dispose.
52
+
53
+ ## Config
54
+
55
+ Schema in `src/schema.ts` (judged by `src/config.ts`); `cordis.patch.yml`
56
+ documents the same keys inline; the five-language READMEs carry the user-facing
57
+ table.
58
+ `package.json#dshWorkshop` is the omdsh-workshop-package/v1 intake manifest
59
+ (declarations only — evidence paths stay null until their adapter runs).
60
+
61
+ ## Build
62
+
63
+ `typescript` + `tsdown` are regular `dependencies` (the git channel's `prepare`
64
+ builds with production dependencies alone). `scripts/prepare.mjs` wipes `lib/`,
65
+ emits tsc declarations into `lib/types`, then runs tsdown (tsdown `clean` stays
66
+ OFF so the declarations survive). `pnpm-workspace.yaml` declares
67
+ `allowBuilds: { esbuild: true }`.
68
+
69
+ ## Checks
70
+
71
+ `pnpm run typecheck && pnpm run typecheck:ci && pnpm test && pnpm run build &&
72
+ pnpm run verify:self-contained && pnpm run verify:artifacts && pnpm pack`. The
73
+ plain `typecheck` resolves the local harness checkout's type faces through
74
+ tsconfig `paths` (four levels up to `D:\deepseek-harness`); `typecheck:ci`
75
+ resolves the npm-published `0.1.2-rc.1` faces (no paths) and is what CI runs —
76
+ keep both green.
77
+
78
+ ## Release
79
+
80
+ `node scripts/release.mjs <x.y.z>` bumps `package.json`, stamps the CHANGELOG
81
+ `[Unreleased]` section, re-runs the gate, commits, and tags `v<x.y.z>` locally —
82
+ never pushes. Push with `git push origin main --follow-tags`; the release
83
+ workflow then gates again, publishes npm with provenance (secret `NPM_TOKEN`),
84
+ and creates the GitHub Release from the CHANGELOG section.
85
+
86
+ ## Docs
87
+
88
+ - Five-language READMEs (`README.md`, `README.zh.md`, `README.es.md`,
89
+ `README.pt.md`, `README.hi.md`) — keep all five in sync; the English file is
90
+ the source of truth.
91
+ - GitHub topics mirror `package.json` keywords.
92
+ - `THIRD_PARTY_NOTICES.md` records the MIT-licensed guard-rule port from
93
+ `dsh-tier-router`.
package/CHANGELOG.md ADDED
@@ -0,0 +1,85 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-09-09
9
+
10
+ ### Added
11
+
12
+ - **Automatic tier routing on the official seam.** A load-time `agent/request`
13
+ waterfall listener registered on the root scope with `{ prepend: true }`
14
+ replaces the provider/model/effort triple while preserving the sampling
15
+ scalars the session already chose (`temperature`, `maxTokens`, `stop`). It
16
+ always awaits `next()` exactly once and never returns `undefined`.
17
+ - **Deterministic intent gate (zero tokens).** Declarative rule table
18
+ (`intent.rules`: patterns/tools/cwd, priority-ordered), explicit-intent
19
+ patterns, bilingual keyword scoring with word boundaries and a CJK
20
+ co-occurrence rule, structural signals (token bands, tool calls, code fences,
21
+ hard hints, turn depth), image and long-text short-circuits, and the
22
+ attempt-first middle band (shipped disabled).
23
+ - **Low-confidence judge.** Only a turn below `intent.ruleThreshold` calls a
24
+ cheap model, never on cooldown, and abstains after
25
+ `intent.judge.unavailableSkip` consecutive failures.
26
+ - **Fingerprint posteriors.** Per-shape `{cheap,strong}` win-rate counters with
27
+ a Wilson lower bound, ε-greedy exploration, half-life decay and an LRU cap.
28
+ Labels come from terminal turn outcomes only, never from the router's own
29
+ judge call.
30
+ - **Decision state machine.** Precedence: session override → active escalation →
31
+ plan mode → fallback chain → declarative rule → posterior → classifier, with a
32
+ double-threshold hysteresis (`toStrong` / `toCheap`) that damps tier flapping.
33
+ - **Plan-mode handoff.** A complex instruction opens plan mode through the
34
+ optional `planMode` service, falling back to an appended `plan/mode` event when
35
+ the service is not reachable; leaving plan mode returns the session to the
36
+ cheap tier.
37
+ - **High-risk guard on `tools/pre-execute`.** A deterministic, tier-conditional
38
+ denial covering recursive-force deletes (including `sh -c` wrapper payloads the
39
+ upstream rule set misses), destructive commands, credential paths and the
40
+ configured `guard.protectedPaths` review surfaces. A guard that throws
41
+ escalates to the strong tier instead of allowing the call.
42
+ - **Failure escalation and fallback chains.** Same-signature recurrence counting
43
+ within a window raises the tier for a TTL; the effort-first ladder raises the
44
+ current model's effort before paying for a model switch. Permanent route
45
+ failures switch the fallback chain immediately, transient failures wait for
46
+ `dsh-llm-retry` exhaustion (this listener is registered after it on purpose).
47
+ - **Surfaces.** `/tier auto|strong|cheap|off|status`, the read-only `tier_status`
48
+ and `tier_route` tools, the `ctx.autotier` service (`status`, `catalog`), the
49
+ `autotier/route` serial veto event, the `autotier/tier-changed` emit event, and
50
+ a host+wire `autotier` session projection folding `request/header` and
51
+ `plan/mode`.
52
+ - **Configuration.** A Schemastery settings namespace (`autotier`) with
53
+ save-time cross-field validation: tier landings, fallback chains, intent
54
+ thresholds, rules, judge, scenarios, cost mode, guard and escalation switches.
55
+ Reasoning effort accepts exactly the adapter vocabulary
56
+ `off | low | high | max`; the default strong model is `deepseek-v4-pro` and the
57
+ default cheap model is `deepseek-v4-flash`.
58
+ - Five-language READMEs, `cordis.patch.yml` with every key documented inline,
59
+ Apache-2.0 license, security policy and third-party notices (including the
60
+ MIT-licensed guard-rule port and its deliberate deltas).
61
+ - CI workflows: `ci.yml` (typecheck against the checkout faces, `typecheck:ci`
62
+ against the published `0.1.2-rc.1` faces, tests, coverage, lint, README sync,
63
+ build, artifact and self-containment verification), `compat.yml` (real profile
64
+ install, `--dump-config` activation assertion, keyless headless smoke,
65
+ uninstall rollback), `release.yml` (npm provenance + GitHub Release),
66
+ `scorecard.yml` and `plugin-doctor.yml`.
67
+ - Test suites (153 cases): config schema and cross-field resolution, the
68
+ function-plugin contract, fiber-disposal lifecycle over the real host
69
+ services, a real Loader composition over a temporary `cordis.yml`, the guard
70
+ rule table with a 5,909-command upstream-equivalence harness (the port itself
71
+ carries 30 cases, 14 of them case-for-case upstream ports), the classifier
72
+ and posterior matrix, the decision state machine, and a real AgentLoop
73
+ integration suite covering simple/complex routing, the `/tier` override,
74
+ escalation after two same-signature failures, fallback-chain switching and the
75
+ tier projection.
76
+
77
+ ### Known limitations
78
+
79
+ - No browser half yet: the Settings card and composer tier pill are planned for
80
+ v0.2; the host surface they need (`ctx.autotier.status()`/`catalog()`) ships.
81
+ - Fingerprint posteriors are in-memory and reset on restart.
82
+ - The attempt-first middle band ships disabled until the calibration corpus and
83
+ its metric gate land.
84
+ - A model picked in the GUI is not detected automatically; use
85
+ `routingMode: delegated` or `/tier off`.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.es.md ADDED
@@ -0,0 +1,247 @@
1
+ # dsh-autotier
2
+
3
+ Enrutamiento automático por niveles de modelo para DeepSeek Harness: entra una
4
+ instrucción del usuario y sale una decisión de nivel — sin cambiar de modelo a
5
+ mano.
6
+
7
+ La intención compleja (arquitectura, planificación, depuración, ingeniería de
8
+ varios pasos) se planifica en el nivel **strong** y luego se implementa en el
9
+ nivel **cheap**. La intención simple (preguntas, recuperación, tareas por lotes,
10
+ trabajo diario) se diseña e implementa directamente en el nivel **cheap**.
11
+ Mientras el nivel cheap ejecuta, las llamadas de herramienta de alto riesgo son
12
+ denegadas por un guard determinista, y los fallos repetidos escalan al nivel
13
+ strong con un TTL de retorno.
14
+
15
+ - **Repositorio oficial**: <https://github.com/PerryLink/dsh-autotier>
16
+ - **npm**: `dsh-autotier` (nombre simple, sin scope)
17
+
18
+ ## Compatibilidad
19
+
20
+ | Harness | Estado |
21
+ |---|---|
22
+ | `@deepseek-ai/dsh` `0.1.2-rc.1` | compatible (es lo que CI verifica y lo que instala el flujo compat) |
23
+ | `0.1.5-alpha.1` (la línea actual del checkout) | verificado por tipos contra sus caras publicadas; el smoke de extremo a extremo corre en `0.1.2-rc.1` |
24
+ | `@deepseek-ai/cordis` `^4.0.2`, `@deepseek-ai/schemastery` `^3.18.2` | base de peers |
25
+
26
+ El plugin vive solo en el plano host y no necesita un preset propio: la fila host
27
+ se aplica a todas las sesiones. Una sección de prompt en *tu* preset es opcional
28
+ y solo hace visibles las decisiones al modelo (véase [Instalación y desinstalación](#instalación-y-desinstalación)).
29
+
30
+ ## Qué obtienes
31
+
32
+ - **Puerta de intención** — cada turno se clasifica con señales deterministas
33
+ (texto del mensaje, nombres de herramientas, presencia de imágenes, longitud de
34
+ la conversación). La capa de reglas decide sin gastar tokens cuando tiene
35
+ confianza; solo un turno de baja confianza llama al modelo juez barato, y
36
+ nunca dentro del cooldown.
37
+ - **Aterrizaje en el seam oficial** — la decisión se aplica en la waterfall
38
+ `agent/request` devolviendo una terna provider/model/effort de reemplazo. Los
39
+ escalares de muestreo ya elegidos por la sesión (`temperature`, `maxTokens`,
40
+ `stop`) se conservan.
41
+ - **Traspaso a modo plan** — una instrucción compleja entra en modo plan en el
42
+ nivel strong; al salir vuelve al nivel cheap para implementar.
43
+ - **Guard de alto riesgo** — durante la ejecución cheap, los comandos
44
+ destructivos (`rm -rf`, `sudo`, `mkfs`, `git push --force`, escritura de
45
+ ficheros de credenciales, …) se deniegan con un mensaje correctivo que pide
46
+ escalar.
47
+ - **Escalado por fallos** — los fallos repetidos (opcionalmente con la misma
48
+ firma) elevan el nivel durante un TTL; un fallo de modelo/ruta recorre la
49
+ cadena de fallback configurada.
50
+ - **Válvulas manuales** — `/tier auto|strong|cheap|off` y las herramientas
51
+ `tier_status` / `tier_route`. Ajustar `routingMode: delegated` (o `/tier off`)
52
+ detiene el enrutamiento para una sesión que debe conservar su propio modelo.
53
+ - **Servicio `ctx.autotier`** — una superficie de lectura (`status`) más la
54
+ waterfall de veto `autotier/route` y el evento `autotier/tier-changed`, para
55
+ que otros plugins observen o anulen una decisión.
56
+
57
+ ## Inicio rápido
58
+
59
+ ```bash
60
+ npm i -g dsh1024
61
+ dsh1024 plugin --profile web add dsh-autotier
62
+ ```
63
+
64
+ Luego inicia (o reinicia) el harness. La fila se añade a tu
65
+ `cordis.patch.yml`; el enrutamiento empieza en el siguiente turno.
66
+
67
+ ## Instalación y desinstalación
68
+
69
+ **Canal npm**
70
+
71
+ ```bash
72
+ npm i -g dsh1024
73
+ dsh1024 plugin --profile web add dsh-autotier
74
+ ```
75
+
76
+ **Canal git**
77
+
78
+ ```bash
79
+ git clone https://github.com/PerryLink/dsh-autotier.git
80
+ cd dsh-autotier && pnpm install && pnpm run build
81
+ dsh plugin --profile web add .
82
+ ```
83
+
84
+ **Sección de prompt opcional en el preset.** El router funciona sin ella. Para
85
+ que el modelo sepa en qué nivel corre, añade una fila a *tu* preset
86
+ (`docs/preset-row.md` tiene el bloque exacto):
87
+
88
+ ```yaml
89
+ - insert:
90
+ - id: autotier-prompt
91
+ name: '@deepseek-ai/dsh-system-prompt'
92
+ # sections: [...] — véase docs/preset-row.md
93
+ ```
94
+
95
+ **Desinstalación**
96
+
97
+ ```bash
98
+ dsh plugin --profile web remove dsh-autotier
99
+ ```
100
+
101
+ La fila, su namespace de settings, su comando, sus herramientas y sus listeners
102
+ se eliminan con el plugin; no se escribe nada fuera del documento de settings.
103
+
104
+ ## Configuración
105
+
106
+ Cada clave se valida al cargar; un valor inválido falla de forma ruidosa en vez
107
+ de desactivar el enrutamiento en silencio. El `cordis.patch.yml` de este
108
+ repositorio documenta las mismas claves en línea.
109
+
110
+ | Clave | Por defecto | Significado |
111
+ |---|---|---|
112
+ | `tiers.strong.provider` | `deepseek-official` | Provider del nivel de planificación/revisión. |
113
+ | `tiers.strong.model` | `deepseek-v4-pro` | Id de catálogo del modelo strong. |
114
+ | `tiers.strong.effort` | `high` | Vocabulario del adaptador `off` \| `low` \| `high` \| `max`. |
115
+ | `tiers.strong.followSession` | `false` | `false` = el effort de este nivel anula el de la sesión. |
116
+ | `tiers.strong.fallback` | `[]` | Aterrizajes provider/model ordenados si el nivel no está disponible. |
117
+ | `tiers.cheap.provider` | `deepseek-official` | Provider del nivel de implementación. |
118
+ | `tiers.cheap.model` | `deepseek-v4-flash` | Id de catálogo del modelo cheap. |
119
+ | `tiers.cheap.effort` | `low` | Vocabulario del adaptador `off` \| `low` \| `high` \| `max`. |
120
+ | `tiers.cheap.followSession` | `true` | `true` = hereda el effort de la sesión y gana la elección explícita. |
121
+ | `tiers.cheap.fallback` | `[]` | Aterrizajes provider/model ordenados si el nivel no está disponible. |
122
+ | `tiers.vision.provider` | `deepseek-official` | Provider para turnos con imágenes. |
123
+ | `tiers.vision.model` | `deepseek-v4-flash-vision-exp` | El único modelo del catálogo con modalidad de imagen. |
124
+ | `intent.ruleThreshold` | `0.7` | Confianza a partir de la cual la capa de reglas decide sola. |
125
+ | `intent.attemptBand.enabled` | `false` | Empezar la banda media en cheap y escalar ante una señal. |
126
+ | `intent.attemptBand.tauLow` | `0.45` | Límite inferior de la banda attempt-first. |
127
+ | `intent.hysteresis.toStrong` | `0.8` | Puntuación que cambia un turno cheap a strong. |
128
+ | `intent.hysteresis.toCheap` | `0.6` | Puntuación por debajo de la cual un turno strong vuelve a cheap. |
129
+ | `intent.rules` | `[]` | Tabla declarativa de reglas (`when.patterns` / `when.tools` / `when.cwd`, `tier`, `priority`). |
130
+ | `intent.judge.enabled` | `true` | Permitir el juez de baja confianza. |
131
+ | `intent.judge.model` | `''` | Id del modelo juez; vacío = primer modelo del catálogo que contenga `flash`. |
132
+ | `intent.judge.temperature` | `0` | Temperatura de muestreo del juez. |
133
+ | `intent.judge.maxTokens` | `16` | Límite de salida del juez (responde con una palabra). |
134
+ | `intent.judge.cooldownMs` | `30000` | Separación mínima entre dos llamadas al juez. |
135
+ | `intent.judge.timeoutMs` | `2000` | Tiempo límite de la llamada al juez. |
136
+ | `intent.judge.unavailableSkip` | `2` | Fallos consecutivos tras los que el turno omite al juez. |
137
+ | `intent.scenarios` | todos `true` | Interruptores por escenario: `coding`, `review`, `planning`, `retrieval`, `batch`, `daily`, `longText`, `multimodal`. |
138
+ | `intent.costMode` | `balanced` | Arbitraje en la ambigüedad: `cost-first` \| `quality-first` \| `balanced`. |
139
+ | `guard.enabled` | `true` | Activar el guard determinista de alto riesgo. |
140
+ | `guard.tiers` | `[cheap]` | Niveles que el guard protege. |
141
+ | `guard.whitelist` | `[]` | Comandos, herramientas o prefijos de ruta que nunca disparan el guard. |
142
+ | `guard.protectedPaths` | `['.dsh','AGENTS.md','package.json','.github/workflows']` | Superficies de automodificación que fuerzan revisión strong. |
143
+ | `guard.interopDefend` | `auto` | Relación con `dsh-defend`: `auto` audita la convivencia, `none` calla. |
144
+ | `escalation.threshold` | `2` | Fallos dentro de la ventana que elevan el nivel. |
145
+ | `escalation.windowMs` | `60000` | Ventana de conteo de fallos. |
146
+ | `escalation.ttlMs` | `180000` | Cuánto dura un escalado. |
147
+ | `escalation.fallbackTtlMs` | `300000` | TTL usado tras tomar un aterrizaje de fallback. |
148
+ | `escalation.signature` | `true` | Contar recurrencias de la misma firma en vez de cada fallo. |
149
+ | `routingMode` | `auto` | `auto` \| `strong` \| `cheap` \| `delegated` \| `off`. |
150
+
151
+ Todas las claves se pueden editar en caliente desde el namespace de settings
152
+ `autotier` (`$DSH_HOME/settings.yaml`); una escritura que viole un requisito
153
+ cruzado se rechaza al guardar y la última política válida sigue vigente.
154
+
155
+ ## Herramientas y superficies
156
+
157
+ | Superficie | Tipo | Propósito |
158
+ |---|---|---|
159
+ | `/tier` | comando | `auto` \| `strong` \| `cheap` \| `off` \| `status`; anulación por sesión. |
160
+ | `tier_status` | herramienta | Nivel actual, modo, TTL de escalado y estado del guard. |
161
+ | `tier_route` | herramienta | Enruta una intención en seco, sin enviar petición. |
162
+ | `ctx.autotier` | servicio | Superficie `status()` para otros plugins. |
163
+ | `autotier/route` | evento serial | Terceros pueden vetar el nivel propuesto. |
164
+ | `autotier/tier-changed` | evento emit | Observabilidad cuando cambia el nivel efectivo. |
165
+
166
+ ## Permisos y datos
167
+
168
+ - **Ficheros** — el plugin no lee ni escribe nada salvo a través del servicio
169
+ compartido de settings (el namespace `autotier`).
170
+ - **Red** — el único tráfico saliente es la llamada al juez, que pasa por la ruta
171
+ normal de `ctx.llm` y el provider configurado.
172
+ - **Registro de sesión** — el plugin no añade eventos de sesión propios. El rastro
173
+ de enrutamiento es el logger del plugin más el evento vivo
174
+ `autotier/tier-changed`; el único añadido es el `plan/mode` de reserva cuando el
175
+ servicio de modo plan no está disponible. Los tipos de evento propios son
176
+ fail-closed desde `0.1.2-alpha.1`, así que no se escribe ningún registro
177
+ duradero del plugin.
178
+ - **Secretos** — este plugin no lee, registra ni almacena credenciales.
179
+
180
+ ## Límites de seguridad
181
+
182
+ - El guard es **defensa en profundidad**, no una sandbox. Deniega los patrones que
183
+ conoce en el nivel cheap y nunca debilita `dsh-defend`, el servicio de
184
+ aprobación ni la política de sandbox. Mantenlos activos.
185
+ - El guard solo protege los niveles de `guard.tiers` (cheap por defecto). Un turno
186
+ strong no se bloquea por diseño: el modelo strong es el revisor.
187
+ - Si el guard mismo lanza, la llamada se escala a strong en lugar de permitirse —
188
+ un guard roto no debe convertirse en una puerta abierta.
189
+ - `/tier off` desactiva el enrutamiento por completo; el harness se comporta
190
+ exactamente como antes de instalar el plugin.
191
+
192
+ ## Limitaciones conocidas
193
+
194
+ - La capa de reglas es determinista y por tanto finita: una frase nueva para una
195
+ petición compleja puede empezar en cheap y escalar solo tras un fallo o una
196
+ denegación del guard. La llamada al juez cubre el medio de baja confianza.
197
+ - El escalado es por agente y en memoria; un reinicio del harness vuelve a `auto`.
198
+ - Cambiar de nivel reinicia la caché de prompt del provider para esa petición, así
199
+ que las sesiones muy activas pueden ver un pequeño coste de fallo de caché en el
200
+ turno de cambio; los umbrales de histéresis existen para que eso sea raro.
201
+ - El plugin enruta peticiones de conversación. La compactación y la generación de
202
+ títulos son seams separados del host; alinea sus propios ajustes de modelo con
203
+ el nivel cheap si quieres el mismo perfil de coste (`docs/supporting-lanes.md`).
204
+ - `followSession: true` en el nivel cheap significa que una elección explícita de
205
+ modelo en la sesión gana; en ese caso el nivel cheap no puede imponer el suyo.
206
+ - **Aún no hay tarjeta de Settings ni píldora del compositor.** El enrutamiento es
207
+ totalmente automático y la superficie host (`ctx.autotier.status()` /
208
+ `catalog()`, `/tier`, `tier_status`, `tier_route`) está completa; la mitad de
209
+ navegador está prevista para v0.2.
210
+ - **Un modelo elegido en la GUI no se detecta automáticamente.** Usa
211
+ `routingMode: delegated` o `/tier off` para detener el enrutamiento.
212
+ - **Las posteriores por huella viven en memoria** y se reinician al reiniciar.
213
+ - **La banda media attempt-first llega desactivada** hasta que exista el corpus
214
+ de calibración (v0.2).
215
+
216
+ ## Desarrollo
217
+
218
+ ```bash
219
+ pnpm install
220
+ pnpm run typecheck # contra las caras de tipo del checkout local del harness
221
+ pnpm run typecheck:ci # contra las caras publicadas 0.1.2-rc.1 (lo que ejecuta CI)
222
+ pnpm test
223
+ pnpm run build
224
+ pnpm run verify:self-contained
225
+ pnpm run verify:artifacts
226
+ pnpm pack
227
+ ```
228
+
229
+ `pnpm run build` emite `lib/types` (declaraciones tsc) y `lib/index.js` (bundle
230
+ tsdown). Las pruebas usan directamente los paquetes host publicados — `Context`
231
+ real, servicios reales de session/tools/commands/settings — más una composición
232
+ real del Loader sobre un `cordis.yml` temporal.
233
+
234
+ ## Temas
235
+
236
+ `dsh`, `dsh-plugin`, `deepseek-harness`, `deepseek`, `cordis`, `router`,
237
+ `model-tier`, `cost`, `auto`.
238
+
239
+ ## Contribuidores
240
+
241
+ PerryLink. Issues y pull requests en
242
+ <https://github.com/PerryLink/dsh-autotier/issues>.
243
+
244
+ ## Licencia
245
+
246
+ Apache-2.0. Véase [LICENSE](./LICENSE) y
247
+ [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md).