/** * Graph Memory 设置卡片控制器:在 DSH 插件页(`plugins.item` 槽位)渲染的 * 配置表单数据层。语义照搬官方 @deepseek-ai/dsh-client-ui-primitives 的 * SettingsFormModel(官方 web-search / agent-loop 的设置页即此模式): * * - 卡片暂存用户输入,仅在保存时一次性写入(staged → plan → scope.mutate); * - staged 用覆盖层语义:set 写 profile 覆盖层,unset 删除覆盖层(回落组合 * 层/schema 默认),invalid 保留错误文本并阻止保存; * - 保存携带首次暂存时的 revision(乐观并发 fence),成功后清空 staged。 * * 与官方 SettingsFormModel 的差异只在于字段模型来自 dsh-settings describe() * 下发的 volatileForm 投影(collectFields,嵌套 path),而非静态字段规格表; * 渲染层用 SettingsForm 外壳 + 内联 InlineField(string/number/array 标签 * 与输入同行)+ Switch/SegmentedControl,模型选择收进条件子区块,参考 * dsh-auto-approval-llm-m 的设置页风格。 */ import { collectFields, type FieldModel, type SchemaDoc } from "./form-model.js"; export const ENTRY_ID = "graph-memory"; /** dsh-settings ConfigFormController scope(官方 client 消费的形态)。 */ export interface FormScope { subscribe?: (listener: () => void) => (() => void) | undefined; getSnapshot: () => { status?: string; value?: Record; revision?: number; writable?: boolean; }; mutate: ( ops: ReadonlyArray<{ op: string; path: string[]; value?: unknown }>, revision?: number, ) => Promise; } /** dsh-settings describe() 设置镜像(view.namespaces[].schema 带序列化 schema)。 */ export interface MirrorLike { subscribe: (listener: () => void) => () => void; getSnapshot: () => { view?: { namespaces?: Array<{ ns: string; schema?: unknown }> } }; } export type StagedEdit = | { kind: "set"; value: unknown } | { kind: "unset" } | { kind: "invalid"; text: string }; /** 控件状态:text(string/number/array)、boolean、union。(2.0.8 起 schema 无 secret 字段) */ export type FieldState = | { kind: "text"; text: string; overridden: boolean; invalid: boolean } | { kind: "boolean"; checked: boolean; overridden: boolean } | { kind: "union"; value: string; options: string[]; overridden: boolean }; export interface CardField { model: FieldModel; state: FieldState; } export interface ShellState { available: boolean; writable: boolean; dirty: boolean; invalid: boolean; saving: boolean; failed: boolean; } /** 模型目录(host providers/llm-models 路由的整理结果,仅辅助选择不参与保存)。 */ export interface CatalogState { providers: Array<{ id: string; name: string }>; /** provider id → 该 provider 的模型目录。 */ byProvider: Record>; loading: boolean; failed: boolean; } /** Embedding 连接测试状态(host /api/graph-memory/embedding/test 路由)。 */ export interface EmbeddingTestState { status: "idle" | "running" | "ok" | "failed"; ok?: boolean; dimensions?: number; latencyMs?: number; model?: string; credentialSource?: string; /** 2.0.13 评审 Important #2:响应附带的 configured 判定——false 表示当前表单值保存重启后不会启用向量召回。 */ enabled?: boolean; stage?: string; error?: string; /** 路由本身不可用(非 2xx / 网络异常)——通常意味插件需部署新版并重启。 */ routeFailed?: boolean; } /** 逐 key 探测报告(host 凭据路由 POST set 返回的 perKey 条目形状一致:index-only,无 key 材料)。 */ export interface CredentialKeyReport { index: number; ok: boolean; dimensions?: number; latencyMs?: number; error?: string; } /** 凭据管理状态(host /api/graph-memory/embedding/credential 路由 GET describe + POST set/unset)。 */ export interface CredentialState { status: "idle" | "loading" | "ready" | "unavailable"; configured?: boolean; source?: string; writable?: boolean; ref?: string; save: "idle" | "saving" | "done" | "failed"; saveError?: string; saveCode?: string; report?: CredentialKeyReport[]; } export interface CardSnapshot extends ShellState { fields: CardField[]; /** 模型目录(点选辅助;加载失败时为空,组件回退手输)。 */ catalog: CatalogState; /** Embedding 连接测试结果(idle = 尚未测试)。 */ embeddingTest: EmbeddingTestState; /** 凭据管理状态(host credential 路由;idle = 尚未加载)。 */ credential: CredentialState; } interface PlannedItem { op?: { op: "set" | "unset"; path: string[]; value?: unknown }; error?: boolean; } function createSnapshotStore(initial: T) { let snapshot = initial; const listeners = new Set<() => void>(); return { getSnapshot: () => snapshot, set: (next: T) => { snapshot = next; for (const listener of [...listeners]) listener(); }, subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, }; } function sameValue(a: unknown, b: unknown): boolean { return JSON.stringify(a) === JSON.stringify(b); } function textOfValue(value: unknown, type: string): string { if (type === "array") return value === undefined || value === null ? "" : JSON.stringify(value); return value === undefined || value === null ? "" : String(value); } /** collectFields 返回的顶层字段树展平为叶子(object 的 children 递归展开)。 */ export function flattenFields(fields: FieldModel[]): FieldModel[] { const out: FieldModel[] = []; for (const field of fields) { if (field.type === "object") out.push(...flattenFields(field.children ?? [])); else out.push(field); } return out; } export function pathKeyOf(field: FieldModel): string { return field.path.join("."); } export class GraphMemoryCardController { scope: FormScope; mirror: MirrorLike; staged = new Map(); baseline?: { revision?: number }; saving = false; failed = false; /** 模型目录(host 目录路由 fetch 的整理结果;失败静默回退手输)。 */ catalog: CatalogState = { providers: [], byProvider: {}, loading: false, failed: false }; /** Embedding 连接测试结果(host /api/graph-memory/embedding/test 路由)。 */ embeddingTest: EmbeddingTestState = { status: "idle" }; /** 凭据管理状态(host /api/graph-memory/embedding/credential 路由;idle = 尚未加载)。 */ credential: CredentialState = { status: "idle", save: "idle" }; /** bind() 挂载的投影监听器(官方 SettingsFormModel.bind 同构)。 */ listeners = new Set<() => void>(); /** bind() 建立的快照 store,经 inject().hooks 暴露给组件。 */ store!: ReturnType>; private unsubscribeScope?: () => void; private unsubscribeMirror?: () => void; /** 字段模型缓存:镜像 schema 或 scope 值引用变化时重建。 */ private cachedDoc?: SchemaDoc; private cachedValue?: Record; private cachedModels?: Map; constructor(scope: FormScope, mirror: MirrorLike) { this.scope = scope; this.mirror = mirror; this.unsubscribeScope = scope.subscribe?.(() => this.publish()) ?? (() => {}); this.unsubscribeMirror = mirror.subscribe(() => this.publish()); } /** 从 describe() 镜像解析出当前 schema 文档(无则空)。 */ schemaDoc(): SchemaDoc | undefined { const view = this.mirror.getSnapshot().view; const row = view?.namespaces?.find((entry) => entry.ns === ENTRY_ID); return row?.schema as SchemaDoc | undefined; } /** 叶子字段模型(按 pathKey 索引),schema/值引用变化时惰性重建。 */ models(): Map { const doc = this.schemaDoc(); const value = this.scope.getSnapshot().value; if (this.cachedDoc === doc && this.cachedValue === value && this.cachedModels !== undefined) { return this.cachedModels; } const models = new Map(); if (doc !== undefined) { for (const leaf of flattenFields(collectFields(doc, value))) { models.set(pathKeyOf(leaf), leaf); } } this.cachedDoc = doc; this.cachedValue = value; this.cachedModels = models; return models; } resolved(field: FieldModel): unknown { return field.value; } fieldState(field: FieldModel): FieldState { const key = pathKeyOf(field); const staged = this.staged.get(key); switch (field.type) { case "boolean": { const base = field.value === true; return { kind: "boolean", checked: staged === undefined ? base : staged.kind === "set" ? staged.value === true : base, overridden: staged !== undefined, }; } case "union": { const base = typeof field.value === "string" ? field.value : ""; return { kind: "union", value: staged === undefined ? base : staged.kind === "set" ? String(staged.value) : base, options: field.options ?? [], overridden: staged !== undefined, }; } case "number": case "array": { if (staged?.kind === "invalid") return { kind: "text", text: staged.text, overridden: true, invalid: true }; if (staged?.kind === "set") return { kind: "text", text: textOfValue(staged.value, field.type), overridden: true, invalid: false }; if (staged?.kind === "unset") return { kind: "text", text: textOfValue(field.value, field.type), overridden: true, invalid: false }; return { kind: "text", text: textOfValue(field.value, field.type), overridden: false, invalid: false }; } default: { if (staged?.kind === "set") return { kind: "text", text: String(staged.value), overridden: true, invalid: false }; if (staged?.kind === "unset") return { kind: "text", text: typeof field.value === "string" ? field.value : "", overridden: true, invalid: false }; return { kind: "text", text: typeof field.value === "string" ? field.value : "", overridden: false, invalid: false }; } } } /** 计划一次保存要写的 ops(与官方 plan() 同语义:无实际变更的 set 被跳过)。 */ plan(): PlannedItem[] { const out: PlannedItem[] = []; const models = this.models(); for (const [key, staged] of this.staged) { const model = models.get(key); if (model === undefined) continue; if (staged.kind === "invalid") { out.push({ error: true }); continue; } if (staged.kind === "unset") { out.push({ op: { op: "unset", path: model.path } }); continue; } // set:与当前有效值相同则跳过(官方 plan() 语义) if (!sameValue(staged.value, this.resolved(model))) { out.push({ op: { op: "set", path: model.path, value: staged.value } }); } } return out; } shell(): ShellState { const snapshot = this.scope.getSnapshot(); const plan = this.plan(); return { available: snapshot.status === "ready", writable: snapshot.writable === true, dirty: plan.length > 0, invalid: plan.some((item) => item.error === true), saving: this.saving, failed: this.failed, }; } projection(): CardSnapshot { const fields: CardField[] = []; for (const model of this.models().values()) { fields.push({ model, state: this.fieldState(model) }); } return { ...this.shell(), fields, catalog: this.catalog, embeddingTest: this.embeddingTest, credential: this.credential }; } stage(key: string, edit?: StagedEdit): void { this.baseline ??= this.scope.getSnapshot(); if (edit === undefined) this.staged.delete(key); else this.staged.set(key, edit); this.failed = false; this.publish(); } actions() { return { edit: (key: string, raw: string | boolean) => this.edit(key, raw), resetField: (key: string) => this.resetField(key), save: () => { void this.save(); }, discard: () => this.discard(), loadCatalog: () => { void this.loadCatalog(); }, testEmbedding: () => { void this.testEmbedding(); }, loadCredentialStatus: () => { void this.loadCredentialStatus(); }, saveCredential: (input: string) => { void this.saveCredential(input); }, clearCredential: () => { void this.clearCredential(); }, }; } /** 拉取 host 模型目录(providers + 每个 provider 的 models),失败静默回退。 */ async loadCatalog(): Promise { if (this.catalog.loading) return; this.catalog = { ...this.catalog, loading: true, failed: false }; this.publish(); try { const base = (globalThis as { location?: { origin?: string } }).location?.origin ?? ""; const providersRes = await fetch(`${base}/api/graph-memory/providers`, { credentials: "same-origin", }); if (!providersRes.ok) throw new Error(`providers ${providersRes.status}`); const providersData = await providersRes.json(); const providers: Array<{ id: string; name: string }> = Array.isArray(providersData?.value?.providers) ? providersData.value.providers : []; const byProvider: Record> = {}; await Promise.all( providers.map(async (provider) => { try { const modelsRes = await fetch( `${base}/api/graph-memory/llm-models?provider=${encodeURIComponent(provider.id)}`, { credentials: "same-origin" }, ); const modelsData = await modelsRes.json(); byProvider[provider.id] = Array.isArray(modelsData?.value?.models) ? modelsData.value.models : []; } catch { byProvider[provider.id] = []; } }), ); this.catalog = { providers, byProvider, loading: false, failed: false }; } catch { this.catalog = { providers: [], byProvider: {}, loading: false, failed: true }; } this.publish(); } /** 组装测试路由 payload:当前表单有效值(staged 草稿优先,空值回落 schema 默认/省略)。 */ private embeddingDraft(): Record { const models = this.models(); const val = (key: string): unknown => { const model = models.get(key); if (model === undefined) return undefined; const staged = this.staged.get(key); if (staged?.kind === "set") return staged.value; if (staged?.kind === "unset") return undefined; return model.value; }; const str = (v: unknown): string | undefined => { const s = typeof v === "string" ? v.trim() : ""; return s || undefined; }; const dims = val("embedding.dimensions"); const dimensions = typeof dims === "number" && Number.isFinite(dims) && dims > 0 ? dims : undefined; // 2.0.18:测试超时随表单值上送(schema 默认 30000 常驻,路由作为主值优先级; // 仅发送合法正数,非法/未配置由宿主回退 saved/默认)。 const tm = val("embedding.testTimeoutMs"); const testTimeoutMs = typeof tm === "number" && Number.isFinite(tm) && tm > 0 ? tm : undefined; // 2.0.19:生产请求超时基线随表单值上送(schema 默认 10000 常驻,engine 作回退)。 const rm = val("embedding.requestTimeoutMs"); const requestTimeoutMs = typeof rm === "number" && Number.isFinite(rm) && rm > 0 ? rm : undefined; const payload: Record = {}; const apiKeyEnv = str(val("embedding.apiKeyEnv")); const baseURL = str(val("embedding.baseURL")); const model = str(val("embedding.model")); if (apiKeyEnv) payload.apiKeyEnv = apiKeyEnv; if (baseURL) payload.baseURL = baseURL; if (model) payload.model = model; if (dimensions !== undefined) payload.dimensions = dimensions; if (testTimeoutMs !== undefined) payload.testTimeoutMs = testTimeoutMs; if (requestTimeoutMs !== undefined) payload.requestTimeoutMs = requestTimeoutMs; return payload; } /** 用当前表单值发起一次 Embedding 连接测试(host /api/graph-memory/embedding/test)。 */ async testEmbedding(): Promise { if (this.embeddingTest.status === "running") return; this.embeddingTest = { status: "running" }; this.publish(); try { const base = (globalThis as { location?: { origin?: string } }).location?.origin ?? ""; const res = await fetch(`${base}/api/graph-memory/embedding/test`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify(this.embeddingDraft()), }); if (!res.ok) { this.embeddingTest = { status: "failed", routeFailed: true }; } else { const data = await res.json() as any; if (data?.ok) { const value = data.value ?? {}; this.embeddingTest = { status: "ok", ok: true, dimensions: value.dimensions, latencyMs: value.latencyMs, model: value.model, credentialSource: value.credentialSource, // 2.0.13 评审 Important #2:enabled 判定透传(旧版路由无此字段 → undefined) enabled: typeof data?.enabled === "boolean" ? data.enabled : undefined, }; } else { this.embeddingTest = { status: "failed", ok: false, stage: data?.stage, error: typeof data?.error === "string" ? data.error : undefined, enabled: typeof data?.enabled === "boolean" ? data.enabled : undefined, }; } } } catch { this.embeddingTest = { status: "failed", routeFailed: true }; } this.publish(); } /** * 拉取凭据 describe(host GET /api/graph-memory/embedding/credential?ref=…)。 * ref 解析:staged 草稿 apiKeyEnv → schema 默认 → 兜底 GRAPH_MEMORY_EMBEDDING_API_KEY。 * 非 2xx / 网络 / route ok:false → status:"unavailable"(旧插件降级,不崩溃、不报错)。 */ async loadCredentialStatus(): Promise { if (this.credential.status === "loading") return; this.credential = { ...this.credential, status: "loading" }; this.publish(); try { const base = (globalThis as { location?: { origin?: string } }).location?.origin ?? ""; const ref = (this.embeddingDraft().apiKeyEnv as string | undefined) ?? "GRAPH_MEMORY_EMBEDDING_API_KEY"; const res = await fetch( `${base}/api/graph-memory/embedding/credential?ref=${encodeURIComponent(ref)}`, { method: "GET", credentials: "same-origin" }, ); if (!res.ok) { this.credential = { ...this.credential, status: "unavailable" }; } else { const data = await res.json() as any; if (data?.ok) { const value = data.value ?? {}; this.credential = { ...this.credential, status: "ready", configured: typeof value.configured === "boolean" ? value.configured : undefined, source: typeof value.source === "string" ? value.source : undefined, writable: typeof value.writable === "boolean" ? value.writable : undefined, ref: typeof value.ref === "string" ? value.ref : undefined, }; } else { this.credential = { ...this.credential, status: "unavailable" }; } } } catch { this.credential = { ...this.credential, status: "unavailable" }; } this.publish(); } /** * 保存凭据(host POST /api/graph-memory/embedding/credential,action:"set")。 * input 原样发送(逗号分隔多 key),成功后保存 probe report 并重新 describe。 * key 材料只经 POST body 发往宿主,绝不存入控制器状态(saveError/saveCode/report 均无 key)。 */ async saveCredential(input: string): Promise { if (this.credential.save === "saving") return; this.credential = { ...this.credential, save: "saving" }; this.publish(); try { const base = (globalThis as { location?: { origin?: string } }).location?.origin ?? ""; const draft = this.embeddingDraft(); const ref = (draft.apiKeyEnv as string | undefined) ?? "GRAPH_MEMORY_EMBEDDING_API_KEY"; // ref 取代 apiKeyEnv;其余 probe target 字段(baseURL/model/dimensions)展开 delete draft.apiKeyEnv; const res = await fetch(`${base}/api/graph-memory/embedding/credential`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ref, action: "set", value: input, ...draft }), }); if (!res.ok) { let saveError: string | undefined; try { const errData = await res.json() as any; saveError = typeof errData?.error === "string" ? errData.error : undefined; } catch { /* 非 JSON 响应体 */ } this.credential = { ...this.credential, save: "failed", saveError: saveError ?? res.statusText }; } else { const data = await res.json() as any; if (data?.ok) { this.credential = { ...this.credential, save: "done", report: Array.isArray(data.value?.perKey) ? data.value.perKey : undefined, }; await this.loadCredentialStatus(); } else { this.credential = { ...this.credential, save: "failed", saveCode: typeof data?.code === "string" ? data.code : undefined, saveError: typeof data?.error === "string" ? data.error : undefined, }; } } } catch { this.credential = { ...this.credential, save: "failed", saveError: "network error" }; } this.publish(); } /** * 清除凭据(host POST /api/graph-memory/embedding/credential,action:"unset")。 * 成功后清除 probe report 并重新 describe。 */ async clearCredential(): Promise { if (this.credential.save === "saving") return; this.credential = { ...this.credential, save: "saving" }; this.publish(); try { const base = (globalThis as { location?: { origin?: string } }).location?.origin ?? ""; const ref = (this.embeddingDraft().apiKeyEnv as string | undefined) ?? "GRAPH_MEMORY_EMBEDDING_API_KEY"; const res = await fetch(`${base}/api/graph-memory/embedding/credential`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ref, action: "unset" }), }); if (!res.ok) { let saveError: string | undefined; try { const errData = await res.json() as any; saveError = typeof errData?.error === "string" ? errData.error : undefined; } catch { /* 非 JSON 响应体 */ } this.credential = { ...this.credential, save: "failed", saveError: saveError ?? res.statusText }; } else { const data = await res.json() as any; if (data?.ok) { this.credential = { ...this.credential, save: "done", report: undefined }; await this.loadCredentialStatus(); } else { this.credential = { ...this.credential, save: "failed", saveCode: typeof data?.code === "string" ? data.code : undefined, saveError: typeof data?.error === "string" ? data.error : undefined, }; } } } catch { this.credential = { ...this.credential, save: "failed", saveError: "network error" }; } this.publish(); } edit(key: string, raw: string | boolean): void { const model = this.models().get(key); if (model === undefined) return; switch (model.type) { case "number": { const text = String(raw).trim(); if (text === "") return this.stage(key, { kind: "unset" }); const numeric = Number(text); return this.stage(key, Number.isFinite(numeric) ? { kind: "set", value: numeric } : { kind: "invalid", text }); } case "array": { const text = String(raw).trim(); if (text === "") return this.stage(key, { kind: "unset" }); try { const parsed: unknown = JSON.parse(text); return this.stage(key, Array.isArray(parsed) ? { kind: "set", value: parsed } : { kind: "invalid", text }); } catch { return this.stage(key, { kind: "invalid", text }); } } case "boolean": return this.stage(key, { kind: "set", value: raw === true }); default: { // string / union const text = String(raw).trim(); return this.stage(key, text === "" ? { kind: "unset" } : { kind: "set", value: text }); } } } resetField(key: string): void { this.stage(key, { kind: "unset" }); } async save(): Promise { const plan = this.plan(); const snapshot = this.scope.getSnapshot(); if ( plan.length === 0 || this.saving || snapshot.writable !== true || plan.some((item) => item.error === true) ) { return; } this.saving = true; this.failed = false; this.publish(); try { const ops = plan .map((item) => item.op) .filter((op): op is NonNullable => op !== undefined); const landed = ops.length === 0 || await this.scope.mutate(ops, this.baseline?.revision); if (landed) { this.staged.clear(); this.baseline = undefined; } this.failed = !landed; } catch { this.failed = true; } finally { this.saving = false; this.publish(); } } discard(): void { if (this.staged.size === 0 && !this.failed) return; this.staged.clear(); this.baseline = undefined; this.failed = false; this.publish(); } /** 挂载投影(官方 SettingsFormModel.bind 同构):每个变化重建 store 快照。 */ bind(project: () => CardSnapshot) { const store = createSnapshotStore(project()); this.store = store; this.listeners.add(() => { store.set(project()); }); return store; } /** 槽位注入的钩子:组件经 hooks.graphMemoryCard(selector) 读快照。 */ inject() { return { hooks: { graphMemoryCard: this.store }, ...this.actions(), }; } publish(): void { for (const listener of [...this.listeners]) listener(); } dispose(): void { this.unsubscribeScope?.(); this.unsubscribeMirror?.(); this.listeners.clear(); } } // ─── 本地化:页面与字段文案(仿官方 agent-loop 的 locales 结构)──────────── /** 页面相关文案(settings.graphMemory 命名空间字典)。 */ const en = { title: "Graph Memory", description: "Cross-session knowledge-graph memory: recall, PageRank, communities, and vector search.", unavailable: "This plugin is not loaded, so it cannot be configured right now.", readOnly: "This deployment stores settings read-only.", save: "Save", saving: "Saving…", saveFailed: "The deployment did not accept these values; they were left for you to correct.", overridden: "Overridden", reset: "Reset to default", invalidNumber: "Enter a number, or leave blank to use the default.", invalidJson: "Enter a JSON array, or leave blank to use the default.", // 模型目录(host 路由拉取,点选即填;目录不可用时仍可手输) catalogUnavailable: "Model catalog is unavailable — type provider/model manually.", modelSectionTitle: "Model selection", modelSectionHint: "Choose where background extraction runs its model: the current session, a preset provider/model pair, or a pool of models.", sessionSourceHint: "Follows the current session's model — no provider/model needed.", poolAdd: "Add", poolAddFromCatalog: "Add from catalog…", poolName: "Label", poolProvider: "Provider", poolModel: "Model", poolTimeoutMs: "Timeout (ms)", poolRemove: "Remove entry", poolEmpty: "No pool entries yet.", poolDrag: "Drag to reorder", // 字段标签 "f.dbPath": "Database path", "f.extractionEnabled": "Extraction", "f.recallEnabled": "Recall", "f.recallMaxNodes": "Recall node cap", "f.semanticScoreThreshold": "Semantic score threshold", "f.maintenanceInterval": "Maintenance interval (turns)", "f.messageRetention.keep": "Message retention policy", "f.messageRetention.recentTurns": "Recent turns to keep", "f.messageRetention.retentionDays": "Retention days", "f.messageRetention.batchSize": "Batch size", "f.messageRetention.dryRun": "Dry run", "f.decay": "Forgetting curve", "f.decay.enabled": "Decay scoring", "f.decay.autoDeprecate": "Auto-deprecate silent nodes", "f.decay.autoDeprecateAfterDays": "Silence days before deprecation", "f.decay.purgeAfterDays": "Hard-delete window (days)", "f.contextCompactionEnabled": "Context compaction", "f.freshTurnCount": "Fresh turns kept", "f.projectCompletedTurnTools": "Project completed-turn tools", "f.assistantTools": "Assistant tools", "f.extractionSource": "Extraction model source", "f.llmProvider": "LLM provider", "f.llmModel": "LLM model", "f.llmReasoningEffort": "Reasoning effort", "f.llmMaxTokens": "Max output tokens", "f.extractionModels": "Model pool (JSON)", "f.extract.trivialPrompts": "Trivial prefilter words (JSON)", "f.extract.trivialMaxChars": "Trivial length cap", "f.embedding.apiKeyEnv": "API key credential reference", "f.embedding.baseURL": "Embedding base URL", "f.embedding.model": "Embedding model", "f.embedding.dimensions": "Embedding dimensions", "f.embedding.testTimeoutMs": "Test timeout (ms)", "f.embedding.requestTimeoutMs": "Request timeout (ms)", // 关键提示(覆盖全部叶子字段,一行说明) "h.dbPath": "SQLite file holding the knowledge graph. Changes apply after a restart.", "h.extractionEnabled": "Extract knowledge-graph memory from conversations in the background.", "h.recallEnabled": "Automatically inject matched memories into the prompt before each answer.", "h.recallMaxNodes": "Maximum query-matched memory nodes returned by one recall.", "h.semanticScoreThreshold": "Provider-calibrated cosine floor for automatic prompt injection.", "h.maintenanceInterval": "Every N user turns between maintenance runs (PageRank, decay, retention).", "h.messageRetention.keep": "Which conversation turns to keep: all, only referenced, or recent.", "h.messageRetention.recentTurns": "With keep=recent: newest turns retained (0 = rely on retention days only).", "h.messageRetention.retentionDays": "With keep=recent: delete extracted raw turns older than this many days.", "h.messageRetention.batchSize": "Rows processed per transaction during retention cleanup.", "h.messageRetention.dryRun": "Log what would be pruned without deleting anything.", "h.decay.enabled": "Decay scoring and tier transitions on every maintenance run.", "h.decay.autoDeprecate": "Disconnect and deprecate peripheral nodes silent past the threshold (revivable on re-reference).", "h.decay.autoDeprecateAfterDays": "Silence required before a low-score peripheral node is deprecated.", "h.decay.purgeAfterDays": "Days after deprecation before hard delete. 0 = never purge.", "h.contextCompactionEnabled": "Let Graph Memory replace older history without an LLM call.", "h.freshTurnCount": "Newest user turns kept verbatim on the model surface.", "h.projectCompletedTurnTools": "Hide completed-turn tool traces while keeping the question and final answer.", "h.assistantTools": "Memory tools the assistant may call: search, all, or none. Automatic recall never depends on tools.", "h.extractionSource": "Where background extraction gets its model: current session, preset pair, or pool.", "h.llmProvider": "Preset provider for extraction (used when source=preset).", "h.llmModel": "Preset model name for extraction (configured together with provider).", "h.llmReasoningEffort": "Background extraction normally runs without chain-of-thought.", "h.llmMaxTokens": "Optional cap on extraction responses; leave empty to not send the parameter.", "h.extractionModels": 'JSON array of {name, provider, model, timeoutMs} entries.', "h.extract.trivialPrompts": "Additional trivial-turn prefilter words (merged with the built-in list).", "h.extract.trivialMaxChars": "Turns shorter than this (after trimming) are skipped as trivial without an LLM call.", "h.embedding.apiKeyEnv": "The key itself is never stored in plugin config. Put the key under this reference name in the DSH credential store (.credentials.yaml refs) or environment; the name is provider-neutral — switching providers only changes the stored value.", "h.embedding.baseURL": "OpenAI-compatible embeddings endpoint; empty = OpenAI default.", "h.embedding.model": "Embedding model name.", "h.embedding.dimensions": "Defaults to the embedding model's own dimension.", "h.embedding.testTimeoutMs": "Per-request timeout for the panel Test button and post-save key probes; 1000–300000, default 30000.", "h.embedding.requestTimeoutMs": "Per-request timeout baseline for production embedding calls (single = this value; batch = max(value, 2s×items)); 1000–300000, default 10000. Restart to apply.", // Embedding 连接测试(面板「测试」按钮 + 结果行) embeddingTestTitle: "Embedding connection test", embeddingTestHint: "Runs one real embedding call with the values currently in this form. The key is resolved on the host and never reaches the browser.", embeddingTestRun: "Test", embeddingTestRunning: "Testing…", embeddingTestOk: "Embedding OK", embeddingTestFailed: "Test failed", embeddingTestRouteUnavailable: "Test route unavailable — deploy the new plugin build and restart.", embeddingTestRestartHint: "Values verified. Save and restart DSH to apply — embedding is restart-effective.", embeddingTestNotEnabledHint: "Heads-up: this configuration will NOT enable vector recall after save/restart — a baseURL (or a custom reference name) is required; a key under the default reference alone is not treated as configured. The test only verified connectivity.", // 凭据管理(host credential 路由;凭据值不经路由回传——保存后 key 不会被回显) credentialTitle: "Credential management", credentialHint: "Comma-separated keys are saved as a whole string (overwriting any previous value). The key value is never echoed back — save reports only per-key connectivity.", credentialSave: "Save", credentialSaving: "Saving…", credentialClear: "Clear", credentialClearConfirm: "Click again to confirm — this removes the stored credential.", credentialConfigured: "Configured", credentialNotConfigured: "Not configured", credentialReadOnlyHint: "This reference is env-sourced and managed in the DSH credential shell, not from this panel.", credentialSaveFailed: "The credential could not be saved. See the error below.", // 选项(英文原词为准,中文另配) "o.assistantTools.search": "Search", "o.assistantTools.all": "All", "o.assistantTools.none": "None", "o.extractionSource.session": "Session", "o.extractionSource.preset": "Preset", "o.extractionSource.pool": "Model pool", "o.messageRetention.keep.all": "All", "o.messageRetention.keep.referenced": "Referenced", "o.messageRetention.keep.recent": "Recent", "o.llmReasoningEffort.default": "Default", }; const zh: Record = { title: "Graph Memory", description: "跨会话知识图谱记忆:召回、PageRank、社区发现与向量检索。", unavailable: "该插件当前未加载,暂时无法配置。", readOnly: "本部署的设置为只读。", save: "保存", saving: "保存中…", saveFailed: "本部署没有接受这些值,已保留供你修改。", overridden: "已覆盖", reset: "恢复默认", invalidNumber: "请填数字;留空表示使用默认值。", invalidJson: "请输入 JSON 数组;留空表示使用默认值。", catalogUnavailable: "模型目录不可用——请手动填写 provider/model。", modelSectionTitle: "模型选择", modelSectionHint: "选择后台提取用哪个模型:当前会话模型、预设的 provider/model 对,或模型池。", sessionSourceHint: "跟随当前会话模型——无需配置 provider/model。", poolAdd: "添加", poolAddFromCatalog: "从目录添加…", poolName: "名称", poolProvider: "Provider", poolModel: "Model", poolTimeoutMs: "超时(毫秒)", poolRemove: "移除条目", poolEmpty: "模型池还没有条目。", poolDrag: "拖拽排序", "f.dbPath": "数据库路径", "f.extractionEnabled": "启用提取", "f.recallEnabled": "启用召回", "f.recallMaxNodes": "召回节点上限", "f.semanticScoreThreshold": "语义相似度阈值", "f.maintenanceInterval": "维护间隔(回合数)", "f.messageRetention.keep": "消息保留策略", "f.messageRetention.recentTurns": "保留最近轮数", "f.messageRetention.retentionDays": "保留天数", "f.messageRetention.batchSize": "批次大小", "f.messageRetention.dryRun": "试运行", "f.decay": "遗忘曲线", "f.decay.enabled": "衰减评分", "f.decay.autoDeprecate": "静默节点自动弃用", "f.decay.autoDeprecateAfterDays": "弃用静默门槛(天)", "f.decay.purgeAfterDays": "硬删窗口(天)", "f.contextCompactionEnabled": "上下文压缩", "f.freshTurnCount": "保留新鲜轮数", "f.projectCompletedTurnTools": "投影已完成轮的工具", "f.assistantTools": "助手工具", "f.extractionSource": "提取模型来源", "f.llmProvider": "LLM 提供方", "f.llmModel": "LLM 模型", "f.llmReasoningEffort": "推理力度", "f.llmMaxTokens": "最大输出 token", "f.extractionModels": "模型池条目(JSON)", "f.extract.trivialPrompts": "预筛词表(JSON)", "f.extract.trivialMaxChars": "预筛长度阈值", "f.embedding.apiKeyEnv": "API Key 凭据引用名", "f.embedding.baseURL": "Embedding Base URL", "f.embedding.model": "Embedding 模型", "f.embedding.dimensions": "向量维度", "f.embedding.testTimeoutMs": "测试超时(毫秒)", "f.embedding.requestTimeoutMs": "请求超时(毫秒)", "h.dbPath": "知识图谱的 SQLite 数据库文件;修改后需重启生效。", "h.extractionEnabled": "在后台从对话中提取知识图谱记忆。", "h.recallEnabled": "每次回答前自动把匹配的记忆注入提示。", "h.recallMaxNodes": "单次召回最多返回的查询匹配记忆节点数。", "h.semanticScoreThreshold": "自动注入提示的余弦相似度下限(按提供方校准)。", "h.maintenanceInterval": "维护运行(PageRank、衰减、保留)间隔的用户回合数。", "h.messageRetention.keep": "保留哪些对话轮:全部、仅被引用或最近。", "h.messageRetention.recentTurns": "keep=recent 时:保留的最近轮数(0 = 仅按保留天数清理)。", "h.messageRetention.retentionDays": "keep=recent 时:超过该天数的已提取原始轮被清理。", "h.messageRetention.batchSize": "保留清理每批(单事务)处理的行数。", "h.messageRetention.dryRun": "只记录将要清理的内容,不实际删除。", "h.decay.enabled": "每次维护运行时执行衰减评分与层级转换。", "h.decay.autoDeprecate": "静默超过门槛的外围节点被断联弃用(重新被引用可复活)。", "h.decay.autoDeprecateAfterDays": "低分外围节点被弃用前所需的连续静默天数。", "h.decay.purgeAfterDays": "弃用后到硬删的天数;0 = 永不硬删。", "h.contextCompactionEnabled": "让 Graph Memory 不调用 LLM 即替换较旧的历史。", "h.freshTurnCount": "在模型上下文中原样保留的最近用户轮数。", "h.projectCompletedTurnTools": "隐藏已完成轮的工具痕迹,保留提问与最终回答。", "h.assistantTools": "允许助手调用的记忆工具:搜索/全部/无。自动召回从不依赖工具。", "h.extractionSource": "后台提取的模型来源:当前会话、预设对或模型池。", "h.llmProvider": "提取用的预设 provider(来源=预设时生效)。", "h.llmModel": "提取用的预设模型名(与 provider 成对配置)。", "h.llmReasoningEffort": "后台提取通常不启用思维链。", "h.llmMaxTokens": "可选的提取响应上限;留空则不发送该参数。", "h.extractionModels": "{name, provider, model, timeoutMs} 条目的 JSON 数组。", "h.extract.trivialPrompts": "追加的 trivial 轮预筛词(与内置词表合并)。", "h.extract.trivialMaxChars": "清洗后长度低于该值的轮按 trivial 跳过,不调用 LLM。", "h.embedding.apiKeyEnv": "Key 本体绝不存入插件配置:在 DSH 凭据存储(.credentials.yaml refs)或环境变量中以该引用名存放。引用名与厂商无关——换 Embedding 厂商只改存储的值,不改这里。", "h.embedding.baseURL": "OpenAI 兼容的 embeddings 地址;留空 = OpenAI 默认。", "h.embedding.model": "Embedding 模型名。", "h.embedding.dimensions": "缺省使用 Embedding 模型自带维度。", "h.embedding.testTimeoutMs": "设置页测试按钮与保存后逐 key 探测的单次请求超时;1000–300000,默认 30000。", "h.embedding.requestTimeoutMs": "生产 Embedding 请求的单次超时基线(单发 = 该值;批量 = max(该值, 2s×条数));1000–300000,默认 10000。需重启生效。", // Embedding 连接测试(面板「测试」按钮 + 结果行) embeddingTestTitle: "Embedding 连接测试", embeddingTestHint: "用当前表单值发起一次真实 embedding 调用;key 只在宿主侧解析,不会传到浏览器。", embeddingTestRun: "测试", embeddingTestRunning: "测试中…", embeddingTestOk: "Embedding 可用", embeddingTestFailed: "测试失败", embeddingTestRouteUnavailable: "测试路由不可用——需部署新版插件并重启。", embeddingTestRestartHint: "值已验证。保存并重启 DSH 后生效——embedding 为重启生效字段。", embeddingTestNotEnabledHint: "注意:当前配置保存并重启后不会启用向量召回——需设置 baseURL 或自定义引用名(仅默认引用名下的 key 不视为已配置);本次测试只验证了连通性。", // 凭据管理(host credential 路由;凭据值不经路由回传——保存后 key 不会被回显) credentialTitle: "凭据管理", credentialHint: "逗号分隔的多 key 以整串保存(覆盖之前的值)。Key 值不会被回显——保存报告仅含逐 key 连通性。", credentialSave: "保存", credentialSaving: "保存中…", credentialClear: "清除", credentialClearConfirm: "再次点击确认——将移除已存储的凭据。", credentialConfigured: "已配置", credentialNotConfigured: "未配置", credentialReadOnlyHint: "该引用为环境变量来源,在 DSH 凭据 shell 中管理,不从本面板操作。", credentialSaveFailed: "凭据保存失败。请查看下方错误信息。", "o.assistantTools.search": "搜索", "o.assistantTools.all": "全部", "o.assistantTools.none": "无", "o.extractionSource.session": "会话", "o.extractionSource.preset": "预设", "o.extractionSource.pool": "模型池", "o.messageRetention.keep.all": "全部", "o.messageRetention.keep.referenced": "被引用", "o.messageRetention.keep.recent": "最近", "o.llmReasoningEffort.default": "默认", }; /** llmReasoningEffort 选项文案(其余选项为英文原词,中文也保留原词)。 */ const reasoningEffortLabels: Record = { "": "default", off: "off", minimal: "minimal", low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max", }; export { en, zh, reasoningEffortLabels }; /** 表单框架文案(官方 SettingsForm 组件消费)。 */ export function formLabels(t: (key: string) => string) { return { unavailable: t("unavailable"), readOnly: t("readOnly"), saveFailed: t("saveFailed"), save: t("save"), saving: t("saving"), }; } /** 控件文案(字段标签/提示/选项)。 */ export function fieldTexts(t: (key: string) => string, field: FieldModel) { const key = pathKeyOf(field); const hintKey = `h.${key}`; const dictionary = en as Record; const hasHint = typeof dictionary[hintKey] === "string"; return { label: t(`f.${key}`), hint: hasHint ? t(hintKey) : undefined, optionLabel: (option: string) => { const optionKey = `o.${key}.${option}`; if (typeof dictionary[optionKey] === "string") return t(optionKey); return field.key === "llmReasoningEffort" ? reasoningEffortLabels[option] ?? option : option; }, }; }