@lynn123411/dsh-llm-agentrouter 0.2.3 → 0.3.1

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
@@ -1,14 +1,15 @@
1
1
  # @lynn123411/dsh-llm-agentrouter
2
2
 
3
- AgentRouter 中转聚合插件:把同一家中转的多个模型收拢为一条 pi-ai 路由(模型选择器只出现一个 AgentRouter 分组),国内 / 国际端点在「设置 - API中转 - AgentRouter 中转站」一键切换、下一请求即生效,外加出站请求的 User-Agent 改写与 402 配额耗尽提示围栏。分叉自 `aqiu817/dsh-llm-agentrouter`,适配 DSH `0.1.2-alpha.5` 起的新 settings/slots API,已在 `0.1.5-rc.1` 逐项实证兼容。
3
+ AgentRouter 中转聚合插件:把同一家中转的多个模型收拢为一条 pi-ai 路由(模型选择器只出现一个 AgentRouter 分组),国内 / 国际端点在「设置 - API中转 - AgentRouter 中转站」一键切换、下一请求即生效,外加出站请求的 User-Agent 改写与 402 配额耗尽提示围栏。模型列表在卡片内直接编辑,写入内核「设置 - 模型」页所编辑的同一份 `llm-pi-ai` 路由数据。
4
4
 
5
5
  ## 特性
6
6
 
7
7
  - **单路由多模型**:Claude Opus 5、GPT-5.6-sol 等走同一 `agentrouter` 路由,`reasoningEffort` 档位与兼容开关按实测探针手写声明,模型列表不翻倍。
8
+ - **模型列表可编辑**:设置卡片里直接列出这条路由的模型,`更新` 向中转站询问它现有的模型 ID(只补缺失的、不动已有条目),每个模型的 ID / 显示名 / 上下文窗口 / 最大输出 / 输入模态 / 各推理档位与线上取值都可改,保存后下一个请求即生效;新补入的模型默认 1048576 上下文、131072 输出、text+image、off..max 七档。改的就是路由自己的 `models`(与内核「设置 - 模型」页同一份数据),patch 里手写的那几条是「重置」的基线。
8
9
  - **端点一键切换**:设置卡片两个大选项(国内端点 / 国际端点,附带真实 host 展示),点击即写即生效,无需重启;API Key 只存 `$DSH_HOME/.credentials.yaml` 的 `AGENTROUTER_API_KEY` 引用。
9
10
  - **共享「API中转」设置页**:本插件的端点卡片与 `dsh-a6api` 的面板挂在同一个设置页里(`settings.section` id `relay` 的页内两个 tab,参与者可增删)。内核不允许一页被多个插件共同声明,因此每个参与者各持一份运行时逻辑一致的页壳,**先加载者当选页面宿主**、其余只注册卡片;当选者被卸载后下次启动自动改选。做法与约束见仓库 `docs/rules/shared-settings-page.md`。
10
11
  - **请求围栏**:重写 relay 要求的 `User-Agent`(适配器强制署名下沉到 `fetch` 层替换),哨兵 host(`.internal` 不可解析)兜底防裸奔,402 配额耗尽的 JSON 错误体改写为可读提示。
11
- - **alpha.5 兼容**:宿主沿用 `ctx.settings.installSection` + `ctx.inject(['settings'])`,客户端卡片改挂共享设置页的子 slot;沿用 `llm-agentrouter` 设置命名空间,老配置无缝继承。
12
+ - **内核设置接入**:宿主用 `ctx.settings.installSection` 注册设置段(`ctx.inject(['settings'])`),客户端卡片挂在共享设置页的子 slot;设置命名空间为 `llm-agentrouter`。
12
13
 
13
14
  ## 安装
14
15
 
package/cordis.patch.yml CHANGED
@@ -5,7 +5,7 @@
5
5
  # row below overrides the dormant zero-route entry dsh-base mounts.
6
6
  #
7
7
  # WHY ONE ROUTE AND NOT TWO
8
- # The relay serves the same three models at a domestic and an international
8
+ # The relay serves the same models at a domestic and an international
9
9
  # endpoint; only the origin differs. Declaring a route per endpoint put every
10
10
  # model in the picker twice and made "which endpoint" a choice the user had to
11
11
  # re-make on every model switch. It is not a model property — it is one
@@ -30,16 +30,26 @@
30
30
  # both endpoints because it is one relay account.
31
31
  #
32
32
  # MODEL CATALOG
33
- # pi-ai's installed catalog describes all three models, but under their vendor
33
+ # This list is the COMPOSITION layer: what the route serves until the user layer
34
+ # overrides it. The plugin's settings card (设置 → API中转 → AgentRouter 中转站)
35
+ # edits the route's own `models` — the same document the kernel's Models page
36
+ # writes — and its 重置 action removes that override, which is when the list
37
+ # below serves again. Treat these entries as the reset baseline and the probe
38
+ # record, not as the only way to add a model.
39
+ #
40
+ # pi-ai's installed catalog describes these models, but under their vendor
34
41
  # providers (`anthropic`, `openai`) and other protocols — Opus via
35
42
  # anthropic-messages, gpt-5.6-sol via openai-responses. A hand-declared route
36
43
  # inherits nothing, so capacities, reasoning levels, and compat switches are
37
44
  # restated here from that catalog, adjusted for Chat Completions.
38
45
  #
39
46
  # `reasoningEfforts` keys are the levels the picker offers; each value is the
40
- # wire spelling sent as `reasoning_effort`. All three models were probed against
41
- # the live relay: every level below answered 200. `off:` (declared, no value)
42
- # offers Off and sends nothing, which is what an OpenAI-shaped endpoint wants.
47
+ # wire spelling sent as `reasoning_effort`. Every model below was probed against
48
+ # the live relay: every level it declares answered 200. `off:` (declared, no
49
+ # value) offers Off and sends nothing, which is what an OpenAI-shaped endpoint
50
+ # wants. A model the card discovers starts instead from generic defaults — see
51
+ # `NEW_MODEL` in lib/client.js — so these hand-probed declarations stay the more
52
+ # accurate ones for a model that is already listed.
43
53
  # WHY THE PICKER SAYS NOTHING ABOUT THE ENDPOINT
44
54
  # The model picker renders no child slots, so a plugin cannot inject anything
45
55
  # into that menu; per group it shows only `displayName`, and per model only the
@@ -50,11 +60,11 @@
50
60
  #
51
61
  # WHOLE-OBJECT OVERWRITE, NOT A DEEP MERGE — RE-CHECK ON EVERY dsh-base BUMP
52
62
  # The loader applies a patch entry as `target[key] = value`
53
- # (applyEntryPatches, 0.1.5-rc.1), so the `config:` below REPLACES the
63
+ # (applyEntryPatches, 0.1.6-alpha.2), so the `config:` below REPLACES the
54
64
  # llm-pi-ai row's whole config object: nothing a default config carried survives,
55
65
  # at any depth. That is safe today only because dsh-base mounts
56
66
  # `- id: llm-pi-ai` with a `name:` and no `config:` at all
57
- # (dsh-base/cordis.patch.yml:107), so there is nothing to lose. If a future
67
+ # (dsh-base/cordis.patch.yml:114-115), so there is nothing to lose. If a future
58
68
  # dsh-base gives that row a default config, this patch swallows it SILENTLY —
59
69
  # diff the shipped llm-pi-ai row against this file on every dsh-base bump and
60
70
  # fold whatever it adds into the `providers:` map below.
package/lib/client.js CHANGED
@@ -6,6 +6,7 @@ window.__ModuleLoader__.load({
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
7
  let jsx = require("react/jsx-runtime");
8
8
  let react = require("react");
9
+ const { Button, Checkbox, Input } = require("@deepseek-ai/dsh-client-ui-primitives");
9
10
 
10
11
  //#region styles
11
12
  /*
@@ -16,19 +17,40 @@ window.__ModuleLoader__.load({
16
17
  */
17
18
  const CSS = [
18
19
  ".dshAr_card{display:flex;flex-direction:column;gap:10px}",
19
- ".dshAr_lead{margin:0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:20px}",
20
+ ".dshAr_lead{margin:0;color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-xs-13)}",
20
21
  ".dshAr_choices{display:flex;gap:10px;margin:0;padding:0;border:0;flex-wrap:wrap}",
21
- ".dshAr_choice{flex:1 1 200px;min-width:0;display:flex;gap:9px;align-items:flex-start;padding:11px 13px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-layer-3);cursor:pointer}",
22
+ ".dshAr_choice{flex:1 1 200px;min-width:0;display:flex;gap:9px;align-items:flex-start;padding:11px 13px;border:0.5px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-layer-3);cursor:pointer;transition:background-color var(--ds-transition-duration) var(--ds-ease-in-out),border-color var(--ds-transition-duration) var(--ds-ease-in-out)}",
22
23
  ".dshAr_choice:hover{background:var(--dsw-alias-interactive-bg-hover)}",
23
24
  ".dshAr_choice[data-selected=true]{border-color:var(--dsw-alias-state-business-primary);box-shadow:0 0 0 1px var(--dsw-alias-state-business-primary) inset}",
24
25
  ".dshAr_choice[data-disabled=true]{cursor:default;opacity:.55}",
25
- ".dshAr_choice input{margin:3px 0 0}",
26
+ ".dshAr_choice input{margin:3px 0 0;accent-color:var(--dsw-alias-brand-primary)}",
27
+ ".dshAr_choice input:focus-visible{outline:none;box-shadow:0 0 0 2px var(--dsw-alias-state-business-primary)}",
26
28
  ".dshAr_choiceText{display:flex;flex-direction:column;gap:2px;min-width:0}",
27
- ".dshAr_choiceTitle{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:600;line-height:20px}",
28
- ".dshAr_choiceHost{overflow-wrap:anywhere;color:var(--dsw-alias-label-tertiary);font-family:var(--ds-font-family-code);font-size:12px;line-height:17px}",
29
- ".dshAr_choiceHint{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:17px}",
30
- ".dshAr_status{margin:0;min-height:18px;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}",
29
+ ".dshAr_choiceTitle{color:var(--dsw-alias-label-primary);font:var(--dsw-font-s-strong-14)}",
30
+ ".dshAr_choiceHost{overflow-wrap:anywhere;color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-xxs-12);font-family:var(--ds-font-family-code)}",
31
+ ".dshAr_choiceHint{color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-xxs-12)}",
32
+ ".dshAr_status{margin:0;min-height:18px;color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-xxs-12)}",
31
33
  ".dshAr_status[data-kind=error]{color:var(--dsw-alias-state-error-primary)}",
34
+ ".dshAr_models{display:flex;flex-direction:column;gap:8px;margin-top:4px;padding-top:12px;border-top:0.5px solid var(--dsw-alias-border-l2)}",
35
+ ".dshAr_modelsHead{display:flex;align-items:center;gap:10px;flex-wrap:wrap}",
36
+ ".dshAr_modelsHead h4{margin:0;color:var(--dsw-alias-label-primary);font:var(--dsw-font-s-strong-14)}",
37
+ ".dshAr_actions{display:flex;gap:8px;flex-wrap:wrap}",
38
+ ".dshAr_modelsHead .dshAr_actions{margin-left:auto}",
39
+ ".dshAr_modelsList{display:flex;flex-direction:column;gap:6px;margin:0;padding:0;list-style:none}",
40
+ ".dshAr_model{margin:0;padding:8px 10px;border:0.5px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-layer-3)}",
41
+ ".dshAr_modelHead{display:flex;gap:8px;align-items:baseline;cursor:pointer;color:var(--dsw-alias-label-primary);font:var(--dsw-font-xs-13)}",
42
+ ".dshAr_modelName{font-weight:600}",
43
+ ".dshAr_modelId{overflow-wrap:anywhere;color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-xxxs-11);font-family:var(--ds-font-family-code)}",
44
+ ".dshAr_fields{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:8px;margin-top:10px}",
45
+ ".dshAr_field{display:flex;flex-direction:column;gap:3px;min-width:0}",
46
+ ".dshAr_fieldLabel{color:var(--dsw-alias-label-secondary);font:var(--dsw-font-xxxs-11)}",
47
+ ".dshAr_inputs{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:10px}",
48
+ ".dshAr_efforts{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:6px;margin-top:10px}",
49
+ ".dshAr_effort{display:flex;gap:6px;align-items:center;min-width:0}",
50
+ ".dshAr_effortLevel{min-width:76px}",
51
+ ".dshAr_effortWire{flex:1 1 60px;min-width:0}",
52
+ ".dshAr_modelActions{display:flex;justify-content:flex-end;margin-top:10px}",
53
+ "@media (prefers-reduced-motion: reduce){.dshAr_choice{transition:none}}",
32
54
  ].join("");
33
55
  const CSS_TAG_ID = "dsh-llm-agentrouter/EndpointCard.css";
34
56
  if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(CSS_TAG_ID) + "]") === null) {
@@ -55,6 +77,47 @@ window.__ModuleLoader__.load({
55
77
  saving: "正在保存…",
56
78
  saved: "已切换到%s。",
57
79
  failed: "保存失败,设置未更改。",
80
+ modelsTitle: "模型列表",
81
+ modelsLead: "这条路由当前提供的模型。「更新」向中转站询问它现有的模型 ID,只补入缺失的、不动已有的;参数改完点「保存」才写入,下一个请求即生效。",
82
+ refresh: "更新",
83
+ refreshing: "正在拉取…",
84
+ refreshAdded: "中转站共 %s 个模型,已补入 %s 个新模型。",
85
+ refreshNone: "中转站共 %s 个模型,没有新的。",
86
+ refreshFailed: "更新失败:%s",
87
+ refreshUnavailable: "当前浏览器读不到中转站能力,无法更新。",
88
+ save: "保存",
89
+ saveDone: "已保存,下一个请求即生效。",
90
+ saveConflict: "设置已被其他地方改动,请重新打开本页再改(%s)。",
91
+ saveFailed: "保存失败:%s",
92
+ reset: "重置为内置默认",
93
+ resetDone: "已恢复内置默认列表。",
94
+ addModel: "添加模型",
95
+ removeModel: "删除",
96
+ newModel: "新模型",
97
+ unsaved: "有未保存的改动。",
98
+ readOnlyModels: "当前部署不允许写入设置,模型列表只读。",
99
+ fieldId: "模型 ID",
100
+ fieldName: "显示名",
101
+ fieldContext: "上下文窗口",
102
+ fieldMaxTokens: "最大输出",
103
+ fieldInput: "输入模态",
104
+ fieldEfforts: "推理档位",
105
+ modalityText: "文本",
106
+ modalityImage: "图片",
107
+ wireNone: "留空 = 不发送",
108
+ wireLabel: "「%s」档位发送给中转站的取值",
109
+ levelOff: "off",
110
+ levelMinimal: "minimal",
111
+ levelLow: "low",
112
+ levelMedium: "medium",
113
+ levelHigh: "high",
114
+ levelXhigh: "xhigh",
115
+ levelMax: "max",
116
+ invalidEmpty: "至少保留一个模型:列表为空时这条路由没有任何可用模型。",
117
+ invalidId: "第 %s 行的模型 ID 不能为空。",
118
+ invalidDuplicate: "模型 ID 重复:%s",
119
+ invalidNumber: "第 %s 行的「%s」必须是正整数。",
120
+ invalidEffort: "第 %s 行的 %s 档位缺少发给中转站的取值。",
58
121
  };
59
122
  /** English dictionary checked against the Chinese key set. */
60
123
  const en = {
@@ -71,6 +134,47 @@ window.__ModuleLoader__.load({
71
134
  saving: "Saving…",
72
135
  saved: "Switched to %s.",
73
136
  failed: "The save failed; the setting is unchanged.",
137
+ modelsTitle: "Model list",
138
+ modelsLead: "The models this route serves. Update asks the relay which model ids it currently offers and adds only the missing ones; an edit is written when you press Save and applies to the next request.",
139
+ refresh: "Update",
140
+ refreshing: "Fetching…",
141
+ refreshAdded: "The relay lists %s models; %s new one(s) added.",
142
+ refreshNone: "The relay lists %s models; nothing new.",
143
+ refreshFailed: "Update failed: %s",
144
+ refreshUnavailable: "This browser cannot interrogate the relay, so Update is unavailable.",
145
+ save: "Save",
146
+ saveDone: "Saved; the next request uses it.",
147
+ saveConflict: "These settings changed elsewhere; reopen this tab and edit again (%s).",
148
+ saveFailed: "Save failed: %s",
149
+ reset: "Reset to built-in",
150
+ resetDone: "Restored the built-in default list.",
151
+ addModel: "Add model",
152
+ removeModel: "Remove",
153
+ newModel: "New model",
154
+ unsaved: "Unsaved changes.",
155
+ readOnlyModels: "This deployment does not accept settings writes; the model list is read-only.",
156
+ fieldId: "Model id",
157
+ fieldName: "Display name",
158
+ fieldContext: "Context window",
159
+ fieldMaxTokens: "Max output",
160
+ fieldInput: "Input modalities",
161
+ fieldEfforts: "Reasoning levels",
162
+ modalityText: "Text",
163
+ modalityImage: "Image",
164
+ wireNone: "empty = send nothing",
165
+ wireLabel: "Wire value sent for the %s level",
166
+ levelOff: "off",
167
+ levelMinimal: "minimal",
168
+ levelLow: "low",
169
+ levelMedium: "medium",
170
+ levelHigh: "high",
171
+ levelXhigh: "xhigh",
172
+ levelMax: "max",
173
+ invalidEmpty: "Keep at least one model: an empty list leaves this route with nothing to serve.",
174
+ invalidId: "Row %s has no model id.",
175
+ invalidDuplicate: "Duplicate model id: %s",
176
+ invalidNumber: "Row %s: %s must be a positive integer.",
177
+ invalidEffort: "Row %s: the %s level names no wire value.",
74
178
  };
75
179
  //#endregion
76
180
 
@@ -103,18 +207,20 @@ window.__ModuleLoader__.load({
103
207
  }
104
208
 
105
209
  /**
106
- * The relay endpoint card: one radio group over this plugin's own settings
107
- * namespace.
210
+ * The relay card: the endpoint radio group over this plugin's own settings
211
+ * namespace, above the model list the route in `llm-pi-ai` actually serves.
108
212
  *
109
213
  * A choice writes immediately rather than staging behind a Save button. The
110
214
  * namespace has exactly one user-facing field and the write is reversible in
111
215
  * one click, so a staged form would add a step without protecting anything —
112
- * and `scope.set` already fences the write with the revision it read.
216
+ * and `scope.set` already fences the write with the revision it read. The
217
+ * two halves are independent: each reads and writes its own namespace, so a
218
+ * deployment that exposes only one of them still renders the other.
113
219
  *
114
- * @param {object} props - the injected scope face plus the bound translator.
220
+ * @param {object} props - the injected scope faces plus the bound translator.
115
221
  * @returns {JSX.Element} the card.
116
222
  */
117
- function EndpointCard({ scope, t }) {
223
+ function EndpointCard({ scope, t, routeScope, operations }) {
118
224
  const snapshot = react.useSyncExternalStore(
119
225
  react.useCallback((listener) => scope.subscribe(listener), [scope]),
120
226
  () => scope.getSnapshot(),
@@ -207,6 +313,609 @@ window.__ModuleLoader__.load({
207
313
  role: shown.kind === "error" ? "alert" : "status",
208
314
  children: shown.text,
209
315
  }),
316
+ routeScope === undefined ? null : jsx.jsx(ModelList, { routeScope, operations, t }),
317
+ ],
318
+ });
319
+ }
320
+ //#endregion
321
+
322
+ //#region model list
323
+ /**
324
+ * The pi-ai settings namespace the relay route is declared in. This plugin's
325
+ * model list is NOT its own preference: it is the `agentrouter` route's
326
+ * `models` array, the same data the kernel's Models page edits, which is why
327
+ * editing it is what changes the model picker. Spelled rather than imported,
328
+ * for the same reason as SETTINGS_NS in the plugin region below: a browser
329
+ * bundle must not depend on a Host package.
330
+ */
331
+ const PI_AI_SETTINGS_NS = "llm-pi-ai";
332
+ /** The route key inside that namespace this plugin owns. */
333
+ const RELAY_ROUTE = "agentrouter";
334
+ /** Reasoning levels a model may offer, in pi-ai's escalation order. */
335
+ const EFFORT_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
336
+ /** Request modalities a model profile may declare. */
337
+ const MODALITIES = ["text", "image"];
338
+ /** Locale key of each modality's label. */
339
+ const MODALITY_LABELS = { text: "modalityText", image: "modalityImage" };
340
+ /**
341
+ * The parameter set a model discovered by 更新 starts from.
342
+ *
343
+ * The relay's listing carries ids only — no capacities — so a discovered row
344
+ * has nothing to inherit them from and starts from this declaration. A model
345
+ * already in the list is never re-seeded: its capacities and reasoning
346
+ * levels stay exactly as they are, because those are the values probed
347
+ * against the relay rather than generic guesses.
348
+ */
349
+ const NEW_MODEL = Object.freeze({
350
+ contextWindow: "1048576",
351
+ maxTokens: "131072",
352
+ input: MODALITIES,
353
+ });
354
+
355
+ /**
356
+ * Fill one `%s`-style template with values, in order. Missing values become
357
+ * empty strings rather than `undefined`, so a diagnostic never renders as
358
+ * the word.
359
+ * @param {string} template - the localized template.
360
+ * @param {string[]} values - replacements for its placeholders.
361
+ * @returns {string} the filled text.
362
+ */
363
+ function fill(template, values) {
364
+ let index = 0;
365
+ return template.replace(/%s/g, () => (index < values.length ? values[index++] : ""));
366
+ }
367
+
368
+ /**
369
+ * The `agentrouter` profile out of one resolved (or stored) `llm-pi-ai`
370
+ * section.
371
+ * @param {unknown} value - a section's resolved value or raw user layer.
372
+ * @returns {object|undefined} the profile, when the shape is one.
373
+ */
374
+ function routeProfile(value) {
375
+ const providers = typeof value === "object" && value !== null ? value.providers : undefined;
376
+ const route = typeof providers === "object" && providers !== null ? providers[RELAY_ROUTE] : undefined;
377
+ return typeof route === "object" && route !== null ? route : undefined;
378
+ }
379
+
380
+ /**
381
+ * The models array inside one resolved `llm-pi-ai` section. The composition
382
+ * layer is the bundle patch's hand-declared list, so this is what the route
383
+ * serves whenever the user layer owns nothing.
384
+ * @param {unknown} value - the resolved section.
385
+ * @returns {object[]} the declared models, or an empty list.
386
+ */
387
+ function modelsOf(value) {
388
+ const models = routeProfile(value)?.models;
389
+ return Array.isArray(models) ? models : [];
390
+ }
391
+
392
+ /**
393
+ * Whether the stored user layer owns the route's model list. Presence in the
394
+ * raw layer is what marks an override — a stored list equal to the
395
+ * composition's is still an override, so comparing values could not see it.
396
+ * @param {unknown} user - the raw user layer.
397
+ * @returns {boolean} whether 重置 has something to remove.
398
+ */
399
+ function overridesModels(user) {
400
+ return Array.isArray(routeProfile(user)?.models);
401
+ }
402
+
403
+ /**
404
+ * Whether a settings node is a nested dict — the shape a path op leaves
405
+ * behind when it removes the last key inside one.
406
+ * @param {unknown} value - a section node.
407
+ * @returns {boolean} whether it is a record.
408
+ */
409
+ function isRecord(value) {
410
+ return typeof value === "object" && value !== null && !Array.isArray(value);
411
+ }
412
+
413
+ /**
414
+ * The ops 重置 sends: the route's model list, plus every ancestor dict that
415
+ * removal empties. An empty dict is inert — the route resolves exactly as it
416
+ * did before a list was ever stored — but leaving one behind keeps the route
417
+ * looking user-owned to the kernel's Models page, and a reset that leaves
418
+ * litter is not a reset.
419
+ * @param {unknown} user - the raw user layer the card read.
420
+ * @returns {object[]} the ordered path ops.
421
+ */
422
+ function resetOps(user) {
423
+ const ops = [{ op: "unset", path: ["providers", RELAY_ROUTE, "models"] }];
424
+ const providers = isRecord(user) ? user.providers : undefined;
425
+ const route = isRecord(providers) ? providers[RELAY_ROUTE] : undefined;
426
+ // Only an ancestor holding nothing else is removed: a sibling the user
427
+ // set through another surface is never touched.
428
+ if (!isRecord(route) || Object.keys(route).length !== 1) return ops;
429
+ ops.push({ op: "unset", path: ["providers", RELAY_ROUTE] });
430
+ if (isRecord(providers) && Object.keys(providers).length === 1) ops.push({ op: "unset", path: ["providers"] });
431
+ return ops;
432
+ }
433
+
434
+ /**
435
+ * One editable draft row from a resolved model entry. Every field is a
436
+ * string while it is being edited, so a half-typed number is a legal value
437
+ * and only the save judges it.
438
+ * @param {object} model - one resolved model entry.
439
+ * @returns {object} the draft row.
440
+ */
441
+ function rowOf(model) {
442
+ const declared = typeof model.reasoningEfforts === "object" && model.reasoningEfforts !== null
443
+ ? model.reasoningEfforts
444
+ : {};
445
+ return {
446
+ id: typeof model.id === "string" ? model.id : "",
447
+ name: typeof model.name === "string" ? model.name : "",
448
+ contextWindow: model.contextWindow === undefined ? "" : String(model.contextWindow),
449
+ maxTokens: model.maxTokens === undefined ? "" : String(model.maxTokens),
450
+ input: Array.isArray(model.input) ? MODALITIES.filter((modality) => model.input.includes(modality)) : [],
451
+ efforts: EFFORT_LEVELS.map((level) => {
452
+ const on = Object.prototype.hasOwnProperty.call(declared, level);
453
+ const wire = declared[level];
454
+ return { level, on, wire: typeof wire === "string" ? wire : "" };
455
+ }),
456
+ };
457
+ }
458
+
459
+ /** Every draft row for one section's model list. */
460
+ function rowsOf(models) {
461
+ return models.map(rowOf);
462
+ }
463
+
464
+ /**
465
+ * A draft row for a model the relay disclosed: the id it named, over
466
+ * {@link NEW_MODEL}'s defaults, with every level offered.
467
+ * @param {string} id - the model id the relay listed.
468
+ * @returns {object} the draft row.
469
+ */
470
+ function freshRow(id) {
471
+ return {
472
+ id,
473
+ name: id,
474
+ contextWindow: NEW_MODEL.contextWindow,
475
+ maxTokens: NEW_MODEL.maxTokens,
476
+ input: [...NEW_MODEL.input],
477
+ efforts: EFFORT_LEVELS.map((level) => ({ level, on: true, wire: level === "off" ? "" : level })),
478
+ };
479
+ }
480
+
481
+ /**
482
+ * Serialize one draft row back into a pi-ai model entry. Unset optional
483
+ * fields are omitted rather than written blank: the Host validates the
484
+ * payload against the adapter's schema, and an empty string is not a
485
+ * capacity.
486
+ *
487
+ * `off` is the one level allowed to carry no wire value — "supported, send
488
+ * nothing" — which the schema spells `null`; every other offered level must
489
+ * name its wire spelling, so an empty one is dropped here and refused by
490
+ * {@link validateRows} before the write.
491
+ * @param {object} row - the draft row.
492
+ * @returns {object} the model entry.
493
+ */
494
+ function modelOf(row) {
495
+ const model = { id: row.id.trim() };
496
+ const name = row.name.trim();
497
+ if (name !== "") model.name = name;
498
+ if (row.contextWindow.trim() !== "") model.contextWindow = Number(row.contextWindow.trim());
499
+ if (row.maxTokens.trim() !== "") model.maxTokens = Number(row.maxTokens.trim());
500
+ model.input = MODALITIES.filter((modality) => row.input.includes(modality));
501
+ const efforts = {};
502
+ for (const entry of row.efforts) {
503
+ if (!entry.on) continue;
504
+ const wire = entry.wire.trim();
505
+ if (wire === "") {
506
+ if (entry.level === "off") efforts.off = null;
507
+ continue;
508
+ }
509
+ efforts[entry.level] = wire;
510
+ }
511
+ if (Object.keys(efforts).length > 0) model.reasoningEfforts = efforts;
512
+ return model;
513
+ }
514
+
515
+ /**
516
+ * Judge a draft before it reaches the Host, so a refusal names the row the
517
+ * user must fix instead of surfacing a schema path.
518
+ * @param {object[]} rows - the draft rows.
519
+ * @param {Function} t - bound translator, for the field names in a message.
520
+ * @returns {{key: string, values: string[]}|undefined} the failure, if any.
521
+ */
522
+ function validateRows(rows, t) {
523
+ if (rows.length === 0) return { key: "invalidEmpty", values: [] };
524
+ const seen = new Set();
525
+ const capacities = [["contextWindow", "fieldContext"], ["maxTokens", "fieldMaxTokens"]];
526
+ for (let index = 0; index < rows.length; index += 1) {
527
+ const row = rows[index];
528
+ const where = String(index + 1);
529
+ const id = row.id.trim();
530
+ if (id === "") return { key: "invalidId", values: [where] };
531
+ if (seen.has(id)) return { key: "invalidDuplicate", values: [id] };
532
+ seen.add(id);
533
+ for (const [field, label] of capacities) {
534
+ const value = row[field].trim();
535
+ if (value !== "" && !/^\d+$/.test(value)) {
536
+ return { key: "invalidNumber", values: [where, t(label)] };
537
+ }
538
+ }
539
+ for (const entry of row.efforts) {
540
+ if (!entry.on || entry.level === "off") continue;
541
+ if (entry.wire.trim() === "") return { key: "invalidEffort", values: [where, entry.level] };
542
+ }
543
+ }
544
+ return undefined;
545
+ }
546
+
547
+ /**
548
+ * One draft row: a collapsible entry carrying the id and display name, the
549
+ * two capacities, the modalities the model accepts, and one line per
550
+ * reasoning level — offered or not, and with which wire spelling.
551
+ *
552
+ * @param {object} props - the row, its index, and the handlers that change it.
553
+ * @returns {JSX.Element} the row.
554
+ */
555
+ function ModelRow({ row, index, readOnly, onPatch, onEffort, onRemove, t }) {
556
+ const field = (name, label) => jsx.jsxs(
557
+ "label",
558
+ {
559
+ className: "dshAr_field",
560
+ children: [
561
+ jsx.jsx("span", { className: "dshAr_fieldLabel", children: t(label) }),
562
+ jsx.jsx(Input, {
563
+ type: "text",
564
+ value: row[name],
565
+ disabled: readOnly,
566
+ "data-model": String(index),
567
+ "data-field": name,
568
+ onChange: (event) => onPatch(index, { [name]: event.target.value }),
569
+ }),
570
+ ],
571
+ },
572
+ name,
573
+ );
574
+ return jsx.jsxs(
575
+ "li",
576
+ {
577
+ className: "dshAr_model",
578
+ "data-model-id": row.id,
579
+ "data-model-index": String(index),
580
+ children: [
581
+ jsx.jsxs("details", {
582
+ children: [
583
+ jsx.jsxs("summary", {
584
+ className: "dshAr_modelHead",
585
+ children: [
586
+ jsx.jsx("span", {
587
+ className: "dshAr_modelName",
588
+ children: row.name.trim() !== "" ? row.name : (row.id.trim() !== "" ? row.id : t("newModel")),
589
+ }),
590
+ jsx.jsx("span", { className: "dshAr_modelId", children: row.id }),
591
+ ],
592
+ }),
593
+ jsx.jsxs("div", {
594
+ className: "dshAr_fields",
595
+ children: [
596
+ field("id", "fieldId"),
597
+ field("name", "fieldName"),
598
+ field("contextWindow", "fieldContext"),
599
+ field("maxTokens", "fieldMaxTokens"),
600
+ ],
601
+ }),
602
+ jsx.jsxs("div", {
603
+ className: "dshAr_inputs",
604
+ children: [
605
+ jsx.jsx("span", { className: "dshAr_fieldLabel", children: t("fieldInput") }),
606
+ ...MODALITIES.map((modality) => jsx.jsx(
607
+ "span",
608
+ {
609
+ "data-modality": modality,
610
+ "data-model": String(index),
611
+ children: jsx.jsx(Checkbox, {
612
+ checked: row.input.includes(modality),
613
+ disabled: readOnly,
614
+ label: t(MODALITY_LABELS[modality]),
615
+ onChange: (next) => onPatch(index, {
616
+ input: next
617
+ ? [...row.input, modality]
618
+ : row.input.filter((entry) => entry !== modality),
619
+ }),
620
+ }),
621
+ },
622
+ modality,
623
+ )),
624
+ ],
625
+ }),
626
+ jsx.jsxs("div", {
627
+ className: "dshAr_efforts",
628
+ "data-field": "reasoningEfforts",
629
+ children: EFFORT_LEVELS.map((level) => {
630
+ const entry = row.efforts.find((candidate) => candidate.level === level)
631
+ ?? { level, on: false, wire: "" };
632
+ const levelKey = "level" + level.charAt(0).toUpperCase() + level.slice(1);
633
+ return jsx.jsxs(
634
+ "div",
635
+ {
636
+ className: "dshAr_effort",
637
+ "data-level": level,
638
+ "data-model": String(index),
639
+ children: [
640
+ jsx.jsx(Checkbox, {
641
+ checked: entry.on,
642
+ disabled: readOnly,
643
+ className: "dshAr_effortLevel",
644
+ label: t(levelKey),
645
+ onChange: (next) => onEffort(index, level, { on: next }),
646
+ }),
647
+ jsx.jsx(Input, {
648
+ className: "dshAr_effortWire",
649
+ type: "text",
650
+ value: entry.wire,
651
+ placeholder: level === "off" ? t("wireNone") : level,
652
+ disabled: readOnly || !entry.on,
653
+ "aria-label": fill(t("wireLabel"), [t(levelKey)]),
654
+ "data-model": String(index),
655
+ "data-wire": level,
656
+ onChange: (event) => onEffort(index, level, { wire: event.target.value }),
657
+ }),
658
+ ],
659
+ },
660
+ level,
661
+ );
662
+ }),
663
+ }),
664
+ jsx.jsx("div", {
665
+ className: "dshAr_modelActions",
666
+ children: jsx.jsx(Button, {
667
+ variant: "ghost",
668
+ size: "sm",
669
+ "data-action": "remove",
670
+ disabled: readOnly,
671
+ onClick: () => onRemove(index),
672
+ children: t("removeModel"),
673
+ }),
674
+ }),
675
+ ],
676
+ }),
677
+ ],
678
+ },
679
+ index,
680
+ );
681
+ }
682
+
683
+ /**
684
+ * Store faces for a caller that injects no Host operations — an older Host,
685
+ * or a test rendering this component directly.
686
+ */
687
+ const NO_OPERATIONS_STORE = { subscribe: () => () => {}, snapshot: () => 0 };
688
+
689
+ /**
690
+ * The relay's model list: one editable row per model the `agentrouter` route
691
+ * serves, the 更新 action that asks the relay what it currently offers, and
692
+ * the write that puts the result back on the route.
693
+ *
694
+ * Reads come from the shared settings mirror through the scope bound to
695
+ * `llm-pi-ai`, so the card and the kernel's Models page can never disagree
696
+ * about the route. Writes go through the Remote call the operations were
697
+ * built with, NOT through `scope.set`: the mirror's write path reports a
698
+ * refusal by silently reloading, while this card has to show the Host's own
699
+ * diagnostic — a stale revision, or a payload the adapter's schema refused.
700
+ *
701
+ * An edit lives in this component until 保存; 重置 drops the draft and, when
702
+ * the user layer owns the list, removes that override so the composition's
703
+ * hand-declared list serves again.
704
+ *
705
+ * @param {object} props - the route scope, the Host operations, and `t`.
706
+ * @returns {JSX.Element} the model list.
707
+ */
708
+ function ModelList({ routeScope, operations, t }) {
709
+ const snapshot = react.useSyncExternalStore(
710
+ react.useCallback((listener) => routeScope.subscribe(listener), [routeScope]),
711
+ () => routeScope.getSnapshot(),
712
+ );
713
+ const ops = operations ?? {};
714
+ // The optional Remote faces mount after this plugin activates, so the
715
+ // capability is re-read on every one of their announcements instead of
716
+ // being frozen at the first render.
717
+ const store = typeof ops.subscribe === "function" && typeof ops.snapshot === "function"
718
+ ? ops
719
+ : NO_OPERATIONS_STORE;
720
+ react.useSyncExternalStore(store.subscribe, store.snapshot, store.snapshot);
721
+ const [draft, setDraft] = react.useState(null);
722
+ const [busy, setBusy] = react.useState(null);
723
+ const [status, setStatus] = react.useState(null);
724
+
725
+ const writable = snapshot.status === "ready" && snapshot.writable === true;
726
+ const canWrite = typeof ops.write === "function";
727
+ const canProbe = typeof ops.available === "function"
728
+ ? ops.available() === true
729
+ : typeof ops.discover === "function";
730
+ const rows = draft !== null ? draft.rows : rowsOf(modelsOf(snapshot.value));
731
+ const overridden = overridesModels(snapshot.user);
732
+ const readOnly = !writable || !canWrite || busy !== null;
733
+
734
+ /**
735
+ * Stage one change as a draft. The first edit captures the namespace
736
+ * revision it was opened at, which is the fence the save carries, so a
737
+ * concurrent write elsewhere is refused instead of overwritten.
738
+ * @param {Function} change - rows in, next rows out.
739
+ */
740
+ const edit = (change) => {
741
+ setDraft((current) => {
742
+ const base = current ?? { rows: rowsOf(modelsOf(snapshot.value)), revision: snapshot.revision };
743
+ return { rows: change(base.rows), revision: base.revision };
744
+ });
745
+ setStatus({ kind: "info", key: "unsaved", values: [] });
746
+ };
747
+ const patchRow = (index, fields) => edit((list) => list.map(
748
+ (row, at) => (at === index ? { ...row, ...fields } : row),
749
+ ));
750
+ const patchEffort = (index, level, fields) => edit((list) => list.map((row, at) => {
751
+ if (at !== index) return row;
752
+ return {
753
+ ...row,
754
+ efforts: row.efforts.map((entry) => (entry.level === level ? { ...entry, ...fields } : entry)),
755
+ };
756
+ }));
757
+ const addRow = () => edit((list) => [...list, freshRow("")]);
758
+ const removeRow = (index) => edit((list) => list.filter((row, at) => at !== index));
759
+ const fail = (key, values) => setStatus({ kind: "error", key, values });
760
+ const reasonOf = (error) => (error instanceof Error ? error.message : String(error));
761
+
762
+ /** Ask the relay what it serves, and stage what is not in the list yet. */
763
+ const refresh = () => {
764
+ if (!canProbe || typeof ops.discover !== "function" || readOnly) return;
765
+ const profile = routeProfile(snapshot.value);
766
+ const baseURL = typeof profile?.baseURL === "string" ? profile.baseURL : "";
767
+ if (baseURL === "") {
768
+ fail("refreshFailed", [t("refreshUnavailable")]);
769
+ return;
770
+ }
771
+ const request = { provider: RELAY_ROUTE, baseURL };
772
+ if (typeof profile.api === "string") request.api = profile.api;
773
+ setBusy("refresh");
774
+ setStatus({ kind: "info", key: "refreshing", values: [] });
775
+ Promise.resolve()
776
+ .then(() => ops.discover(request))
777
+ .then((outcome) => {
778
+ if (!outcome.ok) {
779
+ fail("refreshFailed", [outcome.message]);
780
+ return;
781
+ }
782
+ // Merge, never replace: a discovered id that is already listed keeps
783
+ // every hand-tuned parameter, and a local model the relay no longer
784
+ // lists is left alone rather than silently dropped.
785
+ const current = draft !== null ? draft.rows : rowsOf(modelsOf(snapshot.value));
786
+ const known = new Set(current.map((row) => row.id.trim()));
787
+ const added = [];
788
+ for (const model of outcome.models) {
789
+ const id = typeof model?.id === "string" ? model.id.trim() : "";
790
+ if (id === "" || known.has(id)) continue;
791
+ known.add(id);
792
+ added.push(freshRow(id));
793
+ }
794
+ if (added.length > 0) {
795
+ setDraft({
796
+ rows: [...current, ...added],
797
+ revision: draft !== null ? draft.revision : snapshot.revision,
798
+ });
799
+ }
800
+ setStatus({
801
+ kind: "info",
802
+ key: added.length > 0 ? "refreshAdded" : "refreshNone",
803
+ values: added.length > 0
804
+ ? [String(outcome.models.length), String(added.length)]
805
+ : [String(outcome.models.length)],
806
+ });
807
+ }, (error) => fail("refreshFailed", [reasonOf(error)]))
808
+ .then(() => setBusy(null));
809
+ };
810
+
811
+ /** Write the drafted list onto the route's own `models` key. */
812
+ const save = () => {
813
+ if (draft === null || !canWrite || readOnly) return;
814
+ const failure = validateRows(draft.rows, t);
815
+ if (failure !== undefined) {
816
+ setStatus({ kind: "error", key: failure.key, values: failure.values });
817
+ return;
818
+ }
819
+ const ops_ = [{
820
+ op: "set",
821
+ path: ["providers", RELAY_ROUTE, "models"],
822
+ value: draft.rows.map(modelOf),
823
+ }];
824
+ setBusy("save");
825
+ Promise.resolve()
826
+ .then(() => ops.write(ops_, draft.revision))
827
+ .then((outcome) => {
828
+ if (!outcome.ok) {
829
+ fail(outcome.code === "settings/conflict" ? "saveConflict" : "saveFailed", [outcome.message]);
830
+ return;
831
+ }
832
+ setDraft(null);
833
+ setStatus({ kind: "info", key: "saveDone", values: [] });
834
+ }, (error) => fail("saveFailed", [reasonOf(error)]))
835
+ .then(() => setBusy(null));
836
+ };
837
+
838
+ /** Drop the draft; with a user-owned list, remove that override too. */
839
+ const reset = () => {
840
+ if (readOnly) return;
841
+ if (!overridden) {
842
+ setDraft(null);
843
+ setStatus({ kind: "info", key: "resetDone", values: [] });
844
+ return;
845
+ }
846
+ if (!canWrite) return;
847
+ setBusy("reset");
848
+ Promise.resolve()
849
+ .then(() => ops.write(resetOps(snapshot.user), snapshot.revision))
850
+ .then((outcome) => {
851
+ if (!outcome.ok) {
852
+ fail(outcome.code === "settings/conflict" ? "saveConflict" : "saveFailed", [outcome.message]);
853
+ return;
854
+ }
855
+ setDraft(null);
856
+ setStatus({ kind: "info", key: "resetDone", values: [] });
857
+ }, (error) => fail("saveFailed", [reasonOf(error)]))
858
+ .then(() => setBusy(null));
859
+ };
860
+
861
+ const shown = status === null
862
+ ? { kind: "info", text: "" }
863
+ : { kind: status.kind, text: fill(t(status.key), status.values) };
864
+ const action = (name, label, disabled, onClick) => jsx.jsx(Button, {
865
+ variant: name === "save" ? "primary" : "outline",
866
+ size: "sm",
867
+ "data-action": name,
868
+ disabled,
869
+ onClick,
870
+ children: label,
871
+ });
872
+ const hint = !writable
873
+ ? t("readOnlyModels")
874
+ : (canProbe ? "" : t("refreshUnavailable"));
875
+
876
+ return jsx.jsxs("section", {
877
+ className: "dshAr_models",
878
+ "data-model-list": RELAY_ROUTE,
879
+ "aria-busy": busy !== null,
880
+ children: [
881
+ jsx.jsxs("div", {
882
+ className: "dshAr_modelsHead",
883
+ children: [
884
+ jsx.jsx("h4", { children: t("modelsTitle") }),
885
+ jsx.jsxs("div", {
886
+ className: "dshAr_actions",
887
+ children: [
888
+ action("refresh", busy === "refresh" ? t("refreshing") : t("refresh"), readOnly || !canProbe, refresh),
889
+ action("reset", t("reset"), readOnly || (draft === null && !overridden), reset),
890
+ action("save", busy === "save" ? t("saving") : t("save"), readOnly || draft === null, save),
891
+ ],
892
+ }),
893
+ ],
894
+ }),
895
+ jsx.jsx("p", { className: "dshAr_lead", children: t("modelsLead") }),
896
+ jsx.jsxs("ul", {
897
+ className: "dshAr_modelsList",
898
+ children: rows.map((row, index) => jsx.jsx(ModelRow, {
899
+ row,
900
+ index,
901
+ readOnly,
902
+ onPatch: patchRow,
903
+ onEffort: patchEffort,
904
+ onRemove: removeRow,
905
+ t,
906
+ }, index)),
907
+ }),
908
+ jsx.jsx("div", {
909
+ className: "dshAr_actions",
910
+ children: action("add", t("addModel"), readOnly, addRow),
911
+ }),
912
+ jsx.jsx("p", {
913
+ className: "dshAr_status",
914
+ "data-kind": shown.kind,
915
+ role: shown.kind === "error" ? "alert" : "status",
916
+ children: shown.text,
917
+ }),
918
+ hint === "" ? null : jsx.jsx("p", { className: "dshAr_lead", children: hint }),
210
919
  ],
211
920
  });
212
921
  }
@@ -268,13 +977,11 @@ window.__ModuleLoader__.load({
268
977
  position: "relative",
269
978
  padding: "7px 1px 11px",
270
979
  cursor: "pointer",
271
- font: "inherit",
272
- fontSize: "13px",
273
- lineHeight: "20px",
274
- color: "var(--dsw-alias-label-tertiary, inherit)",
980
+ font: "var(--dsw-font-xs-13)",
981
+ color: "var(--dsw-alias-label-tertiary)",
275
982
  };
276
983
  const TAB_ACTIVE_STYLE = Object.assign({}, TAB_STYLE, {
277
- color: "var(--dsw-alias-label-primary, inherit)",
984
+ color: "var(--dsw-alias-label-primary)",
278
985
  });
279
986
  /** The kernel's own tab marker: a 2px rounded bar under the active label. */
280
987
  const TAB_MARKER_STYLE = {
@@ -284,7 +991,7 @@ window.__ModuleLoader__.load({
284
991
  bottom: 0,
285
992
  height: "2px",
286
993
  borderRadius: "2px 2px 0 0",
287
- background: "var(--dsw-alias-label-primary, currentColor)",
994
+ background: "var(--dsw-alias-label-primary)",
288
995
  };
289
996
  /**
290
997
  * Panels stay mounted (hidden) so each card keeps its local state. `display:
@@ -444,6 +1151,66 @@ window.__ModuleLoader__.load({
444
1151
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), "llm-agentrouter: dictionaries");
445
1152
  const t = ctx.locale.bind(NS);
446
1153
  const scope = ctx.settingsScope.bind({ namespace: SETTINGS_NS });
1154
+ // The model list is not this plugin's own section: it is the `agentrouter`
1155
+ // route inside the adapter's namespace, the same document the kernel's
1156
+ // Models page edits, so the card derives from that namespace's mirror.
1157
+ const routeScope = ctx.settingsScope.bind({ namespace: PI_AI_SETTINGS_NS });
1158
+ // Both Host faces are OPTIONAL reads: a deployment whose Client assembly
1159
+ // mounts neither still shows the endpoint switch, and the model list
1160
+ // degrades to read-only with the reason rendered instead of going blank.
1161
+ //
1162
+ // They are resolved per call rather than captured: the Remote namespaces
1163
+ // install asynchronously after this plugin activates, so a face captured
1164
+ // here could read as absent for the whole session. `ctx.inject`
1165
+ // re-announces every mount, and the store below turns that into the
1166
+ // re-render that re-reads the capability.
1167
+ let version = 0;
1168
+ const waiting = new Set();
1169
+ const announce = () => {
1170
+ version += 1;
1171
+ for (const listener of [...waiting]) listener();
1172
+ };
1173
+ const remoteOf = (name) => ctx.get(name);
1174
+ const operations = {
1175
+ available: () => remoteOf("remote.llm") !== undefined,
1176
+ subscribe: (listener) => {
1177
+ waiting.add(listener);
1178
+ return () => {
1179
+ waiting.delete(listener);
1180
+ };
1181
+ },
1182
+ snapshot: () => version,
1183
+ discover: (request) => {
1184
+ const llm = remoteOf("remote.llm");
1185
+ if (llm === undefined) return Promise.resolve({ ok: false, message: t("refreshUnavailable") });
1186
+ return llm.discoverModels(PI_AI_SETTINGS_NS, request).then(
1187
+ (response) => (response.ok
1188
+ ? { ok: true, models: response.value }
1189
+ : { ok: false, message: response.error.message }),
1190
+ (error) => ({ ok: false, message: error instanceof Error ? error.message : String(error) }),
1191
+ );
1192
+ },
1193
+ write: (ops, revision) => {
1194
+ const settings = remoteOf("remote.settings");
1195
+ if (settings === undefined) {
1196
+ return Promise.resolve({ ok: false, code: "settings/unavailable", message: t("readOnlyModels") });
1197
+ }
1198
+ return settings.mutate(PI_AI_SETTINGS_NS, ops, revision).then(
1199
+ (response) => (response.ok
1200
+ ? { ok: true, revision: response.value.revision }
1201
+ : { ok: false, code: response.error.code, message: response.error.message }),
1202
+ (error) => ({ ok: false, code: "settings/failed", message: error instanceof Error ? error.message : String(error) }),
1203
+ );
1204
+ },
1205
+ };
1206
+ // Announced per face rather than as one dependency set: a deployment that
1207
+ // mounts only one of them must still let the card observe it.
1208
+ ctx.inject(["remote.llm"], () => {
1209
+ announce();
1210
+ });
1211
+ ctx.inject(["remote.settings"], () => {
1212
+ announce();
1213
+ });
447
1214
  // The page is shared with dsh-a6api and the kernel cannot declare one page
448
1215
  // twice, so whichever participant activates first claims it and the other
449
1216
  // only contributes a card (see the shell region above).
@@ -460,7 +1227,7 @@ window.__ModuleLoader__.load({
460
1227
  // Rendered as the card's tab title inside the shared page.
461
1228
  label: () => t("title"),
462
1229
  locale: NS,
463
- inject: () => ({ scope, t }),
1230
+ inject: () => ({ scope, t, routeScope, operations }),
464
1231
  },
465
1232
  EndpointCard,
466
1233
  ),
@@ -471,6 +1238,7 @@ window.__ModuleLoader__.load({
471
1238
  exports.NS = NS;
472
1239
  exports.SETTINGS_NS = SETTINGS_NS;
473
1240
  exports.EndpointCard = EndpointCard;
1241
+ exports.ModelList = ModelList;
474
1242
  exports.apply = apply;
475
1243
  exports.inject = inject;
476
1244
  return module.exports;
package/lib/index.js CHANGED
@@ -293,7 +293,7 @@ function apply(ctx, config) {
293
293
  if (config.announce) {
294
294
  const table = routingTable(config)
295
295
  ctx.logger.info(
296
- 'llm-agentrouter: endpoint %c (%c), sending %c',
296
+ 'llm-agentrouter: endpoint %s (%s), sending %s',
297
297
  config.endpoint,
298
298
  table.get(config.sentinel.trim().toLowerCase()) ?? 'unrouted',
299
299
  config.userAgent,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lynn123411/dsh-llm-agentrouter",
3
- "version": "0.2.3",
4
- "description": "AgentRouter 中转聚合:一条 pi-ai 路由承载多模型 + 国内/国际端点一键切换(设置卡片)+ 出站请求 User-Agent/402-配额改写围栏。aqiu817/dsh-llm-agentrouter 分叉,适配 0.1.2-alpha.5 起新 settings/slots API,已在 0.1.5-rc.1 逐项实证兼容。",
3
+ "version": "0.3.1",
4
+ "description": "AgentRouter 中转聚合:一条 pi-ai 路由承载多模型(设置卡片内可从中转站拉取、逐个编辑模型与参数)+ 国内/国际端点一键切换 + 出站请求 User-Agent/402-配额改写围栏。模型列表写入内核「设置 - 模型」页所编辑的同一份 llm-pi-ai 路由数据。",
5
5
  "keywords": [
6
6
  "deepseek-harness",
7
7
  "dsh-plugin",
@@ -33,6 +33,7 @@
33
33
  "client": {
34
34
  "inject": [
35
35
  "@deepseek-ai/dsh-client-locale",
36
+ "@deepseek-ai/dsh-client-ui-primitives",
36
37
  "@deepseek-ai/dsh-client-ui-settings"
37
38
  ],
38
39
  "platform": "web"
@@ -41,7 +42,6 @@
41
42
  "files": [
42
43
  "lib/",
43
44
  "cordis.patch.yml",
44
- "LICENSE",
45
45
  "README.md"
46
46
  ],
47
47
  "publishConfig": {
@@ -51,7 +51,8 @@
51
51
  "test": "node --test test/*.test.mjs"
52
52
  },
53
53
  "engines": {
54
- "node": ">=22"
54
+ "node": ">=22",
55
+ "dsh": "0.1.6-alpha.2"
55
56
  },
56
57
  "dependencies": {
57
58
  "@deepseek-ai/schemastery": "^3.18.2"
package/LICENSE DELETED
@@ -1,22 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 aqiu817
4
- Copyright (c) 2026 lynn123411 (alpha.5 compatibility fork: settings/slots API migration, package rename)
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining a copy
7
- of this software and associated documentation files (the "Software"), to deal
8
- in the Software without restriction, including without limitation the rights
9
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- copies of the Software, and to permit persons to whom the Software is
11
- furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included in all
14
- copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.