dsh-router-core 0.3.11 → 0.3.13

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.
@@ -38,6 +38,15 @@ export declare class RouterAdapter extends LlmAdapter {
38
38
  name: string;
39
39
  };
40
40
  listModels(_provider: string): Promise<readonly LlmModelInfo[]>;
41
+ /**
42
+ * 只收文本。`resolveModel` 声明 `inputModalities: ['text']` 是**必须**的:
43
+ * 0.1.5 的 runtime 只在 `inputModalities` 存在且不含 `image` 时才把 image 块
44
+ * 投影成占位文本(见 dsh-llm adapterStream 的 projectImagesForTextModel)。
45
+ * 不声明 = "unknown" = 不投影,而 wireMessages 只读 text 块 → 图片**静默
46
+ * 丢失**,模型看到一条没有图片的用户消息却毫无提示。声明后由 runtime 统一
47
+ * 投影,我们仍只处理文本。
48
+ */
49
+ private static readonly INPUT_MODALITIES;
41
50
  resolveModel(_provider: string, model: string): Promise<LlmResolvedModelInfo>;
42
51
  stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
43
52
  }
@@ -31,6 +31,14 @@ export declare class AccountPool {
31
31
  /** uid → 连接级禁用 / 手动暂停。 */
32
32
  private byUid;
33
33
  private rrCursor;
34
+ /** (supplier, model) → 当前驻留的号(只有**无亲和**的回退路径用它)。 */
35
+ private blocks;
36
+ /** (supplier, model, uid) → 该号的缓存质量样本(降权判据,跨驻留累计)。 */
37
+ private samples;
38
+ /** (supplier, model, uid) → 缓存无效降权。 */
39
+ private demoted;
40
+ /** (supplier, model) → Map<前缀指纹, uid>:前缀亲和的选号记忆(LRU 封顶)。 */
41
+ private affinity;
34
42
  constructor(supplierId?: string);
35
43
  private key;
36
44
  private entry;
@@ -46,13 +54,61 @@ export declare class AccountPool {
46
54
  private healthy;
47
55
  /**
48
56
  * 按策略为「某个模型」选一个健康账号。
57
+ *
58
+ * round-robin = **前缀亲和定号 + 块统计只用来判定缓存无效**:
59
+ *
60
+ * 1. 算请求的前缀指纹(messages 前几条),查绑定表 → 命中且该号健康 → 用它。
61
+ * 这是第一优先:同一个会话的连续请求**永远落回同一个号**,前缀在该号的
62
+ * 缓存里只写一份。块轮询治不了跨会话驱逐(多会话大前缀在同一号互踩,
63
+ * 实测 3 会话 3.8% vs 单会话 82.5%),亲和才是根治。
64
+ * 2. 新指纹(或绑定的号不健康)→ 按游标挑一个号并**记下绑定**,之后就固定。
65
+ * 新会话用游标分发,所以不同会话天然散到不同号上(均衡)。
66
+ * 3. 块统计不再驱动轮转(亲和已经保证驻留,再轮转只会把会话踢出已热前缀),
67
+ * 只保留 `BLOCK_MAX` 次不达标 → 降权该号(缓存无效,可恢复)。
68
+ *
69
+ * 亲和失效(拿不到 messages / 指纹算不出)时**回退到块轮询**,行为与之前一致。
70
+ * 设计见 docs/pool-sticky-block.md §8。
71
+ *
49
72
  * @param accounts 插件报告的「现在状态」(顺序即插件的自然顺序)
50
73
  * @param poolOrder 用户在面板拖出来的顺序(核心管)
51
- * @param strategy fallback 取第一个健康 / round-robin 轮转健康号
74
+ * @param strategy fallback 取第一个健康 / round-robin 前缀亲和
52
75
  * @param modelId 当前要路由的模型(决定查哪个 (model, uid) 冷却单元)
76
+ * @param messages 请求体的 messages(可选;给了才能算前缀指纹)
53
77
  * @returns 选中的 uid;无健康账号返回 undefined
54
78
  */
55
- pick(accounts: SupplierAccountNow[], poolOrder: string[], strategy: string, modelId: string): string | undefined;
79
+ pick(accounts: SupplierAccountNow[], poolOrder: string[], strategy: string, modelId: string, messages?: unknown): string | undefined;
80
+ /** 记下「前缀指纹 → 号」的绑定(LRU:超上限丢最久未用的)。 */
81
+ private bind;
82
+ /** 该号在本模型上是否被判定「缓存无效」(降权中)。 */
83
+ private isDemoted;
84
+ /**
85
+ * 驻留是否还应留在当前号上(**只用于无亲和的回退路径**)。
86
+ *
87
+ * OR 语义(用户拍板):`留守 = 计数 < N OR 命中率 < M`。
88
+ * 单一账号内部:一个号先被轮到(冷启动/热),然后
89
+ * - 命中率**爬上去**(>= M,缓存热了)→ 让位,轮到下一个号(均衡)
90
+ * - 命中率**没上去**(冷启动/短块)→ 留守,继续热(不急着跳)
91
+ * - 轮次**实在太多**(计数 >= N_max)→ 也换(防死守 + 保均衡下限)
92
+ *
93
+ * 关键:命中率是**留守**条件不是切号执行器(反接会正反馈死锁,
94
+ * 见文档 §3)。换号由「命中达标 OR 份额用够」触发,都不是「命中率低」。
95
+ */
96
+ private blockKeeps;
97
+ /**
98
+ * 记录一次成功请求的缓存命中情况(降权判据的反馈信号)。
99
+ *
100
+ * 只有**成功**请求才计入:失败没产生缓存,计入会污染命中率并导致错降权。
101
+ * 统计按 (model, uid) 记,**不管这个号是不是「当前驻留」**——亲和开启后
102
+ * 多个会话各绑各的号交错服务,按驻留记会漏掉大部分真实反馈。
103
+ * @param uid 实际服务的号
104
+ * @param modelId 模型(块粒度)
105
+ * @param cachedTokens 上游报的命中 token 数;0 = 全量重算
106
+ */
107
+ noteCache(uid: string, modelId: string, cachedTokens: number): void;
108
+ /** 故障切走时作废当前驻留:换号后前缀归属变了,驻留计数不能沿用。 */
109
+ dropBlock(modelId: string): void;
110
+ /** 块状态键:与冷却同粒度 (supplier, model),不含 uid。 */
111
+ private blockKey;
56
112
  /** 记录一次失败:按状态处置(冷却/禁用/退避),落在「(模型, 连接)」这个冷却单元上。 */
57
113
  noteFailure(uid: string, modelId: string, state: AccountState, message: string): void;
58
114
  /** 记录一次成功:清零「该模型」的限流退避等级(好号不背历史惩罚)。不解除禁用。 */
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 算请求的前缀指纹。
3
+ * @param messages OpenAI 请求体的 `messages` 字段(未校验,来自外部输入)
4
+ * @returns 指纹字符串;**空串 = 算不出来(无亲和,回退到块轮询)**
5
+ */
6
+ export declare function prefixFingerprint(messages: unknown): string;
@@ -15,6 +15,14 @@ export interface UsageRecord {
15
15
  durationMs: number;
16
16
  /** 首字节延迟(ms);非流式为 0。 */
17
17
  ttfbMs: number;
18
+ /**
19
+ * 实际服务的账号 uid(成功时回填)。
20
+ *
21
+ * 有了它才能把命中率按**号**下钻——prompt cache 是 per-account 命名空间,
22
+ * 只看供应商/模型无法判断「是某个号的缓存没热,还是策略在乱切号」。
23
+ * 块轮询(docs/pool-sticky-block.md)的调参完全依赖这个归因。
24
+ */
25
+ uid?: string;
18
26
  /** 失败原因(ok=false 时)。 */
19
27
  error?: string;
20
28
  }
@@ -132,6 +132,24 @@ export interface RouterSettingsResponse {
132
132
  error?: string;
133
133
  requireApiKey?: boolean;
134
134
  }
135
+ /** 一条扩展器(`/router/api/ext`)。 */
136
+ export interface RouterExtItem {
137
+ id: string;
138
+ name: string;
139
+ description?: string;
140
+ /** 是否启用改写(面板开关)。 */
141
+ enabled?: boolean;
142
+ /** 运行时是否就绪(如 RTK 二进制是否可用)。 */
143
+ ready?: boolean;
144
+ /** 一句话状态说明(如「本机未装 rtk」)。 */
145
+ detail?: string;
146
+ }
147
+ /** `/router/api/ext` response(扩展插件列表 + 开关)。 */
148
+ export interface RouterExtResponse {
149
+ ok: boolean;
150
+ error?: string;
151
+ enhancers?: RouterExtItem[];
152
+ }
135
153
  /** 供应商模型(含启用状态)。 */
136
154
  export interface RouterSupplierModel {
137
155
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-router-core",
3
- "version": "0.3.11",
3
+ "version": "0.3.13",
4
4
  "description": "DSH plugin: a simplified 9router (AI routing gateway). Adds a 路由系统 (Routing System) sidebar entry beside 记忆系统; the panel shows suppliers, account pool, combos, and endpoint/API keys.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -66,9 +66,9 @@
66
66
  "license": "MIT",
67
67
  "peerDependencies": {
68
68
  "@deepseek-ai/cordis": "^4.0.2",
69
- "@deepseek-ai/dsh-client-locale": "^0.1.2-rc.1",
70
- "@deepseek-ai/dsh-client-ui-slots": "^0.1.2-rc.1",
71
- "@deepseek-ai/dsh-llm": "^0.1.2-rc.1",
69
+ "@deepseek-ai/dsh-client-locale": "^0.1.5-rc.1",
70
+ "@deepseek-ai/dsh-client-ui-slots": "^0.1.5-rc.1",
71
+ "@deepseek-ai/dsh-llm": "^0.1.5-rc.1",
72
72
  "cordis": "^4.0.0-rc.7",
73
73
  "react": "^18.2.0",
74
74
  "react-dom": "^18.2.0"
@@ -85,7 +85,7 @@
85
85
  }
86
86
  },
87
87
  "devDependencies": {
88
- "@deepseek-ai/dsh-llm": "0.1.2-rc.1",
88
+ "@deepseek-ai/dsh-llm": "0.1.5-rc.1",
89
89
  "@types/node": "^26.4.1",
90
90
  "@types/react": "~19.2.18",
91
91
  "@types/react-dom": "~19.2.7",
@@ -0,0 +1,143 @@
1
+ /**
2
+ * 扩展 (Ext) 页 —— 列出所有注册进 `router.ext` 的扩展插件,每个一个开关。
3
+ *
4
+ * 数据来自 `/router/api/ext`:核心把自己存的开关(`ext.json`)+ 扩展器报的
5
+ * 运行时事实(`ready` / `detail`)合并后给面板。扩展器只实现具体能力(如 RTK),
6
+ * 开关与渲染都在核心。
7
+ *
8
+ * 布局贴近 EndpointTab 的「Require API key」开关行:每个扩展器一张卡片。
9
+ * 未装任何扩展 → 空状态提示。
10
+ */
11
+ import { useEffect, useRef, useState } from 'react'
12
+ import { ROUTER_API_BASE, type RouterExtItem, type RouterExtResponse } from '../shared.ts'
13
+
14
+ function Icon({ d, size = 18 }: { d: string; size?: number }): JSX.Element {
15
+ return (
16
+ <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
17
+ <path d={d} />
18
+ </svg>
19
+ )
20
+ }
21
+
22
+ const I = {
23
+ bolt: 'M13 2L4 14h6l-1 8 9-12h-6l1-8z',
24
+ puzzle: 'M4 7h3a2 2 0 0 1 4 0h5a1 1 0 0 1 1 1v4a2 2 0 0 0 0 4v4H8v-3a2 2 0 0 1 0-4H4V7z',
25
+ }
26
+
27
+ export function ExtTab(): JSX.Element {
28
+ const [items, setItems] = useState<RouterExtItem[]>([])
29
+ const [loaded, setLoaded] = useState(false)
30
+ const [error, setError] = useState('')
31
+ const mounted = useRef(true)
32
+
33
+ useEffect(() => {
34
+ mounted.current = true
35
+ void load()
36
+ return () => { mounted.current = false }
37
+ }, [])
38
+
39
+ const load = async (): Promise<void> => {
40
+ try {
41
+ const response = await fetch(`${ROUTER_API_BASE}/ext`, { cache: 'no-store' })
42
+ const data = await response.json() as RouterExtResponse
43
+ if (mounted.current) {
44
+ setError(data.ok ? '' : (data.error ?? '加载扩展失败'))
45
+ setItems(data.enhancers ?? [])
46
+ setLoaded(true)
47
+ }
48
+ } catch (err) {
49
+ if (mounted.current) {
50
+ setError((err as Error).message)
51
+ setLoaded(true)
52
+ }
53
+ }
54
+ }
55
+
56
+ const toggle = async (item: RouterExtItem, value: boolean): Promise<void> => {
57
+ // 乐观更新
58
+ setItems(prev => prev.map(i => i.id === item.id ? { ...i, enabled: value } : i))
59
+ setError('')
60
+ try {
61
+ const response = await fetch(`${ROUTER_API_BASE}/ext`, {
62
+ method: 'PATCH',
63
+ headers: { 'Content-Type': 'application/json' },
64
+ body: JSON.stringify({ id: item.id, enabled: value }),
65
+ cache: 'no-store',
66
+ })
67
+ const data = await response.json() as RouterExtResponse
68
+ if (mounted.current && data.enhancers) {
69
+ setItems(data.enhancers)
70
+ } else if (mounted.current && !data.ok) {
71
+ setError(data.error ?? '切换失败')
72
+ setItems(prev => prev.map(i => i.id === item.id ? { ...i, enabled: !value } : i))
73
+ }
74
+ } catch (err) {
75
+ if (mounted.current) {
76
+ setError((err as Error).message)
77
+ setItems(prev => prev.map(i => i.id === item.id ? { ...i, enabled: !value } : i))
78
+ }
79
+ }
80
+ }
81
+
82
+ return (
83
+ <div className="dshr-tabBody">
84
+ {error !== '' && (
85
+ <div className="dshr-alert"><strong>出错了</strong><span>{error}</span></div>
86
+ )}
87
+
88
+ {!loaded ? (
89
+ <div className="dshr-empty">加载中…</div>
90
+ ) : items.length === 0 ? (
91
+ <div className="dshr-keyEmpty">
92
+ <span className="dshr-keyEmptyIcon"><Icon d={I.puzzle} size={30} /></span>
93
+ <p className="dshr-keyEmptyTitle">暂无扩展</p>
94
+ <p className="dshr-keyEmptyDesc">
95
+ 安装扩展插件(如 <code>dsh-router-ext-rtk</code>)后,这里会出现开关
96
+ </p>
97
+ </div>
98
+ ) : (
99
+ items.map(item => {
100
+ const notReady = item.ready === false
101
+ return (
102
+ <section key={item.id} className="dshr-card">
103
+ <div className="dshr-cardHead">
104
+ <span className="dshr-cardIcon"><Icon d={I.bolt} /></span>
105
+ <div className="dshr-cardTitle">{item.name}</div>
106
+ {/* 开关放标题行最右端:.dshr-cardAction 是现成的
107
+ margin-left:auto(EndpointTab 的「创建 Key」就靠它),复用不新增。
108
+ 不可用时禁开——禁了就无从开启成功。 */}
109
+ <button
110
+ type="button"
111
+ className={`dshr-toggle dshr-cardAction ${item.enabled ? 'dshr-toggle-on' : ''}`}
112
+ role="switch"
113
+ aria-checked={!!item.enabled}
114
+ disabled={notReady && !item.enabled}
115
+ onClick={() => void toggle(item, !item.enabled)}
116
+ title={notReady && !item.enabled
117
+ ? '当前不可用,无法开启'
118
+ : item.enabled ? `关闭 ${item.name}` : `开启 ${item.name}`}
119
+ >
120
+ <span className="dshr-toggleKnob" />
121
+ </button>
122
+ </div>
123
+
124
+ {/* 内容区:说明 + 未就绪红字(左对齐、与卡片图标对齐) */}
125
+ <div className="dshr-extBody">
126
+ {item.description !== undefined && item.description !== '' && (
127
+ <div className="dshr-muted">{item.description}</div>
128
+ )}
129
+ {notReady && (
130
+ <div className="dshr-ext-error">
131
+ {item.detail !== undefined && item.detail !== ''
132
+ ? item.detail
133
+ : '未就绪,无法开启'}
134
+ </div>
135
+ )}
136
+ </div>
137
+ </section>
138
+ )
139
+ })
140
+ )}
141
+ </div>
142
+ )
143
+ }
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * 路由系统 (Routing System) panel — a simplified 9router.
3
3
  *
4
- * Four tabs fed by the host half (/router/api/*), mirroring 9router's
4
+ * Five tabs fed by the host half (/router/api/*), mirroring 9router's
5
5
  * dashboard: 概览 (usage), 供应商 (supplier cards → detail: accounts +
6
6
  * add-account + models), 组合 (combo fallback chains),
7
+ * 扩展 (extension plugins — one toggle each, self-checked),
7
8
  * 端点与密钥 (endpoint URL + API keys + auth).
8
9
  *
9
10
  * **挂载在「设置」里**(`settings.section` 座位),所以布局规则跟中心栏劫持时期不同:
@@ -27,8 +28,9 @@ import { SupplierDetail } from './SupplierDetail.tsx'
27
28
  import { EndpointTab } from './EndpointTab.tsx'
28
29
  import { CombosTab } from './CombosTab.tsx'
29
30
  import { StatsTab } from './StatsTab.tsx'
31
+ import { ExtTab } from './ExtTab.tsx'
30
32
 
31
- type TabId = 'overview' | 'suppliers' | 'combos' | 'endpoint'
33
+ type TabId = 'overview' | 'suppliers' | 'combos' | 'endpoint' | 'ext'
32
34
 
33
35
  interface Snapshot {
34
36
  health: RouterHealthResponse | null
@@ -142,6 +144,9 @@ export function RouterView({ onBack }: RouterViewProps): JSX.Element {
142
144
  <button type="button" role="tab" aria-selected={tab === 'combos'} className={`dshr-tab${tab === 'combos' ? ' dshr-tab-on' : ''}`} onClick={() => setTab('combos')}>
143
145
  组合 <span className="dshr-navCount">{combos.length}</span>
144
146
  </button>
147
+ <button type="button" role="tab" aria-selected={tab === 'ext'} className={`dshr-tab${tab === 'ext' ? ' dshr-tab-on' : ''}`} onClick={() => setTab('ext')}>
148
+ 扩展
149
+ </button>
145
150
  <button type="button" role="tab" aria-selected={tab === 'endpoint'} className={`dshr-tab${tab === 'endpoint' ? ' dshr-tab-on' : ''}`} onClick={() => setTab('endpoint')}>
146
151
  端点与密钥
147
152
  </button>
@@ -205,6 +210,9 @@ export function RouterView({ onBack }: RouterViewProps): JSX.Element {
205
210
 
206
211
  {/* ---------------- 端点与密钥 ---------------- */}
207
212
  {tab === 'endpoint' && <EndpointTab />}
213
+
214
+ {/* ---------------- 增强 (扩展插件) ---------------- */}
215
+ {tab === 'ext' && <ExtTab />}
208
216
  </div>
209
217
  </div>
210
218
  )
@@ -908,7 +908,7 @@ export function SupplierDetail({ supplier, accounts, statusLoading, onBack, onRe
908
908
  </>
909
909
  <>
910
910
  <label className="dshr-fieldLabel">连接池策略</label>
911
- <p className="dshr-muted">回退 = 按连接池顺序取第一个健康链接;轮询 = 轮流使用健康链接。</p>
911
+ <p className="dshr-muted">回退 = 按连接池顺序取第一个健康链接;轮询 = 按会话前缀粘住同一链接(前缀亲和,多会话不打架),拿不到会话信息时退回块轮转。</p>
912
912
  <select
913
913
  className="dshr-select dshr-input"
914
914
  value={poolStrategy}
@@ -910,6 +910,25 @@ html[data-dsh-router-active]:not([data-dsh-taskboard-active]):not([data-dsh-ssh-
910
910
 
911
911
  .dshr-toggle-on .dshr-toggleKnob { transform: translateX(14px); }
912
912
 
913
+ /* 开关禁用态:不可用(未就绪)且未开启时,灰显 + 不可点 */
914
+ .dshr-toggle:disabled {
915
+ cursor: default;
916
+ opacity: .45;
917
+ }
918
+
919
+ /* 扩展页:未就绪问题描述(红字) */
920
+ .dshr-ext-error {
921
+ color: var(--rs-danger);
922
+ font-size: 11px;
923
+ margin-top: 4px;
924
+ }
925
+
926
+ /* 扩展卡片内容区:文字左对齐,左侧留白与标题行的图标位对齐 */
927
+ .dshr-extBody {
928
+ padding: 10px 14px 12px 48px;
929
+ text-align: left;
930
+ }
931
+
913
932
  /* 操作按钮组 */
914
933
  .dshr-ops {
915
934
  display: flex;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * 扩展 (Ext) 通用契约 —— dsh-router 的「扩展插件」扩展点(不是供应商)。
3
+ *
4
+ * 分工(2026-09 重构:核心只做管理,不做拦截):
5
+ * - **dsh-router 核心 = 管理面**:持有 `router.ext` 注册表(发现)、渲染面板与
6
+ * `/router/api/ext`(展示)、代存开关与插件数据(`router.extStore` →
7
+ * `<dataDir>/ext.json`)。核心**不挂 `tools/execute`、不裁决、不改写**。
8
+ * - **扩展插件 = 执行面**:自己挂监听、自己问 `isEnabled`、自己按 ready 裁决、
9
+ * 自己短路执行。怎么改一条命令是插件的**私事**,不在本契约里。
10
+ *
11
+ * 为什么把拦截从核心挪走:
12
+ * `tools/execute` 是任何插件都能自己挂的 around-dispatch waterfall(插件 ctx 不在
13
+ * agent scope 下就能收到全部派发)。核心代挂只在一个消费者(rtk)时是纯亏损:为留
14
+ * 40 行委派逻辑,付了共享表 + inject 广播 + 契约两处同步的代价。核心归位成管理面
15
+ * 后,扩展插件与 dsh-router 只在**注册表 + 存储**两处耦合。
16
+ *
17
+ * ponytail: 天花板 —— 核心代挂原本顺带解决「多个扩展插件各自挂监听会互相踩 / 顺序
18
+ * 不可控」。这个保护现在没了;目前只有 rtk 一家消费,无所谓。**第二家 ext 出现时
19
+ * 要重新收敛顺序**(升级路径:核心暴露一个按顺序委派的共享工具方法,而不是收回拦截)。
20
+ *
21
+ * 契约要点:
22
+ * - 扩展器只有**声明**(id / name / description)+ `getState()`;核心拿这些渲染面板。
23
+ * - `getState()` 只报**运行时事实**(ready 是否可用、detail 说明),不报开关。
24
+ * - **开关与数据归核心持久化**(`router.extStore` → `<dataDir>/ext.json`),插件不自己
25
+ * file IO —— 落盘位置由核心锚定(不跟 cwd 跑),读写经核心,插件无状态。
26
+ */
27
+ import type { Context } from '@deepseek-ai/cordis'
28
+
29
+ /** 扩展器唯一 id(注册键)。 */
30
+ export type ExtId = string
31
+
32
+ /**
33
+ * 扩展器当前状态(**运行时事实**,由插件现算,不持久化)。
34
+ *
35
+ * 注意:`enabled` 不在这里 —— 开关状态归核心持久化(`<dataDir>/ext.json`),
36
+ * 插件只负责做事 + 报自己是否可用。核心把两者合并后再给面板用。
37
+ */
38
+ export interface ExtState {
39
+ /** 运行时是否就绪(如 RTK 二进制是否可用);false 时即使开启也不生效。 */
40
+ ready: boolean
41
+ /** 不就绪时的一句话说明(如「本机未装 rtk」),面板红字显示。 */
42
+ detail?: string
43
+ }
44
+
45
+ /**
46
+ * 注册到 `router.ext` 表的扩展器实现。核心(面板/API)只认这几个成员,
47
+ * 插件可以携带更多内部状态。
48
+ */
49
+ export interface RouterExt {
50
+ /** 扩展器 id,也是 `router.ext` 表里的注册键。 */
51
+ readonly id: ExtId
52
+ /** 面板显示名(如「RTK」)。 */
53
+ readonly name: string
54
+ /** 面板副标题说明。 */
55
+ readonly description?: string
56
+ /** 当前运行时状态(ready + 不就绪时的说明)。 */
57
+ getState(): ExtState
58
+ /** 卸载清理(表删除时由 dsh-router 调用,可选)。 */
59
+ dispose?(): void
60
+ }
61
+
62
+ /** 面板/API 用的一条扩展器信息 = 核心存的开关 + 插件报的运行时事实。 */
63
+ export interface ExtInfo {
64
+ id: string
65
+ name: string
66
+ description?: string
67
+ /** 核心持久化的开关(默认关)。 */
68
+ enabled: boolean
69
+ /** 插件报的运行时就绪状态。 */
70
+ ready: boolean
71
+ /** 不就绪时的说明(面板红字)。 */
72
+ detail?: string
73
+ }
74
+
75
+ /** `router.ext` 共享聚合表:`{ [extId]: RouterExt }`(同一 live 对象可追加)。 */
76
+ export interface RouterExtService {
77
+ [extId: string]: RouterExt
78
+ }
79
+
80
+ /**
81
+ * 扩展的存储面(核心 provide,插件 inject)。
82
+ *
83
+ * 插件**不自己 file IO**:落盘位置由核心用 `dataDirOf(ctx.baseUrl)` 锚定(不跟
84
+ * process.cwd() 跑),读写都经核心,同一文件、同一次原子写。
85
+ *
86
+ * 落盘形状:`<dataDir>/ext.json` = `{ "<id>": { "enabled": boolean, "data": unknown } }`
87
+ */
88
+ export interface ExtStoreService {
89
+ /** 是否开启(未记录过 = 默认关)。 */
90
+ isEnabled(id: string): boolean
91
+ /** 置开关(面板/API 调)。 */
92
+ setEnabled(id: string, enabled: boolean): void
93
+ /** 读插件自己的数据块(没有 = undefined)。 */
94
+ readData<T = unknown>(id: string): T | undefined
95
+ /** 写插件自己的数据块(覆盖;与 enabled 同文件原子落盘)。 */
96
+ writeData(id: string, value: unknown): void
97
+ }
98
+
99
+ /** 读取当前 router.ext 表(同一 live 对象,可追加)——扩展插件用它注册自己。 */
100
+ export function currentExts(ctx: Context): RouterExtService | undefined {
101
+ const c = ctx as unknown as {
102
+ get?: (key: string) => unknown
103
+ router?: { ext?: RouterExtService }
104
+ }
105
+ return (c.get?.('router.ext') ?? c.router?.ext) as RouterExtService | undefined
106
+ }
107
+
108
+ /** 读取扩展存储服务——扩展插件用它读开关、读写自己存的数据。 */
109
+ export function currentExtStore(ctx: Context): ExtStoreService | undefined {
110
+ const c = ctx as unknown as {
111
+ get?: (key: string) => unknown
112
+ router?: { extStore?: ExtStoreService }
113
+ }
114
+ return (c.get?.('router.extStore') ?? c.router?.extStore) as ExtStoreService | undefined
115
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * 扩展开关存储测试 —— 开关状态归核心持久化(`<dataDir>/ext.json`)。
3
+ *
4
+ * 锁定的契约:
5
+ * - 默认关(没记录过 = 关)
6
+ * - 开启 → 落盘,新实例(模拟重启)读到
7
+ * - 按 id 隔离,互不影响
8
+ * - 坏数据读盘不炸
9
+ * - 重复设同值不写盘
10
+ */
11
+ import test from 'node:test'
12
+ import assert from 'node:assert/strict'
13
+ import { mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
14
+ import { tmpdir } from 'node:os'
15
+ import { join } from 'node:path'
16
+ import { ExtStore } from './store.ts'
17
+
18
+ /** 每个用例一个独立数据目录(stateFile 推导出 ext.json)。 */
19
+ function tempStore(preload?: unknown): { store: ExtStore; file: string } {
20
+ const dir = mkdtempSync(join(tmpdir(), 'dshr-ext-'))
21
+ const stateFile = join(dir, 'state.json')
22
+ if (preload !== undefined) writeFileSync(join(dir, 'ext.json'), JSON.stringify(preload))
23
+ return { store: new ExtStore(stateFile), file: join(dir, 'ext.json') }
24
+ }
25
+
26
+ test('默认关', () => {
27
+ const { store } = tempStore()
28
+ assert.equal(store.isEnabled('rtk'), false)
29
+ })
30
+
31
+ test('开启 → 落盘,重开还在', () => {
32
+ const { store, file } = tempStore()
33
+ store.setEnabled('rtk', true)
34
+ const raw = JSON.parse(readFileSync(file, 'utf8')) as { rtk?: { enabled: boolean } }
35
+ assert.equal(raw.rtk?.enabled, true)
36
+ // 新实例 = 模拟重启
37
+ assert.equal(new ExtStore(join(file, '..', 'state.json')).isEnabled('rtk'), true)
38
+ })
39
+
40
+ test('关回去 → 落盘 false', () => {
41
+ const { store, file } = tempStore()
42
+ store.setEnabled('rtk', true)
43
+ store.setEnabled('rtk', false)
44
+ assert.equal(new ExtStore(join(file, '..', 'state.json')).isEnabled('rtk'), false)
45
+ })
46
+
47
+ test('按 id 隔离,互不影响', () => {
48
+ const { store } = tempStore()
49
+ store.setEnabled('rtk', true)
50
+ assert.equal(store.isEnabled('rtk'), true)
51
+ assert.equal(store.isEnabled('other'), false)
52
+ })
53
+
54
+ test('坏数据读盘不炸,当没配置过', () => {
55
+ const { store: s1 } = tempStore({ rtk: { enabled: 'yes' } })
56
+ assert.equal(s1.isEnabled('rtk'), false)
57
+ const { store: s2 } = tempStore({ rtk: null })
58
+ assert.equal(s2.isEnabled('rtk'), false)
59
+ const { store: s3 } = tempStore([])
60
+ assert.equal(s3.isEnabled('rtk'), false)
61
+ })
62
+
63
+ /** 造一个带旧 enhance.json 的目录(模拟升级前的状态)。 */
64
+ function legacyStore(enabled: boolean): { store: ExtStore; file: string } {
65
+ const dir = mkdtempSync(join(tmpdir(), 'dshr-ext-legacy-'))
66
+ writeFileSync(join(dir, 'enhance.json'), JSON.stringify({ enabled }))
67
+ const stateFile = join(dir, 'state.json')
68
+ return { store: new ExtStore(stateFile), file: join(dir, 'ext.json') }
69
+ }
70
+
71
+ test('迁移:旧 enhance.json 开着 → 新 ext.json 里 rtk 开', () => {
72
+ const { store, file } = legacyStore(true)
73
+ assert.equal(store.isEnabled('rtk'), true)
74
+ const raw = JSON.parse(readFileSync(file, 'utf8')) as { rtk?: { enabled: boolean } }
75
+ assert.equal(raw.rtk?.enabled, true)
76
+ })
77
+
78
+ test('迁移:旧文件关着 → 不迁移(保持默认关)', () => {
79
+ const { store, file } = legacyStore(false)
80
+ assert.equal(store.isEnabled('rtk'), false)
81
+ assert.equal(existsSync(file), false)
82
+ })
83
+
84
+ test('迁移:已有新配置时不覆盖', () => {
85
+ const { store: s1, file } = tempStore()
86
+ s1.setEnabled('rtk', false)
87
+ // 往同目录塞一个「开着」的旧文件,不应覆盖已经明确存过的新配置
88
+ writeFileSync(join(file, '..', 'enhance.json'), JSON.stringify({ enabled: true }))
89
+ const s2 = new ExtStore(join(file, '..', 'state.json'))
90
+ assert.equal(s2.isEnabled('rtk'), false)
91
+ })
92
+
93
+ test('空 id 不落盘(连文件都不建)', () => {
94
+ const { store, file } = tempStore()
95
+ store.setEnabled('', true)
96
+ assert.equal(store.isEnabled(''), false)
97
+ assert.equal(existsSync(file), false, '空 id 应直接拒绝,不创建文件')
98
+ })
99
+
100
+ // ---- data 槽:给插件的通用抽屉(2026-09 加) ----
101
+
102
+ test('data:没存过 → undefined;写后能读回', () => {
103
+ const { store } = tempStore()
104
+ assert.equal(store.readData('rtk'), undefined)
105
+ store.writeData('rtk', { hits: 3 })
106
+ assert.deepEqual(store.readData('rtk'), { hits: 3 })
107
+ })
108
+
109
+ test('data:落盘 + 重启还在(与 enabled 同一文件)', () => {
110
+ const { store, file } = tempStore()
111
+ store.setEnabled('rtk', true)
112
+ store.writeData('rtk', { hits: 3 })
113
+ const raw = JSON.parse(readFileSync(file, 'utf8')) as { rtk?: { enabled: boolean; data?: { hits: number } } }
114
+ assert.equal(raw.rtk?.enabled, true)
115
+ assert.deepEqual(raw.rtk?.data, { hits: 3 })
116
+ const revived = new ExtStore(join(file, '..', 'state.json'))
117
+ assert.equal(revived.isEnabled('rtk'), true)
118
+ assert.deepEqual(revived.readData('rtk'), { hits: 3 })
119
+ })
120
+
121
+ test('data:写 data 不冲掉 enabled,置 enabled 不冲掉 data', () => {
122
+ const { store, file } = tempStore()
123
+ store.setEnabled('rtk', true)
124
+ store.writeData('rtk', { hits: 1 })
125
+ assert.equal(store.isEnabled('rtk'), true, '写 data 不能把开关冲掉')
126
+ store.setEnabled('rtk', false)
127
+ assert.deepEqual(store.readData('rtk'), { hits: 1 }, '置开关不能把 data 冲掉')
128
+ const revived = new ExtStore(join(file, '..', 'state.json'))
129
+ assert.equal(revived.isEnabled('rtk'), false)
130
+ assert.deepEqual(revived.readData('rtk'), { hits: 1 })
131
+ })
132
+
133
+ test('data:按 id 隔离', () => {
134
+ const { store } = tempStore()
135
+ store.writeData('rtk', { hits: 1 })
136
+ assert.deepEqual(store.readData('other'), undefined)
137
+ })
138
+
139
+ test('data:空 id 不落盘', () => {
140
+ const { store, file } = tempStore()
141
+ store.writeData('', { x: 1 })
142
+ assert.equal(store.readData(''), undefined)
143
+ assert.equal(existsSync(file), false)
144
+ })