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.
- package/CHANGELOG.md +73 -12
- package/README.md +68 -11
- package/README.zh.md +93 -36
- package/client/README.md +267 -0
- package/client/art/mascot-asleep.webp +0 -0
- package/client/art/mascot-busy.webp +0 -0
- package/client/art/mascot-nag.webp +0 -0
- package/client/art/mascot-ready.webp +0 -0
- package/client/art/mascot-trouble.webp +0 -0
- package/client/client.js +4226 -1269
- package/client/src/clipboard.cjs +52 -0
- package/client/src/constants.cjs +43 -0
- package/client/src/fields.cjs +960 -0
- package/client/src/hooks.cjs +220 -0
- package/client/src/i18n.cjs +444 -0
- package/client/src/index.cjs +69 -0
- package/client/src/kit/controls.cjs +189 -0
- package/client/src/kit/icons.cjs +40 -0
- package/client/src/kit/layout.cjs +124 -0
- package/client/src/layout.cjs +143 -0
- package/client/src/model/changelog.cjs +29 -0
- package/client/src/model/feedback.cjs +168 -0
- package/client/src/model/form.cjs +83 -0
- package/client/src/model/models.cjs +87 -0
- package/client/src/model/overview.cjs +111 -0
- package/client/src/model/page.cjs +104 -0
- package/client/src/model/status.cjs +57 -0
- package/client/src/model/trial.cjs +111 -0
- package/client/src/net.cjs +101 -0
- package/client/src/react.cjs +11 -0
- package/client/src/theme/page.css +1284 -0
- package/client/src/theme/styles.cjs +43 -0
- package/client/src/view/feedback.cjs +180 -0
- package/client/src/view/field-row.cjs +98 -0
- package/client/src/view/hero.cjs +54 -0
- package/client/src/view/markdown.cjs +96 -0
- package/client/src/view/models.cjs +154 -0
- package/client/src/view/page.cjs +199 -0
- package/client/src/view/settings-tab.cjs +78 -0
- package/client/src/view/tabs.cjs +71 -0
- package/client/src/view/trial.cjs +84 -0
- package/docs/DETAIL.en.md +55 -6
- package/docs/DETAIL.md +63 -14
- package/locale/zh.json +1 -1
- package/package.json +2 -1
- package/python/GATEWAY_VERSION.json +37 -31
- package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
- package/python/feiyu_memgate/backends/base.py +121 -6
- package/python/feiyu_memgate/backends/embedding.py +265 -178
- package/python/feiyu_memgate/backends/hybrid.py +330 -83
- package/python/feiyu_memgate/backends/inmemory.py +115 -24
- package/python/feiyu_memgate/backends/openviking.py +7 -10
- package/python/feiyu_memgate/backends/sqlite.py +129 -145
- package/python/feiyu_memgate/builtins.py +1 -0
- package/python/feiyu_memgate/cli.py +124 -20
- package/python/feiyu_memgate/client/block.py +4 -2
- package/python/feiyu_memgate/client/http.py +106 -19
- package/python/feiyu_memgate/client/local.py +4 -3
- package/python/feiyu_memgate/config.py +118 -24
- package/python/feiyu_memgate/core/limits.py +2 -1
- package/python/feiyu_memgate/core/pool.py +29 -2
- package/python/feiyu_memgate/core/recall.py +179 -10
- package/python/feiyu_memgate/core/redact.py +4 -2
- package/python/feiyu_memgate/core/stages.py +52 -9
- package/python/feiyu_memgate/core/tidy.py +2 -1
- package/python/feiyu_memgate/core/watch.py +3 -2
- package/python/feiyu_memgate/core/write.py +9 -3
- package/python/feiyu_memgate/forgetting/archive.py +38 -10
- package/python/feiyu_memgate/forgetting/engine.py +46 -10
- package/python/feiyu_memgate/forgetting/stage.py +4 -2
- package/python/feiyu_memgate/gateway/app.py +168 -272
- package/python/feiyu_memgate/gateway/fields.py +121 -0
- package/python/feiyu_memgate/gateway/policies.py +162 -0
- package/python/feiyu_memgate/gateway/server.py +12 -4
- package/python/feiyu_memgate/gateway/tokens.py +137 -0
- package/python/feiyu_memgate/gateway/validate.py +120 -0
- package/python/feiyu_memgate/identity.py +152 -0
- package/python/feiyu_memgate/model.py +170 -2
- package/python/feiyu_memgate/registry.py +6 -3
- package/python/feiyu_memgate/tools/crypto.py +5 -4
- package/python/feiyu_memgate/tools/evaluate.py +2 -1
- package/python/feiyu_memgate/tools/tenants.py +2 -0
- package/src/block.js +9 -3
- package/src/capture.js +98 -0
- package/src/catalogue.js +4 -4
- package/src/changelog.js +72 -0
- package/src/client.js +145 -10
- package/src/commands.js +112 -62
- package/src/config.js +139 -62
- package/src/followup.js +139 -0
- package/src/gateway.js +79 -4
- package/src/migrate.py +54 -9
- package/src/mirror.py +44 -7
- package/src/plugin.js +416 -412
- package/src/pool.js +298 -0
- package/src/recent.js +68 -0
- package/src/relevance.js +80 -0
- package/src/routes.js +320 -0
- package/src/setup.js +36 -36
- package/src/shared.js +77 -0
- package/src/tiers.js +4 -4
- package/src/time.js +27 -0
- 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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['安装向量插件需要你明确确认。', '
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: ['
|
|
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: '
|
|
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
|
|
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: '
|
|
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: '
|
|
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
|
|
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: '
|
|
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: '
|
|
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)']),
|