@kenz1117/dsh-engram 0.9.4 → 0.9.5

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/lib/index.js CHANGED
@@ -51,186 +51,6 @@ function resolveLanguage(setting) {
51
51
  return setting === "auto" ? systemLanguage() : setting;
52
52
  }
53
53
  //#endregion
54
- //#region src/config.ts
55
- /**
56
- * 插件 Config:所有部署可变项集中于此,禁止在实现里内嵌默认值。
57
- * @module @kenz1117/dsh-engram/config
58
- */
59
- /** 合法配置键集合(未知键 loud 失败)。 */
60
- const CONFIG_KEYS = /* @__PURE__ */ new Set([
61
- "legacyMigration",
62
- "dbDir",
63
- "injectProfile",
64
- "profileTopN",
65
- "modelCacheDir",
66
- "hfEndpoint",
67
- "ingest",
68
- "reflect",
69
- "provider",
70
- "model",
71
- "decayAfterDays",
72
- "decayImportanceBelow",
73
- "injectTokenBudget",
74
- "injectItemBudgetStart",
75
- "injectItemBudgetDecay",
76
- "injectItemBudgetFloor",
77
- "rankRecencyWeight",
78
- "rankProofWeight",
79
- "queryRewrite",
80
- "autoSlot",
81
- "reviewScheduling",
82
- "assessReminder",
83
- "historyBackfillDays",
84
- "historyBackfillMaxTurnsPerSession",
85
- "historyBackfillMaxTotalTurns",
86
- "historyBackfillIncludeSubagents",
87
- "historyBackfillIncludeSeeded",
88
- "historyBackfillIncludeNoCwd",
89
- "jev",
90
- "language",
91
- "redactWords"
92
- ]);
93
- const INGEST_MODES = /* @__PURE__ */ new Set([
94
- "off",
95
- "light",
96
- "eager"
97
- ]);
98
- const REFLECT_MODES = /* @__PURE__ */ new Set([
99
- "off",
100
- "suggest",
101
- "auto"
102
- ]);
103
- /** Schemastery 校验面(cordis.yml 读取时校验)。 */
104
- const Config = z.object({
105
- dbDir: z.string(),
106
- legacyMigration: z.string(),
107
- injectProfile: z.boolean(),
108
- profileTopN: z.number().step(1).min(1).max(64),
109
- modelCacheDir: z.string(),
110
- hfEndpoint: z.string(),
111
- ingest: z.string(),
112
- reflect: z.string(),
113
- provider: z.string(),
114
- model: z.string(),
115
- decayAfterDays: z.number().step(1).min(1).max(3650),
116
- decayImportanceBelow: z.number().min(0).max(1),
117
- injectTokenBudget: z.number().step(1).min(128).max(8192),
118
- injectItemBudgetStart: z.number().step(1).min(40).max(2e3),
119
- injectItemBudgetDecay: z.number().min(.5).max(1),
120
- injectItemBudgetFloor: z.number().step(1).min(8).max(200),
121
- rankRecencyWeight: z.number().min(0).max(2),
122
- rankProofWeight: z.number().min(0).max(2),
123
- queryRewrite: z.boolean(),
124
- autoSlot: z.boolean(),
125
- reviewScheduling: z.boolean(),
126
- assessReminder: z.boolean(),
127
- historyBackfillDays: z.number().step(1).min(0).max(3650),
128
- historyBackfillMaxTurnsPerSession: z.number().step(1).min(1).max(500),
129
- historyBackfillMaxTotalTurns: z.number().step(1).min(1).max(5e3),
130
- historyBackfillIncludeSubagents: z.boolean(),
131
- historyBackfillIncludeSeeded: z.boolean(),
132
- historyBackfillIncludeNoCwd: z.boolean(),
133
- jev: z.object({
134
- enabled: z.boolean(),
135
- apiKey: z.string(),
136
- baseUrl: z.string(),
137
- model: z.string(),
138
- timeoutMs: z.number().step(1).min(1e3).max(6e4),
139
- deferMergeAbove: z.number().min(.5).max(1),
140
- deferAcceptBelow: z.number().min(0).max(.5),
141
- contradictMinProbability: z.number().min(.5).max(1)
142
- }),
143
- language: z.string(),
144
- redactWords: z.array(z.string())
145
- });
146
- /**
147
- * 显式 resolve 步骤:默认值只在唯一的此处落地,非法值 loud 失败。
148
- * @param config - cordis.yml 传入的未校验配置。
149
- * @returns 完整解析配置。
150
- * @throws 未知键、ingest 档位非法、provider/model 只给其一、decay/预算/排序权重/历史回填规则越界时抛错。
151
- */
152
- function resolveConfig(config = {}) {
153
- for (const key of Object.keys(config)) if (!CONFIG_KEYS.has(key)) throw new Error(`dsh-engram: unknown config key "${key}"`);
154
- if (config.legacyMigration !== void 0 && config.legacyMigration !== "eager" && config.legacyMigration !== "conservative") throw new Error("dsh-engram: legacyMigration must be one of eager|conservative");
155
- if (config.ingest !== void 0 && !INGEST_MODES.has(config.ingest)) throw new Error(`dsh-engram: ingest must be one of off|light|eager, got "${String(config.ingest)}"`);
156
- if (config.reflect !== void 0 && !REFLECT_MODES.has(config.reflect)) throw new Error(`dsh-engram: reflect must be one of off|suggest|auto, got "${String(config.reflect)}"`);
157
- if (config.language !== void 0 && config.language !== "auto" && !isEngramLanguage(config.language)) throw new Error(`dsh-engram: language must be one of auto|zh|en|ru, got "${String(config.language)}"`);
158
- if (config.profileTopN !== void 0 && (!Number.isInteger(config.profileTopN) || config.profileTopN < 1 || config.profileTopN > 64)) throw new Error("dsh-engram: profileTopN must be an integer in [1, 64]");
159
- const hasProvider = config.provider !== void 0;
160
- const hasModel = config.model !== void 0;
161
- if (hasProvider !== hasModel) throw new Error("dsh-engram: provider and model must be supplied together");
162
- if (config.decayAfterDays !== void 0 && (!Number.isInteger(config.decayAfterDays) || config.decayAfterDays < 1 || config.decayAfterDays > 3650)) throw new Error("dsh-engram: decayAfterDays must be an integer in [1, 3650]");
163
- if (config.decayImportanceBelow !== void 0 && (config.decayImportanceBelow < 0 || config.decayImportanceBelow > 1)) throw new Error("dsh-engram: decayImportanceBelow must be in [0, 1]");
164
- if (config.injectTokenBudget !== void 0 && (!Number.isInteger(config.injectTokenBudget) || config.injectTokenBudget < 128 || config.injectTokenBudget > 8192)) throw new Error("dsh-engram: injectTokenBudget must be an integer in [128, 8192]");
165
- if (config.injectItemBudgetStart !== void 0 && (!Number.isInteger(config.injectItemBudgetStart) || config.injectItemBudgetStart < 40 || config.injectItemBudgetStart > 2e3)) throw new Error("dsh-engram: injectItemBudgetStart must be an integer in [40, 2000]");
166
- if (config.injectItemBudgetDecay !== void 0 && (config.injectItemBudgetDecay < .5 || config.injectItemBudgetDecay > 1)) throw new Error("dsh-engram: injectItemBudgetDecay must be in [0.5, 1]");
167
- if (config.injectItemBudgetFloor !== void 0 && (!Number.isInteger(config.injectItemBudgetFloor) || config.injectItemBudgetFloor < 8 || config.injectItemBudgetFloor > 200)) throw new Error("dsh-engram: injectItemBudgetFloor must be an integer in [8, 200]");
168
- if (config.injectItemBudgetStart !== void 0 && config.injectItemBudgetFloor !== void 0 && config.injectItemBudgetFloor > config.injectItemBudgetStart) throw new Error("dsh-engram: injectItemBudgetFloor must not exceed injectItemBudgetStart");
169
- if (config.assessReminder !== void 0 && typeof config.assessReminder !== "boolean") throw new Error("dsh-engram: assessReminder must be a boolean");
170
- if (config.rankRecencyWeight !== void 0 && (config.rankRecencyWeight < 0 || config.rankRecencyWeight > 2)) throw new Error("dsh-engram: rankRecencyWeight must be in [0, 2]");
171
- if (config.rankProofWeight !== void 0 && (config.rankProofWeight < 0 || config.rankProofWeight > 2)) throw new Error("dsh-engram: rankProofWeight must be in [0, 2]");
172
- if (config.historyBackfillDays !== void 0 && (!Number.isInteger(config.historyBackfillDays) || config.historyBackfillDays < 0 || config.historyBackfillDays > 3650)) throw new Error("dsh-engram: historyBackfillDays must be an integer in [0, 3650] (0 = unlimited)");
173
- if (config.historyBackfillMaxTurnsPerSession !== void 0 && (!Number.isInteger(config.historyBackfillMaxTurnsPerSession) || config.historyBackfillMaxTurnsPerSession < 1 || config.historyBackfillMaxTurnsPerSession > 500)) throw new Error("dsh-engram: historyBackfillMaxTurnsPerSession must be an integer in [1, 500]");
174
- if (config.historyBackfillMaxTotalTurns !== void 0 && (!Number.isInteger(config.historyBackfillMaxTotalTurns) || config.historyBackfillMaxTotalTurns < 1 || config.historyBackfillMaxTotalTurns > 5e3)) throw new Error("dsh-engram: historyBackfillMaxTotalTurns must be an integer in [1, 5000]");
175
- const jev = config.jev;
176
- if (jev !== void 0) {
177
- if (jev.enabled !== void 0 && typeof jev.enabled !== "boolean") throw new Error("dsh-engram: jev.enabled must be a boolean");
178
- if (jev.enabled === true && (jev.apiKey === void 0 || jev.apiKey === "")) throw new Error("dsh-engram: jev.enabled=true requires jev.apiKey");
179
- if (jev.timeoutMs !== void 0 && (!Number.isInteger(jev.timeoutMs) || jev.timeoutMs < 1e3 || jev.timeoutMs > 6e4)) throw new Error("dsh-engram: jev.timeoutMs must be an integer in [1000, 60000]");
180
- if (jev.deferMergeAbove !== void 0 && (jev.deferMergeAbove < .5 || jev.deferMergeAbove > 1)) throw new Error("dsh-engram: jev.deferMergeAbove must be in [0.5, 1]");
181
- if (jev.deferAcceptBelow !== void 0 && (jev.deferAcceptBelow < 0 || jev.deferAcceptBelow > .5)) throw new Error("dsh-engram: jev.deferAcceptBelow must be in [0, 0.5]");
182
- if (jev.contradictMinProbability !== void 0 && (jev.contradictMinProbability < .5 || jev.contradictMinProbability > 1)) throw new Error("dsh-engram: jev.contradictMinProbability must be in [0.5, 1]");
183
- if ((jev.deferAcceptBelow ?? .15) >= (jev.deferMergeAbove ?? .85)) throw new Error("dsh-engram: jev.deferAcceptBelow must be less than jev.deferMergeAbove");
184
- }
185
- const dbDir = config.dbDir ?? join(homedir(), ".dsh", "engram");
186
- return {
187
- dbDir,
188
- legacyMigration: config.legacyMigration ?? "eager",
189
- injectProfile: config.injectProfile ?? true,
190
- profileTopN: config.profileTopN ?? 8,
191
- modelCacheDir: config.modelCacheDir ?? join(dbDir, "models"),
192
- hfEndpoint: config.hfEndpoint,
193
- ingest: config.ingest ?? "off",
194
- reflect: config.reflect ?? "off",
195
- language: resolveLanguage(config.language ?? "auto"),
196
- redactWords: config.redactWords ?? [],
197
- routeOverride: hasProvider && hasModel ? {
198
- provider: config.provider,
199
- model: config.model
200
- } : void 0,
201
- decayAfterDays: config.decayAfterDays ?? 30,
202
- decayImportanceBelow: config.decayImportanceBelow ?? .3,
203
- injectTokenBudget: config.injectTokenBudget ?? 1024,
204
- injectItemBudgetStart: config.injectItemBudgetStart ?? 160,
205
- injectItemBudgetDecay: config.injectItemBudgetDecay ?? .9,
206
- injectItemBudgetFloor: config.injectItemBudgetFloor ?? 24,
207
- assessReminder: config.assessReminder ?? true,
208
- rankRecencyWeight: config.rankRecencyWeight ?? .2,
209
- rankProofWeight: config.rankProofWeight ?? .1,
210
- queryRewrite: config.queryRewrite ?? true,
211
- autoSlot: config.autoSlot ?? true,
212
- reviewScheduling: config.reviewScheduling ?? true,
213
- historyBackfill: {
214
- days: config.historyBackfillDays ?? 7,
215
- maxTurnsPerSession: config.historyBackfillMaxTurnsPerSession ?? 20,
216
- maxTotalTurns: config.historyBackfillMaxTotalTurns ?? 200,
217
- includeSubagents: config.historyBackfillIncludeSubagents ?? false,
218
- includeSeeded: config.historyBackfillIncludeSeeded ?? false,
219
- includeNoCwd: config.historyBackfillIncludeNoCwd ?? false
220
- },
221
- jev: {
222
- enabled: config.jev?.enabled ?? false,
223
- apiKey: config.jev?.apiKey,
224
- baseUrl: config.jev?.baseUrl ?? "https://api.typesafe.ai",
225
- model: config.jev?.model ?? "jev-latest",
226
- timeoutMs: config.jev?.timeoutMs ?? 3e3,
227
- deferMergeAbove: config.jev?.deferMergeAbove ?? .85,
228
- deferAcceptBelow: config.jev?.deferAcceptBelow ?? .15,
229
- contradictMinProbability: config.jev?.contradictMinProbability ?? .8
230
- }
231
- };
232
- }
233
- //#endregion
234
54
  //#region src/i18n/catalog/core.ts
235
55
  /**
236
56
  * Словарь: ядро плагина — профиль сессии, бюджет токенов, предложение экскурсии,
@@ -288,6 +108,7 @@ const zh$4 = {
288
108
  "core.warnConsolidationFailed": "[dsh-engram] 闭馆整理失败(不影响对话):",
289
109
  "core.warnEmbedderUnavailable": "[dsh-engram] 嵌入器不可用,检索降级为纯关键词模式:",
290
110
  "core.warnRoomFull": "[dsh-engram] 房间已满,自动开新房「{room}」(可在管理面板翻新清单中人工拆分/命名)",
111
+ "core.warnJevLegacyFields": "[dsh-engram] {where} 中的 jev.{field} 已不再读取:令牌与地址现取自 jev.provider 所指的 DSH 提供商——请把密钥迁入该提供商的密钥库,并删除这个字段",
291
112
  "core.warnSlotsBackfilled": "[dsh-engram] 存量记忆排桩完成:{count} 条已钉入宫殿({path})",
292
113
  "core.logReflectDone": "[dsh-engram] 信念巩固完成({scope}):新建 {formed},细化 {refined},维持 {confirmed},否定 {refuted}",
293
114
  "core.logConsolidationDone": "[dsh-engram] 闭馆整理完成:归档 {archived},合并 {merged},跳过 {skipped}({ms} ms)",
@@ -341,6 +162,7 @@ const en$4 = {
341
162
  "core.warnConsolidationFailed": "[dsh-engram] Closing-time consolidation failed (conversation unaffected):",
342
163
  "core.warnEmbedderUnavailable": "[dsh-engram] Embedder unavailable; retrieval degrades to keyword-only mode:",
343
164
  "core.warnRoomFull": "[dsh-engram] Room full; opening a new room “{room}” automatically (split or rename it by hand in the panel’s slot-list view)",
165
+ "core.warnJevLegacyFields": "[dsh-engram] jev.{field} in {where} is no longer read: the token and endpoint now come from the DSH provider named by jev.provider — move the key into that provider’s credential store and delete the field",
344
166
  "core.warnSlotsBackfilled": "[dsh-engram] Existing memories slotted: {count} pinned into the palace ({path})",
345
167
  "core.logReflectDone": "[dsh-engram] Belief consolidation done ({scope}): {formed} formed, {refined} refined, {confirmed} confirmed, {refuted} refuted",
346
168
  "core.logConsolidationDone": "[dsh-engram] Closing-time consolidation done: {archived} archived, {merged} merged, {skipped} skipped ({ms} ms)",
@@ -394,6 +216,7 @@ const ru$4 = {
394
216
  "core.warnConsolidationFailed": "[dsh-engram] Закрытие зала не удалось (диалог не затронут):",
395
217
  "core.warnEmbedderUnavailable": "[dsh-engram] Встраиватель недоступен, поиск деградирует до режима «только ключевые слова»:",
396
218
  "core.warnRoomFull": "[dsh-engram] Комната заполнена, автоматически открывается новая «{room}» (её можно вручную разделить или переименовать в списке обновления панели)",
219
+ "core.warnJevLegacyFields": "[dsh-engram] jev.{field} в {where} больше не читается: ключ и адрес берутся у провайдера DSH, названного в jev.provider — перенесите ключ в хранилище секретов этого провайдера и удалите поле",
397
220
  "core.warnSlotsBackfilled": "[dsh-engram] Разметка существующих воспоминаний завершена: {count} закреплено во дворце ({path})",
398
221
  "core.logReflectDone": "[dsh-engram] Закрепление убеждений завершено ({scope}): создано {formed}, уточнено {refined}, подтверждено {confirmed}, опровергнуто {refuted}",
399
222
  "core.logConsolidationDone": "[dsh-engram] Закрытие зала завершено: архивировано {archived}, объединено {merged}, пропущено {skipped} ({ms} ms)",
@@ -516,7 +339,10 @@ const zh$2 = {
516
339
  "misc.exportHeading": "# dsh-engram 导出({scope})",
517
340
  "misc.exportRecordLine": "- [{status}/{kind}] {content}(id={id},importance {importance})",
518
341
  "misc.exportEdgesHeading": "## 关系边",
519
- "misc.importInvalidPayload": "导入文件结构校验失败:{error}",
342
+ "misc.importInvalidPayload": "导入文件结构有误:{error}",
343
+ "misc.importBodyTooLarge": "导入文件过大:超过 {limit} 上限。请拆分导出文件后重试,或改用 engram_import 工具按文件路径导入。",
344
+ "misc.importBodyMalformed": "导入请求体不是合法 JSON:{error}",
345
+ "misc.importBodyNotObject": "导入请求体必须是 JSON 对象。",
520
346
  "misc.backfillCannotStart": "无法启动回填",
521
347
  "misc.archivePathOutsideDbDir": "archivePath 必须在 dbDir 内",
522
348
  "misc.restoreFailed": "恢复失败:{message}",
@@ -541,9 +367,15 @@ const zh$2 = {
541
367
  "misc.refurbLowPlacardReason": "{slot}门牌得分 {score} < 0.5(不合唯一/差异化/带日期纪律),建议重写铭牌。",
542
368
  "misc.placardImprovementHint": "门牌不合规(宫殿纪律:唯一 · 差异化 · 带日期):建议用 engram_update 的 placard 参数挂一个 4-30 字、含日期锚点、与同房其他门牌前 6 字不重复的铭牌。",
543
369
  "misc.jevEnabledMustBeBoolean": "invalid: jev.enabled 必须是布尔值",
544
- "misc.jevApiKeyMustBeString": "invalid: jev.apiKey 必须是字符串",
545
- "misc.jevBaseUrlMustBeString": "invalid: jev.baseUrl 必须是字符串",
546
- "misc.jevBaseUrlMustBeHttp": "invalid: jev.baseUrl 必须是 http(s) URL",
370
+ "misc.jevProviderMustBeString": "invalid: jev.provider 必须是字符串",
371
+ "misc.jevProviderMustBeSelected": "Jev:请先选择提供商和模型",
372
+ "misc.jevHostLlmUnavailable": "Jev:宿主的模型服务不可用,无法获取提供商列表",
373
+ "misc.jevProviderNotConfigured": "Jev:提供商「{provider}」未在 DSH 中配置",
374
+ "misc.jevProviderHasNoBaseUrl": "Jev:提供商「{provider}」在 DSH 配置中没有 baseURL",
375
+ "misc.jevProviderKeyMissing": "Jev:提供商「{provider}」没有密钥(引用「{ref}」为空)",
376
+ "misc.jevProviderUnresolved": "Jev:没有提供商——面板、插件设置和会话路由都没有指定",
377
+ "misc.jevModelNotPicked": "Jev:提供商「{provider}」的 DSH 设置里没有 JEV 模型,请手动指定模型",
378
+ "misc.jevEndpointMustBeHttp": "invalid: jev.endpoint 必须是 http(s) URL",
547
379
  "misc.jevModelMustNotBeEmpty": "invalid: jev.model 不能为空",
548
380
  "misc.jevTimeoutMsMustBeInteger": "invalid: jev.timeoutMs 必须是 1000-60000 的整数毫秒"
549
381
  };
@@ -554,7 +386,10 @@ const en$2 = {
554
386
  "misc.exportHeading": "# dsh-engram export ({scope})",
555
387
  "misc.exportRecordLine": "- [{status}/{kind}] {content} (id={id}, importance {importance})",
556
388
  "misc.exportEdgesHeading": "## Relation edges",
557
- "misc.importInvalidPayload": "import file structure validation failed: {error}",
389
+ "misc.importInvalidPayload": "import file structure is invalid: {error}",
390
+ "misc.importBodyTooLarge": "import file is too large: over the {limit} limit. Split the export and retry, or use the engram_import tool with a file path.",
391
+ "misc.importBodyMalformed": "import request body is not valid JSON: {error}",
392
+ "misc.importBodyNotObject": "import request body must be a JSON object.",
558
393
  "misc.backfillCannotStart": "cannot start backfill",
559
394
  "misc.archivePathOutsideDbDir": "archivePath must be inside dbDir",
560
395
  "misc.restoreFailed": "restore failed: {message}",
@@ -579,9 +414,15 @@ const en$2 = {
579
414
  "misc.refurbLowPlacardReason": "{slot}placard score {score} < 0.5 (violates the unique/distinctive/date-anchored discipline); rewrite the placard.",
580
415
  "misc.placardImprovementHint": "placard does not comply (palace discipline: unique · distinctive · date-anchored): attach a 4-30 character placard with the placard parameter of engram_update, including a date anchor and not repeating the first 6 characters of another placard in the same room.",
581
416
  "misc.jevEnabledMustBeBoolean": "invalid: jev.enabled must be a boolean",
582
- "misc.jevApiKeyMustBeString": "invalid: jev.apiKey must be a string",
583
- "misc.jevBaseUrlMustBeString": "invalid: jev.baseUrl must be a string",
584
- "misc.jevBaseUrlMustBeHttp": "invalid: jev.baseUrl must be an http(s) URL",
417
+ "misc.jevProviderMustBeString": "invalid: jev.provider must be a string",
418
+ "misc.jevProviderMustBeSelected": "Jev: choose a provider and a model first",
419
+ "misc.jevHostLlmUnavailable": "Jev: the host LLM service is unavailable, so providers cannot be listed",
420
+ "misc.jevProviderNotConfigured": "Jev: provider \"{provider}\" is not configured in DSH",
421
+ "misc.jevProviderHasNoBaseUrl": "Jev: provider \"{provider}\" has no baseURL in the DSH configuration",
422
+ "misc.jevProviderKeyMissing": "Jev: provider \"{provider}\" has no key (credential \"{ref}\" is empty)",
423
+ "misc.jevProviderUnresolved": "Jev: no provider — neither the panel, nor the plugin settings, nor the session route names one",
424
+ "misc.jevModelNotPicked": "Jev: provider \"{provider}\" has no JEV model in its DSH settings; name the model explicitly",
425
+ "misc.jevEndpointMustBeHttp": "invalid: jev.endpoint must be an http(s) URL",
585
426
  "misc.jevModelMustNotBeEmpty": "invalid: jev.model must not be empty",
586
427
  "misc.jevTimeoutMsMustBeInteger": "invalid: jev.timeoutMs must be an integer number of milliseconds between 1000 and 60000"
587
428
  };
@@ -592,7 +433,10 @@ const ru$2 = {
592
433
  "misc.exportHeading": "# Экспорт dsh-engram ({scope})",
593
434
  "misc.exportRecordLine": "- [{status}/{kind}] {content} (id={id}, importance {importance})",
594
435
  "misc.exportEdgesHeading": "## Связи",
595
- "misc.importInvalidPayload": "проверка структуры файла импорта не пройдена: {error}",
436
+ "misc.importInvalidPayload": "структура файла импорта некорректна: {error}",
437
+ "misc.importBodyTooLarge": "файл импорта слишком большой: превышен предел {limit}. Разделите экспорт и повторите либо используйте инструмент engram_import с путём к файлу.",
438
+ "misc.importBodyMalformed": "тело запроса импорта — не корректный JSON: {error}",
439
+ "misc.importBodyNotObject": "тело запроса импорта должно быть JSON-объектом.",
596
440
  "misc.backfillCannotStart": "не удалось запустить заполнение",
597
441
  "misc.archivePathOutsideDbDir": "archivePath должен находиться внутри dbDir",
598
442
  "misc.restoreFailed": "восстановление не удалось: {message}",
@@ -617,9 +461,15 @@ const ru$2 = {
617
461
  "misc.refurbLowPlacardReason": "{slot}оценка таблички {score} < 0.5 (нарушает дисциплину уникальности/различимости/даты); перепишите табличку.",
618
462
  "misc.placardImprovementHint": "табличка не соответствует дисциплине дворца (уникальность · различимость · дата): прикрепите параметром placard инструмента engram_update табличку из 4-30 символов с датой, первые 6 символов которой не совпадают с другими табличками той же комнаты.",
619
463
  "misc.jevEnabledMustBeBoolean": "invalid: jev.enabled должно быть логическим значением",
620
- "misc.jevApiKeyMustBeString": "invalid: jev.apiKey должно быть строкой",
621
- "misc.jevBaseUrlMustBeString": "invalid: jev.baseUrl должно быть строкой",
622
- "misc.jevBaseUrlMustBeHttp": "invalid: jev.baseUrl должно быть URL со схемой http(s)",
464
+ "misc.jevProviderMustBeString": "invalid: jev.provider должно быть строкой",
465
+ "misc.jevProviderMustBeSelected": "Jev: сначала выберите провайдера и модель",
466
+ "misc.jevHostLlmUnavailable": "Jev: сервис моделей хоста недоступен, список провайдеров получить нельзя",
467
+ "misc.jevProviderNotConfigured": "Jev: провайдер «{provider}» не настроен в DSH",
468
+ "misc.jevProviderHasNoBaseUrl": "Jev: у провайдера «{provider}» в настройках DSH нет baseURL",
469
+ "misc.jevProviderKeyMissing": "Jev: у провайдера «{provider}» нет ключа (ссылка «{ref}» пуста)",
470
+ "misc.jevProviderUnresolved": "Jev: провайдер не назван — ни панелью, ни настройками плагина, ни маршрутом сессии",
471
+ "misc.jevModelNotPicked": "Jev: у провайдера «{provider}» в настройках DSH нет JEV-модели — укажите модель вручную",
472
+ "misc.jevEndpointMustBeHttp": "invalid: jev.endpoint должно быть URL со схемой http(s)",
623
473
  "misc.jevModelMustNotBeEmpty": "invalid: jev.model не может быть пустым",
624
474
  "misc.jevTimeoutMsMustBeInteger": "invalid: jev.timeoutMs должно быть целым числом миллисекунд от 1000 до 60000"
625
475
  };
@@ -1818,6 +1668,245 @@ function message(key, params) {
1818
1668
  return messageIn(current, key, params);
1819
1669
  }
1820
1670
  //#endregion
1671
+ //#region src/jev/stale.ts
1672
+ /**
1673
+ * Поля Jev прежнего формата: ключ и адрес когда-то хранились у самого плагина
1674
+ * (`jev.apiKey`, `jev.baseUrl`). После переезда к провайдеру хоста они больше не
1675
+ * читаются, но продолжают лежать в уже написанных конфигурациях — и человек вправе
1676
+ * об этом узнать, а не гадать, почему судья молчит.
1677
+ *
1678
+ * Предупреждение одноразовое на процесс, причём отдельно для каждого источника и
1679
+ * поля: перекрытие панели читается при каждой сборке судьи, и без счётчика один и
1680
+ * тот же текст повторялся бы на каждой записи. Источники разделены намеренно —
1681
+ * `cordis.yml` и `jev-config.json` правятся в разных местах, и заглушить один
1682
+ * предупреждением о другом значило бы оставить половину работы незамеченной.
1683
+ *
1684
+ * @module @kenz1117/dsh-engram/jev/stale
1685
+ */
1686
+ /** Прежние поля Jev, пережившие переезд ключа и адреса к провайдеру хоста. */
1687
+ const LEGACY_FIELDS = ["apiKey", "baseUrl"];
1688
+ /** Уже прозвучавшие предупреждения: ключ — «источник + поле». */
1689
+ const warned = /* @__PURE__ */ new Set();
1690
+ /**
1691
+ * Имена полей прежнего формата, реально присутствующих в объекте.
1692
+ * @param value - разобранный JSON перекрытия или подконфигурация `jev` из cordis.yml.
1693
+ * @returns найденные имена полей; пустой массив — объект чист.
1694
+ */
1695
+ function legacyJevFields(value) {
1696
+ if (value === null || typeof value !== "object") return [];
1697
+ const raw = value;
1698
+ return LEGACY_FIELDS.filter((field) => raw[field] !== void 0);
1699
+ }
1700
+ /**
1701
+ * Напомнить один раз, что поля прежнего формата игнорируются, и сказать, куда
1702
+ * переехал ключ. Текст берётся из служебного словаря: язык — состояние процесса.
1703
+ * @param where - где нашлись поля: `cordis.yml` или `jev-config.json`.
1704
+ * @param fields - имена полей (см. `legacyJevFields`).
1705
+ */
1706
+ function noteLegacyJevFields(where, fields) {
1707
+ for (const field of fields) {
1708
+ const seen = `${where}|${field}`;
1709
+ if (warned.has(seen)) continue;
1710
+ warned.add(seen);
1711
+ console.warn(message("core.warnJevLegacyFields", {
1712
+ where,
1713
+ field
1714
+ }));
1715
+ }
1716
+ }
1717
+ //#endregion
1718
+ //#region src/config.ts
1719
+ /**
1720
+ * 插件 Config:所有部署可变项集中于此,禁止在实现里内嵌默认值。
1721
+ * @module @kenz1117/dsh-engram/config
1722
+ */
1723
+ /** 合法配置键集合(未知键 loud 失败)。 */
1724
+ const CONFIG_KEYS = /* @__PURE__ */ new Set([
1725
+ "legacyMigration",
1726
+ "dbDir",
1727
+ "injectProfile",
1728
+ "profileTopN",
1729
+ "modelCacheDir",
1730
+ "hfEndpoint",
1731
+ "ingest",
1732
+ "reflect",
1733
+ "provider",
1734
+ "model",
1735
+ "decayAfterDays",
1736
+ "decayImportanceBelow",
1737
+ "injectTokenBudget",
1738
+ "injectItemBudgetStart",
1739
+ "injectItemBudgetDecay",
1740
+ "injectItemBudgetFloor",
1741
+ "rankRecencyWeight",
1742
+ "rankProofWeight",
1743
+ "queryRewrite",
1744
+ "autoSlot",
1745
+ "reviewScheduling",
1746
+ "assessReminder",
1747
+ "historyBackfillDays",
1748
+ "historyBackfillMaxTurnsPerSession",
1749
+ "historyBackfillMaxTotalTurns",
1750
+ "historyBackfillIncludeSubagents",
1751
+ "historyBackfillIncludeSeeded",
1752
+ "historyBackfillIncludeNoCwd",
1753
+ "jev",
1754
+ "language",
1755
+ "redactWords"
1756
+ ]);
1757
+ const INGEST_MODES = /* @__PURE__ */ new Set([
1758
+ "off",
1759
+ "light",
1760
+ "eager"
1761
+ ]);
1762
+ const REFLECT_MODES = /* @__PURE__ */ new Set([
1763
+ "off",
1764
+ "suggest",
1765
+ "auto"
1766
+ ]);
1767
+ /** Schemastery 校验面(cordis.yml 读取时校验)。 */
1768
+ const Config = z.object({
1769
+ dbDir: z.string(),
1770
+ legacyMigration: z.string(),
1771
+ injectProfile: z.boolean(),
1772
+ profileTopN: z.number().step(1).min(1).max(64),
1773
+ modelCacheDir: z.string(),
1774
+ hfEndpoint: z.string(),
1775
+ ingest: z.string(),
1776
+ reflect: z.string(),
1777
+ provider: z.string(),
1778
+ model: z.string(),
1779
+ decayAfterDays: z.number().step(1).min(1).max(3650),
1780
+ decayImportanceBelow: z.number().min(0).max(1),
1781
+ injectTokenBudget: z.number().step(1).min(128).max(8192),
1782
+ injectItemBudgetStart: z.number().step(1).min(40).max(2e3),
1783
+ injectItemBudgetDecay: z.number().min(.5).max(1),
1784
+ injectItemBudgetFloor: z.number().step(1).min(8).max(200),
1785
+ rankRecencyWeight: z.number().min(0).max(2),
1786
+ rankProofWeight: z.number().min(0).max(2),
1787
+ queryRewrite: z.boolean(),
1788
+ autoSlot: z.boolean(),
1789
+ reviewScheduling: z.boolean(),
1790
+ assessReminder: z.boolean(),
1791
+ historyBackfillDays: z.number().step(1).min(0).max(3650),
1792
+ historyBackfillMaxTurnsPerSession: z.number().step(1).min(1).max(500),
1793
+ historyBackfillMaxTotalTurns: z.number().step(1).min(1).max(5e3),
1794
+ historyBackfillIncludeSubagents: z.boolean(),
1795
+ historyBackfillIncludeSeeded: z.boolean(),
1796
+ historyBackfillIncludeNoCwd: z.boolean(),
1797
+ jev: z.object({
1798
+ enabled: z.boolean(),
1799
+ provider: z.string(),
1800
+ model: z.string(),
1801
+ endpoint: z.string(),
1802
+ timeoutMs: z.number().step(1).min(1e3).max(6e4),
1803
+ deferMergeAbove: z.number().min(.5).max(1),
1804
+ deferAcceptBelow: z.number().min(0).max(.5),
1805
+ contradictMinProbability: z.number().min(.5).max(1)
1806
+ }),
1807
+ language: z.string(),
1808
+ redactWords: z.array(z.string())
1809
+ });
1810
+ /**
1811
+ * 显式 resolve 步骤:默认值只在唯一的此处落地,非法值 loud 失败。
1812
+ * @param config - cordis.yml 传入的未校验配置。
1813
+ * @returns 完整解析配置。
1814
+ * @throws 未知键、ingest 档位非法、provider/model 只给其一、decay/预算/排序权重/历史回填规则越界时抛错。
1815
+ */
1816
+ function resolveConfig(config = {}) {
1817
+ for (const key of Object.keys(config)) if (!CONFIG_KEYS.has(key)) throw new Error(`dsh-engram: unknown config key "${key}"`);
1818
+ if (config.legacyMigration !== void 0 && config.legacyMigration !== "eager" && config.legacyMigration !== "conservative") throw new Error("dsh-engram: legacyMigration must be one of eager|conservative");
1819
+ if (config.ingest !== void 0 && !INGEST_MODES.has(config.ingest)) throw new Error(`dsh-engram: ingest must be one of off|light|eager, got "${String(config.ingest)}"`);
1820
+ if (config.reflect !== void 0 && !REFLECT_MODES.has(config.reflect)) throw new Error(`dsh-engram: reflect must be one of off|suggest|auto, got "${String(config.reflect)}"`);
1821
+ if (config.language !== void 0 && config.language !== "auto" && !isEngramLanguage(config.language)) throw new Error(`dsh-engram: language must be one of auto|zh|en|ru, got "${String(config.language)}"`);
1822
+ if (config.profileTopN !== void 0 && (!Number.isInteger(config.profileTopN) || config.profileTopN < 1 || config.profileTopN > 64)) throw new Error("dsh-engram: profileTopN must be an integer in [1, 64]");
1823
+ const hasProvider = config.provider !== void 0;
1824
+ const hasModel = config.model !== void 0;
1825
+ if (hasProvider !== hasModel) throw new Error("dsh-engram: provider and model must be supplied together");
1826
+ if (config.decayAfterDays !== void 0 && (!Number.isInteger(config.decayAfterDays) || config.decayAfterDays < 1 || config.decayAfterDays > 3650)) throw new Error("dsh-engram: decayAfterDays must be an integer in [1, 3650]");
1827
+ if (config.decayImportanceBelow !== void 0 && (config.decayImportanceBelow < 0 || config.decayImportanceBelow > 1)) throw new Error("dsh-engram: decayImportanceBelow must be in [0, 1]");
1828
+ if (config.injectTokenBudget !== void 0 && (!Number.isInteger(config.injectTokenBudget) || config.injectTokenBudget < 128 || config.injectTokenBudget > 8192)) throw new Error("dsh-engram: injectTokenBudget must be an integer in [128, 8192]");
1829
+ if (config.injectItemBudgetStart !== void 0 && (!Number.isInteger(config.injectItemBudgetStart) || config.injectItemBudgetStart < 40 || config.injectItemBudgetStart > 2e3)) throw new Error("dsh-engram: injectItemBudgetStart must be an integer in [40, 2000]");
1830
+ if (config.injectItemBudgetDecay !== void 0 && (config.injectItemBudgetDecay < .5 || config.injectItemBudgetDecay > 1)) throw new Error("dsh-engram: injectItemBudgetDecay must be in [0.5, 1]");
1831
+ if (config.injectItemBudgetFloor !== void 0 && (!Number.isInteger(config.injectItemBudgetFloor) || config.injectItemBudgetFloor < 8 || config.injectItemBudgetFloor > 200)) throw new Error("dsh-engram: injectItemBudgetFloor must be an integer in [8, 200]");
1832
+ if (config.injectItemBudgetStart !== void 0 && config.injectItemBudgetFloor !== void 0 && config.injectItemBudgetFloor > config.injectItemBudgetStart) throw new Error("dsh-engram: injectItemBudgetFloor must not exceed injectItemBudgetStart");
1833
+ if (config.assessReminder !== void 0 && typeof config.assessReminder !== "boolean") throw new Error("dsh-engram: assessReminder must be a boolean");
1834
+ if (config.rankRecencyWeight !== void 0 && (config.rankRecencyWeight < 0 || config.rankRecencyWeight > 2)) throw new Error("dsh-engram: rankRecencyWeight must be in [0, 2]");
1835
+ if (config.rankProofWeight !== void 0 && (config.rankProofWeight < 0 || config.rankProofWeight > 2)) throw new Error("dsh-engram: rankProofWeight must be in [0, 2]");
1836
+ if (config.historyBackfillDays !== void 0 && (!Number.isInteger(config.historyBackfillDays) || config.historyBackfillDays < 0 || config.historyBackfillDays > 3650)) throw new Error("dsh-engram: historyBackfillDays must be an integer in [0, 3650] (0 = unlimited)");
1837
+ if (config.historyBackfillMaxTurnsPerSession !== void 0 && (!Number.isInteger(config.historyBackfillMaxTurnsPerSession) || config.historyBackfillMaxTurnsPerSession < 1 || config.historyBackfillMaxTurnsPerSession > 500)) throw new Error("dsh-engram: historyBackfillMaxTurnsPerSession must be an integer in [1, 500]");
1838
+ if (config.historyBackfillMaxTotalTurns !== void 0 && (!Number.isInteger(config.historyBackfillMaxTotalTurns) || config.historyBackfillMaxTotalTurns < 1 || config.historyBackfillMaxTotalTurns > 5e3)) throw new Error("dsh-engram: historyBackfillMaxTotalTurns must be an integer in [1, 5000]");
1839
+ const jev = config.jev;
1840
+ if (jev !== void 0) {
1841
+ const legacy = legacyJevFields(jev);
1842
+ if (legacy.length > 0) noteLegacyJevFields("cordis.yml", legacy);
1843
+ if (jev.enabled !== void 0 && typeof jev.enabled !== "boolean") throw new Error("dsh-engram: jev.enabled must be a boolean");
1844
+ if (jev.provider !== void 0 && (typeof jev.provider !== "string" || jev.provider.trim() === "")) throw new Error("dsh-engram: jev.provider must be a non-empty string");
1845
+ if (jev.model !== void 0 && (typeof jev.model !== "string" || jev.model.trim() === "")) throw new Error("dsh-engram: jev.model must be a non-empty string");
1846
+ if (jev.endpoint !== void 0) {
1847
+ let scheme = "";
1848
+ try {
1849
+ scheme = new URL(jev.endpoint).protocol;
1850
+ } catch {
1851
+ throw new Error("dsh-engram: jev.endpoint must be an http(s) URL");
1852
+ }
1853
+ if (scheme !== "https:" && scheme !== "http:") throw new Error("dsh-engram: jev.endpoint must be an http(s) URL");
1854
+ }
1855
+ if (jev.timeoutMs !== void 0 && (!Number.isInteger(jev.timeoutMs) || jev.timeoutMs < 1e3 || jev.timeoutMs > 6e4)) throw new Error("dsh-engram: jev.timeoutMs must be an integer in [1000, 60000]");
1856
+ if (jev.deferMergeAbove !== void 0 && (jev.deferMergeAbove < .5 || jev.deferMergeAbove > 1)) throw new Error("dsh-engram: jev.deferMergeAbove must be in [0.5, 1]");
1857
+ if (jev.deferAcceptBelow !== void 0 && (jev.deferAcceptBelow < 0 || jev.deferAcceptBelow > .5)) throw new Error("dsh-engram: jev.deferAcceptBelow must be in [0, 0.5]");
1858
+ if (jev.contradictMinProbability !== void 0 && (jev.contradictMinProbability < .5 || jev.contradictMinProbability > 1)) throw new Error("dsh-engram: jev.contradictMinProbability must be in [0.5, 1]");
1859
+ if ((jev.deferAcceptBelow ?? .15) >= (jev.deferMergeAbove ?? .85)) throw new Error("dsh-engram: jev.deferAcceptBelow must be less than jev.deferMergeAbove");
1860
+ }
1861
+ const dbDir = config.dbDir ?? join(homedir(), ".dsh", "engram");
1862
+ return {
1863
+ dbDir,
1864
+ legacyMigration: config.legacyMigration ?? "eager",
1865
+ injectProfile: config.injectProfile ?? true,
1866
+ profileTopN: config.profileTopN ?? 8,
1867
+ modelCacheDir: config.modelCacheDir ?? join(dbDir, "models"),
1868
+ hfEndpoint: config.hfEndpoint,
1869
+ ingest: config.ingest ?? "off",
1870
+ reflect: config.reflect ?? "off",
1871
+ language: resolveLanguage(config.language ?? "auto"),
1872
+ redactWords: config.redactWords ?? [],
1873
+ routeOverride: hasProvider && hasModel ? {
1874
+ provider: config.provider,
1875
+ model: config.model
1876
+ } : void 0,
1877
+ decayAfterDays: config.decayAfterDays ?? 30,
1878
+ decayImportanceBelow: config.decayImportanceBelow ?? .3,
1879
+ injectTokenBudget: config.injectTokenBudget ?? 1024,
1880
+ injectItemBudgetStart: config.injectItemBudgetStart ?? 160,
1881
+ injectItemBudgetDecay: config.injectItemBudgetDecay ?? .9,
1882
+ injectItemBudgetFloor: config.injectItemBudgetFloor ?? 24,
1883
+ assessReminder: config.assessReminder ?? true,
1884
+ rankRecencyWeight: config.rankRecencyWeight ?? .2,
1885
+ rankProofWeight: config.rankProofWeight ?? .1,
1886
+ queryRewrite: config.queryRewrite ?? true,
1887
+ autoSlot: config.autoSlot ?? true,
1888
+ reviewScheduling: config.reviewScheduling ?? true,
1889
+ historyBackfill: {
1890
+ days: config.historyBackfillDays ?? 7,
1891
+ maxTurnsPerSession: config.historyBackfillMaxTurnsPerSession ?? 20,
1892
+ maxTotalTurns: config.historyBackfillMaxTotalTurns ?? 200,
1893
+ includeSubagents: config.historyBackfillIncludeSubagents ?? false,
1894
+ includeSeeded: config.historyBackfillIncludeSeeded ?? false,
1895
+ includeNoCwd: config.historyBackfillIncludeNoCwd ?? false
1896
+ },
1897
+ jev: {
1898
+ enabled: config.jev?.enabled ?? false,
1899
+ provider: config.jev?.provider,
1900
+ model: config.jev?.model,
1901
+ endpoint: config.jev?.endpoint,
1902
+ timeoutMs: config.jev?.timeoutMs ?? 3e3,
1903
+ deferMergeAbove: config.jev?.deferMergeAbove ?? .85,
1904
+ deferAcceptBelow: config.jev?.deferAcceptBelow ?? .15,
1905
+ contradictMinProbability: config.jev?.contradictMinProbability ?? .8
1906
+ }
1907
+ };
1908
+ }
1909
+ //#endregion
1821
1910
  //#region src/i18n/patterns.ts
1822
1911
  /**
1823
1912
  * Языкозависимые образцы распознавания ввода.
@@ -2919,6 +3008,7 @@ async function ingestPreviousTurn(deps) {
2919
3008
  skipped: raw.trim() === "" ? "empty-answer" : "unparseable-output"
2920
3009
  };
2921
3010
  const embedder = await deps.embedder;
3011
+ const judge = deps.resolveJudge?.();
2922
3012
  const writtenContents = [];
2923
3013
  let written = 0;
2924
3014
  let merged = 0;
@@ -2971,8 +3061,8 @@ async function ingestPreviousTurn(deps) {
2971
3061
  continue;
2972
3062
  }
2973
3063
  const vector = embedder === void 0 ? void 0 : (await embedder.embed([content]))[0];
2974
- const decision = await decideWrite(target, kind, vector, deps.judge === void 0 ? {} : {
2975
- judge: deps.judge,
3064
+ const decision = await decideWrite(target, kind, vector, judge === void 0 ? {} : {
3065
+ judge,
2976
3066
  content
2977
3067
  });
2978
3068
  if (decision.disposition === "merge") {
@@ -2995,7 +3085,7 @@ async function ingestPreviousTurn(deps) {
2995
3085
  ...deps.history === true ? { initialReviewAt: null } : {}
2996
3086
  });
2997
3087
  if (decision.disposition === "defer") {
2998
- const neighbors = deps.judge === void 0 ? [decision.neighbor] : await confirmContradictions(deps.judge, content, [decision.neighbor]) ?? [decision.neighbor];
3088
+ const neighbors = judge === void 0 ? [decision.neighbor] : await confirmContradictions(judge, content, [decision.neighbor]) ?? [decision.neighbor];
2999
3089
  for (const neighbor of neighbors) {
3000
3090
  if (neighbor.id === record.id) continue;
3001
3091
  await target.linkEdge(record.id, neighbor.id, "contradicts");
@@ -3160,7 +3250,7 @@ async function replayPendingIngests(deps) {
3160
3250
  routeOverride: deps.routeOverride,
3161
3251
  call: deps.call,
3162
3252
  logRequest: deps.logRequest,
3163
- ...deps.judge === void 0 ? {} : { judge: deps.judge },
3253
+ ...deps.resolveJudge === void 0 ? {} : { resolveJudge: deps.resolveJudge },
3164
3254
  signal: deps.signal
3165
3255
  });
3166
3256
  if (outcome.skipped === "unparseable-output" || outcome.skipped === "empty-answer") {
@@ -3404,6 +3494,7 @@ async function runHistoryBackfill(deps, defaults, overrides, onProgress, signal)
3404
3494
  provider: overrides.provider,
3405
3495
  model: overrides.model
3406
3496
  } : deps.routeOverride;
3497
+ const judge = deps.resolveJudge?.();
3407
3498
  const failures = [];
3408
3499
  /** 内部可变累加器(对外以只读的 HistoryRunProgress 暴露)。 */
3409
3500
  const progress = {
@@ -3436,7 +3527,7 @@ async function runHistoryBackfill(deps, defaults, overrides, onProgress, signal)
3436
3527
  routeOverride,
3437
3528
  call: deps.call,
3438
3529
  logRequest: deps.logRequest,
3439
- ...deps.judge === void 0 ? {} : { judge: deps.judge },
3530
+ ...judge === void 0 ? {} : { judge },
3440
3531
  signal,
3441
3532
  throttle: true,
3442
3533
  history: true
@@ -4025,7 +4116,7 @@ const parseEntity = (raw, index) => {
4025
4116
  * 空文件(records 为空数组)合法——预览为空、提交零写入。
4026
4117
  */
4027
4118
  function parseImportData(raw) {
4028
- if (!isObj(raw)) return "导入文件不是 JSON 对象";
4119
+ if (!isObj(raw)) return "文件顶层不是 JSON 对象(顶层须是 {\"records\": [...]};若文件本身就是数组,请包成 {\"records\": 数组})";
4029
4120
  if (!Array.isArray(raw.records)) return "records 不是数组(不是 dsh-engram 导出文件?)";
4030
4121
  if (raw.edges !== void 0 && !Array.isArray(raw.edges)) return "edges 不是数组";
4031
4122
  if (raw.entities !== void 0 && !Array.isArray(raw.entities)) return "entities 不是数组";
@@ -4158,35 +4249,146 @@ async function embedImportedRecords(store, embedder, importedIds) {
4158
4249
  return embedded;
4159
4250
  }
4160
4251
  //#endregion
4252
+ //#region src/body-limits.ts
4253
+ /**
4254
+ * 回环 API 的 body 字节上限(服务端与面板共用一份数字)。
4255
+ *
4256
+ * 单列一个模块的原因:上限既要写在服务端路由里,也要写在面板的前置检查里,
4257
+ * 两边各写一份迟早漂移——而漂移的后果是「面板放行、服务端拒收」或反过来,
4258
+ * 用户看到的却是另一句不相干的话。
4259
+ *
4260
+ * 本模块刻意不依赖任何运行时(无 node API、无 DOM API),服务端与浏览器端都能直接内联。
4261
+ *
4262
+ * @module @kenz1117/dsh-engram/body-limits
4263
+ */
4264
+ /** 普通写接口的 body 上限:64 KiB(防坏/恶意 body 拖住 handler)。 */
4265
+ const BODY_LIMIT_BYTES = 65536;
4266
+ /**
4267
+ * 导入接口的 body 上限:16 MiB。
4268
+ * 导入 payload 是整份导出(records + edges + entities),实测导出件动辄上百 KB
4269
+ * (issue #34 的现场导出件是 117 KB 与 165 KB),16 MiB 给足余量同时留住上限。
4270
+ */
4271
+ const IMPORT_BODY_LIMIT_BYTES = 16777216;
4272
+ /** 字节数 → 可读上限文案(上限要能让人一眼看出量级)。 */
4273
+ function formatBytes(bytes) {
4274
+ if (bytes >= 1048576) return `${String(Math.round(bytes / 1024 / 1024))} MB`;
4275
+ if (bytes >= 1024) return `${String(Math.round(bytes / 1024))} KB`;
4276
+ return `${String(bytes)} B`;
4277
+ }
4278
+ //#endregion
4279
+ //#region src/http-body.ts
4280
+ /**
4281
+ * 读取并解析 JSON body。
4282
+ *
4283
+ * 字节口径:限额按 body 的**字节数**算,不是字符数。中文一字 3 字节,按字符算
4284
+ * 会让实际字节上限虚高到 3 倍——等于把防滥用防线悄悄放宽了。
4285
+ *
4286
+ * 解码口径:先攒 Buffer,最后一次性 UTF-8 解码。逐块 `String(chunk)` 会在多字节
4287
+ * 字符跨块边界时被切成两个 U+FFFD——大文件必中招(导出件全是中文)。
4288
+ *
4289
+ * @param req - 请求。
4290
+ * @param limit - 字节上限(默认 64 KiB)。
4291
+ */
4292
+ async function readJsonBody(req, limit = BODY_LIMIT_BYTES) {
4293
+ const declared = Number(req.headers["content-length"]);
4294
+ if (Number.isFinite(declared) && declared > limit) {
4295
+ req.resume();
4296
+ return {
4297
+ ok: false,
4298
+ reason: "too-large",
4299
+ limit
4300
+ };
4301
+ }
4302
+ const chunks = [];
4303
+ let size = 0;
4304
+ let tooLarge = false;
4305
+ await new Promise((resolve, reject) => {
4306
+ let ended = false;
4307
+ req.on("data", (chunk) => {
4308
+ size += chunk.length;
4309
+ if (size > limit) {
4310
+ tooLarge = true;
4311
+ chunks.length = 0;
4312
+ return;
4313
+ }
4314
+ chunks.push(chunk);
4315
+ });
4316
+ req.on("end", () => {
4317
+ ended = true;
4318
+ resolve();
4319
+ });
4320
+ req.on("error", (error) => reject(error));
4321
+ req.on("aborted", () => reject(/* @__PURE__ */ new Error("request aborted")));
4322
+ req.on("close", () => {
4323
+ if (!ended) reject(/* @__PURE__ */ new Error("request closed before end"));
4324
+ });
4325
+ });
4326
+ if (tooLarge) return {
4327
+ ok: false,
4328
+ reason: "too-large",
4329
+ limit
4330
+ };
4331
+ const text = Buffer.concat(chunks).toString("utf8");
4332
+ let parsed;
4333
+ try {
4334
+ parsed = JSON.parse(text === "" ? "{}" : text);
4335
+ } catch (error) {
4336
+ return {
4337
+ ok: false,
4338
+ reason: "malformed",
4339
+ error: error instanceof Error ? error.message : String(error)
4340
+ };
4341
+ }
4342
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
4343
+ ok: false,
4344
+ reason: "not-object"
4345
+ };
4346
+ return {
4347
+ ok: true,
4348
+ body: parsed
4349
+ };
4350
+ }
4351
+ /**
4352
+ * 读取 JSON body 并宽容降级:坏 body 视为空对象。
4353
+ *
4354
+ * 给「body 整体可选」的普通写接口用(补做、配置、复习等)——它们的 body 都是
4355
+ * 小结构,坏 body 落到字段校验上照样 400,不需要区分原因。要区分原因的路由
4356
+ * (导入)自己用 {@link readJsonBody}。
4357
+ */
4358
+ async function readJsonBodyOrEmpty(req, limit = BODY_LIMIT_BYTES) {
4359
+ const result = await readJsonBody(req, limit);
4360
+ return result.ok ? result.body : {};
4361
+ }
4362
+ //#endregion
4161
4363
  //#region src/jev/client.ts
4162
4364
  /**
4163
- * 调用 Jev /v1/systemone 端点并行回答 Noul 问题。
4164
- * @param config - 已解析的 Jev 子配置(调用方先判 enabled)。
4165
- * @param state - 待判断的状态文本(如两条记忆正文的对照)。
4166
- * @param questions - Noul 问题列表;空列表直接返回空结果,不发请求。
4167
- * @param signal - 外部取消信号;与配置超时信号合并监听,超时按配置 timeoutMs 兜底。
4168
- * @returns 问题 id → Noul 概率(0-1,数字即信念)。
4169
- * @throws 网络、非 2xx、响应缺 answers、答案缺失或非 0-1 数字时抛错。
4365
+ * Задать Noul-вопросы эндпоинту System One и получить вероятности.
4366
+ * @param connection - собранное соединение (адрес, ключ, модель, тайм-аут).
4367
+ * @param state - текст состояния, по которому идёт суждение (например, две записи рядом).
4368
+ * @param questions - список Noul-вопросов; пустой список возвращает пустой результат без запроса.
4369
+ * @param signal - внешний сигнал отмены; складывается с тайм-аутом из connection.timeoutMs.
4370
+ * @returns идентификатор вопроса → вероятность Noul (0-1; число и есть убеждённость).
4371
+ * @throws при сетевом сбое, не-2xx, отсутствии `answers`, пропуске ответа или не-числе вне 0-1.
4170
4372
  */
4171
- async function askNoul(config, state, questions, signal = new AbortController().signal) {
4373
+ async function askNoul(connection, state, questions, signal = new AbortController().signal) {
4172
4374
  if (questions.length === 0) return {};
4173
- const response = await fetch(new URL("/v1/systemone", config.baseUrl), {
4375
+ const response = await fetch(connection.endpoint, {
4174
4376
  method: "POST",
4175
4377
  headers: {
4176
- Authorization: `Bearer ${config.apiKey ?? ""}`,
4378
+ Authorization: `Bearer ${connection.apiKey}`,
4177
4379
  "Content-Type": "application/json"
4178
4380
  },
4179
4381
  body: JSON.stringify({
4180
- model: config.model,
4382
+ model: connection.model,
4181
4383
  state,
4182
4384
  questions: Object.fromEntries(questions.map((question) => [question.id, {
4183
4385
  type: "noul",
4184
4386
  instructions: question.instructions
4185
4387
  }]))
4186
4388
  }),
4187
- signal: AbortSignal.any([signal, AbortSignal.timeout(config.timeoutMs)])
4389
+ signal: AbortSignal.any([signal, AbortSignal.timeout(connection.timeoutMs)])
4188
4390
  });
4189
- if (!response.ok) throw new Error(`jev: HTTP ${response.status} from ${config.baseUrl}`);
4391
+ if (!response.ok) throw new Error(`jev: HTTP ${response.status} from ${connection.endpoint}`);
4190
4392
  const payload = await response.json();
4191
4393
  if (payload.answers === void 0 || payload.answers === null) throw new Error("jev: response missing answers");
4192
4394
  const result = {};
@@ -4198,27 +4400,52 @@ async function askNoul(config, state, questions, signal = new AbortController().
4198
4400
  return result;
4199
4401
  }
4200
4402
  /**
4201
- * 从已解析配置构建可注入摄取与工具链路的判断器。
4202
- * @param config - 已解析的 Jev 子配置(含三阈值)。
4203
- * @returns MemoryJudge 实现;ask 不接收外部取消信号,仅受配置超时约束。
4204
- */
4205
- function createMemoryJudge(config) {
4403
+ * Собрать судью для конвейеров записи и инструментов из разрешённой конфигурации.
4404
+ *
4405
+ * Реквизиты соединения берутся у хоста лениво — при первом вопросе этого судьи —
4406
+ * и запоминаются на время его жизни: одна операция задаёт десятки вопросов, а
4407
+ * чтение конфигурации провайдера и секрета — это обращения к сервисам хоста.
4408
+ * Помнится только удачная сборка: неудачную следующая попытка повторяет, иначе
4409
+ * разовый сбой сервиса хоста залипал бы на всю жизнь судьи.
4410
+ *
4411
+ * @param config - разрешённая конфигурация Jev (включая три порога).
4412
+ * @param resolveConnection - сборщик соединения из данных хоста; строка = текст ошибки.
4413
+ * @returns реализация MemoryJudge; ask не принимает внешний сигнал отмены, только тайм-аут.
4414
+ */
4415
+ function createMemoryJudge(config, resolveConnection) {
4416
+ let cached;
4417
+ let attempt;
4418
+ const connection = async () => {
4419
+ if (cached !== void 0) return cached;
4420
+ attempt ??= resolveConnection();
4421
+ const resolved = await attempt;
4422
+ attempt = void 0;
4423
+ if (typeof resolved === "string") return resolved;
4424
+ cached = resolved;
4425
+ return resolved;
4426
+ };
4206
4427
  return {
4207
4428
  deferMergeAbove: config.deferMergeAbove,
4208
4429
  deferAcceptBelow: config.deferAcceptBelow,
4209
4430
  contradictMinProbability: config.contradictMinProbability,
4210
- ask: (state, questions) => askNoul(config, state, questions)
4431
+ ask: async (state, questions) => {
4432
+ const resolved = await connection();
4433
+ if (typeof resolved === "string") throw new Error(resolved);
4434
+ return askNoul(resolved, state, questions);
4435
+ }
4211
4436
  };
4212
4437
  }
4213
4438
  /**
4214
- * 连接测试:向端点发一个最小 ping 问题,验证 baseUrl/model/apiKey 三者组合可用。
4215
- * 不抛错——失败原因以 error 字段返回,供面板直接展示。
4216
- * @param config - 待测试的生效配置(enabled 不参与判断;apiKey/baseUrl/model 用调用方给的值)。
4439
+ * Проверка связи: минимальный ping-вопрос на эндпоинт — проверяет, что связка
4440
+ * «провайдер + модель + ключ» рабочая. Она же и есть проверка «модель действительно
4441
+ * Jev»: обычная чат-модель на запрос System One вероятностью не ответит.
4442
+ * Не бросает ошибку — причина возвращается полем error, чтобы панель её показала.
4443
+ * @param connection - проверяемое соединение (вызывающий уже собрал его из данных хоста).
4217
4444
  */
4218
- async function testJevConnection(config) {
4445
+ async function testJevConnection(connection) {
4219
4446
  const startedAt = Date.now();
4220
4447
  try {
4221
- const answers = await askNoul(config, "Connectivity test: this state exists.", [{
4448
+ const answers = await askNoul(connection, "Connectivity test: this state exists.", [{
4222
4449
  id: "ping",
4223
4450
  instructions: "This is a connectivity test. Return any probability between 0 and 1."
4224
4451
  }]);
@@ -4238,19 +4465,310 @@ async function testJevConnection(config) {
4238
4465
  }
4239
4466
  }
4240
4467
  //#endregion
4468
+ //#region src/jev/host.ts
4469
+ /**
4470
+ * Мост к хосту DSH: провайдеры, их модели и ключи живут в одном месте — у хоста.
4471
+ *
4472
+ * Jev не хранит ни токен, ни адрес. Панель выбирает провайдера из числа
4473
+ * **настроенных** в DSH (`ctx.llm.listConfigurableProviders()`, отбор по признаку
4474
+ * `declared`), а реквизиты собираются в момент вызова:
4475
+ * адрес — шаблон от `baseURL` провайдера (можно переопределить в настройках Jev);
4476
+ * ключ — из хранилища секретов по ссылке `apiKeyEnv` (`ctx.credentials.resolve`).
4477
+ *
4478
+ * Шаблон адреса: `{baseURL}/systemone`. Проверено на живом провайдере: при
4479
+ * `baseURL = https://api.aitunnel.ru/v1` эндпоинт `…/v1/systemone` отвечает
4480
+ * корректным Noul-ответом, а прежняя настройка Jev (`https://api.aitunnel.ru`)
4481
+ * давала тот же адрес через свой зашитый путь `/v1/systemone`.
4482
+ *
4483
+ * Почему не через `ctx.llm.stream`: у Jev собственный протокол (state/questions →
4484
+ * вероятности), он не OpenAI-chat-совместим, поэтому HTTP-клиент остаётся свой,
4485
+ * а у хоста берутся только реквизиты — тогда токен вводится ровно в одном месте.
4486
+ *
4487
+ * @module @kenz1117/dsh-engram/jev/host
4488
+ */
4489
+ function asRecord(value) {
4490
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4491
+ }
4492
+ function readString(record, key) {
4493
+ const value = record?.[key];
4494
+ return typeof value === "string" && value !== "" ? value : void 0;
4495
+ }
4496
+ function readBoolean(record, key) {
4497
+ const value = record?.[key];
4498
+ return typeof value === "boolean" ? value : void 0;
4499
+ }
4500
+ /** Пройти по пути вида `['providers', 'aitunnel']` внутри конфигурации плагина хоста. */
4501
+ function readPath(root, path) {
4502
+ let current = root;
4503
+ for (const segment of path) {
4504
+ const record = asRecord(current);
4505
+ if (record === void 0) return void 0;
4506
+ current = record[segment];
4507
+ }
4508
+ return current;
4509
+ }
4510
+ /** Модели из конфигурации провайдера: `[{id, name}]`; битые записи пропускаем. */
4511
+ function readModels(profile) {
4512
+ const models = profile?.["models"];
4513
+ if (!Array.isArray(models)) return [];
4514
+ const result = [];
4515
+ for (const entry of models) {
4516
+ const record = asRecord(entry);
4517
+ const id = readString(record, "id");
4518
+ if (id === void 0) continue;
4519
+ result.push({
4520
+ id,
4521
+ name: readString(record, "name") ?? id
4522
+ });
4523
+ }
4524
+ return result;
4525
+ }
4526
+ /** Собрать адрес из корня и относительного пути, не теряя уже имеющийся `/`. */
4527
+ function joinUrl(base, relative) {
4528
+ try {
4529
+ return new URL(relative, base.endsWith("/") ? base : `${base}/`).toString();
4530
+ } catch {
4531
+ return;
4532
+ }
4533
+ }
4534
+ /**
4535
+ * Шаблон адреса System One от корня API провайдера.
4536
+ * `https://api.aitunnel.ru/v1` → `https://api.aitunnel.ru/v1/systemone`
4537
+ * (системный путь — сосед `/chat/completions` в том же корне API).
4538
+ */
4539
+ function systemOneEndpoint(baseUrl) {
4540
+ return joinUrl(baseUrl, "systemone");
4541
+ }
4542
+ /** Дескриптор конфигурации хоста по namespace (например `llm-pi-ai`). */
4543
+ async function readSettingsValue(ctx, ns) {
4544
+ const settings = ctx.get("settings");
4545
+ if (settings?.describe === void 0) return void 0;
4546
+ try {
4547
+ const descriptors = await settings.describe();
4548
+ for (const descriptor of descriptors) if (descriptor.ns === ns) return descriptor.value;
4549
+ } catch {
4550
+ return;
4551
+ }
4552
+ }
4553
+ /** Конфигурация провайдера: подпись, `baseURL`, ссылка на ключ и модели. */
4554
+ async function readProviderProfile(ctx, providerId) {
4555
+ const entry = (ctx.get("llm")?.listConfigurableProviders?.() ?? []).find((candidate) => candidate.provider === providerId);
4556
+ if (entry === void 0) return void 0;
4557
+ const ns = typeof entry.settingsNs === "string" ? entry.settingsNs : void 0;
4558
+ if (ns === void 0) return void 0;
4559
+ const path = Array.isArray(entry.settingsPath) ? entry.settingsPath.filter((segment) => typeof segment === "string") : [];
4560
+ const value = await readSettingsValue(ctx, ns);
4561
+ if (value === void 0) return void 0;
4562
+ return asRecord(readPath(value, path.length > 0 ? path : ["providers", providerId]));
4563
+ }
4564
+ /** Ключ провайдера из хранилища секретов хоста по ссылке `apiKeyEnv`. */
4565
+ async function readProviderKey(ctx, profile) {
4566
+ const apiKeyEnv = readString(profile, "apiKeyEnv");
4567
+ if (apiKeyEnv === void 0) return "";
4568
+ const credentials = ctx.get("credentials");
4569
+ if (credentials?.resolve === void 0) return "";
4570
+ try {
4571
+ const value = (await credentials.resolve(apiKeyEnv))?.value;
4572
+ return typeof value === "string" ? value : "";
4573
+ } catch {
4574
+ return "";
4575
+ }
4576
+ }
4577
+ async function readProviderRekvisites(ctx, providerId) {
4578
+ if (ctx.get("llm") === void 0) return message("misc.jevHostLlmUnavailable");
4579
+ const profile = await readProviderProfile(ctx, providerId);
4580
+ if (profile === void 0) return message("misc.jevProviderNotConfigured", { provider: providerId });
4581
+ return {
4582
+ baseUrl: readString(profile, "baseURL"),
4583
+ apiKey: await readProviderKey(ctx, profile),
4584
+ apiKeyEnv: readString(profile, "apiKeyEnv"),
4585
+ modelIds: readModels(profile).map((item) => item.id)
4586
+ };
4587
+ }
4588
+ /**
4589
+ * Каталог для панели: только провайдеры, настроенные в DSH, с шаблоном адреса
4590
+ * и моделями из настроек (без обращения к сети — живой список берётся отдельно).
4591
+ *
4592
+ * Реестр хоста отдаёт и весь встроенный каталог pi-ai (anthropic, openai, google
4593
+ * и ещё три десятка видов) — их пользователь не настраивал, и в выпадающем списке
4594
+ * Jev им делать нечего. Признак «свой» хост сообщает сам: `declared = true`
4595
+ * у провайдера, объявленного в настройках, и `false` — у взятого из каталога
4596
+ * (функция `directoryEntries` в `dsh-llm-pi-ai`; там же видно, что объявленные
4597
+ * идут в конце списка, после встроенных).
4598
+ *
4599
+ * @param ctx - контекст плагина (доступ к сервисам хоста по имени).
4600
+ * @returns настроенные провайдеры с моделями; пустой список, если хост не отдал ничего.
4601
+ */
4602
+ async function readJevCatalog(ctx) {
4603
+ const llm = ctx.get("llm");
4604
+ const configurable = llm?.listConfigurableProviders?.() ?? [];
4605
+ const declared = [];
4606
+ const withProfile = [];
4607
+ const every = [];
4608
+ for (const entry of configurable) {
4609
+ const id = typeof entry.provider === "string" ? entry.provider : void 0;
4610
+ if (id === void 0) continue;
4611
+ const profile = await readProviderProfile(ctx, id);
4612
+ const baseUrl = readString(profile, "baseURL");
4613
+ const item = {
4614
+ id,
4615
+ displayName: readString(asRecord(entry), "displayName") ?? readString(profile, "displayName") ?? id,
4616
+ baseUrl,
4617
+ endpoint: baseUrl === void 0 ? void 0 : systemOneEndpoint(baseUrl),
4618
+ models: readModels(profile)
4619
+ };
4620
+ every.push(item);
4621
+ if (profile !== void 0) withProfile.push(item);
4622
+ const flag = readBoolean(asRecord(entry), "declared");
4623
+ if (flag === true || flag === void 0 && profile !== void 0) declared.push(item);
4624
+ }
4625
+ if (declared.length > 0) return { providers: declared };
4626
+ if (withProfile.length > 0) return { providers: withProfile };
4627
+ if (every.length > 0) return { providers: every };
4628
+ const providers = [];
4629
+ for (const route of llm?.listProviders?.() ?? []) {
4630
+ const id = readString(route, "id");
4631
+ if (id === void 0) continue;
4632
+ providers.push({
4633
+ id,
4634
+ displayName: readString(route, "name") ?? id,
4635
+ baseUrl: void 0,
4636
+ endpoint: void 0,
4637
+ models: []
4638
+ });
4639
+ }
4640
+ return { providers };
4641
+ }
4642
+ /**
4643
+ * Живой список моделей провайдера: `GET {baseURL}/models` тем же ключом, что и
4644
+ * судейство. Список сужается до Jev-моделей — панель предлагает только то, что
4645
+ * может отвечать протоколом System One.
4646
+ *
4647
+ * Если Jev-моделей у провайдера не нашлось, не предлагается ничего: остальные его
4648
+ * модели этого протокола не понимают, и подсказка из них была бы подсказкой сломать
4649
+ * судью. Имя в таком случае вписывают руками — поле принимает любое.
4650
+ * Ничего не бросает: причина отказа возвращается полем error.
4651
+ * @param ctx - контекст плагина.
4652
+ * @param providerId - выбранный провайдер DSH.
4653
+ */
4654
+ async function readProviderModels(ctx, providerId) {
4655
+ const rekvisites = await readProviderRekvisites(ctx, providerId);
4656
+ if (typeof rekvisites === "string") return {
4657
+ models: [],
4658
+ filtered: false,
4659
+ error: rekvisites
4660
+ };
4661
+ if (rekvisites.baseUrl === void 0) return {
4662
+ models: [],
4663
+ filtered: false,
4664
+ error: message("misc.jevProviderHasNoBaseUrl", { provider: providerId })
4665
+ };
4666
+ if (rekvisites.apiKey === "") return {
4667
+ models: [],
4668
+ filtered: false,
4669
+ error: message("misc.jevProviderKeyMissing", {
4670
+ provider: providerId,
4671
+ ref: rekvisites.apiKeyEnv ?? ""
4672
+ })
4673
+ };
4674
+ const url = joinUrl(rekvisites.baseUrl, "models");
4675
+ if (url === void 0) return {
4676
+ models: [],
4677
+ filtered: false,
4678
+ error: message("misc.jevProviderHasNoBaseUrl", { provider: providerId })
4679
+ };
4680
+ try {
4681
+ const response = await fetch(url, {
4682
+ headers: { Authorization: `Bearer ${rekvisites.apiKey}` },
4683
+ signal: AbortSignal.timeout(1e4)
4684
+ });
4685
+ if (!response.ok) return {
4686
+ models: [],
4687
+ filtered: false,
4688
+ error: `HTTP ${response.status}`
4689
+ };
4690
+ const payload = await response.json();
4691
+ const ids = [];
4692
+ if (Array.isArray(payload.data)) for (const entry of payload.data) {
4693
+ const id = readString(asRecord(entry), "id");
4694
+ if (id !== void 0) ids.push(id);
4695
+ }
4696
+ ids.sort((left, right) => left.localeCompare(right));
4697
+ return {
4698
+ models: ids.filter((id) => /jev/i.test(id)),
4699
+ filtered: true,
4700
+ error: void 0
4701
+ };
4702
+ } catch (error) {
4703
+ return {
4704
+ models: [],
4705
+ filtered: false,
4706
+ error: error instanceof Error ? error.message : String(error)
4707
+ };
4708
+ }
4709
+ }
4710
+ /**
4711
+ * Собрать соединение Jev: адрес — из настроек Jev либо шаблоном от провайдера,
4712
+ * ключ — из хранилища секретов по ссылке `apiKeyEnv`, модель — из настроек Jev
4713
+ * либо первая Jev-модель провайдера.
4714
+ * @param ctx - контекст плагина.
4715
+ * @param providerId - выбранный провайдер DSH; пусто = провайдера не назвал никто.
4716
+ * @param model - выбранная модель; пусто = взять Jev-модель провайдера.
4717
+ * @param timeoutMs - тайм-аут одного запроса.
4718
+ * @param endpointOverride - адрес из настроек Jev; пусто = взять шаблон от провайдера.
4719
+ * @returns соединение либо текст ошибки (как в `parseJevPatch`).
4720
+ */
4721
+ async function resolveJevConnection(ctx, providerId, model, timeoutMs, endpointOverride) {
4722
+ if (providerId.trim() === "") return message("misc.jevProviderUnresolved");
4723
+ const rekvisites = await readProviderRekvisites(ctx, providerId);
4724
+ if (typeof rekvisites === "string") return rekvisites;
4725
+ const chosenModel = model.trim() !== "" ? model.trim() : pickJevModel(rekvisites.modelIds);
4726
+ if (chosenModel === void 0) return message("misc.jevModelNotPicked", { provider: providerId });
4727
+ const endpoint = (endpointOverride !== void 0 && endpointOverride.trim() !== "" ? endpointOverride.trim() : void 0) ?? (rekvisites.baseUrl === void 0 ? void 0 : systemOneEndpoint(rekvisites.baseUrl));
4728
+ if (endpoint === void 0) return message("misc.jevProviderHasNoBaseUrl", { provider: providerId });
4729
+ if (rekvisites.apiKey === "") return message("misc.jevProviderKeyMissing", {
4730
+ provider: providerId,
4731
+ ref: rekvisites.apiKeyEnv ?? ""
4732
+ });
4733
+ return {
4734
+ endpoint,
4735
+ apiKey: rekvisites.apiKey,
4736
+ model: chosenModel,
4737
+ timeoutMs
4738
+ };
4739
+ }
4740
+ /**
4741
+ * Первая Jev-модель из настроек провайдера — замена пустому полю модели.
4742
+ * Порядок не пересортировываем: он задан пользователем в настройках DSH, и выбранной
4743
+ * должна стать та модель, которую он поставил выше.
4744
+ * @param modelIds - модели провайдера из его настроек в DSH.
4745
+ * @returns имя модели либо `undefined`, если Jev-моделей у провайдера нет.
4746
+ */
4747
+ function pickJevModel(modelIds) {
4748
+ return modelIds.find((id) => /jev/i.test(id));
4749
+ }
4750
+ //#endregion
4241
4751
  //#region src/jev/runtime.ts
4242
4752
  /**
4243
- * Jev 连接配置的运行时覆盖:管理面板保存到 `<dbDir>/jev-config.json`(0600),
4244
- * 字段级覆盖 cordis.yml 的 jev 子配置;装配免缓存——judge 构造是无状态闭包、
4245
- * 覆盖文件是小读,每个装配点即时解析,面板保存后立即生效。
4246
- * 覆盖文件损坏按空覆盖处理:不卡启动,面板重新保存即修复。
4753
+ * Настройки Jev, задаваемые из панели: сохраняются в `<dbDir>/jev-config.json` (0600)
4754
+ * и пофайлово перекрывают подконфигурацию `jev` из cordis.yml.
4755
+ *
4756
+ * Здесь хранится только то, что действительно относится к Jev: включён ли он,
4757
+ * какой провайдер DSH и какая его модель выбраны, тайм-аут. Ни адреса, ни токена
4758
+ * тут нет и быть не должно — их берёт у хоста мост `./host.ts` в момент вызова,
4759
+ * поэтому провайдеры и ключи вводятся ровно в одном месте, у хоста.
4760
+ *
4761
+ * Сборка судьи не кэшируется: конструктор — это замыкание без состояния, а файл
4762
+ * настроек читается мелко, поэтому каждая точка сборки разрешает его заново и
4763
+ * сохранение в панели действует сразу. Битый файл настроек считается пустым
4764
+ * перекрытием: запуск не блокируется, панель перезапишет файл при сохранении.
4247
4765
  * @module @kenz1117/dsh-engram/jev/runtime
4248
4766
  */
4249
- /** 覆盖文件路径(dbDir 已 0700,文件本身 0600 双保险)。 */
4767
+ /** Путь к файлу перекрытия (каталог уже 0700, сам файл — 0600, двойная защита). */
4250
4768
  function jevOverridePath(dbDir) {
4251
4769
  return `${dbDir}/jev-config.json`;
4252
4770
  }
4253
- /** 读覆盖文件:缺失/损坏/非法 JSON 都按空覆盖(面板重新保存即修复)。 */
4771
+ /** Прочитать перекрытие: нет файла, битый JSON или мусор — всё считается пустым перекрытием. */
4254
4772
  function loadJevOverride(dbDir) {
4255
4773
  let raw;
4256
4774
  try {
@@ -4264,28 +4782,35 @@ function loadJevOverride(dbDir) {
4264
4782
  return {};
4265
4783
  }
4266
4784
  }
4267
- /** 收敛未知 JSON 为覆盖对象:只认五个已知字段,类型不符的丢弃。 */
4785
+ /**
4786
+ * Свести произвольный JSON к перекрытию: известны четыре поля, остальное отбрасывается.
4787
+ * Поля прежнего формата (`apiKey`, `baseUrl`) намеренно не читаются: ключ и адрес
4788
+ * больше не хранятся у Jev, их место занял выбор провайдера у хоста.
4789
+ */
4268
4790
  function collectOverride(value) {
4269
4791
  if (value === null || typeof value !== "object") return {};
4270
4792
  const raw = value;
4793
+ const legacy = legacyJevFields(raw);
4794
+ if (legacy.length > 0) noteLegacyJevFields("jev-config.json", legacy);
4271
4795
  return {
4272
4796
  ...typeof raw["enabled"] === "boolean" ? { enabled: raw["enabled"] } : {},
4273
- ...typeof raw["apiKey"] === "string" ? { apiKey: raw["apiKey"] } : {},
4274
- ...typeof raw["baseUrl"] === "string" ? { baseUrl: raw["baseUrl"] } : {},
4275
- ...typeof raw["model"] === "string" ? { model: raw["model"] } : {},
4797
+ ...typeof raw["provider"] === "string" && raw["provider"] !== "" ? { provider: raw["provider"] } : {},
4798
+ ...typeof raw["model"] === "string" && raw["model"] !== "" ? { model: raw["model"] } : {},
4799
+ ...typeof raw["endpoint"] === "string" && raw["endpoint"] !== "" ? { endpoint: raw["endpoint"] } : {},
4276
4800
  ...typeof raw["timeoutMs"] === "number" && Number.isInteger(raw["timeoutMs"]) ? { timeoutMs: raw["timeoutMs"] } : {}
4277
4801
  };
4278
4802
  }
4279
- /** 全量保存覆盖文件(调用方先经 parseJevPatch 校验;内容为面板合并后的完整覆盖)。 */
4803
+ /** Записать перекрытие целиком (вызывающий уже проверил его через `parseJevPatch`). */
4280
4804
  function saveJevOverride(dbDir, override) {
4281
4805
  writeFileSync(jevOverridePath(dbDir), `${JSON.stringify(override, null, 2)}\n`, { mode: 384 });
4282
4806
  }
4283
4807
  /**
4284
- * 面板 patch 解析:只认已知字段并逐个校验,出现非法值整体拒绝。
4285
- * `apiKey: ''` 表示清除面板密钥覆盖(回落 yml);缺席的字段保留 current。
4286
- * @param current - 现有覆盖(合并底座)。
4287
- * @param patch - POST body 原始对象。
4288
- * @returns 合法时返回合并后的完整覆盖;非法时返回 `invalid:` 前缀的字段错误文案。
4808
+ * Разобрать правку из панели: известные поля проверяются по одному, при любой
4809
+ * негодности отвергается вся правка. `provider: ''` очищает выбор провайдера
4810
+ * (Jev при этом молча уходит в чистые правила); отсутствующее поле сохраняет текущее.
4811
+ * @param current - текущее перекрытие (основа слияния).
4812
+ * @param patch - сырой объект из тела POST.
4813
+ * @returns при годности — слитое перекрытие целиком; иначе текст ошибки с префиксом `invalid:`.
4289
4814
  */
4290
4815
  function parseJevPatch(current, patch) {
4291
4816
  const merged = { ...current };
@@ -4293,26 +4818,32 @@ function parseJevPatch(current, patch) {
4293
4818
  if (typeof patch["enabled"] !== "boolean") return message("misc.jevEnabledMustBeBoolean");
4294
4819
  merged.enabled = patch["enabled"];
4295
4820
  }
4296
- if (patch["apiKey"] !== void 0) {
4297
- if (typeof patch["apiKey"] !== "string") return message("misc.jevApiKeyMustBeString");
4298
- const trimmed = patch["apiKey"].trim();
4299
- if (trimmed === "") delete merged.apiKey;
4300
- else merged.apiKey = trimmed;
4301
- }
4302
- if (patch["baseUrl"] !== void 0) {
4303
- if (typeof patch["baseUrl"] !== "string") return message("misc.jevBaseUrlMustBeString");
4304
- const value = patch["baseUrl"].trim();
4305
- try {
4306
- const url = new URL(value);
4307
- if (url.protocol !== "https:" && url.protocol !== "http:") return message("misc.jevBaseUrlMustBeHttp");
4308
- } catch {
4309
- return message("misc.jevBaseUrlMustBeHttp");
4310
- }
4311
- merged.baseUrl = value;
4821
+ if (patch["provider"] !== void 0) {
4822
+ if (typeof patch["provider"] !== "string") return message("misc.jevProviderMustBeString");
4823
+ const trimmed = patch["provider"].trim();
4824
+ if (trimmed === "") delete merged.provider;
4825
+ else merged.provider = trimmed;
4312
4826
  }
4313
4827
  if (patch["model"] !== void 0) {
4314
- if (typeof patch["model"] !== "string" || patch["model"].trim() === "") return message("misc.jevModelMustNotBeEmpty");
4315
- merged.model = patch["model"].trim();
4828
+ if (typeof patch["model"] !== "string") return message("misc.jevModelMustNotBeEmpty");
4829
+ const trimmed = patch["model"].trim();
4830
+ if (trimmed === "") delete merged.model;
4831
+ else merged.model = trimmed;
4832
+ }
4833
+ if (patch["endpoint"] !== void 0) {
4834
+ if (typeof patch["endpoint"] !== "string") return message("misc.jevEndpointMustBeHttp");
4835
+ const trimmed = patch["endpoint"].trim();
4836
+ if (trimmed === "") delete merged.endpoint;
4837
+ else {
4838
+ let scheme = "";
4839
+ try {
4840
+ scheme = new URL(trimmed).protocol;
4841
+ } catch {
4842
+ scheme = "";
4843
+ }
4844
+ if (scheme !== "http:" && scheme !== "https:") return message("misc.jevEndpointMustBeHttp");
4845
+ merged.endpoint = trimmed;
4846
+ }
4316
4847
  }
4317
4848
  if (patch["timeoutMs"] !== void 0) {
4318
4849
  const value = patch["timeoutMs"];
@@ -4322,36 +4853,41 @@ function parseJevPatch(current, patch) {
4322
4853
  return merged;
4323
4854
  }
4324
4855
  /**
4325
- * 面板覆盖与 yml 基线的字段级合并;合并后 enabled=true 但无密钥时强制降级
4326
- * enabled=false(与 Jev 不可用静默降级语义一致,不卡启动)。
4856
+ * Непустое значение либо `undefined`: пустая строка означает «поле не названо»,
4857
+ * а не «названо пустым». Без этого шага очищенное поле панели затирало бы значение
4858
+ * из cordis.yml вместо того, чтобы уступить ему место.
4859
+ */
4860
+ function named(value) {
4861
+ return value !== void 0 && value !== "" ? value : void 0;
4862
+ }
4863
+ /**
4864
+ * Слить перекрытие панели с базой из cordis.yml по полям.
4865
+ *
4866
+ * Провайдер и модель вправе остаться неназванными: провайдера тогда подставит ленивый
4867
+ * резолвер соединения (маршрут текущей сессии), а модель — первая Jev-модель этого
4868
+ * провайдера. Поэтому `enabled` здесь означает только «пользователь включил Jev»:
4869
+ * снимать его заранее значило бы терять наследование, которое видно лишь в момент вопроса.
4327
4870
  */
4328
4871
  function effectiveJevConfig(base, override) {
4329
- const apiKey = override.apiKey ?? base.apiKey;
4330
- const enabled = (override.enabled ?? base.enabled) && apiKey !== void 0 && apiKey !== "";
4331
4872
  return {
4332
- enabled,
4333
- apiKey: enabled ? apiKey : void 0,
4334
- baseUrl: override.baseUrl ?? base.baseUrl,
4335
- model: override.model ?? base.model,
4873
+ enabled: override.enabled ?? base.enabled,
4874
+ provider: named(override.provider) ?? named(base.provider),
4875
+ model: named(override.model) ?? named(base.model),
4876
+ endpoint: override.endpoint ?? base.endpoint,
4336
4877
  timeoutMs: override.timeoutMs ?? base.timeoutMs,
4337
4878
  deferMergeAbove: base.deferMergeAbove,
4338
4879
  deferAcceptBelow: base.deferAcceptBelow,
4339
4880
  contradictMinProbability: base.contradictMinProbability
4340
4881
  };
4341
4882
  }
4342
- /** 密钥掩码:长度 > 8 显示尾 4 位,其余全掩码。 */
4343
- function maskApiKey(key) {
4344
- return key.length > 8 ? `****${key.slice(-4)}` : "******";
4345
- }
4346
- /** 组装面板视图:基于生效配置;掩码取合并后的密钥。 */
4883
+ /** Собрать вид для панели по действующей конфигурации. */
4347
4884
  function jevConfigView(base, override) {
4348
4885
  const config = effectiveJevConfig(base, override);
4349
4886
  return {
4350
4887
  enabled: config.enabled,
4351
- apiKeySet: config.apiKey !== void 0 && config.apiKey !== "",
4352
- apiKeyMask: config.apiKey === void 0 || config.apiKey === "" ? null : maskApiKey(config.apiKey),
4353
- baseUrl: config.baseUrl,
4888
+ provider: config.provider,
4354
4889
  model: config.model,
4890
+ endpoint: config.endpoint,
4355
4891
  timeoutMs: config.timeoutMs,
4356
4892
  deferMergeAbove: config.deferMergeAbove,
4357
4893
  deferAcceptBelow: config.deferAcceptBelow,
@@ -4359,14 +4895,34 @@ function jevConfigView(base, override) {
4359
4895
  };
4360
4896
  }
4361
4897
  /**
4362
- * 统一装配函数:读面板覆盖、合并 yml 基线,enabled 时产出 judge,否则返回空对象。
4363
- * 产出形状可直接条件展开进摄取/工具/末轮/回填四类依赖(`...resolveJevField(resolved.jev, dbDir)`)。
4364
- * 免缓存:judge 构造是无状态闭包、覆盖文件是小读,每次调用即时解析,面板保存立即生效。
4365
- */
4366
- function resolveJevField(base, dbDir) {
4367
- const config = effectiveJevConfig(base, loadJevOverride(dbDir));
4368
- if (!config.enabled || config.apiKey === void 0 || config.apiKey === "") return {};
4369
- return { judge: createMemoryJudge(config) };
4898
+ * Единая точка сборки: отдать поставщика судьи Jev — функцию, которая собирает судью
4899
+ * в момент операции. Результат раскладывается в зависимости четырёх видов
4900
+ * (запись, инструменты, последний ход, догрузка истории).
4901
+ *
4902
+ * Поставщик читает перекрытие панели и базу cordis.yml при каждом вызове, а реквизиты
4903
+ * соединения резолвятся ещё позже — при первом вопросе судьи, где и доопределяются
4904
+ * провайдер и модель, которых не назвал никто. Поэтому включение Jev и смена провайдера,
4905
+ * модели или адреса в панели действуют без перезапуска, а не только при загрузке плагина.
4906
+ * Три порога задаются лишь в cordis.yml и меняются с перезапуском.
4907
+ * @param ctx - контекст плагина (доступ к сервисам хоста: llm, settings, credentials).
4908
+ * @param base - база из cordis.yml.
4909
+ * @param dbDir - каталог данных (там лежит файл перекрытия).
4910
+ * @param routeProvider - провайдер текущей сессии: подставляется, только если его не
4911
+ * назвали ни панель, ни cordis.yml. Читается в момент вопроса, поэтому смена
4912
+ * маршрута посреди сессии подхватывается сама.
4913
+ */
4914
+ function resolveJevField(ctx, base, dbDir, routeProvider) {
4915
+ return { resolveJudge: () => {
4916
+ const config = effectiveJevConfig(base, loadJevOverride(dbDir));
4917
+ if (!config.enabled) return void 0;
4918
+ const configured = config.provider;
4919
+ const model = config.model ?? "";
4920
+ const endpoint = config.endpoint;
4921
+ const timeoutMs = config.timeoutMs;
4922
+ return createMemoryJudge(config, () => {
4923
+ return resolveJevConnection(ctx, configured !== void 0 && configured !== "" ? configured : routeProvider?.() ?? "", model, timeoutMs, endpoint);
4924
+ });
4925
+ } };
4370
4926
  }
4371
4927
  //#endregion
4372
4928
  //#region src/mirror/markdown.ts
@@ -5083,20 +5639,6 @@ function guardWrite(req, res) {
5083
5639
  }
5084
5640
  return true;
5085
5641
  }
5086
- /** 读取并解析 JSON body(上限 64 KiB,防坏/恶意 body 拖住 handler)。 */
5087
- async function readJsonBody(req) {
5088
- let body = "";
5089
- for await (const chunk of req) {
5090
- body += String(chunk);
5091
- if (body.length > 65536) return null;
5092
- }
5093
- try {
5094
- const parsed = JSON.parse(body === "" ? "{}" : body);
5095
- return parsed !== null && typeof parsed === "object" ? parsed : null;
5096
- } catch {
5097
- return null;
5098
- }
5099
- }
5100
5642
  function json(res, status, body) {
5101
5643
  res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
5102
5644
  res.end(JSON.stringify(body));
@@ -5445,8 +5987,8 @@ function registerEngramRoutes(ctx, deps) {
5445
5987
  }
5446
5988
  if (req.method === "POST" && route === "review-answer") {
5447
5989
  if (!guardWrite(req, res)) return;
5448
- const body = await readJsonBody(req);
5449
- if (body === null || typeof body.id !== "string" || body.id === "") {
5990
+ const body = await readJsonBodyOrEmpty(req);
5991
+ if (typeof body.id !== "string" || body.id === "") {
5450
5992
  json(res, 400, { error: "id required" });
5451
5993
  return;
5452
5994
  }
@@ -5510,8 +6052,8 @@ function registerEngramRoutes(ctx, deps) {
5510
6052
  }
5511
6053
  if (req.method === "POST" && route === "review-answer") {
5512
6054
  if (!guardWrite(req, res)) return;
5513
- const body = await readJsonBody(req);
5514
- if (body === null || typeof body.id !== "string" || body.id === "") {
6055
+ const body = await readJsonBodyOrEmpty(req);
6056
+ if (typeof body.id !== "string" || body.id === "") {
5515
6057
  json(res, 400, { error: "id required" });
5516
6058
  return;
5517
6059
  }
@@ -5558,8 +6100,20 @@ function registerEngramRoutes(ctx, deps) {
5558
6100
  }
5559
6101
  if (req.method === "POST" && route === "import") {
5560
6102
  if (!guardWrite(req, res)) return;
5561
- const body = await readJsonBody(req);
5562
- const bodyObj = typeof body === "object" && body !== null && !Array.isArray(body) ? body : {};
6103
+ const bodyResult = await readJsonBody(req, IMPORT_BODY_LIMIT_BYTES);
6104
+ if (!bodyResult.ok) {
6105
+ if (bodyResult.reason === "too-large") {
6106
+ json(res, 413, { error: messageIn(deps.language, "misc.importBodyTooLarge", { limit: formatBytes(bodyResult.limit) }) });
6107
+ return;
6108
+ }
6109
+ if (bodyResult.reason === "malformed") {
6110
+ json(res, 400, { error: messageIn(deps.language, "misc.importBodyMalformed", { error: bodyResult.error }) });
6111
+ return;
6112
+ }
6113
+ json(res, 400, { error: messageIn(deps.language, "misc.importBodyNotObject") });
6114
+ return;
6115
+ }
6116
+ const bodyObj = bodyResult.body;
5563
6117
  const scope = scopeOf$1(typeof bodyObj.scope === "string" ? bodyObj.scope : null, "user");
5564
6118
  let data;
5565
6119
  let redacted = false;
@@ -5791,8 +6345,8 @@ function registerEngramRoutes(ctx, deps) {
5791
6345
  }
5792
6346
  if (req.method === "POST" && route === "history-backfill/start") {
5793
6347
  if (!guardWrite(req, res)) return;
5794
- const body = await readJsonBody(req);
5795
- const started = deps.history.start(historyRulesOf(body ?? {}));
6348
+ const body = await readJsonBodyOrEmpty(req);
6349
+ const started = deps.history.start(historyRulesOf(body));
5796
6350
  if (!started.ok) {
5797
6351
  json(res, 409, {
5798
6352
  ok: false,
@@ -5816,33 +6370,74 @@ function registerEngramRoutes(ctx, deps) {
5816
6370
  return;
5817
6371
  }
5818
6372
  if (req.method === "GET" && route === "jev-config") {
5819
- json(res, 200, jevConfigView(deps.jev.base, loadJevOverride(deps.jev.dbDir)));
6373
+ const catalog = await deps.jev.host.catalog();
6374
+ json(res, 200, {
6375
+ ...jevConfigView(deps.jev.base, loadJevOverride(deps.jev.dbDir)),
6376
+ providers: catalog.providers
6377
+ });
5820
6378
  return;
5821
6379
  }
5822
6380
  if (req.method === "POST" && route === "jev-config") {
5823
6381
  if (!guardWrite(req, res)) return;
5824
- const body = await readJsonBody(req);
5825
- const parsed = parseJevPatch(loadJevOverride(deps.jev.dbDir), body ?? {});
6382
+ const body = await readJsonBodyOrEmpty(req);
6383
+ const parsed = parseJevPatch(loadJevOverride(deps.jev.dbDir), body);
5826
6384
  if (typeof parsed === "string") {
5827
6385
  json(res, 400, { error: parsed });
5828
6386
  return;
5829
6387
  }
5830
6388
  saveJevOverride(deps.jev.dbDir, parsed);
6389
+ const catalog = await deps.jev.host.catalog();
5831
6390
  json(res, 200, {
5832
6391
  ok: true,
5833
- view: jevConfigView(deps.jev.base, parsed)
6392
+ view: {
6393
+ ...jevConfigView(deps.jev.base, parsed),
6394
+ providers: catalog.providers
6395
+ }
5834
6396
  });
5835
6397
  return;
5836
6398
  }
5837
6399
  if (req.method === "POST" && route === "jev-test") {
5838
6400
  if (!guardWrite(req, res)) return;
5839
- const body = await readJsonBody(req);
5840
- json(res, 200, await testJevConnection({
5841
- ...effectiveJevConfig(deps.jev.base, loadJevOverride(deps.jev.dbDir)),
5842
- ...typeof body?.baseUrl === "string" && body.baseUrl.trim() !== "" ? { baseUrl: body.baseUrl.trim() } : {},
5843
- ...typeof body?.model === "string" && body.model.trim() !== "" ? { model: body.model.trim() } : {},
5844
- ...typeof body?.apiKey === "string" && body.apiKey !== "" ? { apiKey: body.apiKey } : {}
5845
- }));
6401
+ const body = await readJsonBodyOrEmpty(req);
6402
+ const base = effectiveJevConfig(deps.jev.base, loadJevOverride(deps.jev.dbDir));
6403
+ const provider = typeof body.provider === "string" && body.provider.trim() !== "" ? body.provider.trim() : base.provider;
6404
+ const model = typeof body.model === "string" && body.model.trim() !== "" ? body.model.trim() : base.model;
6405
+ const endpoint = typeof body.endpoint === "string" && body.endpoint.trim() !== "" ? body.endpoint.trim() : base.endpoint;
6406
+ if (provider === void 0 || model === void 0) {
6407
+ json(res, 200, {
6408
+ ok: false,
6409
+ elapsedMs: 0,
6410
+ probability: void 0,
6411
+ error: message("misc.jevProviderMustBeSelected")
6412
+ });
6413
+ return;
6414
+ }
6415
+ const connection = await deps.jev.host.connection(provider, model, base.timeoutMs, endpoint);
6416
+ if (typeof connection === "string") {
6417
+ json(res, 200, {
6418
+ ok: false,
6419
+ elapsedMs: 0,
6420
+ probability: void 0,
6421
+ error: connection
6422
+ });
6423
+ return;
6424
+ }
6425
+ json(res, 200, await testJevConnection(connection));
6426
+ return;
6427
+ }
6428
+ if (req.method === "POST" && route === "jev-models") {
6429
+ if (!guardWrite(req, res)) return;
6430
+ const body = await readJsonBodyOrEmpty(req);
6431
+ const provider = typeof body.provider === "string" ? body.provider.trim() : "";
6432
+ if (provider === "") {
6433
+ json(res, 200, {
6434
+ models: [],
6435
+ filtered: false,
6436
+ error: message("misc.jevProviderMustBeSelected")
6437
+ });
6438
+ return;
6439
+ }
6440
+ json(res, 200, await deps.jev.host.models(provider));
5846
6441
  return;
5847
6442
  }
5848
6443
  if (req.method === "GET" && route === "jev-observations") {
@@ -5851,11 +6446,11 @@ function registerEngramRoutes(ctx, deps) {
5851
6446
  }
5852
6447
  if (req.method === "POST" && route === "consolidate") {
5853
6448
  if (!guardWrite(req, res)) return;
5854
- const body = await readJsonBody(req);
6449
+ const body = await readJsonBodyOrEmpty(req);
5855
6450
  adoptBodySelector(body);
5856
- const rawScope = typeof body?.scope === "string" ? body.scope : "user";
6451
+ const rawScope = typeof body.scope === "string" ? body.scope : "user";
5857
6452
  const scope = rawScope === "project" ? "project" : rawScope === "shared" ? "shared" : "user";
5858
- const candidates = Array.isArray(body?.candidates) ? body.candidates.filter((value) => typeof value === "string") : void 0;
6453
+ const candidates = Array.isArray(body.candidates) ? body.candidates.filter((value) => typeof value === "string") : void 0;
5859
6454
  json(res, 200, await runConsolidation(await storeFor(scope), deps.embedder, candidates === void 0 ? { scope } : {
5860
6455
  scope,
5861
6456
  mergeCandidateIds: candidates
@@ -5875,8 +6470,8 @@ function registerEngramRoutes(ctx, deps) {
5875
6470
  }
5876
6471
  if (req.method === "POST" && route === "restore-backup") {
5877
6472
  if (!guardWrite(req, res)) return;
5878
- const body = await readJsonBody(req);
5879
- if (body === null || typeof body.archivePath !== "string" || body.archivePath === "") {
6473
+ const body = await readJsonBodyOrEmpty(req);
6474
+ if (typeof body.archivePath !== "string" || body.archivePath === "") {
5880
6475
  json(res, 400, { error: "archivePath required" });
5881
6476
  return;
5882
6477
  }
@@ -5901,8 +6496,8 @@ function registerEngramRoutes(ctx, deps) {
5901
6496
  }
5902
6497
  if (req.method === "POST" && (route === "update" || route === "forget" || route === "restore")) {
5903
6498
  if (!guardWrite(req, res)) return;
5904
- const body = await readJsonBody(req);
5905
- if (body === null || typeof body.id !== "string" || body.id === "") {
6499
+ const body = await readJsonBodyOrEmpty(req);
6500
+ if (typeof body.id !== "string" || body.id === "") {
5906
6501
  json(res, 400, { error: "id required" });
5907
6502
  return;
5908
6503
  }
@@ -8623,10 +9218,10 @@ function createEngramTools(baseDeps) {
8623
9218
  * 写入单条已清洗内容(四态处置):MERGE 不新建条目只强化既有;
8624
9219
  * DEFER 写入并建 contradicts 边待裁决;ACCEPT 原样写入。
8625
9220
  */
8626
- async function writeWithDisposition(store, item) {
9221
+ async function writeWithDisposition(store, item, judge) {
8627
9222
  const { embedding } = item;
8628
- const decision = await decideWrite(store, item.kind, embedding, deps.judge === void 0 ? {} : {
8629
- judge: deps.judge,
9223
+ const decision = await decideWrite(store, item.kind, embedding, judge === void 0 ? {} : {
9224
+ judge,
8630
9225
  content: item.content
8631
9226
  });
8632
9227
  if (decision.disposition === "merge") return {
@@ -8647,7 +9242,7 @@ function createEngramTools(baseDeps) {
8647
9242
  });
8648
9243
  if (decision.disposition === "defer") {
8649
9244
  const candidates = (await store.findContradictions(embedding)).filter((candidate) => candidate.id !== record.id);
8650
- const confirmed = deps.judge === void 0 ? candidates : await confirmContradictions(deps.judge, item.content, candidates) ?? candidates;
9245
+ const confirmed = judge === void 0 ? candidates : await confirmContradictions(judge, item.content, candidates) ?? candidates;
8651
9246
  for (const candidate of confirmed) await store.linkEdge(record.id, candidate.id, "contradicts");
8652
9247
  return {
8653
9248
  disposition: "defer",
@@ -8745,6 +9340,7 @@ function createEngramTools(baseDeps) {
8745
9340
  }
8746
9341
  const vectors = embedder === void 0 || prepared.length === 0 ? void 0 : await embedder.embed(prepared.map((item) => item.content.trim()));
8747
9342
  const saved = [];
9343
+ const judge = deps.resolveJudge?.();
8748
9344
  for (const [position, item] of prepared.entries()) try {
8749
9345
  const embedding = vectors?.[position];
8750
9346
  const outcome = await writeWithDisposition(store, {
@@ -8754,7 +9350,7 @@ function createEngramTools(baseDeps) {
8754
9350
  ...item.importance === void 0 ? {} : { importance: item.importance },
8755
9351
  sourceSessionId,
8756
9352
  ...embedding === void 0 ? {} : { embedding }
8757
- });
9353
+ }, judge);
8758
9354
  await linkEntities(store, outcome.disposition === "merge" && outcome.relatedId !== void 0 ? asMemoryId(outcome.relatedId) : outcome.record.id, item.entities);
8759
9355
  saved.push({
8760
9356
  id: outcome.record.id,
@@ -9000,6 +9596,7 @@ function createEngramTools(baseDeps) {
9000
9596
  const embeddings = embedder === void 0 ? void 0 : await embedder.embed([content.trim()]);
9001
9597
  const imagery = placardOf(input.placard);
9002
9598
  const mentions = parseEntityMentions(input.entities);
9599
+ const judge = deps.resolveJudge?.();
9003
9600
  const outcome = await writeWithDisposition(store, {
9004
9601
  scope,
9005
9602
  kind: input.kind,
@@ -9008,7 +9605,7 @@ function createEngramTools(baseDeps) {
9008
9605
  sourceSessionId,
9009
9606
  ...embeddings?.[0] === void 0 ? {} : { embedding: embeddings[0] },
9010
9607
  ...imagery === void 0 ? {} : { imagery }
9011
- });
9608
+ }, judge);
9012
9609
  if (mentions.length > 0) await linkEntities(store, outcome.disposition === "merge" && outcome.relatedId !== void 0 ? asMemoryId(outcome.relatedId) : outcome.record.id, mentions);
9013
9610
  const { record, candidates } = outcome;
9014
9611
  if (outcome.disposition === "merge") {
@@ -11229,7 +11826,7 @@ function estimateTokens(text) {
11229
11826
  }
11230
11827
  //#endregion
11231
11828
  //#region package.json
11232
- var version = "0.9.2";
11829
+ var version = "0.9.5";
11233
11830
  //#endregion
11234
11831
  //#region src/index.ts
11235
11832
  /**
@@ -11411,7 +12008,7 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
11411
12008
  embedder,
11412
12009
  mode,
11413
12010
  routeOverride: resolved.routeOverride,
11414
- ...resolveJevField(resolved.jev, resolved.dbDir),
12011
+ ...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => state.route?.provider),
11415
12012
  call: (params) => streamText(ctx, {
11416
12013
  ...params,
11417
12014
  sessionId: agent.session.id
@@ -11432,7 +12029,7 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
11432
12029
  embedder,
11433
12030
  mode,
11434
12031
  routeOverride: resolved.routeOverride,
11435
- ...resolveJevField(resolved.jev, resolved.dbDir),
12032
+ ...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => state.route?.provider),
11436
12033
  call: (params) => streamText(ctx, {
11437
12034
  ...params,
11438
12035
  sessionId: agent.session.id
@@ -11794,7 +12391,7 @@ function apply(ctx, config = {}) {
11794
12391
  sessionId: ""
11795
12392
  }),
11796
12393
  logRequest: logIngestRequest,
11797
- ...resolveJevField(resolved.jev, resolved.dbDir)
12394
+ ...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => (resolved.routeOverride ?? preStepState.route)?.provider)
11798
12395
  });
11799
12396
  /** 回填任务(进程内单例;面板轮询它的进度,工具同步等待自己的那一次运行)。 */
11800
12397
  let backfillJob;
@@ -11901,7 +12498,7 @@ function apply(ctx, config = {}) {
11901
12498
  sessionId: callParams.sessionId ?? ""
11902
12499
  }),
11903
12500
  routeOverride: resolved.routeOverride,
11904
- ...resolveJevField(resolved.jev, resolved.dbDir),
12501
+ ...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => preStepState.route?.provider),
11905
12502
  queryRewrite: resolved.queryRewrite,
11906
12503
  exportDir: `${resolved.dbDir}/exports`,
11907
12504
  language: resolved.language,
@@ -11923,7 +12520,12 @@ function apply(ctx, config = {}) {
11923
12520
  embedder,
11924
12521
  jev: {
11925
12522
  base: resolved.jev,
11926
- dbDir: resolved.dbDir
12523
+ dbDir: resolved.dbDir,
12524
+ host: {
12525
+ catalog: () => readJevCatalog(ctx),
12526
+ models: (provider) => readProviderModels(ctx, provider),
12527
+ connection: (provider, model, timeoutMs, endpoint) => resolveJevConnection(ctx, provider, model, timeoutMs, endpoint)
12528
+ }
11927
12529
  },
11928
12530
  history: {
11929
12531
  estimate: historyApi.estimate,
@@ -11956,7 +12558,7 @@ function apply(ctx, config = {}) {
11956
12558
  embedder,
11957
12559
  mode,
11958
12560
  routeOverride: resolved.routeOverride,
11959
- ...resolveJevField(resolved.jev, resolved.dbDir),
12561
+ ...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => (resolved.routeOverride ?? routeFromEvents(events))?.provider),
11960
12562
  call: (params) => streamText(ctx, {
11961
12563
  ...params,
11962
12564
  sessionId: session.id