From 31037b0d31d5f4874399675144ef7b78e0a74ca0 Mon Sep 17 00:00:00 2001 From: newbie Date: Fri, 27 Nov 2026 17:16:44 +0800 Subject: [PATCH] chore(release): 0.10.3 Bumps the manifest, version fallback and README, and rebuilds lib/ and client/ so the committed artifacts match the sources. --- README.md | 9 +- client/index.js | 1166 ++++++++++++++++------- lib/api.js | 9 +- lib/clients.js | 6 +- lib/cloudsync-routes.js | 6 +- lib/config.js | 10 +- lib/diagnostics.js | 3 +- lib/entries/raw.js | 115 +++ lib/index.js | 2 + lib/local-memory/departments/manager.js | 7 +- lib/local-memory/manager.js | 14 +- lib/memory/tools.js | 6 +- lib/mnemon/driver.js | 6 +- lib/mnemon/native.js | 4 +- lib/raw-memory/index.js | 26 + lib/raw-memory/routes.js | 109 +++ lib/raw-memory/settings.js | 39 + lib/raw-memory/store.js | 267 ++++++ lib/raw-memory/tools.js | 121 +++ lib/raw-memory/types.js | 1 + lib/reporter.js | 9 +- lib/routes.js | 28 +- lib/skill-admin.js | 4 +- lib/skill-groups.js | 6 +- lib/skill-sync.js | 13 +- lib/skills/routes.js | 28 - lib/store.js | 6 +- lib/tools.js | 2 +- lib/version.js | 2 +- package.json | 2 +- src/version.ts | 2 +- 31 files changed, 1563 insertions(+), 465 deletions(-) create mode 100644 lib/entries/raw.js create mode 100644 lib/raw-memory/index.js create mode 100644 lib/raw-memory/routes.js create mode 100644 lib/raw-memory/settings.js create mode 100644 lib/raw-memory/store.js create mode 100644 lib/raw-memory/tools.js create mode 100644 lib/raw-memory/types.js diff --git a/README.md b/README.md index 5b7aabe..1911dd3 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,15 @@ # dsh-brain -> **0.10.1**:插件按功能拆成五个可单独开关的子插件(见「五个子插件」); -> 技能同步引入按内容与更新时间的自动冲突解决(0.9.9/0.9.10 语义); -> 令牌环境变量改为**绑定服务地址**(见「配置」)。 +> **0.10.3**:插件按功能拆成六个可单独开关的子插件,新增可选的原始记录层 +> `dsh-brain-raw`(见「六个子插件」);同步清理了不可达的防御性分支与重复 +> 响应校验。0.10.1 起技能同步按内容与更新时间自动解决冲突(0.9.9/0.9.10 +> 语义),令牌环境变量**绑定服务地址**(见「配置」)。 把 DeepSeek Harness 接到 LongMemory 云端记忆服务:每轮对话结束自动上报一条 活动记录(只上传元数据),并把云端记忆库变成 agent 可用的工具;同时双向 同步云端技能中心与本机技能目录。 -当前版本 **0.10.1**,含宿主端与浏览器端两部分:宿主端负责活动上报、 +当前版本 **0.10.3**,含宿主端与浏览器端两部分:宿主端负责活动上报、 记忆工具注册与技能同步。浏览器 UI 有三个入口: - 左侧栏 **Brain** 展示全局运行状态,管理全局记忆与部门。 diff --git a/client/index.js b/client/index.js index 6768b65..72749bc 100644 --- a/client/index.js +++ b/client/index.js @@ -482,20 +482,20 @@ window.__ModuleLoader__.load({ } }; // src-client/components.tsx - const h$12 = react.createElement; + const h$13 = react.createElement; function Pill$1(props) { var tone = styles[props.tone] === void 0 ? styles.muted : styles[props.tone]; - return h$12("span", { style: Object.assign({}, styles.pill, tone) }, h$12("span", { style: { opacity: .75 } }, props.label), h$12("span", { style: { fontWeight: 600 } }, String(props.value))); + return h$13("span", { style: Object.assign({}, styles.pill, tone) }, h$13("span", { style: { opacity: .75 } }, props.label), h$13("span", { style: { fontWeight: 600 } }, String(props.value))); } function Banner(props) { var tone = styles[props.tone] === void 0 ? styles.muted : styles[props.tone]; - return h$12("div", { + return h$13("div", { style: Object.assign({}, styles.banner, tone), role: props.role }, props.children); } function Field(props) { - return h$12("label", { style: styles.field }, h$12("span", { style: styles.label }, props.label), h$12("input", { + return h$13("label", { style: styles.field }, h$13("span", { style: styles.label }, props.label), h$13("input", { style: styles.input, type: props.type === void 0 ? "text" : props.type, value: props.value, @@ -506,7 +506,7 @@ window.__ModuleLoader__.load({ onChange: function(event) { props.onChange(event.target.value); } - }), props.hint === void 0 ? null : h$12("span", { style: styles.hint }, props.hint)); + }), props.hint === void 0 ? null : h$13("span", { style: styles.hint }, props.hint)); } function Btn(props) { var base = props.variant === "primary" ? styles.buttonPrimary : props.variant === "danger" ? styles.buttonDanger : props.variant === "small" ? styles.buttonSmall : styles.button; @@ -514,7 +514,7 @@ window.__ModuleLoader__.load({ opacity: .45, cursor: "not-allowed" }) : base; - return h$12("button", { + return h$13("button", { type: "button", style, disabled: props.disabled === true, @@ -527,7 +527,7 @@ window.__ModuleLoader__.load({ opacity: .45, cursor: "not-allowed" } : null); - return h$12("button", { + return h$13("button", { type: "button", style, disabled: props.disabled === true, @@ -537,13 +537,13 @@ window.__ModuleLoader__.load({ }, props.glyph); } function Switch(props) { - return h$12("div", { + return h$13("div", { style: styles.tabs, role: "tablist", "aria-label": props.ariaLabel }, props.options.map(function(option) { var active = option.value === props.value; - return h$12("button", { + return h$13("button", { key: option.value, type: "button", role: "tab", @@ -558,7 +558,7 @@ window.__ModuleLoader__.load({ function Toggle(props) { var on = props.checked === true; var disabled = props.disabled === true; - return h$12("button", { + return h$13("button", { type: "button", role: "switch", "aria-checked": on, @@ -581,7 +581,7 @@ window.__ModuleLoader__.load({ transition: "background 120ms ease" }, onClick: disabled ? void 0 : props.onChange - }, h$12("span", { style: { + }, h$13("span", { style: { width: "16px", height: "16px", borderRadius: "999px", @@ -591,7 +591,7 @@ window.__ModuleLoader__.load({ } })); } function Section(props) { - return h$12("div", { style: styles.section }, h$12("div", { style: styles.sectionHead }, h$12("h4", { style: styles.sectionTitle }, props.title), props.aside === void 0 ? null : h$12("div", { style: styles.actions }, props.aside)), props.hint === void 0 ? null : h$12("p", { style: styles.hint }, props.hint), props.children); + return h$13("div", { style: styles.section }, h$13("div", { style: styles.sectionHead }, h$13("h4", { style: styles.sectionTitle }, props.title), props.aside === void 0 ? null : h$13("div", { style: styles.actions }, props.aside)), props.hint === void 0 ? null : h$13("p", { style: styles.hint }, props.hint), props.children); } function CardBoundary(props) { react.Component.call(this, props); @@ -603,7 +603,7 @@ window.__ModuleLoader__.load({ return { failure }; }; CardBoundary.prototype.render = function() { - if (this.state.failure !== null) return h$12("div", { style: Object.assign({}, styles.root) }, h$12("div", { style: Object.assign({}, styles.banner, styles.bad) }, "云端记忆设置卡渲染失败:" + messageOf(this.state.failure)), h$12("p", { style: styles.hint }, "插件本身仍在运行,可改用 /dsh-brain 页面配置。")); + if (this.state.failure !== null) return h$13("div", { style: Object.assign({}, styles.root) }, h$13("div", { style: Object.assign({}, styles.banner, styles.bad) }, "云端记忆设置卡渲染失败:" + messageOf(this.state.failure)), h$13("p", { style: styles.hint }, "插件本身仍在运行,可改用 /dsh-brain 页面配置。")); return this.props.children; }; // src-client/format.ts @@ -728,7 +728,7 @@ window.__ModuleLoader__.load({ return "HTTP " + String(result.status) + (result.error === void 0 ? "" : ":" + result.error); } // src-client/sections/MarketSection.tsx - const h$11 = react.createElement; + const h$12 = react.createElement; function MarketSection(props) { var capabilities = props.capabilities || {}; var tuple = react.useState({ @@ -910,31 +910,31 @@ window.__ModuleLoader__.load({ }); }); } - if (!available) return h$11(Section, { + if (!available) return h$12(Section, { title: "技能市场", hint: "本版没有配置经验证的市场来源。" - }, h$11("p", { style: styles.hint }, "能力缺口:capabilities.features.skillsMarketplace = false,因此不显示任何搜索框或示例条目。")); + }, h$12("p", { style: styles.hint }, "能力缺口:capabilities.features.skillsMarketplace = false,因此不显示任何搜索框或示例条目。")); var providerLabel = state.provider; if (state.providers !== null) state.providers.forEach(function(provider) { if (provider.id === state.provider) providerLabel = provider.label; }); var resultRows = state.entries.map(function(entry) { - return h$11("div", { + return h$12("div", { key: entry.id, style: styles.row - }, h$11("div", { style: styles.rowHead }, h$11("span", { style: styles.rowTitle }, entry.name), h$11("div", { style: styles.pills }, entry.version === void 0 ? null : h$11(Pill$1, { + }, h$12("div", { style: styles.rowHead }, h$12("span", { style: styles.rowTitle }, entry.name), h$12("div", { style: styles.pills }, entry.version === void 0 ? null : h$12(Pill$1, { label: "版本", value: String(entry.version), tone: "muted" - }), h$11(Pill$1, { + }), h$12(Pill$1, { label: "技能", value: (entry.skills || []).length, tone: "muted" - }), entry.author === void 0 ? null : h$11(Pill$1, { + }), entry.author === void 0 ? null : h$12(Pill$1, { label: "作者", value: String(entry.author), tone: "muted" - }))), h$11("p", { style: styles.hint }, entry.description === "" ? "(无描述)" : entry.description), h$11("div", { style: styles.actions }, h$11(Btn, { + }))), h$12("p", { style: styles.hint }, entry.description === "" ? "(无描述)" : entry.description), h$12("div", { style: styles.actions }, h$12(Btn, { label: "查看详情", variant: "small", disabled: state.busy !== "", @@ -946,16 +946,16 @@ window.__ModuleLoader__.load({ var detailBox = null; if (state.detail !== null) { var details = Array.isArray(state.detail.skillDetails) ? state.detail.skillDetails : []; - detailBox = h$11("div", { style: styles.nested }, h$11("p", { style: styles.hint }, "来源:" + String(state.detail.sourceRepo) + " · " + (state.detail.description || "")), h$11("div", { style: { + detailBox = h$12("div", { style: styles.nested }, h$12("p", { style: styles.hint }, "来源:" + String(state.detail.sourceRepo) + " · " + (state.detail.description || "")), h$12("div", { style: { display: "flex", flexDirection: "column", gap: "4px" } }, details.map(function(skill) { - return h$11("div", { + return h$12("div", { key: skill.folder, style: styles.rowHead - }, h$11("span", { style: styles.rowTitle }, skill.name === void 0 ? skill.folder : skill.name), h$11("span", { style: styles.hint }, skill.ok === false ? "(无法读取 SKILL.md)" : String(skill.description || ""))); - })), h$11("div", { style: styles.actions }, h$11(Btn, { + }, h$12("span", { style: styles.rowTitle }, skill.name === void 0 ? skill.folder : skill.name), h$12("span", { style: styles.hint }, skill.ok === false ? "(无法读取 SKILL.md)" : String(skill.description || ""))); + })), h$12("div", { style: styles.actions }, h$12(Btn, { variant: "primary", label: state.busy === "plan" ? "拉取中…" : "拉取安装计划", disabled: state.busy !== "", @@ -965,71 +965,71 @@ window.__ModuleLoader__.load({ var planBox = null; if (state.plan !== null) { var candidates = Array.isArray(state.plan.candidates) ? state.plan.candidates : []; - planBox = h$11("div", { style: styles.nested }, h$11("p", { style: styles.hint }, "已固定提交:" + (state.plan.commit === void 0 ? "克隆时记录实际提交" : String(state.plan.commit).slice(0, 12)) + ";只安装勾选项,冲突项默认不勾,不执行仓库脚本。"), candidates.length === 0 ? h$11("p", { style: styles.hint }, "该条目没有可安装的技能。") : null, h$11("div", { style: { + planBox = h$12("div", { style: styles.nested }, h$12("p", { style: styles.hint }, "已固定提交:" + (state.plan.commit === void 0 ? "克隆时记录实际提交" : String(state.plan.commit).slice(0, 12)) + ";只安装勾选项,冲突项默认不勾,不执行仓库脚本。"), candidates.length === 0 ? h$12("p", { style: styles.hint }, "该条目没有可安装的技能。") : null, h$12("div", { style: { display: "flex", flexDirection: "column", gap: "6px" } }, candidates.map(function(candidate) { - return h$11("label", { + return h$12("label", { key: candidate.folder, style: styles.checkboxRow - }, h$11("input", { + }, h$12("input", { type: "checkbox", checked: state.selected[candidate.folder] === true, disabled: candidate.conflict === true || candidate.problem !== void 0, onChange: function() { toggleFolder(candidate.folder); } - }), h$11("span", null, candidate.folder + " · " + String(candidate.files) + " 个文件 · " + formatBytes(candidate.bytes) + (candidate.conflict === true ? " · 已存在,跳过" : "") + (candidate.problem === void 0 ? "" : " · " + candidate.problem))); - })), h$11("div", { style: styles.actions }, h$11(Btn, { + }), h$12("span", null, candidate.folder + " · " + String(candidate.files) + " 个文件 · " + formatBytes(candidate.bytes) + (candidate.conflict === true ? " · 已存在,跳过" : "") + (candidate.problem === void 0 ? "" : " · " + candidate.problem))); + })), h$12("div", { style: styles.actions }, h$12(Btn, { variant: "primary", label: state.busy === "commit" ? "安装中…" : "安装选中", disabled: state.busy !== "", onClick: commitPlan }))); } - return h$11(Section, { + return h$12(Section, { title: "技能市场", hint: "来自经验证的公开市场清单;安装走暂存计划、只装勾选项并固定提交。" - }, h$11("div", { style: { + }, h$12("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, h$11("div", { style: styles.pills }, h$11(Pill$1, { + } }, h$12("div", { style: styles.pills }, h$12(Pill$1, { label: "来源", value: String(providerLabel || "未配置"), tone: "muted" - }), state.providers === null ? null : h$11(Pill$1, { + }), state.providers === null ? null : h$12(Pill$1, { label: "已接入", value: state.providers.length, tone: "ok" - })), h$11("div", { style: { + })), h$12("div", { style: { display: "flex", gap: "8px", alignItems: "flex-end", flexWrap: "wrap" - } }, h$11("div", { style: { + } }, h$12("div", { style: { flex: "1 1 220px", minWidth: 0 - } }, h$11(Field, { + } }, h$12(Field, { label: "搜索市场", value: state.query, placeholder: "例如 xlsx / pdf / design", onChange: function(value) { patch({ query: value }); } - })), h$11(Btn, { + })), h$12(Btn, { variant: "primary", label: state.busy === "search" ? "搜索中…" : "搜索", disabled: state.busy !== "", onClick: function() { search(false); } - })), state.error === null ? null : h$11(Banner, { tone: "bad" }, state.error), state.notice === null ? null : h$11(Banner, { tone: state.notice.tone }, state.notice.text), state.status === "ready" && state.entries.length === 0 ? h$11("p", { style: styles.hint }, "没有匹配的市场条目。") : null, h$11("div", { style: { + })), state.error === null ? null : h$12(Banner, { tone: "bad" }, state.error), state.notice === null ? null : h$12(Banner, { tone: state.notice.tone }, state.notice.text), state.status === "ready" && state.entries.length === 0 ? h$12("p", { style: styles.hint }, "没有匹配的市场条目。") : null, h$12("div", { style: { display: "flex", flexDirection: "column", gap: "8px" - } }, resultRows), state.nextCursor === null ? null : h$11("div", { style: styles.actions }, h$11(Btn, { + } }, resultRows), state.nextCursor === null ? null : h$12("div", { style: styles.actions }, h$12(Btn, { label: "加载更多", variant: "small", disabled: state.busy !== "", @@ -1039,7 +1039,7 @@ window.__ModuleLoader__.load({ })), detailBox, planBox)); } // src-client/sections/SyncResolveSection.tsx - const h$10 = react.createElement; + const h$11 = react.createElement; function SyncResolveSection(props) { var tuple = react.useState({ status: "idle", @@ -1205,23 +1205,23 @@ window.__ModuleLoader__.load({ var data = state.data; var stats = data === null || data === void 0 ? null : data.stats; var conflicts = data === null || data === void 0 || !Array.isArray(data.conflicts) ? [] : data.conflicts; - var statPills = stats === null ? h$10("p", { style: styles.hint }, "同步引擎未启用或尚未运行。") : h$10("div", { style: styles.pills }, h$10(Pill$1, { + var statPills = stats === null ? h$11("p", { style: styles.hint }, "同步引擎未启用或尚未运行。") : h$11("div", { style: styles.pills }, h$11(Pill$1, { label: "运行中", value: stats.running === true ? "是" : "否", tone: stats.running === true ? "warn" : "muted" - }), h$10(Pill$1, { + }), h$11(Pill$1, { label: "上次运行", value: formatIso(stats.lastRunAt), tone: "muted" - }), h$10(Pill$1, { + }), h$11(Pill$1, { label: "上传", value: (stats.uploaded || []).length, tone: "muted" - }), h$10(Pill$1, { + }), h$11(Pill$1, { label: "下载", value: (stats.downloaded || []).length, tone: "muted" - }), h$10(Pill$1, { + }), h$11(Pill$1, { label: "冲突", value: conflicts.length, tone: conflicts.length > 0 ? "warn" : "muted" @@ -1229,36 +1229,36 @@ window.__ModuleLoader__.load({ var conflictRows = conflicts.map(function(conflict) { var local = conflict.local || {}; var cloud = conflict.cloud; - return h$10("div", { + return h$11("div", { key: conflict.name, style: styles.row - }, h$10("div", { style: styles.rowHead }, h$10("span", { style: styles.rowTitle }, conflict.name), h$10("div", { style: styles.pills }, h$10(Pill$1, { + }, h$11("div", { style: styles.rowHead }, h$11("span", { style: styles.rowTitle }, conflict.name), h$11("div", { style: styles.pills }, h$11(Pill$1, { label: "原因", value: String(conflict.reason), tone: "warn" - }), h$10(Pill$1, { + }), h$11(Pill$1, { label: "本地", value: local.exists === true ? local.files + " 文件" : "缺失", tone: local.exists === true ? "muted" : "bad" - }), h$10(Pill$1, { + }), h$11(Pill$1, { label: "云端", value: cloud === null ? "无" : "rev " + String(cloud.revision === void 0 ? "?" : cloud.revision), tone: cloud === null ? "muted" : "ok" - }))), h$10("p", { style: styles.hint }, conflict.note), h$10("div", { style: styles.actions }, h$10(Btn, { + }))), h$11("p", { style: styles.hint }, conflict.note), h$11("div", { style: styles.actions }, h$11(Btn, { label: "保留本地", variant: "small", disabled: state.busy !== "" || conflict.canKeepLocal !== true, onClick: function() { resolve(conflict.name, "keep_local", conflict.conflictId); } - }), h$10(Btn, { + }), h$11(Btn, { label: "采用云端", variant: "small", disabled: state.busy !== "" || conflict.canTakeCloud !== true, onClick: function() { resolve(conflict.name, "take_cloud", conflict.conflictId); } - }), h$10(Btn, { + }), h$11(Btn, { label: "手动合并", variant: "small", disabled: state.busy !== "", @@ -1268,7 +1268,7 @@ window.__ModuleLoader__.load({ }))); }); var batchRow = null; - if (conflicts.length > 0) batchRow = h$10("div", { style: styles.actions }, h$10(Btn, { + if (conflicts.length > 0) batchRow = h$11("div", { style: styles.actions }, h$11(Btn, { label: "全部保留本地", variant: "small", disabled: state.busy !== "" || !conflicts.some(function(item) { @@ -1280,7 +1280,7 @@ window.__ModuleLoader__.load({ notice: null }); } - }), h$10(Btn, { + }), h$11(Btn, { label: "全部采用云端", variant: "small", disabled: state.busy !== "" || !conflicts.some(function(item) { @@ -1296,14 +1296,14 @@ window.__ModuleLoader__.load({ var confirmAllRow = null; if (state.pendingAll !== null && conflicts.length > 0) { var pendingText = state.pendingAll === "keep_local" ? "把全部本地版本上传为新版本" : "用云端版本覆盖全部本地(覆盖前自动备份)"; - confirmAllRow = h$10("div", { style: styles.nested }, h$10("p", { style: styles.hint }, "确认" + pendingText + "?共 " + conflicts.length + " 项。"), h$10("div", { style: styles.actions }, h$10(Btn, { + confirmAllRow = h$11("div", { style: styles.nested }, h$11("p", { style: styles.hint }, "确认" + pendingText + "?共 " + conflicts.length + " 项。"), h$11("div", { style: styles.actions }, h$11(Btn, { variant: "primary", label: state.busy === "all:keep_local" || state.busy === "all:take_cloud" ? "处理中…" : "确认批量", disabled: state.busy !== "", onClick: function() { resolveAll(state.pendingAll); } - }), h$10(Btn, { + }), h$11(Btn, { variant: "small", label: "取消", disabled: state.busy !== "", @@ -1312,27 +1312,27 @@ window.__ModuleLoader__.load({ } }))); } - return h$10(Section, { + return h$11(Section, { title: "云端同步与冲突", hint: "同步先比内容与更新时间:一致直接认领,不同则自动采用较新的一边(覆盖云端前先备份本地);只有时间相同/缺失或目录结构不支持时才逐项询问,也可用批量按钮一次处理。", - aside: h$10(Btn, { + aside: h$11(Btn, { label: state.busy === "run" ? "同步中…" : "立即同步", variant: "small", disabled: state.busy !== "", onClick: runNow }) - }, h$10("div", { style: { + }, h$11("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, state.error === null ? null : h$10(Banner, { tone: "bad" }, state.error), state.notice === null ? null : h$10(Banner, { tone: state.notice.tone }, state.notice.text), statPills, batchRow, confirmAllRow, conflicts.length === 0 ? h$10("p", { style: styles.hint }, "当前没有待处理冲突。") : h$10("div", { style: { + } }, state.error === null ? null : h$11(Banner, { tone: "bad" }, state.error), state.notice === null ? null : h$11(Banner, { tone: state.notice.tone }, state.notice.text), statPills, batchRow, confirmAllRow, conflicts.length === 0 ? h$11("p", { style: styles.hint }, "当前没有待处理冲突。") : h$11("div", { style: { display: "flex", flexDirection: "column", gap: "8px" } }, conflictRows))); } // src-client/sections/McpCustomSection.tsx - const h$9 = react.createElement; + const h$10 = react.createElement; function McpCustomSection(props) { var open = react.useState(false); var tuple = react.useState({ @@ -1446,10 +1446,10 @@ window.__ModuleLoader__.load({ if (ok && typeof props.onChanged === "function") props.onChanged(); }); } - return h$9(Section, { + return h$10(Section, { title: "新增 / 导入连接", hint: "HTTP 与 stdio 都由宿主校验并保存凭据;本卡不回显已有密钥。stdio 的启动命令由你显式填写,云端不会执行任何本机命令。", - aside: h$9(Btn, { + aside: h$10(Btn, { label: open[0] ? "收起" : "展开", ariaLabel: "展开新增连接", variant: "small", @@ -1457,90 +1457,90 @@ window.__ModuleLoader__.load({ open[1](!open[0]); } }) - }, open[0] ? h$9("div", { style: { + }, open[0] ? h$10("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, h$9("div", { style: styles.grid }, h$9(Field, { + } }, h$10("div", { style: styles.grid }, h$10(Field, { label: "名称", value: s.name, onChange: function(v) { patch({ name: v }); } - }), h$9(Field, { + }), h$10(Field, { label: "Server 名(可选)", value: s.serverName, onChange: function(v) { patch({ serverName: v }); } - }), h$9("div", { style: styles.field }, h$9("span", { style: styles.label }, "传输方式"), h$9("select", { + }), h$10("div", { style: styles.field }, h$10("span", { style: styles.label }, "传输方式"), h$10("select", { value: s.transport, style: styles.input, onChange: function(e) { patch({ transport: e.target.value }); } - }, h$9("option", { value: "streamable-http" }, "Streamable HTTP"), h$9("option", { value: "stdio" }, "stdio(本机进程)")))), s.transport === "stdio" ? h$9("div", { style: styles.grid }, h$9(Field, { + }, h$10("option", { value: "streamable-http" }, "Streamable HTTP"), h$10("option", { value: "stdio" }, "stdio(本机进程)")))), s.transport === "stdio" ? h$10("div", { style: styles.grid }, h$10(Field, { label: "启动命令", value: s.command, placeholder: "npx / uvx / 本机可执行文件", onChange: function(v) { patch({ command: v }); } - }), h$9(Field, { + }), h$10(Field, { label: "参数(空格分隔)", value: s.args, onChange: function(v) { patch({ args: v }); } - }), h$9(Field, { + }), h$10(Field, { label: "工作目录(可选)", value: s.cwd, onChange: function(v) { patch({ cwd: v }); } - })) : h$9("div", { style: { + })) : h$10("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, h$9(Field, { + } }, h$10(Field, { label: "URL", value: s.url, placeholder: "https://…", onChange: function(v) { patch({ url: v }); } - }), h$9("div", { style: styles.grid }, h$9("div", { style: styles.field }, h$9("span", { style: styles.label }, "鉴权"), h$9("select", { + }), h$10("div", { style: styles.grid }, h$10("div", { style: styles.field }, h$10("span", { style: styles.label }, "鉴权"), h$10("select", { value: s.authMode, style: styles.input, onChange: function(e) { patch({ authMode: e.target.value }); } - }, h$9("option", { value: "none" }, "无"), h$9("option", { value: "bearer" }, "Bearer Token"), h$9("option", { value: "api-key" }, "API Key"))), s.authMode === "bearer" ? h$9(Field, { + }, h$10("option", { value: "none" }, "无"), h$10("option", { value: "bearer" }, "Bearer Token"), h$10("option", { value: "api-key" }, "API Key"))), s.authMode === "bearer" ? h$10(Field, { label: "Bearer Token", type: "password", value: s.bearerToken, onChange: function(v) { patch({ bearerToken: v }); } - }) : null, s.authMode === "api-key" ? h$9(Field, { + }) : null, s.authMode === "api-key" ? h$10(Field, { label: "API Key 头", value: s.apiKeyHeader, onChange: function(v) { patch({ apiKeyHeader: v }); } - }) : null, s.authMode === "api-key" ? h$9(Field, { + }) : null, s.authMode === "api-key" ? h$10(Field, { label: "API Key 值", type: "password", value: s.apiKeyValue, onChange: function(v) { patch({ apiKeyValue: v }); } - }) : null)), h$9("div", { style: styles.actions }, h$9(Btn, { + }) : null)), h$10("div", { style: styles.actions }, h$10(Btn, { variant: "primary", label: s.busy === "configure" ? "保存中…" : "校验并保存连接", disabled: s.busy !== "", onClick: submit - })), h$9("p", { style: styles.hint }, "或粘贴 mcpServers JSON 批量导入:"), h$9("textarea", { + })), h$10("p", { style: styles.hint }, "或粘贴 mcpServers JSON 批量导入:"), h$10("textarea", { value: s.importJson, rows: 5, style: Object.assign({}, styles.input, { @@ -1551,14 +1551,14 @@ window.__ModuleLoader__.load({ onChange: function(e) { patch({ importJson: e.target.value }); } - }), h$9("div", { style: styles.actions }, h$9(Btn, { + }), h$10("div", { style: styles.actions }, h$10(Btn, { label: s.busy === "import" ? "导入中…" : "导入 JSON", disabled: s.busy !== "", onClick: importJson - })), s.notice === null ? null : h$9(Banner, { tone: s.notice.tone }, s.notice.text)) : null); + })), s.notice === null ? null : h$10(Banner, { tone: s.notice.tone }, s.notice.text)) : null); } // src-client/sections/McpConfigSection.tsx - const h$8 = react.createElement; + const h$9 = react.createElement; function McpConfigSection(props) { var items = Array.isArray(props.items) ? props.items : []; var open = react.useState(false); @@ -1728,10 +1728,10 @@ window.__ModuleLoader__.load({ }); } var gov = s.gov; - return h$8(Section, { + return h$9(Section, { title: "连接配置、范围与治理", hint: "配置编辑使用宿主的保留标记合并,空输入不会清空已有密钥;作用域与策略都带 revision 预览后再提交。", - aside: h$8(Btn, { + aside: h$9(Btn, { label: open[0] ? "收起" : "展开", ariaLabel: "展开连接配置", variant: "small", @@ -1739,11 +1739,11 @@ window.__ModuleLoader__.load({ open[1](!open[0]); } }) - }, open[0] ? h$8("div", { style: { + }, open[0] ? h$9("div", { style: { display: "flex", flexDirection: "column", gap: "12px" - } }, itemSelect(items, s.key, choose), s.key === "" ? h$8("p", { style: styles.hint }, "选择一条连接后可编辑配置、调整范围或设置治理策略。") : h$8("div", { style: styles.nested }, h$8("p", { style: styles.hint }, "可编辑配置(保留标记 表示保留原密钥):"), h$8("textarea", { + } }, itemSelect(items, s.key, choose), s.key === "" ? h$9("p", { style: styles.hint }, "选择一条连接后可编辑配置、调整范围或设置治理策略。") : h$9("div", { style: styles.nested }, h$9("p", { style: styles.hint }, "可编辑配置(保留标记 表示保留原密钥):"), h$9("textarea", { value: s.json, rows: 8, style: Object.assign({}, styles.input, { @@ -1753,88 +1753,88 @@ window.__ModuleLoader__.load({ onChange: function(e) { patch({ json: e.target.value }); } - }), h$8("div", { style: styles.actions }, h$8(Btn, { + }), h$9("div", { style: styles.actions }, h$9(Btn, { variant: "primary", label: s.busy === "save" ? "保存中…" : "保存配置", disabled: s.busy !== "" || s.json === "", onClick: save - })), h$8("p", { style: styles.hint }, "作用域(目标范围 + mode=move,凭据不复制):"), h$8("div", { style: styles.grid }, h$8("div", { style: styles.field }, h$8("span", { style: styles.label }, "目标范围"), h$8("select", { + })), h$9("p", { style: styles.hint }, "作用域(目标范围 + mode=move,凭据不复制):"), h$9("div", { style: styles.grid }, h$9("div", { style: styles.field }, h$9("span", { style: styles.label }, "目标范围"), h$9("select", { value: s.targetScope, style: styles.input, onChange: function(e) { patch({ targetScope: e.target.value }); } - }, h$8("option", { value: "global" }, "全局"), h$8("option", { value: "project" }, "指定工作区"))), s.targetScope === "project" ? h$8(Field, { + }, h$9("option", { value: "global" }, "全局"), h$9("option", { value: "project" }, "指定工作区"))), s.targetScope === "project" ? h$9(Field, { label: "工作区 id", value: s.workspaceId, onChange: function(v) { patch({ workspaceId: v }); } - }) : null), h$8("div", { style: styles.actions }, h$8(Btn, { + }) : null), h$9("div", { style: styles.actions }, h$9(Btn, { label: s.busy === "scope-preview" ? "预览中…" : "预览作用域", disabled: s.busy !== "", onClick: previewScope - }), s.scopePreview === null ? null : h$8(Btn, { + }), s.scopePreview === null ? null : h$9(Btn, { variant: "primary", label: s.busy === "scope-apply" ? "应用中…" : "应用作用域(rev " + String(s.scopePreview.baseRevision) + ")", disabled: s.busy !== "" || s.scopePreview.canApply !== true, onClick: applyScope - })), s.scopePreview === null ? null : h$8("p", { style: styles.hint }, "影响:" + String(s.scopePreview.impact === void 0 ? "" : JSON.stringify(s.scopePreview.impact)) + ";可应用:" + (s.scopePreview.canApply === true ? "是" : "否") + ";凭据复制:否"), h$8("p", { style: styles.hint }, "治理(当前 connection 级):"), gov === null ? h$8("p", { style: styles.hint }, "治理文档未读取。") : h$8("div", { style: styles.pills }, h$8(Pill$1, { + })), s.scopePreview === null ? null : h$9("p", { style: styles.hint }, "影响:" + String(s.scopePreview.impact === void 0 ? "" : JSON.stringify(s.scopePreview.impact)) + ";可应用:" + (s.scopePreview.canApply === true ? "是" : "否") + ";凭据复制:否"), h$9("p", { style: styles.hint }, "治理(当前 connection 级):"), gov === null ? h$9("p", { style: styles.hint }, "治理文档未读取。") : h$9("div", { style: styles.pills }, h$9(Pill$1, { label: "revision", value: gov.revision, tone: "muted" - }), h$8(Pill$1, { + }), h$9(Pill$1, { label: "规则", value: (gov.rules || []).length, tone: "muted" - }), h$8(Pill$1, { + }), h$9(Pill$1, { label: "优先级", value: String(gov.precedenceLabel || "—"), tone: "muted" - })), h$8("div", { style: styles.actions }, h$8(Btn, { + })), h$9("div", { style: styles.actions }, h$9(Btn, { label: "预览 allow", variant: "small", disabled: s.busy !== "" || selected === null, onClick: function() { previewPolicy("allow"); } - }), h$8(Btn, { + }), h$9(Btn, { label: "预览 deny", variant: "small", disabled: s.busy !== "" || selected === null, onClick: function() { previewPolicy("deny"); } - }), h$8(Btn, { + }), h$9(Btn, { label: "预览 inherit", variant: "small", disabled: s.busy !== "" || selected === null, onClick: function() { previewPolicy("inherit"); } - }), s.policyPreview === null ? null : h$8(Btn, { + }), s.policyPreview === null ? null : h$9(Btn, { variant: "primary", label: s.busy === "policy-apply" ? "应用中…" : "应用策略(rev " + String(s.policyPreview.baseRevision) + ")", disabled: s.busy !== "", onClick: applyPolicy - }))), s.notice === null ? null : h$8(Banner, { tone: s.notice.tone }, s.notice.text)) : null); + }))), s.notice === null ? null : h$9(Banner, { tone: s.notice.tone }, s.notice.text)) : null); } function itemSelect(items, value, onChange) { - return h$8("div", { style: styles.field }, h$8("span", { style: styles.label }, "连接"), h$8("select", { + return h$9("div", { style: styles.field }, h$9("span", { style: styles.label }, "连接"), h$9("select", { value, style: styles.input, onChange: function(e) { onChange(e.target.value); } - }, h$8("option", { value: "" }, "选择连接…"), items.map(function(item) { - return h$8("option", { + }, h$9("option", { value: "" }, "选择连接…"), items.map(function(item) { + return h$9("option", { key: item.key, value: item.key }, String(item.name || item.key) + "(" + String(item.transport || "") + ")"); }))); } // src-client/sections/ImportSection.tsx - const h$7 = react.createElement; + const h$8 = react.createElement; function ImportSection(props) { var onImported = props && typeof props.onImported === "function" ? props.onImported : null; var tuple = react.useState({ @@ -2016,17 +2016,17 @@ window.__ModuleLoader__.load({ load(); }); } - if (!s.expanded) return h$7("div", { style: { + if (!s.expanded) return h$8("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: "8px", flexWrap: "wrap" - } }, h$7(Btn, { + } }, h$8(Btn, { label: "从其他软件导入", ariaLabel: "从其他软件导入", onClick: openPanel - }), s.notice === null ? null : h$7(Banner, { tone: s.notice.tone }, s.notice.text)); + }), s.notice === null ? null : h$8(Banner, { tone: s.notice.tone }, s.notice.text)); function describe(skill) { var text = String(skill.description === void 0 || skill.description === null ? "" : skill.description).trim(); if (/^[>|][+-]?$/.test(text)) return ""; @@ -2041,15 +2041,15 @@ window.__ModuleLoader__.load({ var selectable = visible.filter(function(entry) { return !importedYet(entry.skill); }); - return h$7("div", { + return h$8("div", { key: source.id, style: styles.row - }, h$7("div", { style: styles.rowHead }, h$7("span", { style: { + }, h$8("div", { style: styles.rowHead }, h$8("span", { style: { display: "inline-flex", alignItems: "center", gap: "8px", minWidth: 0 - } }, h$7("span", { style: styles.sourceGlyph }, String(source.label).slice(0, 1)), h$7("span", { style: styles.sourceTitle }, String(source.label)), h$7("span", { style: styles.hint }, source.exists ? String(all.length) + " 个技能" + (needle === "" ? "" : " · 匹配 " + String(visible.length)) + " · 可导入 " + String(selectable.length) : "未安装")), source.exists ? h$7("div", { style: styles.actions }, h$7(Btn, { + } }, h$8("span", { style: styles.sourceGlyph }, String(source.label).slice(0, 1)), h$8("span", { style: styles.sourceTitle }, String(source.label)), h$8("span", { style: styles.hint }, source.exists ? String(all.length) + " 个技能" + (needle === "" ? "" : " · 匹配 " + String(visible.length)) + " · 可导入 " + String(selectable.length) : "未安装")), source.exists ? h$8("div", { style: styles.actions }, h$8(Btn, { label: "全选本来源(" + String(selectable.length) + ")", ariaLabel: "全选本来源 " + String(source.label), variant: "small", @@ -2057,13 +2057,13 @@ window.__ModuleLoader__.load({ onClick: function() { chooseMany(visible, true); } - }), h$7(Btn, { + }), h$8(Btn, { label: open ? "收起" : "展开", variant: "small", onClick: function() { toggleSource(source.id); } - })) : null), h$7("span", { style: styles.mono }, String(source.root)), !source.exists || !open ? null : visible.length === 0 ? h$7("p", { style: styles.hint }, needle === "" ? "这个来源里还没有技能。" : "没有匹配「" + s.search + "」的技能。") : h$7("div", { style: { + })) : null), h$8("span", { style: styles.mono }, String(source.root)), !source.exists || !open ? null : visible.length === 0 ? h$8("p", { style: styles.hint }, needle === "" ? "这个来源里还没有技能。" : "没有匹配「" + s.search + "」的技能。") : h$8("div", { style: { display: "flex", flexDirection: "column", gap: "2px", @@ -2072,10 +2072,10 @@ window.__ModuleLoader__.load({ } }, visible.map(function(entry) { var skill = entry.skill; var has = importedYet(skill); - return h$7("label", { + return h$8("label", { key: String(skill.folder), style: styles.checkboxRow - }, h$7("input", { + }, h$8("input", { type: "checkbox", checked: has || isChosen(entry), disabled: has || s.busy !== "", @@ -2083,54 +2083,54 @@ window.__ModuleLoader__.load({ onChange: function(event) { chooseMany([entry], event.target.checked === true); } - }), h$7("span", { style: { + }), h$8("span", { style: { minWidth: 0, flex: "1 1 auto" - } }, h$7("span", { style: styles.rowTitle }, String(skill.name)), describe(skill) === "" ? null : h$7("span", { style: Object.assign({}, styles.hint, styles.clamp1) }, describe(skill))), has ? h$7(Pill$1, { + } }, h$8("span", { style: styles.rowTitle }, String(skill.name)), describe(skill) === "" ? null : h$8("span", { style: Object.assign({}, styles.hint, styles.clamp1) }, describe(skill))), has ? h$8(Pill$1, { label: "DSH", value: "已导入", tone: "muted" }) : null); }))); }); - return h$7(Section, { + return h$8(Section, { title: "从其他软件导入", hint: "把其他软件技能目录里的技能复制一份到 DSH,原目录不动;同名技能不能重复导入。", - aside: h$7("div", { style: styles.actions }, h$7(Btn, { + aside: h$8("div", { style: styles.actions }, h$8(Btn, { label: "刷新", variant: "small", onClick: load - }), h$7(Btn, { + }), h$8(Btn, { label: "收起", variant: "small", onClick: closePanel })) - }, s.status === "loading" ? h$7("p", { style: styles.hint }, "正在读取来源…") : others.length === 0 ? h$7("p", { style: styles.hint }, "没有检测到其他软件的技能目录。") : h$7("div", { style: styles.root }, h$7("div", { style: styles.pills }, h$7(Pill$1, { + }, s.status === "loading" ? h$8("p", { style: styles.hint }, "正在读取来源…") : others.length === 0 ? h$8("p", { style: styles.hint }, "没有检测到其他软件的技能目录。") : h$8("div", { style: styles.root }, h$8("div", { style: styles.pills }, h$8(Pill$1, { label: "来源", value: String(others.length), tone: "muted" - }), h$7(Pill$1, { + }), h$8(Pill$1, { label: "可导入", value: String(candidates.length - alreadyCount), tone: "muted" - }), s.search === "" ? null : h$7(Pill$1, { + }), s.search === "" ? null : h$8(Pill$1, { label: "匹配", value: String(matches.length), tone: matches.length === 0 ? "muted" : "ok" - }), h$7(Pill$1, { + }), h$8(Pill$1, { label: "已选", value: String(chosenEntries.length), tone: chosenEntries.length === 0 ? "muted" : "ok" - }), alreadyCount === 0 ? null : h$7(Pill$1, { + }), alreadyCount === 0 ? null : h$8(Pill$1, { label: "已在 DSH", value: String(alreadyCount), tone: "muted" - })), h$7("div", { style: { + })), h$8("div", { style: { display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" - } }, h$7("input", { + } }, h$8("input", { type: "search", style: Object.assign({}, styles.input, { flex: "1 1 220px", @@ -2142,13 +2142,13 @@ window.__ModuleLoader__.load({ onChange: function(event) { patch({ search: event.target.value }); } - }), s.search === "" ? null : h$7(Btn, { + }), s.search === "" ? null : h$8(Btn, { label: "清空搜索", variant: "small", onClick: function() { patch({ search: "" }); } - })), h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7(Btn, { + })), h$8("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$8(Btn, { label: "全选匹配可导入(" + String(importable.length) + ")", ariaLabel: "全选匹配可导入", variant: "small", @@ -2156,7 +2156,7 @@ window.__ModuleLoader__.load({ onClick: function() { chooseMany(importable, true); } - }), h$7(Btn, { + }), h$8(Btn, { label: "全选全部(" + String(candidates.length - alreadyCount) + ")", ariaLabel: "全选全部", variant: "small", @@ -2166,7 +2166,7 @@ window.__ModuleLoader__.load({ return !importedYet(entry.skill); }), true); } - }), h$7(Btn, { + }), h$8(Btn, { label: "清空已选", ariaLabel: "清空已选", variant: "small", @@ -2174,20 +2174,20 @@ window.__ModuleLoader__.load({ onClick: function() { patch({ selection: [] }); } - }), h$7(Btn, { + }), h$8(Btn, { variant: "primary", label: s.busy === "batch" ? "导入中…" : "导入所选(" + String(chosenEntries.length) + ")", ariaLabel: "导入所选", disabled: s.busy !== "" || chosenEntries.length === 0, onClick: importSelected - })), s.progress === null ? null : h$7("p", { style: styles.hint }, "正在导入:" + String(s.progress.done) + " / " + String(s.progress.total)), h$7("div", { style: { + })), s.progress === null ? null : h$8("p", { style: styles.hint }, "正在导入:" + String(s.progress.done) + " / " + String(s.progress.total)), h$8("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, blocks)), s.notice === null ? null : h$7(Banner, { tone: s.notice.tone }, s.notice.text)); + } }, blocks)), s.notice === null ? null : h$8(Banner, { tone: s.notice.tone }, s.notice.text)); } // src-client/SettingsCard.tsx - const h$6 = react.createElement; + const h$7 = react.createElement; function findCheck(source, id) { if (source === null || source === void 0 || !Array.isArray(source.checks)) return void 0; for (var index = 0; index < source.checks.length; index += 1) if (source.checks[index] !== null && typeof source.checks[index] === "object" && source.checks[index].id === id) return source.checks[index]; @@ -2935,13 +2935,13 @@ window.__ModuleLoader__.load({ return probeMcp(); }); } - if (error !== null && snapshot === null) return h$6("div", { style: styles.root }, h$6(Banner, { tone: "bad" }, error), h$6("div", { style: styles.actions }, h$6(Btn, { + if (error !== null && snapshot === null) return h$7("div", { style: styles.root }, h$7(Banner, { tone: "bad" }, error), h$7("div", { style: styles.actions }, h$7(Btn, { label: "重新加载", onClick: function() { load(false); } }))); - if (snapshot === null || draft === null) return h$6("div", { style: styles.root }, h$6("p", { style: styles.hint }, "正在读取云端记忆插件状态…")); + if (snapshot === null || draft === null) return h$7("div", { style: styles.root }, h$7("p", { style: styles.hint }, "正在读取云端记忆插件状态…")); var reporter = snapshot.reporter === void 0 || snapshot.reporter === null ? {} : snapshot.reporter; var tokens = snapshot.tokens === void 0 || snapshot.tokens === null ? { activity: {}, @@ -2980,10 +2980,10 @@ window.__ModuleLoader__.load({ tone: "bad", text: "不可达" }; - var header = h$6("div", { + var header = h$7("div", { style: styles.section, key: "header" - }, h$6("div", { style: styles.sectionHead }, h$6("h4", { style: styles.sectionTitle }, h$6("span", { style: { + }, h$7("div", { style: styles.sectionHead }, h$7("h4", { style: styles.sectionTitle }, h$7("span", { style: { display: "inline-block", width: "9px", height: "9px", @@ -2991,32 +2991,32 @@ window.__ModuleLoader__.load({ background: "linear-gradient(135deg, #6366f1, #8b5cf6)", marginRight: "8px", verticalAlign: "1px" - } }), "云端记忆 · v" + String(caps.version === void 0 ? "—" : caps.version)), h$6("div", { style: styles.pills }, h$6(Pill$1, { + } }), "云端记忆 · v" + String(caps.version === void 0 ? "—" : caps.version)), h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "连接", value: connectivity.text, tone: connectivity.tone - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "最后检查", value: checkedAt, tone: "muted" - }), dirty ? h$6(Pill$1, { + }), dirty ? h$7(Pill$1, { label: "草稿", value: "未保存", tone: "warn" - }) : null)), h$6("div", { style: styles.pills }, h$6(Pill$1, { + }) : null)), h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "已上报", value: reporter.recorded === void 0 ? 0 : reporter.recorded, tone: "ok" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "待重试", value: reporter.queued === void 0 ? 0 : reporter.queued, tone: reporter.queued > 0 ? "warn" : "muted" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "失败", value: reporter.failed === void 0 ? 0 : reporter.failed, tone: reporter.failed > 0 ? "bad" : "muted" }))); - var tabBar = h$6(Switch, { + var tabBar = h$7(Switch, { key: "tabs", ariaLabel: "云端记忆管理页签", value: tab, @@ -3036,7 +3036,7 @@ window.__ModuleLoader__.load({ } ] }); - var noticeBox = notice === null ? null : h$6(Banner, { + var noticeBox = notice === null ? null : h$7(Banner, { tone: notice.tone, role: "status", key: "notice" @@ -3044,13 +3044,13 @@ window.__ModuleLoader__.load({ var connectionTab = null; if (tab === "connection") { var changedOrigin = draft.baseUrlConfigured && draft.baseUrlOrigin !== "" && String(draft.baseUrl) !== "" && String(draft.baseUrl).indexOf(draft.baseUrlOrigin) !== 0; - connectionTab = h$6("div", { + connectionTab = h$7("div", { style: styles.root, key: "connection" - }, h$6(Section, { + }, h$7(Section, { title: "身份验证", hint: "两种方式最终更新同一组配置;切换不会清除任何一种方式已保存的凭据,也不会自动发起请求。", - aside: h$6(Switch, { + aside: h$7(Switch, { ariaLabel: "身份验证方式", value: identity, onChange: switchIdentity, @@ -3062,7 +3062,7 @@ window.__ModuleLoader__.load({ label: "手动令牌" }] }) - }, identity === "account" ? h$6("div", { style: styles.nested }, h$6("p", { style: styles.hint }, "用云端面板的普通用户账号登录,插件会用一次性会话换取活动与记忆令牌并写入本机。密码只在这一次请求里使用:不保存、不写日志、不回显。"), h$6("div", { style: styles.grid }, h$6(Field, { + }, identity === "account" ? h$7("div", { style: styles.nested }, h$7("p", { style: styles.hint }, "用云端面板的普通用户账号登录,插件会用一次性会话换取活动与记忆令牌并写入本机。密码只在这一次请求里使用:不保存、不写日志、不回显。"), h$7("div", { style: styles.grid }, h$7(Field, { label: "用户名", value: loginDraft.username, placeholder: "云端面板的账号", @@ -3071,7 +3071,7 @@ window.__ModuleLoader__.load({ return Object.assign({}, previous, { username: value }); }); } - }), h$6(Field, { + }), h$7(Field, { label: "密码", type: "password", value: loginDraft.password, @@ -3082,12 +3082,12 @@ window.__ModuleLoader__.load({ return Object.assign({}, previous, { password: value }); }); } - })), h$6("div", { style: styles.actions }, h$6(Btn, { + })), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: busy === "login" ? "登录中…" : "登录并获取令牌", disabled: busy !== "", onClick: login - }), loginResult === null ? null : h$6("span", { style: styles.hint }, "当前账号:" + String(loginResult.user !== void 0 && loginResult.user !== null && loginResult.user.username !== void 0 ? loginResult.user.username : "未知") + (loginResult.warning === void 0 ? "" : "(" + String(loginResult.warning) + ")")))) : h$6("div", { style: styles.nested }, h$6("p", { style: styles.hint }, "三个令牌各有独立权限:activity:write 只用于上报,memory:write 同时允许检索与写入,summary:write 用于自动摘要(可选)。空值表示不修改;清除是独立动作。"), h$6("div", { style: styles.grid }, h$6(Field, { + }), loginResult === null ? null : h$7("span", { style: styles.hint }, "当前账号:" + String(loginResult.user !== void 0 && loginResult.user !== null && loginResult.user.username !== void 0 ? loginResult.user.username : "未知") + (loginResult.warning === void 0 ? "" : "(" + String(loginResult.warning) + ")")))) : h$7("div", { style: styles.nested }, h$7("p", { style: styles.hint }, "三个令牌各有独立权限:activity:write 只用于上报,memory:write 同时允许检索与写入,summary:write 用于自动摘要(可选)。空值表示不修改;清除是独立动作。"), h$7("div", { style: styles.grid }, h$7(Field, { label: "活动上报令牌(activity:write)", type: "password", value: tokenDraft.activity, @@ -3096,7 +3096,7 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchTokens({ activity: value }); } - }), h$6(Field, { + }), h$7(Field, { label: "记忆读写令牌(memory:write)", type: "password", value: tokenDraft.memory, @@ -3105,7 +3105,7 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchTokens({ memory: value }); } - }), h$6(Field, { + }), h$7(Field, { label: "摘要令牌(summary:write,可选)", type: "password", value: tokenDraft.summary, @@ -3114,31 +3114,31 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchTokens({ summary: value }); } - })), h$6("div", { style: styles.actions }, h$6(Btn, { + })), h$7("div", { style: styles.actions }, h$7(Btn, { label: "清除上报令牌", variant: "small", disabled: activityToken.configured !== true || busy !== "", onClick: function() { clearToken("activity"); } - }), h$6(Btn, { + }), h$7(Btn, { label: "清除记忆令牌", variant: "small", disabled: memoryToken.configured !== true || busy !== "", onClick: function() { clearToken("memory"); } - }), h$6(Btn, { + }), h$7(Btn, { label: "清除摘要令牌", variant: "small", disabled: summaryToken.configured !== true || busy !== "", onClick: function() { clearToken("summary"); } - })))), h$6(Section, { + })))), h$7(Section, { title: "服务地址", hint: "账号登录会把密码发到该地址:仅接受 HTTPS(本机回环除外)。不同 origin 不会复用旧令牌。" - }, h$6(Field, { + }, h$7(Field, { label: "服务地址(baseUrl)", value: draft.baseUrl, placeholder: "https://<你的域名>/api/longmemory", @@ -3146,57 +3146,57 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchDraft({ baseUrl: value }); } - }), advanced ? h$6("div", { style: styles.nested }, h$6("div", { style: styles.grid }, h$6(Field, { + }), advanced ? h$7("div", { style: styles.nested }, h$7("div", { style: styles.grid }, h$7(Field, { label: "客户端标识(client_id)", value: draft.clientId, onChange: function(value) { patchDraft({ clientId: value }); } - }), h$6(Field, { + }), h$7(Field, { label: "请求超时(毫秒)", type: "number", value: draft.requestTimeoutMs, onChange: function(value) { patchDraft({ requestTimeoutMs: value }); } - })), h$6("div", { style: styles.checkboxRow }, h$6("input", { + })), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.enabled, id: "dsh-brain-enabled", onChange: function(event) { patchDraft({ enabled: event.target.checked }); } - }), h$6("label", { + }), h$7("label", { htmlFor: "dsh-brain-enabled", style: styles.label - }, "启用每轮活动上报(只上报时间戳、会话 id 与状态,不上传对话内容)")), h$6("div", { style: styles.checkboxRow }, h$6("input", { + }, "启用每轮活动上报(只上报时间戳、会话 id 与状态,不上传对话内容)")), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.summaryEnabled, id: "dsh-brain-summary", onChange: function(event) { patchDraft({ summaryEnabled: event.target.checked }); } - }), h$6("label", { + }), h$7("label", { htmlFor: "dsh-brain-summary", style: styles.label - }, "启用自动摘要(会把该轮对话文本上传为待确认提案;与上面的元数据上报是两件事)")), h$6("div", { style: styles.checkboxRow }, h$6("input", { + }, "启用自动摘要(会把该轮对话文本上传为待确认提案;与上面的元数据上报是两件事)")), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.activityEnabled, id: "dsh-brain-activity", onChange: function(event) { patchDraft({ activityEnabled: event.target.checked }); } - }), h$6("label", { + }), h$7("label", { htmlFor: "dsh-brain-activity", style: styles.label - }, "启用活动上报(细粒度开关;未显式设置时跟随总开关)"))) : h$6("div", { style: styles.actions }, h$6(Btn, { + }, "启用活动上报(细粒度开关;未显式设置时跟随总开关)"))) : h$7("div", { style: styles.actions }, h$7(Btn, { label: "高级设置", variant: "small", onClick: toggleAdvanced - }))), h$6(Section, { + }))), h$7(Section, { title: "记忆配置", hint: "只影响记忆工具:开关未显式设置时跟随总开关,检索上限只限制单次返回条数。" - }, h$6("div", { style: styles.grid }, h$6(Field, { + }, h$7("div", { style: styles.grid }, h$7(Field, { label: "单次搜索返回上限(defaultK)", type: "number", value: draft.defaultK, @@ -3204,20 +3204,20 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchDraft({ defaultK: value }); } - })), h$6("div", { style: styles.checkboxRow }, h$6("input", { + })), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.memoryEnabled, id: "dsh-brain-memory-enabled", onChange: function(event) { patchDraft({ memoryEnabled: event.target.checked }); } - }), h$6("label", { + }), h$7("label", { htmlFor: "dsh-brain-memory-enabled", style: styles.label - }, "启用记忆工具(memory_search / memory_read / memory_add)"))), features.skillsSync === false ? h$6("div", null) : h$6("div", null, h$6(Section, { + }, "启用记忆工具(memory_search / memory_read / memory_add)"))), features.skillsSync === false ? h$7("div", null) : h$7("div", null, h$7(Section, { title: "Skill 同步", hint: "同步由后台定时执行,这里只保存开关与目录;目录留空使用默认位置。" - }, h$6(Field, { + }, h$7(Field, { label: "技能目录(skillsDir,可选)", value: draft.skillsDir, placeholder: "默认 $DSH_HOME/skills", @@ -3225,52 +3225,52 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchDraft({ skillsDir: value }); } - }), h$6("div", { style: styles.checkboxRow }, h$6("input", { + }), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.skillsSyncEnabled, id: "dsh-brain-skills-sync", onChange: function(event) { patchDraft({ skillsSyncEnabled: event.target.checked }); } - }), h$6("label", { + }), h$7("label", { htmlFor: "dsh-brain-skills-sync", style: styles.label - }, "启用云端技能同步(下载云端技能库、上传本机新技能)")))), h$6(Section, { + }, "启用云端技能同步(下载云端技能库、上传本机新技能)")))), h$7(Section, { title: "连接与权限检查", - aside: h$6("div", { style: styles.actions }, h$6(Btn, { + aside: h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: busy === "save" ? "保存中…" : "保存", disabled: busy !== "", onClick: save - }), h$6(Btn, { + }), h$7(Btn, { label: busy === "test" ? "测试中…" : "测试连接", disabled: busy !== "", onClick: test - }), h$6(Btn, { + }), h$7(Btn, { label: "重试上报队列", disabled: busy !== "" || reporter.queued === void 0 || reporter.queued === 0, onClick: flush })) - }, checkSource === null ? h$6("p", { style: styles.hint }, "还没有检查记录。点「测试连接」做一次只读检查:网络 → 活动权限 → 记忆权限 → 摘要权限。") : h$6("div", { style: styles.pills }, (checkSource.checks || []).map(function(check) { - return h$6(Pill$1, { + }, checkSource === null ? h$7("p", { style: styles.hint }, "还没有检查记录。点「测试连接」做一次只读检查:网络 → 活动权限 → 记忆权限 → 摘要权限。") : h$7("div", { style: styles.pills }, (checkSource.checks || []).map(function(check) { + return h$7(Pill$1, { key: String(check.id), label: String(check.label === void 0 ? check.id : check.label), value: CHECK_LABELS[check.state] === void 0 ? String(check.state) : CHECK_LABELS[check.state], tone: CHECK_TONES[check.state] === void 0 ? "muted" : CHECK_TONES[check.state] }); - })), checkSource === null ? null : h$6("div", { style: { + })), checkSource === null ? null : h$7("div", { style: { display: "flex", flexDirection: "column", gap: "6px" } }, (checkSource.checks || []).map(function(check) { - return h$6("div", { + return h$7("div", { key: "detail-" + String(check.id), style: Object.assign({}, styles.banner, styles[CHECK_TONES[check.state]] === void 0 ? styles.muted : styles[CHECK_TONES[check.state]]) }, String(check.label === void 0 ? check.id : check.label) + ":" + String(check.message)); - })), h$6("p", { style: styles.hint }, "鉴权通过只代表令牌有效,不代表已经成功写入一条上报;两者在下面分开显示。")), h$6(Section, { title: "最近上报" }, recent.length === 0 ? h$6("p", { style: styles.hint }, "还没有记录。发一条消息让它跑完一轮,这里就会出现一条。") : h$6("table", { style: styles.table }, h$6("thead", null, h$6("tr", null, h$6("th", { style: styles.th }, "时间"), h$6("th", { style: styles.th }, "结果"), h$6("th", { style: styles.th }, "turn_id"))), h$6("tbody", null, recent.map(function(row, index) { + })), h$7("p", { style: styles.hint }, "鉴权通过只代表令牌有效,不代表已经成功写入一条上报;两者在下面分开显示。")), h$7(Section, { title: "最近上报" }, recent.length === 0 ? h$7("p", { style: styles.hint }, "还没有记录。发一条消息让它跑完一轮,这里就会出现一条。") : h$7("table", { style: styles.table }, h$7("thead", null, h$7("tr", null, h$7("th", { style: styles.th }, "时间"), h$7("th", { style: styles.th }, "结果"), h$7("th", { style: styles.th }, "turn_id"))), h$7("tbody", null, recent.map(function(row, index) { var outcome = String(row.outcome === void 0 ? "" : row.outcome); - return h$6("tr", { key: String(row.turnId) + ":" + String(index) }, h$6("td", { style: styles.td }, formatTime(row.at)), h$6("td", { style: styles.td }, h$6("span", { style: Object.assign({}, styles.pill, styles[OUTCOME_TONES[outcome]] === void 0 ? styles.muted : styles[OUTCOME_TONES[outcome]]) }, OUTCOME_LABELS[outcome] === void 0 ? outcome : OUTCOME_LABELS[outcome])), h$6("td", { style: Object.assign({}, styles.td, styles.mono) }, String(row.turnId === void 0 ? "" : row.turnId))); - }))), reporter.lastError === void 0 ? null : h$6("p", { style: styles.hint }, "最近一次错误:" + String(reporter.lastError))), h$6("p", { style: styles.hint }, "配置保存在 " + String(snapshot.settingsPath === void 0 ? "本机配置文件" : snapshot.settingsPath) + "。页面地址 /dsh-brain 仍然可用。")); + return h$7("tr", { key: String(row.turnId) + ":" + String(index) }, h$7("td", { style: styles.td }, formatTime(row.at)), h$7("td", { style: styles.td }, h$7("span", { style: Object.assign({}, styles.pill, styles[OUTCOME_TONES[outcome]] === void 0 ? styles.muted : styles[OUTCOME_TONES[outcome]]) }, OUTCOME_LABELS[outcome] === void 0 ? outcome : OUTCOME_LABELS[outcome])), h$7("td", { style: Object.assign({}, styles.td, styles.mono) }, String(row.turnId === void 0 ? "" : row.turnId))); + }))), reporter.lastError === void 0 ? null : h$7("p", { style: styles.hint }, "最近一次错误:" + String(reporter.lastError))), h$7("p", { style: styles.hint }, "配置保存在 " + String(snapshot.settingsPath === void 0 ? "本机配置文件" : snapshot.settingsPath) + "。页面地址 /dsh-brain 仍然可用。")); } var skillsTab = null; if (tab === "skills") { @@ -3291,31 +3291,31 @@ window.__ModuleLoader__.load({ var detailBox = null; if (skills.detail !== null) { var detail = skills.detail.data; - detailBox = h$6("div", { style: styles.row }, h$6("div", { style: styles.rowHead }, h$6("span", { style: styles.rowTitle }, "详情:" + String(skills.detail.folder)), h$6(Btn, { + detailBox = h$7("div", { style: styles.row }, h$7("div", { style: styles.rowHead }, h$7("span", { style: styles.rowTitle }, "详情:" + String(skills.detail.folder)), h$7(Btn, { label: "关闭", variant: "small", onClick: function() { patchSkills({ detail: null }); } - })), detail === null ? h$6("p", { style: styles.hint }, skills.detail.error === null ? "正在读取…" : String(skills.detail.error)) : h$6("div", { style: styles.nested }, h$6("div", { style: styles.grid }, h$6(Field, { + })), detail === null ? h$7("p", { style: styles.hint }, skills.detail.error === null ? "正在读取…" : String(skills.detail.error)) : h$7("div", { style: styles.nested }, h$7("div", { style: styles.grid }, h$7(Field, { label: "目录", value: String(detail.dir), onChange: function() {} - }), h$6(Field, { + }), h$7(Field, { label: "SKILL.md 哈希", value: String(detail.skill !== void 0 ? detail.skill.skillSha256 : ""), onChange: function() {} - })), h$6("p", { style: styles.hint }, "文件:" + String(Array.isArray(detail.files) ? detail.files.length : 0) + " 个,共 " + formatBytes(detail.totalBytes) + (detail.truncated ? "(SKILL.md 过长,已截断显示)" : "")), h$6("pre", { style: styles.code }, String(detail.skillMd === void 0 ? "" : detail.skillMd)), h$6("p", { style: styles.hint }, "文件清单:" + (Array.isArray(detail.files) ? detail.files.map(function(file) { + })), h$7("p", { style: styles.hint }, "文件:" + String(Array.isArray(detail.files) ? detail.files.length : 0) + " 个,共 " + formatBytes(detail.totalBytes) + (detail.truncated ? "(SKILL.md 过长,已截断显示)" : "")), h$7("pre", { style: styles.code }, String(detail.skillMd === void 0 ? "" : detail.skillMd)), h$7("p", { style: styles.hint }, "文件清单:" + (Array.isArray(detail.files) ? detail.files.map(function(file) { return String(file.path) + (file.script ? "(脚本)" : ""); }).join("、") : "")))); } var uninstallBox = null; - if (skills.uninstall !== null) uninstallBox = h$6("div", { style: Object.assign({}, styles.row, styles.warn) }, h$6("div", { style: styles.rowHead }, h$6("span", { style: styles.rowTitle }, "卸载确认:" + String(skills.uninstall.folder))), h$6("p", { style: styles.hint }, "将实际删除:" + String(skills.uninstall.dir) + ";影响:" + String(skills.uninstall.files) + " 个文件 / " + formatBytes(skills.uninstall.bytes) + (Array.isArray(skills.uninstall.scripts) && skills.uninstall.scripts.length > 0 ? ";含脚本:" + skills.uninstall.scripts.join("、") : "")), h$6("p", { style: styles.hint }, String(skills.uninstall.note)), h$6("div", { style: styles.actions }, h$6(Btn, { + if (skills.uninstall !== null) uninstallBox = h$7("div", { style: Object.assign({}, styles.row, styles.warn) }, h$7("div", { style: styles.rowHead }, h$7("span", { style: styles.rowTitle }, "卸载确认:" + String(skills.uninstall.folder))), h$7("p", { style: styles.hint }, "将实际删除:" + String(skills.uninstall.dir) + ";影响:" + String(skills.uninstall.files) + " 个文件 / " + formatBytes(skills.uninstall.bytes) + (Array.isArray(skills.uninstall.scripts) && skills.uninstall.scripts.length > 0 ? ";含脚本:" + skills.uninstall.scripts.join("、") : "")), h$7("p", { style: styles.hint }, String(skills.uninstall.note)), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "danger", label: tree.busy === "uninstall" ? "删除中…" : "确认删除(不可恢复)", disabled: tree.busy !== "", onClick: confirmUninstall - }), h$6(Btn, { + }), h$7(Btn, { label: "取消", disabled: tree.busy !== "", onClick: function() { @@ -3325,17 +3325,17 @@ window.__ModuleLoader__.load({ var planBox = null; if (skills.plan !== null) { var candidates = Array.isArray(skills.plan.candidates) ? skills.plan.candidates : []; - planBox = h$6("div", { style: styles.row }, h$6("div", { style: styles.rowHead }, h$6("span", { style: styles.rowTitle }, "安装预览:" + String(skills.plan.url))), h$6("p", { style: styles.hint }, "计划 " + String(skills.plan.planId) + " 有效到 " + formatTime(skills.plan.expiresAt) + "。默认不勾选冲突项;只安装勾选的技能,来源中的安装脚本不会执行。"), h$6("div", { style: { + planBox = h$7("div", { style: styles.row }, h$7("div", { style: styles.rowHead }, h$7("span", { style: styles.rowTitle }, "安装预览:" + String(skills.plan.url))), h$7("p", { style: styles.hint }, "计划 " + String(skills.plan.planId) + " 有效到 " + formatTime(skills.plan.expiresAt) + "。默认不勾选冲突项;只安装勾选的技能,来源中的安装脚本不会执行。"), h$7("div", { style: { display: "flex", flexDirection: "column", gap: "6px" } }, candidates.map(function(candidate) { var selected = skills.selection.indexOf(candidate.folder) >= 0; var blocked = candidate.conflict === true || candidate.problem !== void 0; - return h$6("label", { + return h$7("label", { key: String(candidate.id), style: styles.checkboxRow - }, h$6("input", { + }, h$7("input", { type: "checkbox", checked: selected, disabled: blocked, @@ -3346,13 +3346,13 @@ window.__ModuleLoader__.load({ if (!event.target.checked && at >= 0) next.splice(at, 1); patchSkills({ selection: next }); } - }), h$6("span", { style: { minWidth: 0 } }, h$6("span", { style: { fontWeight: 600 } }, String(candidate.name)), h$6("span", { style: styles.hint }, " · " + String(candidate.folder) + " · " + String(candidate.files) + " 个文件 · " + formatBytes(candidate.bytes) + (candidate.conflict === true ? " · 已存在(" + String(candidate.conflictLocation === "holding" ? "已停用目录" : "技能目录") + "),不覆盖" : "") + (candidate.problem === void 0 ? "" : " · " + String(candidate.problem)) + (Array.isArray(candidate.scripts) && candidate.scripts.length > 0 ? " · 含脚本:" + candidate.scripts.join("、") : "")))); - })), h$6("div", { style: styles.actions }, h$6(Btn, { + }), h$7("span", { style: { minWidth: 0 } }, h$7("span", { style: { fontWeight: 600 } }, String(candidate.name)), h$7("span", { style: styles.hint }, " · " + String(candidate.folder) + " · " + String(candidate.files) + " 个文件 · " + formatBytes(candidate.bytes) + (candidate.conflict === true ? " · 已存在(" + String(candidate.conflictLocation === "holding" ? "已停用目录" : "技能目录") + "),不覆盖" : "") + (candidate.problem === void 0 ? "" : " · " + String(candidate.problem)) + (Array.isArray(candidate.scripts) && candidate.scripts.length > 0 ? " · 含脚本:" + candidate.scripts.join("、") : "")))); + })), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: tree.busy === "commit" ? "安装中…" : "安装所选(" + String(skills.selection.length) + ")", disabled: tree.busy !== "" || skills.selection.length === 0, onClick: commitInstall - }), h$6(Btn, { + }), h$7(Btn, { label: "放弃计划", variant: "small", disabled: tree.busy !== "", @@ -3400,24 +3400,24 @@ window.__ModuleLoader__.load({ }); setSelection(next); } - assignBox = h$6("div", { style: styles.row }, h$6("div", { style: styles.rowHead }, h$6("span", { style: styles.rowTitle }, "加入分类:" + String(assignGroup === void 0 ? "" : assignGroup.name)), h$6("div", { style: styles.pills }, h$6(Pill$1, { + assignBox = h$7("div", { style: styles.row }, h$7("div", { style: styles.rowHead }, h$7("span", { style: styles.rowTitle }, "加入分类:" + String(assignGroup === void 0 ? "" : assignGroup.name)), h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "可分配", value: String(assignable.length), tone: "muted" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "匹配", value: String(filteredAssignable.length), tone: filteredAssignable.length === 0 ? "muted" : "ok" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "已选", value: String(selectedCount), tone: selectedCount === 0 ? "muted" : "ok" - }))), h$6("p", { style: styles.hint }, "先搜索再勾选,或直接「全选匹配结果」一次性加入;一个技能只会属于一个分类,取消勾选即回到「未分类」。"), h$6("div", { style: { + }))), h$7("p", { style: styles.hint }, "先搜索再勾选,或直接「全选匹配结果」一次性加入;一个技能只会属于一个分类,取消勾选即回到「未分类」。"), h$7("div", { style: { display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" - } }, h$6("input", { + } }, h$7("input", { type: "search", style: Object.assign({}, styles.input, { flex: "1 1 200px", @@ -3430,41 +3430,41 @@ window.__ModuleLoader__.load({ onChange: function(event) { setSelectionFilter(event.target.value); } - }), assignSearch !== "" ? h$6(Btn, { + }), assignSearch !== "" ? h$7(Btn, { label: "清空搜索", variant: "small", onClick: function() { setSelectionFilter(""); } - }) : null), h$6("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$6(Btn, { + }) : null), h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7(Btn, { label: "全选匹配结果(" + String(filteredAssignable.length) + ")", variant: "small", disabled: tree.busy !== "" || filteredAssignable.length === 0, onClick: function() { selectMany(filteredAssignable, true); } - }), h$6(Btn, { + }), h$7(Btn, { label: "全选全部(" + String(assignable.length) + ")", variant: "small", disabled: tree.busy !== "" || assignable.length === 0 || selectedCount === assignable.length, onClick: function() { selectMany(assignable, true); } - }), h$6(Btn, { + }), h$7(Btn, { label: "取消勾选匹配项(" + String(matchedSelected) + ")", variant: "small", disabled: tree.busy !== "" || matchedSelected === 0, onClick: function() { selectMany(filteredAssignable, false); } - }), h$6(Btn, { + }), h$7(Btn, { label: "清空已选", variant: "small", disabled: tree.busy !== "" || selectedCount === 0, onClick: function() { setSelection([]); } - })), filteredAssignable.length === 0 ? h$6("p", { style: styles.hint }, assignable.length === 0 ? "当前来源还没有可分配的技能。" : "没有匹配「" + assignSearch + "」的技能。换个关键词,或点「清空搜索」看全部。") : h$6("div", { style: { + })), filteredAssignable.length === 0 ? h$7("p", { style: styles.hint }, assignable.length === 0 ? "当前来源还没有可分配的技能。" : "没有匹配「" + assignSearch + "」的技能。换个关键词,或点「清空搜索」看全部。") : h$7("div", { style: { display: "flex", flexDirection: "column", gap: "4px", @@ -3472,24 +3472,24 @@ window.__ModuleLoader__.load({ overflow: "auto" } }, filteredAssignable.map(function(skill) { var checked = tree.assign.selection.indexOf(skill.folder) >= 0; - return h$6("label", { + return h$7("label", { key: String(skill.folder), style: styles.checkboxRow - }, h$6("input", { + }, h$7("input", { type: "checkbox", checked, onChange: function(event) { selectMany([skill], event.target.checked === true); } - }), h$6("span", { style: { minWidth: 0 } }, String(skill.name) + " ", h$6("span", { style: styles.hint }, "· " + String(skill.folder) + (skill.description ? " · " + String(skill.description) : "")))); - })), h$6("div", { style: styles.actions }, h$6(Btn, { + }), h$7("span", { style: { minWidth: 0 } }, String(skill.name) + " ", h$7("span", { style: styles.hint }, "· " + String(skill.folder) + (skill.description ? " · " + String(skill.description) : "")))); + })), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: "保存分类(" + String(selectedCount) + ")", disabled: tree.busy !== "", onClick: function() { saveAssign(); } - }), h$6(Btn, { + }), h$7(Btn, { label: "取消", disabled: tree.busy !== "", onClick: function() { @@ -3499,10 +3499,10 @@ window.__ModuleLoader__.load({ } var renderSkillRow = function(source, skill) { var writable = source.writable === true; - return h$6("div", { + return h$7("div", { key: String(source.id) + ":" + String(skill.folder), style: styles.skillRow - }, h$6("div", { + }, h$7("div", { style: { display: "flex", alignItems: "baseline", @@ -3515,12 +3515,12 @@ window.__ModuleLoader__.load({ onClick: writable ? function() { openDetail(skill.folder); } : void 0 - }, h$6("span", { style: Object.assign({}, styles.rowTitle, { flex: "0 0 auto" }) }, String(skill.name)), skill.description === "" ? null : h$6("span", { style: Object.assign({}, styles.hint, styles.clamp1, { minWidth: 0 }) }, String(skill.description))), h$6("div", { style: { + }, h$7("span", { style: Object.assign({}, styles.rowTitle, { flex: "0 0 auto" }) }, String(skill.name)), skill.description === "" ? null : h$7("span", { style: Object.assign({}, styles.hint, styles.clamp1, { minWidth: 0 }) }, String(skill.description))), h$7("div", { style: { display: "flex", alignItems: "center", gap: "6px", flex: "0 0 auto" - } }, skill.enabledEditable !== true ? h$6("span", { style: styles.hint }, "只读") : null, writable ? h$6(IconBtn, { + } }, skill.enabledEditable !== true ? h$7("span", { style: styles.hint }, "只读") : null, writable ? h$7(IconBtn, { glyph: "🗑", danger: true, ariaLabel: "卸载 " + String(skill.name), @@ -3528,7 +3528,7 @@ window.__ModuleLoader__.load({ onClick: function() { planUninstall(skill.folder); } - }) : null, skill.enabledEditable !== true ? null : h$6(Toggle, { + }) : null, skill.enabledEditable !== true ? null : h$7(Toggle, { checked: skill.enabled === true, disabled: tree.busy !== "", label: "技能 " + String(skill.name) + " 启停", @@ -3544,52 +3544,52 @@ window.__ModuleLoader__.load({ var confirming = tree.confirm === renameKey; var assigning = tree.assign !== null && tree.assign.sourceId === source.id && tree.assign.groupId === group.id; var groupSkills = group.visible === void 0 ? group.skills || [] : group.visible; - return h$6("div", { + return h$7("div", { key: renameKey, style: styles.groupRow - }, h$6("div", { style: styles.rowHead }, h$6("div", { style: { + }, h$7("div", { style: styles.rowHead }, h$7("div", { style: { display: "flex", alignItems: "center", gap: "6px", minWidth: 0, flexWrap: "wrap" - } }, h$6(Btn, { + } }, h$7(Btn, { label: open ? "▾" : "▸", variant: "small", ariaLabel: "展开或收起 " + String(group.name), onClick: function() { patchTree({ openGroups: Object.assign({}, tree.openGroups, { [renameKey]: !open }) }); } - }), h$6("span", { style: styles.folderGlyph }, "📁"), renaming ? h$6("input", { + }), h$7("span", { style: styles.folderGlyph }, "📁"), renaming ? h$7("input", { style: Object.assign({}, styles.input, { width: "160px" }), value: tree.edit.value, autoFocus: true, onChange: function(event) { patchTree({ edit: Object.assign({}, tree.edit, { value: event.target.value }) }); } - }) : h$6("span", { style: styles.rowTitle }, String(group.name)), h$6("span", { style: styles.hint }, String(group.total) + " 项 · " + String(group.enabledCount) + "/" + String(group.total) + " 启用"), group.cardOnly === true ? h$6(Pill$1, { + }) : h$7("span", { style: styles.rowTitle }, String(group.name)), h$7("span", { style: styles.hint }, String(group.total) + " 项 · " + String(group.enabledCount) + "/" + String(group.total) + " 启用"), group.cardOnly === true ? h$7(Pill$1, { label: "开关", value: "仅本卡", tone: "muted" - }) : null), h$6("div", { style: styles.actions }, renaming ? h$6(Btn, { + }) : null), h$7("div", { style: styles.actions }, renaming ? h$7(Btn, { label: "保存", variant: "small", disabled: tree.busy !== "", onClick: saveRename - }) : h$6(IconBtn, { + }) : h$7(IconBtn, { glyph: "+", ariaLabel: "把技能加入 " + String(group.name), disabled: tree.busy !== "" || group.id === "unassigned", onClick: function() { openAssign(source, group); } - }), renaming ? h$6(Btn, { + }), renaming ? h$7(Btn, { label: "取消", variant: "small", onClick: function() { patchTree({ edit: null }); } - }) : h$6(IconBtn, { + }) : h$7(IconBtn, { glyph: "✎", ariaLabel: "重命名 " + String(group.name), disabled: tree.busy !== "" || group.id === "unassigned", @@ -3602,14 +3602,14 @@ window.__ModuleLoader__.load({ value: String(group.name) } }); } - }), confirming ? h$6(Btn, { + }), confirming ? h$7(Btn, { label: "确认删除分类", variant: "danger", disabled: tree.busy !== "", onClick: function() { deleteGroup(source.id, group.id); } - }) : h$6(IconBtn, { + }) : h$7(IconBtn, { glyph: "🗑", danger: true, ariaLabel: "删除分类 " + String(group.name) + "(技能回到未分类)", @@ -3621,45 +3621,45 @@ window.__ModuleLoader__.load({ text: "删除分类只删除分组记录,里面的技能会回到「未分类」,文件不会被删除。再点一次确认。" }); } - }), group.enabledEditable === false ? null : h$6(Toggle, { + }), group.enabledEditable === false ? null : h$7(Toggle, { checked: group.enabled !== false, disabled: tree.busy !== "", label: "分类 " + String(group.name) + " 启停", onChange: function() { toggleGroup(source.id, group.id, group.enabled === false); } - }))), assigning ? h$6("div", { style: styles.nested }, assignBox) : null, open ? h$6("div", { style: styles.nested }, groupSkills.length === 0 ? assigning ? null : h$6("p", { style: styles.hint }, group.id === "unassigned" ? "没有未分类的技能。" : "这个分类还没有技能,点「+」加入。") : groupSkills.map(function(skill) { + }))), assigning ? h$7("div", { style: styles.nested }, assignBox) : null, open ? h$7("div", { style: styles.nested }, groupSkills.length === 0 ? assigning ? null : h$7("p", { style: styles.hint }, group.id === "unassigned" ? "没有未分类的技能。" : "这个分类还没有技能,点「+」加入。") : groupSkills.map(function(skill) { return renderSkillRow(source, skill); })) : null); }; var dshSource = treeSources.find(function(src) { return src.writable === true; }); - skillsTab = h$6("div", { + skillsTab = h$7("div", { style: styles.root, key: "skills" - }, h$6(ImportSection, { onImported: function() { + }, h$7(ImportSection, { onImported: function() { loadTree(); loadSkills(); - } }), h$6(Section, { + } }), h$7(Section, { title: "技能文件夹", hint: "按软件来源分组;展开来源与分类查看技能。" - }, dshSource === void 0 ? null : h$6("div", { style: styles.statsBar }, h$6("span", { style: styles.stat }, h$6("span", { style: styles.statNum }, String(dshSource.total || 0)), h$6("span", { style: styles.hint }, "个技能")), h$6("span", { style: styles.stat }, h$6("span", { style: styles.statNum }, String(dshSource.enabledCount || 0)), h$6("span", { style: styles.hint }, "个已启用")), h$6("span", { style: styles.statLast }, h$6("span", { style: styles.statNum }, String((dshSource.total || 0) - (dshSource.enabledCount || 0))), h$6("span", { style: styles.hint }, "个已停用"))), h$6("div", { style: { + }, dshSource === void 0 ? null : h$7("div", { style: styles.statsBar }, h$7("span", { style: styles.stat }, h$7("span", { style: styles.statNum }, String(dshSource.total || 0)), h$7("span", { style: styles.hint }, "个技能")), h$7("span", { style: styles.stat }, h$7("span", { style: styles.statNum }, String(dshSource.enabledCount || 0)), h$7("span", { style: styles.hint }, "个已启用")), h$7("span", { style: styles.statLast }, h$7("span", { style: styles.statNum }, String((dshSource.total || 0) - (dshSource.enabledCount || 0))), h$7("span", { style: styles.hint }, "个已停用"))), h$7("div", { style: { display: "flex", gap: "8px", alignItems: "flex-end", flexWrap: "wrap" - } }, h$6("div", { style: { + } }, h$7("div", { style: { flex: "1 1 220px", minWidth: 0 - } }, h$6(Field, { + } }, h$7(Field, { label: "搜索", value: skills.search, placeholder: "按名称、目录或描述筛选", onChange: function(value) { patchSkills({ search: value }); } - })), h$6(Btn, { + })), h$7(Btn, { label: tree.status === "loading" ? "刷新中…" : "刷新", variant: "small", disabled: tree.status === "loading", @@ -3667,18 +3667,18 @@ window.__ModuleLoader__.load({ loadTree(); loadSkills(); } - })), tree.error === null ? null : h$6(Banner, { tone: "bad" }, tree.error), tree.status === "loading" && tree.data === null ? h$6("p", { style: styles.hint }, "正在读取技能来源…") : null, tree.status === "ready" && treeSources.length === 0 ? h$6("p", { style: styles.hint }, "没有探测到任何技能来源。") : null, dshSource === void 0 ? null : h$6("div", { style: { + })), tree.error === null ? null : h$7(Banner, { tone: "bad" }, tree.error), tree.status === "loading" && tree.data === null ? h$7("p", { style: styles.hint }, "正在读取技能来源…") : null, tree.status === "ready" && treeSources.length === 0 ? h$7("p", { style: styles.hint }, "没有探测到任何技能来源。") : null, dshSource === void 0 ? null : h$7("div", { style: { display: "flex", flexDirection: "column", gap: "2px" } }, visibleGroupsOf(dshSource).map(function(group) { return renderGroup(dshSource, group); - }), tree.edit !== null && tree.edit.kind === "create" && tree.edit.sourceId === dshSource.id ? h$6("div", { style: Object.assign({}, styles.row, { + }), tree.edit !== null && tree.edit.kind === "create" && tree.edit.sourceId === dshSource.id ? h$7("div", { style: Object.assign({}, styles.row, { flexDirection: "row", alignItems: "center", flexWrap: "wrap", marginTop: "6px" - }) }, h$6("input", { + }) }, h$7("input", { style: Object.assign({}, styles.input, { width: "180px" }), placeholder: "分类名称,例如 QQ-Skill", value: tree.edit.value, @@ -3686,17 +3686,17 @@ window.__ModuleLoader__.load({ onChange: function(event) { patchTree({ edit: Object.assign({}, tree.edit, { value: event.target.value }) }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "创建分类", variant: "primary", disabled: tree.busy !== "", onClick: createGroup - }), h$6(Btn, { + }), h$7(Btn, { label: "取消", onClick: function() { patchTree({ edit: null }); } - })) : h$6("div", { style: { marginTop: "6px" } }, h$6(Btn, { + })) : h$7("div", { style: { marginTop: "6px" } }, h$7(Btn, { label: "+ 新建分类", variant: "small", disabled: tree.busy !== "", @@ -3707,28 +3707,28 @@ window.__ModuleLoader__.load({ value: "" } }); } - }))), tree.data !== null && tree.data.note !== void 0 ? h$6("p", { style: styles.hint }, String(tree.data.note)) : null), detailBox, uninstallBox, h$6(Section, { + }))), tree.data !== null && tree.data.note !== void 0 ? h$7("p", { style: styles.hint }, String(tree.data.note)) : null), detailBox, uninstallBox, h$7(Section, { title: "从 Git 仓库安装", hint: "先克隆到隔离暂存目录并列出候选技能,确认后才写入 DSH 技能目录;不执行仓库里的任何脚本,符号链接不会跟随。仓库地址只接受 https:// 或 file://。" - }, h$6("div", { style: styles.grid }, h$6(Field, { + }, h$7("div", { style: styles.grid }, h$7(Field, { label: "仓库地址", value: skills.installUrl, placeholder: "https://github.com//.git", onChange: function(value) { patchSkills({ installUrl: value }); } - })), h$6("div", { style: styles.actions }, h$6(Btn, { + })), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: skills.busy === "plan" ? "拉取中…" : "拉取并预览", disabled: skills.busy !== "", onClick: prepareInstall - })), planBox), h$6(MarketSection, { + })), planBox), h$7(MarketSection, { capabilities: caps, onInstalled: function() { loadTree(); loadSkills(); } - }), h$6(SyncResolveSection, { onResolved: function() { + }), h$7(SyncResolveSection, { onResolved: function() { loadSkills(); } })); } @@ -3783,49 +3783,49 @@ window.__ModuleLoader__.load({ return mcpChosen.indexOf(item.key) >= 0; }).length; var bridgeBox = null; - if (mcp.status === "missing") bridgeBox = h$6(Banner, { tone: "warn" }, "MCP 管理当前不可用:没有探测到宿主 dsh-mcp-connector 的公开接口(" + MCP_BRIDGE + ")。" + (mcp.error === null ? "" : "原因:" + String(mcp.error)) + "。自定义 MCP Server 的权威位置仍是「设置 → 插件配置 → MCP 服务器配置」,本卡不会修改它的托管配置。"); - mcpTab = h$6("div", { + if (mcp.status === "missing") bridgeBox = h$7(Banner, { tone: "warn" }, "MCP 管理当前不可用:没有探测到宿主 dsh-mcp-connector 的公开接口(" + MCP_BRIDGE + ")。" + (mcp.error === null ? "" : "原因:" + String(mcp.error)) + "。自定义 MCP Server 的权威位置仍是「设置 → 插件配置 → MCP 服务器配置」,本卡不会修改它的托管配置。"); + mcpTab = h$7("div", { style: styles.root, key: "mcp" - }, h$6(Section, { + }, h$7(Section, { title: "我的连接", hint: "数据来自宿主 dsh-mcp-connector 插件(同一 origin 的公开接口);本卡不保存任何 MCP 凭据,也不回显启动命令与密钥。", - aside: h$6(Btn, { + aside: h$7(Btn, { label: mcp.status === "probe" ? "探测中…" : "重新探测", variant: "small", disabled: mcp.busy !== "", onClick: probeMcp }) - }, bridgeBox, mcp.status === "ok" && items.length === 0 ? h$6("p", { style: styles.hint }, "宿主还没有登记任何 MCP 连接。") : null, mcp.status === "ok" && items.length > 0 ? h$6("div", { style: { + }, bridgeBox, mcp.status === "ok" && items.length === 0 ? h$7("p", { style: styles.hint }, "宿主还没有登记任何 MCP 连接。") : null, mcp.status === "ok" && items.length > 0 ? h$7("div", { style: { display: "flex", flexDirection: "column", gap: "8px" - } }, h$6("div", { style: styles.pills }, h$6(Pill$1, { + } }, h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "共", value: String(items.length), tone: "muted" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "匹配", value: String(visibleItems.length), tone: visibleItems.length === 0 ? "muted" : "ok" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "已选", value: String(mcpChosen.length), tone: mcpChosen.length === 0 ? "muted" : "ok" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "已连接", value: String(mcpCounts.connected), tone: "ok" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "异常", value: String(mcpCounts.problem), tone: mcpCounts.problem === 0 ? "muted" : "warn" - })), h$6("div", { style: { + })), h$7("div", { style: { display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" - } }, h$6("input", { + } }, h$7("input", { type: "search", style: Object.assign({}, styles.input, { flex: "1 1 220px", @@ -3837,37 +3837,37 @@ window.__ModuleLoader__.load({ onChange: function(event) { patchMcp({ search: event.target.value }); } - }), mcpSearch !== "" ? h$6(Btn, { + }), mcpSearch !== "" ? h$7(Btn, { label: "清空搜索", variant: "small", onClick: function() { patchMcp({ search: "" }); } - }) : null), h$6("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$6(Btn, { + }) : null), h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7(Btn, { label: "筛选:全部(" + String(items.length) + ")", variant: mcpFilter === "all" ? "primary" : "small", onClick: function() { patchMcp({ filter: "all" }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "已连接(" + String(mcpCounts.connected) + ")", variant: mcpFilter === "connected" ? "primary" : "small", onClick: function() { patchMcp({ filter: "connected" }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "已停用(" + String(mcpCounts.disabled) + ")", variant: mcpFilter === "disabled" ? "primary" : "small", onClick: function() { patchMcp({ filter: "disabled" }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "异常(" + String(mcpCounts.problem) + ")", variant: mcpFilter === "problem" ? "primary" : "small", onClick: function() { patchMcp({ filter: "problem" }); } - })), h$6("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$6(Btn, { + })), h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7(Btn, { label: "全选匹配结果(" + String(visibleItems.length) + ")", ariaLabel: "全选匹配结果", variant: "small", @@ -3875,7 +3875,7 @@ window.__ModuleLoader__.load({ onClick: function() { selectMcpMany(visibleItems, true); } - }), h$6(Btn, { + }), h$7(Btn, { label: "全选全部(" + String(items.length) + ")", ariaLabel: "全选全部", variant: "small", @@ -3883,7 +3883,7 @@ window.__ModuleLoader__.load({ onClick: function() { selectMcpMany(items, true); } - }), h$6(Btn, { + }), h$7(Btn, { label: "取消勾选匹配项(" + String(matchedSelected) + ")", ariaLabel: "取消勾选匹配项", variant: "small", @@ -3891,7 +3891,7 @@ window.__ModuleLoader__.load({ onClick: function() { selectMcpMany(visibleItems, false); } - }), h$6(Btn, { + }), h$7(Btn, { label: "清空已选", ariaLabel: "清空已选", variant: "small", @@ -3902,7 +3902,7 @@ window.__ModuleLoader__.load({ confirmBulk: false }); } - })), mcpChosen.length === 0 ? h$6("p", { style: styles.hint }, "勾选左侧连接后,这里会出现批量健康检查、启停、重连与移除。") : h$6("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$6("span", { style: styles.hint }, "批量操作(已选 " + String(mcpChosen.length) + "):"), h$6(Btn, { + })), mcpChosen.length === 0 ? h$7("p", { style: styles.hint }, "勾选左侧连接后,这里会出现批量健康检查、启停、重连与移除。") : h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7("span", { style: styles.hint }, "批量操作(已选 " + String(mcpChosen.length) + "):"), h$7(Btn, { label: "健康检查", ariaLabel: "批量健康检查", variant: "small", @@ -3912,7 +3912,7 @@ window.__ModuleLoader__.load({ return { connectorId: item.connectorId }; }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "启用", ariaLabel: "批量启用", variant: "small", @@ -3925,7 +3925,7 @@ window.__ModuleLoader__.load({ }; }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "停用", ariaLabel: "批量停用", variant: "small", @@ -3938,7 +3938,7 @@ window.__ModuleLoader__.load({ }; }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "重连", ariaLabel: "批量重连", variant: "small", @@ -3948,7 +3948,7 @@ window.__ModuleLoader__.load({ return { key: item.key }; }); } - }), mcp.confirmBulk === true ? h$6(Btn, { + }), mcp.confirmBulk === true ? h$7(Btn, { label: "确认移除(" + String(mcpChosen.length) + ")", ariaLabel: "确认批量移除", variant: "danger", @@ -3958,7 +3958,7 @@ window.__ModuleLoader__.load({ return { key: item.key }; }); } - }) : h$6(Btn, { + }) : h$7(Btn, { label: "移除…", ariaLabel: "批量移除", variant: "small", @@ -3970,64 +3970,64 @@ window.__ModuleLoader__.load({ text: "批量移除会断开所选 " + String(mcpChosen.length) + " 条连接定义;再点一次「确认移除」才执行。" }); } - })), mcpBulk === null ? null : h$6("p", { style: styles.hint }, String(mcpBulk.label) + " 进行中:" + String(mcpBulk.done) + " / " + String(mcpBulk.total)), visibleItems.length === 0 ? h$6("p", { style: styles.hint }, "没有匹配「" + mcpSearch + "」的连接。换个关键词或切回「全部」筛选。") : null, visibleItems.map(function(item) { + })), mcpBulk === null ? null : h$7("p", { style: styles.hint }, String(mcpBulk.label) + " 进行中:" + String(mcpBulk.done) + " / " + String(mcpBulk.total)), visibleItems.length === 0 ? h$7("p", { style: styles.hint }, "没有匹配「" + mcpSearch + "」的连接。换个关键词或切回「全部」筛选。") : null, visibleItems.map(function(item) { var state = stateOf(item); var tools = mcp.tools[item.key]; var details = mcp.details === null || mcp.details === void 0 ? {} : mcp.details; var open = details[item.key] === true; var label = String(item.name === void 0 ? item.key : item.name); - return h$6("div", { + return h$7("div", { key: String(item.key), style: styles.row - }, h$6("div", { style: styles.rowHead }, h$6("label", { style: { + }, h$7("div", { style: styles.rowHead }, h$7("label", { style: { display: "inline-flex", alignItems: "center", gap: "8px", minWidth: 0, flex: "1 1 auto" - } }, h$6("input", { + } }, h$7("input", { type: "checkbox", checked: mcpChosen.indexOf(item.key) >= 0, "aria-label": "选择连接 " + label, onChange: function(event) { selectMcpMany([item], event.target.checked === true); } - }), h$6("span", { style: styles.rowTitle }, label), h$6(Pill$1, { + }), h$7("span", { style: styles.rowTitle }, label), h$7(Pill$1, { label: "状态", value: MCP_STATE_LABELS[state] === void 0 ? state : MCP_STATE_LABELS[state], tone: state === "connected" ? "ok" : state === "disabled" ? "muted" : "warn" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "传输", value: String(item.transport === void 0 ? "—" : item.transport), tone: "muted" - })), h$6(Btn, { + })), h$7(Btn, { label: open ? "收起" : "详情", ariaLabel: (open ? "收起详情 " : "详情 ") + label, variant: "small", onClick: function() { patchMcp({ details: Object.assign({}, details, { [String(item.key)]: !open }) }); } - })), open ? h$6("div", { style: { + })), open ? h$7("div", { style: { display: "flex", flexDirection: "column", gap: "6px" - } }, h$6("div", { style: styles.pills }, h$6(Pill$1, { + } }, h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "鉴权", value: String(item.authMode === void 0 ? "none" : item.authMode), tone: "muted" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "注入", value: String(item.injectionLabel === void 0 ? "—" : item.injectionLabel), tone: "muted" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "范围", value: item.scope === void 0 || item.scope === null ? "未知" : String(item.scope.visibility === void 0 ? JSON.stringify(item.scope) : item.scope.visibility), tone: "muted" - }), h$6(Pill$1, { + }), h$7(Pill$1, { label: "健康检查", value: formatIso(item.healthCheckedAt), tone: "muted" - })), item.lastError === null || item.lastError === void 0 ? null : h$6("p", { style: styles.hint }, "最近错误:" + String(item.lastError)), h$6("div", { style: styles.actions }, h$6(Btn, { + })), item.lastError === null || item.lastError === void 0 ? null : h$7("p", { style: styles.hint }, "最近错误:" + String(item.lastError)), h$7("div", { style: styles.actions }, h$7(Btn, { label: "健康检查", ariaLabel: "健康检查 " + label, variant: "small", @@ -4037,7 +4037,7 @@ window.__ModuleLoader__.load({ probeMcp(); }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "工具列表", ariaLabel: "工具列表 " + label, variant: "small", @@ -4045,7 +4045,7 @@ window.__ModuleLoader__.load({ onClick: function() { loadTools(item); } - }), h$6(Btn, { + }), h$7(Btn, { label: item.enabled === false ? "启用" : "停用", ariaLabel: "启停 " + label, variant: "small", @@ -4058,7 +4058,7 @@ window.__ModuleLoader__.load({ probeMcp(); }); } - }), h$6(Btn, { + }), h$7(Btn, { label: "重连", ariaLabel: "重连 " + label, variant: "small", @@ -4068,7 +4068,7 @@ window.__ModuleLoader__.load({ probeMcp(); }); } - }), mcp.confirm === item.key ? h$6(Btn, { + }), mcp.confirm === item.key ? h$7(Btn, { label: "确认移除", ariaLabel: "确认移除 " + label, variant: "danger", @@ -4079,7 +4079,7 @@ window.__ModuleLoader__.load({ probeMcp(); }); } - }) : h$6(Btn, { + }) : h$7(Btn, { label: "移除连接…", ariaLabel: "移除连接 " + label, variant: "small", @@ -4091,15 +4091,15 @@ window.__ModuleLoader__.load({ text: "再次点击「确认移除」才会断开该连接定义。" }); } - })), tools === void 0 ? null : h$6("p", { style: styles.hint }, "工具缓存(" + formatTime(tools.at) + "):" + (tools.items.length === 0 ? "空" : tools.items.map(function(tool) { + })), tools === void 0 ? null : h$7("p", { style: styles.hint }, "工具缓存(" + formatTime(tools.at) + "):" + (tools.items.length === 0 ? "空" : tools.items.map(function(tool) { return String(tool.name === void 0 ? tool : tool.name); }).join("、")))) : null); - }), h$6("p", { style: styles.hint }, "工具可见不等于业务可调用:连接状态与工具缓存分开显示。")) : null), h$6(McpCustomSection, { onChanged: probeMcp }), h$6(McpConfigSection, { + }), h$7("p", { style: styles.hint }, "工具可见不等于业务可调用:连接状态与工具缓存分开显示。")) : null), h$7(McpCustomSection, { onChanged: probeMcp }), h$7(McpConfigSection, { items, onChanged: probeMcp })); } - return h$6("div", { style: styles.root }, header, tabBar, noticeBox, error === null ? null : h$6(Banner, { tone: "bad" }, error), tab === "connection" ? connectionTab : tab === "skills" ? skillsTab : mcpTab); + return h$7("div", { style: styles.root }, header, tabBar, noticeBox, error === null ? null : h$7(Banner, { tone: "bad" }, error), tab === "connection" ? connectionTab : tab === "skills" ? skillsTab : mcpTab); } // src-client/panel/brain-icon.tsx const BRAIN_ICON_PATHS = [ @@ -4109,9 +4109,9 @@ window.__ModuleLoader__.load({ "M2.4 9.6C3.2 10 4.4 9.7 4.8 8.8M13.6 9.6C12.8 10 11.6 9.7 11.2 8.8", "M4.5 12.2C4.4 11.2 4.9 10.5 5.7 10.2M11.5 12.2C11.6 11.2 11.1 10.5 10.3 10.2" ]; - const h$5 = react.createElement; + const h$6 = react.createElement; function BrainIcon({ size = 18, ...marker }) { - return h$5("svg", { + return h$6("svg", { ...marker, "data-dsh-panel-entry": "dsh-brain", "data-dsh-plugin": "dsh-brain", @@ -4125,7 +4125,7 @@ window.__ModuleLoader__.load({ strokeWidth: "1", strokeLinecap: "round", strokeLinejoin: "round" - }, BRAIN_ICON_PATHS.map((path) => h$5("path", { + }, BRAIN_ICON_PATHS.map((path) => h$6("path", { key: path, d: path }))); @@ -4176,7 +4176,7 @@ window.__ModuleLoader__.load({ "statNum": "dshbrain_d75ahw" }; // src-client/panel/Overview.tsx - const h$4 = react.createElement; + const h$5 = react.createElement; const BUNDLE_LABELS = { cloudsync: "云同步", memory: "记忆", @@ -4187,10 +4187,10 @@ window.__ModuleLoader__.load({ }; function Pill(props) { const tone = props.tone === void 0 ? BrainPanel_module_css_default.muted : props.tone === "ok" ? BrainPanel_module_css_default.ok : props.tone === "bad" ? BrainPanel_module_css_default.bad : props.tone === "warn" ? BrainPanel_module_css_default.warn : BrainPanel_module_css_default.muted; - return h$4("span", { className: BrainPanel_module_css_default.pill + " " + tone }, h$4("span", { className: BrainPanel_module_css_default.pillLabel }, props.label), h$4("span", { className: BrainPanel_module_css_default.pillValue }, String(props.value))); + return h$5("span", { className: BrainPanel_module_css_default.pill + " " + tone }, h$5("span", { className: BrainPanel_module_css_default.pillLabel }, props.label), h$5("span", { className: BrainPanel_module_css_default.pillValue }, String(props.value))); } function Card(props) { - return h$4("div", { className: BrainPanel_module_css_default.card }, h$4("div", { className: BrainPanel_module_css_default.cardHead }, h$4("h4", { className: BrainPanel_module_css_default.cardTitle }, props.title)), props.children); + return h$5("div", { className: BrainPanel_module_css_default.card }, h$5("div", { className: BrainPanel_module_css_default.cardHead }, h$5("h4", { className: BrainPanel_module_css_default.cardTitle }, props.title)), props.children); } function Overview(props) { const active = props.active !== false; @@ -4242,43 +4242,45 @@ window.__ModuleLoader__.load({ const skills = status?.skills ?? {}; const memorySpaces = memory?.spaces ?? {}; const version = capabilities?.version ?? status?.capabilities?.version ?? "—"; - return h$4("div", { className: BrainPanel_module_css_default.overviewGrid }, error === null ? null : h$4("div", { className: BrainPanel_module_css_default.error }, error), h$4(Card, { title: "版本与构建" }, h$4("div", { className: BrainPanel_module_css_default.pills }, h$4(Pill, { + const lastChecks = Array.isArray(status?.lastCheck?.checks) ? status.lastCheck.checks : []; + const lastFailed = lastChecks.filter((check) => check.state !== "ok" && check.state !== "unconfigured").length; + return h$5("div", { className: BrainPanel_module_css_default.overviewGrid }, error === null ? null : h$5("div", { className: BrainPanel_module_css_default.error }, error), h$5(Card, { title: "版本与构建" }, h$5("div", { className: BrainPanel_module_css_default.pills }, h$5(Pill, { label: "版本", value: version - }), h$4(Pill, { + }), h$5(Pill, { label: "服务", value: settings.baseUrlConfigured === false ? "未配置" : settings.baseUrlOrigin || "已配置", tone: settings.baseUrlConfigured === false ? "warn" : "muted" - }), h$4(Pill, { + }), h$5(Pill, { label: "上报", value: settings.activityEnabled === true ? "开" : "关", tone: settings.activityEnabled === true ? "ok" : "muted" - }), h$4(Pill, { + }), h$5(Pill, { label: "记忆", value: settings.memoryEnabled === true ? "开" : "关", tone: settings.memoryEnabled === true ? "ok" : "muted" - }), h$4(Pill, { + }), h$5(Pill, { label: "诊断日志", value: settings.diagnosticsEnabled === false ? "关" : "开", tone: settings.diagnosticsEnabled === false ? "muted" : "ok" - })), h$4("p", { className: BrainPanel_module_css_default.hint }, "全局诊断日志:$DSH_HOME/brain/logs"), status?.lastCheck === null || status?.lastCheck === void 0 ? null : h$4("p", { className: BrainPanel_module_css_default.hint }, "最近检查:" + formatTime(status.lastCheck.at) + " · " + String(status.lastCheck.status ?? ""))), h$4(Card, { title: "五个 bundle 开关态" }, h$4("div", { className: BrainPanel_module_css_default.pills }, bundleKeys.map((key) => h$4(Pill, { + })), h$5("p", { className: BrainPanel_module_css_default.hint }, "全局诊断日志:$DSH_HOME/brain/logs"), status?.lastCheck === null || status?.lastCheck === void 0 ? null : h$5("p", { className: BrainPanel_module_css_default.hint }, "最近检查:" + formatTime(status.lastCheck.at) + (lastChecks.length === 0 ? "" : lastFailed === 0 ? " · 全部通过" : " · " + String(lastFailed) + " 项异常"))), h$5(Card, { title: "五个 bundle 开关态" }, h$5("div", { className: BrainPanel_module_css_default.pills }, bundleKeys.map((key) => h$5(Pill, { key, label: BUNDLE_LABELS[key] ?? key, value: bundles[key] === true ? "启用" : bundles[key] === false ? "停用" : "未知", tone: bundles[key] === true ? "ok" : bundles[key] === false ? "bad" : "muted" - })))), h$4(Card, { title: "本地记忆" }, h$4("div", { className: BrainPanel_module_css_default.pills }, h$4(Pill, { + })))), h$5(Card, { title: "本地记忆" }, h$5("div", { className: BrainPanel_module_css_default.pills }, h$5(Pill, { label: "状态", value: memory === null ? "不可用" : "已启用", tone: memory === null ? "warn" : "ok" - }), h$4(Pill, { + }), h$5(Pill, { label: "全局空间", value: memorySpaces.global === null || memorySpaces.global === void 0 ? "未创建" : "就绪", tone: memorySpaces.global === null || memorySpaces.global === void 0 ? "muted" : "ok" - }), h$4(Pill, { + }), h$5(Pill, { label: "云同步", value: memory?.cloudSyncEnabled === true ? "开" : "关", tone: memory?.cloudSyncEnabled === true ? "ok" : "muted" - })), memory === null ? h$4("p", { className: BrainPanel_module_css_default.hint }, "本地记忆状态路由不可用;启用「本地记忆」后此处会显示空间状态。") : null), h$4(Card, { title: "同步统计" }, h$4("div", { className: BrainPanel_module_css_default.statRow }, h$4("span", { className: BrainPanel_module_css_default.stat }, h$4("span", { className: BrainPanel_module_css_default.statNum }, String(reporter.reportedTurns ?? 0)), h$4("span", { className: BrainPanel_module_css_default.hint }, "已上报回合")), h$4("span", { className: BrainPanel_module_css_default.stat }, h$4("span", { className: BrainPanel_module_css_default.statNum }, String(skills.downloaded?.length ?? 0)), h$4("span", { className: BrainPanel_module_css_default.hint }, "技能下载")), h$4("span", { className: BrainPanel_module_css_default.stat }, h$4("span", { className: BrainPanel_module_css_default.statNum }, String(skills.uploaded?.length ?? 0)), h$4("span", { className: BrainPanel_module_css_default.hint }, "技能上传")), h$4("span", { className: BrainPanel_module_css_default.statLast }, h$4("span", { className: BrainPanel_module_css_default.statNum }, String(skills.conflicts?.length ?? 0)), h$4("span", { className: BrainPanel_module_css_default.hint }, "待处理冲突"))))); + })), memory === null ? h$5("p", { className: BrainPanel_module_css_default.hint }, "本地记忆状态路由不可用;启用「本地记忆」后此处会显示空间状态。") : null), h$5(Card, { title: "同步统计" }, h$5("div", { className: BrainPanel_module_css_default.statRow }, h$5("span", { className: BrainPanel_module_css_default.stat }, h$5("span", { className: BrainPanel_module_css_default.statNum }, String(reporter.recorded ?? 0)), h$5("span", { className: BrainPanel_module_css_default.hint }, "已上报回合")), h$5("span", { className: BrainPanel_module_css_default.stat }, h$5("span", { className: BrainPanel_module_css_default.statNum }, String(skills.downloaded?.length ?? 0)), h$5("span", { className: BrainPanel_module_css_default.hint }, "技能下载")), h$5("span", { className: BrainPanel_module_css_default.stat }, h$5("span", { className: BrainPanel_module_css_default.statNum }, String(skills.uploaded?.length ?? 0)), h$5("span", { className: BrainPanel_module_css_default.hint }, "技能上传")), h$5("span", { className: BrainPanel_module_css_default.statLast }, h$5("span", { className: BrainPanel_module_css_default.statNum }, String(skills.conflicts?.length ?? 0)), h$5("span", { className: BrainPanel_module_css_default.hint }, "待处理冲突"))))); } // src-client/panel/useApi.ts function useApi(loader, options = {}) { @@ -4337,7 +4339,7 @@ window.__ModuleLoader__.load({ return params; } // src-client/panel/MemoryTab.tsx - const h$3 = react.createElement; + const h$4 = react.createElement; const PAGE_SIZE = 50; function MemoryTab(props) { const active = props.active !== false; @@ -4413,13 +4415,13 @@ window.__ModuleLoader__.load({ }; const space = status.data?.spaces?.[props.scope]; const root = project ? status.data?.projectRoot : status.data?.globalRoot; - return h$3("div", { style: { + return h$4("div", { style: { display: "flex", flexDirection: "column", gap: "12px" - } }, status.error === null ? null : h$3(Banner, { tone: "bad" }, status.error), h$3(Section, { + } }, status.error === null ? null : h$4(Banner, { tone: "bad" }, status.error), h$4(Section, { title: scopeLabel + "记忆空间", - aside: h$3(Btn, { + aside: h$4(Btn, { label: "刷新", variant: "small", onClick: () => { @@ -4428,93 +4430,570 @@ window.__ModuleLoader__.load({ if (project) documents.reload(); } }) - }, h$3(Pill$1, { + }, h$4(Pill$1, { label: "空间状态", value: status.status === "loading" ? "读取中" : space?.name ?? (space ? "就绪" : "未创建"), tone: space ? "ok" : "muted" - }), root === void 0 ? null : h$3("p", { style: styles.hint }, String(root))), h$3(Section, { + }), root === void 0 ? null : h$4("p", { style: styles.hint }, String(root))), h$4(Section, { title: "记忆条目(" + String(total) + ")", hint: "只显示当前页;搜索只在当前页内过滤。删除需要二次确认并带 revision 校验。", - aside: h$3("div", { style: styles.actions }, h$3(Field, { + aside: h$4("div", { style: styles.actions }, h$4(Field, { label: "搜索当前页", value: search, onChange: setSearch - }), h$3(Btn, { + }), h$4(Btn, { label: "刷新", variant: "small", onClick: () => memories.reload() })) - }, notice === null ? null : h$3(Banner, { tone: notice.tone }, notice.text), memories.error === null ? null : h$3(Banner, { tone: "bad" }, memories.error), memories.status === "loading" && items.length === 0 ? h$3("p", { style: styles.hint }, "正在读取记忆…") : null, filtered.length === 0 ? h$3("p", { style: styles.hint }, "当前页没有匹配的记忆条目。") : h$3("div", { style: { + }, notice === null ? null : h$4(Banner, { tone: notice.tone }, notice.text), memories.error === null ? null : h$4(Banner, { tone: "bad" }, memories.error), memories.status === "loading" && items.length === 0 ? h$4("p", { style: styles.hint }, "正在读取记忆…") : null, filtered.length === 0 ? h$4("p", { style: styles.hint }, "当前页没有匹配的记忆条目。") : h$4("div", { style: { display: "flex", flexDirection: "column", gap: "8px" - } }, filtered.map((item) => h$3("div", { + } }, filtered.map((item) => h$4("div", { key: item.id, style: styles.row - }, h$3("div", { style: styles.rowHead }, h$3("div", { style: styles.pills }, h$3(Pill$1, { + }, h$4("div", { style: styles.rowHead }, h$4("div", { style: styles.pills }, h$4(Pill$1, { label: "scope", value: item.scope ?? "—", tone: "muted" - }), item.category === void 0 ? null : h$3(Pill$1, { + }), item.category === void 0 ? null : h$4(Pill$1, { label: "分类", value: item.category, tone: "muted" - }), h$3(Pill$1, { + }), h$4(Pill$1, { label: "rev", value: item.revision ?? "—", tone: "muted" - }), h$3(Pill$1, { + }), h$4(Pill$1, { label: "更新", value: formatIso(item.updatedAt), tone: "muted" - })), h$3("div", { style: styles.actions }, pendingForget === item.id ? null : h$3(Btn, { + })), h$4("div", { style: styles.actions }, pendingForget === item.id ? null : h$4(Btn, { label: "删除…", variant: "small", onClick: () => { setPendingForget(item.id); setNotice(null); } - }))), h$3("div", { style: styles.clamp2 }, String(item.content ?? "")), Array.isArray(item.tags) && item.tags.length > 0 ? h$3("p", { style: styles.hint }, "标签:" + item.tags.join("、")) : null, pendingForget === item.id ? h$3("div", { style: styles.nested }, h$3("p", { style: styles.hint }, "确认删除这条记忆?此操作不可撤销。"), h$3("div", { style: styles.actions }, h$3(Btn, { + }))), h$4("div", { style: styles.clamp2 }, String(item.content ?? "")), Array.isArray(item.tags) && item.tags.length > 0 ? h$4("p", { style: styles.hint }, "标签:" + item.tags.join("、")) : null, pendingForget === item.id ? h$4("div", { style: styles.nested }, h$4("p", { style: styles.hint }, "确认删除这条记忆?此操作不可撤销。"), h$4("div", { style: styles.actions }, h$4(Btn, { variant: "danger", label: busy === item.id ? "删除中…" : "确认删除", disabled: busy !== "", onClick: () => { forget(item); } - }), h$3(Btn, { + }), h$4(Btn, { variant: "small", label: "取消", disabled: busy !== "", onClick: () => setPendingForget(null) - }))) : null))), h$3("div", { style: styles.actions }, h$3(Btn, { + }))) : null))), h$4("div", { style: styles.actions }, h$4(Btn, { label: "上一页", variant: "small", disabled: offset === 0 || memories.status === "loading", onClick: () => setOffset(Math.max(0, offset - PAGE_SIZE)) - }), h$3("span", { style: styles.hint }, "第 " + String(Math.floor(offset / PAGE_SIZE) + 1) + " 页 · 共 " + String(total) + " 条"), h$3(Btn, { + }), h$4("span", { style: styles.hint }, "第 " + String(Math.floor(offset / PAGE_SIZE) + 1) + " 页 · 共 " + String(total) + " 条"), h$4(Btn, { label: "下一页", variant: "small", disabled: offset + PAGE_SIZE >= total || memories.status === "loading", onClick: () => setOffset(offset + PAGE_SIZE) - }))), project ? h$3(Section, { + }))), project ? h$4(Section, { title: "文档(只读)", hint: "项目文档由本地记忆库维护;这里只展示标题与摘要。" - }, documents.error === null ? null : h$3(Banner, { tone: "bad" }, documents.error), (documents.data?.documents ?? []).length === 0 ? h$3("p", { style: styles.hint }, "当前项目还没有文档。") : h$3("div", { style: { + }, documents.error === null ? null : h$4(Banner, { tone: "bad" }, documents.error), (documents.data?.documents ?? []).length === 0 ? h$4("p", { style: styles.hint }, "当前项目还没有文档。") : h$4("div", { style: { display: "flex", flexDirection: "column", gap: "8px" - } }, (documents.data?.documents ?? []).map((doc) => h$3("div", { + } }, (documents.data?.documents ?? []).map((doc) => h$4("div", { key: doc.id, style: styles.row - }, h$3("div", { style: styles.rowHead }, h$3("span", { style: styles.rowTitle }, String(doc.title ?? doc.id)), h$3("div", { style: styles.pills }, h$3(Pill$1, { + }, h$4("div", { style: styles.rowHead }, h$4("span", { style: styles.rowTitle }, String(doc.title ?? doc.id)), h$4("div", { style: styles.pills }, h$4(Pill$1, { label: "rev", value: doc.revision ?? "—", tone: "muted" - }), h$3(Pill$1, { + }), h$4(Pill$1, { label: "更新", value: formatIso(doc.updatedAt), tone: "muted" - }))), h$3("div", { style: styles.clamp2 }, String(doc.content ?? "")))))) : null); + }))), h$4("div", { style: styles.clamp2 }, String(doc.content ?? "")))))) : null); + } + // src-client/panel/RawTab.tsx + const h$3 = react.createElement; + const ROLE_USER = "user"; + const ROLE_ASSISTANT = "assistant"; + function roleLabel(role) { + return role === ROLE_USER ? "你" : role === ROLE_ASSISTANT ? "助手" : role; + } + function shortId(value) { + const text = String(value ?? ""); + if (text.length <= 18) return text || "—"; + return text.slice(0, 10) + "…" + text.slice(-5); + } + function when(value) { + if (typeof value === "number" && Number.isFinite(value)) return formatTime(value); + if (typeof value === "string" && value !== "") { + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? formatTime(parsed) : value; + } + return "—"; + } + function metric(label, value) { + return h$3("div", { style: s.metric }, h$3("div", { style: s.metricLabel }, label), h$3("div", { style: s.metricValue }, String(value ?? "—"))); + } + const s = { + page: { + display: "flex", + flexDirection: "column", + gap: "14px" + }, + hero: { + display: "flex", + gap: "18px", + flexWrap: "wrap", + alignItems: "stretch", + padding: "20px 22px", + borderRadius: "18px", + border: "1px solid rgba(127,127,127,0.22)", + background: "linear-gradient(135deg, rgba(99,102,241,0.14), rgba(139,92,246,0.06) 58%, transparent)" + }, + heroText: { + flex: "1 1 260px", + minWidth: "240px", + display: "flex", + flexDirection: "column", + gap: "5px" + }, + kicker: { + fontSize: "10.5px", + letterSpacing: ".16em", + fontWeight: 700, + color: "#6366f1", + opacity: .9 + }, + heroTitle: { + margin: 0, + fontSize: "22px", + lineHeight: 1.2, + fontWeight: 720 + }, + heroSub: { + margin: 0, + fontSize: "12px", + opacity: .62, + lineHeight: 1.6, + maxWidth: "540px" + }, + metrics: { + display: "grid", + gridTemplateColumns: "repeat(2, minmax(84px, 1fr))", + gap: "8px", + flex: "0 1 280px", + minWidth: "220px" + }, + metric: { + border: "1px solid rgba(127,127,127,0.18)", + borderRadius: "12px", + padding: "10px 12px", + background: "rgba(127,127,127,0.07)" + }, + metricLabel: { + fontSize: "10.5px", + letterSpacing: ".08em", + opacity: .55, + fontWeight: 600 + }, + metricValue: { + fontSize: "19px", + fontWeight: 720, + fontVariantNumeric: "tabular-nums", + marginTop: "2px" + }, + toolbar: { + display: "flex", + gap: "8px", + flexWrap: "wrap", + alignItems: "center" + }, + searchBox: { + display: "flex", + alignItems: "center", + gap: "8px", + flex: "1 1 320px", + minWidth: "240px", + border: "1px solid rgba(127,127,127,0.28)", + borderRadius: "12px", + padding: "3px 10px", + background: "rgba(127,127,127,0.05)" + }, + searchGlyph: { + fontSize: "16px", + opacity: .5, + flex: "0 0 auto" + }, + searchInput: { + font: "inherit", + fontSize: "13px", + padding: "7px 2px", + border: "none", + outline: "none", + background: "transparent", + color: "inherit", + width: "100%", + minWidth: 0 + }, + chips: { + display: "flex", + gap: "4px", + padding: "2px", + borderRadius: "9px", + border: "1px solid rgba(127,127,127,0.18)" + }, + chip: { + font: "inherit", + fontSize: "11.5px", + padding: "5px 9px", + borderRadius: "7px", + border: "1px solid transparent", + background: "transparent", + color: "inherit", + cursor: "pointer" + }, + chipActive: { + border: "1px solid rgba(99,102,241,0.45)", + background: "rgba(99,102,241,0.14)", + fontWeight: 600 + }, + layout: { + display: "grid", + gridTemplateColumns: "minmax(240px, .78fr) minmax(0, 1.55fr)", + gap: "12px", + alignItems: "start" + }, + card: { + border: "1px solid rgba(127,127,127,0.22)", + borderRadius: "16px", + padding: "16px", + minWidth: 0, + display: "flex", + flexDirection: "column", + gap: "10px" + }, + cardHead: { + display: "flex", + alignItems: "baseline", + justifyContent: "space-between", + gap: "8px", + flexWrap: "wrap" + }, + cardTitle: { + margin: 0, + fontSize: "13.5px", + fontWeight: 650 + }, + hint: { + margin: 0, + fontSize: "11.5px", + opacity: .58, + lineHeight: 1.55 + }, + sessionList: { + display: "flex", + flexDirection: "column", + gap: "6px", + maxHeight: "620px", + overflow: "auto" + }, + session: { + display: "flex", + flexDirection: "column", + gap: "5px", + padding: "10px 11px", + borderRadius: "11px", + border: "1px solid rgba(127,127,127,0.14)", + cursor: "pointer", + background: "transparent" + }, + sessionActive: { + border: "1px solid rgba(99,102,241,0.55)", + background: "rgba(99,102,241,0.10)" + }, + sessionTitle: { + fontWeight: 600, + fontSize: "12.5px", + overflowWrap: "anywhere" + }, + sessionMeta: { + display: "flex", + gap: "8px", + flexWrap: "wrap", + alignItems: "baseline", + fontSize: "11px", + opacity: .6 + }, + sessionSnippet: { + fontSize: "11.5px", + opacity: .72, + overflow: "hidden", + display: "-webkit-box", + WebkitLineClamp: 2, + WebkitBoxOrient: "vertical", + lineHeight: 1.45 + }, + main: { + display: "flex", + flexDirection: "column", + gap: "10px", + minWidth: 0 + }, + resultList: { + display: "flex", + flexDirection: "column", + gap: "6px" + }, + result: { + display: "flex", + flexDirection: "column", + gap: "5px", + padding: "10px 12px", + borderRadius: "11px", + border: "1px solid rgba(127,127,127,0.14)", + cursor: "pointer" + }, + resultHead: { + display: "flex", + gap: "8px", + flexWrap: "wrap", + alignItems: "baseline" + }, + resultSnippet: { + fontSize: "12px", + lineHeight: 1.55, + whiteSpace: "pre-wrap", + overflowWrap: "anywhere" + }, + messageList: { + display: "flex", + flexDirection: "column", + gap: "9px" + }, + message: { + display: "flex", + flexDirection: "column", + gap: "5px", + padding: "10px 12px", + borderRadius: "11px", + border: "1px solid rgba(127,127,127,0.12)", + borderLeft: "3px solid rgba(99,102,241,0.65)", + background: "rgba(127,127,127,0.035)" + }, + messageAssistant: { borderLeft: "3px solid rgba(16,185,129,0.7)" }, + msgHead: { + display: "flex", + gap: "9px", + flexWrap: "wrap", + alignItems: "baseline" + }, + role: { + fontSize: "11px", + fontWeight: 700, + padding: "1px 7px", + borderRadius: "999px", + background: "rgba(99,102,241,0.14)", + color: "inherit" + }, + roleAssistant: { background: "rgba(16,185,129,0.14)" }, + msgMeta: { + fontSize: "10.5px", + opacity: .52 + }, + msgText: { + fontSize: "12.5px", + lineHeight: 1.65, + whiteSpace: "pre-wrap", + overflowWrap: "anywhere" + }, + empty: { + border: "1px dashed rgba(127,127,127,0.3)", + borderRadius: "14px", + padding: "26px 20px", + textAlign: "center", + color: "inherit", + opacity: .72, + fontSize: "12.5px" + }, + selectedBar: { + display: "flex", + alignItems: "baseline", + gap: "8px", + flexWrap: "wrap" + } + }; + function RawTab(props) { + const active = props.active !== false; + const [query, setQuery] = react.useState(""); + const [role, setRole] = react.useState(""); + const [searchResult, setSearchResult] = react.useState(null); + const [searchError, setSearchError] = react.useState(null); + const [searching, setSearching] = react.useState(false); + const [selected, setSelected] = react.useState(null); + const [detail, setDetail] = react.useState(null); + const [detailError, setDetailError] = react.useState(null); + const [detailLoading, setDetailLoading] = react.useState(false); + const status = useApi(async () => { + const result = await request("/dsh-brain/raw/status"); + if (result.status === 404) throw new Error("原始记录接口还没加载:请完全退出并重启 DSH。"); + if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error("读取原始记录状态失败(HTTP " + String(result.status) + ")"); + return result.body; + }, { + visible: active, + pollMs: 15e3 + }); + const sessions = useApi(async () => { + const result = await request("/dsh-brain/raw/sessions?limit=30"); + if (result.status === 404) throw new Error("原始记录接口还没加载:请完全退出并重启 DSH。"); + if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error("读取原始会话失败(HTTP " + String(result.status) + ")"); + return result.body; + }, { visible: active }); + const runSearch = async () => { + const value = query.trim(); + if (value === "") { + setSearchResult(null); + setSearchError("先输入要搜索的关键词。"); + return; + } + setSearching(true); + setSearchError(null); + try { + const params = new URLSearchParams({ + q: value, + k: "30" + }); + if (role !== "") params.set("role", role); + const result = await request("/dsh-brain/raw/search?" + params.toString()); + if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error("搜索原始记录失败(HTTP " + String(result.status) + ")"); + setSearchResult(result.body); + } catch (failure) { + setSearchError(messageOf(failure)); + } finally { + setSearching(false); + } + }; + const openSession = async (sessionId, seq) => { + setSelected({ + sessionId, + ...seq === void 0 ? {} : { seq } + }); + setDetail(null); + setDetailError(null); + setDetailLoading(true); + try { + const params = new URLSearchParams({ + session_id: sessionId, + limit: "100" + }); + if (seq !== void 0) params.set("seq", String(seq)); + const result = await request("/dsh-brain/raw/session?" + params.toString()); + if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error("读取会话失败(HTTP " + String(result.status) + ")"); + setDetail(result.body); + } catch (failure) { + setDetailError(messageOf(failure)); + } finally { + setDetailLoading(false); + } + }; + const sessionRows = Array.isArray(sessions.data?.sessions) ? sessions.data.sessions : []; + const matches = Array.isArray(searchResult?.matches) ? searchResult.matches : []; + const detailItems = Array.isArray(detail?.items) ? detail.items : []; + const disabled = status.data?.enabled === false; + return h$3("div", { style: s.page }, status.error === null ? null : h$3(Banner, { tone: "bad" }, status.error), disabled ? h$3(Banner, { tone: "warn" }, "原始记录层当前已停用:在「设置 → 插件」中启用 dsh-brain-raw 子插件后重启 DSH。") : null, h$3("div", { style: s.hero }, h$3("div", { style: s.heroText }, h$3("div", { style: s.kicker }, "RAW MEMORY · 原话档案"), h$3("h3", { style: s.heroTitle }, "原始记录"), h$3("p", { style: s.heroSub }, "这里不筛摘要、不改写,只按会话保存真实对话。记忆条目说不清时,回到原话里核对。")), h$3("div", { style: s.metrics }, metric("记录", status.status === "loading" ? "…" : status.data?.records ?? 0), metric("会话", status.status === "loading" ? "…" : status.data?.sessions ?? 0), metric("占用", status.status === "loading" ? "…" : formatBytes(status.data?.bytes ?? 0)), metric("保留", status.status === "loading" ? "…" : String(status.data?.retentionDays ?? "—") + " 天"))), status.data?.dir === void 0 ? null : h$3("p", { style: s.hint }, "保存目录:" + String(status.data.dir)), h$3("div", { style: s.toolbar }, h$3("div", { style: s.searchBox }, h$3("span", { style: s.searchGlyph }, "⌕"), h$3("input", { + style: s.searchInput, + type: "text", + value: query, + placeholder: "搜索原话,例如:预算、接口、苹果…", + spellCheck: false, + onChange: (event) => setQuery(event.target.value), + onKeyDown: (event) => { + if (event.key === "Enter") runSearch(); + } + })), h$3("div", { + style: s.chips, + role: "tablist", + "aria-label": "原始记录角色筛选" + }, [ + ["", "全部"], + ["user", "你"], + ["assistant", "助手"] + ].map((item) => h$3("button", { + key: item[0], + type: "button", + role: "tab", + "aria-selected": role === item[0], + style: role === item[0] ? Object.assign({}, s.chip, s.chipActive) : s.chip, + onClick: () => setRole(item[0]) + }, item[1]))), h$3(Btn, { + label: searching ? "搜索中…" : "搜索", + variant: "primary", + disabled: searching, + onClick: () => { + runSearch(); + } + }), searchResult === null ? null : h$3(Btn, { + label: "清空结果", + variant: "small", + onClick: () => { + setSearchResult(null); + setSearchError(null); + } + })), searchError === null ? null : h$3(Banner, { tone: "bad" }, searchError), searchResult === null ? null : h$3("div", { style: s.card }, h$3("div", { style: s.cardHead }, h$3("h4", { style: s.cardTitle }, "搜索结果(" + String(searchResult.total ?? matches.length) + ")"), h$3("span", { style: s.hint }, searchResult.truncated === true ? "结果过多,已截断" : "点击结果查看原话")), matches.length === 0 ? h$3("div", { style: s.empty }, "没有找到匹配的原话。") : h$3("div", { style: s.resultList }, matches.map((item, index) => h$3("div", { + key: String(item.sessionId) + ":" + String(item.seq ?? index) + ":" + String(index), + style: s.result, + onClick: () => { + openSession(String(item.sessionId), typeof item.seq === "number" ? item.seq : void 0); + } + }, h$3("div", { style: s.resultHead }, h$3(Pill$1, { + label: "角色", + value: roleLabel(String(item.role)), + tone: "muted" + }), h$3(Pill$1, { + label: "会话", + value: shortId(item.sessionId), + tone: "muted" + }), item.seq === void 0 ? null : h$3(Pill$1, { + label: "seq", + value: item.seq, + tone: "muted" + }), h$3("span", { style: s.msgMeta }, when(item.time ?? item.createdAt))), h$3("div", { style: s.resultSnippet }, String(item.snippet ?? "")))))), h$3("div", { style: s.layout }, h$3("div", { style: s.card }, h$3("div", { style: s.cardHead }, h$3("h4", { style: s.cardTitle }, "最近会话"), h$3(Btn, { + label: "刷新", + variant: "small", + onClick: () => { + status.reload(); + sessions.reload(); + } + })), sessions.error === null ? null : h$3(Banner, { tone: "bad" }, sessions.error), sessionRows.length === 0 ? h$3("div", { style: s.empty }, "还没有原始记录。重启 DSH 后,新的对话会开始采集。") : h$3("div", { style: s.sessionList }, sessionRows.map((item) => h$3("div", { + key: String(item.sessionId), + style: selected?.sessionId === item.sessionId ? Object.assign({}, s.session, s.sessionActive) : s.session, + onClick: () => { + openSession(String(item.sessionId)); + } + }, h$3("div", { style: s.sessionTitle }, shortId(item.sessionId)), h$3("div", { style: s.sessionMeta }, h$3("span", null, String(item.records ?? 0) + " 条"), h$3("span", null, when(item.lastAt)), h$3("span", null, formatBytes(item.bytes ?? 0))), item.latestSnippet === void 0 ? null : h$3("div", { style: s.sessionSnippet }, String(item.latestSnippet)))))), h$3("div", { style: s.card }, selected === null ? h$3("div", { style: s.empty }, "从左侧选择一个会话,或在上方搜索原话。") : h$3("div", { style: s.main }, h$3("div", { style: s.cardHead }, h$3("h4", { style: s.cardTitle }, "会话 " + shortId(selected.sessionId)), h$3("div", { style: s.chips }, h$3(Pill$1, { + label: "总记录", + value: detailLoading ? "…" : detail?.total ?? "—", + tone: "muted" + }), selected.seq === void 0 ? null : h$3(Pill$1, { + label: "seq", + value: selected.seq, + tone: "muted" + }), h$3(Btn, { + label: "查看整个会话", + variant: "small", + onClick: () => { + openSession(String(selected.sessionId)); + } + }))), detailError === null ? null : h$3(Banner, { tone: "bad" }, detailError), detailLoading ? h$3("p", { style: s.hint }, "正在读取原话…") : null, !detailLoading && detailError === null && detailItems.length === 0 ? h$3("div", { style: s.empty }, "这个会话还没有原始记录。") : null, detailItems.length === 0 ? null : h$3("div", { style: s.messageList }, detailItems.map((item, index) => h$3("div", { + key: String(item.messageId ?? item.seq ?? index), + style: item.role === ROLE_ASSISTANT ? Object.assign({}, s.message, s.messageAssistant) : s.message + }, h$3("div", { style: s.msgHead }, h$3("span", { style: item.role === ROLE_ASSISTANT ? Object.assign({}, s.role, s.roleAssistant) : s.role }, roleLabel(String(item.role))), item.seq === void 0 ? null : h$3("span", { style: s.msgMeta }, "seq " + String(item.seq)), item.turn === void 0 ? null : h$3("span", { style: s.msgMeta }, "turn " + String(item.turn)), h$3("span", { style: s.msgMeta }, when(item.time ?? item.createdAt))), h$3("div", { style: s.msgText }, String(item.text ?? ""))))))))); } // src-client/panel/DepartmentTab.tsx const h$2 = react.createElement; @@ -4864,6 +5343,10 @@ window.__ModuleLoader__.load({ id: "memory", label: "记忆" }, + { + id: "raw", + label: "原始记录" + }, { id: "departments", label: "部门" @@ -4874,6 +5357,7 @@ window.__ModuleLoader__.load({ let content; if (tab === "overview") content = h$1(Overview); else if (tab === "memory") content = h$1(MemoryTab, { scope: "global" }); + else if (tab === "raw") content = h$1(RawTab, {}); else content = h$1(DepartmentTab, { scope: "global" }); return h$1("div", { className: BrainPanel_module_css_default.nativeWorkspace, @@ -4883,7 +5367,7 @@ window.__ModuleLoader__.load({ className: BrainPanel_module_css_default.windowDragBand, "data-window-drag": true, "aria-hidden": "true" - }), h$1("div", { className: BrainPanel_module_css_default.panelInner }, h$1("div", { className: BrainPanel_module_css_default.header }, h$1("div", { className: BrainPanel_module_css_default.titleBlock }, h$1("h3", { className: BrainPanel_module_css_default.title }, "Brain"), h$1("p", { className: BrainPanel_module_css_default.subtitle }, "全局记忆、部门与运行状态"))), h$1("div", { + }), h$1("div", { className: BrainPanel_module_css_default.panelInner }, h$1("div", { className: BrainPanel_module_css_default.header }, h$1("div", { className: BrainPanel_module_css_default.titleBlock }, h$1("h3", { className: BrainPanel_module_css_default.title }, "Brain"), h$1("p", { className: BrainPanel_module_css_default.subtitle }, "全局记忆、原始记录、部门与运行状态"))), h$1("div", { className: BrainPanel_module_css_default.tabBar, role: "tablist", "aria-label": "Brain 面板页签" diff --git a/lib/api.js b/lib/api.js index a960fea..9b6c7ff 100644 --- a/lib/api.js +++ b/lib/api.js @@ -200,7 +200,6 @@ function validateSkillListing(value) { function validateSkillBundle(value) { const body = requireResponseObject(value, 'skill bundle response'); requireResponseString(body, 'name'); - optionalResponseNumber(body, 'revision'); if (typeof body.revision !== 'number' || !Number.isFinite(body.revision)) { throw new Error('revision must be a number'); } @@ -466,12 +465,8 @@ export class CloudClient { if (base === '') return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }; const headers = { Accept: 'application/json' }; - try { - headers.Origin = new URL(baseUrl).origin; - } - catch { - return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }; - } + // authBase already parsed this exact URL successfully, so this cannot throw. + headers.Origin = new URL(baseUrl).origin; if (cookie !== undefined && cookie !== '') headers.Cookie = cookie; const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) }; diff --git a/lib/clients.js b/lib/clients.js index e28e83e..cb5b418 100644 --- a/lib/clients.js +++ b/lib/clients.js @@ -191,9 +191,7 @@ export class ClientRegistry { if (software === undefined) throw new Error('invalid_software'); const path = typeof pathInput === 'string' ? pathInput.trim() : ''; - if (path === '' || !existsSync(path)) - throw new Error('invalid_path'); - const stats = await stat(path).catch(() => undefined); + const stats = path === '' ? undefined : await stat(path).catch(() => undefined); if (stats === undefined || !stats.isDirectory()) throw new Error('invalid_path'); const resolved = resolve(path); @@ -232,7 +230,7 @@ export class ClientRegistry { const frontmatter = parseSkillFrontmatter(markdown); out.push({ folder: entry.name, - name: typeof frontmatter.name === 'string' && frontmatter.name !== '' ? frontmatter.name : entry.name, + name: frontmatter.name ?? entry.name, description: String(frontmatter.description ?? '').slice(0, 300), path: skillDir, softwareId: software, diff --git a/lib/cloudsync-routes.js b/lib/cloudsync-routes.js index c77a226..6bb4e02 100644 --- a/lib/cloudsync-routes.js +++ b/lib/cloudsync-routes.js @@ -72,7 +72,7 @@ async function serveTest(deps, req, res) { id: 'memory', label: '记忆读写权限(memory:write)', state: probe.ok ? 'ok' : checkState(probe.error), - message: probe.ok ? `鉴权通过(${(probe.data.projects ?? []).length} 个项目)` : describeError(probe.error), + message: probe.ok ? `鉴权通过(${probe.data.projects.length} 个项目)` : describeError(probe.error), }); } const summaryToken = deps.store.summaryToken(); @@ -183,9 +183,7 @@ async function serveLogin(deps, req, res) { const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory, target); const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary, target); if (!activity.ok && !memory.ok) { - const first = activity.ok ? memory : activity; - const reason = first.ok ? '无法创建令牌' : describeError(first.error); - json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` }); + json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${describeError(activity.error)}` }); return; } // Atomic account switch: a scope whose mint failed must not keep the token diff --git a/lib/config.js b/lib/config.js index 8c17b9e..ce267f2 100644 --- a/lib/config.js +++ b/lib/config.js @@ -70,13 +70,9 @@ export function isPlaceholderBaseUrl(value) { const normalized = normalizeBaseUrl(value); if (normalized === undefined) return true; - try { - const host = new URL(normalized).hostname.toLowerCase(); - return host === 'your-memory-host' || host === 'example.com'; - } - catch { - return true; - } + // normalized was built from a successfully parsed URL, so this cannot throw. + const host = new URL(normalized).hostname.toLowerCase(); + return host === 'your-memory-host' || host === 'example.com'; } /** Service origin of one base URL, or '' when it cannot be parsed. */ export function originOf(value) { diff --git a/lib/diagnostics.js b/lib/diagnostics.js index 9de4a07..7cc3d93 100644 --- a/lib/diagnostics.js +++ b/lib/diagnostics.js @@ -147,7 +147,6 @@ export class BrainLogger { if (this.warned) return; this.warned = true; - if (typeof console !== 'undefined') - console.warn('[dsh-brain] diagnostic log write failed; continuing without logs'); + console.warn('[dsh-brain] diagnostic log write failed; continuing without logs'); } } diff --git a/lib/entries/raw.js b/lib/entries/raw.js new file mode 100644 index 0000000..3bc2cd6 --- /dev/null +++ b/lib/entries/raw.js @@ -0,0 +1,115 @@ +import { createRawMemoryRuntime } from "../raw-memory/index.js"; +import { createRawMemoryRoutes } from "../raw-memory/routes.js"; +import { conversationIdOf, redactSecrets, textOf, turnOf } from "../reporter.js"; +export const name = 'dsh-brain-raw'; +/** Services required before `apply` runs. */ +export const inject = ['tools']; +function isInjected(value) { + if (value === null || typeof value !== 'object') + return false; + const source = value.source; + if (source === null || typeof source !== 'object') + return false; + const kind = source.kind; + return typeof kind === 'string' && kind !== 'user'; +} +function workspaceOf(session) { + return session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace; +} +function messageIdOf(value) { + if (value === null || typeof value !== 'object') + return undefined; + const id = value.id; + return typeof id === 'string' && id !== '' ? id : undefined; +} +function epochOf(time) { + if (typeof time === 'number' && Number.isFinite(time)) + return time; + if (typeof time === 'string' && time.trim() !== '') { + const parsed = Date.parse(time); + return Number.isFinite(parsed) ? parsed : undefined; + } + return undefined; +} +/** Register the raw recorder with the host. */ +export function apply(ctx, config) { + const runtime = createRawMemoryRuntime(config); + const logger = ctx.logger('dsh-brain'); + ctx.inject(['tools'], (toolsCtx) => { + const tools = toolsCtx.tools; + if (tools === undefined) + return; + for (const tool of runtime.tools) { + toolsCtx.effect(() => tools.register(tool), `dsh-brain-raw: tool ${tool.name}`); + } + }); + ctx.inject(['webServer'], (webCtx) => { + const webServer = webCtx.webServer; + if (webServer === undefined) + return; + for (const route of createRawMemoryRoutes({ store: runtime.store, settings: () => runtime.settings })) { + webCtx.effect(() => webServer.register(route), `dsh-brain-raw: route ${route.path}`); + } + }); + const seen = new Map(); + const onEvent = ctx.on; + ctx.effect(() => { + const dispose = onEvent('session/event', (session, event) => { + if (!runtime.settings.enabled) + return; + if (event === null || typeof event !== 'object') + return; + if (event.type !== 'user/message' && event.type !== 'assistant/message') + return; + if (event.type === 'assistant/message' && !runtime.settings.captureAssistant) + return; + const sessionId = conversationIdOf(session); + if (sessionId === undefined) + return; + const value = event.data?.message ?? event.data; + if (event.type === 'user/message' && isInjected(value)) + return; + const raw = textOf(value); + if (raw === undefined || raw.trim() === '') + return; + const seq = typeof event.seq === 'number' && Number.isFinite(event.seq) ? event.seq : undefined; + const dedupe = `${sessionId}:${seq === undefined ? event.type + ':' + raw.slice(0, 120) : String(seq)}:${event.type}`; + if (seen.has(dedupe)) + return; + seen.set(dedupe, Date.now()); + if (seen.size > 10_000) { + const oldest = seen.keys().next(); + if (oldest.done !== true) + seen.delete(oldest.value); + } + const turn = turnOf(event.data); + const messageId = messageIdOf(value); + const time = epochOf(event.time); + const workspace = workspaceOf(session); + const record = { + v: 1, + sessionId, + ...(seq === undefined ? {} : { seq }), + ...(turn === undefined ? {} : { turn }), + role: event.type === 'user/message' ? 'user' : 'assistant', + text: redactSecrets(raw).slice(0, runtime.settings.maxTextChars), + ...(time === undefined ? {} : { time }), + ...(messageId === undefined ? {} : { messageId }), + createdAt: Date.now(), + ...(workspace === undefined ? {} : { workspace }), + }; + void runtime.store.append(record).catch((error) => { + logger.warn('dsh-brain-raw capture failed: ' + (error instanceof Error ? error.message : String(error))); + }); + }); + return () => dispose(); + }, 'dsh-brain-raw: session capture'); + // Retention is checked once on load and then every six hours; it only deletes + // whole session files whose last write is older than the configured window. + ctx.effect(() => { + void runtime.store.prune(runtime.settings.retentionDays).catch(() => undefined); + const timer = setInterval(() => { void runtime.store.prune(runtime.settings.retentionDays); }, 6 * 60 * 60 * 1000); + timer.unref?.(); + return () => clearInterval(timer); + }, 'dsh-brain-raw: retention'); +} diff --git a/lib/index.js b/lib/index.js index d5cd968..f4d604c 100644 --- a/lib/index.js +++ b/lib/index.js @@ -3,6 +3,7 @@ import * as memory from "./entries/memory.js"; import * as skills from "./entries/skills.js"; import * as mcp from "./entries/mcp.js"; import * as ui from "./entries/ui.js"; +import * as raw from "./entries/raw.js"; /** Package name; also the client bundle id. */ export const name = 'dsh-brain'; /** Services required before `apply` runs. */ @@ -18,4 +19,5 @@ export function apply(ctx, config) { skills.apply(ctx, config); mcp.apply(ctx, config); ui.apply(ctx, config); + raw.apply(ctx, config); } diff --git a/lib/local-memory/departments/manager.js b/lib/local-memory/departments/manager.js index aa07fac..e1362cf 100644 --- a/lib/local-memory/departments/manager.js +++ b/lib/local-memory/departments/manager.js @@ -92,8 +92,6 @@ export class DepartmentManager { } async update(id, patch, expectedRevision, scope) { const current = await this.required(id, scope); - if (expectedRevision !== undefined && current.revision !== expectedRevision) - throw new Error('revision_conflict'); if (patch.role !== undefined && containsSecret(patch.role)) throw new Error('secret_not_allowed'); return this.registry(current.scope).update(async (file) => { @@ -166,8 +164,6 @@ export class DepartmentManager { } async checkpoint(id, input, expectedRevision, scope) { const current = await this.required(id, scope); - if (expectedRevision !== undefined && current.revision !== expectedRevision) - throw new Error('revision_conflict'); const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000); const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000); if ((currentTask !== undefined && containsSecret(currentTask)) || (handoff !== undefined && containsSecret(handoff))) @@ -243,6 +239,9 @@ export class DepartmentManager { /** Disable without deleting private memories or allowing automatic session recovery. */ async disable(id, expectedRevision, scope) { const current = await this.required(id, scope); + // Fail on a stale revision before deactivating the space below: the update + // callback re-checks under the registry lock, but the deactivation has + // already happened by then. if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict'); const store = this.store(current); diff --git a/lib/local-memory/manager.js b/lib/local-memory/manager.js index 77ddea7..844658d 100644 --- a/lib/local-memory/manager.js +++ b/lib/local-memory/manager.js @@ -320,12 +320,9 @@ export class LocalMemoryManager { return new JsonDocumentStore(join(root, 'documents')).list(); } async addDocument(input, workspace) { - const store = await this.ensureProject(workspace); - void store; - const root = this.projectRootFor(workspace); - const documents = this.workspaces.get(root)?.documents; - if (documents === undefined) - throw new Error('local_documents_unavailable'); + await this.ensureProject(workspace); + // ensureProject guarantees the workspace entry exists (the map is never pruned). + const documents = this.workspaces.get(this.projectRootFor(workspace)).documents; return documents.add(input); } async storageStatus(workspace, scope) { @@ -425,9 +422,8 @@ export class LocalMemoryManager { processedNext.add(turn.turnId); let documentId; if (fresh.length > 0) { - const documents = this.workspaces.get(this.projectRootFor(workspace))?.documents; - if (documents === undefined) - throw new Error('local_documents_unavailable'); + // ensureProject above guarantees the workspace entry exists (the map is never pruned). + const documents = this.workspaces.get(this.projectRootFor(workspace)).documents; const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] }); documentId = document.id; } diff --git a/lib/memory/tools.js b/lib/memory/tools.js index 4f32da8..fda9f43 100644 --- a/lib/memory/tools.js +++ b/lib/memory/tools.js @@ -100,7 +100,7 @@ function searchTool(deps) { const result = await deps.remote().search(query, k, project, workspace); if (!result.ok) throw new Error(`检索失败:${describeError(result.error)}`); - const matches = result.data.matches ?? []; + const matches = result.data.matches; return { query, total: result.data.total ?? matches.length, @@ -237,7 +237,7 @@ function listTool(deps) { const result = await deps.remote().list({ limit, offset, project }, workspace); if (!result.ok) throw new Error(`列表读取失败:${describeError(result.error)}`); - const items = result.data.items ?? []; + const items = result.data.items; return { total: result.data.total ?? items.length, items: items.map(toHitView) }; }, }; @@ -258,7 +258,7 @@ function projectsTool(deps) { const result = await deps.remote().projects(workspace); if (!result.ok) throw new Error(`项目列表读取失败:${describeError(result.error)}`); - return { projects: result.data.projects ?? [] }; + return { projects: result.data.projects }; }, }; } diff --git a/lib/mnemon/driver.js b/lib/mnemon/driver.js index 113778a..0ae9a5c 100644 --- a/lib/mnemon/driver.js +++ b/lib/mnemon/driver.js @@ -150,7 +150,7 @@ export class LongMemoryProvider { description: 'Account-wide default scope (no project filter).', connection: {}, }]; - for (const project of result.data.projects ?? []) { + for (const project of result.data.projects) { if (typeof project.id !== 'string' || project.id === '') continue; spaces.push({ @@ -183,7 +183,7 @@ export class LongMemoryProvider { throw new Error(`LongMemory search failed: ${result.error.message}`); } return { - results: (result.data.matches ?? []) + results: result.data.matches .map(insightFromHit) .filter((item) => item !== undefined), }; @@ -201,7 +201,7 @@ export class LongMemoryProvider { if (!result.ok) { throw new Error(`LongMemory list failed: ${result.error.message}`); } - return (result.data.items ?? []) + return result.data.items .map(insightFromHit) .filter((item) => item !== undefined); } diff --git a/lib/mnemon/native.js b/lib/mnemon/native.js index 75db194..29ef6f2 100644 --- a/lib/mnemon/native.js +++ b/lib/mnemon/native.js @@ -28,8 +28,8 @@ export class LocalMnemonProvider { } async status(body) { try { - const status = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body))); - return { healthy: true, stats: { totalInsights: Number(status.spaces?.project ? 0 : 0), deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } }; + await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body))); + return { healthy: true, stats: { totalInsights: 0, deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } }; } catch (error) { return { healthy: false, error: error instanceof Error ? error.message : String(error) }; diff --git a/lib/raw-memory/index.js b/lib/raw-memory/index.js new file mode 100644 index 0000000..cdb5bb7 --- /dev/null +++ b/lib/raw-memory/index.js @@ -0,0 +1,26 @@ +/** + * Original-record layer public surface. + * + * This module deliberately has no dependency on Mnemon's core: a host entry + * can create the recorder, register its three tools, and feed it session + * events without changing any Mnemon source, database or UI. + */ +import { RawMemoryStore } from "./store.js"; +import { rawMemorySettingsFromConfig } from "./settings.js"; +import { createRawMemoryTools } from "./tools.js"; +/** Build the raw recorder and its tools from one row config. */ +export function createRawMemoryRuntime(config) { + const settings = rawMemorySettingsFromConfig(config); + const store = new RawMemoryStore({ + root: settings.dir, + maxBytesPerSession: settings.maxBytesPerSession, + }); + return { + settings, + store, + tools: createRawMemoryTools({ store, settings: () => settings }), + }; +} +export { RawMemoryStore } from "./store.js"; +export { createRawMemoryTools } from "./tools.js"; +export { rawMemorySettingsFromConfig } from "./settings.js"; diff --git a/lib/raw-memory/routes.js b/lib/raw-memory/routes.js new file mode 100644 index 0000000..a47386a --- /dev/null +++ b/lib/raw-memory/routes.js @@ -0,0 +1,109 @@ +import { fail, json } from "../http.js"; +function urlOf(req) { + return new URL(req.url ?? '/', 'http://localhost'); +} +function method(req, res, allowed) { + if (req.method === allowed || (allowed === 'GET' && req.method === 'HEAD')) + return true; + fail(res, 405, 'method-not-allowed'); + return false; +} +function numberParam(url, name, fallback, min, max) { + const parsed = Number.parseInt(url.searchParams.get(name) ?? '', 10); + if (!Number.isFinite(parsed)) + return fallback; + return Math.min(max, Math.max(min, parsed)); +} +function serveStatus(deps, req, res) { + if (!method(req, res, 'GET')) + return; + const settings = deps.settings(); + void deps.store.status(settings.enabled, settings.retentionDays).then((status) => { + json(res, 200, { ok: true, ...status }); + }).catch((error) => { + fail(res, 500, error instanceof Error ? error.message : 'raw-status-failed'); + }); +} +function serveSessions(deps, req, res) { + if (!method(req, res, 'GET')) + return; + const settings = deps.settings(); + if (!settings.enabled) { + fail(res, 503, 'raw-disabled'); + return; + } + const url = urlOf(req); + const limit = numberParam(url, 'limit', 30, 1, 100); + void deps.store.listSessions(limit).then((sessions) => { + json(res, 200, { ok: true, sessions }); + }).catch((error) => { + fail(res, 500, error instanceof Error ? error.message : 'raw-sessions-failed'); + }); +} +function serveSearch(deps, req, res) { + if (!method(req, res, 'GET')) + return; + const settings = deps.settings(); + if (!settings.enabled) { + fail(res, 503, 'raw-disabled'); + return; + } + const url = urlOf(req); + const query = (url.searchParams.get('q') ?? '').trim(); + if (query === '') { + fail(res, 400, 'query-required'); + return; + } + const roleValue = url.searchParams.get('role'); + const role = roleValue === 'user' || roleValue === 'assistant' ? roleValue : undefined; + const k = numberParam(url, 'k', settings.maxSearchResults, 1, 50); + const sessionId = (url.searchParams.get('session_id') ?? '').trim() || undefined; + void deps.store.search(query, { k, ...(role === undefined ? {} : { role }), ...(sessionId === undefined ? {} : { sessionId }) }).then((result) => { + json(res, 200, { + ok: true, + query, + total: result.total, + truncated: result.truncated, + sessions_scanned: result.sessionsScanned, + matches: result.matches, + }); + }).catch((error) => { + fail(res, 500, error instanceof Error ? error.message : 'raw-search-failed'); + }); +} +function serveSession(deps, req, res) { + if (!method(req, res, 'GET')) + return; + const settings = deps.settings(); + if (!settings.enabled) { + fail(res, 503, 'raw-disabled'); + return; + } + const url = urlOf(req); + const sessionId = (url.searchParams.get('session_id') ?? '').trim(); + if (sessionId === '') { + fail(res, 400, 'session-id-required'); + return; + } + const seqValue = url.searchParams.get('seq'); + const seq = seqValue === null ? undefined : Number.parseInt(seqValue, 10); + const offset = numberParam(url, 'offset', 0, 0, 1000000); + const limit = numberParam(url, 'limit', settings.maxReadRecords, 1, 500); + void deps.store.readSession(sessionId, { + ...(seq === undefined || !Number.isFinite(seq) ? {} : { seq }), + ...(seq === undefined ? { offset } : {}), + limit, + }).then((result) => { + json(res, 200, { ok: true, session_id: result.sessionId, total: result.total, items: result.items }); + }).catch((error) => { + fail(res, 500, error instanceof Error ? error.message : 'raw-session-failed'); + }); +} +export function createRawMemoryRoutes(deps) { + return [ + { kind: 'exact', path: '/dsh-brain/raw/status', handler: (req, res) => serveStatus(deps, req, res) }, + { kind: 'exact', path: '/dsh-brain/raw/sessions', handler: (req, res) => serveSessions(deps, req, res) }, + { kind: 'exact', path: '/dsh-brain/raw/search', handler: (req, res) => serveSearch(deps, req, res) }, + { kind: 'exact', path: '/dsh-brain/raw/session', handler: (req, res) => serveSession(deps, req, res) }, + ]; +} diff --git a/lib/raw-memory/settings.js b/lib/raw-memory/settings.js new file mode 100644 index 0000000..6361d1b --- /dev/null +++ b/lib/raw-memory/settings.js @@ -0,0 +1,39 @@ +/** + * Raw-layer configuration. + * + * The row config in cordis.patch.yml is the first-boot seed. Keeping the + * parser here (rather than in the five-bundle Settings store) lets the raw + * recorder stay an optional, self-contained row: disabling the row stops all + * capture, and changing its config changes the recorder without touching + * Mnemon or the existing memory bundles. + */ +import { join, resolve } from 'node:path'; +import { dshHome } from "../store.js"; +function asRecord(value) { + if (value === null || typeof value !== 'object' || Array.isArray(value)) + return {}; + return value; +} +function bool(value, fallback) { + return typeof value === 'boolean' ? value : fallback; +} +function integer(value, fallback, min, max) { + if (typeof value !== 'number' || !Number.isFinite(value)) + return fallback; + return Math.min(max, Math.max(min, Math.trunc(value))); +} +/** Parse one raw-row config defensively; every field is optional. */ +export function rawMemorySettingsFromConfig(config) { + const source = asRecord(config); + const rawDir = typeof source.rawDir === 'string' ? source.rawDir.trim() : ''; + return { + enabled: bool(source.rawEnabled, true), + captureAssistant: bool(source.rawCaptureAssistant, true), + dir: rawDir === '' ? join(dshHome(), 'brain', 'raw') : resolve(rawDir), + retentionDays: integer(source.rawRetentionDays, 90, 1, 3650), + maxBytesPerSession: integer(source.rawMaxBytesPerSession, 20_000_000, 100_000, 1_000_000_000), + maxTextChars: integer(source.rawMaxTextChars, 16_000, 1_000, 200_000), + maxSearchResults: integer(source.rawMaxSearchResults, 10, 1, 50), + maxReadRecords: integer(source.rawMaxReadRecords, 50, 1, 500), + }; +} diff --git a/lib/raw-memory/store.js b/lib/raw-memory/store.js new file mode 100644 index 0000000..84506ff --- /dev/null +++ b/lib/raw-memory/store.js @@ -0,0 +1,267 @@ +/** + * Append-only original-record store. + * + * One JSONL file per session, under a separate directory from Mnemon's + * mnemon.db. The raw layer deliberately does not join Mnemon's identity / + * merge tables: those walk every non-oplog row and would become slower with + * every captured message. Rotation keeps one session bounded; retention is + * enforced by the entry's maintenance timer. + */ +import { createHash } from 'node:crypto'; +import { appendFile, mkdir, readdir, readFile, rename, rm, stat } from 'node:fs/promises'; +import { join } from 'node:path'; +function sizeOf(path) { + return stat(path).then((info) => info.size).catch(() => 0); +} +function snippetFor(text, terms) { + const lower = text.toLowerCase(); + let first = -1; + for (const term of terms) { + const found = lower.indexOf(term); + if (found >= 0 && (first < 0 || found < first)) + first = found; + } + const start = first <= 80 ? 0 : first - 80; + const end = Math.min(text.length, start + 500); + return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`; +} +function isRecord(value) { + if (value === null || typeof value !== 'object' || Array.isArray(value)) + return false; + const record = value; + return record.v === 1 + && typeof record.sessionId === 'string' + && typeof record.text === 'string' + && (record.role === 'user' || record.role === 'assistant') + && typeof record.createdAt === 'number'; +} +export class RawMemoryStore { + options; + queues = new Map(); + sizes = new Map(); + constructor(options) { + this.options = { ...options, maxScanBytes: options.maxScanBytes ?? 128 * 1024 * 1024 }; + } + get dir() { + return this.options.root; + } + safeSessionName(sessionId) { + const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80) || 'session'; + const hash = createHash('sha256').update(sessionId).digest('hex').slice(0, 8); + return `${readable}-${hash}`; + } + fileFor(sessionId) { + return join(this.options.root, `${this.safeSessionName(sessionId)}.jsonl`); + } + rotatedFor(file) { + return file.replace(/\.jsonl$/, '.1.jsonl'); + } + async listFiles() { + try { + const entries = await readdir(this.options.root, { withFileTypes: true }); + return entries + .filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl')) + .map((entry) => join(this.options.root, entry.name)) + .sort(); + } + catch { + return []; + } + } + async readRecords(file) { + let text; + try { + text = await readFile(file, 'utf8'); + } + catch { + return []; + } + const records = []; + for (const line of text.split(/\r?\n/)) { + if (line.trim() === '') + continue; + try { + const value = JSON.parse(line); + if (isRecord(value)) + records.push(value); + } + catch { + // A torn final line must not make the rest of the file unreadable. + } + } + return records; + } + /** Append one message, serialized per session so concurrent turns cannot interleave. */ + async append(record) { + const file = this.fileFor(record.sessionId); + const line = `${JSON.stringify(record)}\n`; + const incoming = Buffer.byteLength(line, 'utf8'); + const previous = this.queues.get(file) ?? Promise.resolve(); + const next = previous.then(async () => { + await mkdir(this.options.root, { recursive: true }); + let size = this.sizes.get(file); + if (size === undefined) + size = await sizeOf(file); + if (size > 0 && size + incoming > this.options.maxBytesPerSession) { + const rotated = this.rotatedFor(file); + await rm(rotated, { force: true }).catch(() => undefined); + await rename(file, rotated).catch(() => undefined); + size = 0; + } + await appendFile(file, line, { encoding: 'utf8', mode: 0o600 }); + this.sizes.set(file, size + incoming); + }).finally(() => { + if (this.queues.get(file) === next) + this.queues.delete(file); + }); + this.queues.set(file, next); + await next; + } + /** Keyword search over original text, newest / best match first. */ + async search(query, options = {}) { + const normalized = query.trim().toLowerCase(); + const terms = normalized.split(/\s+/).filter((term) => term !== ''); + if (terms.length === 0) + return { matches: [], total: 0, truncated: false, sessionsScanned: 0 }; + // Boundary responsibility: callers (raw tools and routes) validate and clamp k. + const k = options.k ?? 10; + const files = await this.listFiles(); + const matches = []; + const seenSessions = new Set(); + let total = 0; + let scannedBytes = 0; + let truncated = false; + for (const file of files) { + // The scan cap is always set by the constructor; hitting it is reported + // explicitly through `truncated`, never silently. + if (scannedBytes >= this.options.maxScanBytes) { + truncated = true; + break; + } + scannedBytes += await sizeOf(file); + for (const record of await this.readRecords(file)) { + seenSessions.add(record.sessionId); + if (options.sessionId !== undefined && record.sessionId !== options.sessionId) + continue; + if (options.role !== undefined && record.role !== options.role) + continue; + const haystack = `${record.text.toLowerCase()}\n${record.sessionId.toLowerCase()}`; + let score = 0; + for (const term of terms) + if (haystack.includes(term)) + score += 1; + if (score === 0) + continue; + if (haystack.includes(normalized)) + score += 2; + total += 1; + matches.push({ + sessionId: record.sessionId, + ...(record.seq === undefined ? {} : { seq: record.seq }), + ...(record.turn === undefined ? {} : { turn: record.turn }), + role: record.role, + ...(record.time === undefined ? {} : { time: record.time }), + createdAt: record.createdAt, + ...(record.messageId === undefined ? {} : { messageId: record.messageId }), + snippet: snippetFor(record.text, terms), + score, + }); + } + } + matches.sort((left, right) => right.score - left.score || right.createdAt - left.createdAt); + return { matches: matches.slice(0, k), total, truncated, sessionsScanned: seenSessions.size }; + } + /** Read one session, either by exact event seq or by record offset. */ + async readSession(sessionId, options = {}) { + const file = this.fileFor(sessionId); + const records = [...await this.readRecords(this.rotatedFor(file)), ...await this.readRecords(file)]; + let selected = records; + if (options.seq !== undefined) { + selected = records.filter((record) => record.seq === options.seq); + } + else { + // Boundary responsibility: callers (raw tools and routes) validate and clamp offset/limit. + const offset = options.offset ?? 0; + const limit = options.limit ?? 50; + selected = records.slice(offset, offset + limit); + } + return { sessionId, total: records.length, items: selected }; + } + /** Aggregate counts for the status tool. */ + async status(enabled, retentionDays) { + const files = await this.listFiles(); + let records = 0; + let bytes = 0; + const sessions = new Set(); + let oldest; + let newest; + for (const file of files) { + bytes += await sizeOf(file); + for (const record of await this.readRecords(file)) { + records += 1; + sessions.add(record.sessionId); + if (oldest === undefined || record.createdAt < oldest) + oldest = record.createdAt; + if (newest === undefined || record.createdAt > newest) + newest = record.createdAt; + } + } + return { + enabled, + dir: this.options.root, + sessions: sessions.size, + records, + bytes, + ...(oldest === undefined ? {} : { oldestAt: new Date(oldest).toISOString() }), + ...(newest === undefined ? {} : { newestAt: new Date(newest).toISOString() }), + retentionDays, + maxBytesPerSession: this.options.maxBytesPerSession, + }; + } + /** Session rows for the Brain panel's session browser, newest first. */ + async listSessions(limit = 30) { + const files = await this.listFiles(); + const sessions = new Map(); + for (const file of files) { + const bytes = await sizeOf(file); + const records = await this.readRecords(file); + if (records.length === 0) + continue; + const sessionId = records[0].sessionId; + const summary = sessions.get(sessionId) ?? { sessionId, records: 0, bytes: 0 }; + summary.records += records.length; + summary.bytes += bytes; + for (const record of records) { + const stamp = record.time ?? record.createdAt; + if (summary.firstAt === undefined || stamp < summary.firstAt) + summary.firstAt = stamp; + if (summary.lastAt === undefined || stamp > summary.lastAt) + summary.lastAt = stamp; + summary.latestSnippet = record.text.slice(0, 160); + } + sessions.set(sessionId, summary); + } + return [...sessions.values()] + .sort((left, right) => (right.lastAt ?? 0) - (left.lastAt ?? 0)) + .slice(0, Math.max(1, Math.min(200, Math.trunc(limit)))); + } + /** Delete session files whose last write is older than the retention window. */ + async prune(retentionDays) { + const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1000; + let removed = 0; + for (const file of await this.listFiles()) { + try { + const info = await stat(file); + if (info.mtimeMs < cutoff) { + await rm(file, { force: true }); + removed += 1; + this.sizes.delete(file); + } + } + catch { + // A file removed concurrently is already in the desired state. + } + } + return removed; + } +} diff --git a/lib/raw-memory/tools.js b/lib/raw-memory/tools.js new file mode 100644 index 0000000..f884fb2 --- /dev/null +++ b/lib/raw-memory/tools.js @@ -0,0 +1,121 @@ +function renderJson(_args, value) { + const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2); + return [{ type: 'text', text }]; +} +function searchTool(deps) { + return { + name: 'memory_raw_search', + description: '在原始对话记录中按关键词搜索原话(不是记忆条目,也不是摘要)。返回会话 id、事件 seq、说话角色、时间和原文片段;' + + '需要完整上下文时用 memory_raw_read 按 session_id + seq 读取。纯本地关键词匹配。', + parameters: { + type: 'object', + properties: { + query: { type: 'string', description: '检索关键词或短语(必填)。' }, + k: { type: 'integer', description: '最多返回条数(1..50,默认取配置值)。' }, + session_id: { type: 'string', description: '可选:只在这个会话内搜索。' }, + role: { type: 'string', enum: ['user', 'assistant'], description: '可选:只看用户或助手原话。' }, + }, + required: ['query'], + additionalProperties: false, + }, + output: { + schema: { + type: 'object', + properties: { + query: { type: 'string' }, + total: { type: 'number' }, + truncated: { type: 'boolean' }, + sessions_scanned: { type: 'number' }, + matches: { type: 'array', items: { type: 'object' } }, + }, + required: ['query', 'matches'], + additionalProperties: true, + }, + render: renderJson, + }, + async execute(args) { + const settings = deps.settings(); + if (!settings.enabled) + throw new Error('原始记录层当前已禁用(dsh-brain-raw 行未启用)。'); + const query = typeof args.query === 'string' ? args.query.trim() : ''; + if (query === '') + throw new Error('query 不能为空。'); + const requested = typeof args.k === 'number' && Number.isFinite(args.k) ? Math.trunc(args.k) : settings.maxSearchResults; + const k = Math.min(50, Math.max(1, requested)); + const sessionId = typeof args.session_id === 'string' && args.session_id !== '' ? args.session_id : undefined; + const role = args.role === 'user' || args.role === 'assistant' ? args.role : undefined; + const result = await deps.store.search(query, { k, ...(sessionId === undefined ? {} : { sessionId }), ...(role === undefined ? {} : { role }) }); + return { + query, + total: result.total, + truncated: result.truncated, + sessions_scanned: result.sessionsScanned, + matches: result.matches, + }; + }, + }; +} +function readTool(deps) { + return { + name: 'memory_raw_read', + description: '读取某个会话的原始记录:给 seq 时返回那一条原话,否则按 offset/limit 分页浏览。' + + '返回 sessionId、seq、turn、role、text 与时间。用于核对记忆条目、追查原话出处。', + parameters: { + type: 'object', + properties: { + session_id: { type: 'string', description: '会话 id(必填,可用 memory_raw_search 获得)。' }, + seq: { type: 'integer', description: '可选:精确读取该事件 seq 对应的那一条。' }, + offset: { type: 'integer', description: '可选:从第几条开始(默认 0)。' }, + limit: { type: 'integer', description: '可选:读取条数(1..500,默认取配置值)。' }, + }, + required: ['session_id'], + additionalProperties: false, + }, + output: { + schema: { + type: 'object', + properties: { + session_id: { type: 'string' }, + total: { type: 'number' }, + items: { type: 'array', items: { type: 'object' } }, + }, + required: ['session_id', 'items'], + additionalProperties: true, + }, + render: renderJson, + }, + async execute(args) { + const settings = deps.settings(); + if (!settings.enabled) + throw new Error('原始记录层当前已禁用(dsh-brain-raw 行未启用)。'); + const sessionId = typeof args.session_id === 'string' ? args.session_id.trim() : ''; + if (sessionId === '') + throw new Error('session_id 不能为空。'); + const seq = typeof args.seq === 'number' && Number.isFinite(args.seq) ? Math.trunc(args.seq) : undefined; + const offset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0; + const requested = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : settings.maxReadRecords; + const limit = Math.min(500, Math.max(1, requested)); + const result = await deps.store.readSession(sessionId, { ...(seq === undefined ? {} : { seq }), offset, limit }); + return { session_id: result.sessionId, total: result.total, items: result.items }; + }, + }; +} +function statusTool(deps) { + return { + name: 'memory_raw_status', + description: '查看原始记录层状态:保存目录、会话数、记录数、占用空间、最早/最新时间与保留天数。', + parameters: { type: 'object', properties: {}, additionalProperties: false }, + output: { + schema: { type: 'object', properties: {}, required: [], additionalProperties: true }, + render: renderJson, + }, + async execute() { + const settings = deps.settings(); + return deps.store.status(settings.enabled, settings.retentionDays); + }, + }; +} +/** Build the three raw-layer tools. */ +export function createRawMemoryTools(deps) { + return [searchTool(deps), readTool(deps), statusTool(deps)]; +} diff --git a/lib/raw-memory/types.js b/lib/raw-memory/types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/lib/raw-memory/types.js @@ -0,0 +1 @@ +export {}; diff --git a/lib/reporter.js b/lib/reporter.js index 92a52f2..8b9f013 100644 --- a/lib/reporter.js +++ b/lib/reporter.js @@ -311,7 +311,7 @@ export class Reporter { /** Take this turn's messages out of the buffer, capped by the char budget. */ takeTranscript(conversationId, turn) { const { picked } = this.partitionTranscript(conversationId, turn); - const maxChars = Math.max(1000, this.options.summary().maxChars); + const maxChars = this.options.summary().maxChars; let total = 0; const kept = []; for (const message of picked) { @@ -367,13 +367,13 @@ export class Reporter { const client = this.clientFor(context); const result = await client.submitSummary(payload, token); if (result.ok) { - this.summaryStaged += typeof result.data.staged === 'number' ? result.data.staged : 0; + this.summaryStaged += result.data.staged ?? 0; return; } if (result.error.status === 0 || result.error.status >= 500) { const retry = await client.submitSummary(payload, token); if (retry.ok) { - this.summaryStaged += typeof retry.data.staged === 'number' ? retry.data.staged : 0; + this.summaryStaged += retry.data.staged ?? 0; return; } } @@ -482,9 +482,8 @@ export class Reporter { // A queued entry belongs to the account that failed to send it. After a // token or endpoint switch the current credential must not replay old // records to (or as) a different account, so stale entries are dropped. + // The loop condition guarantees a head; no await runs between them. const head = this.queue[0]; - if (head === undefined) - break; if (head.scope !== scope) { this.queue.shift(); this.options.log(`dsh-brain: dropping queued turn report for a switched account: ${head.payload.turn_id}`); diff --git a/lib/routes.js b/lib/routes.js index 8ed7eca..28bfb7a 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -2,7 +2,7 @@ import { createSettingsUiRoutes } from "./settings-ui/routes.js"; import { serveDepartments } from "./settings-ui/departments-routes.js"; import { brainStatus, migrateLegacyFiles } from "./brain-migration.js"; import { mcpCapability } from "./mcp.js"; -import { fail, json, readBody, sameOrigin } from "./http.js"; +import { fail, json, jsonBody, readBody, sameOrigin } from "./http.js"; import { createCloudSyncRoutes, getLastCheck } from "./cloudsync-routes.js"; import { createSkillRoutes } from "./skills/routes.js"; /** Route constants — kept in one place so the client half can reuse them. */ @@ -121,31 +121,9 @@ function serveCapabilities(deps, req, res) { } /** `PUT /dsh-brain/config`. */ async function serveConfig(deps, req, res) { - if (req.method !== 'PUT' && req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); + const patch = await jsonBody(req, res); + if (patch === undefined) return; - } - if (!sameOrigin(req)) { - fail(res, 403, 'origin-rejected'); - return; - } - const type = (req.headers['content-type'] ?? '').toLowerCase(); - if (!type.startsWith('application/json')) { - fail(res, 415, 'json-required'); - return; - } - let patch; - try { - patch = JSON.parse(await readBody(req)); - } - catch (error) { - fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json'); - return; - } - if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { - fail(res, 400, 'invalid-patch'); - return; - } const result = deps.store.patch(patch); if (!result.ok) { fail(res, 400, result.error ?? 'invalid-patch'); diff --git a/lib/skill-admin.js b/lib/skill-admin.js index 9bfc204..85081ef 100644 --- a/lib/skill-admin.js +++ b/lib/skill-admin.js @@ -209,7 +209,7 @@ export class SkillAdmin { const source = await readSkillSourceRecord(dir); return { folder, - name: typeof name === 'string' && name !== '' ? name : folder, + name: name ?? folder, description: String(frontmatter.description ?? '').slice(0, 300), enabled, origin, @@ -484,7 +484,7 @@ export class SkillAdmin { const name = frontmatter.name; candidates.push({ folder: candidate.folder, - name: typeof name === 'string' && name !== '' ? name : candidate.folder, + name: name ?? candidate.folder, description: String(frontmatter.description ?? '').slice(0, 300), files: files.length, bytes, diff --git a/lib/skill-groups.js b/lib/skill-groups.js index 7b453cb..d8a4443 100644 --- a/lib/skill-groups.js +++ b/lib/skill-groups.js @@ -314,7 +314,8 @@ export class SkillGroupManager { catch { throw new SkillGroupError('not_found', `来源里没有这个技能:${folder}`); } - if (!stat.isDirectory() || stat.isSymbolicLink()) { + // lstat never reports a symlink as a directory, so this also rejects links. + if (!stat.isDirectory()) { throw new SkillGroupError('invalid_skill', `来源技能不是普通目录:${folder}`); } const rootReal = realpathSync(source.root); @@ -329,7 +330,8 @@ export class SkillGroupManager { catch { throw new SkillGroupError('invalid_skill', `来源技能缺少 SKILL.md:${folder}`); } - if (!marker.isFile() || marker.isSymbolicLink()) { + // lstat never reports a symlink as a regular file, so this also rejects links. + if (!marker.isFile()) { throw new SkillGroupError('invalid_skill', `来源技能的 SKILL.md 不是普通文件:${folder}`); } return this.deps.admin.importFolder(dirReal, folder); diff --git a/lib/skill-sync.js b/lib/skill-sync.js index ec07229..36de067 100644 --- a/lib/skill-sync.js +++ b/lib/skill-sync.js @@ -403,7 +403,8 @@ export class SkillSync { const listing = await client.listSkills(); if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`); - const items = (listing.data.items ?? []).filter((item) => typeof item.name === 'string' && CLOUD_SKILL_NAME.test(item.name)); + // validateSkillListing already guarantees items is an array of summaries with non-empty string names. + const items = listing.data.items.filter((item) => CLOUD_SKILL_NAME.test(item.name)); const cloudByName = new Map(items.map((item) => [item.name, item])); let stateDirty = false; // Self-heal: an uploaded folder whose delivery receipt reappeared (a @@ -451,8 +452,8 @@ export class SkillSync { continue; } const removed = state.removed[item.name]; - const uploaded = state.uploaded[item.name]; - const localFolder = uploaded?.folder ?? state.delivered[item.name]?.folder ?? item.name; + // Uploaded names were skipped above, so only a delivery receipt can name the folder here. + const localFolder = state.delivered[item.name]?.folder ?? item.name; const local = await repo.read(localFolder); const exists = local !== undefined; const delivery = local?.delivery; @@ -924,7 +925,7 @@ export class SkillSync { try { const listing = await active.client.listSkills(); if (listing.ok) - cloudItems = listing.data.items ?? []; + cloudItems = listing.data.items; } catch { // Offline: report local sides only, never throw the list away. @@ -1007,14 +1008,14 @@ export class SkillSync { const listing = await client.listSkills(); if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`); - const cloud = (listing.data.items ?? []).find((item) => item.name === name); + const cloud = listing.data.items.find((item) => item.name === name); const state = await this.loadState(scope); const localFolder = preview?.folder ?? state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name; const localNow = await repo.read(localFolder); const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n')); if (localVersionNow !== confirmed.localVersion) throw new Error('stale_conflict'); - if ((cloud?.revision ?? undefined) !== (confirmed.cloud?.revision ?? undefined) || (cloud?.manifest_sha256 ?? undefined) !== (confirmed.cloud?.manifest ?? undefined)) + if (cloud?.revision !== confirmed.cloud?.revision || cloud?.manifest_sha256 !== confirmed.cloud?.manifest) throw new Error('stale_conflict'); if (action === 'manual') { return { diff --git a/lib/skills/routes.js b/lib/skills/routes.js index db315a1..0b6faf8 100644 --- a/lib/skills/routes.js +++ b/lib/skills/routes.js @@ -342,10 +342,6 @@ async function serveClients(deps, req, res) { return; } if (suffix === '/workspaces/add') { - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); - return; - } const body = await jsonBody(req, res); if (body === undefined) return; @@ -354,10 +350,6 @@ async function serveClients(deps, req, res) { return; } if (suffix === '/workspaces/remove') { - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); - return; - } const body = await jsonBody(req, res); if (body === undefined) return; @@ -374,10 +366,6 @@ async function serveClients(deps, req, res) { return; } if (suffix === '/workspace/detail') { - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); - return; - } const body = await jsonBody(req, res); if (body === undefined) return; @@ -386,10 +374,6 @@ async function serveClients(deps, req, res) { return; } if (suffix === '/workspace/toggle') { - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); - return; - } const body = await jsonBody(req, res); if (body === undefined) return; @@ -398,10 +382,6 @@ async function serveClients(deps, req, res) { return; } if (suffix === '/workspace/remove') { - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); - return; - } const body = await jsonBody(req, res); if (body === undefined) return; @@ -412,10 +392,6 @@ async function serveClients(deps, req, res) { return; } if (suffix === '/workspace/install/plan') { - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); - return; - } const body = await jsonBody(req, res); if (body === undefined) return; @@ -424,10 +400,6 @@ async function serveClients(deps, req, res) { return; } if (suffix === '/workspace/install/commit') { - if (req.method !== 'POST') { - fail(res, 405, 'method-not-allowed'); - return; - } const body = await jsonBody(req, res); if (body === undefined) return; diff --git a/lib/store.js b/lib/store.js index 3bfe5f8..64cb191 100644 --- a/lib/store.js +++ b/lib/store.js @@ -275,9 +275,9 @@ export class SettingsStore { * marker blocks the env fallback until a new token is written. */ tokenFor(label, sidecar) { - if (sidecar !== undefined && sidecar !== '') + if (sidecar !== undefined) return sidecar; - if (this.state.clearedTokens?.includes(label) === true) + if (this.state.clearedTokens?.includes(label)) return ''; const envPrefix = label === 'activity' ? 'DSH_BRAIN_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_BRAIN_MEMORY_TOKEN' : 'DSH_BRAIN_SUMMARY_TOKEN'; const legacyPrefix = label === 'activity' ? 'DSH_CLOUD_MEMORY_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_CLOUD_MEMORY_MEMORY_TOKEN' : 'DSH_CLOUD_MEMORY_SUMMARY_TOKEN'; @@ -290,7 +290,7 @@ export class SettingsStore { } /** Which layer currently supplies each token (drives the card's hint). */ tokenSource(label, sidecar) { - if (sidecar !== undefined && sidecar !== '') + if (sidecar !== undefined) return 'sidecar'; if (this.tokenFor(label, sidecar) !== '') return 'env'; diff --git a/lib/tools.js b/lib/tools.js index df4c1bc..fc9dc2c 100644 --- a/lib/tools.js +++ b/lib/tools.js @@ -15,7 +15,7 @@ function skillListTool(deps) { const result = await deps.client().listSkills(); if (!result.ok) throw new Error(`技能列表读取失败:${describeError(result.error)}`); - const skills = (result.data.items ?? []).map((item) => ({ + const skills = result.data.items.map((item) => ({ name: item.name, description: item.description ?? '', revision: item.revision ?? null, diff --git a/lib/version.js b/lib/version.js index b399198..ffdb5a6 100644 --- a/lib/version.js +++ b/lib/version.js @@ -8,7 +8,7 @@ */ import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -const FALLBACK_VERSION = '0.10.2'; +const FALLBACK_VERSION = '0.10.3'; function readVersion() { try { const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')); diff --git a/package.json b/package.json index 0d07e16..b44c06e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-brain", - "version": "0.10.2", + "version": "0.10.3", "description": "Cloud memory for DSH: report one activity turn per conversation round and expose memory_search / memory_read / memory_add tools against a LongMemory cloud endpoint.", "type": "module", "license": "MIT", diff --git a/src/version.ts b/src/version.ts index 11fdffc..9411acf 100644 --- a/src/version.ts +++ b/src/version.ts @@ -9,7 +9,7 @@ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' -const FALLBACK_VERSION = '0.10.2' +const FALLBACK_VERSION = '0.10.3' function readVersion(): string { try {