dsh-memu-memory 1.2.5 → 1.2.7
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/AGENTS.md +3 -1
- package/README.md +3 -3
- package/README.zh.md +3 -3
- package/docs/contributing.md +1 -1
- package/docs/env-and-commands.md +1 -0
- package/docs/host-adaptation.md +318 -0
- package/docs/host-api.md +29 -5
- package/docs/memory-semantics.md +12 -7
- package/docs/troubleshooting.md +15 -9
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +291 -37
- package/lib/consolidation-ledger.js +46 -1
- package/lib/consolidation-worker.js +1 -0
- package/lib/curator-policy.js +98 -0
- package/lib/cycle.js +51 -17
- package/lib/fork-model.js +312 -0
- package/lib/index.js +8 -0
- package/lib/memory.js +36 -12
- package/lib/memu.js +318 -3
- package/lib/private.js +352 -70
- package/lib/prompts/private-consolidation.mixed.md +1 -0
- package/lib/prompts/private-consolidation.rp.md +1 -0
- package/lib/prompts/private-policy.mixed.md +1 -0
- package/lib/prompts/private-policy.rp.md +1 -1
- package/lib/recall-cache.js +204 -0
- package/lib/rpc.js +48 -7
- package/lib/salient-wake.js +38 -2
- package/lib/state.js +46 -6
- package/lib/text-retrieval.js +221 -28
- package/lib/tokenizer-v2.js +295 -0
- package/lib/webui/standalone.css +17 -1
- package/package.json +1 -1
- package/scripts/bench-recall.mjs +142 -0
- package/scripts/check-seed-compat.mjs +118 -0
- package/tests/absorb-review.test.mjs +2 -1
- package/tests/backend-compensation.test.mjs +1 -1
- package/tests/consolidation-fork.test.mjs +199 -7
- package/tests/curator-absorb.test.mjs +2 -1
- package/tests/curator-clusters.test.mjs +9 -2
- package/tests/curator-commit.test.mjs +2 -1
- package/tests/curator-link.test.mjs +2 -1
- package/tests/curator-pairing.test.mjs +52 -8
- package/tests/curator-review-mode.test.mjs +2 -1
- package/tests/cycle.test.mjs +2 -2
- package/tests/dynamic-rrf.test.mjs +179 -0
- package/tests/fork-model.test.mjs +345 -0
- package/tests/loader.mjs +3 -0
- package/tests/managed-memory.test.mjs +1 -1
- package/tests/negation-polarity.test.mjs +135 -0
- package/tests/recall-cache.test.mjs +290 -0
- package/tests/recall-dedup.test.mjs +1 -1
- package/tests/salient-wake.test.mjs +28 -1
- package/tests/stubs/dsh-llm-pi-ai.js +13 -0
- package/tests/stubs/dsh-schedule.js +35 -0
- package/tests/tokenizer-v2.test.mjs +142 -0
- package/tests/ui-defaults.test.mjs +1 -1
package/lib/index.js
CHANGED
|
@@ -9,6 +9,7 @@ import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibrari
|
|
|
9
9
|
import { pruneOrphanEntitiesAll } from './graph.js'
|
|
10
10
|
import { closeEmbeddingWorkers } from './local-embedding-manager.js'
|
|
11
11
|
import { bootstrapLocalVector } from './local-vector-service.js'
|
|
12
|
+
import { closeMemuResident, prewarmMemuResident } from './memu.js'
|
|
12
13
|
import { vectorStatus } from './vector-profile.js'
|
|
13
14
|
import { setWarnSink } from './paths.js'
|
|
14
15
|
|
|
@@ -30,6 +31,10 @@ function startLocalVectorBootstrap(ctx) {
|
|
|
30
31
|
const catalogId = state?.active?.profile?.catalogId || state?.requested?.catalogId || null
|
|
31
32
|
if (!catalogId) return
|
|
32
33
|
const timer = setTimeout(() => {
|
|
34
|
+
// The resident interpreter only pays the MemU import once; it does not wait
|
|
35
|
+
// for the embedding worker, so warming it in parallel with the runtime
|
|
36
|
+
// bootstrap is safe and keeps the first recall from paying the cold start.
|
|
37
|
+
void prewarmMemuResident()
|
|
33
38
|
void bootstrapLocalVector({ confirmed: false }).then((ready) => {
|
|
34
39
|
try { ctx.logger?.info?.(`dsh-memu-memory: managed local embedding runtime ready (${String(ready?.model || catalogId)} ${Number(ready?.dimension) || '?'}d)`) } catch {}
|
|
35
40
|
}).catch((error) => {
|
|
@@ -162,6 +167,9 @@ export function apply(ctx, config) {
|
|
|
162
167
|
// afterwards instead of failing.
|
|
163
168
|
if (!inPreset && typeof ctx.effect === 'function') {
|
|
164
169
|
ctx.effect(() => () => { closeEmbeddingWorkers() }, 'dsh-memu-memory: embedding workers')
|
|
170
|
+
// The resident interpreter is also process-global; leaving it behind would keep
|
|
171
|
+
// a Python process (and its sqlite handles) alive after this plugin unloads.
|
|
172
|
+
ctx.effect(() => () => { closeMemuResident() }, 'dsh-memu-memory: memu resident engine')
|
|
165
173
|
}
|
|
166
174
|
|
|
167
175
|
const disposeCycle = inPreset ? null : registerCycle(ctx, {
|
package/lib/memory.js
CHANGED
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
updatePrivateIndex, updateGlobalIndex,
|
|
9
9
|
newMemoryId, getSettings, effectiveVectorRoute, getActiveCue, consumeCue,
|
|
10
10
|
getLibrary, setSessionBinding, setRecallError, effectiveScope, listLibrariesAll,
|
|
11
|
-
listLibraries, listSessionBindings, getWorkspacePolicy,
|
|
11
|
+
listLibraries, listSessionBindings, getWorkspacePolicy, memoryRevision,
|
|
12
12
|
} from './state.js'
|
|
13
13
|
import { stamp, redactSecrets, retryStoreWrite, warn } from './paths.js'
|
|
14
14
|
import { scopeGenerationOf } from './consolidation-ledger.js'
|
|
@@ -22,6 +22,11 @@ import { normalizeMemoryContext, contextVisible, sameFactContext } from './conte
|
|
|
22
22
|
import { activeEntryStamp, assertGeneration, assertVectorWriteAllowed, captureGeneration, enrollActiveLibrary, hasActiveVectorGeneration, isVectorStateError, readVectorState, withVectorWrite } from './vector-profile.js'
|
|
23
23
|
import { bigrams, dice, similarTexts, DUP_DICE, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
|
|
24
24
|
import { applyAbsorbIndexTransaction } from './curator.js'
|
|
25
|
+
import { recallCache, recallCacheKey } from './recall-cache.js'
|
|
26
|
+
|
|
27
|
+
// P1-1 召回缓存。缓存自身出错时 fail-open,
|
|
28
|
+
// 但真实故障必须留痕(AGENTS.md §1 规则 10):把缓存内部的吞没错误接到 warn 上。
|
|
29
|
+
recallCache.setErrorHandler((info) => warn('recall cache failed open: ' + (info?.message || info)))
|
|
25
30
|
|
|
26
31
|
const HALF_LIFE_DAYS = 14
|
|
27
32
|
// A short-term entry is meant to live for the length of a conversation, not a
|
|
@@ -183,7 +188,7 @@ async function withManagedGlobalWrite(action) {
|
|
|
183
188
|
return withVectorWrite(() => { assertVectorWriteAllowed(); return action() })
|
|
184
189
|
}
|
|
185
190
|
|
|
186
|
-
async function managedRecall({ exec, index, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false }) {
|
|
191
|
+
async function managedRecall({ exec, index, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null }) {
|
|
187
192
|
const local = localRecall(index, query)
|
|
188
193
|
try {
|
|
189
194
|
if (intent.error) throw intent.error
|
|
@@ -191,14 +196,33 @@ async function managedRecall({ exec, index, query, topK, libraryId, automatic =
|
|
|
191
196
|
if (byId) return { ...local, recallRoute: 'local' }
|
|
192
197
|
const db = captured ? (libraryId ? captured.libraries[libraryId] : captured.global) : (libraryId ? memoryDbPath(libraryId) : globalDbPath())
|
|
193
198
|
if (!db) throw new Error('managed vector generation has no database for library ' + libraryId)
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
199
|
+
// P1-1 召回缓存:只缓存成功的语义召回——byId 与 local-fallback 都在上面短路或走
|
|
200
|
+
// catch,不会进入这里;producer 抛错不缓存,原样落到下面的 local-fallback。
|
|
201
|
+
// 键覆盖所有能改变融合结果的输入。失效三层:
|
|
202
|
+
// · revision = memoryRevision():state.js 在 savePrivateIndex/saveGlobalIndex/
|
|
203
|
+
// saveState/clearCaches 收敛处自增,本进程所有索引与状态写入(含 curator/
|
|
204
|
+
// graph/rpc/migrate 的写)写完键即变,无需逐写路径挂钩;
|
|
205
|
+
// · generation = captureGeneration() 的代数 token:向量代际切换(迁移/换档案)
|
|
206
|
+
// 后语义腿来自另一个向量库,键随之改变;
|
|
207
|
+
// · TTL(默认 120s)兜底跨进程写入、expiresAt 到点与一切漏网。
|
|
208
|
+
// recallCache.bumpGeneration() 是手动闸(测试/运维)。
|
|
209
|
+
const binding = peekBinding(exec)
|
|
210
|
+
const cacheKey = recallCacheKey({
|
|
211
|
+
query, topK, libraryId, byId, route: intent.route, generation: captured?.token ?? null,
|
|
212
|
+
revision: memoryRevision(), domain, automatic,
|
|
213
|
+
sessionId: memorySessionId(exec), context: binding?.memoryContext ?? null,
|
|
214
|
+
})
|
|
215
|
+
const result = await recallCache.wrap(cacheKey, async () => {
|
|
216
|
+
const semantic = await retrieveImpl({ query, db, route: intent.route, timeoutMs: HYBRID_SEMANTIC_TIMEOUT_MS })
|
|
217
|
+
if (semantic?.parseWarning) throw new Error(semantic.parseWarning)
|
|
218
|
+
if (!Array.isArray(semantic?.files)) throw new Error('managed vector recall returned no file list')
|
|
219
|
+
if (captured) assertGeneration(captured)
|
|
220
|
+
const fused = fuseRecallCandidates({ local: local.files, semantic: semantic.files, index,
|
|
221
|
+
limit: hybridCandidateLimit(topK), automatic, sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
|
|
222
|
+
return { ...semantic, files: fused.files, recallRoute: 'managed-vector-rrf', fusion: fused.debug }
|
|
223
|
+
})
|
|
200
224
|
clearRecallError(exec)
|
|
201
|
-
return
|
|
225
|
+
return result
|
|
202
226
|
} catch (error) {
|
|
203
227
|
const reason = rememberRecallError(exec, error)
|
|
204
228
|
return { ...local, recallRoute: 'local-fallback', errors: ['semantic recall failed: ' + reason] }
|
|
@@ -1761,7 +1785,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
|
|
|
1761
1785
|
}
|
|
1762
1786
|
const managed = await managedRecall({
|
|
1763
1787
|
exec, index: scoped, query, topK, libraryId: source.libraryId,
|
|
1764
|
-
automatic, intent, retrieveImpl, byId,
|
|
1788
|
+
automatic, intent, retrieveImpl, byId, domain,
|
|
1765
1789
|
})
|
|
1766
1790
|
lists.push({ libraryId: source.libraryId, files: managed.files || [], errors: managed.errors || [] })
|
|
1767
1791
|
}
|
|
@@ -1829,7 +1853,7 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
|
|
|
1829
1853
|
const result = sources.length === 1
|
|
1830
1854
|
? (route === 'lexical' || byId
|
|
1831
1855
|
? { ...localRecall(sources[0].index, query), recallRoute: 'local' }
|
|
1832
|
-
: await managedRecall({ exec, index: sources[0].index, query, topK: wanted, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId }))
|
|
1856
|
+
: await managedRecall({ exec, index: sources[0].index, query, topK: wanted, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId, domain }))
|
|
1833
1857
|
: await recallCrossLibrary({ exec, sources, query, topK: wanted, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain })
|
|
1834
1858
|
const current = peekBinding(exec)
|
|
1835
1859
|
if (!current || current.libraryId !== binding.libraryId) throw new Error('memory scope changed during recall; retry')
|
|
@@ -2746,7 +2770,7 @@ export async function globalRecall({ exec, query, topK, relevanceThreshold, retr
|
|
|
2746
2770
|
.filter(([, entry]) => appliesToDomain(entry, binding))) }
|
|
2747
2771
|
const result = effectiveVectorRoute() !== 'lexical'
|
|
2748
2772
|
? await managedRecall({ exec, index: domainIndex, query, topK: topK || settings.globalTopK || 3,
|
|
2749
|
-
libraryId: null, automatic: true, intent, retrieveImpl })
|
|
2773
|
+
libraryId: null, automatic: true, intent, retrieveImpl, domain: domainOf(binding) })
|
|
2750
2774
|
: localRecall(index, query, (file) => appliesToDomain(file.entry, binding))
|
|
2751
2775
|
if (peeked) {
|
|
2752
2776
|
const current = peekBinding(exec)
|
package/lib/memu.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import fs from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import { spawn } from 'node:child_process'
|
|
4
|
-
import { dataDir, ensureDir, redactSecrets, windowsSystemEnv } from './paths.js'
|
|
4
|
+
import { dataDir, ensureDir, redactSecrets, warn, windowsSystemEnv } from './paths.js'
|
|
5
5
|
import { ENGINE_VERSION, readCurrent, verifyEngine } from './engine.js'
|
|
6
|
-
import { getSettings } from './state.js'
|
|
6
|
+
import { effectiveVectorRoute, getSettings } from './state.js'
|
|
7
7
|
import { activeProfile, captureVectorGeneration, assertVectorGeneration, assertProfileVerified, assertMigrationProfile } from './vector-profile.js'
|
|
8
8
|
import { embeddingWorkerManager } from './local-embedding-manager.js'
|
|
9
9
|
import { modelIdForRole } from './local-embedding-protocol.js'
|
|
@@ -79,6 +79,316 @@ function runRaw(pythonArgs, { env, timeoutMs = 90_000, cwd } = {}) {
|
|
|
79
79
|
})
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
// ---- resident engine ---------------------------------------------------------
|
|
83
|
+
// MemU is a Python CLI: every command normally pays the whole import chain
|
|
84
|
+
// (~2 s), because the process exits when the command ends. Local vector mode
|
|
85
|
+
// calls the same three commands on every turn (recall) and on every write,
|
|
86
|
+
// so one warm interpreter removes that constant from both paths.
|
|
87
|
+
//
|
|
88
|
+
// The worker imports ``memu.cli`` once and calls the exact ``main(argv)`` the
|
|
89
|
+
// CLI entrypoint calls — command semantics stay in MemU's own code. One JSON
|
|
90
|
+
// object per line is the protocol on both directions. ``_close_backends`` is
|
|
91
|
+
// what keeps the per-command process model intact: a command that ends must
|
|
92
|
+
// release its sqlite handles, otherwise backup / migration / rollback would
|
|
93
|
+
// see a database still held open by a process that is supposed to be idle.
|
|
94
|
+
const RESIDENT_SCRIPT = String.raw`
|
|
95
|
+
import contextlib
|
|
96
|
+
import io
|
|
97
|
+
import json
|
|
98
|
+
import os
|
|
99
|
+
import sys
|
|
100
|
+
|
|
101
|
+
for _stream in (sys.stdin, sys.stdout, sys.stderr):
|
|
102
|
+
try:
|
|
103
|
+
_stream.reconfigure(encoding="utf-8", errors="replace")
|
|
104
|
+
except Exception:
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _reply(payload):
|
|
109
|
+
sys.stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
|
|
110
|
+
sys.stdout.flush()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
BASE_ENV = dict(os.environ)
|
|
114
|
+
try:
|
|
115
|
+
import memu.cli as _cli
|
|
116
|
+
except Exception as _exc:
|
|
117
|
+
_reply({"ready": False, "error": "memu import failed: %s" % (_exc,)})
|
|
118
|
+
raise SystemExit(1)
|
|
119
|
+
|
|
120
|
+
_original_build = _cli.build_agentic_memory_backend_from_env
|
|
121
|
+
_created = []
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _tracked_build(*args, **kwargs):
|
|
125
|
+
backend = _original_build(*args, **kwargs)
|
|
126
|
+
_created.append(backend)
|
|
127
|
+
return backend
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
_cli.build_agentic_memory_backend_from_env = _tracked_build
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _close_backends():
|
|
134
|
+
while _created:
|
|
135
|
+
backend = _created.pop()
|
|
136
|
+
try:
|
|
137
|
+
closer = getattr(getattr(backend, "database", None), "close", None)
|
|
138
|
+
if callable(closer):
|
|
139
|
+
closer()
|
|
140
|
+
except Exception:
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
_reply({"ready": True})
|
|
145
|
+
|
|
146
|
+
for _line in sys.stdin:
|
|
147
|
+
_line = _line.strip()
|
|
148
|
+
if not _line:
|
|
149
|
+
continue
|
|
150
|
+
try:
|
|
151
|
+
_request = json.loads(_line)
|
|
152
|
+
except Exception:
|
|
153
|
+
continue
|
|
154
|
+
if _request.get("op") == "shutdown":
|
|
155
|
+
break
|
|
156
|
+
os.environ.clear()
|
|
157
|
+
os.environ.update(BASE_ENV)
|
|
158
|
+
for _key, _value in (_request.get("env") or {}).items():
|
|
159
|
+
if _value is None:
|
|
160
|
+
os.environ.pop(str(_key), None)
|
|
161
|
+
else:
|
|
162
|
+
os.environ[str(_key)] = str(_value)
|
|
163
|
+
_argv = [str(_item) for _item in (_request.get("argv") or [])]
|
|
164
|
+
_out = io.StringIO()
|
|
165
|
+
_err = io.StringIO()
|
|
166
|
+
_code = 1
|
|
167
|
+
try:
|
|
168
|
+
with contextlib.redirect_stdout(_out), contextlib.redirect_stderr(_err):
|
|
169
|
+
_result = _cli.main(_argv)
|
|
170
|
+
_code = 0 if _result is None else int(_result)
|
|
171
|
+
except BaseException as _exc:
|
|
172
|
+
_err.write("%s: %s\n" % (type(_exc).__name__, _exc))
|
|
173
|
+
finally:
|
|
174
|
+
_close_backends()
|
|
175
|
+
_reply({"id": _request.get("id"), "code": _code, "stdout": _out.getvalue(), "stderr": _err.getvalue()})
|
|
176
|
+
`
|
|
177
|
+
|
|
178
|
+
const RESIDENT_READY_TIMEOUT_MS = 30_000
|
|
179
|
+
const RESIDENT_LINE_LIMIT = 8 << 20
|
|
180
|
+
|
|
181
|
+
function residentKey(current) {
|
|
182
|
+
return `${current.python}\u0000${String(current.version || '')}`
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function residentBaseEnv() {
|
|
186
|
+
return {
|
|
187
|
+
...windowsSystemEnv(),
|
|
188
|
+
...process.env,
|
|
189
|
+
PYTHONUTF8: '1',
|
|
190
|
+
PYTHONIOENCODING: 'utf-8',
|
|
191
|
+
MEMU_MEMORY_MODE: memoryMode(),
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function stopResident(record, failure = null) {
|
|
196
|
+
if (!record) return
|
|
197
|
+
record.stopping = true
|
|
198
|
+
if (residentRecord === record) residentRecord = null
|
|
199
|
+
if (failure) {
|
|
200
|
+
for (const pending of record.pending.values()) {
|
|
201
|
+
clearTimeout(pending.timer)
|
|
202
|
+
pending.reject(failure)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
record.pending.clear()
|
|
206
|
+
try { record.child?.stdin?.end() } catch {}
|
|
207
|
+
try { record.child?.kill() } catch {}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function residentFailure(pending, code, detail, timedOut = false) {
|
|
211
|
+
const stdout = redactSecrets(String(detail?.stdout || ''), pending.secrets)
|
|
212
|
+
const stderr = redactSecrets(String(detail?.stderr || ''), pending.secrets)
|
|
213
|
+
const text = (stderr || stdout || '').trim()
|
|
214
|
+
return new MemuError(
|
|
215
|
+
`memu ${pending.label} failed (exit ${code}${timedOut ? ', timeout' : ''}): ${text.slice(-2000)}`,
|
|
216
|
+
'MEMU_COMMAND_FAILED',
|
|
217
|
+
{ code, stdout, stderr, timedOut },
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function startResident(current, key) {
|
|
222
|
+
const record = { key, child: null, pending: new Map(), seq: 0, stopping: false, stderr: '', readySettled: false }
|
|
223
|
+
const abortReady = (message) => {
|
|
224
|
+
if (record.readySettled) return
|
|
225
|
+
record.readySettled = true
|
|
226
|
+
if (residentRecord === record) residentRecord = null
|
|
227
|
+
try { clearTimeout(record.bootTimer) } catch {}
|
|
228
|
+
try { record.child?.kill() } catch {}
|
|
229
|
+
record.readyReject?.(new MemuError(`failed to start memu: ${message}`, 'MEMU_SPAWN_FAILED'))
|
|
230
|
+
}
|
|
231
|
+
record.ready = new Promise((resolve, reject) => {
|
|
232
|
+
record.readyReject = reject
|
|
233
|
+
let buffer = ''
|
|
234
|
+
const settle = () => {
|
|
235
|
+
record.readySettled = true
|
|
236
|
+
try { clearTimeout(record.bootTimer) } catch {}
|
|
237
|
+
resolve(record)
|
|
238
|
+
}
|
|
239
|
+
record.bootTimer = setTimeout(() => abortReady('the memu resident process did not become ready in time'), RESIDENT_READY_TIMEOUT_MS)
|
|
240
|
+
try {
|
|
241
|
+
record.child = spawn(current.python, ['-c', RESIDENT_SCRIPT], {
|
|
242
|
+
env: residentBaseEnv(),
|
|
243
|
+
windowsHide: true,
|
|
244
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
245
|
+
})
|
|
246
|
+
} catch (error) {
|
|
247
|
+
abortReady(error.message)
|
|
248
|
+
return
|
|
249
|
+
}
|
|
250
|
+
// An unhandled 'error' event on a child pipe is an uncaught exception in the host.
|
|
251
|
+
for (const pipe of [record.child.stdin, record.child.stdout, record.child.stderr]) {
|
|
252
|
+
try { pipe?.on?.('error', () => {}) } catch {}
|
|
253
|
+
}
|
|
254
|
+
record.child.stderr?.on('data', (chunk) => {
|
|
255
|
+
record.stderr = (record.stderr + String(chunk)).slice(-4096)
|
|
256
|
+
})
|
|
257
|
+
record.child.stdout?.on('data', (chunk) => {
|
|
258
|
+
buffer += String(chunk)
|
|
259
|
+
if (buffer.length > RESIDENT_LINE_LIMIT) {
|
|
260
|
+
buffer = ''
|
|
261
|
+
abortReady('the resident engine response exceeded the line limit')
|
|
262
|
+
return
|
|
263
|
+
}
|
|
264
|
+
let newline = buffer.indexOf('\n')
|
|
265
|
+
while (newline >= 0) {
|
|
266
|
+
const line = buffer.slice(0, newline).replace(/\r+$/, '')
|
|
267
|
+
buffer = buffer.slice(newline + 1)
|
|
268
|
+
newline = buffer.indexOf('\n')
|
|
269
|
+
if (!line.trim()) continue
|
|
270
|
+
let message = null
|
|
271
|
+
try { message = JSON.parse(line) } catch { continue }
|
|
272
|
+
if (!record.readySettled) {
|
|
273
|
+
if (message.ready === true) settle()
|
|
274
|
+
else abortReady(String(message.error || 'the resident worker did not report ready'))
|
|
275
|
+
continue
|
|
276
|
+
}
|
|
277
|
+
const pending = record.pending.get(message.id)
|
|
278
|
+
if (!pending) continue
|
|
279
|
+
record.pending.delete(message.id)
|
|
280
|
+
clearTimeout(pending.timer)
|
|
281
|
+
const code = Number(message.code)
|
|
282
|
+
if (code === 0) pending.resolve({ stdout: String(message.stdout || ''), stderr: String(message.stderr || ''), code: 0 })
|
|
283
|
+
else pending.reject(residentFailure(pending, code, message))
|
|
284
|
+
}
|
|
285
|
+
})
|
|
286
|
+
record.child.on('error', (error) => abortReady(error.message))
|
|
287
|
+
record.child.on('close', (code) => {
|
|
288
|
+
if (!record.readySettled) {
|
|
289
|
+
abortReady(`the resident engine exited before it was ready (exit ${code})`)
|
|
290
|
+
return
|
|
291
|
+
}
|
|
292
|
+
if (residentRecord === record) residentRecord = null
|
|
293
|
+
if (record.stopping) return
|
|
294
|
+
const tail = redactSecrets(record.stderr.trim(), [])
|
|
295
|
+
const failure = new MemuError(
|
|
296
|
+
`memu resident process exited (exit ${code})${tail ? `: ${tail.slice(-2000)}` : ''}`,
|
|
297
|
+
'MEMU_COMMAND_FAILED',
|
|
298
|
+
{ code, timedOut: false, stderr: tail },
|
|
299
|
+
)
|
|
300
|
+
for (const pending of record.pending.values()) {
|
|
301
|
+
clearTimeout(pending.timer)
|
|
302
|
+
pending.reject(failure)
|
|
303
|
+
}
|
|
304
|
+
record.pending.clear()
|
|
305
|
+
warn('dsh-memu-memory: the resident memu engine exited; the next command will cold-start')
|
|
306
|
+
})
|
|
307
|
+
})
|
|
308
|
+
return record
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function ensureResident(current) {
|
|
312
|
+
const key = residentKey(current)
|
|
313
|
+
if (residentRecord && residentRecord.key !== key) {
|
|
314
|
+
stopResident(residentRecord, new MemuError('the memu engine changed; the resident process was stopped', 'MEMU_COMMAND_FAILED'))
|
|
315
|
+
}
|
|
316
|
+
if (!residentRecord) residentRecord = startResident(current, key)
|
|
317
|
+
return residentRecord.ready
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function runResident(args, { env, timeoutMs = 90_000 } = {}) {
|
|
321
|
+
const current = currentEngine()
|
|
322
|
+
let record
|
|
323
|
+
try {
|
|
324
|
+
record = await ensureResident(current)
|
|
325
|
+
} catch (error) {
|
|
326
|
+
throw error instanceof MemuError ? error : new MemuError(String(error?.message || error), 'MEMU_SPAWN_FAILED')
|
|
327
|
+
}
|
|
328
|
+
if (!record || record.stopping) throw new MemuError('the resident memu engine is not available', 'MEMU_SPAWN_FAILED')
|
|
329
|
+
const label = args[0] || ''
|
|
330
|
+
const id = ++record.seq
|
|
331
|
+
const secrets = Object.entries({ ...process.env, ...(env || {}) })
|
|
332
|
+
.filter(([key]) => /(?:API_KEY|TOKEN|SECRET)$/.test(key)).map(([, value]) => value)
|
|
333
|
+
const payload = JSON.stringify({
|
|
334
|
+
id,
|
|
335
|
+
argv: args,
|
|
336
|
+
env: { ...(env || {}), MEMU_MEMORY_MODE: memoryMode() },
|
|
337
|
+
}) + '\n'
|
|
338
|
+
return new Promise((resolve, reject) => {
|
|
339
|
+
const timer = setTimeout(() => {
|
|
340
|
+
record.pending.delete(id)
|
|
341
|
+
const failure = new MemuError(
|
|
342
|
+
`memu ${label} failed (timeout): the resident engine did not answer in ${Math.round(timeoutMs / 1000)}s`,
|
|
343
|
+
'MEMU_COMMAND_FAILED',
|
|
344
|
+
{ code: null, stdout: '', stderr: '', timedOut: true },
|
|
345
|
+
)
|
|
346
|
+
reject(failure)
|
|
347
|
+
// A Python command cannot be cancelled from the outside, so a stuck command
|
|
348
|
+
// costs this process; the next request cold-starts a fresh one.
|
|
349
|
+
stopResident(record, failure)
|
|
350
|
+
}, timeoutMs)
|
|
351
|
+
record.pending.set(id, { resolve, reject, timer, label, secrets })
|
|
352
|
+
try {
|
|
353
|
+
record.child.stdin.write(payload)
|
|
354
|
+
} catch (error) {
|
|
355
|
+
record.pending.delete(id)
|
|
356
|
+
clearTimeout(timer)
|
|
357
|
+
const failure = new MemuError(`failed to start memu: ${error.message}`, 'MEMU_SPAWN_FAILED', { error })
|
|
358
|
+
reject(failure)
|
|
359
|
+
stopResident(record, failure)
|
|
360
|
+
}
|
|
361
|
+
})
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Close the resident engine (plugin dispose, or an explicit teardown). */
|
|
365
|
+
export function closeMemuResident() {
|
|
366
|
+
const record = residentRecord
|
|
367
|
+
residentRecord = null
|
|
368
|
+
if (!record) return 0
|
|
369
|
+
stopResident(record, new MemuError('the resident memu engine is closed', 'MEMU_COMMAND_FAILED'))
|
|
370
|
+
return 1
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Warm the resident engine for local vector mode. Called after the local vector
|
|
375
|
+
* bootstrap (or on the first managed-local command), and deliberately fail-open:
|
|
376
|
+
* an engine that is missing or broken must not delay plugin activation.
|
|
377
|
+
*/
|
|
378
|
+
export async function prewarmMemuResident() {
|
|
379
|
+
try {
|
|
380
|
+
if (effectiveVectorRoute() !== 'managed-local') return false
|
|
381
|
+
if (!activeProfile()) return false
|
|
382
|
+
const current = readCurrent()
|
|
383
|
+
if (!current?.python) return false
|
|
384
|
+
await ensureResident(current)
|
|
385
|
+
return true
|
|
386
|
+
} catch (error) {
|
|
387
|
+
try { warn(`dsh-memu-memory: resident memu prewarm skipped: ${error?.message || error}`) } catch {}
|
|
388
|
+
return false
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
82
392
|
async function runConfigured(args, options = {}) {
|
|
83
393
|
const route = options.route || (options.vectorProfile ? 'managed-local' : 'remote-api')
|
|
84
394
|
const useManagedLocal = route === 'managed-local'
|
|
@@ -90,7 +400,12 @@ async function runConfigured(args, options = {}) {
|
|
|
90
400
|
const env = await envFor({ ...options, route })
|
|
91
401
|
if (generation) assertVectorGeneration(generation)
|
|
92
402
|
if (migration) assertMigrationProfile(migration)
|
|
93
|
-
|
|
403
|
+
// Local vector mode is the only route this plugin can reach without a vendor key,
|
|
404
|
+
// so it is where a cold Python import is paid most often. Keep one interpreter warm
|
|
405
|
+
// there; the remote API path keeps the one-process-per-command behavior.
|
|
406
|
+
const result = useManagedLocal
|
|
407
|
+
? await runResident(args, { env, timeoutMs: options.timeoutMs })
|
|
408
|
+
: await runRaw(['-m', 'memu', ...args], { env, timeoutMs: options.timeoutMs })
|
|
94
409
|
if (generation) assertVectorGeneration(generation)
|
|
95
410
|
if (migration) assertMigrationProfile(migration)
|
|
96
411
|
return result
|