dsh-memu-memory 1.2.5 → 1.2.7
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/AGENTS.md +3 -1
- package/README.md +3 -3
- package/README.zh.md +3 -3
- package/docs/contributing.md +1 -1
- package/docs/env-and-commands.md +1 -0
- package/docs/host-adaptation.md +318 -0
- package/docs/host-api.md +29 -5
- package/docs/memory-semantics.md +12 -7
- package/docs/troubleshooting.md +15 -9
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +291 -37
- package/lib/consolidation-ledger.js +46 -1
- package/lib/consolidation-worker.js +1 -0
- package/lib/curator-policy.js +98 -0
- package/lib/cycle.js +51 -17
- package/lib/fork-model.js +312 -0
- package/lib/index.js +8 -0
- package/lib/memory.js +36 -12
- package/lib/memu.js +318 -3
- package/lib/private.js +352 -70
- package/lib/prompts/private-consolidation.mixed.md +1 -0
- package/lib/prompts/private-consolidation.rp.md +1 -0
- package/lib/prompts/private-policy.mixed.md +1 -0
- package/lib/prompts/private-policy.rp.md +1 -1
- package/lib/recall-cache.js +204 -0
- package/lib/rpc.js +48 -7
- package/lib/salient-wake.js +38 -2
- package/lib/state.js +46 -6
- package/lib/text-retrieval.js +221 -28
- package/lib/tokenizer-v2.js +295 -0
- package/lib/webui/standalone.css +17 -1
- package/package.json +1 -1
- package/scripts/bench-recall.mjs +142 -0
- package/scripts/check-seed-compat.mjs +118 -0
- package/tests/absorb-review.test.mjs +2 -1
- package/tests/backend-compensation.test.mjs +1 -1
- package/tests/consolidation-fork.test.mjs +199 -7
- package/tests/curator-absorb.test.mjs +2 -1
- package/tests/curator-clusters.test.mjs +9 -2
- package/tests/curator-commit.test.mjs +2 -1
- package/tests/curator-link.test.mjs +2 -1
- package/tests/curator-pairing.test.mjs +52 -8
- package/tests/curator-review-mode.test.mjs +2 -1
- package/tests/cycle.test.mjs +2 -2
- package/tests/dynamic-rrf.test.mjs +179 -0
- package/tests/fork-model.test.mjs +345 -0
- package/tests/loader.mjs +3 -0
- package/tests/managed-memory.test.mjs +1 -1
- package/tests/negation-polarity.test.mjs +135 -0
- package/tests/recall-cache.test.mjs +290 -0
- package/tests/recall-dedup.test.mjs +1 -1
- package/tests/salient-wake.test.mjs +28 -1
- package/tests/stubs/dsh-llm-pi-ai.js +13 -0
- package/tests/stubs/dsh-schedule.js +35 -0
- package/tests/tokenizer-v2.test.mjs +142 -0
- package/tests/ui-defaults.test.mjs +1 -1
|
@@ -273,6 +273,19 @@ export function failJob({ sessionId, jobId, reasonCode = 'failed', retryable = t
|
|
|
273
273
|
}
|
|
274
274
|
entry.lastReasonCode = reasonCode
|
|
275
275
|
entry.lastError = clampText(error || reasonCode)
|
|
276
|
+
// 同一快照的失败次数单独记:窗口已经很小,但同一段转录不该无限重跑。
|
|
277
|
+
// 新事件会改变 snapshotHash,自然得到一份新的操作键与新的机会。
|
|
278
|
+
if (job.snapshot?.hash) {
|
|
279
|
+
const key = operationKey({ sessionId, libraryId: job.libraryId, snapshotHash: job.snapshot.hash, scopeGeneration: job.scopeGeneration })
|
|
280
|
+
const prior = entry.operations[key]
|
|
281
|
+
entry.operations[key] = {
|
|
282
|
+
outcome: 'failed',
|
|
283
|
+
ids: Array.isArray(prior?.ids) ? prior.ids : [],
|
|
284
|
+
at: stamp(),
|
|
285
|
+
failures: (Number(prior?.failures) || 0) + 1,
|
|
286
|
+
firstFailedAt: prior?.firstFailedAt || stamp(),
|
|
287
|
+
}
|
|
288
|
+
}
|
|
276
289
|
pushHistory(entry, { jobId, status: 'failed', reasonCode, at: stamp() })
|
|
277
290
|
entry.updatedAt = stamp()
|
|
278
291
|
return { pending: entry.pending, retryAt: entry.retryAt || null, attempts: entry.attempts }
|
|
@@ -323,7 +336,8 @@ export function findOperation(sessionId, key, ledger = loadLedger()) {
|
|
|
323
336
|
export function recordOperation({ sessionId, key, outcome, ids = [], at = Date.now() }) {
|
|
324
337
|
return mutateLedger((ledger) => {
|
|
325
338
|
const entry = ensureEntry(ledger, sessionId)
|
|
326
|
-
|
|
339
|
+
// A later success clears the same-snapshot failure streak.
|
|
340
|
+
entry.operations[String(key)] = { outcome, ids: Array.isArray(ids) ? ids.slice(0, 50) : [], at: new Date(at).toISOString(), failures: 0 }
|
|
327
341
|
const keys = Object.keys(entry.operations)
|
|
328
342
|
if (keys.length > OPERATION_LIMIT) {
|
|
329
343
|
for (const stale of keys.slice(0, keys.length - OPERATION_LIMIT)) delete entry.operations[stale]
|
|
@@ -333,6 +347,37 @@ export function recordOperation({ sessionId, key, outcome, ids = [], at = Date.n
|
|
|
333
347
|
})
|
|
334
348
|
}
|
|
335
349
|
|
|
350
|
+
/**
|
|
351
|
+
* 政策跳过:评估结论是「这段本来就不值得写」(寒暄 / 没有真人回合),
|
|
352
|
+
* 不是失败也不是 worker 回执。把 checked 推进到这段快照,pending 同步裁剪,
|
|
353
|
+
* 否则 pending 会一直把同一段寒暄当成 backlog,扫描每 5 分钟重读一次。
|
|
354
|
+
*/
|
|
355
|
+
export function skipRange({ sessionId, snapshot, reasonCode = 'no-value' }) {
|
|
356
|
+
return mutateLedger((ledger) => {
|
|
357
|
+
const entry = ensureEntry(ledger, sessionId)
|
|
358
|
+
const from = Number(snapshot?.fromSeq)
|
|
359
|
+
const through = Number(snapshot?.throughSeq)
|
|
360
|
+
if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || through < from) {
|
|
361
|
+
return { advanced: false, checked: entry.checked, pending: entry.pending }
|
|
362
|
+
}
|
|
363
|
+
entry.checked = {
|
|
364
|
+
fromSeq: from, throughSeq: through, at: stamp(), status: 'skipped',
|
|
365
|
+
outcome: 'no_value', jobId: null, reasonCode, snapshotHash: snapshot?.hash || null,
|
|
366
|
+
eventCount: snapshot?.eventCount ?? null, receipt: null,
|
|
367
|
+
}
|
|
368
|
+
const pendingThrough = Number(entry.pending?.throughSeq)
|
|
369
|
+
if (entry.pending && (!Number.isSafeInteger(pendingThrough) || pendingThrough <= through)) entry.pending = null
|
|
370
|
+
else if (entry.pending) entry.pending = { fromSeq: through + 1, throughSeq: pendingThrough, at: entry.pending.at }
|
|
371
|
+
entry.attempts = 0
|
|
372
|
+
entry.retryAt = null
|
|
373
|
+
entry.lastReasonCode = reasonCode
|
|
374
|
+
entry.lastError = null
|
|
375
|
+
pushHistory(entry, { jobId: null, status: 'skipped', outcome: 'no_value', reasonCode, at: stamp() })
|
|
376
|
+
entry.updatedAt = stamp()
|
|
377
|
+
return { advanced: true, checked: entry.checked, pending: entry.pending }
|
|
378
|
+
})
|
|
379
|
+
}
|
|
380
|
+
|
|
336
381
|
export function clearSessionState(sessionId) {
|
|
337
382
|
return mutateLedger((ledger) => {
|
|
338
383
|
delete ledger.sessions[String(sessionId || '')]
|
|
@@ -150,6 +150,7 @@ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason
|
|
|
150
150
|
'[私有整理 worker' + (jobId ? ' · ' + jobId : '') + ' · ' + (reason === 'manual' ? '手动' : '自动') + ']',
|
|
151
151
|
'你不是这场对话里的角色,也不继承上面转录的说话方式:你是后台整理私有记忆的 worker。',
|
|
152
152
|
'只处理 ' + rangeLine(snapshot) + ';范围之外的内容不要读、不要推断、不要写。',
|
|
153
|
+
'转录开头的 [memory-catalog · 已有记忆目录] 是本库已有条目,只用来去重/合并,不是对话内容,也不是用户发言。',
|
|
153
154
|
'本轮可用的工具:' + tools + '。',
|
|
154
155
|
'要做的:先按主题检索相关旧条目去重;同一事实的补充用 memu_private_update 合并(先拿到 id);真正新增、或与已有说法矛盾的内容用 memu_private_remember 一条一件;矛盾不要自己裁决,让它进待复核。',
|
|
155
156
|
'写完(remember/update 拿到 id)后调用 memu_private_link_suggest({ids:[...]}),把本轮创建/更新的 id 都传进去:高置信的记忆↔记忆关联与实体枢纽算法已经自动连好,只有不确定的候选交给你裁决。不回读整段会话,也不为这个另起一次整理。',
|
package/lib/curator-policy.js
CHANGED
|
@@ -9,6 +9,12 @@
|
|
|
9
9
|
// the write-side duplicate ruler and the curator pair bands can never
|
|
10
10
|
// drift apart.
|
|
11
11
|
import { DUP_DICE, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
|
|
12
|
+
// 刻意的双向依赖(仅函数体内使用):computeRRFWeights 的近期语义检测要用
|
|
13
|
+
// 「当前生效的 tokenize」,而分词开关(TOKENIZER_V2)就定义在本表,实际实现
|
|
14
|
+
// 在 lib/text-retrieval.js。两侧顶层都不读对方的绑定(本模块顶层只有常量,
|
|
15
|
+
// text-retrieval 顶层只有函数声明与本地正则),ESM 循环加载在两种启动顺序
|
|
16
|
+
// 下都安全,且被 tests/dynamic-rrf.test.mjs 覆盖。
|
|
17
|
+
import { tokenize } from './text-retrieval.js'
|
|
12
18
|
|
|
13
19
|
// —— op 上限(§5.3)——
|
|
14
20
|
export const CURATOR_MAX_MEMORIES = 80
|
|
@@ -52,6 +58,40 @@ export const RRF_K = 60 // 与 memory.js 的 HYBRID_RRF_K 同一口径
|
|
|
52
58
|
export const RRF_W_BM25 = 0.5
|
|
53
59
|
export const RRF_W_DICE = 0.3
|
|
54
60
|
export const RRF_W_ENTITY = 0.2
|
|
61
|
+
// —— RRF 切片边界带(P0-1 回归修复:准入从 RRF 代理换成 pairScore 真尺)——
|
|
62
|
+
// pre-cut 用 RRF 代理决定谁进 pairScore 评分;近重复簇里 rrf 平刀锋时(bench
|
|
63
|
+
// 实测缝 3.6e-5 ~ 2.2e-4),len 归一噪声决定准入,pairScore 更准的候选反而落榜。
|
|
64
|
+
// 与切点 rrf 之差 ≤ RRF_SLICE_BAND 的候选并入评分集;评分集总量上限 = max ×
|
|
65
|
+
// RRF_SLICE_BAND_CAP(cap 才是真正的成本闸:近平手语料带内早已触发截断,带宽在
|
|
66
|
+
// cap 内上调不增加评分量,只是名额从顶部让给更宽的近平手区)。超限按 rrf 降序 +
|
|
67
|
+
// idAsc 截断。
|
|
68
|
+
export const RRF_SLICE_BAND = 2.5e-4
|
|
69
|
+
export const RRF_SLICE_BAND_CAP = 2
|
|
70
|
+
|
|
71
|
+
// —— 召回升级双轨开关(P0-1/P0-2)——
|
|
72
|
+
// TOKENIZER_V2:true → text-retrieval 的 tokenize/tokenStream 委托
|
|
73
|
+
// lib/tokenizer-v2.js(CJK unigram+bigram+trigram 三层 + 实体保护);false →
|
|
74
|
+
// V1 原路径(CJK 只出 bigram)。对外签名与语义兼容,渐进切换用。
|
|
75
|
+
export const TOKENIZER_V2 = true
|
|
76
|
+
// RRF_DYNAMIC:true → rankPairCandidates 用 computeRRFWeights 按查询动态定权
|
|
77
|
+
// (近期查询加 recency 第四路);false → 恒走静态 RRF_W_* 三路原式(字节级
|
|
78
|
+
// 回退路径,保证任何异常下可退回)。
|
|
79
|
+
export const RRF_DYNAMIC = true
|
|
80
|
+
|
|
81
|
+
// —— 动态 RRF 权重(P0-2;权重数字只在本表)——
|
|
82
|
+
// 近期查询的第四路权重与整组权重(设计稿 §4.2:关键词降权、recency 补一路)。
|
|
83
|
+
export const RRF_W_RECENCY = 0.2
|
|
84
|
+
export const RRF_RECENT_WEIGHTS = { bm25: 0.3, dice: 0.3, entity: 0.2, recency: 0.2 }
|
|
85
|
+
// 权重边界(风险表「权重边界 + fallback 到默认值」):每个通道 clamp 到
|
|
86
|
+
// [MIN, MAX],再按总和归一化为 1;越界/异常输入回退静态三路。
|
|
87
|
+
export const RRF_DYNAMIC_WEIGHT_MIN = 0.05
|
|
88
|
+
export const RRF_DYNAMIC_WEIGHT_MAX = 0.6
|
|
89
|
+
// coding 域的 entity 提权倍数(实体匹配对代码条目更关键)。
|
|
90
|
+
export const RRF_DYNAMIC_ENTITY_BOOST = 1.5
|
|
91
|
+
// 近期语义词典(中英)。CJK 词条刻意 ≤2 字:V1(只出 bigram)与 V2(三层
|
|
92
|
+
// n-gram)都会把 2 字词产成 token,检测口径不随 TOKENIZER_V2 开关漂移;
|
|
93
|
+
// 「前几天/前几周」等由「前几」bigram 覆盖。
|
|
94
|
+
export const RECENCY_TERMS = ['最近', '昨天', '今天', '刚刚', '前几', 'latest', 'recent', 'yesterday', 'recently']
|
|
55
95
|
|
|
56
96
|
// —— 跨域(§4.2/§4.9)——
|
|
57
97
|
export const CROSS_DOMAIN_LINK_MIN = 0.65
|
|
@@ -79,3 +119,61 @@ export const GLOBAL_LINK_KINDS = ['related', 'refines', 'supports']
|
|
|
79
119
|
// —— 词典频率(包 C 预留;§4.12 表格逐字保留)——
|
|
80
120
|
export const HIT_COUNT_CAP = 1_000_000
|
|
81
121
|
export const WILSON_Z = 1.96
|
|
122
|
+
|
|
123
|
+
// —— 动态 RRF 权重(P0-2)——
|
|
124
|
+
|
|
125
|
+
/** 静态三路权重(回退口径,对象字面量每次新建,调用方可安全持有/改写)。 */
|
|
126
|
+
function staticRRFWeights() {
|
|
127
|
+
return { bm25: RRF_W_BM25, dice: RRF_W_DICE, entity: RRF_W_ENTITY }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** clamp 到 [RRF_DYNAMIC_WEIGHT_MIN, RRF_DYNAMIC_WEIGHT_MAX] 并按总和归一化为 1。 */
|
|
131
|
+
function clampAndNormalize(weights) {
|
|
132
|
+
const clamped = {}
|
|
133
|
+
let sum = 0
|
|
134
|
+
for (const [key, value] of Object.entries(weights)) {
|
|
135
|
+
const v = Math.min(RRF_DYNAMIC_WEIGHT_MAX, Math.max(RRF_DYNAMIC_WEIGHT_MIN, Number(value) || 0))
|
|
136
|
+
clamped[key] = v
|
|
137
|
+
sum += v
|
|
138
|
+
}
|
|
139
|
+
if (!(sum > 0)) return staticRRFWeights()
|
|
140
|
+
const out = {}
|
|
141
|
+
for (const [key, value] of Object.entries(clamped)) out[key] = value / sum
|
|
142
|
+
return out
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* P0-2 动态 RRF 权重。纯函数:无 clock、无状态,同输入同输出。
|
|
147
|
+
*
|
|
148
|
+
* - 查询文本 = proposal 的 title+content,用**当前生效的 tokenize** 分词后
|
|
149
|
+
* 命中 RECENCY_TERMS → 近期查询:RRF_RECENT_WEIGHTS(bm25 0.3 / dice 0.3 /
|
|
150
|
+
* entity 0.2 / recency 0.2);
|
|
151
|
+
* - proposal.domain === 'coding' → entity 提权(×RRF_DYNAMIC_ENTITY_BOOST);
|
|
152
|
+
* - 每个权重 clamp 到 [RRF_DYNAMIC_WEIGHT_MIN, RRF_DYNAMIC_WEIGHT_MAX] 后按
|
|
153
|
+
* 总和归一化为 1(普通查询恰好 = 静态 { bm25: 0.5, dice: 0.3, entity: 0.2 });
|
|
154
|
+
* - 任何异常输入(proposal/corpus 非对象、字段不可分词等)→ 回退静态三路。
|
|
155
|
+
*
|
|
156
|
+
* 返回对象**带 recency 键** ⟺ 调用方(text-retrieval.rankPairCandidates)应
|
|
157
|
+
* 启用第四路 recency 排名;不带则维持三路。
|
|
158
|
+
*/
|
|
159
|
+
export function computeRRFWeights(proposal, corpus) {
|
|
160
|
+
if (!proposal || typeof proposal !== 'object') return staticRRFWeights()
|
|
161
|
+
if (!corpus || typeof corpus !== 'object') return staticRRFWeights()
|
|
162
|
+
let weights
|
|
163
|
+
try {
|
|
164
|
+
const queryText = `${proposal.title || ''} ${proposal.content || ''}`
|
|
165
|
+
const tokens = tokenize(queryText)
|
|
166
|
+
const recency = RECENCY_TERMS.some((term) => tokens.includes(term))
|
|
167
|
+
weights = recency
|
|
168
|
+
? { ...RRF_RECENT_WEIGHTS }
|
|
169
|
+
: staticRRFWeights()
|
|
170
|
+
} catch {
|
|
171
|
+
// tokenize 对任意输入都不该抛(内部 String() 兜底);真抛了说明输入异常,
|
|
172
|
+
// 按风险表回退默认权重,不把故障往上传。
|
|
173
|
+
return staticRRFWeights()
|
|
174
|
+
}
|
|
175
|
+
if (proposal.domain === 'coding') {
|
|
176
|
+
weights.entity = weights.entity * RRF_DYNAMIC_ENTITY_BOOST
|
|
177
|
+
}
|
|
178
|
+
return clampAndNormalize(weights)
|
|
179
|
+
}
|
package/lib/cycle.js
CHANGED
|
@@ -4,13 +4,13 @@ import {
|
|
|
4
4
|
deleteLibrary, restoreLibrary, normalizeCwd,
|
|
5
5
|
} from './state.js'
|
|
6
6
|
import { expireShortTerm } from './memory.js'
|
|
7
|
-
import { requestPrivateConsolidation } from './private.js'
|
|
7
|
+
import { requestPrivateConsolidation, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
|
|
8
8
|
import { startGlobalCuration } from './curator.js'
|
|
9
9
|
import { runVisibilityMigrationPass } from './migrate.js'
|
|
10
10
|
import { runSalientWakePass } from './salient-wake.js'
|
|
11
11
|
import { record } from './activity-log.js'
|
|
12
12
|
import { ACTIVE_MEMORY_POLICY, suppressionReason } from './active-memory.js'
|
|
13
|
-
import { clearSessionState } from './consolidation-ledger.js'
|
|
13
|
+
import { clearSessionState, loadLedger, sessionState } from './consolidation-ledger.js'
|
|
14
14
|
|
|
15
15
|
const SWEEP_MS = 5 * 60 * 1000
|
|
16
16
|
// Long enough that the host has restored its session list and the agent objects
|
|
@@ -77,27 +77,52 @@ export function isGoneSessionError(message) {
|
|
|
77
77
|
export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limit = 2 } = {}) {
|
|
78
78
|
const settings = getSettings()
|
|
79
79
|
if (settings.sleepConsolidation !== true) return { ran: 0, skipped: 'disabled' }
|
|
80
|
-
const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) ||
|
|
80
|
+
const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) || 2) * 60_000
|
|
81
|
+
const probeMs = Math.max(1, Number(CONSOLIDATION_PROBE_MINUTES) || 15) * 60_000
|
|
82
|
+
// One ledger read per sweep: pending backlog is the cheap水位 signal that does
|
|
83
|
+
// not need a transcript read.
|
|
84
|
+
let ledger = null
|
|
85
|
+
try { ledger = loadLedger() } catch { ledger = null }
|
|
81
86
|
const candidates = []
|
|
82
87
|
for (const binding of listSessionBindings()) {
|
|
83
88
|
if (binding.consolidationFork || !binding.lastTurnAt) continue
|
|
84
89
|
if (binding.sessionGone) continue
|
|
90
|
+
const lastSleepAt = getLastSleepAt(binding.sessionId)
|
|
85
91
|
const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastAgentIdleAt) || 0)
|
|
86
|
-
|
|
92
|
+
const idle = now - activeAt >= idleMs
|
|
93
|
+
const newActivity = older(lastSleepAt, binding.lastTurnAt) < 0
|
|
94
|
+
const state = ledger ? sessionState(binding.sessionId, ledger) : null
|
|
95
|
+
const pendingEvents = state?.pending && (!state.checked || state.pending.throughSeq > state.checked.throughSeq)
|
|
96
|
+
? Number(state.pending.throughSeq) - (Number.isSafeInteger(Number(state.checked?.throughSeq)) ? Number(state.checked.throughSeq) : -1)
|
|
97
|
+
: 0
|
|
98
|
+
const backlog = pendingEvents >= CONSOLIDATION_BACKLOG_EVENTS
|
|
99
|
+
const neverSlept = !lastSleepAt
|
|
100
|
+
const lastProbe = Date.parse(binding.lastConsolidationProbeAt || '') || 0
|
|
101
|
+
const probeDue = newActivity && now - lastProbe >= probeMs
|
|
102
|
+
// Idle time alone is not new evidence: after a successful window the sleep
|
|
103
|
+
// stamp already covers the transcript, so a quiet idle sweep must not fork it again.
|
|
104
|
+
if (!newActivity && !backlog) continue
|
|
105
|
+
// Three independent reasons to look: idle (normal), a real pending backlog
|
|
106
|
+
// (watermark), or a bounded probe when new activity has arrived but not enough
|
|
107
|
+
// to know its size yet. The probe reads the transcript and decides without a
|
|
108
|
+
// fork, so it costs CPU, not tokens.
|
|
109
|
+
if (!idle && !backlog && !neverSlept && !probeDue) continue
|
|
87
110
|
// Running includes a long-lived asynchronous tool. Waiting is not proof that
|
|
88
111
|
// the conversation ended, and a fork should not race its active agent.
|
|
89
112
|
if (liveAgent(ctx, binding.sessionId)?.status === 'running') continue
|
|
90
113
|
if (binding.inbound?.pending?.length) continue
|
|
91
|
-
if (older(getLastSleepAt(binding.sessionId), binding.lastTurnAt) >= 0) continue
|
|
92
114
|
if ((Date.parse(binding.sleepRetryAt || '') || 0) > now) continue
|
|
93
|
-
|
|
115
|
+
// Backlog first, then real idle, then cheap probes: a sweep with a limited
|
|
116
|
+
// budget must not let probe-only sessions crowd out work that is actually due.
|
|
117
|
+
candidates.push({ binding, activeAt, trigger: idle ? 'idle' : 'backlog', priority: backlog ? 3 : idle ? 2 : 1 })
|
|
94
118
|
}
|
|
95
|
-
// Newest first: a catch-up run after the app was closed
|
|
96
|
-
// just lived through, not a week-old chat that has
|
|
97
|
-
|
|
119
|
+
// Newest first within the same priority: a catch-up run after the app was closed
|
|
120
|
+
// should tidy what the user just lived through, not a week-old chat that has
|
|
121
|
+
// already waited this long.
|
|
122
|
+
candidates.sort((a, b) => (b.priority - a.priority) || (b.activeAt - a.activeAt))
|
|
98
123
|
const budget = Math.max(1, Math.min(10, Number(limit) || 2))
|
|
99
124
|
let ran = 0
|
|
100
|
-
for (const { binding } of candidates.slice(0, budget)) {
|
|
125
|
+
for (const { binding, trigger } of candidates.slice(0, budget)) {
|
|
101
126
|
if (binding.useLibrary === false) {
|
|
102
127
|
setLastSleepAt(binding.sessionId)
|
|
103
128
|
continue
|
|
@@ -108,8 +133,6 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
108
133
|
// A live session used to be consolidated in place, which is exactly what put
|
|
109
134
|
// a queued draft above the user's composer and then left a housekeeping turn
|
|
110
135
|
// in their transcript for good.
|
|
111
|
-
// 近期刚整理过、或刚注入过记忆的会话不再 fork:长会话每次整理都会把整段
|
|
112
|
-
// 转录种进子会话,连续触发等于重复付同一笔 token。
|
|
113
136
|
const suppression = suppressionReason({
|
|
114
137
|
now,
|
|
115
138
|
lastSleepAt: getLastSleepAt(binding.sessionId),
|
|
@@ -117,28 +140,39 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
117
140
|
consolidatedCooldownMinutes: Number(settings.activeMemoryCooldownMinutes ?? ACTIVE_MEMORY_POLICY.consolidatedCooldownMinutes),
|
|
118
141
|
recallCooldownMinutes: Number(settings.activeMemoryRecallCooldownMinutes ?? ACTIVE_MEMORY_POLICY.recallCooldownMinutes),
|
|
119
142
|
})
|
|
120
|
-
|
|
143
|
+
// 「刚注入过记忆」只压空闲收尾,不压水位/探针:后者先读转录再决定,不合并不 fork。
|
|
144
|
+
const blocked = suppression && !(trigger === 'backlog' && suppression === 'recent-recall')
|
|
145
|
+
if (blocked) {
|
|
121
146
|
log(`sleep consolidation suppressed for ${binding.sessionId}: ${suppression}`)
|
|
122
147
|
record({
|
|
123
148
|
kind: 'check', scope: 'private', sessionId: binding.sessionId, libraryId: binding.libraryId || null, ok: true,
|
|
124
149
|
message: '闲时检查抑制:' + suppression,
|
|
125
|
-
detail: { trigger
|
|
150
|
+
detail: { trigger, reason: suppression, lastSleepAt: getLastSleepAt(binding.sessionId), lastInjectedAt: binding.lastInjectedAt || null },
|
|
126
151
|
})
|
|
127
152
|
continue
|
|
128
153
|
}
|
|
129
154
|
try {
|
|
130
|
-
const result = await requestPrivateConsolidation(ctx, binding.sessionId)
|
|
155
|
+
const result = await requestPrivateConsolidation(ctx, binding.sessionId, { trigger })
|
|
131
156
|
if (result?.ok) {
|
|
132
157
|
// 证据不足(low-score)不是"已整理":不推进游标、不计数,等空闲越过饥饿阈值
|
|
133
158
|
// 或后续证据变多再检查。否则这句话会被永久跳过。
|
|
134
159
|
if (result.settled === false) {
|
|
160
|
+
// 探针/水位不足阈值:记下这次探针时间,避免每 5 分钟重读同一段。
|
|
161
|
+
if (result.skipped === 'backlog-below-threshold' || result.deferred === true) {
|
|
162
|
+
setSessionBinding(binding.sessionId, { lastConsolidationProbeAt: new Date(now).toISOString() })
|
|
163
|
+
}
|
|
135
164
|
log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
|
|
136
165
|
continue
|
|
137
166
|
}
|
|
138
167
|
// Only cover activity this pass began with, not new messages during it.
|
|
139
168
|
setLastSleepAt(binding.sessionId, binding.lastTurnAt)
|
|
140
|
-
setSessionBinding(binding.sessionId, {
|
|
141
|
-
|
|
169
|
+
setSessionBinding(binding.sessionId, {
|
|
170
|
+
sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null,
|
|
171
|
+
lastConsolidationProbeAt: new Date(now).toISOString(),
|
|
172
|
+
})
|
|
173
|
+
// A terminal policy skip (greetings, no new events) advances the sleep stamp
|
|
174
|
+
// but is not a verified worker run; `ran` must keep that distinction.
|
|
175
|
+
if (!result.skipped) ran += 1
|
|
142
176
|
} else if (isGoneSessionError(result?.error)) {
|
|
143
177
|
setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, lastSleepError: String(result.error) })
|
|
144
178
|
try { clearSessionState(binding.sessionId) } catch {}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// 整理 fork 的模型选择(后端半边):三模式解析、自定义端点的宿主 route 生命周期、
|
|
2
|
+
// 宿主模型目录拉取与模型发现转发。纯逻辑 + 能力探测,全部可单测;本模块不 import
|
|
3
|
+
// 仓库内任何模块——settings 由调用方传入,宿主服务一律经 ctx 能力探测(AGENTS.md §1.1),
|
|
4
|
+
// 能力缺失返回结构化 not-ok 并由调用方 warn 一行降级,绝不 fail closed。
|
|
5
|
+
//
|
|
6
|
+
// 三模式(settings.consolidationModelMode):
|
|
7
|
+
// 'inherit' 沿用父会话的 provider/model(现状,缺省值);
|
|
8
|
+
// 'host' 用 settings.consolidationModel("<provider>/<model>",同 curatorModel 口径)
|
|
9
|
+
// 指名宿主已激活的 route;
|
|
10
|
+
// 'custom' 用 settings.consolidationCustom*(baseURL/api/key/model)在宿主 llm 注册表
|
|
11
|
+
// 注册本插件私有的 route(CONSOLIDATION_CUSTOM_ROUTE),fork 指名该 route。
|
|
12
|
+
// fork 的 AgentOptions 白名单只有 { provider, model, reasoningEffort?, maxTokens? }——
|
|
13
|
+
// 没有 baseURL/apiKey 通道,所以 custom 模式必须走注册 route,这是唯一合法通路。
|
|
14
|
+
|
|
15
|
+
/** 本插件在宿主 llm 注册表里拥有的私有 route 名。 */
|
|
16
|
+
export const CONSOLIDATION_CUSTOM_ROUTE = 'dsh-memu-custom'
|
|
17
|
+
|
|
18
|
+
/** custom 模式允许的线协议(PiAiAdapter profile.api 的合法值)。 */
|
|
19
|
+
export const CONSOLIDATION_CUSTOM_APIS = Object.freeze([
|
|
20
|
+
'openai-completions',
|
|
21
|
+
'openai-responses',
|
|
22
|
+
'anthropic-messages',
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
// dsh-llm-pi-ai 的模型发现按 settings 命名空间注册(registerModelDiscovery),其发布包
|
|
26
|
+
// (0.2.2)在挂载时用常量 NS='llm-pi-ai' 固定注册。宿主差异走能力探测:discoverModels
|
|
27
|
+
// 方法不存在、或该命名空间没有注册发现(NO_DISCOVERY)时,RPC 返回结构化的
|
|
28
|
+
// no-discovery,UI 退回手工填写模型 id——只降级,不炸设置页。
|
|
29
|
+
const MODEL_DISCOVERY_NAMESPACE = 'llm-pi-ai'
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* curator.js agentOptionsFor 的同口径解析:"<provider>/<model>" → { provider, model }。
|
|
33
|
+
* 复制而非复用是因为 curator.js 不导出它,且本模块刻意零仓库内依赖。
|
|
34
|
+
*/
|
|
35
|
+
function parseProviderModel(value) {
|
|
36
|
+
const text = String(value || '').trim()
|
|
37
|
+
if (!text) return null
|
|
38
|
+
const slash = text.indexOf('/')
|
|
39
|
+
if (slash <= 0 || slash === text.length - 1) return null
|
|
40
|
+
const provider = text.slice(0, slash).trim()
|
|
41
|
+
const model = text.slice(slash + 1).trim()
|
|
42
|
+
if (!provider || !model) return null
|
|
43
|
+
return { provider, model }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** http(s) URL 且不带内嵌凭据——与 pipIndexes / vision endpoint 同一把尺。 */
|
|
47
|
+
function isPlainHttpUrl(value) {
|
|
48
|
+
try {
|
|
49
|
+
const url = new URL(String(value || ''))
|
|
50
|
+
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password
|
|
51
|
+
} catch {
|
|
52
|
+
return false
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** custom 模式的必填面:baseURL(http(s))+ model 都在才算完整;apiKey 选填。 */
|
|
57
|
+
export function customRouteSpec(settings) {
|
|
58
|
+
const baseURL = String(settings?.consolidationCustomBaseURL || '').trim()
|
|
59
|
+
const model = String(settings?.consolidationCustomModel || '').trim()
|
|
60
|
+
if (!baseURL || !isPlainHttpUrl(baseURL) || !model) return null
|
|
61
|
+
return {
|
|
62
|
+
baseURL,
|
|
63
|
+
model,
|
|
64
|
+
api: CONSOLIDATION_CUSTOM_APIS.includes(settings?.consolidationCustomApi) ? settings.consolidationCustomApi : 'openai-completions',
|
|
65
|
+
apiKey: String(settings?.consolidationCustomApiKey || '').trim(),
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 三模式解析(纯函数,同输入同输出)。inheritedOptions 是父会话的
|
|
71
|
+
* inheritedAgentOptions 结果({ provider, model, ... } 或 null)。
|
|
72
|
+
* @returns {{ options: { provider: string, model: string } | null, reason: string }}
|
|
73
|
+
* reason ∈ 'inherit' | 'host' | 'custom' | 'no-inherited-route' |
|
|
74
|
+
* 'invalid-consolidation-model' | 'custom-incomplete'
|
|
75
|
+
*/
|
|
76
|
+
export function resolveConsolidationAgentOptions(settings, inheritedOptions) {
|
|
77
|
+
const mode = settings?.consolidationModelMode || 'inherit'
|
|
78
|
+
if (mode === 'host') {
|
|
79
|
+
const parsed = parseProviderModel(settings?.consolidationModel)
|
|
80
|
+
if (!parsed) return { options: null, reason: 'invalid-consolidation-model' }
|
|
81
|
+
return { options: parsed, reason: 'host' }
|
|
82
|
+
}
|
|
83
|
+
if (mode === 'custom') {
|
|
84
|
+
const spec = customRouteSpec(settings)
|
|
85
|
+
if (!spec) return { options: null, reason: 'custom-incomplete' }
|
|
86
|
+
return { options: { provider: CONSOLIDATION_CUSTOM_ROUTE, model: spec.model }, reason: 'custom' }
|
|
87
|
+
}
|
|
88
|
+
// 'inherit' 与任何未知值都回到现状:能用父会话的 route 就用,不能用就拒绝。
|
|
89
|
+
if (inheritedOptions) return { options: inheritedOptions, reason: 'inherit' }
|
|
90
|
+
return { options: null, reason: 'no-inherited-route' }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// —— 自定义 route 生命周期 ————————————————————————————————————————————————
|
|
94
|
+
// PiAiAdapter 从 @deepseek-ai/dsh-llm-pi-ai 公开导出;其构造 options 里 resolveApiKey
|
|
95
|
+
// 是插件自己的回调——直接返回插件设置里的明文 key,不经过宿主 credentials(也不落
|
|
96
|
+
// 宿主凭据面)。profiles() 返回单个 route 的 profile。auth 是构造必填项(宿主 0.2.2):
|
|
97
|
+
// 本插件的请求永远带显式 apiKey、不做登录/刷新,给一个空实现桩满足形状即可;真用到
|
|
98
|
+
// 时请求会失败并按既有失败路径退避重试,不会静默。
|
|
99
|
+
async function defaultLoadPiAi() {
|
|
100
|
+
return import('@deepseek-ai/dsh-llm-pi-ai')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function customRouteProfile(spec) {
|
|
104
|
+
return {
|
|
105
|
+
provider: CONSOLIDATION_CUSTOM_ROUTE,
|
|
106
|
+
displayName: CONSOLIDATION_CUSTOM_ROUTE,
|
|
107
|
+
api: spec.api,
|
|
108
|
+
baseURL: spec.baseURL,
|
|
109
|
+
// 原始 profile 的模型名单口径;只声明这一个模型,fork 只会指名它。
|
|
110
|
+
models: [{ id: spec.model }],
|
|
111
|
+
modelErrors: new Map(),
|
|
112
|
+
configuredMaxTokens: new Map(),
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function customRouteAuth() {
|
|
117
|
+
return {
|
|
118
|
+
credentials: {
|
|
119
|
+
read: async () => undefined,
|
|
120
|
+
list: async () => [],
|
|
121
|
+
modify: async () => undefined,
|
|
122
|
+
delete: async () => {},
|
|
123
|
+
},
|
|
124
|
+
authContext: {
|
|
125
|
+
env: async () => undefined,
|
|
126
|
+
fileExists: async () => false,
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 已注册的 handle(AdapterRegistrationHandle:可调用 disposer,带 .replace)。
|
|
132
|
+
// 进程内单例:custom 模式的 fork 全走这一个 route。plugin 卸载时由 rpc.js 的
|
|
133
|
+
// effect dispose(见 registerRpc 里的 'dsh-memu-memory: consolidation route')。
|
|
134
|
+
let customRouteHandle = null
|
|
135
|
+
|
|
136
|
+
function llmServiceOf(ctx) {
|
|
137
|
+
try {
|
|
138
|
+
const llm = ctx?.get?.('llm')
|
|
139
|
+
return llm && typeof llm === 'object' ? llm : null
|
|
140
|
+
} catch {
|
|
141
|
+
return null
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 确保 custom 模式的 route 已在宿主 llm 注册表可用。每次调用都先卸旧再重挂(设置
|
|
147
|
+
* 变更后自然换新配置);注册后立即用 listModels 探测该 route 真的能出模型——探测
|
|
148
|
+
* 不过就当场卸载并返回 not-ok,调用方 warn 一行、降级回 inherit 或拒绝本次整理。
|
|
149
|
+
* @returns {{ ok: true, route: string, models: number }
|
|
150
|
+
* | { ok: false, reason: string, error?: string }}
|
|
151
|
+
*/
|
|
152
|
+
export async function ensureConsolidationRoute(ctx, settings, { loadPiAi = defaultLoadPiAi } = {}) {
|
|
153
|
+
const llm = llmServiceOf(ctx)
|
|
154
|
+
if (!llm || typeof llm.registerAdapter !== 'function' || typeof llm.listModels !== 'function') {
|
|
155
|
+
return { ok: false, reason: 'llm-service-unavailable' }
|
|
156
|
+
}
|
|
157
|
+
const spec = customRouteSpec(settings)
|
|
158
|
+
if (!spec) return { ok: false, reason: 'custom-incomplete' }
|
|
159
|
+
let PiAiAdapter
|
|
160
|
+
try {
|
|
161
|
+
PiAiAdapter = (await loadPiAi())?.PiAiAdapter
|
|
162
|
+
} catch {
|
|
163
|
+
return { ok: false, reason: 'pi-ai-adapter-unavailable' }
|
|
164
|
+
}
|
|
165
|
+
if (typeof PiAiAdapter !== 'function') return { ok: false, reason: 'pi-ai-adapter-unavailable' }
|
|
166
|
+
const profile = customRouteProfile(spec)
|
|
167
|
+
const adapter = new PiAiAdapter({
|
|
168
|
+
profiles: () => new Map([[CONSOLIDATION_CUSTOM_ROUTE, profile]]),
|
|
169
|
+
// 明文 key 直进请求头,不写日志、不进回执、不经宿主 credentials(硬规则 §1.9)。
|
|
170
|
+
resolveApiKey: async () => spec.apiKey,
|
|
171
|
+
auth: customRouteAuth(),
|
|
172
|
+
})
|
|
173
|
+
// 先卸旧再注册(设置变更重挂)。旧 handle 卸掉后若注册失败,custom 模式本次不可用,
|
|
174
|
+
// 调用方按 not-ok 降级——比留着一份过期配置继续用更诚实。
|
|
175
|
+
disposeCustomRouteHandle()
|
|
176
|
+
let handle
|
|
177
|
+
try {
|
|
178
|
+
handle = llm.registerAdapter([CONSOLIDATION_CUSTOM_ROUTE], adapter)
|
|
179
|
+
} catch (error) {
|
|
180
|
+
return { ok: false, reason: 'register-failed', error: String(error?.message || error) }
|
|
181
|
+
}
|
|
182
|
+
// 服务性探测:注册成功 ≠ 真能出模型。listModels 走 adapter 本地目录(无网络),拿
|
|
183
|
+
// 不到模型说明这版宿主的 adapter 不认外部构造的 profile——当场卸载,留给调用方降级。
|
|
184
|
+
try {
|
|
185
|
+
const models = await llm.listModels(CONSOLIDATION_CUSTOM_ROUTE)
|
|
186
|
+
if (!Array.isArray(models) || models.length === 0) throw new Error('route serves no models')
|
|
187
|
+
} catch (error) {
|
|
188
|
+
try { handle?.() } catch {}
|
|
189
|
+
return { ok: false, reason: 'custom-route-unserviceable', error: String(error?.message || error) }
|
|
190
|
+
}
|
|
191
|
+
customRouteHandle = handle
|
|
192
|
+
return { ok: true, route: CONSOLIDATION_CUSTOM_ROUTE, models: 1 }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function disposeCustomRouteHandle() {
|
|
196
|
+
const handle = customRouteHandle
|
|
197
|
+
customRouteHandle = null
|
|
198
|
+
if (typeof handle === 'function') {
|
|
199
|
+
try { handle() } catch {}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** plugin 卸载钩子:释放注册表里的私有 route。幂等。 */
|
|
204
|
+
export function disposeConsolidationRoute() {
|
|
205
|
+
disposeCustomRouteHandle()
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// —— 宿主模型目录(UI 的 provider/model 选择器数据源)——————————————————————
|
|
209
|
+
|
|
210
|
+
function normalizeModelEntry(entry) {
|
|
211
|
+
if (typeof entry === 'string') return entry.trim() ? { id: entry.trim() } : null
|
|
212
|
+
if (entry && typeof entry === 'object' && typeof entry.id === 'string' && entry.id.trim()) {
|
|
213
|
+
const item = { id: entry.id.trim() }
|
|
214
|
+
const name = typeof entry.name === 'string' ? entry.name.trim() : ''
|
|
215
|
+
if (name) item.name = name
|
|
216
|
+
return item
|
|
217
|
+
}
|
|
218
|
+
return null
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* 宿主已激活 route 的 provider/model 目录。单个 provider 的 listModels 失败降级为空
|
|
223
|
+
* 数组不炸整体;llm service 缺席返回空目录。customAvailable 是「这台宿主能不能挂
|
|
224
|
+
* custom 模式」(registerAdapter + PiAiAdapter 都在),discoveryAvailable 是
|
|
225
|
+
* 「能不能代拉远端模型列表」(discoverModels 方法在)。
|
|
226
|
+
*/
|
|
227
|
+
export async function listHostModelOptions(ctx, { loadPiAi = defaultLoadPiAi } = {}) {
|
|
228
|
+
const llm = llmServiceOf(ctx)
|
|
229
|
+
if (!llm || typeof llm.listProviders !== 'function') {
|
|
230
|
+
return { providers: [], customAvailable: false, discoveryAvailable: false }
|
|
231
|
+
}
|
|
232
|
+
const providers = []
|
|
233
|
+
let routes = []
|
|
234
|
+
try { routes = await llm.listProviders() || [] } catch { routes = [] }
|
|
235
|
+
for (const route of routes) {
|
|
236
|
+
const id = typeof route === 'string' ? route.trim() : String(route?.id || '').trim()
|
|
237
|
+
if (!id) continue
|
|
238
|
+
const name = typeof route === 'object' && typeof route?.name === 'string' ? route.name : ''
|
|
239
|
+
let models = []
|
|
240
|
+
try { models = (await llm.listModels(id) || []).map(normalizeModelEntry).filter(Boolean) } catch { models = [] }
|
|
241
|
+
providers.push(name && name !== id ? { id, name, models } : { id, models })
|
|
242
|
+
}
|
|
243
|
+
let customAvailable = typeof llm.registerAdapter === 'function'
|
|
244
|
+
if (customAvailable) {
|
|
245
|
+
try { customAvailable = typeof (await loadPiAi())?.PiAiAdapter === 'function' } catch { customAvailable = false }
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
providers,
|
|
249
|
+
customAvailable,
|
|
250
|
+
discoveryAvailable: typeof llm.discoverModels === 'function',
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* 「拉取模型列表」:把 UI 草稿端点转给宿主的模型发现(dsh-llm-pi-ai 按 baseURL 逐
|
|
256
|
+
* 协议问 /models)。apiKey 是一次性草稿凭据,只进发现请求、绝不进日志或回包。
|
|
257
|
+
* useStoredKey 时复用设置里已保存的 custom key。返回结构化结果,UI 直接渲染。
|
|
258
|
+
*/
|
|
259
|
+
export async function discoverForkModels(ctx, { baseURL, api, apiKey, useStoredKey } = {}, settings = null) {
|
|
260
|
+
const llm = llmServiceOf(ctx)
|
|
261
|
+
if (!llm || typeof llm.discoverModels !== 'function') {
|
|
262
|
+
return { ok: false, reason: 'discovery-unavailable', models: [] }
|
|
263
|
+
}
|
|
264
|
+
const url = String(baseURL || '').trim()
|
|
265
|
+
if (!isPlainHttpUrl(url)) return { ok: false, reason: 'invalid-base-url', models: [] }
|
|
266
|
+
const key = String(apiKey || '').trim() || (useStoredKey === true ? String(settings?.consolidationCustomApiKey || '').trim() : '')
|
|
267
|
+
const request = { baseURL: url }
|
|
268
|
+
if (CONSOLIDATION_CUSTOM_APIS.includes(api)) request.api = api
|
|
269
|
+
if (key) request.apiKey = key
|
|
270
|
+
try {
|
|
271
|
+
const models = await llm.discoverModels(MODEL_DISCOVERY_NAMESPACE, request)
|
|
272
|
+
// 宿主的 discoverModels 已按端点序去重;这里防御性再走一遍同一规则,mock/旧宿主
|
|
273
|
+
// 返回重复 id 时 UI 不会看到两行同一个模型。
|
|
274
|
+
const seen = new Set()
|
|
275
|
+
const out = []
|
|
276
|
+
for (const entry of (Array.isArray(models) ? models : []).map(normalizeModelEntry)) {
|
|
277
|
+
if (!entry || seen.has(entry.id)) continue
|
|
278
|
+
seen.add(entry.id)
|
|
279
|
+
out.push(entry)
|
|
280
|
+
}
|
|
281
|
+
return { ok: true, models: out }
|
|
282
|
+
} catch (error) {
|
|
283
|
+
const message = String(error?.message || error)
|
|
284
|
+
// NO_DISCOVERY:这台宿主没在 'llm-pi-ai' 命名空间注册发现(版本差异/未挂载)。
|
|
285
|
+
if (/no model discovery is registered/i.test(message)) return { ok: false, reason: 'no-discovery', models: [] }
|
|
286
|
+
// 其余错误(端点拒绝、协议不可列举)原样带回——宿主的公共诊断信息不含凭据。
|
|
287
|
+
return { ok: false, reason: 'discovery-failed', error: message.slice(0, 300), models: [] }
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// —— 回包打码 ————————————————————————————————————————————————————————————
|
|
292
|
+
// 任何 RPC 回包不回传 consolidationCustomApiKey 明文(硬规则 §1.9)。对齐
|
|
293
|
+
// getVisionConfig 的 hasKey 模式:has<…> 布尔 + 尾 4 位(key 过短时只给掩码,
|
|
294
|
+
// 不回明文)。undefined 字段经 JSON.stringify 自然消失,回包不带键名。
|
|
295
|
+
|
|
296
|
+
/** 尾 4 位打码:key 长于 8 才给尾 4 位,否则只回 '****' 占位。 */
|
|
297
|
+
export function maskApiKeyTail(key) {
|
|
298
|
+
const value = String(key || '')
|
|
299
|
+
if (!value) return ''
|
|
300
|
+
return value.length > 8 ? value.slice(-4) : '****'
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function redactConsolidationSettings(settings) {
|
|
304
|
+
if (!settings || typeof settings !== 'object') return settings
|
|
305
|
+
const key = String(settings.consolidationCustomApiKey || '')
|
|
306
|
+
return {
|
|
307
|
+
...settings,
|
|
308
|
+
consolidationCustomApiKey: undefined,
|
|
309
|
+
hasConsolidationCustomApiKey: Boolean(key),
|
|
310
|
+
consolidationCustomApiKeyTail: maskApiKeyTail(key),
|
|
311
|
+
}
|
|
312
|
+
}
|