dsh-jev-tools-continued 0.0.0-stage → 0.2.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 (122) hide show
  1. package/CHANGELOG.en.md +449 -0
  2. package/CHANGELOG.i18n.yaml +13 -0
  3. package/CHANGELOG.md +357 -0
  4. package/LICENSE +21 -0
  5. package/README.en.md +210 -0
  6. package/README.i18n.yaml +13 -0
  7. package/README.md +209 -2
  8. package/client/client.js +755 -0
  9. package/cordis.patch.yml +30 -0
  10. package/docs/banner.png +0 -0
  11. package/docs/dev-workflow.md +414 -0
  12. package/docs/s0-trigger-rate.md +168 -0
  13. package/icon.svg +16 -0
  14. package/lib/backends/jev.d.ts +69 -0
  15. package/lib/backends/jev.d.ts.map +1 -0
  16. package/lib/backends/jev.js +151 -0
  17. package/lib/backends/jev.js.map +1 -0
  18. package/lib/backends/types.d.ts +104 -0
  19. package/lib/backends/types.d.ts.map +1 -0
  20. package/lib/backends/types.js +12 -0
  21. package/lib/backends/types.js.map +1 -0
  22. package/lib/budget.d.ts +60 -0
  23. package/lib/budget.d.ts.map +1 -0
  24. package/lib/budget.js +70 -0
  25. package/lib/budget.js.map +1 -0
  26. package/lib/calibrate.d.ts +162 -0
  27. package/lib/calibrate.d.ts.map +1 -0
  28. package/lib/calibrate.js +269 -0
  29. package/lib/calibrate.js.map +1 -0
  30. package/lib/config.d.ts +261 -0
  31. package/lib/config.d.ts.map +1 -0
  32. package/lib/config.js +194 -0
  33. package/lib/config.js.map +1 -0
  34. package/lib/context-cache.d.ts +59 -0
  35. package/lib/context-cache.d.ts.map +1 -0
  36. package/lib/context-cache.js +116 -0
  37. package/lib/context-cache.js.map +1 -0
  38. package/lib/credentials.d.ts +32 -0
  39. package/lib/credentials.d.ts.map +1 -0
  40. package/lib/credentials.js +44 -0
  41. package/lib/credentials.js.map +1 -0
  42. package/lib/degrade.d.ts +36 -0
  43. package/lib/degrade.d.ts.map +1 -0
  44. package/lib/degrade.js +41 -0
  45. package/lib/degrade.js.map +1 -0
  46. package/lib/features/prune.d.ts +116 -0
  47. package/lib/features/prune.d.ts.map +1 -0
  48. package/lib/features/prune.js +574 -0
  49. package/lib/features/prune.js.map +1 -0
  50. package/lib/features/screen.d.ts +112 -0
  51. package/lib/features/screen.d.ts.map +1 -0
  52. package/lib/features/screen.js +130 -0
  53. package/lib/features/screen.js.map +1 -0
  54. package/lib/features/skill-suggest.d.ts +68 -0
  55. package/lib/features/skill-suggest.d.ts.map +1 -0
  56. package/lib/features/skill-suggest.js +283 -0
  57. package/lib/features/skill-suggest.js.map +1 -0
  58. package/lib/host.d.ts +280 -0
  59. package/lib/host.d.ts.map +1 -0
  60. package/lib/host.js +15 -0
  61. package/lib/host.js.map +1 -0
  62. package/lib/http.d.ts +71 -0
  63. package/lib/http.d.ts.map +1 -0
  64. package/lib/http.js +162 -0
  65. package/lib/http.js.map +1 -0
  66. package/lib/i18n.d.ts +372 -0
  67. package/lib/i18n.d.ts.map +1 -0
  68. package/lib/i18n.js +254 -0
  69. package/lib/i18n.js.map +1 -0
  70. package/lib/index.d.ts +44 -0
  71. package/lib/index.d.ts.map +1 -0
  72. package/lib/index.js +268 -0
  73. package/lib/index.js.map +1 -0
  74. package/lib/keys.d.ts +90 -0
  75. package/lib/keys.d.ts.map +1 -0
  76. package/lib/keys.js +131 -0
  77. package/lib/keys.js.map +1 -0
  78. package/lib/ledger-domain.d.ts +169 -0
  79. package/lib/ledger-domain.d.ts.map +1 -0
  80. package/lib/ledger-domain.js +338 -0
  81. package/lib/ledger-domain.js.map +1 -0
  82. package/lib/ledger.d.ts +243 -0
  83. package/lib/ledger.d.ts.map +1 -0
  84. package/lib/ledger.js +239 -0
  85. package/lib/ledger.js.map +1 -0
  86. package/lib/memo.d.ts +32 -0
  87. package/lib/memo.d.ts.map +1 -0
  88. package/lib/memo.js +62 -0
  89. package/lib/memo.js.map +1 -0
  90. package/lib/notify.d.ts +78 -0
  91. package/lib/notify.d.ts.map +1 -0
  92. package/lib/notify.js +122 -0
  93. package/lib/notify.js.map +1 -0
  94. package/lib/proxy.d.ts +40 -0
  95. package/lib/proxy.d.ts.map +1 -0
  96. package/lib/proxy.js +136 -0
  97. package/lib/proxy.js.map +1 -0
  98. package/lib/request.d.ts +99 -0
  99. package/lib/request.d.ts.map +1 -0
  100. package/lib/request.js +168 -0
  101. package/lib/request.js.map +1 -0
  102. package/lib/source.d.ts +46 -0
  103. package/lib/source.d.ts.map +1 -0
  104. package/lib/source.js +35 -0
  105. package/lib/source.js.map +1 -0
  106. package/lib/status.d.ts +42 -0
  107. package/lib/status.d.ts.map +1 -0
  108. package/lib/status.js +214 -0
  109. package/lib/status.js.map +1 -0
  110. package/lib/tokens.d.ts +26 -0
  111. package/lib/tokens.d.ts.map +1 -0
  112. package/lib/tokens.js +57 -0
  113. package/lib/tokens.js.map +1 -0
  114. package/lib/tools/jev-ask.d.ts +44 -0
  115. package/lib/tools/jev-ask.d.ts.map +1 -0
  116. package/lib/tools/jev-ask.js +208 -0
  117. package/lib/tools/jev-ask.js.map +1 -0
  118. package/lib/tools/jev-gate.d.ts +79 -0
  119. package/lib/tools/jev-gate.d.ts.map +1 -0
  120. package/lib/tools/jev-gate.js +412 -0
  121. package/lib/tools/jev-gate.js.map +1 -0
  122. package/package.json +169 -4
@@ -0,0 +1,755 @@
1
+ /**
2
+ * dsh-jev-tools-continued browser half: the bundle's own configuration card.
3
+ *
4
+ * Hand-written lazy-CJS bundle (`window.__ModuleLoader__.load`), no build step,
5
+ * no imports beyond React — deliberately so, because the npm-published
6
+ * `@deepseek-ai/dsh-*` packages lag the running harness badly and requiring one
7
+ * would couple this plugin to a stale signature.
8
+ *
9
+ * It renders into `plugins.bundle.config`, the purpose-built seat for a
10
+ * bundle's own configuration, keyed by the bundle's package name.
11
+ *
12
+ * The card follows the DSH language: it reads the client locale service and
13
+ * re-renders when that changes. (The host half cannot do this — the locale
14
+ * service is client-only — so it infers the language from the conversation
15
+ * instead. See `src/i18n.ts`.)
16
+ *
17
+ * Two seams carry the data, both already present in the harness:
18
+ * - `remote.credentials` answers only whether a key is configured, its
19
+ * source, and whether it is writable. The secret literal never rides a
20
+ * response; the input starts blank on every load.
21
+ * - `configForms` is the browser's settings seam: `get(namespace)` binds this
22
+ * bundle's Host entry, and the shared mirror behind it is the one place the
23
+ * page reads `settings.describe()`. The toggles, the judgment endpoint and
24
+ * the model are therefore the same values the host resolves — and because
25
+ * the provider owns the write queue, a write from this card and one from any
26
+ * other editor of the same entry are serialized together.
27
+ *
28
+ * Endpoint and model are hand-written fields rather than a form generated from
29
+ * the schema: this card occupies `plugins.bundle.config` under this bundle's
30
+ * package name, and that seat is single-occupant, so whatever it draws *is* the
31
+ * bundle's configuration page. A settings field the card omits is a field a GUI
32
+ * user cannot reach at all — which is exactly how `baseUrl` shipped unused
33
+ * between 0.1.6 and 0.1.10 (issue #3).
34
+ *
35
+ * @module dsh-jev-tools-continued/client
36
+ */
37
+
38
+ window.__ModuleLoader__.load({
39
+ id: 'dsh-jev-tools-continued',
40
+ factory: (require) => {
41
+ /** Settings namespace owned by the host half. */
42
+ const NS = 'dsh-jev-tools-continued'
43
+ /** Where a user creates a TypeSafe API key. */
44
+ const KEYS_URL = 'https://console.typesafe.ai/keys'
45
+ /** Where a user creates an OpenRouter key, when the endpoint is OpenRouter's. */
46
+ const OPENROUTER_KEYS_URL = 'https://openrouter.ai/settings/keys'
47
+ /** The vendor's own System One root: what the host falls back to, and what the card shows before it has read a value. */
48
+ const DEFAULT_BASE_URL = 'https://api.typesafe.ai'
49
+ /** Credential reference used when the settings name none. */
50
+ const DEFAULT_REF = 'TYPESAFE_API_KEY'
51
+ /**
52
+ * The only address shape the backend can POST to: an absolute http(s) root
53
+ * with no whitespace. Checked here because a save that stores `openrouter.ai`
54
+ * would send the next judgment to a relative URL, and every capability in
55
+ * this plugin is fail-open — that failure looks exactly like doing nothing.
56
+ */
57
+ const BASE_URL_RE = /^https?:\/\/\S+$/i
58
+
59
+ /**
60
+ * Whether an endpoint is OpenRouter's, which issues its own keys.
61
+ *
62
+ * @param {string} baseUrl - the endpoint as configured.
63
+ * @returns {boolean} true when the card should link to OpenRouter's console.
64
+ */
65
+ function isOpenRouter (baseUrl) {
66
+ try {
67
+ const host = new URL(baseUrl).hostname
68
+ return host === 'openrouter.ai' || host.endsWith('.openrouter.ai')
69
+ } catch {
70
+ return false
71
+ }
72
+ }
73
+
74
+ /**
75
+ * The endpoint's host, for copy that has to name where content is sent.
76
+ *
77
+ * @param {string} baseUrl - the endpoint as configured.
78
+ * @returns {string} the host, or the raw value when it will not parse.
79
+ */
80
+ function hostOf (baseUrl) {
81
+ try {
82
+ return new URL(baseUrl).host
83
+ } catch {
84
+ return baseUrl
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Split the key-reference setting into usable variable names.
90
+ *
91
+ * Commas, semicolons and whitespace all separate, so `A,B`, `A B` and a
92
+ * pasted `A, B` all mean two keys. Duplicates collapse: resolving the same
93
+ * variable twice would pin the same key and switch to itself. Mirrors
94
+ * `keyRefs()` on the host side; the card cannot import it, so the rule
95
+ * lives here too.
96
+ *
97
+ * @param {unknown} raw - the `apiKeyEnv` setting as configured.
98
+ * @returns {string[]} the reference names, in order, without blanks or duplicates.
99
+ */
100
+ function splitRefs (raw) {
101
+ const refs = []
102
+ if (typeof raw !== 'string') return refs
103
+ for (const part of raw.split(/[\s,;]+/)) {
104
+ const ref = part.trim()
105
+ if (ref !== '' && refs.indexOf(ref) === -1) refs.push(ref)
106
+ }
107
+ return refs
108
+ }
109
+
110
+ /** Every user-facing string, in both languages. */
111
+ const S = {
112
+ zh: {
113
+ heading: '自动精简工具输出、自动推荐技能',
114
+ status: '状态',
115
+ reading: '读取中…',
116
+ configured: (source) => `已配置(来源:${source})`,
117
+ unconfigured: '未配置',
118
+ intro: '还没有 API key。按下面的链接申请一个,然后粘贴到下面。',
119
+ getKeyTypeSafe: '到 TypeSafe 控制台申请 key →',
120
+ getKeyOpenRouter: '到 OpenRouter 申请 key →',
121
+ keyPlaceholder: (ref) => `粘贴 ${ref}`,
122
+ keyPlaceholderSet: '已配置,粘贴新值可覆盖',
123
+ save: '保存',
124
+ saved: '已保存。',
125
+ readFailed: (error) => `读取配置失败:${error}`,
126
+ saveFailed: (error) => `保存失败:${error}`,
127
+ noCredentialService: '凭据服务不可用,无法保存。可改用环境变量方式配置。',
128
+ noSettingsService: '设置服务不可用。',
129
+ readonlyRef: (ref) => `环境变量 ${ref} 由只读来源提供,无法在界面上覆盖。要修改请改动它的来源。`,
130
+ refsHeading: '密钥变量名',
131
+ refsSaved: '变量名已保存;凭据按新的变量名重新读取。',
132
+ refsHint: '一行一把:左边改名,右边粘贴 key,点行上的保存;「添加一把」加一行,「移除」删一行(至少留一把)。同一会话固定用一把,只有它 401/429 才换下一把。',
133
+ refsDup: '这个名字已经在用了,换一个。',
134
+ refsRename: '新变量名',
135
+ refsAdd: '添加一把',
136
+ refsRemove: '移除',
137
+ configuredMany: (done, total) => `已配置 ${done}/${total}`,
138
+ proxyLabel: '网络出口',
139
+ proxyHint: '留空直连;填 system 走系统代理;也可直接填地址,如 http://127.0.0.1:7897。受限地区直连只会拿到 403。',
140
+ proxyBad: '网络出口只能留空、填 system,或填 http(s) 地址。',
141
+ endpointHeading: '判定端点',
142
+ endpointBase: '服务地址',
143
+ endpointModel: '模型',
144
+ endpointSave: '保存端点',
145
+ endpointSaved: '端点已保存;下一次判定就用新地址。',
146
+ endpointBadUrl: '服务地址要以 http:// 或 https:// 开头,且不能含空格。',
147
+ endpointBadModel: '模型不能为空。',
148
+ endpointHint: '插件会在这个地址后追加 /v1/systemone,所以这里填服务的根地址。接第三方 System One 主机:'
149
+ + 'OpenRouter 填 https://openrouter.ai/api,模型填 jev-latest(或 typesafe/jev-1.13),key 用 OpenRouter 的。',
150
+ toggleMaster: '启用插件',
151
+ togglePrune: '精简超长的工具输出',
152
+ toggleSuggest: '推荐该用的技能',
153
+ privacy: (host) => `隐私:启用后,被精简掉的工具输出内容会发送到 ${host} 进行判定;`
154
+ + '推荐技能时只发送当前请求与技能名称、描述。密钥保存在本机凭据存储中,不会回显。'
155
+ + '没配 key 时两项能力完全不生效、不发任何网络请求。',
156
+ ledger: '判定台账只记元数据(token 数、段数、作答版本、跳过原因),不含任何提示词或工具输出正文,'
157
+ + '且只留在本机。有 storage 时持久化到 $DSH_HOME/storages,重启后累计数字不丢。',
158
+ summary: (status) => `Jev · ${status}`,
159
+ unknownSource: '未知',
160
+ namespaceMissing: (ns, served) => `读取不到设置命名空间 ${ns}:挂载这一行用的 id 必须与包名一致(见 cordis.patch.yml)。`
161
+ + `当前宿主提供的命名空间:${served.length === 0 ? '(无)' : served.join('、')}。`,
162
+ },
163
+ en: {
164
+ heading: 'Prunes long tool output, suggests which skill to use',
165
+ status: 'Status',
166
+ reading: 'reading…',
167
+ configured: (source) => `configured (source: ${source})`,
168
+ unconfigured: 'not configured',
169
+ intro: 'No API key yet. Get one from the link below, then paste it here.',
170
+ getKeyTypeSafe: 'Get a key from the TypeSafe console →',
171
+ getKeyOpenRouter: 'Get a key from OpenRouter →',
172
+ keyPlaceholder: (ref) => `paste ${ref}`,
173
+ keyPlaceholderSet: 'configured — paste a new value to replace it',
174
+ save: 'Save',
175
+ saved: 'Saved.',
176
+ readFailed: (error) => `Could not read settings: ${error}`,
177
+ saveFailed: (error) => `Save failed: ${error}`,
178
+ noCredentialService: 'The credentials service is unavailable, so the key cannot be stored here. Use an environment variable instead.',
179
+ noSettingsService: 'The settings service is unavailable.',
180
+ readonlyRef: (ref) => `${ref} comes from a read-only source and cannot be overridden here; change that source instead.`,
181
+ refsHeading: 'Key reference',
182
+ refsSaved: 'Reference saved; credentials are re-read from the new names.',
183
+ refsHint: 'One row per key: rename on the left, paste the key on the right, save the row; “Add a key” grows the list, “Remove” shrinks it (one reference always stays). A session stays on one key and moves on only when it answers 401 or 429.',
184
+ refsDup: 'That name is already in the list.',
185
+ refsRename: 'New variable name',
186
+ refsAdd: 'Add a key',
187
+ refsRemove: 'Remove',
188
+ configuredMany: (done, total) => `configured ${done}/${total}`,
189
+ proxyLabel: 'Network exit',
190
+ proxyHint: 'Empty connects directly; system uses the operating system proxy; a URL such as http://127.0.0.1:7897 is used as given. A blocked region only ever gets a 403 on a direct connection.',
191
+ proxyBad: 'The network exit must be empty, system, or an http(s) URL.',
192
+ endpointHeading: 'Judgment endpoint',
193
+ endpointBase: 'Service address',
194
+ endpointModel: 'Model',
195
+ endpointSave: 'Save endpoint',
196
+ endpointSaved: 'Endpoint saved; the next judgment uses it.',
197
+ endpointBadUrl: 'The service address must start with http:// or https:// and contain no spaces.',
198
+ endpointBadModel: 'The model cannot be empty.',
199
+ endpointHint: 'The plugin appends /v1/systemone to this address, so enter the service root. '
200
+ + 'For a third-party System One host: OpenRouter is https://openrouter.ai/api with model '
201
+ + 'jev-latest (or typesafe/jev-1.13), using an OpenRouter key.',
202
+ toggleMaster: 'Enable the plugin',
203
+ togglePrune: 'Prune oversized tool output',
204
+ toggleSuggest: 'Suggest which skill to use',
205
+ privacy: (host) => `Privacy: once enabled, the tool output that gets pruned is sent to ${host} for judging; `
206
+ + 'skill suggestions send only the current request plus skill names and descriptions. '
207
+ + 'The key is stored in this machine\u2019s credential store and is never echoed back. '
208
+ + 'With no key configured both capabilities are completely inert and make no network request.',
209
+ ledger: 'The judgment ledger records metadata only — token counts, segment counts, the version that '
210
+ + 'answered, and why a judgment was skipped. No prompt or tool-output text, and it never leaves this '
211
+ + 'machine. With a storage domain it persists under $DSH_HOME/storages, so the cumulative numbers '
212
+ + 'survive a restart.',
213
+ summary: (status) => `Jev · ${status}`,
214
+ unknownSource: 'unknown',
215
+ namespaceMissing: (ns, served) => `The settings namespace ${ns} was not found: the row must be mounted `
216
+ + `under the bundle's package name (see cordis.patch.yml). The host serves: `
217
+ + `${served.length === 0 ? '(none)' : served.join(', ')}.`,
218
+ },
219
+ }
220
+
221
+ /** The active language, from the client locale service. */
222
+ function langOf (ctx) {
223
+ try {
224
+ const locale = ctx.locale
225
+ if (locale === undefined || typeof locale.getLocale !== 'function') return 'en'
226
+ const snapshot = locale.getLocale()
227
+ const active = snapshot !== null && snapshot !== undefined ? snapshot.active : undefined
228
+ return typeof active === 'string' && active.toLowerCase().indexOf('zh') === 0 ? 'zh' : 'en'
229
+ } catch {
230
+ return 'en'
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Build the card component bound to one client context.
236
+ *
237
+ * @param {object} React - the browser module table's React.
238
+ * @param {object} ctx - the client plugin context.
239
+ * @returns {Function} the card component.
240
+ */
241
+ function makeCard (React, ctx) {
242
+ const h = React.createElement
243
+
244
+ /** Read one remote namespace defensively: absent services are not errors. */
245
+ function remote (path) {
246
+ const parts = path.split('.')
247
+ let node = ctx
248
+ for (const part of parts) {
249
+ if (node === undefined || node === null) return undefined
250
+ node = node[part]
251
+ }
252
+ return node
253
+ }
254
+
255
+ /** Resolve a RemoteResult to its value, or undefined on any failure. */
256
+ function valueOf (response) {
257
+ if (response === undefined || response === null) return undefined
258
+ if (response.ok === false) return undefined
259
+ return response.value
260
+ }
261
+
262
+ /** Hidden characters without being a password field, so the key stays out of keychain offers. */
263
+ function maskedProps () {
264
+ const props = { autoComplete: 'off' }
265
+ if (typeof CSS !== 'undefined' && 'textSecurity' in document.documentElement.style) {
266
+ props.style = { textSecurity: 'disc', WebkitTextSecurity: 'disc' }
267
+ } else {
268
+ props.type = 'password'
269
+ }
270
+ return props
271
+ }
272
+
273
+ const MUTED = 'var(--dsw-alias-label-tertiary, rgba(127,127,127,0.85))'
274
+ const ACCENT = 'var(--dsw-alias-accent, #4f8cff)'
275
+ const TEXT = 'var(--dsw-alias-label-primary, inherit)'
276
+ const BORDER = 'var(--dsw-alias-border-secondary, rgba(127,127,127,0.35))'
277
+
278
+ function row (label, value) {
279
+ return h('div', { style: { display: 'flex', gap: '8px', fontSize: '12px', lineHeight: '18px' } },
280
+ h('span', { style: { color: MUTED, minWidth: '76px' } }, label),
281
+ h('span', { style: { color: TEXT } }, value))
282
+ }
283
+
284
+ function toggle (label, checked, disabled, onChange) {
285
+ return h('label', {
286
+ style: { display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px', cursor: disabled ? 'default' : 'pointer', opacity: disabled ? 0.5 : 1 },
287
+ },
288
+ h('input', {
289
+ type: 'checkbox', checked: checked === true, disabled: disabled === true,
290
+ onChange: (event) => { onChange(event.target.checked) },
291
+ }),
292
+ h('span', { style: { color: TEXT } }, label))
293
+ }
294
+
295
+ /**
296
+ * One staged text field.
297
+ *
298
+ * @param {string} label - the field's name.
299
+ * @param {string} value - the staged value.
300
+ * @param {(next: string) => void} onChange - receives the whole next value.
301
+ * @param {string} placeholder - shown while the field is empty.
302
+ * @param {boolean} disabled - true while the host has not answered yet.
303
+ * @returns {object} the field element.
304
+ */
305
+ function field (label, value, onChange, placeholder, disabled) {
306
+ return h('label', {
307
+ style: { display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px' },
308
+ },
309
+ h('span', { style: { color: MUTED, minWidth: '76px' } }, label),
310
+ h('input', {
311
+ value, placeholder, autoComplete: 'off', disabled: disabled === true,
312
+ onChange: (event) => { onChange(event.target.value) },
313
+ style: { flex: 1, minWidth: 0, fontSize: '12px', padding: '6px 8px', borderRadius: '6px', border: `1px solid ${BORDER}`, background: 'transparent', color: TEXT },
314
+ }))
315
+ }
316
+
317
+ const link = (href, text) => h('a', {
318
+ href, target: '_blank', rel: 'noreferrer',
319
+ style: { color: ACCENT, fontSize: '12px', textDecoration: 'none' },
320
+ }, text)
321
+
322
+ /**
323
+ * The card.
324
+ *
325
+ * @param {{ view?: 'summary' | 'page' }} props - `summary` renders the
326
+ * one-liner alone; `page` renders the full form with its save control.
327
+ */
328
+ return function JevCard (props) {
329
+ const view = props !== null && props !== undefined && props.view === 'summary' ? 'summary' : 'page'
330
+ const [lang, setLang] = React.useState(() => langOf(ctx))
331
+ const [settings, setSettings] = React.useState(null)
332
+ const [revision, setRevision] = React.useState(undefined)
333
+ /** One credential standing per reference, keyed by reference name. */
334
+ const [infos, setInfos] = React.useState(null)
335
+ /** Staged key values, keyed by reference name — one input per configured reference. */
336
+ const [drafts, setDrafts] = React.useState({})
337
+ /** Latest settings writer: callbacks defined before `patch` call through here. */
338
+ const patchRef = React.useRef(null)
339
+ /** Staged reference renames, keyed by the saved name — one input per row. */
340
+ const [refDrafts, setRefDrafts] = React.useState({})
341
+ const [note, setNote] = React.useState('')
342
+ const [busy, setBusy] = React.useState(false)
343
+ /** Whether the host's profile accepts form edits at all. */
344
+ const [formWritable, setFormWritable] = React.useState(true)
345
+ // The endpoint travels with the key: a key issued by OpenRouter or a
346
+ // self-hosted System One host earns a 401 against the default host, and
347
+ // because every capability here is fail-open that 401 looks like the
348
+ // plugin doing nothing. Both fields are staged, and written only on the
349
+ // explicit save below — a settings write is durable, so it must not
350
+ // happen per keystroke.
351
+ const [baseUrlDraft, setBaseUrlDraft] = React.useState('')
352
+ const [modelDraft, setModelDraft] = React.useState('')
353
+ const [proxyDraft, setProxyDraft] = React.useState('')
354
+ const seeded = React.useRef(false)
355
+
356
+ /**
357
+ * The browser's one settings seam.
358
+ *
359
+ * `ctx.configForms` is provided by the settings UI and owns the single
360
+ * `settings.describe()` reader in the browser; every page — the four
361
+ * official ones included — derives from it. Its `get(namespace)` binds
362
+ * this bundle's entry by the namespace the host publishes (the mount row
363
+ * id, which is why the row and the package name have to agree).
364
+ */
365
+ const forms = ctx.configForms
366
+ const form = forms !== undefined && typeof forms.get === 'function' ? forms.get(NS) : undefined
367
+
368
+ /** Every namespace the browser's settings mirror currently serves. */
369
+ function servedNamespaces () {
370
+ try {
371
+ if (forms === undefined || typeof forms.describe !== 'function') return []
372
+ const view = forms.describe().getSnapshot().view
373
+ return Array.isArray(view !== null && view !== undefined ? view.namespaces : undefined)
374
+ ? view.namespaces.map((entry) => entry.ns).filter((ns) => typeof ns === 'string')
375
+ : []
376
+ } catch {
377
+ return []
378
+ }
379
+ }
380
+
381
+ const t = S[lang]
382
+
383
+ // Seed the endpoint drafts once, when the host's values first arrive.
384
+ // Re-seeding on every load would discard whatever is being typed the
385
+ // moment a toggle writes and reloads.
386
+ React.useEffect(() => {
387
+ if (settings === null || seeded.current) return
388
+ seeded.current = true
389
+ setBaseUrlDraft(typeof settings.baseUrl === 'string' ? settings.baseUrl : '')
390
+ setModelDraft(typeof settings.model === 'string' ? settings.model : '')
391
+ setProxyDraft(typeof settings.proxy === 'string' ? settings.proxy : '')
392
+ }, [settings])
393
+
394
+ // Follow the DSH language: re-render whenever the locale changes.
395
+ React.useEffect(() => {
396
+ const locale = ctx.locale
397
+ if (locale === undefined || typeof locale.subscribe !== 'function') return undefined
398
+ return locale.subscribe(() => { setLang(langOf(ctx)) })
399
+ }, [])
400
+
401
+ /** The configured references, in order — one key input each. Falls back to the default reference. */
402
+ const rawRef = settings !== null && typeof settings.apiKeyEnv === 'string' ? settings.apiKeyEnv : ''
403
+ const refs = splitRefs(rawRef).length === 0 ? [DEFAULT_REF] : splitRefs(rawRef)
404
+ /** Re-seed the credential read whenever the reference list changes. */
405
+ const refsKey = refs.join(',')
406
+
407
+ /** The endpoint the host reports, before this card has read a value. */
408
+ const settingsBaseUrl = settings !== null && typeof settings.baseUrl === 'string' ? settings.baseUrl : ''
409
+ const settingsModel = settings !== null && typeof settings.model === 'string' ? settings.model : ''
410
+ const settingsProxy = settings !== null && typeof settings.proxy === 'string' ? settings.proxy : ''
411
+ /** The endpoint the copy names: the configured one, or the vendor's own until the host answers. */
412
+ const effectiveBaseUrl = settingsBaseUrl === '' ? DEFAULT_BASE_URL : settingsBaseUrl
413
+ const openRouter = isOpenRouter(effectiveBaseUrl)
414
+
415
+ /** Re-read the shared form and the credential seam. Never throws: a failure becomes a visible note. */
416
+ const load = React.useCallback(async () => {
417
+ try {
418
+ if (form === undefined) {
419
+ setNote(S[langOf(ctx)].noSettingsService)
420
+ } else {
421
+ const snapshot = typeof form.getSnapshot === 'function' ? form.getSnapshot() : undefined
422
+ if (snapshot !== undefined && snapshot.value !== undefined) {
423
+ setSettings(snapshot.value ?? null)
424
+ setRevision(snapshot.revision)
425
+ setFormWritable(snapshot.writable !== false)
426
+ } else {
427
+ // The namespace DSH publishes is the mount row id, while this card
428
+ // addresses the bundle by package name — so a profile that mounts
429
+ // the row under another id leaves the shared form with nothing to
430
+ // read. Say which namespace was missing and which ones the mirror
431
+ // does serve, instead of drawing the empty form that used to look
432
+ // exactly like "nothing is configured".
433
+ setNote(S[langOf(ctx)].namespaceMissing(NS, servedNamespaces()))
434
+ }
435
+ }
436
+ const credentialsApi = remote('remote.credentials')
437
+ if (credentialsApi !== undefined) {
438
+ const described = valueOf(await credentialsApi.describe(refs))
439
+ const next = {}
440
+ for (const name of refs) {
441
+ const info = described !== null && described !== undefined ? described[name] : undefined
442
+ next[name] = info !== null && info !== undefined ? info : { configured: false, writable: true }
443
+ }
444
+ setInfos(next)
445
+ } else {
446
+ const next = {}
447
+ for (const name of refs) next[name] = { configured: false, writable: true, unavailable: true }
448
+ setInfos(next)
449
+ }
450
+ } catch (error) {
451
+ setNote(S[langOf(ctx)].readFailed(String(error)))
452
+ }
453
+ }, [refsKey])
454
+
455
+ React.useEffect(() => {
456
+ if (settings === null && infos === null) void load()
457
+ }, [settings, infos, load])
458
+
459
+ // Live updates: the shared form derives from the browser's one settings
460
+ // mirror, so a write from anywhere — this card, the Plugins page, another
461
+ // editor — arrives here as a store replacement.
462
+ React.useEffect(() => {
463
+ if (form === undefined || typeof form.subscribe !== 'function') return undefined
464
+ return form.subscribe(() => { void load() })
465
+ }, [form, load])
466
+
467
+ /**
468
+ * Save one row: a rename, a key, or both. Defined after `patch`, whose
469
+ * operation list the rename writes through. A rename rewrites the whole
470
+ * reference list with this entry swapped out, then the key (when one is
471
+ * staged) lands under the new name — so a row added as `NEW_KEY` becomes
472
+ * whatever was typed into its name field in a single save.
473
+ */
474
+ const saveRow = React.useCallback(async (oldName) => {
475
+ const newName = (refDrafts[oldName] ?? oldName).trim()
476
+ const keyVal = drafts[oldName] ?? ''
477
+ if (newName === '') return
478
+ if (refs.some((other) => other !== oldName && other === newName)) return
479
+ setBusy(true)
480
+ setNote('')
481
+ const strings = S[langOf(ctx)]
482
+ try {
483
+ if (newName !== oldName) {
484
+ const value = refs.map((entry) => entry === oldName ? newName : entry).join(', ')
485
+ const moved = await patchRef.current([{ op: 'set', path: ['apiKeyEnv'], value }])
486
+ if (moved === false) return
487
+ setRefDrafts((previous) => {
488
+ const next = Object.assign({}, previous)
489
+ delete next[oldName]
490
+ return next
491
+ })
492
+ }
493
+ if (keyVal !== '') {
494
+ const credentialsApi = remote('remote.credentials')
495
+ if (credentialsApi === undefined) {
496
+ setNote(strings.noCredentialService)
497
+ return
498
+ }
499
+ await credentialsApi.set(newName, keyVal)
500
+ }
501
+ setDrafts((previous) => {
502
+ const next = Object.assign({}, previous)
503
+ delete next[oldName]
504
+ delete next[newName]
505
+ return next
506
+ })
507
+ await load()
508
+ setNote(strings.saved)
509
+ } catch (error) {
510
+ setNote(strings.saveFailed(String(error)))
511
+ } finally {
512
+ setBusy(false)
513
+ }
514
+ }, [refDrafts, drafts, refs, load])
515
+
516
+ /**
517
+ * Write one atomic operation list through the shared form, then re-read.
518
+ *
519
+ * Staged and saved explicitly: every settings write is a durable document
520
+ * mutation, so a control that committed as it settled would turn one edit
521
+ * into a write nobody asked for. The revision read before editing travels
522
+ * with the write, so a concurrent editor conflicts instead of winning
523
+ * silently.
524
+ *
525
+ * @param {Array<{op: string, path: string[], value?: unknown}>} ops - ordered field operations.
526
+ * @returns {Promise<boolean>} whether the host accepted the write.
527
+ */
528
+ const patch = React.useCallback(async (ops) => {
529
+ setBusy(true)
530
+ setNote('')
531
+ const strings = S[langOf(ctx)]
532
+ try {
533
+ if (form === undefined) {
534
+ setNote(strings.noSettingsService)
535
+ return false
536
+ }
537
+ const accepted = await form.mutate(ops, revision)
538
+ await load()
539
+ return accepted !== false
540
+ } catch (error) {
541
+ setNote(strings.saveFailed(String(error)))
542
+ return false
543
+ } finally {
544
+ setBusy(false)
545
+ }
546
+ }, [form, revision, load])
547
+
548
+ patchRef.current = patch
549
+
550
+ /**
551
+ * Append a fresh reference name and save the list: the new row's key
552
+ * input appears once the host's re-read arrives. Names are `NEW_KEY`,
553
+ * `NEW_KEY_2`, … — rename them in the field above if they offend.
554
+ */
555
+ const addRef = React.useCallback(async () => {
556
+ if (settings === null) return
557
+ let n = 1
558
+ let name = 'NEW_KEY'
559
+ while (refs.indexOf(name) !== -1) { n += 1; name = `NEW_KEY_${n}` }
560
+ const value = rawRef === '' ? name : `${rawRef}, ${name}`
561
+ if (await patch([{ op: 'set', path: ['apiKeyEnv'], value }])) setNote(S[langOf(ctx)].refsSaved)
562
+ }, [rawRef, refs, settings, patch])
563
+
564
+ /**
565
+ * Drop one reference from the list; its key input leaves with it. The
566
+ * last reference cannot be removed — an empty list would fall back to
567
+ * the default name and pretend nothing was configured.
568
+ */
569
+ const removeRef = React.useCallback(async (name) => {
570
+ if (settings === null || refs.length <= 1) return
571
+ const value = refs.filter((entry) => entry !== name).join(', ')
572
+ if (await patch([{ op: 'set', path: ['apiKeyEnv'], value }])) setNote(S[langOf(ctx)].refsSaved)
573
+ }, [refs, settings, patch])
574
+
575
+ /**
576
+ * Save the endpoint fields, and only the ones that changed.
577
+ *
578
+ * Writing an unchanged field would turn "I looked at it" into an
579
+ * override, which pins the value against future default changes; a
580
+ * strict-equal draft therefore produces no write at all.
581
+ */
582
+ const saveEndpoint = React.useCallback(async () => {
583
+ const ops = []
584
+ const baseUrl = baseUrlDraft.trim()
585
+ const model = modelDraft.trim()
586
+ const proxy = proxyDraft.trim()
587
+ if (settings === null) return
588
+ if (baseUrl !== settingsBaseUrl) ops.push({ op: 'set', path: ['baseUrl'], value: baseUrl })
589
+ if (model !== settingsModel) ops.push({ op: 'set', path: ['model'], value: model })
590
+ if (proxy !== settingsProxy) ops.push({ op: 'set', path: ['proxy'], value: proxy })
591
+ if (ops.length === 0) return
592
+ if (await patch(ops)) setNote(S[langOf(ctx)].endpointSaved)
593
+ }, [baseUrlDraft, modelDraft, proxyDraft, settings, patch])
594
+
595
+ /** One row per reference: whether its key resolves, and whether the card may write it. */
596
+ const entries = refs.map((name) => {
597
+ const info = infos !== null ? infos[name] : undefined
598
+ const ok = info !== undefined && info !== null && info.configured === true
599
+ return {
600
+ name,
601
+ ok,
602
+ writable: info === undefined || info === null || info.writable !== false,
603
+ text: infos === null
604
+ ? t.reading
605
+ : ok
606
+ ? t.configured((info !== null && info !== undefined && info.source !== undefined) ? info.source : t.unknownSource)
607
+ : t.unconfigured,
608
+ }
609
+ })
610
+ const configuredCount = entries.filter((entry) => entry.ok).length
611
+ const status = infos === null
612
+ ? t.reading
613
+ : configuredCount === 0
614
+ ? t.unconfigured
615
+ : refs.length === 1
616
+ ? entries[0].text
617
+ : t.configuredMany(configuredCount, refs.length)
618
+
619
+ if (view === 'summary') {
620
+ return h('div', { style: { fontSize: '12px', color: MUTED } }, t.summary(status))
621
+ }
622
+
623
+ const pruneOn = settings !== null && settings.prune !== undefined && settings.prune.enabled === true
624
+ const suggestOn = settings !== null && settings.suggest !== undefined && settings.suggest.enabled === true
625
+ const masterOn = settings !== null && settings.enabled === true
626
+
627
+ // What the endpoint section can do right now. An invalid draft blocks
628
+ // the save and says why, rather than being stored and failing later as
629
+ // silence: every capability in this plugin is fail-open.
630
+ const baseUrlValue = baseUrlDraft.trim()
631
+ const modelValue = modelDraft.trim()
632
+ const proxyValue = proxyDraft.trim()
633
+ const endpointReadOnly = settings === null || busy || !formWritable
634
+ // An empty address is invalid too: storing one would POST to a relative
635
+ // URL, and that failure is invisible everywhere else.
636
+ const baseUrlInvalid = !BASE_URL_RE.test(baseUrlValue)
637
+ const modelInvalid = modelValue === ''
638
+ const proxyInvalid = !(proxyValue === '' || proxyValue === 'system' || BASE_URL_RE.test(proxyValue))
639
+ const endpointDirty = settings !== null
640
+ && (baseUrlValue !== settingsBaseUrl || modelValue !== settingsModel || proxyValue !== settingsProxy)
641
+ const endpointSaveDisabled = endpointReadOnly || !endpointDirty || baseUrlInvalid || modelInvalid || proxyInvalid
642
+
643
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px', padding: '4px 0' } },
644
+ h('div', { style: { fontSize: '13px', fontWeight: 600, color: TEXT } }, t.heading),
645
+
646
+ row(t.status, status),
647
+ configuredCount === 0 ? h('div', { style: { fontSize: '12px', color: MUTED } }, t.intro) : null,
648
+ h('div', { style: { fontSize: '12px' } },
649
+ link(openRouter ? OPENROUTER_KEYS_URL : KEYS_URL, openRouter ? t.getKeyOpenRouter : t.getKeyTypeSafe)),
650
+
651
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '6px', paddingTop: '4px', borderTop: `1px solid ${BORDER}` } },
652
+ h('div', { style: { fontSize: '12px', fontWeight: 600, color: TEXT } }, t.refsHeading),
653
+ h('div', { style: { display: 'flex', gap: '8px', alignItems: 'center' } },
654
+ h('button', {
655
+ type: 'button',
656
+ disabled: endpointReadOnly || busy,
657
+ onClick: () => { void addRef() },
658
+ style: { fontSize: '12px', padding: '6px 12px', borderRadius: '6px', border: `1px solid ${BORDER}`, background: 'transparent', color: TEXT, cursor: endpointReadOnly || busy ? 'default' : 'pointer' },
659
+ }, t.refsAdd)),
660
+ h('div', { style: { fontSize: '11px', color: MUTED, lineHeight: '16px' } }, t.refsHint)),
661
+
662
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
663
+ ...entries.map((entry) => {
664
+ const stagedName = refDrafts[entry.name] ?? entry.name
665
+ const trimmedName = stagedName.trim()
666
+ const nameChanged = trimmedName !== entry.name
667
+ const keyStaged = drafts[entry.name] ?? ''
668
+ const dup = trimmedName !== '' && refs.some((other) => other !== entry.name && other === trimmedName)
669
+ const rowDirty = nameChanged || keyStaged !== ''
670
+ const rowBad = trimmedName === '' || dup
671
+ const rowSaveDisabled = busy || !entry.writable || !rowDirty || rowBad
672
+ return h('div', {
673
+ key: entry.name,
674
+ style: { display: 'flex', flexDirection: 'column', gap: '6px' },
675
+ },
676
+ row(entry.name, entry.text),
677
+ field(t.refsHeading, stagedName, (next) => { setRefDrafts((previous) => Object.assign({}, previous, { [entry.name]: next })) }, t.refsRename, endpointReadOnly || busy),
678
+ dup ? h('div', { style: { fontSize: '11px', color: MUTED } }, t.refsDup) : null,
679
+ h('div', { style: { display: 'flex', gap: '8px', alignItems: 'center' } },
680
+ h('input', Object.assign({
681
+ value: keyStaged,
682
+ placeholder: entry.ok ? t.keyPlaceholderSet : t.keyPlaceholder(entry.name),
683
+ disabled: busy || !entry.writable,
684
+ onChange: (event) => { setDrafts((previous) => Object.assign({}, previous, { [entry.name]: event.target.value })) },
685
+ style: { flex: 1, minWidth: 0, fontSize: '12px', padding: '6px 8px', borderRadius: '6px', border: `1px solid ${BORDER}`, background: 'transparent', color: TEXT },
686
+ }, maskedProps())),
687
+ h('button', {
688
+ type: 'button',
689
+ disabled: rowSaveDisabled,
690
+ onClick: () => { void saveRow(entry.name) },
691
+ style: { fontSize: '12px', padding: '6px 12px', borderRadius: '6px', border: `1px solid ${BORDER}`, background: 'transparent', color: TEXT, cursor: rowSaveDisabled ? 'default' : 'pointer' },
692
+ }, t.save),
693
+ h('button', {
694
+ type: 'button',
695
+ disabled: busy || refs.length <= 1,
696
+ onClick: () => { void removeRef(entry.name) },
697
+ style: { fontSize: '12px', padding: '6px 12px', borderRadius: '6px', border: `1px solid ${BORDER}`, background: 'transparent', color: TEXT, cursor: busy || refs.length <= 1 ? 'default' : 'pointer' },
698
+ }, t.refsRemove)),
699
+ entry.writable ? null : h('div', { style: { fontSize: '11px', color: MUTED } }, t.readonlyRef(entry.name)))})),
700
+
701
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '6px', paddingTop: '4px', borderTop: `1px solid ${BORDER}` } },
702
+ h('div', { style: { fontSize: '12px', fontWeight: 600, color: TEXT } }, t.endpointHeading),
703
+ field(t.endpointBase, baseUrlDraft, (next) => { setBaseUrlDraft(next) }, DEFAULT_BASE_URL, endpointReadOnly),
704
+ field(t.endpointModel, modelDraft, (next) => { setModelDraft(next) }, 'jev-latest', endpointReadOnly),
705
+ field(t.proxyLabel, proxyDraft, (next) => { setProxyDraft(next) }, 'system', endpointReadOnly),
706
+ baseUrlInvalid ? h('div', { style: { fontSize: '11px', color: MUTED } }, t.endpointBadUrl) : null,
707
+ modelInvalid ? h('div', { style: { fontSize: '11px', color: MUTED } }, t.endpointBadModel) : null,
708
+ proxyInvalid ? h('div', { style: { fontSize: '11px', color: MUTED } }, t.proxyBad) : null,
709
+ h('div', { style: { display: 'flex', gap: '8px', alignItems: 'center' } },
710
+ h('button', {
711
+ type: 'button',
712
+ disabled: endpointSaveDisabled,
713
+ onClick: () => { void saveEndpoint() },
714
+ style: { fontSize: '12px', padding: '6px 12px', borderRadius: '6px', border: `1px solid ${BORDER}`, background: 'transparent', color: TEXT, cursor: endpointSaveDisabled ? 'default' : 'pointer' },
715
+ }, t.endpointSave)),
716
+ h('div', { style: { fontSize: '11px', color: MUTED, lineHeight: '16px' } }, t.endpointHint),
717
+ h('div', { style: { fontSize: '11px', color: MUTED, lineHeight: '16px' } }, t.proxyHint)),
718
+
719
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '6px', paddingTop: '4px', borderTop: `1px solid ${BORDER}` } },
720
+ toggle(t.toggleMaster, masterOn, busy || settings === null || !formWritable, (next) => { void patch([{ op: 'set', path: ['enabled'], value: next }]) }),
721
+ toggle(t.togglePrune, pruneOn, busy || settings === null || !formWritable, (next) => { void patch([{ op: 'set', path: ['prune', 'enabled'], value: next }]) }),
722
+ toggle(t.toggleSuggest, suggestOn, busy || settings === null || !formWritable, (next) => { void patch([{ op: 'set', path: ['suggest', 'enabled'], value: next }]) })),
723
+
724
+ h('div', { style: { fontSize: '11px', color: MUTED, lineHeight: '16px' } }, t.privacy(hostOf(effectiveBaseUrl))),
725
+
726
+ h('div', { style: { fontSize: '11px', color: MUTED, lineHeight: '16px' } }, t.ledger),
727
+
728
+ note === '' ? null : h('div', { style: { fontSize: '11px', color: MUTED } }, note))
729
+ }
730
+ }
731
+
732
+ return {
733
+ // `configForms` is the browser's settings seam: the provider owns the only
734
+ // `settings.describe()` reader, and every page — the official four included
735
+ // — derives from its shared mirror. `remote.credentials` is injected beside
736
+ // it for the key, and `locale` drives the card's language.
737
+ inject: ['slots', 'locale', 'remote', 'remote.credentials', 'configForms'],
738
+ /**
739
+ * Register the card into the bundle-configuration seat.
740
+ *
741
+ * @param {object} ctx - the client plugin context.
742
+ */
743
+ apply (ctx) {
744
+ const slots = ctx.slots
745
+ if (slots === undefined || typeof slots.inject !== 'function') return
746
+ const React = require('react')
747
+ const Card = makeCard(React, ctx)
748
+ slots.inject('plugins.bundle.config', () => slots.register({
749
+ name: 'plugins.bundle.config',
750
+ key: 'dsh-jev-tools-continued',
751
+ }, Card))
752
+ },
753
+ }
754
+ },
755
+ })