sage-mem 2.24.0 → 2.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  **Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.**
14
14
 
15
- **Current release: `2.24.0`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
15
+ **Current release: `2.25.0`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
16
16
  [frozen contract](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md).
17
17
 
18
18
  If it is useful to you, a Star is the most direct feedback.
@@ -556,6 +556,39 @@ The **Initial memory** card at the top of Settings → Memory management → **L
556
556
  - It starts expanded on an empty library and collapsed on a full one; copying pops a reminder — the next step is yours.
557
557
  - Why this is not an install-time generator: see `docs/decisions.md` D46.
558
558
 
559
+ ## External access: let other agents read a copy (2.25.0)
560
+
561
+ You probably run other agents on this machine (Claude Code, Cursor, Codex, Cline and friends). They cannot see your memories, so every session starts with you re-explaining the background. This release ships the **read side**: whitelisted memories are incrementally exported into a copy under `<state dir>/mirror/`, and a **read-only** endpoint hands that copy out. Your library itself is never touched by them - they read the copy, and the copy can be rebuilt at any time.
562
+
563
+ It is **off** by default. Once enabled, point your local MCP config at `http://127.0.0.1:7461/mcp` (port configurable) - no token needed:
564
+
565
+ ```json
566
+ {
567
+ "mcpServers": {
568
+ "sage-mem": { "url": "http://127.0.0.1:7461/mcp" }
569
+ }
570
+ }
571
+ ```
572
+
573
+ It exposes three tools: `memory_search` (keyword search over the copy), `memory_read` (read one entry in full), `memory_list` (what is in there). The endpoint binds to `127.0.0.1` only, returns no absolute paths, and has **no write tool at all**.
574
+
575
+ ### Whitelist: project and reference only, by default
576
+
577
+ The exposed surface starts at its smallest setting: **`project_*` and `reference_*` only**. `user_*` (about you) and `feedback_*` (how I should work) stay private. Four granularities stack: prefix groups, `frontmatter.tags`, forced per-file include, forced per-file exclude. **The order is exclude > include > prefix > tag**, so unchecking one row in the panel wins over an enabled prefix group.
578
+
579
+ Export is incremental and self-healing: unchanged content is not rewritten, entries that leave the whitelist or disappear from the library are deleted from the copy, and a copy that some outside process mangled is overwritten on the next round. The copy has its own `MEMORY.md` that is **regenerated** rather than copied from your index - the real index lists the names of files you are not sharing. When the library cannot be read (disk offline, no permission, directory missing) the copy is left **byte for byte untouched** and the failure is reported, so one failed scan is never mistaken for an empty library.
580
+
581
+ Triggering is a 45 second poll plus a 10 second debounce on directory events, so the semantics are **eventual consistency**: an edit shows up in the copy after 10 to 55 seconds. The switch, the whitelist and the port are read on every round - changes take effect immediately, no restart.
582
+
583
+ | Setting | Default | Description |
584
+ |---|---|---|
585
+ | `external.enabled` | `0` (off) | Master switch. While off there is no watcher, no timer and no open port |
586
+ | `external.prefixes` | `["project_", "reference_"]` | Whole prefix groups; the panel shows four chips (`project_` / `reference_` / `user_` / `feedback_`) |
587
+ | `external.tags` | `[]` | Expose by `frontmatter.tags`; empty means no tag-based exposure |
588
+ | `external.port` | `7461` (1024-65535) | Read-only endpoint port, bound to `127.0.0.1`. If it is taken the endpoint reports why instead of drifting to another port |
589
+
590
+ **Out of scope on purpose**: the write side (an `intake/` area and a merger for incoming submissions) belongs to 2.26.0; there is no per-agent tiered permission model (ACLs are useless under one OS user, so visibility replaces permissions); there is no endpoint auth and no cross-machine access - use an SSH port forward if you need that.
591
+
559
592
  ## Configuration Reference
560
593
 
561
594
  ### Environment Variables
@@ -572,6 +605,8 @@ The **Initial memory** card at the top of Settings → Memory management → **L
572
605
  | `SAGE_MEM_TASK_ID` | empty | scope of task checkpoints; empty falls back to the session id |
573
606
  | `SAGE_MEM_DEBUG` | off | debug logging; when on, the panel's **工具 ▾ → 注入调试** shows the last 8 injection attempts (read-only, never written to disk; it also lists any memory kept out of the body by an expired `invalid_at` or an unresolved contradiction, with the reason and the conflict id) |
574
607
  | `SAGE_MEM_VALIDITY` | on | master switch for invalidity filtering and contradiction suppression. **Only `0` / `false` / `off` turn it off** (empty or misspelled values count as on); off restores the 1.9.x injection behaviour |
608
+ | `SAGE_MEM_EXTERNAL` | `0` (off) | external access (read side) master switch: `1` exports the copy and opens the read-only endpoint |
609
+ | `SAGE_MEM_EXTERNAL_PORT` | `7461` (1024-65535) | read-only MCP endpoint port, bound to `127.0.0.1` |
575
610
 
576
611
  Value semantics: **out-of-range values are clamped to the boundary, illegal values (including pure whitespace) fall back to the default.**
577
612
 
@@ -774,10 +809,17 @@ Or manually delete the `sage-mem` dependency from the profile's `package.json` a
774
809
 
775
810
  ## Credits
776
811
 
777
- - [@bjvgukv25842-cmyk](https://github.com/bjvgukv25842-cmyk) (LITMUS) — the earliest Web memory management UI; the memory management page started here.
778
- - [@miztizm](https://github.com/miztizm) (mjztjzm) — i18n for the memory panel: the dictionary shard and the `ctx.locale` wiring, so three screens follow the harness language (1.9.0).
779
- - [@DDDMUC](https://github.com/DDDMUC) — three things: the open-memory-folder entry in the file list; the short-circuit gate in the recall chain (2.4.3, the same question is no longer re-scored on every step); and `interpolate: false` on the recall context (2.4.2, a memory containing double braces no longer kills the whole turn).
780
- - [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) — the plugin host and the Cordis plugin system.
812
+ - [@bjvgukv25842-cmyk](https://github.com/bjvgukv25842-cmyk) (LITMUS) — the earliest Web memory management UI: pagination, type badges, expandable bodies, two-step delete confirmation, and the `get_observations` read path. **No build tooling was added to the repository** — it was hand-written to match the host's artifact format, and that trade-off still shapes the project.
813
+ - [@miztizm](https://github.com/miztizm) (mjztjzm) — i18n for the memory panel: the dictionary shard plus the `ctx.locale` wiring, so three screens follow the harness language (1.9.0). It became the template for every later i18n batch.
814
+ - [@DDDMUC](https://github.com/DDDMUC) — three fixes, each closing a failure that looked random:
815
+ - **`interpolate: false` on the recall context** (2.4.2): a memory body containing double braces made the host throw `malformed prompt variable reference` while assembling the prompt, so the turn failed before the model even started — it looked like "sometimes it chats, sometimes any question fails", depending on which memories that turn happened to recall.
816
+ - **A short-circuit gate in the recall chain** (2.4.3): `system-prompt/assemble` fires on every step, and the old implementation ran the whole "scan → summary scoring → body BM25 → signature" chain before deduplicating. The decision inputs are all available before scoring.
817
+ - **The "open memory folder" entry** (2.4.0): no more hunting for the path in a file manager.
818
+ - **[DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)** — not merely the host; this plugin's shape was forced by several of its designs:
819
+ - **Everything is a plugin, plus Cordis's service / event / fiber model** — file-based memory therefore needs no worker, port, or database;
820
+ - **`ctx.systemPrompt.section` and `agent/pre-step`** — injection and the pre-compaction reminder land on the right seams, instead of a prompt line saying "remember to read the files";
821
+ - **The typert remote protocol** — the type-safe channel between panel and host; the delete guard in 2.21.0 and the rollback guard in 2.22.0 both rely on it to carry "the version you confirmed" over to the host side;
822
+ - **The official docs (AGENTS.md / cordis-api / persistence)** — plugin authors can verify for themselves instead of guessing.
781
823
 
782
824
  This plugin is alive today because of more than one person; the list above follows the order their code entered the repository. If I missed someone, open an issue and tell me off — I will add them.
783
825
 
package/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  > File-based cross-session memory for DeepSeek Harness — every memory is a plain markdown file you can open, edit and delete. No database, no worker, no port.
16
16
 
17
- **当前发布版本:`2.24.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
17
+ **当前发布版本:`2.25.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
18
18
  [契约冻结](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md)。
19
19
 
20
20
  如果它对你有用,给个 Star 是最直接的反馈。
@@ -558,6 +558,39 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
558
558
  - 空库默认展开、老库默认收起;复制成功会弹一句提醒 —— 下一棒在你手里。
559
559
  - 为什么不做成「安装时自动写」:取舍记录见 `docs/decisions.md` D46。
560
560
 
561
+ ## 外部访问:让别的 agent 读一份副本(2.25.0)
562
+
563
+ 你机器上可能还跑着别的 agent(Claude Code、Cursor、Codex、Cline…)。它们看不见你的记忆,于是每次都要从零复述背景。这一版给的是**读侧**:把白名单内的记忆**增量导出**成一份副本,放在 `<状态目录>/mirror/`,再经一个**只读**端点给出去。主库一个字都不会被它们碰到 —— 读的是副本,副本可以随时重建。
564
+
565
+ 默认**关**着。打开之后,本机 MCP 配置里填 `http://127.0.0.1:7461/mcp`(端口可改)即可,不用 token:
566
+
567
+ ```json
568
+ {
569
+ "mcpServers": {
570
+ "sage-mem": { "url": "http://127.0.0.1:7461/mcp" }
571
+ }
572
+ }
573
+ ```
574
+
575
+ 它提供三个工具:`memory_search`(按词检索副本)、`memory_read`(读某条全文)、`memory_list`(有哪些)。端点只绑 `127.0.0.1`、不返回任何绝对路径、**没有任何写工具**。
576
+
577
+ ### 白名单:默认只给「项目」与「参考」
578
+
579
+ 暴露面默认是最小的那一档:**只开 `project_*` 与 `reference_*`**,`user_*`(关于你)与 `feedback_*`(我怎么工作)默认不给。四种粒度可以叠:按前缀整类、按 `frontmatter.tags`、逐条强制包含、逐条强制排除;**优先级是「逐条排除 > 逐条包含 > 前缀 > 标签」**,所以面板上取消一条勾选能压过「整类打开」。
580
+
581
+ 导出是增量且自愈的:内容没变就不写;退出白名单或主库删掉的条目会从副本里同步删除;副本被外面的进程改坏了,下一轮按主库覆盖。副本里的 `MEMORY.md` 是**重新生成**的,不是复制主库索引 —— 原索引列着你不给看的那些条目名。主库读不出来时(盘掉线、没权限、目录不存在)**一个字节都不动**,只报错,免得一次扫描失败就被当成「库空了」把副本清掉。
582
+
583
+ 触发是轮询 45 秒 + 目录事件 10 秒防抖,语义是**最终一致**:一条记忆改完,最快 10 秒、最慢约 55 秒才出现在副本里。开关、白名单、端口都是现读现用 —— 改完立刻生效,不用重启。
584
+
585
+ | 设置项 | 默认值 | 说明 |
586
+ |---|---|---|
587
+ | `external.enabled` | `0`(关) | 总开关。关着时不起 watcher、不起定时器、不开端口 |
588
+ | `external.prefixes` | `["project_", "reference_"]` | 按文件名前缀整类开放;面板上是四颗 chip(`project_` / `reference_` / `user_` / `feedback_`) |
589
+ | `external.tags` | `[]` | 按 frontmatter 的 `tags` 开放,留空表示不按标签开放 |
590
+ | `external.port` | `7461`(1024–65535) | 只读端点端口,只绑 `127.0.0.1`;被占用时端点报错并说明原因,不自动漂移 |
591
+
592
+ **明确不做**:写侧(外来提交的 `intake/` 与归并器)留给 2.26.0;不做「按 agent 分三档权限」(单用户同 SID 下 ACL 无效,改用「可见性」);不做端点鉴权和跨机器访问 —— 真要跨机器,走 SSH 端口转发。
593
+
561
594
  ## 配置参考
562
595
 
563
596
  ### 环境变量
@@ -574,6 +607,8 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
574
607
  | `SAGE_MEM_TASK_ID` | 空 | 任务检查点的作用域;空则回落会话 id |
575
608
  | `SAGE_MEM_DEBUG` | 关 | 调试日志;打开后面板「工具 ▾ → 注入调试」显示最近 8 次注入的账(只读、不落盘;同时列出被已失效标注 / 未裁决矛盾挡在正文外的记忆与理由,矛盾还带冲突 id) |
576
609
  | `SAGE_MEM_VALIDITY` | 开 | 失效过滤与矛盾抑制的总开关。**只认 `0` / `false` / `off` 为关闭**(空值、拼错都按开启);关掉后回到 1.9.x 的注入行为 |
610
+ | `SAGE_MEM_EXTERNAL` | `0`(关) | 外部访问(读侧)总开关:`1` 才导出副本并开只读端点 |
611
+ | `SAGE_MEM_EXTERNAL_PORT` | `7461`(1024–65535) | 只读 MCP 端点端口,只绑 `127.0.0.1` |
577
612
 
578
613
  取值语义:**越界夹到边界,非法值(含纯空格)回落默认。**
579
614
 
@@ -779,10 +814,17 @@ dsh plugin --profile web remove sage-mem
779
814
 
780
815
  ## 致谢
781
816
 
782
- - [@bjvgukv25842-cmyk](https://github.com/bjvgukv25842-cmyk)(LITMUS)—— 最早的 Web 记忆管理界面,记忆管理页从这一版开始。
783
- - [@miztizm](https://github.com/miztizm)(mjztjzm)—— 记忆管理面板的 i18n:字典分片、`ctx.locale` 接入,三屏跟随宿主语言(1.9.0)。
784
- - [@DDDMUC](https://github.com/DDDMUC)(暮迟)—— 三处:文件列表的「打开记忆文件夹」入口;注入链的短路闸门(2.4.3,同一个问题不再每一步重算);注入段声明 `interpolate: false`(2.4.2,记忆里写了双大括号不再让整轮对话崩掉)。
785
- - [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) —— 插件宿主与 Cordis 插件体系。
817
+ - [@bjvgukv25842-cmyk](https://github.com/bjvgukv25842-cmyk)(LITMUS)—— 最早的 Web 记忆管理界面:分页、类型徽章、展开正文、两步确认删除,以及 `get_observations` 这条读取通道。**没给仓库引入任何构建工具**,照着宿主产物的格式手写 —— 这个取舍一直影响到现在。
818
+ - [@miztizm](https://github.com/miztizm)(mjztjzm)—— 记忆管理面板的 i18n:字典分片 + `ctx.locale` 接线,三屏跟随宿主语言(1.9.0)。它是这个项目 i18n 的样板,后面几批照它的形状做。
819
+ - [@DDDMUC](https://github.com/DDDMUC)(暮迟)—— 三处,每处都堵掉一个「看起来像随机」的故障:
820
+ - **注入段声明 `interpolate: false`**(2.4.2):记忆正文里出现双大括号,宿主组装 prompt 时抛 `malformed prompt variable reference`,模型还没开始跑整轮就失败 —— 表现成「有时能聊、有时一提问就挂」,取决于这一轮召回到了哪些记忆。
821
+ - **注入链的短路闸门**(2.4.3):`system-prompt/assemble` 每个 step 都派发,旧实现每一步都把「扫描 → 摘要打分 → 正文 BM25 → 算签名」整条跑完再判重;而判据其实在打分之前就全拿得到。
822
+ - **「打开记忆文件夹」入口**(2.4.0):记忆目录不必再去文件管理器里翻路径。
823
+ - **[DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)** —— 不只是宿主;这个插件的形态是被它的几处设计逼出来的:
824
+ - **一切皆插件 + Cordis 的 service / event / fiber** —— 文件式记忆因此不必自带 worker、端口或数据库;
825
+ - **`ctx.systemPrompt.section` 与 `agent/pre-step`** —— 注入与压缩前提醒能挂在正确的接缝上,而不是靠 prompt 里写「记得读文件」;
826
+ - **typert 远程协议** —— 面板与宿主之间那条类型安全的通道;2.21.0 的删除守卫、2.22.0 的回滚守卫都靠它把「你确认过的那一版」带到宿主侧;
827
+ - **官方文档(AGENTS.md / cordis-api / persistence)** —— 让插件作者能自己查证,而不是猜。
786
828
 
787
829
  这个插件活到今天,靠的不只是我一个人。上面按代码进入仓库的顺序排。漏了谁的话开个 issue 骂我,我补上。
788
830
 
@@ -14,3 +14,6 @@ export { mountWriteGate } from './write-gate-mount.js'
14
14
  // 2.17.0:第五块挂载。它不参与上面四块的顺序语义(不碰写门、不碰工具注册窗口),
15
15
  // 只是两条事件监听 —— 所以排在最后,坏了也不影响前面任何一块。
16
16
  export { mountPreCompact } from './precompact-mount.js'
17
+ // 2.25.0:第六块挂载 —— 外部访问读侧(白名单导出 + 只读 MCP 端点)。它与前五块互不依赖:
18
+ // 只读主库、只写 `<状态根>/mirror/`,开关关着时一行都不跑(refresh 第一句就返回)。
19
+ export { mountMirror } from './mirror-mount.js'
@@ -0,0 +1,184 @@
1
+ /**
2
+ * mirror 的挂载(2.25.0)—— **只接线,不写业务**。
3
+ *
4
+ * 这一层回答三个问题,多一句都不该有:
5
+ * 1. **什么时候跑**:主库目录有事件(再防抖 10s)或轮询到点(默认 45s);
6
+ * 2. **跑谁**:`export.js` 的导出器(唯一写盘点),端点由 `mcp.js` 起停;
7
+ * 3. **现在什么状态**:给面板的一份 `status()`。
8
+ *
9
+ * 判据全在 `mirror/policy.js`,落盘全在 `mirror/export.js` —— 所以这一层坏了的后果是
10
+ * 「不跑」或「跑得晚」,不是「导出错东西」。
11
+ *
12
+ * 开关与白名单**现读现用**(不进 `restartRequired`):面板保存后由 `setSettings` 调 `refresh()`,
13
+ * 这里重读一遍设置、按需起停端点、立刻导出一轮;改完立刻生效。
14
+ */
15
+ import { MIRROR_DEBOUNCE_MS } from '../mirror/policy.js'
16
+ import { createMirrorExporter } from '../mirror/export.js'
17
+ import { createMirrorMcpServer } from '../mirror/mcp.js'
18
+ import { createDirWatcher } from '../memory/watch.js'
19
+ import { warnLog } from '../memory/util.js'
20
+
21
+ /**
22
+ * @param {object} ctx — 宿主上下文
23
+ * @param {object} opts
24
+ * @param {string} opts.memoryDir — 主库目录(只读)
25
+ * @param {string} opts.stateRoot — 状态根
26
+ * @param {() => Promise<{external:object, diagnostics:string[]}>} opts.readExternal — 读当前生效的外部访问设置
27
+ */
28
+ export function mountMirror(ctx, { memoryDir, stateRoot, readExternal }) {
29
+ const exporter = createMirrorExporter({ ctx, memoryDir, stateRoot })
30
+ const mcp = createMirrorMcpServer({ ctx, exporter })
31
+
32
+ /** 当前生效设置(null = 还没读过)。 */
33
+ let external = null
34
+ /** 端点用的端口(-1 = 没起过)。 */
35
+ let mcpPort = -1
36
+ let watcher = null
37
+ let pollTimer = null
38
+ let pollSeconds = 0
39
+ let debounceTimer = null
40
+ /** 最近一轮的结果(面板要的那份)。 */
41
+ let last = { at: 0, ok: true, exposed: 0, written: 0, unchanged: 0, deleted: 0, indexed: false, errors: [] }
42
+ /** 导出串行:一轮没跑完,后来的请求只置位,跑完再补一轮。 */
43
+ let running = false
44
+ let queued = false
45
+ let disposed = false
46
+
47
+ function clearDebounce() {
48
+ if (debounceTimer) {
49
+ clearTimeout(debounceTimer)
50
+ debounceTimer = null
51
+ }
52
+ }
53
+
54
+ /** 目录事件 → 10 秒防抖 → 跑一轮。第一次事件也等满窗口:导出的消费者不需要秒级。 */
55
+ function scheduleExport() {
56
+ if (disposed || !external?.enabled) return
57
+ clearDebounce()
58
+ debounceTimer = setTimeout(() => {
59
+ debounceTimer = null
60
+ runOnce().catch(() => {})
61
+ }, MIRROR_DEBOUNCE_MS)
62
+ if (typeof debounceTimer.unref === 'function') debounceTimer.unref()
63
+ }
64
+
65
+ function startWatcher() {
66
+ if (watcher) return
67
+ watcher = createDirWatcher(memoryDir, scheduleExport)
68
+ if (!watcher.ok) {
69
+ // 起不来不是错误:轮询仍在,只是延迟变大。如实记进状态里。
70
+ warnLog(ctx, `外部访问:主库目录监视起不来(${watcher.reason}),只靠轮询`)
71
+ }
72
+ }
73
+
74
+ function startPoll() {
75
+ const seconds = external?.pollSeconds ?? 45
76
+ if (pollTimer && pollSeconds === seconds) return
77
+ if (pollTimer) clearInterval(pollTimer)
78
+ pollSeconds = seconds
79
+ pollTimer = setInterval(() => {
80
+ runOnce().catch(() => {})
81
+ }, seconds * 1000)
82
+ if (typeof pollTimer.unref === 'function') pollTimer.unref()
83
+ }
84
+
85
+ function stopTimers() {
86
+ clearDebounce()
87
+ if (pollTimer) {
88
+ clearInterval(pollTimer)
89
+ pollTimer = null
90
+ pollSeconds = 0
91
+ }
92
+ if (watcher) {
93
+ watcher.dispose()
94
+ watcher = null
95
+ }
96
+ }
97
+
98
+ /** 跑一轮导出(串行;开关关着时什么都不做)。 */
99
+ async function runOnce() {
100
+ if (disposed || !external?.enabled) return last
101
+ if (running) {
102
+ queued = true
103
+ return last
104
+ }
105
+ running = true
106
+ try {
107
+ last = await exporter.run(external)
108
+ } catch (err) {
109
+ // `run()` 自己不抛;这里兜的是「连它都炸了」的意外(比如内存耗尽)。
110
+ last = { at: Date.now(), ok: false, exposed: 0, written: 0, unchanged: 0, deleted: 0, indexed: false, errors: [String(err?.message ?? err)] }
111
+ warnLog(ctx, `外部访问:导出一轮失败(${err?.message ?? err})`)
112
+ } finally {
113
+ running = false
114
+ if (queued) {
115
+ queued = false
116
+ setTimeout(() => { runOnce().catch(() => {}) }, 0).unref?.()
117
+ }
118
+ }
119
+ return last
120
+ }
121
+
122
+ /**
123
+ * 重读设置并按需起停。**幂等**:可以在任何时刻反复调(面板保存、启动、定时)。
124
+ */
125
+ async function refresh() {
126
+ if (disposed) return status()
127
+ let next
128
+ try {
129
+ next = (await readExternal()).external
130
+ } catch (err) {
131
+ warnLog(ctx, `外部访问:读设置失败,按「关闭」处理(${err?.message ?? err})`)
132
+ next = null
133
+ }
134
+ external = next ?? { ...(external ?? {}), enabled: 0 }
135
+ if (!external.enabled) {
136
+ stopTimers()
137
+ if (mcp.status().listening) await mcp.stop()
138
+ mcpPort = -1
139
+ return status()
140
+ }
141
+ startWatcher()
142
+ startPoll()
143
+ if (mcpPort !== external.port || !mcp.status().listening) {
144
+ await mcp.stop()
145
+ const started = await mcp.start(external.port)
146
+ mcpPort = started.listening ? started.port : -1
147
+ }
148
+ await runOnce()
149
+ return status()
150
+ }
151
+
152
+ /** 面板读的一份状态(不含任何记忆正文)。 */
153
+ function status() {
154
+ return {
155
+ enabled: external?.enabled ? 1 : 0,
156
+ mirrorDir: exporter.mirrorDir,
157
+ exposed: last.exposed,
158
+ // 当前暴露的**名字**:面板的逐条勾选直接用它判断「这条现在是不是给外面看」。
159
+ // 不在这里另算一遍白名单(那就是第二份判据),用的就是上一轮导出的结果。
160
+ exposedNames: Array.isArray(last.names) ? last.names.slice() : [],
161
+ lastExportAt: last.at,
162
+ lastOk: last.ok,
163
+ written: last.written,
164
+ unchanged: last.unchanged,
165
+ deleted: last.deleted,
166
+ indexed: last.indexed,
167
+ errors: Array.isArray(last.errors) ? last.errors.slice(0, 8) : [],
168
+ pollSeconds: external?.pollSeconds ?? 0,
169
+ watcher: watcher ? { ok: watcher.ok !== false, reason: watcher.reason ?? '' } : { ok: false, reason: '未启动' },
170
+ endpoint: mcp.status(),
171
+ }
172
+ }
173
+
174
+ /** 停掉一切(宿主卸载 / 关掉开关都会走到)。幂等。 */
175
+ async function dispose() {
176
+ if (disposed) return
177
+ disposed = true
178
+ stopTimers()
179
+ await mcp.stop()
180
+ mcpPort = -1
181
+ }
182
+
183
+ return { refresh, status, runOnce, dispose, exporter }
184
+ }