dsh-fallback-router 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -2
  3. package/README.zh-CN.md +170 -0
  4. package/bundle/cordis.patch.yml +19 -0
  5. package/dist/authorized-route.d.ts +68 -0
  6. package/dist/automatch.d.ts +98 -0
  7. package/dist/chains.d.ts +186 -0
  8. package/dist/client/ConversationFallbackSwitch.d.ts +91 -0
  9. package/dist/client/FallbacksCard.d.ts +36 -0
  10. package/dist/client/GeneralFallbacksRow.d.ts +19 -0
  11. package/dist/client/ModelsPanel.d.ts +64 -0
  12. package/dist/client/SubagentRoleBadge.d.ts +53 -0
  13. package/dist/client/fallbacks-store.d.ts +631 -0
  14. package/dist/client/index.d.ts +64 -0
  15. package/dist/client/index.js +3420 -0
  16. package/dist/client/locales.d.ts +454 -0
  17. package/dist/client/switch-guard.d.ts +17 -0
  18. package/dist/client/use-snapshot.d.ts +11 -0
  19. package/dist/commands.d.ts +380 -0
  20. package/dist/config.d.ts +239 -0
  21. package/dist/cooldown.d.ts +57 -0
  22. package/dist/events.d.ts +52 -0
  23. package/dist/gateway.d.ts +359 -0
  24. package/dist/index.d.ts +195 -0
  25. package/dist/index.js +4587 -0
  26. package/dist/models.d.ts +306 -0
  27. package/dist/override.d.ts +39 -0
  28. package/dist/presets.d.ts +20 -0
  29. package/dist/recovery.d.ts +92 -0
  30. package/dist/role-notice.d.ts +184 -0
  31. package/dist/role-persona.d.ts +71 -0
  32. package/dist/role-projection-key.d.ts +41 -0
  33. package/dist/role-projection.d.ts +152 -0
  34. package/dist/role-resolution.d.ts +105 -0
  35. package/dist/roles.d.ts +90 -0
  36. package/dist/route-allowlist.d.ts +43 -0
  37. package/dist/schema.d.ts +46 -0
  38. package/dist/seeds.d.ts +237 -0
  39. package/dist/selectors.d.ts +38 -0
  40. package/dist/state.d.ts +205 -0
  41. package/dist/subagent-policy.d.ts +123 -0
  42. package/dist/subagents-seam.d.ts +305 -0
  43. package/dist/time-slots.d.ts +147 -0
  44. package/dist/tui-settings.d.ts +145 -0
  45. package/dist/tui.d.ts +63 -0
  46. package/dist/virtual-adapter.d.ts +259 -0
  47. package/icon.svg +16 -0
  48. package/locale/en.json +6 -0
  49. package/locale/zh.json +6 -0
  50. package/package.json +138 -6
@@ -0,0 +1,380 @@
1
+ /**
2
+ * `/fallbacks` slash command (plan fallbacks-role-runtime T3, AC-5).
3
+ *
4
+ * Session-scoped, read-only diagnostic: current session origin → resolved
5
+ * role → resolved chain (role chain, else rootChain — an `inherit: true`
6
+ * tail is annotated 「(inherit-root)」) → recent `fallbacks/switch` events
7
+ * (newest first, capped) → cooldown status. Mirrors dsh-advisor's
8
+ * `/advisor` command pattern: a conditional `ctx.inject(['commands'])` child
9
+ * in `src/index.ts` calls {@link registerFallbacksCommands} with a
10
+ * factory-bound handler; `commands` never joins the top-level inject list, so
11
+ * the command is silently absent when no command registry is composed (no
12
+ * top-level inject pollution — advisor T1 fix).
13
+ *
14
+ * The bare diagnostic and the config readback are **read-only**: they never
15
+ * mutate fallback state (no cooldown reset, no pending-switch writes). The
16
+ * `config revert-seed <role-id>` subcommand is the one write action (plan
17
+ * fallbacks-tui-settings Task 2, AC-3): it delegates to the controller's
18
+ * `revertSeed` (wired to the seeds service) and prints the outcome — a
19
+ * web-card action capability the settings seam cannot express. zh/en copy
20
+ * lives in this file — the client half's `src/client/locales.ts` is a
21
+ * separate client-side dictionary. The host carries no per-session locale
22
+ * signal (the `locale` service is client-side), so the wiring picks a
23
+ * deterministic default (`zh`, this repo's primary language); both
24
+ * dictionaries are unit-tested.
25
+ *
26
+ * @module dsh-fallback-router/commands
27
+ */
28
+ import type { CommandDefinition } from '@deepseek-ai/dsh-commands';
29
+ import { type FallbacksRole } from './config.ts';
30
+ import type { Origin } from './roles.ts';
31
+ import type { FallbacksSwitchEventData } from './events.ts';
32
+ import type { SeedRevertFailReason } from './seeds.ts';
33
+ import { type SlotRowConfig } from './time-slots.ts';
34
+ /** How many recent `fallbacks/switch` events `/fallbacks` shows (newest first). */
35
+ export declare const RECENT_SWITCHES_LIMIT = 5;
36
+ /** Minimal command registry surface (satisfied by the dsh `CommandService`). */
37
+ export interface FallbacksCommandRegistry {
38
+ register(definition: CommandDefinition): () => void;
39
+ }
40
+ /** Minimal agent/session surface the command reads (satisfied by the real `Agent`). */
41
+ export interface FallbacksCommandAgent {
42
+ readonly id: string;
43
+ readonly options?: {
44
+ readonly provider?: string;
45
+ readonly model?: string;
46
+ };
47
+ readonly session: {
48
+ readonly header?: {
49
+ readonly origin?: Origin;
50
+ };
51
+ readonly snapshotEvents: () => readonly unknown[];
52
+ };
53
+ }
54
+ /** One active cooldown entry displayed by `/fallbacks`. */
55
+ export interface FallbacksCooldownEntry {
56
+ /** `${provider}/${model}` key. */
57
+ readonly key: string;
58
+ /** Expiry epoch ms; `Infinity` for `revertPolicy: 'never'`. */
59
+ readonly untilEpochMs: number;
60
+ /** True for a half-open marker row (an expired cooldown awaiting a recovery probe). */
61
+ readonly halfOpen?: boolean;
62
+ }
63
+ /** The read-only diagnostic snapshot the `/fallbacks` handler renders. */
64
+ export interface FallbacksCommandSnapshot {
65
+ /** Session origin: `'root'` when the agent carries no header origin. */
66
+ readonly origin: Origin;
67
+ /** Resolved role (first matching `roles.rules` entry → built-in `'inherit'`, spec §7.1). */
68
+ readonly role: string;
69
+ /** True when the role's own chain is non-empty and shown; false when rootChain (or none) is shown. */
70
+ readonly chainRole: boolean;
71
+ /** The displayed chain entries: the role's own chain when non-empty, else
72
+ * rootChain — except `fallback: 'none'` with an empty own chain, which
73
+ * yields `[]` even when rootChain is non-empty (nothing appended, mirroring
74
+ * resolveChainViews' `[...[], ...[]]`); empty = not configured. */
75
+ readonly chain: readonly string[];
76
+ /** True when rootChain is appended as the inherit fallback tail (role's
77
+ * `fallback` is `'inherit-root'` — or the role is unknown — and rootChain
78
+ * is non-empty; the diagnostic annotation source, spec §7.4). */
79
+ readonly inherit: boolean;
80
+ /** Current time-slot winner + display label (P5/P7): the 分时切换 side of
81
+ * the status strip. The switches section below is the 降级切换 side —
82
+ * the copy never mixes. */
83
+ readonly slot: {
84
+ readonly winner: SlotRowConfig | 'all-day';
85
+ readonly label: string;
86
+ };
87
+ /** Recent `fallbacks/switch` events (failure walks — 降级切换), newest
88
+ * first, capped at {@link RECENT_SWITCHES_LIMIT}. */
89
+ readonly switches: readonly FallbacksSwitchEventData[];
90
+ /** Active cooldown entries for the agent. */
91
+ readonly cooldown: readonly FallbacksCooldownEntry[];
92
+ }
93
+ /**
94
+ * The composed-config surface `/fallbacks config` renders (plan
95
+ * fallbacks-tui-client T2, AC-2): the composed `fallbacks` namespace as the
96
+ * runtime sees it (settings user layer included). Roles are summarized from
97
+ * `roles.list` as `{ id, chainCount }` — the two-block model: `roles.list`
98
+ * entities carry id/persona/chain/fallback (NO per-role `model`;
99
+ * `provider`/`model` live on `roles.rules`), so the readback line is id +
100
+ * chain count, never a rules dump.
101
+ *
102
+ * Enriched readback (plan fallbacks-tui-settings Task 2, AC-4): timeSlots /
103
+ * tz / roles.rules join the summary so TUI operators can verify `/settings`
104
+ * edits. One summarized time-slot row: preset rows carry `{ preset,
105
+ * chainCount }` (windows are frozen code constants in {@link PRESETS} and
106
+ * never stored on the row — the render resolves the window text from
107
+ * PRESETS); custom rows carry `{ start, end, chainCount }`. Rules rows carry
108
+ * `{ provider, model, role }` — an omitted provider/model (wildcard match at
109
+ * runtime) is summarized as `''` and rendered as `*`.
110
+ */
111
+ export interface FallbacksConfigSummary {
112
+ /**
113
+ * Content-presence gate (`isFallbackActive`, plan fallbacks-web-ux-alignment
114
+ * T2 — the removed config-level `enabled` switch re-keyed): the plugin
115
+ * intervenes exactly when a chain/time-slot/role is configured.
116
+ */
117
+ readonly active: boolean;
118
+ readonly triggerCodes: readonly string[];
119
+ readonly rootChain: readonly string[];
120
+ /** Summarized time-slot rows (preset rows carry `preset`, custom rows carry `start`/`end`; both may carry a day mask). */
121
+ readonly timeSlots: readonly {
122
+ preset?: string;
123
+ start?: string;
124
+ end?: string;
125
+ days?: readonly number[];
126
+ chainCount: number;
127
+ }[];
128
+ /** Config-level timezone for slot matching (default `Asia/Shanghai`). */
129
+ readonly tz: string;
130
+ readonly roles: readonly {
131
+ id: string;
132
+ chainCount: number;
133
+ }[];
134
+ /** Summarized role rules: provider/model patterns → declared role (or the built-in `'inherit'`). */
135
+ readonly rules: readonly {
136
+ provider: string;
137
+ model: string;
138
+ role: string;
139
+ }[];
140
+ readonly cooldownMs: number;
141
+ readonly revertPolicy: string;
142
+ readonly maxSwitchesPerStep: number;
143
+ readonly alwaysModeRetryCap: number;
144
+ readonly presets: 'bundled' | 'none';
145
+ /** Dispatch-time LLM role auto-match switch (default true). */
146
+ readonly roleAutoMatch: boolean;
147
+ }
148
+ /**
149
+ * The session-scoped read-only operations the `/fallbacks` handler drives.
150
+ * Implemented by the wiring (`src/index.ts`) against the live config source
151
+ * (`roles.list` / `rootChain` — no chain map anymore) and the per-agent
152
+ * state store; faked in unit tests.
153
+ */
154
+ export interface FallbacksCommandController {
155
+ /** Snapshot the session's fallback diagnostics. Never mutates state. */
156
+ getSnapshot(agent: FallbacksCommandAgent): FallbacksCommandSnapshot;
157
+ /**
158
+ * Snapshot the composed fallbacks config (settings readback). Not
159
+ * agent-scoped — the composed config is session-independent; reads the
160
+ * same live config source the runtime reads. Never mutates state.
161
+ */
162
+ getConfig(): FallbacksConfigSummary;
163
+ /**
164
+ * Revert one role's persona to its CURRENT declared seed default (AC-3).
165
+ * Surfaces the outcome as VALUES, not copy (qc1 F-003 / qc2 F-006 / qc3
166
+ * F-003): `ok: true` when reverted; `ok: false` with the
167
+ * {@link SeedRevertFailReason} code explaining why not (not a seeded role
168
+ * / role row absent). The command handler localizes the code per its
169
+ * registration locale — the controller never pre-localizes. A
170
+ * settings-write failure propagates loudly as a rejected promise (the
171
+ * same contract as the seeds service — never swallowed into an
172
+ * `ok: false`); the handler maps it to a structured error. Implemented by
173
+ * the wiring against the per-apply seed manager
174
+ * (`seeds.revert(roleId, seedsIo)`), not the typert gateway.
175
+ */
176
+ revertSeed(roleId: string): Promise<{
177
+ ok: boolean;
178
+ reason?: SeedRevertFailReason;
179
+ }>;
180
+ }
181
+ /** zh/en dictionaries for the `/fallbacks` output. */
182
+ export declare const FALLBACKS_COMMAND_LOCALES: {
183
+ readonly zh: {
184
+ readonly title: "当前会话 fallback 诊断(只读)";
185
+ readonly description: "查看当前会话的降级链、最近降级切换与冷却状态(只读)";
186
+ readonly usageConfig: "查看组合后的 fallbacks 配置(设置回读)";
187
+ readonly usageRevertSeed: "将角色的 persona 还原为已声明的 Seed 默认";
188
+ readonly usage: " /fallbacks config 查看组合后的 fallbacks 配置(设置回读)\n /fallbacks config revert-seed <role-id> 将角色的 persona 还原为已声明的 Seed 默认";
189
+ readonly origin: "会话来源";
190
+ readonly role: "角色";
191
+ readonly chain: "链";
192
+ readonly inheritRoot: "(inherit-root)";
193
+ readonly chainNone: "未配置";
194
+ readonly slot: "分时";
195
+ readonly switches: "最近降级切换";
196
+ readonly switchesNone: "本会话暂无 fallback 切换";
197
+ readonly switchLine: "{from} → {to}(role={role},reason={reason})";
198
+ readonly cooldown: "冷却";
199
+ readonly cooldownNone: "无活跃冷却";
200
+ readonly cooldownLine: "{key} 冷却至 {time}";
201
+ readonly cooldownNever: "{key} 会话内不再回主";
202
+ readonly cooldownHalfOpen: "{key} half-open(等待恢复探针)";
203
+ readonly reason: {
204
+ readonly 'trigger-code': "触发码";
205
+ readonly 'always-cap': "always 上限";
206
+ };
207
+ readonly configTitle: "Fallbacks 配置";
208
+ readonly configEnabled: "已启用";
209
+ readonly configDisabled: "未启用";
210
+ readonly configTriggerCodes: "触发码";
211
+ readonly configRootChain: "根链";
212
+ readonly configEmpty: "(空)";
213
+ readonly configTimeSlots: "分时槽";
214
+ readonly configSlotPresetItem: "{preset}(chain: {n}, window {window})";
215
+ readonly configSlotPresetBare: "{preset}(chain: {n})";
216
+ readonly configSlotCustomItem: "custom {start}-{end}(chain: {n})";
217
+ readonly configTz: "时区";
218
+ readonly configRoles: "角色";
219
+ readonly configRoleItem: "{id}(chain: {n})";
220
+ readonly configRules: "角色规则";
221
+ readonly configCooldown: "冷却";
222
+ readonly configRevert: "回主策略";
223
+ readonly configMaxSwitches: "单步最大切换";
224
+ readonly configAlwaysCap: "always 上限";
225
+ readonly configPresets: "预置";
226
+ readonly configRoleAutoMatch: "角色自动匹配";
227
+ readonly configEdit: "编辑:/settings(TUI 设置界面)或 ~/.dsh/profiles/<profile>/cordis.patch.yml(插件行)/ $DSH_HOME/settings.yaml(fallbacks: 分节)";
228
+ readonly configEditHint: "TUI 通过 /settings 修改配置;文件编辑仍然可用";
229
+ readonly revertSeedOk: "角色 {id} 已还原为 Seed 默认";
230
+ readonly revertSeedFail: "角色 {id} 未还原({reason})";
231
+ readonly revertSeedError: "角色 {id} 还原失败(设置写入失败)";
232
+ readonly revertSeedReason: {
233
+ readonly 'not-seeded': "未声明种子";
234
+ readonly 'row-absent': "角色行不存在";
235
+ readonly 'settings-unavailable': "设置通道不可用";
236
+ };
237
+ };
238
+ readonly en: {
239
+ readonly title: "Session fallback diagnostics (read-only)";
240
+ readonly description: "Inspect fallback chain, recent fallback switches, and cooldown for this session (read-only)";
241
+ readonly usageConfig: "show the composed fallbacks config (settings readback)";
242
+ readonly usageRevertSeed: "revert a role's persona to its declared seed default";
243
+ readonly usage: " /fallbacks config show the composed fallbacks config (settings readback)\n /fallbacks config revert-seed <role-id> revert a role's persona to its declared seed default";
244
+ readonly origin: "Session origin";
245
+ readonly role: "Role";
246
+ readonly chain: "Chain";
247
+ readonly inheritRoot: " (inherit-root)";
248
+ readonly chainNone: "not configured";
249
+ readonly slot: "Time slot";
250
+ readonly switches: "Recent fallback switches";
251
+ readonly switchesNone: "No fallback switches in this session";
252
+ readonly switchLine: "{from} → {to} (role={role}, reason={reason})";
253
+ readonly cooldown: "Cooldown";
254
+ readonly cooldownNone: "none active";
255
+ readonly cooldownLine: "{key} suppressed until {time}";
256
+ readonly cooldownNever: "{key} not reverting this session";
257
+ readonly cooldownHalfOpen: "{key} half-open (awaiting recovery probe)";
258
+ readonly reason: {
259
+ readonly 'trigger-code': "trigger-code";
260
+ readonly 'always-cap': "always-cap";
261
+ };
262
+ readonly configTitle: "Fallbacks config";
263
+ readonly configEnabled: "enabled";
264
+ readonly configDisabled: "disabled";
265
+ readonly configTriggerCodes: "Trigger codes";
266
+ readonly configRootChain: "Root chain";
267
+ readonly configEmpty: "(empty)";
268
+ readonly configTimeSlots: "Time slots";
269
+ readonly configSlotPresetItem: "{preset} (chain: {n}, window {window})";
270
+ readonly configSlotPresetBare: "{preset} (chain: {n})";
271
+ readonly configSlotCustomItem: "custom {start}-{end} (chain: {n})";
272
+ readonly configTz: "TZ";
273
+ readonly configRoles: "Roles";
274
+ readonly configRoleItem: "{id} (chain: {n})";
275
+ readonly configRules: "Rules";
276
+ readonly configCooldown: "Cooldown";
277
+ readonly configRevert: "Revert";
278
+ readonly configMaxSwitches: "Max switches/step";
279
+ readonly configAlwaysCap: "Always-mode cap";
280
+ readonly configPresets: "Presets";
281
+ readonly configRoleAutoMatch: "Auto-match";
282
+ readonly configEdit: "Edit: /settings (TUI settings screen) or ~/.dsh/profiles/<profile>/cordis.patch.yml (plugin row) / $DSH_HOME/settings.yaml (fallbacks: section)";
283
+ readonly configEditHint: "TUI edits config via /settings; file editing still works";
284
+ readonly revertSeedOk: "role {id} reverted to its seed default";
285
+ readonly revertSeedFail: "role {id} not reverted ({reason})";
286
+ readonly revertSeedError: "role {id} revert failed (settings write failed)";
287
+ readonly revertSeedReason: {
288
+ readonly 'not-seeded': "not a seeded role";
289
+ readonly 'row-absent': "role row absent";
290
+ readonly 'settings-unavailable': "settings channel unavailable";
291
+ };
292
+ };
293
+ };
294
+ /** A locale id supported by {@link FALLBACKS_COMMAND_LOCALES}. */
295
+ export type FallbacksCommandLocale = keyof typeof FALLBACKS_COMMAND_LOCALES;
296
+ /** The `/fallbacks` subcommands: `'config'` (composed-config readback),
297
+ * `'revert-seed'` (persona revert action, requires a role id), or `''` (the
298
+ * bare session snapshot). */
299
+ export type FallbacksSubcommand = '' | 'config' | 'revert-seed';
300
+ /** One parsed subcommand invocation: the kind plus the optional role id
301
+ * carried by `revert-seed`. */
302
+ export interface FallbacksSubcommandParse {
303
+ readonly kind: FallbacksSubcommand;
304
+ /** The role id argument of `revert-seed` (present iff `kind === 'revert-seed'`). */
305
+ readonly arg?: string;
306
+ }
307
+ /**
308
+ * Map an invocation's rawInput to a subcommand: trimmed `'config'` →
309
+ * `{ kind: 'config' }`; `'config revert-seed <id>'` → `{ kind: 'revert-seed',
310
+ * arg: id }`; everything else (incl. empty, a missing id, or an unknown
311
+ * subcommand under `config`) → `{ kind: '' }` (bare snapshot). Lenient by
312
+ * design — unknown input keeps today's bare behavior, never errors.
313
+ */
314
+ export declare function parseFallbacksSubcommand(rawInput: string): FallbacksSubcommandParse;
315
+ /**
316
+ * The newest `limit` `fallbacks/switch` events from a session's raw event
317
+ * log, newest first. Unknown event shapes and malformed `fallbacks/switch`
318
+ * payloads are skipped defensively (a session log may carry any
319
+ * `SessionEventMap` type, and the durable log can outlive schema versions).
320
+ */
321
+ export declare function recentFallbacksSwitches(events: readonly unknown[], limit: number): FallbacksSwitchEventData[];
322
+ /**
323
+ * The chain entries `/fallbacks` shows for a role (spec §7.4): the declared
324
+ * role's own chain when non-empty (`chainRole: true`); an empty own chain
325
+ * defers to `rootChain` unless `fallback: 'none'` — then nothing is appended
326
+ * and the display chain is empty, mirroring `resolveChainViews`'s
327
+ * `[...[], ...[]]` exactly; undeclared ids and the built-in `'inherit'`
328
+ * role resolve to `rootChain`. `inherit: true` marks the append-not-replace
329
+ * tail — the role's `fallback` is `'inherit-root'` (the default) or the role
330
+ * is unknown/built-in `'inherit'`, and `rootChain` is non-empty. Mirrors
331
+ * `resolveChainViews`'s concatenation (see {@link buildRoleEntries} —
332
+ * `src/chains.ts`; the diagnostic keeps its display semantics: the role's
333
+ * own chain renders in full, `rootChain` only when the role has no own
334
+ * chain, with the inherit tail as an annotation) without a failing model to
335
+ * resolve against (the diagnostic is model-independent).
336
+ *
337
+ * `warn` mirrors {@link resolveChainViews}' defensive unknown-role warn
338
+ * (qc2 F-002 — routed through the injected logger; the `/fallbacks` path
339
+ * never reaches here unsanitized, as {@link resolveRole} resolves to a
340
+ * declared id or `'inherit'` first, so this is direct-caller parity).
341
+ */
342
+ export declare function resolveChainForDiagnostic(roles: readonly FallbacksRole[], rootChain: readonly string[], role: string, warn?: (message: string) => void): {
343
+ readonly chainRole: boolean;
344
+ readonly chain: readonly string[];
345
+ readonly inherit: boolean;
346
+ };
347
+ /**
348
+ * Cap for the composed-config readback's LIST lines — Trigger codes, Root
349
+ * chain, Time slots, Roles, and Rules (qc2 Task-2 Minor): beyond this many
350
+ * items a line truncates with `…` while its leading count always stays the
351
+ * FULL count. Same sanity scale as {@link RECENT_SWITCHES_LIMIT}.
352
+ */
353
+ export declare const FALLBACKS_CONFIG_LIST_CAP = 5;
354
+ /**
355
+ * Render the `/fallbacks config` surface (plan fallbacks-tui-client T2,
356
+ * AC-2 + fallbacks-tui-settings Task 2 AC-4): the composed `fallbacks`
357
+ * namespace as the runtime reads it — enriched with the time-slot rows
358
+ * (preset rows resolve their frozen window from {@link PRESETS}), the
359
+ * config timezone, and the role rules — plus edit hints pointing at the
360
+ * `/settings` TUI edit surface while keeping the file-edit documentation.
361
+ * The FIRST LINE marks the composed-config readback — distinct from the
362
+ * diagnostic title and never merged into {@link fallbacksCommandText} (two
363
+ * operator surfaces, product lock). Locale defaults to `zh` (the command
364
+ * default); en dictionary tested.
365
+ */
366
+ export declare function fallbacksConfigText(summary: FallbacksConfigSummary, locale?: FallbacksCommandLocale): string;
367
+ /**
368
+ * Render the `/fallbacks` status surface for one snapshot. Kept minimal and
369
+ * truthful: origin → role → chain (+ inherit tail) → current slot (分时) →
370
+ * recent switches (降级切换) → cooldown.
371
+ */
372
+ export declare function fallbacksCommandText(snapshot: FallbacksCommandSnapshot, locale?: FallbacksCommandLocale): string;
373
+ /**
374
+ * Register the `/fallbacks` command with a command registry (the dsh
375
+ * `CommandService`, or a fake in tests). Called from the plugin's conditional
376
+ * `ctx.inject(['commands'], ...)` child — the command exists only when a
377
+ * registry is composed.
378
+ * @returns the registry disposer (the inject child owns its lifetime).
379
+ */
380
+ export declare function registerFallbacksCommands(registry: FallbacksCommandRegistry, controller: FallbacksCommandController, locale?: FallbacksCommandLocale): () => void;
@@ -0,0 +1,239 @@
1
+ /**
2
+ * The `fallbacks` settings namespace: config types + defaults (the
3
+ * schemastery `Config` schema lives in `./schema.ts`, host-only — this
4
+ * module must stay free of `@deepseek-ai/*` value imports so the client
5
+ * bundle never reaches schemastery).
6
+ *
7
+ * Two-block config model (plan fallbacks-role-config-model): block 1
8
+ * `rootChain` — the root agent's single fallback chain (empty = no
9
+ * degradation) — plus block 2 declared role entities: `roles.list`
10
+ * (id/persona/prompt?/permissions?/chain?/fallback) and
11
+ * `roles.rules` enum references into the declared ids (or the built-in
12
+ * `'inherit'` role). The legacy `chains` / `roles.default` keys are gone
13
+ * from the schema and type (zero residual, migration table excepted); the
14
+ * runtime consumes the new shape directly and flags surviving legacy keys
15
+ * at startup via `detectLegacyKeys` (see `src/index.ts` apply()).
16
+ *
17
+ * Spec §4 is authoritative for field names and default values — notably
18
+ * `triggerCodes` defaults to dsh's stable failure codes `['AUTH', 'QUOTA',
19
+ * 'RATE_LIMIT']` (there is no `QUOTA_EXCEEDED` code in dsh), and an
20
+ * unconfigured install (empty `rootChain`, no time slots, empty roles) is a
21
+ * no-op pass-through exactly like an uninstalled plugin (AC-8 —
22
+ * {@link isFallbackActive}). There is NO config-level `enabled` switch
23
+ * (plan fallbacks-web-ux-alignment T2): the Plugins-page row toggle is the
24
+ * master switch (row disable = fiber destroy), and the runtime gates re-key
25
+ * to content presence. A stored profile still carrying the removed
26
+ * `enabled:` key loads cleanly — the gateway tolerates and strips it (the
27
+ * advisor LEGACY_KEYS mechanism), it is never read and never re-persisted.
28
+ *
29
+ * This module is pure logic: it must not import any `@deepseek-ai/*` package
30
+ * (types included) — `FallbacksConfig` is the plugin's own type. Task 3
31
+ * registers the schemastery schema (see `./schema.ts`) with
32
+ * `installSettingsSection` under the `fallbacks` settings namespace.
33
+ *
34
+ * @module dsh-fallback-router/config
35
+ */
36
+ import type { SlotRowConfig } from './time-slots.ts';
37
+ import type { ModelProfile, ProviderRetry } from './models.ts';
38
+ /** How an expired cooldown recovers the route (plan fallbacks-half-open-recovery Task 1). */
39
+ export type RecoveryPolicy = 'timer' | 'half-open';
40
+ /** How a cooled-down model comes back (spec §4). */
41
+ export type RevertPolicy = 'cooldown-expiry' | 'never';
42
+ /** A single role rule: match on provider/model patterns (spec §3). */
43
+ export interface FallbacksRoleRule {
44
+ /**
45
+ * Legacy persisted wire field (PR #62 feedback): rules are subagent-only,
46
+ * so this constraint is IGNORED at match time — root requests never
47
+ * match rules. Kept in the type/schema so pre-feedback `settings.yaml`
48
+ * files that carry `origin` still parse, validate, and save unchanged.
49
+ */
50
+ origin?: 'root' | 'subagent';
51
+ provider?: string;
52
+ model?: string;
53
+ role: string;
54
+ }
55
+ /**
56
+ * Chain-append strategy of a declared role entity: `inherit-root` (the
57
+ * default) runs the role's own chain and then appends `rootChain`;
58
+ * `none` uses only the role's own chain.
59
+ */
60
+ export type FallbackStrategy = 'inherit-root' | 'none';
61
+ /**
62
+ * A declared role entity (plan fallbacks-role-config-model Task 1).
63
+ *
64
+ * `prompt` / `permissions` are schema-reserved for the next iteration
65
+ * (fallbacks-explicit-role-tool) — no consumer this round, and writing them
66
+ * does NOT change this round's degradation behavior.
67
+ */
68
+ export interface FallbacksRole {
69
+ id: string;
70
+ /** Personality hint (人格提示) — free text, never validated. */
71
+ persona: string;
72
+ /** Reserved for next iteration — no consumer this round. */
73
+ prompt?: string;
74
+ /** Reserved for next iteration — no consumer this round. */
75
+ permissions?: {
76
+ allow?: string[];
77
+ deny?: string[];
78
+ };
79
+ chain?: string[];
80
+ fallback?: FallbackStrategy;
81
+ }
82
+ /** Role grouping for fallback chains: declared entities + enum references. */
83
+ export interface FallbacksRoles {
84
+ list: FallbacksRole[];
85
+ rules: FallbacksRoleRule[];
86
+ }
87
+ /** A fixed, user-selectable fallback chain exposed as its own picker route. */
88
+ export interface NamedFallbackChain {
89
+ /** Stable route id; lowercase letters, digits, and hyphens only. */
90
+ id: string;
91
+ /** Human-readable model-picker label. */
92
+ name: string;
93
+ /** Ordered provider/model selectors tried after a failure. */
94
+ chain: string[];
95
+ }
96
+ /**
97
+ * The full `fallbacks` settings shape (two-block config model, verbatim
98
+ * field names).
99
+ */
100
+ export interface FallbacksConfig {
101
+ /**
102
+ * The authored model profiles — THE primary config surface of this plugin
103
+ * (see `src/models.ts`). When non-empty they COMPILE down to `rootChain` +
104
+ * `timeSlots` at normalization time; the compiled fields are then derived
105
+ * state, never authored.
106
+ */
107
+ models: ModelProfile[];
108
+ /** Per-provider retry rows (对每个 provider 单独开启重试). */
109
+ providers: ProviderRetry[];
110
+ triggerCodes: string[];
111
+ rootChain: string[];
112
+ roles: FallbacksRoles;
113
+ /** Fixed named chains exposed as independent model-picker routes. */
114
+ namedChains?: NamedFallbackChain[];
115
+ cooldownMs: number;
116
+ revertPolicy: RevertPolicy;
117
+ maxSwitchesPerStep: number;
118
+ alwaysModeRetryCap: number;
119
+ /**
120
+ * Preset-role injection switch: `'bundled'` declares the 5 preset roles
121
+ * (spec §9.2) as seed rows on apply; `'none'` disables declaration.
122
+ * Optional on purpose — a required field would break library consumers
123
+ * that construct `FallbacksConfig` literals with the existing 8 keys
124
+ * (additive, non-breaking). The value domain is guarded by the schema
125
+ * (`Config` in `src/schema.ts`), NOT by `validateFallbacksConfig`, and
126
+ * every resolved config carries a value via the schema default.
127
+ */
128
+ presets?: 'bundled' | 'none';
129
+ /**
130
+ * Dispatch-time LLM role auto-match switch (plan fallbacks-role-automatch
131
+ * Task 1): when `true` (default), a subagent-origin request with no
132
+ * explicit/rules-resolved role may have the best-fit declared role picked
133
+ * by the LLM; `false` reproduces today's behavior exactly. Optional on
134
+ * purpose, mirroring `presets` — a required field would break library
135
+ * consumers that construct `FallbacksConfig` literals with the existing
136
+ * keys (additive, non-breaking). The value domain is guarded by the
137
+ * schema (`z.boolean().default(true)` in `src/schema.ts`), and the
138
+ * runtime reads it defensively as `config.roleAutoMatch ?? true` (safe
139
+ * for direct constructors that omit it).
140
+ */
141
+ roleAutoMatch?: boolean;
142
+ /**
143
+ * Extra time-slot rows (plan fallbacks-timeslots Task 1, P5): the FIRST
144
+ * matching row's chain becomes the effective root chain at request time;
145
+ * `rootChain` (the all-day chain) is always the last row.
146
+ * Optional on purpose, mirroring `presets` — additive, non-breaking for
147
+ * library consumers. Malformed rows warn once and are skipped by the
148
+ * resolver; the gateway rejects them on save (Task 3).
149
+ */
150
+ timeSlots?: SlotRowConfig[];
151
+ /**
152
+ * Config-level timezone for slot matching (default `Asia/Shanghai`,
153
+ * UTC+8). Not per-slot.
154
+ */
155
+ tz?: string;
156
+ /**
157
+ * Cooldown-expiry recovery mode (plan fallbacks-half-open-recovery Task
158
+ * 1): `'timer'` restores the preferred candidate when the cooldown
159
+ * expires (today's behavior); `'half-open'` leaves the route half-open
160
+ * for one logged probe instead. Optional on purpose, mirroring
161
+ * `presets` — a required field would break library consumers that
162
+ * construct `FallbacksConfig` literals with the existing keys
163
+ * (additive, non-breaking). The value domain is guarded by the schema
164
+ * (`Config` in `src/schema.ts`), NOT by `validateFallbacksConfig`, and
165
+ * every resolved config carries a value via the schema default.
166
+ */
167
+ recovery?: RecoveryPolicy;
168
+ }
169
+ /**
170
+ * Spec §4 defaults — `Config({})` must equal this (no-op install).
171
+ * There is no `enabled` default (the key is removed — the Plugins-page row
172
+ * toggle is the master switch): an unconfigured install (empty rootChain,
173
+ * no time slots, empty roles) behaves exactly like an uninstalled plugin
174
+ * (AC-3 / no-op invariant, {@link isFallbackActive}).
175
+ */
176
+ export declare const defaultFallbacksConfig: FallbacksConfig;
177
+ /**
178
+ * Reserved role id: legal as a rule target (`roles.rules[].role`) and as
179
+ * the no-rule-match fallback, but FORBIDDEN in `roles.list[].id`.
180
+ */
181
+ export declare const INHERIT_ROLE_ID = "inherit";
182
+ /**
183
+ * The no-op gate (AC-8), re-keyed from the removed `enabled` switch to
184
+ * CONTENT PRESENCE (plan fallbacks-web-ux-alignment T2): the plugin
185
+ * intervenes exactly when something is configured — a non-empty `rootChain`
186
+ * (the all-day chain), at least one time-slot row, or at least one declared
187
+ * role. An inactive config is a pass-through exactly like an uninstalled
188
+ * plugin; the Plugins-page row toggle remains the master switch (row
189
+ * disable = fiber destroy). ONE helper for every runtime gate — the former
190
+ * `config.enabled` sites (request waterfalls, picker-row registration, TUI
191
+ * summary, General-row badge) all read through this.
192
+ */
193
+ export declare function isFallbackActive(config: FallbacksConfig): boolean;
194
+ /** Role id format (aligned with yet-another-subagent `isValidProfileId`). */
195
+ export declare const ROLE_ID_PATTERN: RegExp;
196
+ /** Provider prefix for fixed named-chain picker routes. */
197
+ export declare const NAMED_FALLBACK_PROVIDER_PREFIX = "FallbacksChain-";
198
+ /** The sole model id exposed by each fixed named-chain provider route. */
199
+ export declare const NAMED_FALLBACK_MODEL = "Chain";
200
+ /** Convert a validated named-chain id into its virtual provider route. */
201
+ export declare function namedFallbackProvider(id: string): string | undefined;
202
+ /** Recover a validated named-chain id from a virtual provider route. */
203
+ export declare function namedFallbackId(provider: string): string | undefined;
204
+ /** Find a named chain addressed by one of its virtual provider routes. */
205
+ export declare function namedFallbackChain(config: FallbacksConfig, provider: string): NamedFallbackChain | undefined;
206
+ /**
207
+ * Minimal logger surface {@link validateFallbacksConfig} warns through —
208
+ * keeps this module free of `@deepseek-ai/*` imports (a cordis Logger is
209
+ * structurally compatible).
210
+ */
211
+ export interface FallbacksConfigLogger {
212
+ warn(message: string): void;
213
+ }
214
+ /**
215
+ * Validate a fallbacks config (pure, warn-only — never throws, never
216
+ * mutates): role id format/uniqueness/reserved word, rule role references
217
+ * (declared ids + the built-in `'inherit'`), the `fallback` enum,
218
+ * `rootChain`/role-chain selector legality, and the role model-config
219
+ * requirement (a declared role with a missing/empty chain warns — a role
220
+ * without a model config is meaningless, plan fallbacks-feedback-round
221
+ * T2). `persona` is free text and is deliberately not
222
+ * validated. Each violation emits one `llm-router: ...` warn and "does
223
+ * not take effect" — the config stays usable (spec §4 / AC-4
224
+ * warn-not-crash semantics).
225
+ */
226
+ export declare function validateFallbacksConfig(config: FallbacksConfig, logger: FallbacksConfigLogger): void;
227
+ /**
228
+ * Detect legacy (two-block-era) leftovers in a config SOURCE — the composed
229
+ * object `source()` returns, or a raw settings document. Recognizes the
230
+ * removed `chains` key, the removed `roles.default` field, the removed
231
+ * role-entity fields `roles.list[].label` / `roles.list[].description`
232
+ * (renamed to `persona`), and `roles.rules[].role` values that reference no
233
+ * declared `roles.list` id and are not the built-in `'inherit'`. Returns
234
+ * descriptive key/role names; the gateway attaches them as `get().legacyKeys`
235
+ * so the client can show a migration banner (spec §9 — the source is read
236
+ * directly because schemastery retains unknown keys, verified plan Task 1
237
+ * Step 1).
238
+ */
239
+ export declare function detectLegacyKeys(source: Record<string, unknown>): string[];