dsh-feiyu-memgate 0.2.0 → 0.3.1
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 +61 -0
- package/README.md +43 -14
- package/README.zh.md +43 -14
- package/client/client.js +71 -2
- package/docs/DETAIL.en.md +23 -10
- package/docs/DETAIL.md +23 -10
- package/package.json +3 -2
- package/python/GATEWAY_VERSION.json +10 -10
- package/python/feiyu_memgate/backends/base.py +23 -0
- package/python/feiyu_memgate/backends/embedding.py +7 -7
- package/python/feiyu_memgate/backends/hybrid.py +4 -4
- package/python/feiyu_memgate/backends/inmemory.py +3 -2
- package/python/feiyu_memgate/backends/sqlite.py +2 -2
- package/python/feiyu_memgate/client/block.py +67 -6
- package/python/feiyu_memgate/client/http.py +2 -1
- package/python/feiyu_memgate/errors.py +1 -1
- package/python/feiyu_memgate/gateway/app.py +1 -1
- package/src/block.js +97 -4
- package/src/client.js +5 -1
- package/src/commands.js +9 -4
- package/src/config.js +19 -0
- package/src/gateway.js +143 -0
- package/src/mirror.py +132 -0
- package/src/plugin.js +199 -39
- package/src/tiers.js +36 -4
package/src/commands.js
CHANGED
|
@@ -28,7 +28,7 @@ const TEXT = {
|
|
|
28
28
|
' reset <key> return a setting to its default',
|
|
29
29
|
' on <feature> switch a feature on (see the modules.* settings)',
|
|
30
30
|
' off <feature> switch a feature off',
|
|
31
|
-
' tiers the retrieval tiers: availability and what each needs',
|
|
31
|
+
' tiers the retrieval tiers: availability and what each needs, and whether hybrid is on',
|
|
32
32
|
' use <tier> choose the retrieval tier: auto, keyword, endpoint or local',
|
|
33
33
|
' models local embedding models: size, memory, languages, licence and state',
|
|
34
34
|
' install <model> [--accept-licence <licence name>] [--confirm]',
|
|
@@ -71,6 +71,8 @@ const TEXT = {
|
|
|
71
71
|
statusTitle: 'feiyu-memgate status',
|
|
72
72
|
tiersTitle: (setting, active) => `Retrieval tier: ${setting}${active ? `, active: ${active}` : ''}.`,
|
|
73
73
|
tiersExternal: 'Retrieval tiers apply to the managed gateway; an external gateway uses its own configuration.',
|
|
74
|
+
hybridWord: 'keyword (hybrid)',
|
|
75
|
+
hybridLine: (on, active) => `Hybrid (keyword and vector search together, retrieval.hybrid): ${on ? (active ? 'on' : 'on, but it does nothing under the current tier') : 'off'}.`,
|
|
74
76
|
tierLine: (t) => `- ${t.name}: ${t.available ? 'available' : 'not available'}${t.active ? ' (active)' : ''}. Needs: ${t.needs}.${t.missing.length ? ` Missing: ${t.missing.join(', ')}.` : ''}`,
|
|
75
77
|
labels: {
|
|
76
78
|
gateway: 'Gateway', python: 'Python', retrieval: 'Retrieval', store: 'Store', embed: 'Embedding add-on',
|
|
@@ -101,7 +103,7 @@ const TEXT = {
|
|
|
101
103
|
' reset <键> 把一项设置恢复默认',
|
|
102
104
|
' on <功能> 打开一项功能(见 modules.* 设置)',
|
|
103
105
|
' off <功能> 关闭一项功能',
|
|
104
|
-
' tiers
|
|
106
|
+
' tiers 各种检索方式:是否可用,各需要什么,混合检索是否开着',
|
|
105
107
|
' use <方式> 选择检索方式:auto、keyword、endpoint 或 local',
|
|
106
108
|
' models 本地向量模型:大小、内存、语言、许可和状态',
|
|
107
109
|
' install <模型> [--accept-licence <许可名称>] [--confirm]',
|
|
@@ -143,6 +145,8 @@ const TEXT = {
|
|
|
143
145
|
statusTitle: 'feiyu-memgate 状态',
|
|
144
146
|
tiersTitle: (setting, active) => `检索方式设置:${setting}${active ? `,正在使用:${active}` : ''}。`,
|
|
145
147
|
tiersExternal: '检索方式只用于自带网关;外部网关按它自己的配置。',
|
|
148
|
+
hybridWord: '关键词(混合)',
|
|
149
|
+
hybridLine: (on, active) => `混合检索(关键词和向量一起查,retrieval.hybrid):${on ? (active ? '开' : '已开,但当前检索方式下不起作用') : '关'}。`,
|
|
146
150
|
tierLine: (t) => `- ${t.name}:${t.available ? '可用' : '不可用'}${t.active ? '(正在使用)' : ''}。需要:${t.needs}。${t.missing.length ? `还缺:${t.missing.join('、')}。` : ''}`,
|
|
147
151
|
labels: {
|
|
148
152
|
gateway: '网关', python: 'Python', retrieval: '检索', store: '存储', embed: '向量插件',
|
|
@@ -198,10 +202,10 @@ export function formatStatus(s, lang) {
|
|
|
198
202
|
const p = s.python
|
|
199
203
|
lines.push(`${t.labels.python}: ${!p ? t.pythonUnknown : p.found ? `${p.version} (${p.source}) ${p.executable}` : t.pythonNone}`)
|
|
200
204
|
const r = s.retrieval
|
|
201
|
-
lines.push(`${t.labels.retrieval}: ${r.setting}${r.active ? ` → ${r.active}` : ''}`)
|
|
205
|
+
lines.push(`${t.labels.retrieval}: ${r.setting}${r.active ? ` → ${r.active}${r.hybrid?.active ? ` + ${t.hybridWord}` : ''}` : ''}`)
|
|
202
206
|
if (s.store) {
|
|
203
207
|
const count = s.store.count === null ? t.countUnknown : t.memories(s.store.count)
|
|
204
|
-
lines.push(`${t.labels.store}: ${s.store.type}, ${s.store.file}, ${count}`)
|
|
208
|
+
lines.push(`${t.labels.store}: ${s.store.type}, ${s.store.file}${s.store.keywordFile ? ` + ${s.store.keywordFile}` : ''}, ${count}`)
|
|
205
209
|
}
|
|
206
210
|
}
|
|
207
211
|
const e = s.embed
|
|
@@ -356,6 +360,7 @@ function formatTiers(s, lang) {
|
|
|
356
360
|
const lines = [t.tiersTitle(r.setting, r.active)]
|
|
357
361
|
if (s.gateway.mode === 'external') lines.push(t.tiersExternal)
|
|
358
362
|
for (const tier of r.tiers) lines.push(t.tierLine({ ...tier, needs: TIERS[tier.name].needs[lang] ?? TIERS[tier.name].needs.en }))
|
|
363
|
+
if (r.hybrid && s.gateway.mode !== 'external') lines.push(t.hybridLine(r.hybrid.setting, r.hybrid.active))
|
|
359
364
|
return lines.join('\n')
|
|
360
365
|
}
|
|
361
366
|
|
package/src/config.js
CHANGED
|
@@ -85,6 +85,10 @@ const GROUPS = [
|
|
|
85
85
|
en: 'auto uses local while the dsh-feiyu-memgate-embed add-on has a model ready, and keyword otherwise.',
|
|
86
86
|
zh: 'auto:dsh-feiyu-memgate-embed 插件的模型就绪时用 local,否则用 keyword。',
|
|
87
87
|
} },
|
|
88
|
+
bool('hybrid', false, { en: 'Combine with keyword search (hybrid)', zh: '同时用关键词检索(混合)' }, {
|
|
89
|
+
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
|
+
}),
|
|
88
92
|
{ key: 'url', kind: 'string', default: '', format: 'url',
|
|
89
93
|
label: { en: 'Endpoint URL', zh: '向量接口地址' },
|
|
90
94
|
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。' } },
|
|
@@ -154,6 +158,21 @@ const GROUPS = [
|
|
|
154
158
|
],
|
|
155
159
|
label: { en: 'Language', zh: '语言' },
|
|
156
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: '不重复给同一条记忆' }, {
|
|
162
|
+
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: '这个对话里前面的记忆块还留着的记忆,不再给第二次(按记忆的文字比较)。没有新的就不加记忆块。关掉:只有和上一个记忆块完全相同时才不加。',
|
|
164
|
+
}),
|
|
165
|
+
bool('showAge', true, { en: "Show today's date and each memory's age", zh: '写明今天的日期和每条记忆的时间' }, {
|
|
166
|
+
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.",
|
|
167
|
+
zh: '记忆块里写明今天的日期(这台电脑上的日期),以及每条有日期的记忆是多久以前的事,例如“3 周前”。关掉:只写具体日期。',
|
|
168
|
+
}),
|
|
169
|
+
bool('failureNote', true, { en: 'Tell the model when recall failed', zh: '召回失败时告诉模型' }, {
|
|
170
|
+
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.',
|
|
171
|
+
zh: '这一轮的查询超时、出错,或者自带网关还在启动时,在用户消息之后加一行说明,免得模型当作“没有相关记忆”。连续失败时只在第一轮加。',
|
|
172
|
+
}),
|
|
173
|
+
{ key: 'captureMinChars', kind: 'integer', default: 4, min: 0, max: 50,
|
|
174
|
+
label: { en: 'Automatic capture: shortest message', zh: '自动记录:最短的消息' },
|
|
175
|
+
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 表示不按字数过滤。' } },
|
|
157
176
|
// broad is the default since 0.2.0, like the gateway's own default: in a chat a topic usually touches
|
|
158
177
|
// several memories. The block stays in the history, so precise is there for those who want less context.
|
|
159
178
|
{ key: 'profile', kind: 'choice', default: 'broad',
|
package/src/gateway.js
CHANGED
|
@@ -380,6 +380,113 @@ export const BOOTSTRAP = [
|
|
|
380
380
|
'sys.exit(main())',
|
|
381
381
|
].join('\n')
|
|
382
382
|
|
|
383
|
+
// ------------------------------------------------------------------ keyword index mirror
|
|
384
|
+
|
|
385
|
+
export const MIRROR_SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), 'mirror.py')
|
|
386
|
+
|
|
387
|
+
const MIRROR_COUNTS = ['added', 'removed', 'remaining']
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Run src/mirror.py once: it brings the keyword index of a hybrid store in line with the vector file
|
|
391
|
+
* (why: see that file). Same shape as the copy in src/migrate.js: a bounded helper, job as one JSON
|
|
392
|
+
* line on stdin, JSON lines on stdout, never kept alive by or outliving the host.
|
|
393
|
+
* python the gateway's interpreter ({ argv })
|
|
394
|
+
* mirror resolveStore().mirror: { keyword, vector }
|
|
395
|
+
* Resolves with { state: 'done' | 'partial' | 'failed' | 'stopped', added?, removed?, remaining?, kind? }.
|
|
396
|
+
* Returns { done: Promise, stop(): Promise }.
|
|
397
|
+
*/
|
|
398
|
+
export function runMirror({
|
|
399
|
+
python, mirror, dataDir, env = process.env, packageDir = PACKAGE_DIR,
|
|
400
|
+
deadlineSeconds = 60, marginSeconds = 30, stopGraceMs = 3000, spawnImpl = spawn,
|
|
401
|
+
}) {
|
|
402
|
+
let child = null
|
|
403
|
+
let stopped = false
|
|
404
|
+
const done = new Promise((resolve) => {
|
|
405
|
+
const job = { package_dir: packageDir, vector: mirror.vector, keyword: mirror.keyword, deadline_seconds: deadlineSeconds }
|
|
406
|
+
try {
|
|
407
|
+
child = spawnImpl(python.argv[0], [...python.argv.slice(1), '-I', '-B', MIRROR_SCRIPT], {
|
|
408
|
+
cwd: dataDir,
|
|
409
|
+
env: { ...scrubbedEnv(env), PYTHONIOENCODING: 'utf-8' },
|
|
410
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
411
|
+
windowsHide: true,
|
|
412
|
+
})
|
|
413
|
+
} catch (error) {
|
|
414
|
+
resolve({ state: 'failed', kind: typeof error?.code === 'string' ? error.code : 'spawn' })
|
|
415
|
+
return
|
|
416
|
+
}
|
|
417
|
+
trackChild(child)
|
|
418
|
+
child.unref?.()
|
|
419
|
+
for (const stream of [child.stdin, child.stdout]) stream?.unref?.()
|
|
420
|
+
child.stdin?.on('error', () => {})
|
|
421
|
+
child.stdin?.write(JSON.stringify(job) + '\n')
|
|
422
|
+
// A run that hangs ends after its own time limit and a margin.
|
|
423
|
+
const guard = setTimeout(() => {
|
|
424
|
+
try {
|
|
425
|
+
child.kill('SIGKILL')
|
|
426
|
+
} catch {
|
|
427
|
+
// already gone
|
|
428
|
+
}
|
|
429
|
+
}, (deadlineSeconds + marginSeconds) * 1000)
|
|
430
|
+
guard.unref?.()
|
|
431
|
+
|
|
432
|
+
let buffer = ''
|
|
433
|
+
let final = null
|
|
434
|
+
child.stdout?.setEncoding?.('utf8')
|
|
435
|
+
child.stdout?.on('data', (chunk) => {
|
|
436
|
+
buffer += chunk
|
|
437
|
+
let at
|
|
438
|
+
while ((at = buffer.indexOf('\n')) >= 0) {
|
|
439
|
+
const line = buffer.slice(0, at)
|
|
440
|
+
buffer = buffer.slice(at + 1)
|
|
441
|
+
let event
|
|
442
|
+
try {
|
|
443
|
+
event = JSON.parse(line)
|
|
444
|
+
} catch {
|
|
445
|
+
continue
|
|
446
|
+
}
|
|
447
|
+
const counts = {}
|
|
448
|
+
for (const key of MIRROR_COUNTS) if (Number.isSafeInteger(event?.[key]) && event[key] >= 0) counts[key] = event[key]
|
|
449
|
+
if (event?.event === 'done' || event?.event === 'partial') final = { state: event.event, ...counts }
|
|
450
|
+
else if (event?.event === 'failed') final = { state: 'failed', kind: /^[A-Za-z]{1,40}$/.test(event.kind) ? event.kind : 'error' }
|
|
451
|
+
}
|
|
452
|
+
})
|
|
453
|
+
let ended = false
|
|
454
|
+
const end = (code) => {
|
|
455
|
+
if (ended) return
|
|
456
|
+
ended = true
|
|
457
|
+
clearTimeout(guard)
|
|
458
|
+
untrackChild(child)
|
|
459
|
+
resolve(stopped ? { state: 'stopped' } : final ?? { state: 'failed', kind: code === null ? 'killed' : `exit${code}` })
|
|
460
|
+
}
|
|
461
|
+
child.once('exit', (code) => end(code))
|
|
462
|
+
child.once('error', () => end(null))
|
|
463
|
+
})
|
|
464
|
+
|
|
465
|
+
return {
|
|
466
|
+
done,
|
|
467
|
+
/** End the run now; what it wrote so far stays (the next run continues). */
|
|
468
|
+
async stop() {
|
|
469
|
+
stopped = true
|
|
470
|
+
const proc = child
|
|
471
|
+
if (!proc || proc.exitCode !== null || proc.signalCode !== null) return
|
|
472
|
+
try {
|
|
473
|
+
proc.stdin?.end()
|
|
474
|
+
} catch {
|
|
475
|
+
// already closed
|
|
476
|
+
}
|
|
477
|
+
const finished = await Promise.race([done.then(() => true), new Promise((r) => setTimeout(r, stopGraceMs, false))])
|
|
478
|
+
if (!finished) {
|
|
479
|
+
try {
|
|
480
|
+
proc.kill('SIGKILL')
|
|
481
|
+
} catch {
|
|
482
|
+
// already gone
|
|
483
|
+
}
|
|
484
|
+
await Promise.race([done, new Promise((r) => setTimeout(r, stopGraceMs))])
|
|
485
|
+
}
|
|
486
|
+
},
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
383
490
|
let instances = 0
|
|
384
491
|
|
|
385
492
|
// ------------------------------------------------------------------ manager
|
|
@@ -407,6 +514,8 @@ export function createGatewayManager({
|
|
|
407
514
|
stableMs = 60000,
|
|
408
515
|
stopGraceMs = 3000,
|
|
409
516
|
spawnImpl = spawn,
|
|
517
|
+
mirrorImpl = runMirror,
|
|
518
|
+
mirrorOptions = {},
|
|
410
519
|
} = {}) {
|
|
411
520
|
const instance = ++instances
|
|
412
521
|
const configFile = path.join(dataDir, `gateway-${process.pid}-${instance}.toml`)
|
|
@@ -421,6 +530,8 @@ export function createGatewayManager({
|
|
|
421
530
|
let python = null
|
|
422
531
|
let log = () => {}
|
|
423
532
|
let waiters = []
|
|
533
|
+
let mirroring = null // the running keyword index update, see src/mirror.py
|
|
534
|
+
let mirrorWarned = false
|
|
424
535
|
|
|
425
536
|
const warn = (message) => {
|
|
426
537
|
try {
|
|
@@ -482,6 +593,25 @@ export function createGatewayManager({
|
|
|
482
593
|
return false
|
|
483
594
|
}
|
|
484
595
|
|
|
596
|
+
// One run of the keyword index update; counts and kinds only go to the log.
|
|
597
|
+
async function mirror(spec) {
|
|
598
|
+
let result
|
|
599
|
+
try {
|
|
600
|
+
mirroring = mirrorImpl({ python, mirror: spec, dataDir, env, packageDir, ...mirrorOptions })
|
|
601
|
+
result = await mirroring.done
|
|
602
|
+
} catch {
|
|
603
|
+
result = { state: 'failed', kind: 'error' }
|
|
604
|
+
} finally {
|
|
605
|
+
mirroring = null
|
|
606
|
+
}
|
|
607
|
+
if (result.state === 'done' || result.state === 'partial') {
|
|
608
|
+
note(`keyword index ${result.state}: ${result.added ?? 0} added, ${result.removed ?? 0} removed, ${result.remaining ?? 0} remaining`)
|
|
609
|
+
} else if (result.state === 'failed') {
|
|
610
|
+
note(`keyword index update failed (${result.kind ?? 'error'})`)
|
|
611
|
+
}
|
|
612
|
+
return result
|
|
613
|
+
}
|
|
614
|
+
|
|
485
615
|
async function launch() {
|
|
486
616
|
timer = null
|
|
487
617
|
if (stopping) return
|
|
@@ -497,6 +627,17 @@ export function createGatewayManager({
|
|
|
497
627
|
return
|
|
498
628
|
}
|
|
499
629
|
if (stopping) return removeConfig()
|
|
630
|
+
// A hybrid store: bring the keyword index in line with the vector file first. The gateway is not
|
|
631
|
+
// running now, so nothing else writes to either file. A failed or partial update never keeps the
|
|
632
|
+
// gateway from starting: the next start continues where this one stopped.
|
|
633
|
+
if (config.store.mirror) {
|
|
634
|
+
const result = await mirror(config.store.mirror)
|
|
635
|
+
if (stopping) return removeConfig()
|
|
636
|
+
if (result.state === 'failed' && !mirrorWarned) {
|
|
637
|
+
mirrorWarned = true
|
|
638
|
+
warn(`feiyu-memgate: the keyword index could not be updated (${result.kind ?? 'error'}); hybrid search starts with what it has`)
|
|
639
|
+
}
|
|
640
|
+
}
|
|
500
641
|
const token = randomBytes(32).toString('base64url')
|
|
501
642
|
const proc = spawnImpl(python.argv[0], [
|
|
502
643
|
...python.argv.slice(1),
|
|
@@ -614,6 +755,8 @@ export function createGatewayManager({
|
|
|
614
755
|
timer = null
|
|
615
756
|
const proc = child
|
|
616
757
|
current = null
|
|
758
|
+
// A keyword index update still running ends now; launch() then sees `stopping` and spawns nothing.
|
|
759
|
+
if (mirroring) await mirroring.stop?.()
|
|
617
760
|
if (proc && proc.exitCode === null && proc.signalCode === null) {
|
|
618
761
|
const gone = new Promise((resolve) => {
|
|
619
762
|
proc.once('exit', resolve)
|
package/src/mirror.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Bring the keyword index of a hybrid store in line with its vector store file.
|
|
2
|
+
|
|
3
|
+
dsh-feiyu-memgate runs this with the interpreter that runs its gateway, right before it starts the
|
|
4
|
+
gateway (the gateway is not running then, so nothing else writes to either file):
|
|
5
|
+
|
|
6
|
+
python -I -B mirror.py
|
|
7
|
+
|
|
8
|
+
Why it exists: the vector file holds every memory of the store. While the hybrid switch is off,
|
|
9
|
+
saving, forgetting, deleting and the copy from the keyword store touch only that file, so the keyword
|
|
10
|
+
index next to it falls behind: a memory forgotten in the meantime would come back through the index,
|
|
11
|
+
and a memory saved in the meantime would have no keyword signal. This script makes the index hold
|
|
12
|
+
exactly the refs of the vector file: it removes the refs the vector file no longer has and adds the
|
|
13
|
+
ones it has not indexed yet, oldest first. It is idempotent: a second run right after a finished one
|
|
14
|
+
changes nothing.
|
|
15
|
+
|
|
16
|
+
The job arrives as one line of JSON on stdin: { package_dir, vector, keyword, deadline_seconds }, where
|
|
17
|
+
`vector` is the path of the vector store file and `keyword` is the keyword index as a gateway store
|
|
18
|
+
table ({ "type": "sqlite", "path": ... }). stdin then stays open, and the script exits as soon as it
|
|
19
|
+
closes: the plugin stopped the run, or the host process went away however it went away. Progress goes
|
|
20
|
+
to stdout as JSON lines. Nothing printed names a memory text, a ref, a key or a path: counts, and the
|
|
21
|
+
kind of error when a run fails. Exit code 0 for done and partial, 2 for failed.
|
|
22
|
+
|
|
23
|
+
The vector file is only read, through SQLite directly and read-only (it needs no embeddings endpoint).
|
|
24
|
+
The keyword index is written through the gateway's own backend, so its layout is always the one the
|
|
25
|
+
gateway expects. A run that reaches its time limit reports `partial` and the next start continues.
|
|
26
|
+
"""
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import sqlite3
|
|
30
|
+
import sys
|
|
31
|
+
import threading
|
|
32
|
+
import time
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
BATCH = 200
|
|
36
|
+
DEFAULT_DEADLINE = 60.0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _watch_stdin():
|
|
40
|
+
try:
|
|
41
|
+
while sys.stdin.buffer.read(4096):
|
|
42
|
+
pass
|
|
43
|
+
except BaseException: # noqa: BLE001 - any end of stdin ends the run
|
|
44
|
+
pass
|
|
45
|
+
os._exit(3)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def emit(event, **fields):
|
|
49
|
+
sys.stdout.write(json.dumps(dict(event=event, **fields)) + "\n")
|
|
50
|
+
sys.stdout.flush()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def open_vector(path):
|
|
54
|
+
"""A read-only connection to the vector store file, or None when there is none yet."""
|
|
55
|
+
if not os.path.exists(path):
|
|
56
|
+
return None
|
|
57
|
+
return sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, timeout=10.0)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def vector_refs(db):
|
|
61
|
+
"""Every ref of the vector store, oldest first. A file without the table holds nothing."""
|
|
62
|
+
if db is None:
|
|
63
|
+
return []
|
|
64
|
+
try:
|
|
65
|
+
return [row[0] for row in db.execute("SELECT ref FROM memories ORDER BY created_at, ref")]
|
|
66
|
+
except sqlite3.OperationalError:
|
|
67
|
+
return []
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def vector_items(db, refs):
|
|
71
|
+
"""(text, ref, date) of the given refs, in that order. Empty texts are left out."""
|
|
72
|
+
marks = ",".join("?" * len(refs))
|
|
73
|
+
rows = db.execute("SELECT ref, text, date FROM memories WHERE ref IN (%s)" % marks, refs).fetchall()
|
|
74
|
+
found = {ref: (text, date) for ref, text, date in rows}
|
|
75
|
+
return [(found[ref][0], ref, found[ref][1]) for ref in refs
|
|
76
|
+
if ref in found and isinstance(found[ref][0], str) and found[ref][0].strip()]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def main():
|
|
80
|
+
job = json.loads(sys.stdin.buffer.readline().decode("utf-8"))
|
|
81
|
+
threading.Thread(target=_watch_stdin, name="parent-watch", daemon=True).start()
|
|
82
|
+
sys.path.insert(0, job["package_dir"])
|
|
83
|
+
from feiyu_memgate import registry # noqa: E402 - the package path is part of the job
|
|
84
|
+
|
|
85
|
+
deadline = time.monotonic() + float(job.get("deadline_seconds", DEFAULT_DEADLINE))
|
|
86
|
+
keyword = None
|
|
87
|
+
vector = None
|
|
88
|
+
try:
|
|
89
|
+
vector = open_vector(job["vector"])
|
|
90
|
+
wanted = vector_refs(vector)
|
|
91
|
+
keyword = registry.create("backend", job["keyword"])
|
|
92
|
+
have = [ref for ref, _ in keyword.refs()]
|
|
93
|
+
wanted_set = set(wanted)
|
|
94
|
+
stale = [ref for ref in have if ref not in wanted_set]
|
|
95
|
+
have_set = set(have)
|
|
96
|
+
missing = [ref for ref in wanted if ref not in have_set]
|
|
97
|
+
emit("start", vector=len(wanted), keyword=len(have))
|
|
98
|
+
|
|
99
|
+
removed = 0
|
|
100
|
+
for ref in stale:
|
|
101
|
+
if time.monotonic() >= deadline:
|
|
102
|
+
break
|
|
103
|
+
keyword.delete(ref)
|
|
104
|
+
removed += 1
|
|
105
|
+
|
|
106
|
+
added = 0
|
|
107
|
+
handled = 0 # refs looked at, whether added or skipped as empty
|
|
108
|
+
while handled < len(missing) and time.monotonic() < deadline and removed == len(stale):
|
|
109
|
+
chunk = missing[handled:handled + BATCH]
|
|
110
|
+
for text, ref, date in vector_items(vector, chunk):
|
|
111
|
+
keyword.put(text, ref=ref, date=date)
|
|
112
|
+
added += 1
|
|
113
|
+
handled += len(chunk)
|
|
114
|
+
emit("progress", added=added, removed=removed, remaining=len(missing) - handled + len(stale) - removed)
|
|
115
|
+
|
|
116
|
+
remaining = len(missing) - handled + len(stale) - removed
|
|
117
|
+
emit("done" if remaining == 0 else "partial", added=added, removed=removed, remaining=remaining)
|
|
118
|
+
return 0
|
|
119
|
+
except Exception as error: # noqa: BLE001 - reported by kind only
|
|
120
|
+
emit("failed", kind=type(error).__name__)
|
|
121
|
+
return 2
|
|
122
|
+
finally:
|
|
123
|
+
for resource in (keyword, vector):
|
|
124
|
+
try:
|
|
125
|
+
if resource is not None:
|
|
126
|
+
resource.close()
|
|
127
|
+
except Exception: # noqa: BLE001
|
|
128
|
+
pass
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == "__main__":
|
|
132
|
+
sys.exit(main())
|