sage-mem 2.24.1 → 2.26.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.1`** — 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.26.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,71 @@ 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
+
592
+ ## Incoming submissions: other agents can submit, only you let them in (2.26.0)
593
+
594
+ The read side solved "they cannot see your memories"; this release solves the other direction: **how what they want to tell you gets in**. The answer is a queue, and you approve it entry by entry.
595
+
596
+ The endpoint gains one tool, `memory_submit` (the only write entry point it has). It does **not** write your library: the submission lands in `<state dir>/intake/agents/<source>/pending/` and shows up in the **Incoming submissions** card on the External access page. It is **off** by default: with `external.acceptSubmissions = 0` submissions are rejected outright - "can read the copy" and "can put things in" are two separate switches.
597
+
598
+ ```jsonc
599
+ // roughly what they send to memory_submit
600
+ { "kind": "new", "source": "claude-code",
601
+ "name": "project_tile-cache", "description": "Tile cache hit-rate findings",
602
+ "type": "project", "tags": ["tiles"], "body": "...markdown..." }
603
+ ```
604
+
605
+ Two kinds: `kind=new` is a complete new memory (`type` is limited to `project` / `reference`); `kind=patch` is an edit suggestion for an existing entry. Malformed submissions are rejected **at the entry point** and never reach the queue.
606
+
607
+ ### Only a new entry can be approved into the library
608
+
609
+ Each pending item carries a proposal in one of four states: **approvable** (a new name), **name conflict** (the library already has that name; reject it or ask for a rename), **needs a human** (an edit suggestion - you get a snippet to copy over), **not applicable** (a suggestion pointing at a memory that does not exist). Approval is an **exclusive create**: if the name is taken it reports a conflict and overwrites nothing.
610
+
611
+ `kind=patch` **never writes the library automatically** - a half-finished patch would destroy the target file. The panel offers a "Copy suggestion" button that copies just the "suggested" section, not the whole patch.
612
+
613
+ Rejecting **does not delete**: the original stays in `intake/agents/<source>/rejected/`, and the reason goes into the report and the audit log (`intake/audit.jsonl`, one line each).
614
+
615
+ | Setting | Default | Description |
616
+ |---|---|---|
617
+ | `external.acceptSubmissions` | `0` (off) | Whether submissions are accepted. While off `memory_submit` is rejected; anything already queued can still be reviewed |
618
+ | Submission size | body <= 32 KB / whole item <= 64 KB | Larger is rejected at the entry point; the body may not carry its own frontmatter |
619
+ | Allowed types | `project` / `reference` | Other agents cannot write `user_*` or `feedback_*` - those are about you, only the main session writes them |
620
+ | After a rejection | original kept in `rejected/` | Never deleted; an approved original is removed, but its full text is already in the report |
621
+
622
+ **Out of scope on purpose**: model-driven auto-merging, automatic rename deduplication, bulk approval (clicking one at a time is the physical guarantee behind "approve first, write later"); `intake/devices/` (cross-device) belongs to 4.0.0.
623
+
559
624
  ## Configuration Reference
560
625
 
561
626
  ### Environment Variables
@@ -572,6 +637,9 @@ The **Initial memory** card at the top of Settings → Memory management → **L
572
637
  | `SAGE_MEM_TASK_ID` | empty | scope of task checkpoints; empty falls back to the session id |
573
638
  | `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
639
  | `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 |
640
+ | `SAGE_MEM_EXTERNAL` | `0` (off) | external access (read side) master switch: `1` exports the copy and opens the read-only endpoint |
641
+ | `SAGE_MEM_EXTERNAL_PORT` | `7461` (1024-65535) | read-only MCP endpoint port, bound to `127.0.0.1` |
642
+ | `SAGE_MEM_EXTERNAL_SUBMIT` | `0` (off) | whether submissions are accepted (`memory_submit`); a separate switch from the one above |`n| `SAGE_MEM_EXTERNAL_SUBMIT` | `0` (off) | whether submissions are accepted (`memory_submit`); a separate switch from the one above |
575
643
 
576
644
  Value semantics: **out-of-range values are clamped to the boundary, illegal values (including pure whitespace) fall back to the default.**
577
645
 
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.1`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
17
+ **当前发布版本:`2.26.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,71 @@ 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
+
594
+ ## 外部来件:别的 agent 能提交,进不进库你说了算(2.26.0)
595
+
596
+ 读侧解决「它们看不见你的记忆」,这一版解决反方向:**它们想告诉你的事,怎么进来**。答案是只收进队列,主库由你一条条批。
597
+
598
+ 端点多了一个工具 `memory_submit`(全端点唯一的写入口)。它**不会**直接写你的记忆库 —— 提交落进 `<状态目录>/intake/agents/<来源>/pending/`,你在「外部访问」页的**外部来件**卡里逐条审。默认**关**:`external.acceptSubmissions = 0` 时提交直接被拒(「能不能读副本」与「能不能往里塞东西」是两个开关)。
599
+
600
+ ```jsonc
601
+ // 它们调用 memory_submit 时大概是这个形状
602
+ { "kind": "new", "source": "claude-code",
603
+ "name": "project_tile-cache", "description": "瓦片缓存的命中率结论",
604
+ "type": "project", "tags": ["瓦片"], "body": "……正文……" }
605
+ ```
606
+
607
+ 两种提交:`kind=new` 是一条完整新记忆(`type` 只许 `project` / `reference`);`kind=patch` 是对现有条目的修改建议。格式不对**在入口就拒**,连队列都进不去。
608
+
609
+ ### 只有「新条目」能被批准落库
610
+
611
+ 面板上每条来件带一个提案,四种:**可批准**(新名字)、**同名冲突**(主库已有同名,只能拒绝或让它改名重提)、**需人工**(修改建议,只给一段「建议」让你复制过去)、**不建议收**(修改建议指向一条不存在的记忆)。批准是**排他创建**:同名文件在你就报冲突,一个字节都不覆盖。
612
+
613
+ `kind=patch` **永远不自动写主库** —— 半成品直接落盘会毁掉目标文件。面板给的是「复制建议」按钮,复制的是「建议改成」那一段,不是整份 patch。
614
+
615
+ 拒绝**不删**:原件留在 `intake/agents/<来源>/rejected/`,理由进报告与审计(`intake/audit.jsonl` 一行一条)。
616
+
617
+ | 设置项 | 默认值 | 说明 |
618
+ |---|---|---|
619
+ | `external.acceptSubmissions` | `0`(不收) | 收不收外来提交。关着时 `memory_submit` 直接拒,已收到的照样能审 |
620
+ | 提交体积 | 正文 ≤ 32 KB / 整条 ≤ 64 KB | 超了在入口就拒;正文不许自带 frontmatter |
621
+ | 允许的类型 | `project` / `reference` | 外来 agent 写不了 `user_*` 与 `feedback_*` —— 那是关于你本人的,只有主会话能写 |
622
+ | 拒绝之后 | 原件留 `rejected/` | 不删;批准的原件删掉,但全文已进报告 |
623
+
624
+ **明确不做**:模型参与的自动归并、自动改名去重、批量批准(一条条点,才是「先批后写」的物理保证);`intake/devices/`(跨设备)留给 4.0.0。
625
+
561
626
  ## 配置参考
562
627
 
563
628
  ### 环境变量
@@ -574,6 +639,9 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
574
639
  | `SAGE_MEM_TASK_ID` | 空 | 任务检查点的作用域;空则回落会话 id |
575
640
  | `SAGE_MEM_DEBUG` | 关 | 调试日志;打开后面板「工具 ▾ → 注入调试」显示最近 8 次注入的账(只读、不落盘;同时列出被已失效标注 / 未裁决矛盾挡在正文外的记忆与理由,矛盾还带冲突 id) |
576
641
  | `SAGE_MEM_VALIDITY` | 开 | 失效过滤与矛盾抑制的总开关。**只认 `0` / `false` / `off` 为关闭**(空值、拼错都按开启);关掉后回到 1.9.x 的注入行为 |
642
+ | `SAGE_MEM_EXTERNAL` | `0`(关) | 外部访问(读侧)总开关:`1` 才导出副本并开只读端点 |
643
+ | `SAGE_MEM_EXTERNAL_PORT` | `7461`(1024–65535) | 只读 MCP 端点端口,只绑 `127.0.0.1` |
644
+ | `SAGE_MEM_EXTERNAL_SUBMIT` | `0`(不收) | 收不收外来提交(`memory_submit`)。与上一个开关是两件事 |
577
645
 
578
646
  取值语义:**越界夹到边界,非法值(含纯空格)回落默认。**
579
647
 
@@ -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,195 @@
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 { createIntakeStore } from '../intake/store.js'
20
+ import { createIntakeMerger } from '../intake/merge.js'
21
+ import { warnLog } from '../memory/util.js'
22
+
23
+ /**
24
+ * @param {object} ctx — 宿主上下文
25
+ * @param {object} opts
26
+ * @param {string} opts.memoryDir — 主库目录(只读)
27
+ * @param {string} opts.stateRoot — 状态根
28
+ * @param {() => Promise<{external:object, diagnostics:string[]}>} opts.readExternal — 读当前生效的外部访问设置
29
+ */
30
+ export function mountMirror(ctx, { memoryDir, stateRoot, readExternal }) {
31
+ const exporter = createMirrorExporter({ ctx, memoryDir, stateRoot })
32
+ // 2.26.0 写侧:提交只进 intake/,归并器只出提案;两者都不在主库之外自己写主库。
33
+ const store = createIntakeStore({ ctx, stateRoot })
34
+ const merger = createIntakeMerger({ ctx, memoryDir, store })
35
+ /** 当前生效设置(null = 还没读过)。 */
36
+ let external = null
37
+
38
+ const mcp = createMirrorMcpServer({
39
+ ctx,
40
+ exporter,
41
+ // 开关现读现用(与读侧同一个 external 段):关着时 memory_submit 直接拒。
42
+ intake: { store, acceptSubmissions: () => !!(external && external.acceptSubmissions) },
43
+ })
44
+
45
+ /** 端点用的端口(-1 = 没起过)。 */
46
+ let mcpPort = -1
47
+ let watcher = null
48
+ let pollTimer = null
49
+ let pollSeconds = 0
50
+ let debounceTimer = null
51
+ /** 最近一轮的结果(面板要的那份)。 */
52
+ let last = { at: 0, ok: true, exposed: 0, written: 0, unchanged: 0, deleted: 0, indexed: false, errors: [] }
53
+ /** 导出串行:一轮没跑完,后来的请求只置位,跑完再补一轮。 */
54
+ let running = false
55
+ let queued = false
56
+ let disposed = false
57
+
58
+ function clearDebounce() {
59
+ if (debounceTimer) {
60
+ clearTimeout(debounceTimer)
61
+ debounceTimer = null
62
+ }
63
+ }
64
+
65
+ /** 目录事件 → 10 秒防抖 → 跑一轮。第一次事件也等满窗口:导出的消费者不需要秒级。 */
66
+ function scheduleExport() {
67
+ if (disposed || !external?.enabled) return
68
+ clearDebounce()
69
+ debounceTimer = setTimeout(() => {
70
+ debounceTimer = null
71
+ runOnce().catch(() => {})
72
+ }, MIRROR_DEBOUNCE_MS)
73
+ if (typeof debounceTimer.unref === 'function') debounceTimer.unref()
74
+ }
75
+
76
+ function startWatcher() {
77
+ if (watcher) return
78
+ watcher = createDirWatcher(memoryDir, scheduleExport)
79
+ if (!watcher.ok) {
80
+ // 起不来不是错误:轮询仍在,只是延迟变大。如实记进状态里。
81
+ warnLog(ctx, `外部访问:主库目录监视起不来(${watcher.reason}),只靠轮询`)
82
+ }
83
+ }
84
+
85
+ function startPoll() {
86
+ const seconds = external?.pollSeconds ?? 45
87
+ if (pollTimer && pollSeconds === seconds) return
88
+ if (pollTimer) clearInterval(pollTimer)
89
+ pollSeconds = seconds
90
+ pollTimer = setInterval(() => {
91
+ runOnce().catch(() => {})
92
+ }, seconds * 1000)
93
+ if (typeof pollTimer.unref === 'function') pollTimer.unref()
94
+ }
95
+
96
+ function stopTimers() {
97
+ clearDebounce()
98
+ if (pollTimer) {
99
+ clearInterval(pollTimer)
100
+ pollTimer = null
101
+ pollSeconds = 0
102
+ }
103
+ if (watcher) {
104
+ watcher.dispose()
105
+ watcher = null
106
+ }
107
+ }
108
+
109
+ /** 跑一轮导出(串行;开关关着时什么都不做)。 */
110
+ async function runOnce() {
111
+ if (disposed || !external?.enabled) return last
112
+ if (running) {
113
+ queued = true
114
+ return last
115
+ }
116
+ running = true
117
+ try {
118
+ last = await exporter.run(external)
119
+ } catch (err) {
120
+ // `run()` 自己不抛;这里兜的是「连它都炸了」的意外(比如内存耗尽)。
121
+ last = { at: Date.now(), ok: false, exposed: 0, written: 0, unchanged: 0, deleted: 0, indexed: false, errors: [String(err?.message ?? err)] }
122
+ warnLog(ctx, `外部访问:导出一轮失败(${err?.message ?? err})`)
123
+ } finally {
124
+ running = false
125
+ if (queued) {
126
+ queued = false
127
+ setTimeout(() => { runOnce().catch(() => {}) }, 0).unref?.()
128
+ }
129
+ }
130
+ return last
131
+ }
132
+
133
+ /**
134
+ * 重读设置并按需起停。**幂等**:可以在任何时刻反复调(面板保存、启动、定时)。
135
+ */
136
+ async function refresh() {
137
+ if (disposed) return status()
138
+ let next
139
+ try {
140
+ next = (await readExternal()).external
141
+ } catch (err) {
142
+ warnLog(ctx, `外部访问:读设置失败,按「关闭」处理(${err?.message ?? err})`)
143
+ next = null
144
+ }
145
+ external = next ?? { ...(external ?? {}), enabled: 0 }
146
+ if (!external.enabled) {
147
+ stopTimers()
148
+ if (mcp.status().listening) await mcp.stop()
149
+ mcpPort = -1
150
+ return status()
151
+ }
152
+ startWatcher()
153
+ startPoll()
154
+ if (mcpPort !== external.port || !mcp.status().listening) {
155
+ await mcp.stop()
156
+ const started = await mcp.start(external.port)
157
+ mcpPort = started.listening ? started.port : -1
158
+ }
159
+ await runOnce()
160
+ return status()
161
+ }
162
+
163
+ /** 面板读的一份状态(不含任何记忆正文)。 */
164
+ function status() {
165
+ return {
166
+ enabled: external?.enabled ? 1 : 0,
167
+ mirrorDir: exporter.mirrorDir,
168
+ exposed: last.exposed,
169
+ // 当前暴露的**名字**:面板的逐条勾选直接用它判断「这条现在是不是给外面看」。
170
+ // 不在这里另算一遍白名单(那就是第二份判据),用的就是上一轮导出的结果。
171
+ exposedNames: Array.isArray(last.names) ? last.names.slice() : [],
172
+ lastExportAt: last.at,
173
+ lastOk: last.ok,
174
+ written: last.written,
175
+ unchanged: last.unchanged,
176
+ deleted: last.deleted,
177
+ indexed: last.indexed,
178
+ errors: Array.isArray(last.errors) ? last.errors.slice(0, 8) : [],
179
+ pollSeconds: external?.pollSeconds ?? 0,
180
+ watcher: watcher ? { ok: watcher.ok !== false, reason: watcher.reason ?? '' } : { ok: false, reason: '未启动' },
181
+ endpoint: mcp.status(),
182
+ }
183
+ }
184
+
185
+ /** 停掉一切(宿主卸载 / 关掉开关都会走到)。幂等。 */
186
+ async function dispose() {
187
+ if (disposed) return
188
+ disposed = true
189
+ stopTimers()
190
+ await mcp.stop()
191
+ mcpPort = -1
192
+ }
193
+
194
+ return { refresh, status, runOnce, dispose, exporter, intake: { store, merger } }
195
+ }