dsh-feiyu-memgate 0.3.2 → 0.4.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.
Files changed (103) hide show
  1. package/CHANGELOG.md +73 -12
  2. package/README.md +68 -11
  3. package/README.zh.md +93 -36
  4. package/client/README.md +267 -0
  5. package/client/art/mascot-asleep.webp +0 -0
  6. package/client/art/mascot-busy.webp +0 -0
  7. package/client/art/mascot-nag.webp +0 -0
  8. package/client/art/mascot-ready.webp +0 -0
  9. package/client/art/mascot-trouble.webp +0 -0
  10. package/client/client.js +4226 -1269
  11. package/client/src/clipboard.cjs +52 -0
  12. package/client/src/constants.cjs +43 -0
  13. package/client/src/fields.cjs +960 -0
  14. package/client/src/hooks.cjs +220 -0
  15. package/client/src/i18n.cjs +444 -0
  16. package/client/src/index.cjs +69 -0
  17. package/client/src/kit/controls.cjs +189 -0
  18. package/client/src/kit/icons.cjs +40 -0
  19. package/client/src/kit/layout.cjs +124 -0
  20. package/client/src/layout.cjs +143 -0
  21. package/client/src/model/changelog.cjs +29 -0
  22. package/client/src/model/feedback.cjs +168 -0
  23. package/client/src/model/form.cjs +83 -0
  24. package/client/src/model/models.cjs +87 -0
  25. package/client/src/model/overview.cjs +111 -0
  26. package/client/src/model/page.cjs +104 -0
  27. package/client/src/model/status.cjs +57 -0
  28. package/client/src/model/trial.cjs +111 -0
  29. package/client/src/net.cjs +101 -0
  30. package/client/src/react.cjs +11 -0
  31. package/client/src/theme/page.css +1284 -0
  32. package/client/src/theme/styles.cjs +43 -0
  33. package/client/src/view/feedback.cjs +180 -0
  34. package/client/src/view/field-row.cjs +98 -0
  35. package/client/src/view/hero.cjs +54 -0
  36. package/client/src/view/markdown.cjs +96 -0
  37. package/client/src/view/models.cjs +154 -0
  38. package/client/src/view/page.cjs +199 -0
  39. package/client/src/view/settings-tab.cjs +78 -0
  40. package/client/src/view/tabs.cjs +71 -0
  41. package/client/src/view/trial.cjs +84 -0
  42. package/docs/DETAIL.en.md +55 -6
  43. package/docs/DETAIL.md +63 -14
  44. package/locale/zh.json +1 -1
  45. package/package.json +2 -1
  46. package/python/GATEWAY_VERSION.json +37 -31
  47. package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
  48. package/python/feiyu_memgate/backends/base.py +121 -6
  49. package/python/feiyu_memgate/backends/embedding.py +265 -178
  50. package/python/feiyu_memgate/backends/hybrid.py +330 -83
  51. package/python/feiyu_memgate/backends/inmemory.py +115 -24
  52. package/python/feiyu_memgate/backends/openviking.py +7 -10
  53. package/python/feiyu_memgate/backends/sqlite.py +129 -145
  54. package/python/feiyu_memgate/builtins.py +1 -0
  55. package/python/feiyu_memgate/cli.py +124 -20
  56. package/python/feiyu_memgate/client/block.py +4 -2
  57. package/python/feiyu_memgate/client/http.py +106 -19
  58. package/python/feiyu_memgate/client/local.py +4 -3
  59. package/python/feiyu_memgate/config.py +118 -24
  60. package/python/feiyu_memgate/core/limits.py +2 -1
  61. package/python/feiyu_memgate/core/pool.py +29 -2
  62. package/python/feiyu_memgate/core/recall.py +179 -10
  63. package/python/feiyu_memgate/core/redact.py +4 -2
  64. package/python/feiyu_memgate/core/stages.py +52 -9
  65. package/python/feiyu_memgate/core/tidy.py +2 -1
  66. package/python/feiyu_memgate/core/watch.py +3 -2
  67. package/python/feiyu_memgate/core/write.py +9 -3
  68. package/python/feiyu_memgate/forgetting/archive.py +38 -10
  69. package/python/feiyu_memgate/forgetting/engine.py +46 -10
  70. package/python/feiyu_memgate/forgetting/stage.py +4 -2
  71. package/python/feiyu_memgate/gateway/app.py +168 -272
  72. package/python/feiyu_memgate/gateway/fields.py +121 -0
  73. package/python/feiyu_memgate/gateway/policies.py +162 -0
  74. package/python/feiyu_memgate/gateway/server.py +12 -4
  75. package/python/feiyu_memgate/gateway/tokens.py +137 -0
  76. package/python/feiyu_memgate/gateway/validate.py +120 -0
  77. package/python/feiyu_memgate/identity.py +152 -0
  78. package/python/feiyu_memgate/model.py +170 -2
  79. package/python/feiyu_memgate/registry.py +6 -3
  80. package/python/feiyu_memgate/tools/crypto.py +5 -4
  81. package/python/feiyu_memgate/tools/evaluate.py +2 -1
  82. package/python/feiyu_memgate/tools/tenants.py +2 -0
  83. package/src/block.js +9 -3
  84. package/src/capture.js +98 -0
  85. package/src/catalogue.js +4 -4
  86. package/src/changelog.js +72 -0
  87. package/src/client.js +145 -10
  88. package/src/commands.js +112 -62
  89. package/src/config.js +139 -62
  90. package/src/followup.js +139 -0
  91. package/src/gateway.js +79 -4
  92. package/src/migrate.py +54 -9
  93. package/src/mirror.py +44 -7
  94. package/src/plugin.js +416 -412
  95. package/src/pool.js +298 -0
  96. package/src/recent.js +68 -0
  97. package/src/relevance.js +80 -0
  98. package/src/routes.js +320 -0
  99. package/src/setup.js +36 -36
  100. package/src/shared.js +77 -0
  101. package/src/tiers.js +4 -4
  102. package/src/time.js +27 -0
  103. package/src/tools.js +164 -0
package/src/config.js CHANGED
@@ -23,45 +23,56 @@ import { TIER_CHOICES, TIERS } from './tiers.js'
23
23
 
24
24
  const VOLATILE_WRITE = Symbol.for('cosmokit.volatile.write') // vendor/cosmokit/src/volatile.ts, isVolatile()
25
25
 
26
- const bool = (key, value, label, help) => ({ key, kind: 'boolean', default: value, label, help })
26
+ // `extra` carries the optional attributes described above GROUPS (needs, unit, experimental).
27
+ const bool = (key, value, label, help, extra) => ({ key, kind: 'boolean', default: value, label, help, ...extra })
27
28
 
28
29
  // One row per field, in form order. kind: boolean | integer | choice | string.
30
+ // Optional attributes describe a setting to the settings page; the schema, readConfig() and
31
+ // parseSetting() do not use them:
32
+ // needs: { key: '<group>.<field>', in: [values] }
33
+ // the field has an effect only while that other setting holds one of these values (a boolean
34
+ // or one of its choice options); the page can fold or dim the field otherwise. A chain of
35
+ // needs is allowed, a loop is not.
36
+ // unit: { en, zh }
37
+ // a short word shown after the number of an integer field ("memories", "ms").
38
+ // experimental: true
39
+ // a boolean switch that is measured offline only; the page marks it.
29
40
  const GROUPS = [
30
41
  {
31
42
  key: 'modules',
32
43
  label: { en: 'Features', zh: '功能' },
33
44
  help: {
34
45
  en: 'Each feature is switched on or off on its own; a switched-off feature leaves nothing behind in the host.',
35
- zh: '每项功能单独开关;关掉的功能不会在宿主里留下任何东西。',
46
+ zh: '各项功能可单独开关;关闭的功能不会在宿主中留下任何内容。',
36
47
  },
37
48
  fields: [
38
49
  bool('autoRecall', true, { en: 'Automatic recall', zh: '自动召回' }, {
39
50
  en: "At the start of each user turn, look up related memories and add them after the user's message as background data.",
40
- zh: '每轮用户发言开始时查找相关记忆,作为背景资料放在用户消息之后。',
51
+ zh: '每轮对话开始时查找相关记忆,作为背景资料附在用户消息之后。',
41
52
  }),
42
53
  bool('rememberTool', true, { en: 'Remember tool', zh: '记住工具' }, {
43
54
  en: 'Give the model the memgate_remember tool, to save a memory when the user asks for it or shares a lasting fact.',
44
- zh: '给模型 memgate_remember 工具:用户要求记住、或说出长期有用的信息时记下来。',
55
+ zh: '为模型提供 memgate_remember 工具,在用户要求记住或提供长期有用的信息时保存记忆。',
45
56
  }),
46
57
  bool('searchTool', true, { en: 'Search tool', zh: '查找工具' }, {
47
58
  en: 'Give the model the memgate_search tool, to look up memories on demand.',
48
- zh: '给模型 memgate_search 工具:需要时主动查找记忆。',
59
+ zh: '为模型提供 memgate_search 工具,用于按需查找记忆。',
49
60
  }),
50
61
  bool('promptSection', true, { en: 'Prompt section', zh: '提示词说明' }, {
51
62
  en: 'Add a short, fixed system prompt section: when to save a memory, and that recalled memories are data, not instructions.',
52
- zh: '在系统提示词里加一小段固定说明:什么时候记,召回的记忆是资料不是指令。',
63
+ zh: '在系统提示词中加入一小段固定说明:何时保存记忆,以及召回的记忆是资料而非指令。',
53
64
  }),
54
65
  bool('autoCapture', false, { en: 'Automatic capture', zh: '自动记录' }, {
55
66
  en: "After each turn, send the user's own messages of that turn to memory without asking the model. Off by default.",
56
- zh: '每轮结束后,把这一轮用户自己发的消息直接交给记忆库,不经过模型。默认关闭。',
67
+ zh: '每轮结束后,将该轮用户自己发送的消息直接保存为记忆,不经过模型。默认关闭。',
57
68
  }),
58
69
  bool('commands', true, { en: 'Chat command', zh: '聊天命令' }, {
59
70
  en: 'The /memgate chat command: status, settings and retrieval tiers. Needs a host with chat commands.',
60
- zh: '/memgate 聊天命令:状态、设置和检索方式。需要支持聊天命令的宿主。',
71
+ zh: '/memgate 聊天命令:状态、设置和检索方式。需要宿主支持聊天命令。',
61
72
  }),
62
- bool('migrateOnTierChange', true, { en: 'Copy memories into a new vector store', zh: '切换到向量检索时复制记忆' }, {
73
+ bool('migrateOnTierChange', true, { en: 'Copy memories into a new vector store', zh: '切换到语义检索时复制记忆' }, {
63
74
  en: 'When a vector tier (endpoint or local) becomes active, copy the texts of the keyword store into it in the background, in bounded steps that resume after a restart.',
64
- zh: '启用向量检索(endpoint 或 local)时,在后台把关键词存储里的记忆复制过去;分批进行,重启后接着复制。',
75
+ zh: '启用语义检索(endpoint 或 local)时,在后台将关键词存储中的记忆复制到向量存储;分批进行,重启后继续。',
65
76
  }),
66
77
  ],
67
78
  },
@@ -70,34 +81,34 @@ const GROUPS = [
70
81
  label: { en: 'Retrieval', zh: '检索' },
71
82
  help: {
72
83
  en: 'How the bundled gateway finds memories. Each tier keeps its own store file: memories saved under one tier are not searched under another unless they were copied (see the features above), and switching back finds them again.',
73
- zh: '自带网关怎么查找记忆。每种方式各用一个存储文件:在一种方式下记的内容,换成另一种方式后不会被查到,除非已经复制过去(见上面的功能开关);切回来还能找到。',
84
+ zh: '内置网关查找记忆的方式。每种方式使用各自的存储文件:在一种方式下保存的记忆,切换到另一种方式后不会被检索到,除非已复制过去(见上方的功能设置);切换回来后可再次检索到。',
74
85
  },
75
86
  fields: [
76
87
  { key: 'tier', kind: 'choice', default: 'auto',
77
88
  options: TIER_CHOICES.map((name) => ({
78
89
  value: name,
79
90
  label: name === 'auto'
80
- ? { en: 'auto: local when the embedding add-on is ready, else keyword', zh: 'auto:本地向量插件就绪时用 local,否则用 keyword' }
91
+ ? { en: 'auto: local when the embedding add-on is ready, else keyword', zh: 'auto:本地向量插件就绪时使用 local,否则使用 keyword' }
81
92
  : { en: `${name}: ${TIERS[name].label.en}`, zh: `${name}:${TIERS[name].label.zh}` },
82
93
  })),
83
94
  label: { en: 'Retrieval tier', zh: '检索方式' },
84
95
  help: {
85
96
  en: 'auto uses local while the dsh-feiyu-memgate-embed add-on has a model ready, and keyword otherwise.',
86
- zh: 'auto:dsh-feiyu-memgate-embed 插件的模型就绪时用 local,否则用 keyword。',
97
+ zh: 'auto:dsh-feiyu-memgate-embed 插件的模型就绪时使用 local,否则使用 keyword。',
87
98
  } },
88
- bool('hybrid', false, { en: 'Combine with keyword search (hybrid)', zh: '同时用关键词检索(混合)' }, {
99
+ bool('hybrid', false, { en: 'Combine with keyword search (hybrid)', zh: '同时使用关键词检索(混合检索)' }, {
89
100
  en: 'Applies to the vector tiers (endpoint, local, and auto while it resolves to local); under keyword it does nothing. Keyword and vector search are both asked and their results fused. It uses the same vector store file as the tier without it, plus a keyword index file next to it, so switching it on or off loses no memory.',
90
- zh: '用于向量检索(endpoint、local,以及 auto 选到 local 的时候);在 keyword 下不起作用。关键词检索和向量检索同时查,结果合并。它用的向量存储文件和不开它时相同,旁边多一个关键词索引文件,所以开或关都不会丢记忆。',
91
- }),
92
- { key: 'url', kind: 'string', default: '', format: 'url',
101
+ zh: '适用于语义检索(endpoint、local,以及 auto 选择 local 时);在 keyword 下无效。同时进行关键词检索和语义检索,并合并结果。使用的向量存储文件与不开启时相同,另在其旁增加一个关键词索引文件,因此开启或关闭都不会丢失记忆。',
102
+ }, { needs: { key: 'retrieval.tier', in: ['auto', 'endpoint', 'local'] } }),
103
+ { key: 'url', kind: 'string', default: '', format: 'url', needs: { key: 'retrieval.tier', in: ['endpoint'] },
93
104
  label: { en: 'Endpoint URL', zh: '向量接口地址' },
94
105
  help: { en: 'endpoint tier: base URL of an OpenAI-compatible embeddings API, for example http://127.0.0.1:11434/v1.', zh: 'endpoint 方式:OpenAI 兼容向量接口的基础地址,例如 http://127.0.0.1:11434/v1。' } },
95
- { key: 'model', kind: 'string', default: '',
106
+ { key: 'model', kind: 'string', default: '', needs: { key: 'retrieval.tier', in: ['endpoint'] },
96
107
  label: { en: 'Endpoint model', zh: '向量模型' },
97
- help: { en: 'endpoint tier: the embeddings model name. A different model starts a new, empty store.', zh: 'endpoint 方式:向量模型的名字。换模型会用一个新的空存储。' } },
98
- { key: 'apiKey', kind: 'string', default: '', secret: true,
108
+ help: { en: 'endpoint tier: the embeddings model name. A different model starts a new, empty store.', zh: 'endpoint 方式:向量模型的名称。更换模型会使用新的空存储。' } },
109
+ { key: 'apiKey', kind: 'string', default: '', secret: true, needs: { key: 'retrieval.tier', in: ['endpoint'] },
99
110
  label: { en: 'Endpoint API key', zh: '向量接口密钥' },
100
- help: { en: 'endpoint tier: the API key of the embeddings endpoint, if it needs one. It is never shown again after saving.', zh: 'endpoint 方式:向量接口的密钥(需要的话)。保存后不再显示。' } },
111
+ help: { en: 'endpoint tier: the API key of the embeddings endpoint, if it needs one. It is never shown again after saving.', zh: 'endpoint 方式:向量接口的密钥(如需要)。保存后不再显示。' } },
101
112
  ],
102
113
  },
103
114
  {
@@ -105,35 +116,35 @@ const GROUPS = [
105
116
  label: { en: 'Gateway', zh: '网关' },
106
117
  help: {
107
118
  en: 'Where memories are kept: the bundled gateway (managed) or a gateway you run yourself (external).',
108
- zh: '记忆放在哪里:插件自带的网关(managed),或你自己运行的网关(external)。',
119
+ zh: '记忆的存放位置:插件内置的网关(managed),或自行运行的外部网关(external)。',
109
120
  },
110
121
  fields: [
111
122
  { key: 'mode', kind: 'choice', default: 'managed',
112
123
  options: [
113
- { value: 'managed', label: { en: 'managed: start the bundled gateway (needs Python 3.11 or newer)', zh: 'managed:启动自带的网关(需要 Python 3.11 或更新)' } },
114
- { value: 'external', label: { en: 'external: use a running gateway (see External gateway)', zh: 'external:使用已经在运行的网关(见“外部网关”)' } },
124
+ { value: 'managed', label: { en: 'managed: start the bundled gateway (needs Python 3.11 or newer)', zh: 'managed:启动内置网关(需要 Python 3.11 或更高版本)' } },
125
+ { value: 'external', label: { en: 'external: use a running gateway (see External gateway)', zh: 'external:使用已在运行的网关(见“外部网关”)' } },
115
126
  ],
116
127
  label: { en: 'Gateway mode', zh: '网关模式' },
117
- help: { en: 'managed starts the gateway that ships with the plugin; external talks to the address under External gateway.', zh: 'managed 启动插件自带的网关;external 连接“外部网关”里填写的地址。' } },
118
- { key: 'python', kind: 'string', default: '',
128
+ help: { en: 'managed starts the gateway that ships with the plugin; external talks to the address under External gateway.', zh: 'managed 启动插件内置的网关;external 连接“外部网关”中填写的地址。' } },
129
+ { key: 'python', kind: 'string', default: '', needs: { key: 'gateway.mode', in: ['managed'] },
119
130
  label: { en: 'Python interpreter', zh: 'Python 解释器' },
120
- help: { en: "managed: the Python to use (3.11 or newer). Empty: the desktop app's bundled Python, then python3, python and py -3.", zh: 'managed:使用哪个 Python(3.11 或更新)。留空:先用桌面版自带的 Python,再找 python3、python、py -3。' } },
121
- { key: 'dataDir', kind: 'string', default: '',
131
+ help: { en: "managed: the Python to use (3.11 or newer). Empty: the desktop app's bundled Python, then python3, python and py -3.", zh: 'managed:使用的 Python(3.11 或更高版本)。留空:依次使用桌面版内置的 Python、python3、python、py -3。' } },
132
+ { key: 'dataDir', kind: 'string', default: '', needs: { key: 'gateway.mode', in: ['managed'] },
122
133
  label: { en: 'Data folder', zh: '数据文件夹' },
123
- help: { en: 'managed: the folder for the memory stores, the generated gateway configuration and its log. Empty: data/feiyu-memgate in the DSH home folder.', zh: 'managed:存放记忆库、生成的网关配置和日志的文件夹。留空:DSH 主目录下的 data/feiyu-memgate。' } },
134
+ help: { en: 'managed: the folder for the memory stores, the generated gateway configuration and its log. Empty: data/feiyu-memgate in the DSH home folder.', zh: 'managed:存放记忆存储、生成的网关配置和日志的文件夹。留空:DSH 主目录下的 data/feiyu-memgate。' } },
124
135
  ],
125
136
  },
126
137
  {
127
138
  key: 'external',
128
139
  label: { en: 'External gateway', zh: '外部网关' },
129
- help: { en: 'Used only in external mode.', zh: '只在 external 模式下使用。' },
140
+ help: { en: 'Used only in external mode.', zh: '仅在 external 模式下使用。' },
130
141
  fields: [
131
- { key: 'url', kind: 'string', default: '', format: 'url',
142
+ { key: 'url', kind: 'string', default: '', format: 'url', needs: { key: 'gateway.mode', in: ['external'] },
132
143
  label: { en: 'Gateway URL', zh: '网关地址' },
133
144
  help: { en: 'The gateway address, for example http://127.0.0.1:8080.', zh: '网关地址,例如 http://127.0.0.1:8080。' } },
134
- { key: 'token', kind: 'string', default: '', secret: true,
145
+ { key: 'token', kind: 'string', default: '', secret: true, needs: { key: 'gateway.mode', in: ['external'] },
135
146
  label: { en: 'Client token', zh: '客户端令牌' },
136
- help: { en: 'The client token that gateway issued for this client. It is never shown again after saving.', zh: '那个网关给这个客户端的令牌。保存后不再显示。' } },
147
+ help: { en: 'The client token that gateway issued for this client. It is never shown again after saving.', zh: '该网关为此客户端签发的令牌。保存后不再显示。' } },
137
148
  ],
138
149
  },
139
150
  {
@@ -141,15 +152,15 @@ const GROUPS = [
141
152
  label: { en: 'Advanced', zh: '高级' },
142
153
  help: {
143
154
  en: 'Recall details and the rules of the bundled gateway (the rules apply to managed mode only; an external gateway follows its own configuration).',
144
- zh: '召回细节和自带网关的规则(规则只用于 managed 模式;外部网关按它自己的配置)。',
155
+ zh: '召回细节和内置网关的规则(规则仅用于 managed 模式;外部网关按其自身配置)。',
145
156
  },
146
157
  fields: [
147
- { key: 'recallLimit', kind: 'integer', default: 5, min: 1, max: 10,
158
+ { key: 'recallLimit', kind: 'integer', default: 8, min: 1, max: 10, unit: { en: 'memories', zh: '条' },
148
159
  label: { en: 'Memories per turn', zh: '每轮记忆条数' },
149
- help: { en: 'Most memories added per turn (1 to 10); also the default number of memgate_search results.', zh: '每轮最多加入几条记忆(1 到 10),也是 memgate_search 默认返回的条数。' } },
150
- { key: 'recallTimeoutMs', kind: 'integer', default: 4000, min: 500, max: 20000,
160
+ help: { en: 'Most memories added per turn (1 to 10); also the default number of memgate_search results.', zh: '每轮最多加入的记忆条数(1 到 10),也是 memgate_search 默认返回的条数。' } },
161
+ { key: 'recallTimeoutMs', kind: 'integer', default: 4000, min: 500, max: 20000, unit: { en: 'ms', zh: '毫秒' },
151
162
  label: { en: 'Recall time limit (ms)', zh: '召回等待上限(毫秒)' },
152
- help: { en: 'How long a turn waits for automatic recall (500 to 20000 ms). A slower lookup is skipped for that turn.', zh: '每轮最多等自动召回多少毫秒(500 到 20000)。超时的话这一轮不加记忆。' } },
163
+ help: { en: 'How long a turn waits for automatic recall (500 to 20000 ms). A slower lookup is skipped for that turn.', zh: '每轮等待自动召回的最长时间(500 到 20000 毫秒)。超时则该轮不加入记忆。' } },
153
164
  { key: 'language', kind: 'choice', default: 'auto',
154
165
  options: [
155
166
  { value: 'auto', label: { en: 'auto: follow the system language', zh: 'auto:跟随系统语言' } },
@@ -157,49 +168,115 @@ const GROUPS = [
157
168
  { value: 'en', label: { en: 'en: English', zh: 'en:英文' } },
158
169
  ],
159
170
  label: { en: 'Language', zh: '语言' },
160
- help: { en: 'Language of the memory block, the tool replies and the /memgate command.', zh: '记忆块、工具回复和 /memgate 命令用的语言。' } },
161
- bool('skipRepeats', true, { en: 'Skip repeated memories', zh: '不重复给同一条记忆' }, {
171
+ help: { en: 'Language of the memory block, the tool replies and the /memgate command.', zh: '记忆块、工具回复和 /memgate 命令使用的语言。' } },
172
+ bool('skipRepeats', true, { en: 'Skip repeated memories', zh: '不重复提供同一条记忆' }, {
162
173
  en: 'Leave out a memory that an earlier memory block of this conversation still shows, compared by its text. If nothing new is left, no block is added. Off: only a block identical to the previous one is left out.',
163
- zh: '这个对话里前面的记忆块还留着的记忆,不再给第二次(按记忆的文字比较)。没有新的就不加记忆块。关掉:只有和上一个记忆块完全相同时才不加。',
174
+ zh: '本对话中,之前的记忆块仍包含的记忆不再重复提供(按记忆的文字比较)。没有新记忆时不加入记忆块。关闭:仅当与上一个记忆块完全相同时才不加入。',
164
175
  }),
165
- bool('linkedRecall', true, { en: 'Recall linked memories', zh: '顺带想起相连的记忆' }, {
166
- en: 'With vector retrieval (the endpoint and local tiers, with or without retrieval.hybrid), after the usual lookup the gateway follows the first two memories it found to the memories closest to them and adds at most two, never beyond advanced.recallLimit. Under keyword retrieval it does nothing.',
167
- zh: '用向量检索时(endpoint 和 local 两档,开不开 retrieval.hybrid 都一样),网关在平常的查找之后,顺着找到的前两条记忆去找和它们最接近的记忆,最多再加两条,总数不超过 advanced.recallLimit。用 keyword 检索时什么都不做。',
176
+ bool('linkedRecall', true, { en: 'Recall linked memories', zh: '召回相关联的记忆' }, {
177
+ en: 'With vector retrieval (the endpoint and local tiers, with or without retrieval.hybrid), after the usual lookup the gateway follows the first two memories it found to the memories closest to them and adds at most two, never beyond advanced.recallLimit. Under keyword retrieval it does nothing, and with advanced.profile set to precise it adds nothing.',
178
+ zh: '使用语义检索时(endpoint 和 local 两档,是否开启 retrieval.hybrid 均适用),网关在常规检索之后,以找到的前两条记忆为起点查找与它们最接近的记忆,最多再加入两条,总数不超过 advanced.recallLimit。使用 keyword 检索时无效;advanced.profile 为 precise 时也不加入。',
168
179
  }),
169
- bool('showAge', true, { en: "Show today's date and each memory's age", zh: '写明今天的日期和每条记忆的时间' }, {
180
+ bool('showAge', true, { en: "Show today's date and each memory's age", zh: '显示今天的日期和每条记忆的时间' }, {
170
181
  en: "The memory block says today's date (the date on this computer) and how long ago each dated memory is, for example 3 weeks ago. Off: the block shows only the absolute dates.",
171
- zh: '记忆块里写明今天的日期(这台电脑上的日期),以及每条有日期的记忆是多久以前的事,例如“3 周前”。关掉:只写具体日期。',
182
+ zh: '记忆块中写明今天的日期(本机日期),以及每条带日期的记忆距今多久,例如“3 周前”。关闭:只写具体日期。',
172
183
  }),
173
184
  bool('failureNote', true, { en: 'Tell the model when recall failed', zh: '召回失败时告诉模型' }, {
174
185
  en: 'When the lookup of a turn times out, fails, or the bundled gateway is still starting, add one short note after the user message, so the model does not take it for "no related memory". Only on the first turn of a failure streak.',
175
- zh: '这一轮的查询超时、出错,或者自带网关还在启动时,在用户消息之后加一行说明,免得模型当作“没有相关记忆”。连续失败时只在第一轮加。',
186
+ zh: '本轮检索超时、出错,或内置网关仍在启动时,在用户消息之后加一行说明,避免模型误认为“没有相关记忆”。连续失败时仅在第一轮加入。',
176
187
  }),
177
- { key: 'captureMinChars', kind: 'integer', default: 4, min: 0, max: 50,
178
- label: { en: 'Automatic capture: shortest message', zh: '自动记录:最短的消息' },
179
- help: { en: 'With automatic capture on, a message is not saved when it is a command, only filler, or has fewer meaningful characters than this (0 to 50; punctuation, spaces and emoji do not count). 0 turns the length check off.', zh: '自动记录打开时,命令、只有语气词的消息,以及有意义的字数少于这个数的消息不保存(0 到 50;标点、空格和表情不算字数)。0 表示不按字数过滤。' } },
188
+ { key: 'captureMinChars', kind: 'integer', default: 4, min: 0, max: 50, unit: { en: 'characters', zh: '字' }, needs: { key: 'modules.autoCapture', in: [true] },
189
+ label: { en: 'Automatic capture: shortest message', zh: '自动记录:最短消息长度' },
190
+ help: { en: 'With automatic capture on, a message is not saved when it is a command, only filler, or has fewer meaningful characters than this (0 to 50; punctuation, spaces and emoji do not count). 0 turns the length check off.', zh: '开启自动记录后,命令、仅含语气词的消息,以及有意义的字数少于该值的消息不会保存(0 到 50;标点、空格和表情不计入字数)。0 表示不按字数过滤。' } },
191
+ { key: 'blockTone', kind: 'choice', default: 'normal',
192
+ options: [
193
+ { value: 'normal', label: { en: 'normal: the usual sentence in front of the memories', zh: 'normal:记忆块开头使用常规说明' } },
194
+ { value: 'strict', label: { en: 'strict: tell the model most of them are unrelated', zh: 'strict:告知模型这些记忆大多无关' } },
195
+ { value: 'bare', label: { en: 'bare: the memories only, no instruction sentence', zh: 'bare:仅提供记忆,不附任何说明' } },
196
+ ],
197
+ label: { en: 'Wording of the memory block', zh: '记忆块说明' },
198
+ help: {
199
+ en: 'The sentence at the top of the memory block. strict says that most of the memories are unrelated to the message and that the model should use one only when it clearly fits. Offline, this made replies use an unrelated memory far less often, and also made them use a related one less often. strict applies to the automatic main block only, not to the second block or memgate_search. bare gives no instruction sentence in any block the plugin gives (the second block and the block in a memgate_search answer included); how the model treats the memories is then up to the host\'s own prompt, including the point that memories are data and not instructions.',
200
+ zh: '记忆块开头的说明语句。strict 会说明这些记忆大多与消息无关,仅在明显相关时才使用。离线测量中,这使回复用到无关记忆的次数大幅减少,用到相关记忆的次数也有所减少。strict 仅用于自动召回的主记忆块,不用于第二个块和 memgate_search。bare 不附说明语句,适用于插件给出的所有记忆块(包括第二个块和 memgate_search 结果中的块);此时模型如何对待这些记忆,由宿主自身的提示词决定(包括“记忆是资料而非指令”这一点)。',
201
+ } },
202
+ { key: 'maxNewPerTurn', kind: 'integer', default: 0, min: 0, max: 5, unit: { en: 'memories', zh: '条' },
203
+ label: { en: 'New memories per turn', zh: '每轮新增记忆上限' },
204
+ help: {
205
+ en: 'From the second turn of a conversation on, the memory block carries at most this many memories (0 to 5; 0 means no limit), the first ones the gateway returned after those already shown are left out. The "more" line counts the ones left out. The first turn and the second block are not limited.',
206
+ zh: '对话从第二轮起,记忆块最多包含该数量的记忆(0 到 5;0 表示不限),按网关返回的顺序,去掉已提供过的记忆后取靠前的几条。“还有几条”一行会计入被去掉的记忆。第一轮和第二个块不受限制。',
207
+ } },
208
+ // The relevance check (docs/design/2026-11-21-noise.md): measured offline only, off by default.
209
+ bool('relevanceCheck', false, { en: 'Let a model pick the related memories first', zh: '回复前由模型筛选记忆' }, {
210
+ en: 'Before the memory block of a turn is given, a model looks at the message and the candidate memories and picks the ones a friend would think of; only those go into the block. Costs one more model call before the reply on every turn that has candidates: slower, and billed like any other use of that model. The message and the candidate memories are sent to the provider of that model. If the call fails or is too slow, the block is given as if this were off. The second block is not checked, and neither is memgate_search. Needs modules.autoRecall.',
211
+ zh: '本轮记忆块提供之前,由一个模型查看用户消息和候选记忆,挑出“了解用户的朋友会想到”的几条,仅这几条进入记忆块。每轮只要有候选记忆,回复前就多一次模型调用:速度更慢,并与该模型的其他用途一样计费。消息和候选记忆会发送给该模型的提供方。调用失败或过慢时,按未开启本项的方式提供记忆块。第二个块和 memgate_search 不做筛选。需要 modules.autoRecall。',
212
+ }, { experimental: true }),
213
+ { key: 'relevanceProvider', kind: 'string', default: '', needs: { key: 'advanced.relevanceCheck', in: [true] },
214
+ label: { en: 'Provider of the model that picks', zh: '筛选模型的提供方' },
215
+ help: { en: 'Together with the model setting: names another provider and model for the check, for example a cheaper one. Both empty means the model of the conversation. Only one of the two set counts as both empty.', zh: '与“筛选模型”一起填写:为这一步指定另一个提供方和模型,例如费用更低的。两项都留空表示使用对话本身的模型。只填其中一项等同于两项都留空。' } },
216
+ { key: 'relevanceModel', kind: 'string', default: '', needs: { key: 'advanced.relevanceCheck', in: [true] },
217
+ label: { en: 'Model that picks', zh: '筛选模型' },
218
+ help: { en: 'Together with the provider setting. Both empty means the model of the conversation.', zh: '与“筛选模型的提供方”一起填写。两项都留空表示使用对话本身的模型。' } },
219
+ { key: 'relevanceTimeoutMs', kind: 'integer', default: 3000, min: 500, max: 10000, unit: { en: 'ms', zh: '毫秒' }, needs: { key: 'advanced.relevanceCheck', in: [true] },
220
+ label: { en: 'Time limit of the check (ms)', zh: '筛选时限(毫秒)' },
221
+ help: { en: 'With the check on: how long the pick may take (500 to 10000 ms). A slower one is given up and the block is given as if the check were off.', zh: '开启筛选后:该步骤最长等待时间(500 到 10000 毫秒)。超时则放弃,按未开启筛选的方式提供记忆块。' } },
222
+ // Prototypes, off by default (docs/design/2026-11-18-recall-with-a-model.md): measured offline only.
223
+ bool('afterthought', false, { en: 'Recall again after replying', zh: '回复后再次召回' }, {
224
+ en: "Experimental. After each reply, look memories up once more in the background with the reply as the query, and give the ones this conversation has not had yet on the next turn, in a second block after the memory block. Costs one more lookup per turn; the added block makes the context longer, and it may hold memories unrelated to the new message. Under keyword retrieval the second lookup matches words of the reply. Needs modules.autoRecall.",
225
+ zh: '实验性功能。每次回复之后,在后台以该回复为查询词再检索一次记忆,将本对话中尚未提供过的记忆,在下一轮放入记忆块之后的第二个块中。每轮多一次检索;多出的块会使上下文变长,其中可能包含与新消息无关的记忆。使用 keyword 检索时,第二次检索匹配的是回复中的词。需要 modules.autoRecall。',
226
+ }, { experimental: true }),
227
+ { key: 'afterthoughtMax', kind: 'integer', default: 2, min: 1, max: 5, unit: { en: 'memories', zh: '条' }, needs: { key: 'advanced.afterthought', in: [true] },
228
+ label: { en: 'Memories a second lookup may add', zh: '回复后再次召回的条数上限' },
229
+ help: { en: 'With advanced.afterthought on: the most memories one second lookup keeps for the next turn (1 to 5).', zh: '开启“回复后再次召回”后:一次再次检索最多留给下一轮的记忆条数(1 到 5)。' } },
230
+ bool('conversationPool', false, { en: 'Conversation pool', zh: '对话池' }, {
231
+ en: 'Experimental. Remember in memory what this conversation was given. When the host has compacted the history and those memory blocks are gone, give the few that were still in play once more, in a second block after the memory block. A memory stays in play for about five turns after it was given, longer when your messages or the replies of the model keep using it. The block makes the context longer and may hold memories unrelated to the new message. Nothing is written to disk. Needs modules.autoRecall.',
232
+ zh: '实验性功能。在内存中记录本对话提供过哪些记忆。宿主压缩历史、原有记忆块消失后,将仍在讨论中的几条再提供一次,放在记忆块之后的第二个块中。一条记忆提供后约五轮内视为仍在讨论中,若你的消息或模型的回复持续用到它,则时间更长。多出的块会使上下文变长,其中可能包含与新消息无关的记忆。不写入磁盘。需要 modules.autoRecall。',
233
+ }, { experimental: true }),
234
+ { key: 'poolSize', kind: 'integer', default: 3, min: 1, max: 5, unit: { en: 'memories', zh: '条' }, needs: { key: 'advanced.conversationPool', in: [true] },
235
+ label: { en: 'Memories the pool brings back', zh: '对话池每次带回的条数' },
236
+ help: { en: 'With advanced.conversationPool on: the most memories the pool brings back in one turn (1 to 5).', zh: '开启“对话池”后:每轮最多带回的记忆条数(1 到 5)。' } },
237
+ bool('recentPool', false, { en: 'Recent pool', zh: '近期池' }, {
238
+ en: 'Experimental. When a new conversation starts, give once, at its first turn, the memories the previous conversation was still using, in a second block after the memory block. To do that a small file (recent-pool.json) with those memories is kept in the data folder. Switching this off deletes the file. The block makes the context longer and may hold memories unrelated to the new message. Needs modules.autoRecall.',
239
+ zh: '实验性功能。新对话开始时,在其第一轮提供一次上一个对话仍在使用的记忆,放在记忆块之后的第二个块中。为此会在数据文件夹中保存一个小文件(recent-pool.json),内含这几条记忆。关闭本项会删除该文件。多出的块会使上下文变长,其中可能包含与新消息无关的记忆。需要 modules.autoRecall。',
240
+ }, { experimental: true }),
241
+ { key: 'recentSize', kind: 'integer', default: 3, min: 1, max: 5, unit: { en: 'memories', zh: '条' }, needs: { key: 'advanced.recentPool', in: [true] },
242
+ label: { en: 'Memories the recent pool carries', zh: '近期池每次带入的条数' },
243
+ help: { en: 'With advanced.recentPool on: the most memories carried into a new conversation (1 to 5).', zh: '开启“近期池”后:带入新对话的记忆最多条数(1 到 5)。' } },
244
+ { key: 'recentDays', kind: 'integer', default: 7, min: 1, max: 30, unit: { en: 'days', zh: '天' }, needs: { key: 'advanced.recentPool', in: [true] },
245
+ label: { en: 'Days the recent pool is kept', zh: '近期池保留天数' },
246
+ help: { en: 'With advanced.recentPool on: a saved conversation older than this many days is not carried into a new one (1 to 30).', zh: '开启“近期池”后:保存的对话超过该天数,就不再带入新对话(1 到 30)。' } },
180
247
  // broad is the default since 0.2.0, like the gateway's own default: in a chat a topic usually touches
181
248
  // several memories. The block stays in the history, so precise is there for those who want less context.
182
249
  { key: 'profile', kind: 'choice', default: 'broad',
183
250
  options: [
184
- { value: 'broad', label: { en: 'broad: more memories per turn, misses less, more noise', zh: 'broad:每轮条数多,漏得少,杂讯也多' } },
185
- { value: 'precise', label: { en: 'precise: about one memory per turn, closer matches, misses more', zh: 'precise:每轮约一条,更贴题,漏得也多' } },
251
+ { value: 'broad', label: { en: 'broad: more memories per turn, misses less, more noise', zh: 'broad:每轮条数较多,遗漏少,噪声多' } },
252
+ { value: 'precise', label: { en: 'precise: about one memory per turn, closer matches, misses more', zh: 'precise:每轮约一条,更贴题,遗漏较多' } },
186
253
  ],
187
254
  label: { en: 'Recall profile', zh: '召回档位' },
188
- help: { en: 'How strict the gateway is about what counts as related. The memory block stays in the conversation, so broad makes the context grow faster.', zh: '网关判断“相关”的严格程度。记忆块会留在对话里,broad 会让上下文涨得更快。' } },
189
- { key: 'dailyWrites', kind: 'integer', default: 50, min: 0, max: 100000,
255
+ help: { en: 'How strict the gateway is about what counts as related. The memory block stays in the conversation, so broad makes the context grow faster.', zh: '网关判断“相关”的严格程度。记忆块会保留在对话中,broad 会使上下文增长更快。' } },
256
+ { key: 'dailyWrites', kind: 'integer', default: 50, min: 0, max: 100000, unit: { en: 'per day', zh: '条/天' }, needs: { key: 'gateway.mode', in: ['managed'] },
190
257
  label: { en: 'Daily write cap', zh: '每日写入上限' },
191
- help: { en: 'Most memories the gateway accepts per day; 0 means no cap. The count starts again whenever the gateway restarts.', zh: '网关每天最多收下几条记忆;0 表示不限。网关重启后重新计数。' } },
192
- bool('redaction', true, { en: 'Redact secrets', zh: '去掉秘密' }, {
258
+ help: { en: 'Most memories the gateway accepts per day; 0 means no cap. The count starts again whenever the gateway restarts.', zh: '网关每天最多接收的记忆条数;0 表示不限。网关重启后重新计数。' } },
259
+ bool('redaction', true, { en: 'Redact secrets', zh: '屏蔽敏感信息' }, {
193
260
  en: 'Remove secrets such as keys, tokens and passwords from memories when they are saved and when they are recalled.',
194
- zh: '保存和召回记忆时去掉密钥、令牌、密码这类秘密。',
195
- }),
196
- bool('newerFirst', true, { en: 'Newer first', zh: '新的优先' }, {
261
+ zh: '保存和召回记忆时,清除其中的密钥、令牌、密码等敏感信息。',
262
+ }, { needs: { key: 'gateway.mode', in: ['managed'] } }),
263
+ bool('newerFirst', true, { en: 'Newer first', zh: '较新的优先' }, {
197
264
  en: 'Among nearly equal matches, put newer memories first.',
198
- zh: '相关度差不多时,较新的记忆排在前面。',
199
- }),
265
+ zh: '相关度相近时,较新的记忆排在前面。',
266
+ }, { needs: { key: 'gateway.mode', in: ['managed'] } }),
200
267
  bool('forgetting', false, { en: 'Forgetting curve', zh: '遗忘曲线' }, {
201
268
  en: 'Memories unused for a long time rank lower and are eventually archived and removed (at most a few per day). Archived memories stay in the data folder for 90 days.',
202
- zh: '很久没用到的记忆排得更靠后,最终存档并删除(每天最多几条)。存档的记忆在数据文件夹里保留 90 天。',
269
+ zh: '长期未被使用的记忆排名靠后,最终会被存档并删除(每天最多几条)。存档的记忆在数据文件夹中保留 90 天。',
270
+ }, { needs: { key: 'gateway.mode', in: ['managed'] } }),
271
+ { key: 'speakerAccount', kind: 'string', default: 'dsh:local',
272
+ label: { en: 'Speaker account', zh: '说话人账号' },
273
+ help: {
274
+ en: "The account the plugin reports to the gateway with every write and recall, written dsh:name (lower-case letters, digits and _ . -). The bundled gateway maps it to the owner. With an external gateway that other programs share, list this account in the gateway's table of people.",
275
+ zh: '插件每次写入和召回时向网关报告的账号,写成 dsh:名字(小写字母、数字和 _ . -)。内置网关把它对应到所有者。使用外部网关并与别的程序共用时,把这个账号写进网关的对照表。',
276
+ } },
277
+ bool('toolFields', false, { en: 'Kind and event date on the memory tool', zh: '记忆工具可填写类型和日期' }, {
278
+ en: "When on, the memgate_remember tool takes two more optional arguments, the kind of the memory (identity, preference, event, plan, entity) and the date of the event, filled in by the model and stored with the memory. When off, the tool's arguments are exactly as before.",
279
+ zh: '开启后,memgate_remember 工具多两个可选参数:记忆的类型(身份、偏好、事件、计划、实体)和事情发生的日期,由模型填写,和记忆一起保存。关闭时工具的参数和以前完全一样。',
203
280
  }),
204
281
  ],
205
282
  },
@@ -0,0 +1,139 @@
1
+ // The second lookup (advanced.afterthought): at the end of a turn the reply is the query of one more
2
+ // lookup, whose finds are kept for the next turn (src/pool.js offers them). Also where the end of a turn
3
+ // settles the conversation pool and the recent pool, and where a session's state is dropped when the
4
+ // session goes. Fire and forget; the lookups it has running are its own and are all stopped by
5
+ // stopLookups(). Logs name kinds of failure only, never a reply, a query or a memory.
6
+ import { buildQuery } from './query.js'
7
+ import * as pool from './pool.js'
8
+ import { FORM_NOTICE, isObject, isSubagent, isUserOrigin, kindOf, REQUEST_CONTEXT, sessionIdOf, SOURCE_KIND, speakerAccount, textOf, within } from './shared.js'
9
+
10
+ /**
11
+ * @param {object} deps
12
+ * @param {object} deps.chat the conversation pool (pool.createPool()), shared with the turn's recall
13
+ * @param {Function} deps.client client(limit): a gateway client, or null while memory is unavailable
14
+ * @param {Function} deps.settings the current settings
15
+ * @param {Function} deps.formatter formatter(lang): the block formatter (seen() recognises blocks)
16
+ * @param {object} deps.log { warn, info }
17
+ * @param {Function} deps.isDisposed whether the plugin has been disposed
18
+ * @param {Function} deps.saveRecent saveRecent(id, state, settings): write the recent pool at the end of a turn
19
+ * @returns {{ onTurnEnd: Function, onChatDisposed: Function, stopLookups: Function }}
20
+ */
21
+ export function createFollowup({ chat, client, settings, formatter, log, isDisposed, saveRecent }) {
22
+ const lookups = new Map() // session id -> AbortController of the second lookup that is running
23
+ let replyWarned = false
24
+
25
+ // The history of a session as the plugin reads it, or null when this host cannot give it.
26
+ function historyOf(session) {
27
+ if (typeof session?.deriveMessages !== 'function') return null
28
+ try {
29
+ const history = session.deriveMessages()
30
+ return Array.isArray(history) ? history : null
31
+ } catch {
32
+ return null
33
+ }
34
+ }
35
+
36
+ // The reply of the turn that just ended: the text of the last assistant message after the last message
37
+ // the user typed, without this plugin's blocks. '' when there is none; null when the history cannot be read.
38
+ function replyOf(history) {
39
+ if (!history) return null
40
+ let from = -1
41
+ for (let i = history.length - 1; i >= 0; i--) {
42
+ if (isUserOrigin(history[i])) {
43
+ from = i
44
+ break
45
+ }
46
+ }
47
+ for (let i = history.length - 1; i > from; i--) {
48
+ if (history[i]?.role === 'assistant') return formatter().strip(textOf(history[i]))
49
+ }
50
+ return ''
51
+ }
52
+
53
+ // The text of every block of this plugin (either form) in a history; a notice is not a block.
54
+ function blocksIn(history) {
55
+ return (history ?? []).filter((m) => m?.source?.kind === SOURCE_KIND && m.source.form !== FORM_NOTICE).map(textOf)
56
+ }
57
+
58
+ function stopLookups() {
59
+ for (const controller of lookups.values()) controller.abort()
60
+ lookups.clear()
61
+ }
62
+
63
+ // Fire and forget: one lookup with the reply as the query. What it finds that no block in the history
64
+ // shows is kept for the next turn; an answer that comes after that turn began is dropped (pool.offer).
65
+ function startSecondLookup(id, state, session, query, s) {
66
+ const c = client(s.advanced.recallLimit)
67
+ if (!c) {
68
+ log.warn('feiyu-memgate: second lookup skipped (unavailable)')
69
+ return
70
+ }
71
+ lookups.get(id)?.abort()
72
+ const controller = new AbortController()
73
+ lookups.set(id, controller)
74
+ const { signal } = controller
75
+ const forTurn = state.turn + 1
76
+ const timeoutMs = s.advanced.recallTimeoutMs
77
+ const max = s.advanced.afterthoughtMax
78
+ Promise.resolve()
79
+ .then(async () => {
80
+ const detail = await within(c.recallDetail(query, { timeoutMs, signal, context: REQUEST_CONTEXT.followup, speaker: speakerAccount(s.advanced) }), timeoutMs + 250, signal)
81
+ if (signal.aborted) return
82
+ if (!detail || !Array.isArray(detail.results)) {
83
+ log.warn('feiyu-memgate: second lookup skipped (timeout)')
84
+ return
85
+ }
86
+ // Read the history now: it holds this turn's blocks, and the host may have compacted it meanwhile.
87
+ const shown = formatter().seen(blocksIn(historyOf(session)))
88
+ const found = detail.results.filter((r) => !shown(r?.text)).slice(0, max)
89
+ if (!found.length || isDisposed() || signal.aborted || chat.peek(id) !== state) return
90
+ pool.offer(state, found, forTurn)
91
+ })
92
+ .catch((error) => {
93
+ if (!signal.aborted) log.warn(`feiyu-memgate: second lookup skipped (${kindOf(error)})`)
94
+ })
95
+ .finally(() => {
96
+ if (lookups.get(id) === controller) lookups.delete(id)
97
+ })
98
+ }
99
+
100
+ function onTurnEnd(session, event) {
101
+ try {
102
+ if (!isObject(event) || event.type !== 'turn/end' || isSubagent(session?.header)) return
103
+ const id = sessionIdOf(session)
104
+ if (id === undefined) return
105
+ const state = chat.peek(id)
106
+ if (!state || !state.open) return // no lookup was planned for this turn
107
+ state.open = false
108
+ const s = settings()
109
+ const afterthought = s.modules.autoRecall && s.advanced.afterthought
110
+ const tracking = s.modules.autoRecall && (s.advanced.conversationPool || s.advanced.recentPool)
111
+ const recent = s.modules.autoRecall && s.advanced.recentPool
112
+ if (!afterthought && !tracking) return
113
+ const ended = event.data?.reason?.kind
114
+ if (ended === 'aborted' || ended === 'error' || ended === 'interrupted') return // no whole reply
115
+ const reply = replyOf(historyOf(session))
116
+ if (reply === null) {
117
+ if (!replyWarned) log.warn('feiyu-memgate: second lookup unavailable (reply-unreadable)')
118
+ replyWarned = true
119
+ return
120
+ }
121
+ // What the reply used gets stronger first: the pool is settled before a second lookup starts.
122
+ if (tracking && reply) pool.reinforce(state, reply)
123
+ if (recent) saveRecent(id, state, s)
124
+ const query = afterthought ? buildQuery(reply, null) : null
125
+ if (query) startSecondLookup(id, state, session, query, s)
126
+ } catch (error) {
127
+ log.warn(`feiyu-memgate: second lookup skipped (${kindOf(error)})`)
128
+ }
129
+ }
130
+
131
+ function onChatDisposed(session) {
132
+ const id = sessionIdOf(session)
133
+ lookups.get(id)?.abort()
134
+ lookups.delete(id)
135
+ chat.drop(id)
136
+ }
137
+
138
+ return { onTurnEnd, onChatDisposed, stopLookups }
139
+ }