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/routes.js ADDED
@@ -0,0 +1,320 @@
1
+ // The routes of the settings page, served by the host's web server: status, the local model list, the
2
+ // trial bench, the changelog and the mascot's drawings. Every route is owner only (admission) and none
3
+ // is reachable by the model. Their small caches (the changelog's parse, the drawings' bytes) live here.
4
+ // Logs name kinds of failure only, never a query, a memory, a path or a token.
5
+ import { createHash } from 'node:crypto'
6
+ import fs from 'node:fs'
7
+ import path from 'node:path'
8
+ import { releasedEntries } from './changelog.js'
9
+ import { buildQuery, codePointLength, pyStrip } from './query.js'
10
+ import { describeFailure } from './setup.js'
11
+ import { kindOf, REQUEST_CONTEXT, speakerAccount } from './shared.js'
12
+
13
+ // Read by the settings page (client/client.js) as the document-relative path `feiyu-memgate/status`,
14
+ // the same way first-party pages reach their host routes (packages/host/open-in-app/src/shared.ts:11-14).
15
+ export const STATUS_PATH = '/feiyu-memgate/status'
16
+ // The local model list of the settings page: GET reads it, POST starts, cancels, switches or removes
17
+ // (src/setup.js). Owner only, like the status.
18
+ export const MODELS_PATH = '/feiyu-memgate/models'
19
+ // The released sections of the package's own CHANGELOG.md, for the settings page (src/changelog.js). Owner only too.
20
+ export const CHANGELOG_PATH = '/feiyu-memgate/changelog'
21
+ // The trial bench of the settings page: POST { query } explains a recall (the candidates, their scores,
22
+ // the step that left one out) without changing anything. Owner only; reads no conversation state.
23
+ export const TRY_PATH = '/feiyu-memgate/try'
24
+ const CHANGELOG_FILE = new URL('../CHANGELOG.md', import.meta.url)
25
+ // The mascot's drawings on the settings page (the four moods of the summary and the one of the Feedback tab): GET <ART_PATH><name>, one exact route per file of client/art.
26
+ // Owner only like the other routes of the page: nothing here is secret, but the plugin serves nothing
27
+ // to anyone the host has not admitted.
28
+ export const ART_PATH = '/feiyu-memgate/art/'
29
+ export const ART_FILES = Object.freeze(['mascot-ready.webp', 'mascot-busy.webp', 'mascot-asleep.webp', 'mascot-trouble.webp', 'mascot-nag.webp'])
30
+ const ART_DIR = new URL('../client/art/', import.meta.url)
31
+ // A drawing is about 30 KB; a file far beyond that is not one of ours and is not served.
32
+ const MAX_ART_BYTES = 512 * 1024
33
+ const MAX_ACTION_BYTES = 8 * 1024
34
+ const TRIAL_MAX_CHARS = 500 // the gateway's query limit
35
+ const MODEL_ACTIONS = new Set(['install', 'builds', 'cancel', 'use', 'remove'])
36
+ // Actions that can make the host install a package: only with `confirmed: true`, which the page sends
37
+ // after its own confirmation step (a direct plugin manager call shows no host dialog).
38
+ const CONFIRMED_ACTIONS = new Set(['install', 'builds'])
39
+
40
+ /**
41
+ * @param {object} deps
42
+ * @param {Function} deps.service service(name): a host service, or undefined
43
+ * @param {object} deps.log { warn, info }
44
+ * @param {Function} deps.status the status answer (the settings page's status block)
45
+ * @param {object} deps.setup the model setup (src/setup.js)
46
+ * @param {Function} deps.settings the current settings
47
+ * @param {Function} deps.client client(limit): a gateway client, or null while memory is unavailable
48
+ * @param {string} deps.version the package version
49
+ * @param {URL|string} [deps.changelogFile] the CHANGELOG.md to read (replaceable in tests)
50
+ * @param {URL|string} [deps.artDir] the folder of the drawings (replaceable in tests)
51
+ */
52
+ export function createRoutes({ service, log, status, setup, settings, client, version, changelogFile: changelogFileDep, artDir: artDirDep }) {
53
+ const changelogFile = changelogFileDep ?? CHANGELOG_FILE
54
+ const artDir = artDirDep ?? ART_DIR
55
+
56
+ /**
57
+ * Who may use this plugin's routes: the owner only, like the first-party host routes. Returns
58
+ * null when the request is admitted, else the HTTP status to answer with.
59
+ * From 0.2.2-rc.3 the web server itself applies the host's Host/Origin fence and the session check
60
+ * to an `auth: 'required'` route and hands the handler the admitted Peer. 0.2.2-rc.1 ignores `auth`
61
+ * and calls the handler without a Peer; there, as its open-in-app routes do, the route asks the
62
+ * connection service, whose admit() applies the same fence and session check.
63
+ */
64
+ function admission(req, peer) {
65
+ if (peer !== undefined && peer !== null) return peer.principal?.kind === 'owner' ? null : 403
66
+ const connection = service('connection')
67
+ if (!connection || typeof connection.admit !== 'function') return 503
68
+ let result
69
+ try {
70
+ result = connection.admit(req)
71
+ } catch {
72
+ return 503
73
+ }
74
+ if (result && result.peer) return result.peer.principal?.kind === 'owner' ? null : 403
75
+ return Number.isInteger(result?.rejection) ? result.rejection : 401
76
+ }
77
+
78
+ // The status for the settings page. Owner only; the response is never cached by the browser.
79
+ function statusRoute() {
80
+ return {
81
+ kind: 'exact',
82
+ auth: 'required',
83
+ path: STATUS_PATH,
84
+ handler: async (req, res, peer) => {
85
+ const send = (code, body, extra = {}) => {
86
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra })
87
+ res.end(req.method === 'HEAD' ? undefined : JSON.stringify(body))
88
+ }
89
+ try {
90
+ const refused = admission(req, peer)
91
+ if (refused !== null) return send(refused, { code: refused === 403 ? 'forbidden' : 'unauthorized', message: 'owner access required' })
92
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(405, { code: 'method-not-allowed' }, { allow: 'GET, HEAD' })
93
+ send(200, await status())
94
+ } catch (error) {
95
+ log.warn(`feiyu-memgate: status unavailable (${kindOf(error)})`)
96
+ if (!res.headersSent) send(500, { code: 'status-unavailable' })
97
+ else res.end()
98
+ }
99
+ },
100
+ }
101
+ }
102
+
103
+ // A small JSON body, or a reason to refuse it: wrong content type, too large, not JSON.
104
+ async function readJson(req) {
105
+ const type = String(req.headers?.['content-type'] ?? '').split(';', 1)[0].trim().toLowerCase()
106
+ if (type !== 'application/json') return { status: 415, code: 'unsupported-media-type' }
107
+ const chunks = []
108
+ let size = 0
109
+ for await (const chunk of req) {
110
+ size += chunk.length
111
+ if (size > MAX_ACTION_BYTES) return { status: 413, code: 'too-large' }
112
+ chunks.push(chunk)
113
+ }
114
+ try {
115
+ return { json: JSON.parse(Buffer.concat(chunks).toString('utf8')) }
116
+ } catch {
117
+ return { status: 400, code: 'bad-json' }
118
+ }
119
+ }
120
+
121
+ // The body of a model-list click, or a reason to refuse it.
122
+ async function readAction(req) {
123
+ const read = await readJson(req)
124
+ if (!('json' in read)) return read
125
+ const body = read.json
126
+ if (!body || typeof body !== 'object' || !MODEL_ACTIONS.has(body.action)) return { status: 400, code: 'bad-action' }
127
+ if (CONFIRMED_ACTIONS.has(body.action) && body.confirmed !== true) return { status: 400, code: 'confirm-required' }
128
+ if (body.action === 'builds' && typeof body.allow !== 'boolean') return { status: 400, code: 'bad-decision' }
129
+ if (body.action !== 'cancel' && body.action !== 'builds' && (typeof body.id !== 'string' || body.id.length > 80)) return { status: 400, code: 'bad-id' }
130
+ if (body.acceptLicence !== undefined && (typeof body.acceptLicence !== 'string' || body.acceptLicence.length > 200)) return { status: 400, code: 'bad-licence' }
131
+ return { body }
132
+ }
133
+
134
+ // The local model list of the settings page: GET reads where everything stands, POST is a click
135
+ // (install, cancel, use, remove). Owner only; a cross-site page cannot send it (the host's
136
+ // Host/Origin fence, a JSON body, the session cookie), and no tool reaches it.
137
+ function modelsRoute() {
138
+ return {
139
+ kind: 'exact',
140
+ auth: 'required',
141
+ path: MODELS_PATH,
142
+ handler: async (req, res, peer) => {
143
+ const send = (code, body, extra = {}) => {
144
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra })
145
+ res.end(req.method === 'HEAD' ? undefined : JSON.stringify(body))
146
+ }
147
+ try {
148
+ const refused = admission(req, peer)
149
+ if (refused !== null) return send(refused, { code: refused === 403 ? 'forbidden' : 'unauthorized', message: 'owner access required' })
150
+ if (req.method === 'GET' || req.method === 'HEAD') return send(200, await setup.view())
151
+ if (req.method !== 'POST') return send(405, { code: 'method-not-allowed' }, { allow: 'GET, HEAD, POST' })
152
+ const parsed = await readAction(req)
153
+ if (!parsed.body) return send(parsed.status, { code: parsed.code })
154
+ const { action, id, acceptLicence, allow } = parsed.body
155
+ const confirmed = parsed.body.confirmed === true
156
+ const result = action === 'install' ? await setup.install(id, { acceptLicence, confirmed })
157
+ : action === 'builds' ? await setup.decideBuilds(allow, { confirmed })
158
+ : action === 'use' ? await setup.use(id)
159
+ : action === 'remove' ? await setup.remove(id)
160
+ : await setup.cancel()
161
+ const ok = result.ok === true
162
+ send(200, {
163
+ result: { ok, code: result.code, problem: ok ? null : (setup.describe?.(result.code) ?? describeFailure(result.code)), licence: result.licence ?? null },
164
+ view: await setup.view(),
165
+ })
166
+ } catch (error) {
167
+ log.warn(`feiyu-memgate: model list unavailable (${kindOf(error)})`)
168
+ if (!res.headersSent) send(500, { code: 'models-unavailable' })
169
+ else res.end()
170
+ }
171
+ },
172
+ }
173
+ }
174
+
175
+ // The trial bench of the settings page: one sentence in, the gateway's explanation of its recall out.
176
+ // Owner only, POST only. It touches no conversation state (the lists of memories already given, the
177
+ // pools, the relevance check, the counters of the status) and logs neither the sentence nor a result.
178
+ function tryRoute() {
179
+ return {
180
+ kind: 'exact',
181
+ auth: 'required',
182
+ path: TRY_PATH,
183
+ handler: async (req, res, peer) => {
184
+ const send = (code, body, extra = {}) => {
185
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra })
186
+ res.end(JSON.stringify(body))
187
+ }
188
+ try {
189
+ const refused = admission(req, peer)
190
+ if (refused !== null) return send(refused, { code: refused === 403 ? 'forbidden' : 'unauthorized', message: 'owner access required' })
191
+ if (req.method !== 'POST') return send(405, { code: 'method-not-allowed' }, { allow: 'POST' })
192
+ const read = await readJson(req)
193
+ if (!('json' in read)) return send(read.status, { code: read.code })
194
+ const text = read.json?.query
195
+ if (typeof text !== 'string' || !pyStrip(text) || codePointLength(text) > TRIAL_MAX_CHARS) return send(400, { code: 'bad-query' })
196
+ const query = buildQuery(text, null)
197
+ if (query === null) return send(200, { ok: false, code: 'no-recall' })
198
+ const limit = settings().advanced.recallLimit
199
+ const c = client(limit)
200
+ if (!c) return send(200, { ok: false, code: 'unavailable' })
201
+ const result = await c.explainRecall(query, { context: REQUEST_CONTEXT.trial, speaker: speakerAccount(settings().advanced) })
202
+ send(200, result?.ok === true ? { ...result, limit } : { ok: false, code: result?.code === 'unsupported' ? 'unsupported' : 'failed' })
203
+ } catch (error) {
204
+ log.warn(`feiyu-memgate: trial recall failed (${kindOf(error)})`)
205
+ if (!res.headersSent) send(200, { ok: false, code: 'failed' })
206
+ else res.end()
207
+ }
208
+ },
209
+ }
210
+ }
211
+
212
+ // ---------------------------------------------------------------- changelog
213
+
214
+ let changelogCache = null // { key: 'mtime:size', entries }
215
+
216
+ /**
217
+ * The released entries of the package's CHANGELOG.md: read on request, parsed again only when the file's
218
+ * modification time or size changed. A file that is missing or cannot be read gives no entries (never an
219
+ * error, never a path).
220
+ */
221
+ function changelog() {
222
+ try {
223
+ const stat = fs.statSync(changelogFile)
224
+ const key = `${stat.mtimeMs}:${stat.size}`
225
+ if (changelogCache?.key !== key) changelogCache = { key, entries: releasedEntries(fs.readFileSync(changelogFile, 'utf8'), version) }
226
+ return { version: version, entries: changelogCache.entries }
227
+ } catch {
228
+ changelogCache = null
229
+ return { version: version, entries: [] }
230
+ }
231
+ }
232
+
233
+ // What the settings page reads under "Changelog". Owner only, never cached by the browser.
234
+ function changelogRoute() {
235
+ return {
236
+ kind: 'exact',
237
+ auth: 'required',
238
+ path: CHANGELOG_PATH,
239
+ handler: async (req, res, peer) => {
240
+ const send = (code, body, extra = {}) => {
241
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra })
242
+ res.end(req.method === 'HEAD' ? undefined : JSON.stringify(body))
243
+ }
244
+ try {
245
+ const refused = admission(req, peer)
246
+ if (refused !== null) return send(refused, { code: refused === 403 ? 'forbidden' : 'unauthorized', message: 'owner access required' })
247
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(405, { code: 'method-not-allowed' }, { allow: 'GET, HEAD' })
248
+ send(200, changelog())
249
+ } catch (error) {
250
+ log.warn(`feiyu-memgate: changelog unavailable (${kindOf(error)})`)
251
+ if (!res.headersSent) send(500, { code: 'changelog-unavailable' })
252
+ else res.end()
253
+ }
254
+ },
255
+ }
256
+ }
257
+
258
+ // ---------------------------------------------------------------- art
259
+
260
+ const artCache = new Map() // file name -> { key: 'mtime:size', bytes, etag }
261
+
262
+ /**
263
+ * One drawing of client/art: its bytes and an entity tag made from them, read again only when the
264
+ * file changed. Null when the file is missing, unreadable or not the size of a drawing.
265
+ */
266
+ function art(name) {
267
+ try {
268
+ const file = artDir instanceof URL ? new URL(name, artDir) : path.join(String(artDir), name)
269
+ const stat = fs.statSync(file)
270
+ if (!stat.isFile() || stat.size === 0 || stat.size > MAX_ART_BYTES) return null
271
+ const key = `${stat.mtimeMs}:${stat.size}`
272
+ const hit = artCache.get(name)
273
+ if (hit?.key === key) return hit
274
+ const bytes = fs.readFileSync(file)
275
+ const entry = { key, bytes, etag: `"${createHash('sha1').update(bytes).digest('hex').slice(0, 16)}"` }
276
+ artCache.set(name, entry)
277
+ return entry
278
+ } catch {
279
+ artCache.delete(name)
280
+ return null
281
+ }
282
+ }
283
+
284
+ // The settings page's <img> for one mood. The name is fixed by the route, never taken from the
285
+ // request, so no path of the request reaches the file system. The browser may keep the picture but
286
+ // asks each time whether it changed (the tag answers with 304), so an updated plugin shows its own.
287
+ function artRoute(name) {
288
+ return {
289
+ kind: 'exact',
290
+ auth: 'required',
291
+ path: ART_PATH + name,
292
+ handler: async (req, res, peer) => {
293
+ const plain = (code, extra = {}) => {
294
+ res.writeHead(code, { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...extra })
295
+ res.end()
296
+ }
297
+ try {
298
+ const refused = admission(req, peer)
299
+ if (refused !== null) return plain(refused)
300
+ if (req.method !== 'GET' && req.method !== 'HEAD') return plain(405, { allow: 'GET, HEAD' })
301
+ const entry = art(name)
302
+ if (!entry) return plain(404)
303
+ const headers = { 'content-type': 'image/webp', 'cache-control': 'private, no-cache', etag: entry.etag, 'x-content-type-options': 'nosniff' }
304
+ if (req.headers?.['if-none-match'] === entry.etag) {
305
+ res.writeHead(304, headers)
306
+ return res.end()
307
+ }
308
+ res.writeHead(200, { ...headers, 'content-length': String(entry.bytes.length) })
309
+ res.end(req.method === 'HEAD' ? undefined : entry.bytes)
310
+ } catch (error) {
311
+ log.warn(`feiyu-memgate: a drawing of the settings page is unavailable (${kindOf(error)})`)
312
+ if (!res.headersSent) plain(500)
313
+ else res.end()
314
+ }
315
+ },
316
+ }
317
+ }
318
+
319
+ return { statusRoute, modelsRoute, tryRoute, changelogRoute, changelog, artRoute }
320
+ }
package/src/setup.js CHANGED
@@ -70,135 +70,135 @@ const CODE = /^[a-z][a-z0-9-]{0,39}$/
70
70
  export const FAILURES = Object.freeze({
71
71
  network: {
72
72
  en: ['The download source could not be reached (no network, or the mirror does not answer).', 'Check the connection. In the embedding add-on’s settings you can pick another download source (hf-mirror or your own mirror); then press the button again: the download resumes where it stopped.'],
73
- zh: ['连不上下载来源(没有网络,或者镜像没有响应)。', '检查网络连接。可以在向量插件的设置里换一个下载来源(hf-mirror 或自己的镜像),然后再按一次按钮,下载会从中断处继续。'],
73
+ zh: ['无法连接下载来源(没有网络,或镜像无响应)。', '请检查网络连接。可在向量插件的设置中更换下载来源(hf-mirror 或自建镜像),然后再次点击按钮,下载将从中断处继续。'],
74
74
  },
75
75
  'disk-full': {
76
76
  en: ['Not enough disk space for the model.', 'Free some space on the drive that holds the DSH data folder (the model size plus a margin), then press the button again.'],
77
- zh: ['磁盘空间不够放下这个模型。', '在存放 DSH 数据目录的磁盘上腾出空间(模型大小再多留一些),然后再按一次按钮。'],
77
+ zh: ['磁盘空间不足,无法存放该模型。', '请在存放 DSH 数据目录的磁盘上释放空间(模型大小再加一定余量),然后再次点击按钮。'],
78
78
  },
79
79
  integrity: {
80
80
  en: ['The downloaded file did not pass verification (its size or checksum is wrong).', 'Press the button again to download it anew. If it happens again, choose another download source in the embedding add-on’s settings.'],
81
- zh: ['下载的文件没通过校验(大小或校验和不对)。', '再按一次按钮重新下载。如果再次出现,在向量插件的设置里换一个下载来源。'],
81
+ zh: ['下载的文件未通过校验(大小或校验和不符)。', '请再次点击按钮重新下载。若再次出现,请在向量插件的设置中更换下载来源。'],
82
82
  },
83
83
  'runtime-unavailable': {
84
84
  en: ['The embedding add-on cannot load its engine on this computer (its status shows the error runtime-missing).', 'On Windows this almost always means the Microsoft Visual C++ 2015-2022 Redistributable (x64) is missing: install it from Microsoft (vc_redist.x64.exe, https://aka.ms/vs/17/release/vc_redist.x64.exe), then restart DSH. Elsewhere the engine has no CPU build for this platform: keep the keyword tier, or use an embeddings service through the endpoint tier.'],
85
- zh: ['向量插件在这台电脑上加载不了它的引擎(它的状态显示错误 runtime-missing)。', '在 Windows 上,这几乎都是因为缺少 Microsoft Visual C++ 2015-2022 运行库(x64):从微软官网安装它(vc_redist.x64.exe,https://aka.ms/vs/17/release/vc_redist.x64.exe),然后重启 DSH。在其他系统上,说明引擎没有这个平台的 CPU 版本:继续用关键词检索,或者用 endpoint 方式接一个向量服务。'],
85
+ zh: ['向量插件无法在本机加载其运行引擎(状态显示错误 runtime-missing)。', '在 Windows 上,这几乎都是因为缺少 Microsoft Visual C++ 2015-2022 运行库(x64):请从微软官网安装(vc_redist.x64.exe,https://aka.ms/vs/17/release/vc_redist.x64.exe),然后重启 DSH。在其他系统上,引擎没有适用于该平台的 CPU 版本:请继续使用关键词检索,或通过 endpoint 检索方式接入向量服务。'],
86
86
  },
87
87
  'python-missing': {
88
88
  en: ['Python 3.11 or newer was not found, so the managed memory gateway is off and a local model cannot be used for memory yet.', 'Install Python 3.11 or newer (or set gateway.python to its path); the gateway starts by itself afterwards.'],
89
- zh: ['没有找到 Python 3.11 或更新的版本,自带的记忆网关没有运行,本地模型暂时用不上。', '安装 Python 3.11 或更新版本(或者把 gateway.python 设为它的路径),之后网关会自己启动。'],
89
+ zh: ['未找到 Python 3.11 或更高版本,内置网关未运行,暂时无法将本地模型用于记忆。', '请安装 Python 3.11 或更高版本(或将 gateway.python 设为其路径),网关随后会自动启动。'],
90
90
  },
91
91
  'install-cancelled': {
92
92
  en: ['The installation of the embedding add-on was declined or cancelled; nothing was installed.', 'Press the button again when you want to install it.'],
93
- zh: ['向量插件的安装被拒绝或取消了,什么都没有装。', '想装的时候再按一次按钮。'],
93
+ zh: ['向量插件的安装已被拒绝或取消,未安装任何内容。', '需要时可再次点击按钮安装。'],
94
94
  },
95
95
  pinned: {
96
96
  en: ['The embedding add-on’s own settings pin a model (activeModel), and that setting wins.', 'Set activeModel back to none on the embedding add-on’s settings page, or use the model it pins.'],
97
- zh: ['向量插件自己的设置里指定了模型(activeModel),以那个设置为准。', '在向量插件的设置页把 activeModel 改回 none,或者就用它指定的模型。'],
97
+ zh: ['向量插件自身的设置中指定了模型(activeModel),以该设置为准。', '请在向量插件的设置页将 activeModel 改回 none,或使用其指定的模型。'],
98
98
  },
99
99
  'addon-incompatible': {
100
100
  en: ['This version of the embedding add-on does not support the running DSH version.', 'Update DSH, or wait for an add-on version that supports it; the Plugins page shows the details.'],
101
- zh: ['这个版本的向量插件不支持当前的 DSH 版本。', '升级 DSH,或者等支持它的插件版本;插件页面有详细说明。'],
101
+ zh: ['当前版本的向量插件不支持正在运行的 DSH 版本。', '请升级 DSH,或等待支持该版本的插件更新;详情见插件页面。'],
102
102
  },
103
103
  'build-approval': {
104
104
  en: ['The host still waits for a decision on an install script, or the decision went stale.', 'Press the button again and answer the install-script question that follows.'],
105
- zh: ['宿主还在等对安装脚本的决定,或者之前的决定已经失效。', '再按一次按钮,回答随后出现的安装脚本问题。'],
105
+ zh: ['宿主仍在等待对安装脚本的决定,或之前的决定已失效。', '请再次点击按钮,并回答随后出现的安装脚本问题。'],
106
106
  },
107
107
  'builds-denied': {
108
108
  en: ['You did not allow the install script, so nothing was installed and nothing loads.', 'DSH has no button to record a refusal; record it in a file. Open {file}. Under “allowBuilds:”, DSH wrote the line “{name}: set this to true or false”; change it to “{name}: false” and save. Then press “Download and enable” again (or run /memgate install with --confirm): the add-on installs with the script skipped and is switched on. Or press the button again and allow the script.'],
109
- zh: ['你没有允许安装脚本,所以什么都没有装,也不会加载。', 'DSH 没有记录“拒绝”的按钮,要在文件里记下。打开 {file},在“allowBuilds:”下面,DSH 写了一行“{name}: set this to true or false”,把它改成“{name}: false”并保存。然后再按一次“下载并启用”(或者执行带 --confirm 的 /memgate install):插件会跳过这个脚本装好并启用。也可以再按一次按钮,选择允许脚本。'],
109
+ zh: ['你未允许安装脚本,因此未安装任何内容,也不会加载。', 'DSH 没有记录“拒绝”的按钮,需在文件中手动记录。请打开 {file},在“allowBuilds:”下找到 DSH 写入的“{name}: set this to true or false”,改为“{name}: false”并保存。然后再次点击“下载并启用”(或执行带 --confirm 的 /memgate install):插件将跳过该脚本完成安装并启用。也可再次点击按钮,选择允许脚本。'],
110
110
  },
111
111
  'addon-enable-failed': {
112
112
  en: ['The embedding add-on is installed but DSH could not switch it on.', 'The Plugins page shows why (for example a version this DSH does not support). Fix that, or remove dsh-feiyu-memgate-embed there, then press the button again.'],
113
- zh: ['向量插件已经安装,但 DSH 没能启用它。', '插件页面会显示原因(例如这个 DSH 不支持的版本)。处理好,或者在那里移除 dsh-feiyu-memgate-embed,然后再按一次按钮。'],
113
+ zh: ['向量插件已安装,但 DSH 无法启用。', '原因见插件页面(例如 DSH 不支持的版本)。请先处理,或在插件页面移除 dsh-feiyu-memgate-embed,然后再次点击按钮。'],
114
114
  },
115
115
  'confirm-required': {
116
116
  en: ['Installing the embedding add-on needs your explicit confirmation.', 'Confirm on the settings page, or repeat the command with --confirm.'],
117
- zh: ['安装向量插件需要你明确确认。', '在设置页面确认,或者在命令后面加上 --confirm 再执行一次。'],
117
+ zh: ['安装向量插件需要你明确确认。', '请在设置页面确认,或在命令后加上 --confirm 再次执行。'],
118
118
  },
119
119
  'builds-pending': {
120
120
  en: ['The host waits for your decision on an install script.', 'Answer the install-script question on the settings page (or with /memgate builds allow|deny).'],
121
- zh: ['宿主在等你对安装脚本做决定。', '在设置页面回答安装脚本的问题(或者用 /memgate builds allow|deny)。'],
121
+ zh: ['宿主正在等待你对安装脚本做出决定。', '请在设置页面回答安装脚本的问题(或使用 /memgate builds allow|deny)。'],
122
122
  },
123
123
  'restart-required': {
124
124
  en: ['The embedding add-on is installed and starts after DSH restarts.', 'Restart DSH; the setup continues by itself afterwards.'],
125
- zh: ['向量插件已经装好,DSH 重启后才会启动。', '重启 DSH,之后会自动继续。'],
125
+ zh: ['向量插件已安装,DSH 重启后才会启动。', '请重启 DSH,之后设置会自动继续。'],
126
126
  },
127
127
  'addon-not-found': {
128
128
  en: ['The package dsh-feiyu-memgate-embed was not found in the package registry.', 'Check the registry and network settings of the Plugins page, or try again later.'],
129
- zh: ['包仓库里找不到 dsh-feiyu-memgate-embed。', '检查插件页面的仓库和网络设置,或者稍后再试。'],
129
+ zh: ['包仓库中未找到 dsh-feiyu-memgate-embed。', '请检查插件页面的仓库和网络设置,或稍后重试。'],
130
130
  },
131
131
  'addon-install-failed': {
132
132
  en: ['The host could not install the embedding add-on.', 'The Plugins page has the installation log; fix what it names and press the button again.'],
133
- zh: ['宿主没能装上向量插件。', '插件页面有安装日志;按日志处理后再按一次按钮。'],
133
+ zh: ['宿主未能安装向量插件。', '插件页面提供安装日志;请按日志处理后再次点击按钮。'],
134
134
  },
135
135
  'no-plugin-manager': {
136
136
  en: ['This DSH profile has no plugin manager, so the add-on cannot be installed from here.', 'Install dsh-feiyu-memgate-embed with the dsh plugin command or the profile’s package.json, then come back.'],
137
- zh: ['这个 DSH 配置没有插件管理器,没法从这里安装向量插件。', '用 dsh plugin 命令或配置的 package.json 安装 dsh-feiyu-memgate-embed,然后回到这里。'],
137
+ zh: ['当前 DSH 配置没有插件管理器,无法在此安装向量插件。', '请使用 dsh plugin 命令或配置的 package.json 安装 dsh-feiyu-memgate-embed,然后返回此处。'],
138
138
  },
139
139
  'addon-outdated': {
140
140
  en: ['The installed embedding add-on is too old for one-click setup.', 'Update dsh-feiyu-memgate-embed on the Plugins page, or use its /memgate-embed command.'],
141
- zh: ['已安装的向量插件版本太旧,不支持一键设置。', '在插件页面更新 dsh-feiyu-memgate-embed,或者用它的 /memgate-embed 命令。'],
141
+ zh: ['已安装的向量插件版本过旧,不支持一键设置。', '请在插件页面更新 dsh-feiyu-memgate-embed,或使用其 /memgate-embed 命令。'],
142
142
  },
143
143
  'addon-not-started': {
144
144
  en: ['The embedding add-on is installed but has not started.', 'Check on the Plugins page that dsh-feiyu-memgate-embed is turned on, then press the button again.'],
145
- zh: ['向量插件已经安装,但没有启动。', '在插件页面确认 dsh-feiyu-memgate-embed 已打开,然后再按一次按钮。'],
145
+ zh: ['向量插件已安装,但未启动。', '请在插件页面确认 dsh-feiyu-memgate-embed 已开启,然后再次点击按钮。'],
146
146
  },
147
147
  'needs-acceptance': {
148
148
  en: ['This model’s weights come under a licence you must accept first.', 'Read the licence, tick the box next to the model, then press the button.'],
149
- zh: ['这个模型的权重有一份需要先同意的许可。', '阅读许可,勾选模型旁的复选框,再按按钮。'],
149
+ zh: ['该模型的权重适用一份需先同意的许可。', '请阅读许可,勾选模型旁的复选框,再点击按钮。'],
150
150
  },
151
151
  busy: {
152
152
  en: ['Another model is being set up.', 'Wait for it to finish, or cancel it first.'],
153
- zh: ['另一个模型正在设置。', '等它完成,或者先取消。'],
153
+ zh: ['另一个模型正在设置。', '请等待其完成,或先取消。'],
154
154
  },
155
155
  interrupted: {
156
156
  en: ['The installation was interrupted (DSH stopped in the middle).', 'Press the button again; what is already done is kept.'],
157
- zh: ['安装中途被打断了(DSH 中途停止)。', '再按一次按钮,已经完成的部分会保留。'],
157
+ zh: ['安装被中断(DSH 中途停止)。', '请再次点击按钮,已完成的部分会保留。'],
158
158
  },
159
159
  storage: {
160
160
  en: ['The model file could not be written.', 'Check that the DSH data folder is writable, then press the button again.'],
161
- zh: ['模型文件写不进去。', '确认 DSH 数据目录可以写入,然后再按一次按钮。'],
161
+ zh: ['无法写入模型文件。', '请确认 DSH 数据目录可写,然后再次点击按钮。'],
162
162
  },
163
163
  'model-failed': {
164
164
  en: ['The model could not be loaded.', 'Remove the model and download it again; if that does not help, choose another model.'],
165
- zh: ['模型加载失败。', '删除这个模型重新下载;还不行就换一个模型。'],
165
+ zh: ['模型加载失败。', '请删除该模型后重新下载;仍无法解决时,请更换模型。'],
166
166
  },
167
167
  cancelled: {
168
168
  en: ['The download was cancelled. The part already downloaded stays on disk.', 'Press the button to continue, or remove the model to delete the part.'],
169
- zh: ['下载已取消,已经下载的部分留在磁盘上。', '按按钮继续下载,或者删除模型把这部分删掉。'],
169
+ zh: ['下载已取消,已下载的部分保留在磁盘上。', '点击按钮可继续下载,或删除模型以清除这部分。'],
170
170
  },
171
171
  'unknown-model': {
172
172
  en: ['There is no such model in the list.', 'Pick one of the listed models.'],
173
- zh: ['列表里没有这个模型。', '从列表里选一个模型。'],
173
+ zh: ['列表中没有该模型。', '请从列表中选择模型。'],
174
174
  },
175
175
  'not-running': {
176
176
  en: ['Nothing is being installed or downloaded.', 'There is nothing to cancel.'],
177
- zh: ['没有正在进行的安装或下载。', '没有可以取消的。'],
177
+ zh: ['没有正在进行的安装或下载。', '没有可取消的内容。'],
178
178
  },
179
179
  'too-late': {
180
180
  en: ['Too late to cancel: the host is applying the add-on.', 'Wait a moment; you can remove the add-on on the Plugins page afterwards.'],
181
- zh: ['来不及取消:宿主正在应用插件。', '稍等一下;之后可以在插件页面移除它。'],
181
+ zh: ['已无法取消:宿主正在应用插件。', '请稍候;之后可在插件页面移除该插件。'],
182
182
  },
183
183
  active: {
184
184
  en: ['This model is in use.', 'Switch to another model before deleting it.'],
185
- zh: ['这个模型正在使用。', '先切换到别的模型再删除。'],
185
+ zh: ['该模型正在使用。', '请先切换到其他模型,再删除。'],
186
186
  },
187
187
  downloading: {
188
188
  en: ['This model is downloading.', 'Cancel the download first.'],
189
- zh: ['这个模型正在下载。', '先取消下载。'],
189
+ zh: ['该模型正在下载。', '请先取消下载。'],
190
190
  },
191
191
  'not-installed': {
192
192
  en: ['This model is not downloaded.', 'Use “Download and enable”.'],
193
- zh: ['这个模型还没下载。', '按“下载并启用”。'],
193
+ zh: ['该模型尚未下载。', '请点击“下载并启用”。'],
194
194
  },
195
195
  'addon-absent': {
196
196
  en: ['The embedding add-on is not installed yet.', 'Use “Download and enable” on a model: it installs the add-on first.'],
197
- zh: ['还没有安装向量插件。', '在某个模型上按“下载并启用”,会先安装向量插件。'],
197
+ zh: ['尚未安装向量插件。', '请在某个模型上点击“下载并启用”,将先安装向量插件。'],
198
198
  },
199
199
  unknown: {
200
200
  en: ['The step failed.', 'Press the button again; the Plugins page and the add-on’s /memgate-embed status have details.'],
201
- zh: ['这一步失败了。', '再按一次按钮;插件页面和向量插件的 /memgate-embed status 有详细信息。'],
201
+ zh: ['该步骤失败。', '请再次点击按钮;详细信息见插件页面和向量插件的 /memgate-embed status。'],
202
202
  },
203
203
  })
204
204
 
@@ -208,13 +208,13 @@ export const FAILURES = Object.freeze({
208
208
  */
209
209
  export const ADDON_CONFIRM = Object.freeze({
210
210
  en: 'This installs the plugin dsh-feiyu-memgate-embed from npm through the DSH plugin manager (it checks that the plugin supports this DSH first), then downloads {model} ({size}) and enables it. The plugin adds a dependency with a native binary (node-llama-cpp): about 90 MB on disk for the CPU build, up to about 740 MB on Windows and Linux x64, where pnpm also fetches the GPU builds. The model runs on the CPU only. On Windows the engine needs the Microsoft Visual C++ 2015-2022 runtime (x64), which most Windows installations already have.',
211
- zh: '这会通过 DSH 的插件管理器从 npm 安装插件 dsh-feiyu-memgate-embed(先检查它是否支持当前 DSH),然后下载 {model}({size})并启用。这个插件会带来一个含原生二进制的依赖(node-llama-cpp):CPU 版约占 90 MB 磁盘;在 Windows 和 Linux x64 上 pnpm 还会取 GPU 版本,最多约 740 MB。模型只在 CPU 上运行。在 Windows 上,引擎需要 Microsoft Visual C++ 2015-2022 运行库(x64),大多数 Windows 已经装有。',
211
+ zh: '将通过 DSH 的插件管理器从 npm 安装插件 dsh-feiyu-memgate-embed(先检查其是否支持当前 DSH),然后下载 {model}({size})并启用。该插件依赖含原生二进制文件的 node-llama-cpp:CPU 版本约占用 90 MB 磁盘;在 Windows 和 Linux x64 上,pnpm 还会获取 GPU 版本,最多约 740 MB。模型仅使用 CPU 运行。在 Windows 上,引擎需要 Microsoft Visual C++ 2015-2022 运行库(x64),大多数 Windows 系统已自带。',
212
212
  })
213
213
 
214
214
  /** The question when pnpm stopped an install script ({names} is filled in). */
215
215
  export const BUILDS_NOTE = Object.freeze({
216
216
  en: 'The embedding add-on depends on node-llama-cpp, which has an install script, and pnpm stopped the installation until you decide; nothing is installed yet. Both answers work: according to the add-on’s author, the script downloads and builds nothing, and the engine runs with it skipped. Allowing installs again and records a lasting permission in this DSH profile for: {names}. Denying has no button in DSH: the page then names the line to change in the profile’s pnpm-workspace.yaml, after which you press the button again.',
217
- zh: '向量插件依赖 node-llama-cpp,它带有一个安装脚本,pnpm 把安装停下来等你决定,现在还什么都没装。两种选择都能用:据插件作者测试,这个脚本不下载也不编译任何东西,跳过它引擎照样能运行。允许会重新安装,并在这个 DSH 配置里为以下项目留下长期许可:{names}。拒绝在 DSH 里没有按钮:页面会告诉你在配置的 pnpm-workspace.yaml 里改哪一行,改好后再按一次按钮。',
217
+ zh: '向量插件依赖 node-llama-cpp,它带有安装脚本,pnpm 已暂停安装,等待你做出决定;目前尚未安装任何内容。两种选择均可:据插件作者测试,该脚本不下载也不编译任何内容,跳过后引擎仍可运行。选择允许将重新安装,并在当前 DSH 配置中为以下项目留下长期许可:{names}。DSH 中没有“拒绝”按钮:页面会指明需在配置的 pnpm-workspace.yaml 中修改的行,修改后再次点击按钮。',
218
218
  })
219
219
 
220
220
  /**
@@ -926,7 +926,7 @@ export function createModelSetup({
926
926
  }
927
927
  const file = typeof dir === 'string' && dir
928
928
  ? path.join(dir, 'pnpm-workspace.yaml')
929
- : { en: 'the pnpm-workspace.yaml in the folder of this DSH profile (<DSH home>/profiles/<profile>)', zh: '这个 DSH 配置文件夹(<DSH home>/profiles/<配置名>)里的 pnpm-workspace.yaml' }
929
+ : { en: 'the pnpm-workspace.yaml in the folder of this DSH profile (<DSH home>/profiles/<profile>)', zh: '当前 DSH 配置文件夹(<DSH home>/profiles/<配置名>)中的 pnpm-workspace.yaml' }
930
930
  return { file, name: chain?.pendingBuilds?.[0] ?? 'node-llama-cpp' }
931
931
  }
932
932
 
package/src/shared.js ADDED
@@ -0,0 +1,77 @@
1
+ // Names and small pure helpers that more than one module of the plugin needs (src/plugin.js and the
2
+ // modules it wires up). Holds no state and reads no setting; a module imports from here, never from
3
+ // plugin.js. Logs name kinds of failure only: kindOf() gives an error name or code, never its message.
4
+
5
+ export const PLUGIN_NAME = 'dsh-feiyu-memgate'
6
+
7
+ // Session format v4 wants a producer-owned source kind; the old shared {kind: 'plugin'} wrapper is
8
+ // refused (packages/session/session-format-v3-to-v4/src/message-sources.ts:9-10; the third-party
9
+ // form is plugin:<name>, session-format-v3-to-v4/README.md:120-134). 'recall' is the host's form for
10
+ // material brought in from elsewhere (packages/llm/llm/src/message.ts:54-66, :100).
11
+ export const SOURCE_KIND = 'plugin:' + PLUGIN_NAME
12
+
13
+ // The two forms of a plugin message: the memory block and the note that a lookup failed.
14
+ export const FORM_RECALL = 'recall'
15
+ export const FORM_NOTICE = 'notice'
16
+ // The second block of a turn (advanced.afterthought, advanced.conversationPool): memories this conversation
17
+ // brought to mind. A block like the first, not a notice.
18
+ export const FORM_POOL = 'pool'
19
+
20
+ export const MAX_REMEMBER_CHARS = 4000 // gateway limit per message
21
+ export const MAX_QUERY_CHARS = 500 // gateway limit per query
22
+
23
+ // The label sent with every recall and remember: where the request comes from and what triggered
24
+ // it. Constants only, nothing from the conversation. The built-in gateway ignores it; an operator's
25
+ // own stages and guards can read it.
26
+ export const REQUEST_CONTEXT = Object.freeze({
27
+ turn: Object.freeze({ channel: 'dsh', via: 'turn' }),
28
+ search: Object.freeze({ channel: 'dsh', via: 'search' }),
29
+ followup: Object.freeze({ channel: 'dsh', via: 'followup' }),
30
+ tool: Object.freeze({ channel: 'dsh', via: 'tool' }),
31
+ capture: Object.freeze({ channel: 'dsh', via: 'capture' }),
32
+ trial: Object.freeze({ channel: 'dsh', via: 'trial' }),
33
+ })
34
+
35
+ // The account this DSH reports to the gateway (advanced.speakerAccount): dsh:name, or the default when the
36
+ // setting does not hold one. Mirrors the shape the gateway takes for an account of the platform dsh.
37
+ export const DEFAULT_ACCOUNT = 'dsh:local'
38
+ const ACCOUNT = /^dsh:[a-z0-9][a-z0-9_.-]{0,31}$/
39
+ export const speakerAccount = (advanced) => (typeof advanced?.speakerAccount === 'string' && ACCOUNT.test(advanced.speakerAccount) ? advanced.speakerAccount : DEFAULT_ACCOUNT)
40
+
41
+ export const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
42
+ export const isUserOrigin = (m) => isObject(m) && m.role === 'user' && m.source?.kind === 'user'
43
+ export const isSubagent = (header) => header?.origin === 'subagent' || (Number.isInteger(header?.delegationDepth) && header.delegationDepth > 0)
44
+
45
+ export function textOf(message) {
46
+ const content = message?.content
47
+ if (typeof content === 'string') return content
48
+ if (!Array.isArray(content)) return ''
49
+ return content.filter((b) => isObject(b) && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n')
50
+ }
51
+
52
+ // A kind of failure fit for a log line: an error name or code, never its message.
53
+ export function kindOf(error) {
54
+ const code = error?.code
55
+ if (typeof code === 'string' && /^[A-Z0-9_]{1,40}$/.test(code)) return code
56
+ const name = error?.name
57
+ return typeof name === 'string' && /^[A-Za-z]{1,40}$/.test(name) ? name : 'error'
58
+ }
59
+
60
+ // Resolves to the value, or to null when the time runs out or the signal aborts first.
61
+ export function within(promise, timeoutMs, signal) {
62
+ return new Promise((resolve) => {
63
+ if (signal?.aborted) return resolve(null)
64
+ let timer = null
65
+ const done = (value) => {
66
+ if (timer) clearTimeout(timer)
67
+ signal?.removeEventListener?.('abort', onAbort)
68
+ resolve(value)
69
+ }
70
+ const onAbort = () => done(null)
71
+ timer = setTimeout(() => done(null), timeoutMs)
72
+ signal?.addEventListener?.('abort', onAbort, { once: true })
73
+ Promise.resolve(promise).then(done, () => done(null))
74
+ })
75
+ }
76
+
77
+ export const sessionIdOf = (session) => session?.id ?? session?.header?.id
package/src/tiers.js CHANGED
@@ -141,7 +141,7 @@ export function embedKey(embed) {
141
141
  export const TIERS = Object.freeze({
142
142
  // Keyword search over SQLite, inside the gateway. Needs no model and no network.
143
143
  keyword: Object.freeze({
144
- label: { en: 'keyword (SQLite, no model)', zh: '关键词(SQLite,不需要模型)' },
144
+ label: { en: 'keyword (SQLite, no model)', zh: '关键词检索(SQLite,无需模型)' },
145
145
  needs: { en: 'nothing; always available', zh: '无,始终可用' },
146
146
  vector: false,
147
147
  missing: () => [],
@@ -156,7 +156,7 @@ export const TIERS = Object.freeze({
156
156
  label: { en: 'embeddings endpoint (OpenAI-compatible)', zh: '向量接口(OpenAI 兼容)' },
157
157
  needs: {
158
158
  en: 'retrieval.url and retrieval.model (and retrieval.apiKey when the endpoint wants one)',
159
- zh: 'retrieval.url 和 retrieval.model(接口需要密钥时还要 retrieval.apiKey)',
159
+ zh: 'retrieval.url 和 retrieval.model(接口要求密钥时另需 retrieval.apiKey)',
160
160
  },
161
161
  vector: true,
162
162
  missing: (retrieval) => [!retrieval.url && 'retrieval.url', !retrieval.model && 'retrieval.model'].filter(Boolean),
@@ -171,10 +171,10 @@ export const TIERS = Object.freeze({
171
171
  // Semantic search with a model the dsh-feiyu-memgate-embed add-on runs on this machine and serves
172
172
  // on a loopback address.
173
173
  local: Object.freeze({
174
- label: { en: 'local model (dsh-feiyu-memgate-embed add-on)', zh: '本地模型(dsh-feiyu-memgate-embed 插件)' },
174
+ label: { en: 'local model (dsh-feiyu-memgate-embed add-on)', zh: '本地向量模型(dsh-feiyu-memgate-embed 插件)' },
175
175
  needs: {
176
176
  en: 'the dsh-feiyu-memgate-embed add-on, installed, switched on and with a model ready',
177
- zh: '安装并启用 dsh-feiyu-memgate-embed 插件,并且模型已就绪',
177
+ zh: '已安装并启用 dsh-feiyu-memgate-embed 插件,且模型已就绪',
178
178
  },
179
179
  vector: true,
180
180
  missing: (retrieval, facts) => (embedReady(facts?.embed) ? [] : ['dsh-feiyu-memgate-embed (ready)']),