dsh-model-router 0.3.0 → 0.5.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
@@ -46,6 +46,43 @@ Everything else is a planner. That logic lives in `src/policy.ts` as a plain fun
46
46
 
47
47
  The router always stamps `provider` + `model`. `reasoningEffort` and `maxTokens` are *optional per role*: set them in the config and they're enforced for that role; leave them out and those fields inherit from your session's selection. So picking "max effort" in the UI but not pinning `reasoningEffort` in the config still gives you max-effort thinking — it just happens on the routed model.
48
48
 
49
+ ## Turning the router off
50
+
51
+ Routing is on by default. Two ways to switch it off:
52
+
53
+ - **GUI (Settings → Plugins → dsh-model-router):** the plugin registers a live
54
+ settings section; flip `enabled` off. It applies immediately (no restart),
55
+ persists in `settings.yaml` under `model-router:`, and unregisters the prompt
56
+ section and the skill too. Flip it back on and everything returns.
57
+ - **Patch row:** set `enabled: false` in the profile's `cordis.patch.yml` row
58
+ (takes effect on the next boot). `disabled: true` still skips the row entirely.
59
+
60
+ With the router off, requests use the session's selected model (your
61
+ `agent-default-model` setting or the base default) — the router is simply not
62
+ rewriting them.
63
+
64
+ ## The GUI toggle (v0.5.0+)
65
+
66
+ Since v0.5.0 the package ships a browser half, and the harness serves it
67
+ automatically — no extra config. After installing (or updating to) v0.5.0+
68
+ and restarting the profile, **Settings → Plugins** shows a **Model router**
69
+ card with a live **Enabled** switch, an "Overridden" badge and **Reset to
70
+ default** button once you've changed it, and a read-only view of the current
71
+ planner/executor routes and mode. Flipping the switch applies immediately (no
72
+ restart) and persists in `settings.yaml` under `model-router:` — the same
73
+ mechanism the GUI toggle described above uses.
74
+
75
+ One harness-wide caveat (it applies to **all** settings pages — Models,
76
+ Plugins, everything — not to this plugin specifically): the harness serves
77
+ settings pages only to **loopback** browsers (`localhost` / `127.x`). A remote
78
+ browser sees "settings are unavailable" instead of the card. Fallbacks that
79
+ work everywhere:
80
+
81
+ - **Patch row** — set `enabled: false` in the profile's `cordis.patch.yml`
82
+ (takes effect on the next boot), or
83
+ - **`settings.yaml`** — add `model-router: { enabled: false }` under the
84
+ settings file the profile uses; this applies live, same as the GUI.
85
+
49
86
  ## Tuning
50
87
 
51
88
  All configuration lives on the plugin row. Patch it in the profile's `cordis.patch.yml`:
package/cordis.patch.yml CHANGED
@@ -28,6 +28,8 @@
28
28
  # plan: root is pro only while plan mode is active; otherwise it
29
29
  # falls back to the executor route to reserve pro for planning.
30
30
  mode: strict
31
+ # enabled: false # off switch — GUI: Settings → Plugins → model-router (live, no restart); patch row needs a reboot
32
+ # GUI: Settings → Plugins → "Model router" card (v0.5.0+, loopback browser only)
31
33
  # Publish the always-on routing convention prompt section.
32
34
  promptSection: true
33
35
  # Register the `pro-flash-routing` skill in the session catalog.
package/lib/client.js ADDED
@@ -0,0 +1,297 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-model-router",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/client.tsx
27
+ var client_exports = {};
28
+ __export(client_exports, {
29
+ apply: () => apply,
30
+ inject: () => inject
31
+ });
32
+ module.exports = __toCommonJS(client_exports);
33
+ var import_react = require("react");
34
+ var NS = "model-router";
35
+ var inject = ["slots", "locale", "settingsScope"];
36
+ var en = {
37
+ nav: "Model router",
38
+ title: "Model router",
39
+ description: "Role-based model routing: planning runs on deepseek-v4-pro, delegated executor subagents on deepseek-v4-flash.",
40
+ enabled: "Enabled",
41
+ enabledHint: "Off stops rewriting requests and unregisters the prompt section and skill; on restores them.",
42
+ on: "On",
43
+ off: "Off",
44
+ reset: "Reset to default",
45
+ overridden: "Overridden",
46
+ readOnly: "This deployment stores settings read-only in this browser; use the plugin row in the profile's cordis.patch.yml instead.",
47
+ plannerRoute: "Planner model",
48
+ executorRoute: "Executor model",
49
+ mode: "Mode",
50
+ modeStrict: "strict \u2014 the root agent is always the planner",
51
+ modePlan: "plan \u2014 the root agent is pro only while plan mode is active"
52
+ };
53
+ var zh = {
54
+ nav: "\u6A21\u578B\u8DEF\u7531",
55
+ title: "\u6A21\u578B\u8DEF\u7531",
56
+ description: "\u6309\u89D2\u8272\u5206\u914D\u6A21\u578B\uFF1A\u89C4\u5212\u5728 deepseek-v4-pro \u4E0A\u8FD0\u884C\uFF0C\u59D4\u6D3E\u7684\u6267\u884C\u5B50\u4EE3\u7406\u5728 deepseek-v4-flash \u4E0A\u8FD0\u884C\u3002",
57
+ enabled: "\u542F\u7528",
58
+ enabledHint: "\u5173\u95ED\u540E\u505C\u6B62\u6539\u5199\u8BF7\u6C42\uFF0C\u5E76\u6CE8\u9500\u63D0\u793A\u533A\u5757\u4E0E\u6280\u80FD\uFF1B\u91CD\u65B0\u6253\u5F00\u5373\u6062\u590D\u3002",
59
+ on: "\u5F00",
60
+ off: "\u5173",
61
+ reset: "\u6062\u590D\u9ED8\u8BA4",
62
+ overridden: "\u5DF2\u8986\u76D6",
63
+ readOnly: "\u5F53\u524D\u6D4F\u89C8\u5668\u4E2D\u8BE5\u90E8\u7F72\u7684\u8BBE\u7F6E\u4E3A\u53EA\u8BFB\uFF1B\u8BF7\u6539\u7528 profile \u7684 cordis.patch.yml \u4E2D\u7684\u63D2\u4EF6\u884C\u3002",
64
+ plannerRoute: "\u89C4\u5212\u6A21\u578B",
65
+ executorRoute: "\u6267\u884C\u6A21\u578B",
66
+ mode: "\u6A21\u5F0F",
67
+ modeStrict: "strict \u2014 \u6839 agent \u59CB\u7EC8\u4E3A\u89C4\u5212\u8005",
68
+ modePlan: "plan \u2014 \u6839 agent \u4EC5\u5728\u8BA1\u5212\u6A21\u5F0F\u6FC0\u6D3B\u65F6\u4F7F\u7528 pro"
69
+ };
70
+ var ModelRouterCardController = class {
71
+ scope;
72
+ constructor(scope) {
73
+ this.scope = scope;
74
+ }
75
+ get store() {
76
+ return {
77
+ subscribe: (listener) => this.scope.subscribe(listener),
78
+ getSnapshot: () => this.scope.getSnapshot()
79
+ };
80
+ }
81
+ /** Build the face the card's slot registration injects. */
82
+ inject() {
83
+ return {
84
+ hooks: { modelRouterCard: this.store },
85
+ setEnabled: async (next) => {
86
+ try {
87
+ await this.scope.set("enabled", next);
88
+ } catch {
89
+ }
90
+ },
91
+ reset: async () => {
92
+ try {
93
+ await this.scope.unset("enabled");
94
+ } catch {
95
+ }
96
+ }
97
+ };
98
+ }
99
+ /** Stop the scope's mirror subscription when the fiber stops. */
100
+ dispose() {
101
+ void this.scope.dispose();
102
+ }
103
+ };
104
+ function routeRow(label, value) {
105
+ return (0, import_react.createElement)("div", { style: styles.routeRow }, [
106
+ (0, import_react.createElement)("dt", { style: styles.routeLabel }, label),
107
+ (0, import_react.createElement)("dd", { style: styles.routeValue }, value)
108
+ ]);
109
+ }
110
+ function modeLabel(t, mode) {
111
+ return mode === "plan" ? t("modePlan") : t("modeStrict");
112
+ }
113
+ function ModelRouterCard(props) {
114
+ const { t } = props;
115
+ const state = props.useModelRouterCard((snapshot) => snapshot);
116
+ const unavailable = !state.writable || state.mode !== "host";
117
+ const overridden = state.user?.enabled !== void 0;
118
+ return (0, import_react.createElement)("section", { style: styles.card }, [
119
+ (0, import_react.createElement)("div", { style: styles.headRow }, [
120
+ (0, import_react.createElement)("h3", { style: styles.title }, t("title")),
121
+ overridden ? (0, import_react.createElement)("span", { style: styles.badge }, t("overridden")) : null
122
+ ]),
123
+ (0, import_react.createElement)("p", { style: styles.description }, t("description")),
124
+ ...unavailable ? [(0, import_react.createElement)("p", { style: styles.note }, t("readOnly"))] : state.value ? [
125
+ (0, import_react.createElement)("div", { style: styles.switchRow }, [
126
+ (0, import_react.createElement)("label", { htmlFor: "model-router-enabled", style: styles.label }, t("enabled")),
127
+ (0, import_react.createElement)("input", {
128
+ id: "model-router-enabled",
129
+ type: "checkbox",
130
+ checked: Boolean(state.value.enabled),
131
+ onChange: (event) => {
132
+ void props.setEnabled(event.currentTarget.checked);
133
+ },
134
+ style: styles.switch
135
+ }),
136
+ (0, import_react.createElement)("span", { style: styles.status }, state.value.enabled ? t("on") : t("off"))
137
+ ]),
138
+ (0, import_react.createElement)("p", { style: styles.hint }, t("enabledHint")),
139
+ overridden ? (0, import_react.createElement)(
140
+ "button",
141
+ { type: "button", style: styles.reset, onClick: () => void props.reset() },
142
+ t("reset")
143
+ ) : null,
144
+ (0, import_react.createElement)("dl", { style: styles.routes }, [
145
+ routeRow(t("plannerRoute"), state.value.planner?.model ?? "\u2014"),
146
+ routeRow(t("executorRoute"), state.value.executor?.model ?? "\u2014"),
147
+ routeRow(t("mode"), modeLabel(t, state.value.mode))
148
+ ])
149
+ ] : []
150
+ ]);
151
+ }
152
+ var styles = {
153
+ card: {
154
+ display: "flex",
155
+ flexDirection: "column",
156
+ gap: "10px",
157
+ padding: "16px 18px",
158
+ background: "var(--dsw-alias-bg-layer-3)",
159
+ border: "1px solid var(--dsw-alias-border-l2)",
160
+ borderRadius: "12px",
161
+ color: "var(--dsw-alias-label-primary)",
162
+ font: "inherit"
163
+ },
164
+ headRow: {
165
+ display: "flex",
166
+ alignItems: "center",
167
+ gap: "8px"
168
+ },
169
+ title: {
170
+ margin: 0,
171
+ fontSize: "15px",
172
+ fontWeight: 600,
173
+ lineHeight: 1.4
174
+ },
175
+ badge: {
176
+ whiteSpace: "nowrap",
177
+ background: "var(--dsw-alias-bg-module-platform)",
178
+ color: "var(--dsw-alias-label-secondary)",
179
+ borderRadius: "999px",
180
+ padding: "1px 8px",
181
+ fontSize: "11px",
182
+ fontWeight: 500,
183
+ lineHeight: "17px"
184
+ },
185
+ description: {
186
+ margin: 0,
187
+ color: "var(--dsw-alias-label-secondary)",
188
+ fontSize: "13px",
189
+ lineHeight: 1.5
190
+ },
191
+ switchRow: {
192
+ display: "flex",
193
+ alignItems: "center",
194
+ gap: "10px",
195
+ padding: "10px 0"
196
+ },
197
+ label: {
198
+ flex: 1,
199
+ minWidth: 0,
200
+ fontSize: "13px",
201
+ fontWeight: 500,
202
+ lineHeight: 1.5
203
+ },
204
+ switch: {
205
+ width: "16px",
206
+ height: "16px",
207
+ accentColor: "var(--dsw-alias-brand-primary)",
208
+ cursor: "pointer"
209
+ },
210
+ status: {
211
+ color: "var(--dsw-alias-label-secondary)",
212
+ fontSize: "12px",
213
+ lineHeight: 1.5,
214
+ minWidth: "24px"
215
+ },
216
+ hint: {
217
+ margin: 0,
218
+ color: "var(--dsw-alias-label-tertiary)",
219
+ fontSize: "12px",
220
+ lineHeight: 1.5
221
+ },
222
+ reset: {
223
+ alignSelf: "flex-start",
224
+ font: "inherit",
225
+ color: "var(--dsw-alias-label-secondary)",
226
+ background: "none",
227
+ border: "1px solid var(--dsw-alias-border-l2)",
228
+ borderRadius: "8px",
229
+ padding: "4px 10px",
230
+ fontSize: "12px",
231
+ lineHeight: 1.5,
232
+ cursor: "pointer"
233
+ },
234
+ routes: {
235
+ margin: "4px 0 0",
236
+ padding: "10px 0 0",
237
+ borderTop: "1px solid var(--dsw-alias-border-l2)",
238
+ display: "flex",
239
+ flexDirection: "column",
240
+ gap: "6px"
241
+ },
242
+ routeRow: {
243
+ display: "flex",
244
+ alignItems: "center",
245
+ gap: "8px"
246
+ },
247
+ routeLabel: {
248
+ minWidth: 0,
249
+ flex: 1,
250
+ margin: 0,
251
+ color: "var(--dsw-alias-label-secondary)",
252
+ fontSize: "12px",
253
+ lineHeight: 1.5
254
+ },
255
+ routeValue: {
256
+ margin: 0,
257
+ color: "var(--dsw-alias-label-primary)",
258
+ fontSize: "12px",
259
+ lineHeight: 1.5,
260
+ fontVariantNumeric: "tabular-nums"
261
+ },
262
+ note: {
263
+ margin: 0,
264
+ color: "var(--dsw-alias-label-tertiary)",
265
+ fontSize: "12px",
266
+ lineHeight: 1.5
267
+ }
268
+ };
269
+ function apply(ctx) {
270
+ const t = ctx.locale.bind(NS);
271
+ ctx.effect(
272
+ () => {
273
+ ctx.locale.register(NS, { zh, en });
274
+ },
275
+ "model-router: card dictionaries"
276
+ );
277
+ const controller = new ModelRouterCardController(ctx.settingsScope.bind({ namespace: NS }));
278
+ ctx.slots.inject("settings.plugin.item", function* () {
279
+ yield ctx.slots.register(
280
+ {
281
+ name: "settings.plugin.item",
282
+ key: NS,
283
+ locale: NS,
284
+ inject: () => controller.inject()
285
+ },
286
+ ModelRouterCard
287
+ );
288
+ });
289
+ ctx.effect(
290
+ () => () => controller.dispose(),
291
+ "model-router: card controller"
292
+ );
293
+ }
294
+
295
+ return module.exports;
296
+ }
297
+ });
package/lib/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import * as _deepseek_ai_dsh_settings from '@deepseek-ai/dsh-settings';
1
2
  import { Service, Context } from '@deepseek-ai/cordis';
2
3
  import z from '@deepseek-ai/schemastery';
3
4
 
@@ -45,6 +46,13 @@ interface RouterConfig {
45
46
  planner: ModelRoute;
46
47
  executor: ModelRoute;
47
48
  mode: RoutingMode;
49
+ /**
50
+ * Live off-switch. Defaults to true; settable from Settings → Plugins →
51
+ * model-router (applies immediately) or from the patch row (next boot).
52
+ * When false, the router stops rewriting requests and unregisters the
53
+ * prompt section and the skill.
54
+ */
55
+ enabled: boolean;
48
56
  promptSection: boolean;
49
57
  skill: boolean;
50
58
  }
@@ -97,27 +105,6 @@ declare function recentStepsHadError(events: readonly unknown[] | undefined, rec
97
105
  */
98
106
  declare function effortFor(route: ModelRoute, events: readonly unknown[] | undefined): ReasoningEffort | undefined;
99
107
 
100
- /**
101
- * dsh-model-router: role-based model routing for the DeepSeek Harness.
102
- *
103
- * The planner (the session's root agent) runs on `deepseek-v4-pro`; delegated
104
- * executor subagents run on `deepseek-v4-flash`. Enforcement is a per-agent
105
- * `agent/request` rewrite registered when the agent is created, so it applies
106
- * in every mode (web / headless / tui) and every agent preset, including
107
- * subagents the delegation tools create.
108
- *
109
- * Each role route may also pin `reasoningEffort` and `maxTokens`; when set,
110
- * they override the session's selection for that role. A `mode` switch lets a
111
- * deployment reserve the planner route for actual planning.
112
- *
113
- * The plugin also publishes:
114
- * - a system-prompt section stating the planner/executor convention, and
115
- * - the `pro-flash-routing` skill teaching the agent to plan itself and
116
- * delegate code execution to flash subagents.
117
- *
118
- * @module dsh-model-router
119
- */
120
-
121
108
  /** Plugin row id; the bundle patch inserts it under this id. */
122
109
  declare const name = "model-router";
123
110
  /** The plugin's public config, validated at row load. */
@@ -157,6 +144,7 @@ declare const Config: z<Schemastery.ObjectS<{
157
144
  recoverySteps: z<number, number>;
158
145
  }>>;
159
146
  mode: z<"strict" | "plan", "strict" | "plan">;
147
+ enabled: z<boolean, boolean>;
160
148
  promptSection: z<boolean, boolean>;
161
149
  skill: z<boolean, boolean>;
162
150
  }>, Schemastery.ObjectT<{
@@ -195,22 +183,82 @@ declare const Config: z<Schemastery.ObjectS<{
195
183
  recoverySteps: z<number, number>;
196
184
  }>>;
197
185
  mode: z<"strict" | "plan", "strict" | "plan">;
186
+ enabled: z<boolean, boolean>;
198
187
  promptSection: z<boolean, boolean>;
199
188
  skill: z<boolean, boolean>;
200
189
  }>>;
190
+ /** Settings namespace the live on/off toggle lives under (settings.yaml). */
191
+ declare const SETTINGS_NS: _deepseek_ai_dsh_settings.SettingsNamespace;
201
192
  declare const SKILL_NAME = "pro-flash-routing";
202
193
  declare const SKILL_DESCRIPTION = "Route planning and code execution across models: plan on the pro planner agent, delegate implementation to flash executor subagents.";
203
194
  declare const SKILL_WHEN_TO_USE = "Use when a task combines planning and implementation: before writing code, after a plan is approved, when delegating execution work, or when the user asks about the pro/flash routing convention.";
204
195
  declare const SKILL_CONTENT = "# Pro planner / Flash executor routing\n\nThis session routes models by role:\n\n- **Planner (this agent)** \u2014 `deepseek-v4-pro`. Planning, design decisions, reviewing delegated output, and user-facing synthesis happen here.\n- **Executors (every subagent)** \u2014 `deepseek-v4-flash`. Implementation work happens there: writing code, running commands, builds, and tests. The harness forces the model automatically; you do not select it.\n\n## Working rhythm\n\n1. **Plan here.** Explore, decide the approach, and (when plan mode is on) submit the plan with `exit_plan_mode`. The plan stays on this agent.\n2. **Delegate the execution.** Once a plan is approved, hand each self-contained chunk of implementation to a subagent with a complete prompt: exact files to touch, the change to make, and how to verify. Subagents are automatically routed to `deepseek-v4-flash`, so keep them execution-focused: give them the decision, not the decision to make.\n3. **Review here.** Read the subagent's result on this agent, verify it yourself (tests, diffs, logs), and iterate with follow-up messages to the same subagent when available.\n4. **Report here.** Summaries, plans, and answers to the user come from this agent.\n\n## Keep this agent's context lean\n\nInput tokens are the expensive part of the planner. Don't re-read large files or full transcripts on this agent \u2014 trust the subagent's final report. Prefer targeted reads (offset/limit) over whole files. When the context grows, compact rather than re-sending everything.\n\n## Delegation guidelines\n\n- Start independent delegations together in one assistant message and continue useful work while they run (background mode by default).\n- Prefer `subagent` for self-contained work and `workflow` when many independent pieces need fan-out; their workers run on flash as well.\n- Do not delegate design: subagents execute decisions already made.\n- If a subagent's task grows into design work, pull it back to this agent and re-delegate the narrowed execution.\n\n## Verification\n\n- Executor output was produced by `deepseek-v4-flash`; planner output by `deepseek-v4-pro`. If you need to confirm, check the session log's model metadata.\n- If routing ever looks wrong, the `model-router` plugin row in the profile composition is the single place that owns it.";
205
196
  /** The plugin row id the bundle patch must insert. */
206
197
  declare const ROW_ID = "model-router";
198
+ /** Minimal structural view of the live agent object the router reads. */
199
+ interface AgentLike {
200
+ ctx: AgentScopedContext;
201
+ options?: {
202
+ subagentDepth?: number;
203
+ };
204
+ session?: {
205
+ header?: {
206
+ origin?: string;
207
+ };
208
+ events?: unknown[];
209
+ };
210
+ }
211
+ /** The agent-scoped context's waterfall surface the router uses. */
212
+ interface AgentScopedContext {
213
+ on(event: "agent/request", listener: (payload: Record<string, unknown>, next: () => Promise<Record<string, unknown>>) => Promise<Record<string, unknown>>, options?: {
214
+ prepend?: boolean;
215
+ }): () => void;
216
+ }
217
+ /** Host-plane surface the router consumes (events, prompt registry, skills). */
218
+ interface HarnessContext {
219
+ on(event: "agent/created", listener: (payload: {
220
+ agent: AgentLike;
221
+ }) => void): () => void;
222
+ on(event: "agent/disposed", listener: (agent: unknown) => void): () => void;
223
+ systemPrompt: {
224
+ section(section: {
225
+ name: string;
226
+ order: number;
227
+ text: string;
228
+ }): () => void;
229
+ };
230
+ skills: {
231
+ register(skill: {
232
+ name: string;
233
+ description: string;
234
+ whenToUse?: string;
235
+ content: string;
236
+ source: string;
237
+ }): () => void;
238
+ };
239
+ }
207
240
  /**
208
241
  * Cordis service: per-agent request routing plus the convention surface.
209
242
  */
210
243
  declare class ModelRouter extends Service {
211
244
  static inject: string[];
212
245
  config: RouterConfig;
246
+ /** Currently authoritative config; swapped by the settings section when one is mounted. */
247
+ source: () => RouterConfig;
248
+ /** Host-plane surface the router consumes (events, prompt registry, skills). */
249
+ harness: HarnessContext;
250
+ /** Disposer of the currently registered prompt section, if any. */
251
+ promptDispose?: () => void;
252
+ /** Disposer of the currently registered skill, if any. */
253
+ skillDispose?: () => void;
213
254
  constructor(ctx: Context, rawConfig?: unknown);
255
+ /**
256
+ * Register the convention surface (prompt section + skill) for `cfg`,
257
+ * replacing whatever is currently registered. Called on construction and
258
+ * after every committed settings change; while `enabled` is false, nothing
259
+ * stays registered.
260
+ */
261
+ private render;
214
262
  }
215
263
 
216
- export { type AgentRole, Config, type ModelRoute, ModelRouter, ROW_ID, type ReasoningEffort, type RouterConfig, type RoutingMode, SKILL_CONTENT, SKILL_DESCRIPTION, SKILL_NAME, SKILL_WHEN_TO_USE, ModelRouter as default, effortFor, name, recentStepsHadError, roleFor, routeFor };
264
+ export { type AgentRole, Config, type ModelRoute, ModelRouter, ROW_ID, type ReasoningEffort, type RouterConfig, type RoutingMode, SETTINGS_NS, SKILL_CONTENT, SKILL_DESCRIPTION, SKILL_NAME, SKILL_WHEN_TO_USE, ModelRouter as default, effortFor, name, recentStepsHadError, roleFor, routeFor };
package/lib/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { Service } from "@deepseek-ai/cordis";
3
3
  import z from "@deepseek-ai/schemastery";
4
4
  import { foldPlanMode } from "@deepseek-ai/dsh-plan-mode";
5
+ import { installSettingsSection, settingsNamespace } from "@deepseek-ai/dsh-settings";
5
6
 
6
7
  // src/policy.ts
7
8
  var DEFAULT_RECOVERY_STEPS = 2;
@@ -65,15 +66,18 @@ var Config = z.object({
65
66
  model: "deepseek-v4-flash"
66
67
  }),
67
68
  mode: z.union(["strict", "plan"]).default("strict"),
69
+ enabled: z.boolean().default(true),
68
70
  promptSection: z.boolean().default(true),
69
71
  skill: z.boolean().default(true)
70
72
  });
73
+ var SETTINGS_NS = settingsNamespace("model-router");
71
74
  function resolveConfig(raw) {
72
75
  const parsed = Config(raw ?? {});
73
76
  return {
74
77
  planner: parsed.planner,
75
78
  executor: parsed.executor,
76
79
  mode: parsed.mode,
80
+ enabled: parsed.enabled,
77
81
  promptSection: parsed.promptSection,
78
82
  skill: parsed.skill
79
83
  };
@@ -125,16 +129,27 @@ function isPlanModeActive(agent) {
125
129
  var ModelRouter = class extends Service {
126
130
  static inject = ["skills", "systemPrompt"];
127
131
  config;
132
+ /** Currently authoritative config; swapped by the settings section when one is mounted. */
133
+ source;
134
+ /** Host-plane surface the router consumes (events, prompt registry, skills). */
135
+ harness;
136
+ /** Disposer of the currently registered prompt section, if any. */
137
+ promptDispose;
138
+ /** Disposer of the currently registered skill, if any. */
139
+ skillDispose;
128
140
  constructor(ctx, rawConfig = {}) {
129
141
  super(ctx, "modelRouter");
130
142
  this.config = resolveConfig(rawConfig);
131
- const harness = ctx;
132
- harness.on("agent/created", ({ agent }) => {
143
+ this.source = () => this.config;
144
+ this.harness = ctx;
145
+ this.harness.on("agent/created", ({ agent }) => {
133
146
  const dispose = agent.ctx.on(
134
147
  "agent/request",
135
148
  async (payload, next) => {
136
149
  const resolved = await next();
137
- const route = routeFor(agent, this.config, isPlanModeActive(agent));
150
+ const cfg = this.source();
151
+ if (!cfg.enabled) return resolved;
152
+ const route = routeFor(agent, cfg, isPlanModeActive(agent));
138
153
  if (route === void 0) return resolved;
139
154
  const stamped = {
140
155
  ...resolved,
@@ -148,22 +163,52 @@ var ModelRouter = class extends Service {
148
163
  },
149
164
  { prepend: true }
150
165
  );
151
- harness.on("agent/disposed", (disposed) => {
166
+ this.harness.on("agent/disposed", (disposed) => {
152
167
  if (disposed === agent) dispose();
153
168
  });
154
169
  });
155
- if (this.config.promptSection) {
156
- harness.systemPrompt.section({
170
+ this.render(this.config);
171
+ installSettingsSection(
172
+ ctx,
173
+ SETTINGS_NS,
174
+ Config,
175
+ this.config,
176
+ {
177
+ setSource: (current) => {
178
+ this.source = current;
179
+ },
180
+ onChange: () => this.render(this.source())
181
+ }
182
+ );
183
+ }
184
+ /**
185
+ * Register the convention surface (prompt section + skill) for `cfg`,
186
+ * replacing whatever is currently registered. Called on construction and
187
+ * after every committed settings change; while `enabled` is false, nothing
188
+ * stays registered.
189
+ */
190
+ render(cfg) {
191
+ if (this.promptDispose) {
192
+ this.promptDispose();
193
+ this.promptDispose = void 0;
194
+ }
195
+ if (this.skillDispose) {
196
+ this.skillDispose();
197
+ this.skillDispose = void 0;
198
+ }
199
+ if (!cfg.enabled) return;
200
+ if (cfg.promptSection) {
201
+ this.promptDispose = this.harness.systemPrompt.section({
157
202
  name: ROW_ID,
158
203
  order: SECTION_ORDER,
159
- text: SECTION_TEXT.replaceAll("{PLANNER_MODEL}", this.config.planner.model).replaceAll(
204
+ text: SECTION_TEXT.replaceAll("{PLANNER_MODEL}", cfg.planner.model).replaceAll(
160
205
  "{EXECUTOR_MODEL}",
161
- this.config.executor.model
206
+ cfg.executor.model
162
207
  )
163
208
  });
164
209
  }
165
- if (this.config.skill) {
166
- harness.skills.register({
210
+ if (cfg.skill) {
211
+ this.skillDispose = this.harness.skills.register({
167
212
  name: SKILL_NAME,
168
213
  description: SKILL_DESCRIPTION,
169
214
  whenToUse: SKILL_WHEN_TO_USE,
@@ -177,6 +222,7 @@ export {
177
222
  Config,
178
223
  ModelRouter,
179
224
  ROW_ID,
225
+ SETTINGS_NS,
180
226
  SKILL_CONTENT,
181
227
  SKILL_DESCRIPTION,
182
228
  SKILL_NAME,
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/policy.ts"],"sourcesContent":["/**\n * dsh-model-router: role-based model routing for the DeepSeek Harness.\n *\n * The planner (the session's root agent) runs on `deepseek-v4-pro`; delegated\n * executor subagents run on `deepseek-v4-flash`. Enforcement is a per-agent\n * `agent/request` rewrite registered when the agent is created, so it applies\n * in every mode (web / headless / tui) and every agent preset, including\n * subagents the delegation tools create.\n *\n * Each role route may also pin `reasoningEffort` and `maxTokens`; when set,\n * they override the session's selection for that role. A `mode` switch lets a\n * deployment reserve the planner route for actual planning.\n *\n * The plugin also publishes:\n * - a system-prompt section stating the planner/executor convention, and\n * - the `pro-flash-routing` skill teaching the agent to plan itself and\n * delegate code execution to flash subagents.\n *\n * @module dsh-model-router\n */\nimport { Context, Service } from \"@deepseek-ai/cordis\";\nimport z from \"@deepseek-ai/schemastery\";\nimport { foldPlanMode } from \"@deepseek-ai/dsh-plan-mode\";\nimport { effortFor, recentStepsHadError, roleFor, routeFor, type RouterConfig } from \"./policy.js\";\n\n/** Plugin row id; the bundle patch inserts it under this id. */\nconst name = \"model-router\";\n\n/** One provider/model pair, with defaults and optional effort/token caps. */\nconst ModelRouteSchema = z.object({\n provider: z.string().min(1),\n model: z.string().min(1),\n reasoningEffort: z.union([\"off\", \"low\", \"high\", \"max\"]),\n maxTokens: z.number().min(1),\n escalateOnError: z.boolean(),\n escalateTo: z.union([\"off\", \"low\", \"high\", \"max\"]),\n recoverySteps: z.number().min(1),\n});\n\n/** The plugin's public config, validated at row load. */\nconst Config = z.object({\n planner: ModelRouteSchema.default({\n provider: \"deepseek-official\",\n model: \"deepseek-v4-pro\",\n } as never),\n executor: ModelRouteSchema.default({\n provider: \"deepseek-official\",\n model: \"deepseek-v4-flash\",\n } as never),\n mode: z.union([\"strict\", \"plan\"]).default(\"strict\"),\n promptSection: z.boolean().default(true),\n skill: z.boolean().default(true),\n});\n\n/**\n * Resolve raw row config into the internal shape, failing loud on garbage.\n * Schemastery schemas are callable: invoking validates and applies defaults.\n * @param raw - the row's config object.\n * @returns the validated RouterConfig.\n */\nfunction resolveConfig(raw: unknown): RouterConfig {\n const parsed = Config(raw ?? {});\n return {\n planner: parsed.planner,\n executor: parsed.executor,\n mode: parsed.mode,\n promptSection: parsed.promptSection,\n skill: parsed.skill,\n };\n}\n\n/**\n * Always-on guidance section. Negative order renders before the persona, so\n * the convention is established before the agent's identity line.\n */\nconst SECTION_ORDER = -50;\n\nconst SECTION_TEXT = `Model routing is role-based. Planning runs on {PLANNER_MODEL}; implementation runs on {EXECUTOR_MODEL}. You are the root agent: plan, design, review subagent output, and write the final answer here. Delegate implementation — writing code, running commands, builds, tests — to subagents with complete, self-contained prompts, preferring background delegation for independent work. Keep plans and replies concise. Do not hand-write large amounts of code or run long executions here; delegate instead.`;\n\nconst SKILL_NAME = \"pro-flash-routing\";\n\nconst SKILL_DESCRIPTION =\n \"Route planning and code execution across models: plan on the pro planner agent, delegate implementation to flash executor subagents.\";\n\nconst SKILL_WHEN_TO_USE = `Use when a task combines planning and implementation: before writing code, after a plan is approved, when delegating execution work, or when the user asks about the pro/flash routing convention.`;\n\nconst SKILL_CONTENT = `# Pro planner / Flash executor routing\n\nThis session routes models by role:\n\n- **Planner (this agent)** — \\`deepseek-v4-pro\\`. Planning, design decisions, reviewing delegated output, and user-facing synthesis happen here.\n- **Executors (every subagent)** — \\`deepseek-v4-flash\\`. Implementation work happens there: writing code, running commands, builds, and tests. The harness forces the model automatically; you do not select it.\n\n## Working rhythm\n\n1. **Plan here.** Explore, decide the approach, and (when plan mode is on) submit the plan with \\`exit_plan_mode\\`. The plan stays on this agent.\n2. **Delegate the execution.** Once a plan is approved, hand each self-contained chunk of implementation to a subagent with a complete prompt: exact files to touch, the change to make, and how to verify. Subagents are automatically routed to \\`deepseek-v4-flash\\`, so keep them execution-focused: give them the decision, not the decision to make.\n3. **Review here.** Read the subagent's result on this agent, verify it yourself (tests, diffs, logs), and iterate with follow-up messages to the same subagent when available.\n4. **Report here.** Summaries, plans, and answers to the user come from this agent.\n\n## Keep this agent's context lean\n\nInput tokens are the expensive part of the planner. Don't re-read large files or full transcripts on this agent — trust the subagent's final report. Prefer targeted reads (offset/limit) over whole files. When the context grows, compact rather than re-sending everything.\n\n## Delegation guidelines\n\n- Start independent delegations together in one assistant message and continue useful work while they run (background mode by default).\n- Prefer \\`subagent\\` for self-contained work and \\`workflow\\` when many independent pieces need fan-out; their workers run on flash as well.\n- Do not delegate design: subagents execute decisions already made.\n- If a subagent's task grows into design work, pull it back to this agent and re-delegate the narrowed execution.\n\n## Verification\n\n- Executor output was produced by \\`deepseek-v4-flash\\`; planner output by \\`deepseek-v4-pro\\`. If you need to confirm, check the session log's model metadata.\n- If routing ever looks wrong, the \\`model-router\\` plugin row in the profile composition is the single place that owns it.`;\n\n/** The plugin row id the bundle patch must insert. */\nconst ROW_ID = \"model-router\";\n\n/** Minimal structural view of the live agent object the router reads. */\ninterface AgentLike {\n ctx: AgentScopedContext;\n options?: { subagentDepth?: number };\n session?: { header?: { origin?: string }; events?: unknown[] };\n}\n\n/** The agent-scoped context's waterfall surface the router uses. */\ninterface AgentScopedContext {\n on(\n event: \"agent/request\",\n listener: (\n payload: Record<string, unknown>,\n next: () => Promise<Record<string, unknown>>,\n ) => Promise<Record<string, unknown>>,\n options?: { prepend?: boolean },\n ): () => void;\n}\n\n/** Host-plane surface the router consumes (events, prompt registry, skills). */\ninterface HarnessContext {\n on(\n event: \"agent/created\",\n listener: (payload: { agent: AgentLike }) => void,\n ): () => void;\n on(event: \"agent/disposed\", listener: (agent: unknown) => void): () => void;\n systemPrompt: {\n section(section: { name: string; order: number; text: string }): unknown;\n };\n skills: {\n register(skill: {\n name: string;\n description: string;\n whenToUse?: string;\n content: string;\n source: string;\n }): unknown;\n };\n}\n\n/** Fold plan-mode state for an agent without trusting the agent's exact shape. */\nfunction isPlanModeActive(agent: AgentLike): boolean {\n const events = agent.session?.events;\n if (!Array.isArray(events)) return false;\n try {\n return foldPlanMode(events as Parameters<typeof foldPlanMode>[0]);\n } catch {\n return false;\n }\n}\n\n/**\n * Cordis service: per-agent request routing plus the convention surface.\n */\nclass ModelRouter extends Service {\n static inject = [\"skills\", \"systemPrompt\"];\n\n config: RouterConfig;\n\n constructor(ctx: Context, rawConfig: unknown = {}) {\n super(ctx, \"modelRouter\");\n this.config = resolveConfig(rawConfig);\n const harness = ctx as unknown as HarnessContext;\n\n // Every agent that gets created — root sessions, delegation children,\n // workflow workers, ralph rounds — passes through here.\n harness.on(\"agent/created\", ({ agent }) => {\n // `prepend` puts this listener OUTERMOST in the `agent/request`\n // waterfall: the harness's model-selection listener runs inside it, so\n // this rewrite is applied LAST and wins over the session's selected\n // model (which dsh-base defaults to deepseek-v4-flash and the user\n // settings or UI can change).\n const dispose = agent.ctx.on(\n \"agent/request\",\n async (payload, next) => {\n const resolved = await next();\n const route = routeFor(agent, this.config, isPlanModeActive(agent));\n if (route === undefined) return resolved;\n const stamped: Record<string, unknown> = {\n ...resolved,\n provider: route.provider,\n model: route.model,\n };\n if (route.maxTokens !== undefined) stamped.maxTokens = route.maxTokens;\n const effort = effortFor(route, agent.session?.events);\n if (effort !== undefined) stamped.reasoningEffort = effort;\n return stamped;\n },\n { prepend: true },\n );\n harness.on(\"agent/disposed\", (disposed) => {\n if (disposed === agent) dispose();\n });\n });\n\n if (this.config.promptSection) {\n harness.systemPrompt.section({\n name: ROW_ID,\n order: SECTION_ORDER,\n text: SECTION_TEXT.replaceAll(\"{PLANNER_MODEL}\", this.config.planner.model).replaceAll(\n \"{EXECUTOR_MODEL}\",\n this.config.executor.model,\n ),\n });\n }\n\n if (this.config.skill) {\n harness.skills.register({\n name: SKILL_NAME,\n description: SKILL_DESCRIPTION,\n whenToUse: SKILL_WHEN_TO_USE,\n content: SKILL_CONTENT,\n source: \"runtime\",\n });\n }\n }\n}\n\nexport {\n Config,\n ModelRouter,\n ModelRouter as default,\n name,\n ROW_ID,\n SKILL_CONTENT,\n SKILL_DESCRIPTION,\n SKILL_NAME,\n SKILL_WHEN_TO_USE,\n effortFor,\n recentStepsHadError,\n roleFor,\n routeFor,\n};\nexport type {\n AgentRole,\n ModelRoute,\n ReasoningEffort,\n RoutingMode,\n RouterConfig,\n} from \"./policy.js\";\n","/**\n * Pure routing policy for dsh-model-router: which model each agent role gets.\n * Kept free of Cordis imports so the policy is trivially unit-testable.\n * @module dsh-model-router/policy\n */\n\n/** Reasoning-effort levels a route may pin (mirrors the harness vocabulary). */\nexport type ReasoningEffort = \"off\" | \"low\" | \"high\" | \"max\";\n\n/**\n * How the router treats the root agent.\n * - `strict`: the root agent is always the planner (pro).\n * - `plan`: the root agent is pro only while plan mode is active; otherwise it\n * falls back to the executor route, reserving pro for real planning.\n */\nexport type RoutingMode = \"strict\" | \"plan\";\n\n/** One route: a provider/model pair stamped onto an agent request. */\nexport interface ModelRoute {\n provider: string;\n model: string;\n /**\n * Optional reasoning-effort override. When omitted, the request inherits the\n * session's own selection; when set, the router pins it for that role.\n */\n reasoningEffort?: ReasoningEffort;\n /** Optional output-token cap for the role; omitted means inherit. */\n maxTokens?: number;\n /**\n * Error-driven escalation (v1): when true, a failed execution step bumps the\n * next request's effort to `escalateTo`, wearing off after `recoverySteps`\n * clean steps. Deterministic, stateless — the session log is folded per\n * request, so only *prior* steps are ever considered.\n */\n escalateOnError?: boolean;\n /** Effort used for the request after a failed step. */\n escalateTo?: ReasoningEffort;\n /** Clean steps before escalation wears off. Defaults to 2. */\n recoverySteps?: number;\n}\n\n/** The two roles the router distinguishes. */\nexport type AgentRole = \"planner\" | \"executor\";\n\n/** Resolved router configuration: one route per role plus routing mode. */\nexport interface RouterConfig {\n planner: ModelRoute;\n executor: ModelRoute;\n mode: RoutingMode;\n promptSection: boolean;\n skill: boolean;\n}\n\n/** Default recovery window: an error escalates for the next two completed steps. */\nexport const DEFAULT_RECOVERY_STEPS = 2;\n\n/**\n * Classify an agent as planner or executor.\n *\n * The main (root) agent of a session is the planner. Every agent created as a\n * delegation child — `subagent`, `subagent_fork`, workflow workers, ralph\n * rounds — is an executor. The harness stamps two durable facts on children:\n * `options.subagentDepth` (>= 1) and the session header `origin: \"subagent\"`.\n *\n * @param agent - the live agent (any subset of the runtime shape).\n * @returns the role the agent should be routed as.\n */\nexport function roleFor(agent: unknown): AgentRole {\n const options = (agent as { options?: unknown })?.options;\n const depth = (options as { subagentDepth?: unknown })?.subagentDepth;\n if (typeof depth === \"number\" && depth >= 1) return \"executor\";\n const session = (agent as { session?: unknown })?.session;\n const origin = (session as { header?: unknown })?.header\n ? ((session as { header: { origin?: unknown } }).header.origin)\n : undefined;\n if (origin === \"subagent\") return \"executor\";\n return \"planner\";\n}\n\n/**\n * Resolve the route for one agent.\n * @param agent - the live agent.\n * @param config - the resolved router configuration.\n * @param planModeActive - whether plan mode is currently folded active for the\n * agent's session; consulted only in `plan` routing mode.\n * @returns the model route to stamp, or `undefined` to leave the request alone.\n */\nexport function routeFor(\n agent: unknown,\n config: RouterConfig,\n planModeActive = false,\n): ModelRoute | undefined {\n const role = roleFor(agent);\n if (role === \"executor\") return config.executor;\n // Root agent. In `plan` mode, reserve the planner route for actual planning;\n // otherwise the root falls back to the executor route.\n if (config.mode === \"plan\" && !planModeActive) return config.executor;\n return config.planner;\n}\n\n/**\n * Whether any of the last `recoverySteps` completed steps carried a failed\n * tool result. A failure is a `tool/result` event whose data carries an\n * `error` field (the harness records tool failures there).\n *\n * Steps are deduplicated by `turn:step`, and only *completed* steps count —\n * events are scanned from the tail, so the current in-flight request is never\n * considered.\n *\n * @param events - the agent's session event log (or `undefined`).\n * @param recoverySteps - how many completed steps back to scan.\n * @returns true when a failed step is within the window.\n */\nexport function recentStepsHadError(\n events: readonly unknown[] | undefined,\n recoverySteps: number = DEFAULT_RECOVERY_STEPS,\n): boolean {\n if (!Array.isArray(events) || recoverySteps <= 0) return false;\n const seen = new Set<string>();\n let steps = 0;\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i] as\n | { type?: string; data?: { turn?: number; step?: number; error?: unknown } }\n | undefined;\n if (event?.type !== \"tool/result\" || event.data === undefined) continue;\n const key = `${event.data.turn}:${event.data.step}`;\n if (!seen.has(key)) {\n // A new step beyond the recovery window ends the scan; events for steps\n // already inside the window are still checked below.\n if (steps >= recoverySteps) break;\n seen.add(key);\n steps += 1;\n }\n if (event.data.error !== undefined && event.data.error !== null) return true;\n }\n return false;\n}\n\n/**\n * Resolve the reasoning effort to stamp for one request.\n *\n * Baseline is the route's `reasoningEffort`; when `escalateOnError` is enabled\n * and a recent step failed, the effort bumps to `escalateTo` (falling back to\n * the baseline when `escalateTo` is unset). Returns `undefined` to leave the\n * request's effort alone (inherit the session selection).\n *\n * @param route - the resolved route for the agent.\n * @param events - the agent's session event log.\n * @returns the effort to stamp, or `undefined` to inherit.\n */\nexport function effortFor(\n route: ModelRoute,\n events: readonly unknown[] | undefined,\n): ReasoningEffort | undefined {\n if (route.escalateOnError === true && recentStepsHadError(events, route.recoverySteps)) {\n return route.escalateTo ?? route.reasoningEffort;\n }\n return route.reasoningEffort;\n}\n"],"mappings":";AAoBA,SAAkB,eAAe;AACjC,OAAO,OAAO;AACd,SAAS,oBAAoB;;;ACgCtB,I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AAa,WAAW,mBAAmB,KAAK,OAAO,QAAQ,KAAK,EAAE;AAAA,UAC1E;AAAA,UACA,KAAK,OAAO,SAAS;AAAA,QACvB;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,KAAK,OAAO,OAAO;AACrB,cAAQ,OAAO,SAAS;AAAA,QACtB,MAAM;AAAA,QACN,aAAa;AAAA,QACb,WAAW;AAAA,QACX,SAAS;AAAA,QACT,QAAQ;AAAA,MACV,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/policy.ts"],"sourcesContent":["/**\n * dsh-model-router: role-based model routing for the DeepSeek Harness.\n *\n * The planner (the session's root agent) runs on `deepseek-v4-pro`; delegated\n * executor subagents run on `deepseek-v4-flash`. Enforcement is a per-agent\n * `agent/request` rewrite registered when the agent is created, so it applies\n * in every mode (web / headless / tui) and every agent preset, including\n * subagents the delegation tools create.\n *\n * Each role route may also pin `reasoningEffort` and `maxTokens`; when set,\n * they override the session's selection for that role. A `mode` switch lets a\n * deployment reserve the planner route for actual planning.\n *\n * The plugin also publishes:\n * - a system-prompt section stating the planner/executor convention, and\n * - the `pro-flash-routing` skill teaching the agent to plan itself and\n * delegate code execution to flash subagents.\n *\n * @module dsh-model-router\n */\nimport { Context, Service } from \"@deepseek-ai/cordis\";\nimport z from \"@deepseek-ai/schemastery\";\nimport { foldPlanMode } from \"@deepseek-ai/dsh-plan-mode\";\nimport { installSettingsSection, settingsNamespace } from \"@deepseek-ai/dsh-settings\";\nimport { effortFor, recentStepsHadError, roleFor, routeFor, type RouterConfig } from \"./policy.js\";\n\n/** Plugin row id; the bundle patch inserts it under this id. */\nconst name = \"model-router\";\n\n/** One provider/model pair, with defaults and optional effort/token caps. */\nconst ModelRouteSchema = z.object({\n provider: z.string().min(1),\n model: z.string().min(1),\n reasoningEffort: z.union([\"off\", \"low\", \"high\", \"max\"]),\n maxTokens: z.number().min(1),\n escalateOnError: z.boolean(),\n escalateTo: z.union([\"off\", \"low\", \"high\", \"max\"]),\n recoverySteps: z.number().min(1),\n});\n\n/** The plugin's public config, validated at row load. */\nconst Config = z.object({\n planner: ModelRouteSchema.default({\n provider: \"deepseek-official\",\n model: \"deepseek-v4-pro\",\n } as never),\n executor: ModelRouteSchema.default({\n provider: \"deepseek-official\",\n model: \"deepseek-v4-flash\",\n } as never),\n mode: z.union([\"strict\", \"plan\"]).default(\"strict\"),\n enabled: z.boolean().default(true),\n promptSection: z.boolean().default(true),\n skill: z.boolean().default(true),\n});\n\n/** Settings namespace the live on/off toggle lives under (settings.yaml). */\nconst SETTINGS_NS = settingsNamespace(\"model-router\");\n\n/**\n * Resolve raw row config into the internal shape, failing loud on garbage.\n * Schemastery schemas are callable: invoking validates and applies defaults.\n * @param raw - the row's config object.\n * @returns the validated RouterConfig.\n */\nfunction resolveConfig(raw: unknown): RouterConfig {\n const parsed = Config(raw ?? {});\n return {\n planner: parsed.planner,\n executor: parsed.executor,\n mode: parsed.mode,\n enabled: parsed.enabled,\n promptSection: parsed.promptSection,\n skill: parsed.skill,\n };\n}\n\n/**\n * Always-on guidance section. Negative order renders before the persona, so\n * the convention is established before the agent's identity line.\n */\nconst SECTION_ORDER = -50;\n\nconst SECTION_TEXT = `Model routing is role-based. Planning runs on {PLANNER_MODEL}; implementation runs on {EXECUTOR_MODEL}. You are the root agent: plan, design, review subagent output, and write the final answer here. Delegate implementation — writing code, running commands, builds, tests — to subagents with complete, self-contained prompts, preferring background delegation for independent work. Keep plans and replies concise. Do not hand-write large amounts of code or run long executions here; delegate instead.`;\n\nconst SKILL_NAME = \"pro-flash-routing\";\n\nconst SKILL_DESCRIPTION =\n \"Route planning and code execution across models: plan on the pro planner agent, delegate implementation to flash executor subagents.\";\n\nconst SKILL_WHEN_TO_USE = `Use when a task combines planning and implementation: before writing code, after a plan is approved, when delegating execution work, or when the user asks about the pro/flash routing convention.`;\n\nconst SKILL_CONTENT = `# Pro planner / Flash executor routing\n\nThis session routes models by role:\n\n- **Planner (this agent)** — \\`deepseek-v4-pro\\`. Planning, design decisions, reviewing delegated output, and user-facing synthesis happen here.\n- **Executors (every subagent)** — \\`deepseek-v4-flash\\`. Implementation work happens there: writing code, running commands, builds, and tests. The harness forces the model automatically; you do not select it.\n\n## Working rhythm\n\n1. **Plan here.** Explore, decide the approach, and (when plan mode is on) submit the plan with \\`exit_plan_mode\\`. The plan stays on this agent.\n2. **Delegate the execution.** Once a plan is approved, hand each self-contained chunk of implementation to a subagent with a complete prompt: exact files to touch, the change to make, and how to verify. Subagents are automatically routed to \\`deepseek-v4-flash\\`, so keep them execution-focused: give them the decision, not the decision to make.\n3. **Review here.** Read the subagent's result on this agent, verify it yourself (tests, diffs, logs), and iterate with follow-up messages to the same subagent when available.\n4. **Report here.** Summaries, plans, and answers to the user come from this agent.\n\n## Keep this agent's context lean\n\nInput tokens are the expensive part of the planner. Don't re-read large files or full transcripts on this agent — trust the subagent's final report. Prefer targeted reads (offset/limit) over whole files. When the context grows, compact rather than re-sending everything.\n\n## Delegation guidelines\n\n- Start independent delegations together in one assistant message and continue useful work while they run (background mode by default).\n- Prefer \\`subagent\\` for self-contained work and \\`workflow\\` when many independent pieces need fan-out; their workers run on flash as well.\n- Do not delegate design: subagents execute decisions already made.\n- If a subagent's task grows into design work, pull it back to this agent and re-delegate the narrowed execution.\n\n## Verification\n\n- Executor output was produced by \\`deepseek-v4-flash\\`; planner output by \\`deepseek-v4-pro\\`. If you need to confirm, check the session log's model metadata.\n- If routing ever looks wrong, the \\`model-router\\` plugin row in the profile composition is the single place that owns it.`;\n\n/** The plugin row id the bundle patch must insert. */\nconst ROW_ID = \"model-router\";\n\n/** Minimal structural view of the live agent object the router reads. */\ninterface AgentLike {\n ctx: AgentScopedContext;\n options?: { subagentDepth?: number };\n session?: { header?: { origin?: string }; events?: unknown[] };\n}\n\n/** The agent-scoped context's waterfall surface the router uses. */\ninterface AgentScopedContext {\n on(\n event: \"agent/request\",\n listener: (\n payload: Record<string, unknown>,\n next: () => Promise<Record<string, unknown>>,\n ) => Promise<Record<string, unknown>>,\n options?: { prepend?: boolean },\n ): () => void;\n}\n\n/** Host-plane surface the router consumes (events, prompt registry, skills). */\ninterface HarnessContext {\n on(\n event: \"agent/created\",\n listener: (payload: { agent: AgentLike }) => void,\n ): () => void;\n on(event: \"agent/disposed\", listener: (agent: unknown) => void): () => void;\n systemPrompt: {\n section(section: { name: string; order: number; text: string }): () => void;\n };\n skills: {\n register(skill: {\n name: string;\n description: string;\n whenToUse?: string;\n content: string;\n source: string;\n }): () => void;\n };\n}\n\n/** Fold plan-mode state for an agent without trusting the agent's exact shape. */\nfunction isPlanModeActive(agent: AgentLike): boolean {\n const events = agent.session?.events;\n if (!Array.isArray(events)) return false;\n try {\n return foldPlanMode(events as Parameters<typeof foldPlanMode>[0]);\n } catch {\n return false;\n }\n}\n\n/**\n * Cordis service: per-agent request routing plus the convention surface.\n */\nclass ModelRouter extends Service {\n static inject = [\"skills\", \"systemPrompt\"];\n\n config: RouterConfig;\n\n /** Currently authoritative config; swapped by the settings section when one is mounted. */\n source: () => RouterConfig;\n\n /** Host-plane surface the router consumes (events, prompt registry, skills). */\n harness: HarnessContext;\n\n /** Disposer of the currently registered prompt section, if any. */\n promptDispose?: () => void;\n\n /** Disposer of the currently registered skill, if any. */\n skillDispose?: () => void;\n\n constructor(ctx: Context, rawConfig: unknown = {}) {\n super(ctx, \"modelRouter\");\n this.config = resolveConfig(rawConfig);\n this.source = () => this.config;\n this.harness = ctx as unknown as HarnessContext;\n\n // Every agent that gets created — root sessions, delegation children,\n // workflow workers, ralph rounds — passes through here.\n this.harness.on(\"agent/created\", ({ agent }) => {\n // `prepend` puts this listener OUTERMOST in the `agent/request`\n // waterfall: the harness's model-selection listener runs inside it, so\n // this rewrite is applied LAST and wins over the session's selected\n // model (which dsh-base defaults to deepseek-v4-flash and the user\n // settings or UI can change).\n const dispose = agent.ctx.on(\n \"agent/request\",\n async (payload, next) => {\n const resolved = await next();\n const cfg = this.source();\n if (!cfg.enabled) return resolved;\n const route = routeFor(agent, cfg, isPlanModeActive(agent));\n if (route === undefined) return resolved;\n const stamped: Record<string, unknown> = {\n ...resolved,\n provider: route.provider,\n model: route.model,\n };\n if (route.maxTokens !== undefined) stamped.maxTokens = route.maxTokens;\n const effort = effortFor(route, agent.session?.events);\n if (effort !== undefined) stamped.reasoningEffort = effort;\n return stamped;\n },\n { prepend: true },\n );\n this.harness.on(\"agent/disposed\", (disposed) => {\n if (disposed === agent) dispose();\n });\n });\n\n // Register the convention surface from the composition config, then let\n // the settings section (when mounted) take over as the live source.\n this.render(this.config);\n installSettingsSection(\n ctx,\n SETTINGS_NS,\n Config,\n this.config as unknown as ReturnType<typeof Config>,\n {\n setSource: (current) => {\n this.source = current;\n },\n onChange: () => this.render(this.source()),\n },\n );\n }\n\n /**\n * Register the convention surface (prompt section + skill) for `cfg`,\n * replacing whatever is currently registered. Called on construction and\n * after every committed settings change; while `enabled` is false, nothing\n * stays registered.\n */\n private render(cfg: RouterConfig): void {\n if (this.promptDispose) {\n this.promptDispose();\n this.promptDispose = undefined;\n }\n if (this.skillDispose) {\n this.skillDispose();\n this.skillDispose = undefined;\n }\n if (!cfg.enabled) return;\n if (cfg.promptSection) {\n this.promptDispose = this.harness.systemPrompt.section({\n name: ROW_ID,\n order: SECTION_ORDER,\n text: SECTION_TEXT.replaceAll(\"{PLANNER_MODEL}\", cfg.planner.model).replaceAll(\n \"{EXECUTOR_MODEL}\",\n cfg.executor.model,\n ),\n });\n }\n if (cfg.skill) {\n this.skillDispose = this.harness.skills.register({\n name: SKILL_NAME,\n description: SKILL_DESCRIPTION,\n whenToUse: SKILL_WHEN_TO_USE,\n content: SKILL_CONTENT,\n source: \"runtime\",\n });\n }\n }\n}\n\nexport {\n Config,\n ModelRouter,\n ModelRouter as default,\n SETTINGS_NS,\n name,\n ROW_ID,\n SKILL_CONTENT,\n SKILL_DESCRIPTION,\n SKILL_NAME,\n SKILL_WHEN_TO_USE,\n effortFor,\n recentStepsHadError,\n roleFor,\n routeFor,\n};\nexport type {\n AgentRole,\n ModelRoute,\n ReasoningEffort,\n RoutingMode,\n RouterConfig,\n} from \"./policy.js\";\n","/**\n * Pure routing policy for dsh-model-router: which model each agent role gets.\n * Kept free of Cordis imports so the policy is trivially unit-testable.\n * @module dsh-model-router/policy\n */\n\n/** Reasoning-effort levels a route may pin (mirrors the harness vocabulary). */\nexport type ReasoningEffort = \"off\" | \"low\" | \"high\" | \"max\";\n\n/**\n * How the router treats the root agent.\n * - `strict`: the root agent is always the planner (pro).\n * - `plan`: the root agent is pro only while plan mode is active; otherwise it\n * falls back to the executor route, reserving pro for real planning.\n */\nexport type RoutingMode = \"strict\" | \"plan\";\n\n/** One route: a provider/model pair stamped onto an agent request. */\nexport interface ModelRoute {\n provider: string;\n model: string;\n /**\n * Optional reasoning-effort override. When omitted, the request inherits the\n * session's own selection; when set, the router pins it for that role.\n */\n reasoningEffort?: ReasoningEffort;\n /** Optional output-token cap for the role; omitted means inherit. */\n maxTokens?: number;\n /**\n * Error-driven escalation (v1): when true, a failed execution step bumps the\n * next request's effort to `escalateTo`, wearing off after `recoverySteps`\n * clean steps. Deterministic, stateless — the session log is folded per\n * request, so only *prior* steps are ever considered.\n */\n escalateOnError?: boolean;\n /** Effort used for the request after a failed step. */\n escalateTo?: ReasoningEffort;\n /** Clean steps before escalation wears off. Defaults to 2. */\n recoverySteps?: number;\n}\n\n/** The two roles the router distinguishes. */\nexport type AgentRole = \"planner\" | \"executor\";\n\n/** Resolved router configuration: one route per role plus routing mode. */\nexport interface RouterConfig {\n planner: ModelRoute;\n executor: ModelRoute;\n mode: RoutingMode;\n /**\n * Live off-switch. Defaults to true; settable from Settings → Plugins →\n * model-router (applies immediately) or from the patch row (next boot).\n * When false, the router stops rewriting requests and unregisters the\n * prompt section and the skill.\n */\n enabled: boolean;\n promptSection: boolean;\n skill: boolean;\n}\n\n/** Default recovery window: an error escalates for the next two completed steps. */\nexport const DEFAULT_RECOVERY_STEPS = 2;\n\n/**\n * Classify an agent as planner or executor.\n *\n * The main (root) agent of a session is the planner. Every agent created as a\n * delegation child — `subagent`, `subagent_fork`, workflow workers, ralph\n * rounds — is an executor. The harness stamps two durable facts on children:\n * `options.subagentDepth` (>= 1) and the session header `origin: \"subagent\"`.\n *\n * @param agent - the live agent (any subset of the runtime shape).\n * @returns the role the agent should be routed as.\n */\nexport function roleFor(agent: unknown): AgentRole {\n const options = (agent as { options?: unknown })?.options;\n const depth = (options as { subagentDepth?: unknown })?.subagentDepth;\n if (typeof depth === \"number\" && depth >= 1) return \"executor\";\n const session = (agent as { session?: unknown })?.session;\n const origin = (session as { header?: unknown })?.header\n ? ((session as { header: { origin?: unknown } }).header.origin)\n : undefined;\n if (origin === \"subagent\") return \"executor\";\n return \"planner\";\n}\n\n/**\n * Resolve the route for one agent.\n * @param agent - the live agent.\n * @param config - the resolved router configuration.\n * @param planModeActive - whether plan mode is currently folded active for the\n * agent's session; consulted only in `plan` routing mode.\n * @returns the model route to stamp, or `undefined` to leave the request alone.\n */\nexport function routeFor(\n agent: unknown,\n config: RouterConfig,\n planModeActive = false,\n): ModelRoute | undefined {\n const role = roleFor(agent);\n if (role === \"executor\") return config.executor;\n // Root agent. In `plan` mode, reserve the planner route for actual planning;\n // otherwise the root falls back to the executor route.\n if (config.mode === \"plan\" && !planModeActive) return config.executor;\n return config.planner;\n}\n\n/**\n * Whether any of the last `recoverySteps` completed steps carried a failed\n * tool result. A failure is a `tool/result` event whose data carries an\n * `error` field (the harness records tool failures there).\n *\n * Steps are deduplicated by `turn:step`, and only *completed* steps count —\n * events are scanned from the tail, so the current in-flight request is never\n * considered.\n *\n * @param events - the agent's session event log (or `undefined`).\n * @param recoverySteps - how many completed steps back to scan.\n * @returns true when a failed step is within the window.\n */\nexport function recentStepsHadError(\n events: readonly unknown[] | undefined,\n recoverySteps: number = DEFAULT_RECOVERY_STEPS,\n): boolean {\n if (!Array.isArray(events) || recoverySteps <= 0) return false;\n const seen = new Set<string>();\n let steps = 0;\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i] as\n | { type?: string; data?: { turn?: number; step?: number; error?: unknown } }\n | undefined;\n if (event?.type !== \"tool/result\" || event.data === undefined) continue;\n const key = `${event.data.turn}:${event.data.step}`;\n if (!seen.has(key)) {\n // A new step beyond the recovery window ends the scan; events for steps\n // already inside the window are still checked below.\n if (steps >= recoverySteps) break;\n seen.add(key);\n steps += 1;\n }\n if (event.data.error !== undefined && event.data.error !== null) return true;\n }\n return false;\n}\n\n/**\n * Resolve the reasoning effort to stamp for one request.\n *\n * Baseline is the route's `reasoningEffort`; when `escalateOnError` is enabled\n * and a recent step failed, the effort bumps to `escalateTo` (falling back to\n * the baseline when `escalateTo` is unset). Returns `undefined` to leave the\n * request's effort alone (inherit the session selection).\n *\n * @param route - the resolved route for the agent.\n * @param events - the agent's session event log.\n * @returns the effort to stamp, or `undefined` to inherit.\n */\nexport function effortFor(\n route: ModelRoute,\n events: readonly unknown[] | undefined,\n): ReasoningEffort | undefined {\n if (route.escalateOnError === true && recentStepsHadError(events, route.recoverySteps)) {\n return route.escalateTo ?? route.reasoningEffort;\n }\n return route.reasoningEffort;\n}\n"],"mappings":";AAoBA,SAAkB,eAAe;AACjC,OAAO,OAAO;AACd,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB,yBAAyB;;;ACsCnD,IAAM,yBAAyB;AAa/B,SAAS,QAAQ,OAA2B;AACjD,QAAM,UAAW,OAAiC;AAClD,QAAM,QAAS,SAAyC;AACxD,MAAI,OAAO,UAAU,YAAY,SAAS,EAAG,QAAO;AACpD,QAAM,UAAW,OAAiC;AAClD,QAAM,SAAU,SAAkC,SAC5C,QAA6C,OAAO,SACtD;AACJ,MAAI,WAAW,WAAY,QAAO;AAClC,SAAO;AACT;AAUO,SAAS,SACd,OACA,QACA,iBAAiB,OACO;AACxB,QAAM,OAAO,QAAQ,KAAK;AAC1B,MAAI,SAAS,WAAY,QAAO,OAAO;AAGvC,MAAI,OAAO,SAAS,UAAU,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;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,OAAO,KAAyB;AACtC,QAAI,KAAK,eAAe;AACtB,WAAK,cAAc;AACnB,WAAK,gBAAgB;AAAA,IACvB;AACA,QAAI,KAAK,cAAc;AACrB,WAAK,aAAa;AAClB,WAAK,eAAe;AAAA,IACtB;AACA,QAAI,CAAC,IAAI,QAAS;AAClB,QAAI,IAAI,eAAe;AACrB,WAAK,gBAAgB,KAAK,QAAQ,aAAa,QAAQ;AAAA,QACrD,MAAM;AAAA,QACN,OAAO;AAAA,QACP,MAAM,aAAa,WAAW,mBAAmB,IAAI,QAAQ,KAAK,EAAE;AAAA,UAClE;AAAA,UACA,IAAI,SAAS;AAAA,QACf;AAAA,MACF,CAAC;AAAA,IACH;AACA,QAAI,IAAI,OAAO;AACb,WAAK,eAAe,KAAK,QAAQ,OAAO,SAAS;AAAA,QAC/C,MAAM;AAAA,QACN,aAAa;AAAA,QACb,WAAW;AAAA,QACX,SAAS;AAAA,QACT,QAAQ;AAAA,MACV,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-model-router",
3
3
  "description": "DeepSeek Harness plugin: role-based model routing — the planner agent runs on deepseek-v4-pro, delegated executor subagents run on deepseek-v4-flash.",
4
- "version": "0.3.0",
4
+ "version": "0.5.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -13,6 +13,9 @@
13
13
  "types": "./lib/index.d.ts",
14
14
  "default": "./lib/index.js"
15
15
  },
16
+ "./client": {
17
+ "default": "./lib/client.js"
18
+ },
16
19
  "./package.json": "./package.json"
17
20
  },
18
21
  "files": [
@@ -24,10 +27,19 @@
24
27
  "dsh": {
25
28
  "bundle": {
26
29
  "patch": "./cordis.patch.yml"
30
+ },
31
+ "client": {
32
+ "inject": [
33
+ "@deepseek-ai/dsh-client-ui-slots",
34
+ "@deepseek-ai/dsh-client-ui-settings",
35
+ "@deepseek-ai/dsh-client-locale"
36
+ ],
37
+ "platform": "web"
27
38
  }
28
39
  },
29
40
  "scripts": {
30
- "build": "tsup",
41
+ "build": "tsup && npm run build:client",
42
+ "build:client": "node scripts/build-client.mjs",
31
43
  "prepare": "npm run build",
32
44
  "typecheck": "tsc --noEmit",
33
45
  "test": "vitest run"
@@ -35,13 +47,17 @@
35
47
  "peerDependencies": {
36
48
  "@deepseek-ai/cordis": "^4.0.1",
37
49
  "@deepseek-ai/schemastery": "^3.18.1",
38
- "@deepseek-ai/dsh-plan-mode": "^0.1.0-rc.8"
50
+ "@deepseek-ai/dsh-plan-mode": "^0.1.0-rc.8",
51
+ "@deepseek-ai/dsh-settings": "^0.1.0-rc.8"
39
52
  },
40
53
  "devDependencies": {
41
54
  "@deepseek-ai/cordis": "^4.0.1",
42
55
  "@deepseek-ai/schemastery": "^3.18.1",
43
56
  "@deepseek-ai/dsh-plan-mode": "^0.1.0-rc.8",
57
+ "@deepseek-ai/dsh-settings": "^0.1.0-rc.8",
44
58
  "@types/node": "^22.10.0",
59
+ "@types/react": "^18.3.12",
60
+ "react": "^18.3.1",
45
61
  "tsup": "^8.3.5",
46
62
  "typescript": "^5.7.2",
47
63
  "vitest": "^2.1.8"