dsh-memu-memory 1.4.3 → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +34 -15
  4. package/README.zh.md +35 -13
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/preset-mount.js +13 -7
  63. package/lib/private.js +47 -21
  64. package/lib/recall-cache.js +20 -34
  65. package/lib/retention.js +173 -0
  66. package/lib/rpc.js +135 -52
  67. package/lib/rt-index/builder.js +209 -0
  68. package/lib/rt-index/format.js +231 -0
  69. package/lib/rt-index/manifest.js +105 -0
  70. package/lib/rt-index/reader.js +673 -0
  71. package/lib/rt-index-retention.js +151 -0
  72. package/lib/rt-index-service.js +283 -0
  73. package/lib/rt-index-worker.js +21 -0
  74. package/lib/salient-wake.js +55 -4
  75. package/lib/state.js +195 -24
  76. package/lib/temporal.js +39 -13
  77. package/lib/token-measurement.js +126 -0
  78. package/lib/tools.js +101 -6
  79. package/lib/turn-log.js +108 -3
  80. package/lib/webui/graph-layout-worker.js +68 -0
  81. package/lib/webui/graph-local-physics.js +390 -0
  82. package/lib/webui/graph-spatial-grid.js +64 -0
  83. package/lib/webui/graph-view.bundle.js +6 -1
  84. package/lib/webui/graph-view.js +478 -135
  85. package/lib/webui/graph-webgl-renderer.js +74 -0
  86. package/lib/webui/standalone.js +1 -1
  87. package/lib/worker-pool.js +38 -7
  88. package/package.json +3 -2
  89. package/scripts/acceptance-local.mjs +4 -10
  90. package/scripts/bench-all-libraries.mjs +47 -0
  91. package/scripts/check-classic-graph-browser.mjs +189 -0
  92. package/scripts/check-client-browser.mjs +929 -0
  93. package/scripts/check-graph-browser.mjs +6 -0
  94. package/scripts/check-graph-elastic-browser.mjs +139 -0
  95. package/scripts/check-memory-review-browser.mjs +124 -0
  96. package/scripts/entity-dedupe.mjs +19 -3
  97. package/scripts/graph-artifact-provenance.mjs +30 -0
  98. package/scripts/graph-freeze-manifest.mjs +129 -0
  99. package/scripts/graph-geometry-fixture.mjs +40 -0
  100. package/scripts/graph-physics-bench.mjs +218 -0
  101. package/scripts/graph-scale-bench.mjs +213 -0
  102. package/scripts/graph-scale-memory.mjs +48 -0
  103. package/scripts/graph-service-bench.mjs +72 -0
  104. package/scripts/make-readme-shots.mjs +17 -5
  105. package/scripts/preview.mjs +1 -0
  106. package/scripts/rebuild-rt.mjs +18 -0
  107. package/scripts/scale-bench.mjs +183 -0
  108. package/scripts/simulate-injection.mjs +47 -8
  109. package/scripts/verify-host-fixtures.mjs +108 -0
  110. package/scripts/verify-host-recovery.mjs +565 -0
  111. package/scripts/verify-vector-recovery.mjs +740 -0
  112. package/tests/auto-link-candidates.test.mjs +20 -0
  113. package/tests/browser.test.mjs +16 -2
  114. package/tests/client-export.test.mjs +16 -1
  115. package/tests/client-pagination.test.mjs +1495 -0
  116. package/tests/client-render.test.mjs +223 -28
  117. package/tests/consolidation-fork.test.mjs +97 -13
  118. package/tests/consolidation-ledger.test.mjs +17 -1
  119. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  120. package/tests/diagnostic-report.test.mjs +429 -0
  121. package/tests/diagnostic-wiring.test.mjs +88 -0
  122. package/tests/diagnostics.test.mjs +27 -0
  123. package/tests/embedding-download.test.mjs +44 -0
  124. package/tests/engine-source-settings.test.mjs +69 -0
  125. package/tests/engine-sources.test.mjs +145 -0
  126. package/tests/entity-dedupe.test.mjs +143 -0
  127. package/tests/entity-merge-review.test.mjs +363 -0
  128. package/tests/entity-merge.test.mjs +12 -4
  129. package/tests/entity-review.test.mjs +87 -0
  130. package/tests/environment-check.test.mjs +51 -1
  131. package/tests/feedback.test.mjs +95 -0
  132. package/tests/graph-adjacency-index.test.mjs +536 -0
  133. package/tests/graph-cascade.test.mjs +229 -0
  134. package/tests/graph-import-diagnostic.test.mjs +25 -0
  135. package/tests/graph-overview.test.mjs +709 -0
  136. package/tests/graph-session-authorization.test.mjs +419 -0
  137. package/tests/graph-view-geometry.test.mjs +426 -0
  138. package/tests/graph-view-scale.test.mjs +88 -0
  139. package/tests/graph-view.test.mjs +444 -5
  140. package/tests/graph.test.mjs +43 -0
  141. package/tests/help-page.test.mjs +128 -54
  142. package/tests/inbound.test.mjs +19 -0
  143. package/tests/index-pagination.test.mjs +113 -0
  144. package/tests/index-read-view.test.mjs +212 -0
  145. package/tests/inject-guide.test.mjs +9 -0
  146. package/tests/injection-dedupe.test.mjs +213 -0
  147. package/tests/lexicon-recall.test.mjs +641 -0
  148. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  149. package/tests/lexicon-rt.test.mjs +468 -0
  150. package/tests/local-embedding-worker.test.mjs +38 -0
  151. package/tests/local-vector-service.test.mjs +32 -3
  152. package/tests/maintenance-compat.test.mjs +128 -0
  153. package/tests/maintenance-settlement.test.mjs +1003 -0
  154. package/tests/managed-memory.test.mjs +39 -11
  155. package/tests/managed-runtime.test.mjs +109 -0
  156. package/tests/memory-fields.test.mjs +24 -12
  157. package/tests/observed-evidence.test.mjs +52 -0
  158. package/tests/port-surface.test.mjs +93 -1
  159. package/tests/preset-mount.test.mjs +12 -4
  160. package/tests/recall-cache.test.mjs +56 -3
  161. package/tests/recall-dedup.test.mjs +63 -2
  162. package/tests/retention.test.mjs +260 -0
  163. package/tests/rt-index-cross-library.test.mjs +230 -0
  164. package/tests/rt-index-integration.test.mjs +194 -0
  165. package/tests/rt-index-retention.test.mjs +552 -0
  166. package/tests/rt-index-scale.test.mjs +204 -0
  167. package/tests/rt-index.test.mjs +705 -0
  168. package/tests/salient-date-boundaries.test.mjs +121 -0
  169. package/tests/salient-wake.test.mjs +29 -0
  170. package/tests/scale-bench.test.mjs +53 -0
  171. package/tests/settings-plumbing.test.mjs +25 -0
  172. package/tests/simulate-injection.test.mjs +15 -1
  173. package/tests/standalone-navigation.test.mjs +44 -0
  174. package/tests/state.test.mjs +51 -0
  175. package/tests/temporal-precision.test.mjs +102 -0
  176. package/tests/temporal.test.mjs +10 -6
  177. package/tests/token-measurement.test.mjs +98 -0
  178. package/tests/tool-schema.test.mjs +41 -5
  179. package/tests/tools.test.mjs +6 -3
  180. package/tests/turn-token-budget.test.mjs +149 -0
  181. package/tests/webui-auth.test.mjs +57 -1
  182. package/tests/webui.test.mjs +40 -15
  183. package/tests/worker-lifecycle.test.mjs +2 -1
@@ -3,18 +3,17 @@ import path from 'node:path'
3
3
  import crypto from 'node:crypto'
4
4
  import { unzipSync } from 'fflate'
5
5
  import { engineDir, ensureDir, writeJson } from './paths.js'
6
+ import {
7
+ UV_VERSION, MANAGED_PYTHON, MANAGED_PYTHON_SERIES, PYTHON_OFFICIAL_BASE,
8
+ resolveEngineSources, describeFetchError, parseSha256Sum, pickLatestUvVersion, pickLatestPythonBuild, runtimeGuidance, downloadGuidance,
9
+ } from './engine-sources.js'
6
10
 
7
- export const UV_VERSION = '0.13.6'
8
- export const MANAGED_PYTHON = '3.12.14'
9
- // Pinned release digests, verified against astral-sh/uv release metadata on 2026-10-28.
10
- const ASSETS = {
11
- 'win32-x64': ['uv-x86_64-pc-windows-msvc.zip', 'a2a8820d5eea32f08ef467ef3b7f66883a9b076d5737a2fc2fbb5f458d1bb50f'],
12
- 'win32-arm64': ['uv-aarch64-pc-windows-msvc.zip', 'c2426c0c8e28b53d8c440e47a18d96ad4db51e159866c0e81435b196d7f0081c'],
13
- 'linux-x64': ['uv-x86_64-unknown-linux-gnu.tar.gz', 'f29c3e94ffabd7e6f3ba521dba169a9b7ec12100bf3257087f0f24f6123f3645'],
14
- 'linux-arm64': ['uv-aarch64-unknown-linux-gnu.tar.gz', '229e194255c7958d86d56e8790d969a6f74736592133f0dfd0076f754c642c1d'],
15
- 'darwin-x64': ['uv-x86_64-apple-darwin.tar.gz', '63ba17fdda55ad1a230d4b37fc6017ffa10c23688c83818bd3bfdf914c652a02'],
16
- 'darwin-arm64': ['uv-aarch64-apple-darwin.tar.gz', '60fbd5c8a1ed681845eea28d9d622fcde03c51e91a43465b64a1e17db1ed3472'],
17
- }
11
+ export { UV_VERSION, MANAGED_PYTHON }
12
+
13
+ const MAX_RUNTIME_BYTES = 64 * 1024 * 1024
14
+ const DOWNLOAD_TIMEOUT_MS = 120_000
15
+ const LISTING_TIMEOUT_MS = 30_000
16
+ const VERSION_RE = /^\d+\.\d+\.\d+$/
18
17
 
19
18
  export function verifyRuntimeArchive(data, digest) {
20
19
  if (crypto.createHash('sha256').update(data).digest('hex') !== digest) throw new Error('managed runtime checksum mismatch; refusing to execute')
@@ -31,88 +30,269 @@ function executableFingerprint(file) {
31
30
  }
32
31
  }
33
32
 
34
- function verifiedRuntimeMetadata(file, asset) {
33
+ // Metadata is the only proof that the binary on disk is the one we verified:
34
+ // version, archive name, the archive digest we checked, and the executable's own
35
+ // fingerprint. A legacy or hand-edited file fails closed (rule: never execute an
36
+ // unverified runtime).
37
+ function verifiedRuntimeMetadata(file, runtime, { allowUnpinned = false } = {}) {
35
38
  try {
36
39
  const metadata = JSON.parse(fs.readFileSync(file, 'utf8'))
37
- return metadata && metadata.version === UV_VERSION && metadata.archive === asset[0] && metadata.archiveSha256 === asset[1] && Number.isInteger(metadata.executableBytes) && typeof metadata.executableSha256 === 'string'
38
- ? metadata
39
- : null
40
+ if (!metadata || typeof metadata.version !== 'string' || !VERSION_RE.test(metadata.version)) return null
41
+ if (metadata.archive !== runtime.asset) return null
42
+ if (!/^[0-9a-f]{64}$/.test(String(metadata.archiveSha256 || ''))) return null
43
+ if (!allowUnpinned && metadata.version !== UV_VERSION) return null
44
+ if (runtime.sha256 && !allowUnpinned && metadata.archiveSha256 !== runtime.sha256) return null
45
+ if (!Number.isInteger(metadata.executableBytes) || typeof metadata.executableSha256 !== 'string') return null
46
+ return metadata
40
47
  } catch {
41
48
  return null
42
49
  }
43
50
  }
44
51
 
45
- export async function ensureManagedPython({ run, log = () => {}, fetcher = fetch } = {}) {
46
- const platform = `${process.platform}-${process.arch}`
47
- const asset = ASSETS[platform]
48
- if (!asset) throw new Error(`managed Python fallback is unavailable for ${platform}; set DSH_MEMU_PYTHON`)
52
+ async function fetchBytes(fetcher, url) {
53
+ const response = await fetcher(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) })
54
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
55
+ const declared = Number(response.headers.get('content-length'))
56
+ if (Number.isFinite(declared) && declared > MAX_RUNTIME_BYTES) throw new Error(`archive is too large (${declared} bytes)`)
57
+ const chunks = []
58
+ let size = 0
59
+ for await (const chunk of response.body) {
60
+ size += chunk.length
61
+ if (size > MAX_RUNTIME_BYTES) throw new Error('download exceeds 64 MB')
62
+ chunks.push(chunk)
63
+ }
64
+ return Buffer.concat(chunks)
65
+ }
66
+
67
+ async function fetchText(fetcher, url) {
68
+ const response = await fetcher(url, { signal: AbortSignal.timeout(LISTING_TIMEOUT_MS) })
69
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
70
+ return response.text()
71
+ }
72
+
73
+ function archiveDigest(source, version, runtime, fetcher, log) {
74
+ if (runtime.sha256 && version === UV_VERSION) return Promise.resolve(runtime.sha256)
75
+ // Rolling mirrors publish sha256.sum beside the release. Never install an
76
+ // archive whose bytes we cannot check, even in the unpinned mode.
77
+ return fetchText(fetcher, `${source.base}/${version}/sha256.sum`).then((text) => {
78
+ const digest = parseSha256Sum(text).get(runtime.asset)
79
+ if (!digest) throw new Error(`sha256.sum has no entry for ${runtime.asset}`)
80
+ return digest
81
+ }).catch((error) => {
82
+ throw new Error(`no verifiable digest for this archive: ${describeFetchError(error)}`)
83
+ })
84
+ }
85
+
86
+ async function versionsForSource(source, { allowUnpinned, fetcher, log }) {
87
+ const versions = [UV_VERSION]
88
+ if (!allowUnpinned || !source.latestOk) return versions
89
+ try {
90
+ const listing = await fetchText(fetcher, `${source.base}/`)
91
+ const latest = pickLatestUvVersion(listing)
92
+ if (!latest) {
93
+ log(`${source.label}: no release directories in listing; using pinned ${UV_VERSION}`)
94
+ return versions
95
+ }
96
+ if (latest !== UV_VERSION) versions.unshift(latest)
97
+ } catch (error) {
98
+ log(`${source.label}: version listing unavailable (${describeFetchError(error)}); using pinned ${UV_VERSION}`)
99
+ }
100
+ return versions
101
+ }
102
+
103
+ function extractUv({ bytes, runtime, bin }) {
104
+ if (runtime.archiveKind === 'zip') {
105
+ const files = unzipSync(bytes, { filter: (item) => item.name === 'uv.exe' && item.originalSize < 100 * 1024 * 1024 })
106
+ if (!files['uv.exe']) throw new Error('managed runtime archive has no uv executable')
107
+ return Buffer.from(files['uv.exe'])
108
+ }
109
+ const archive = path.join(bin, `download-${crypto.randomUUID()}.tar.gz`)
110
+ fs.writeFileSync(archive, bytes, { mode: 0o600, flag: 'wx' })
111
+ return archive
112
+ }
113
+
114
+ async function installUvArchive({ bytes, runtime, executable, bin }) {
115
+ const staged = extractUv({ bytes, runtime, bin })
116
+ if (Buffer.isBuffer(staged)) {
117
+ const temporary = `${executable}.tmp-${crypto.randomUUID()}`
118
+ fs.writeFileSync(temporary, staged, { mode: 0o700, flag: 'wx' })
119
+ fs.renameSync(temporary, executable)
120
+ return
121
+ }
122
+ try {
123
+ const { x } = await import('tar')
124
+ await x({
125
+ file: staged,
126
+ cwd: bin,
127
+ strip: 1,
128
+ strict: true,
129
+ filter: (name, entry) => entry.type === 'File' && /^uv-[a-z0-9_-]+\/uv$/.test(name) && entry.size < 100 * 1024 * 1024,
130
+ })
131
+ if (!fs.existsSync(executable)) throw new Error('managed runtime archive has no uv executable')
132
+ } finally {
133
+ fs.rmSync(staged, { force: true })
134
+ }
135
+ }
136
+
137
+ async function ensureUv({ plan, log, fetcher, bins, target }) {
138
+ // A verified runtime already on disk can be reused from either the pinned
139
+ // directory or the rolling one, as long as its metadata passes the policy.
140
+ for (const candidate of bins) {
141
+ const fingerprint = executableFingerprint(candidate.executable)
142
+ const metadata = verifiedRuntimeMetadata(candidate.metadataFile, plan.runtime, { allowUnpinned: plan.allowUnpinned })
143
+ if (metadata && fingerprint && metadata.executableBytes === fingerprint.bytes && metadata.executableSha256 === fingerprint.sha256) {
144
+ log(`reusing managed uv ${metadata.version} from ${candidate.bin}`)
145
+ return { version: metadata.version, source: metadata.source || 'reused', executable: candidate.executable }
146
+ }
147
+ }
148
+
149
+ const executable = target.executable
150
+ const { bin } = target
151
+ if (fs.existsSync(executable)) log('managed uv is missing trusted metadata or was modified; replacing it')
152
+ try { fs.rmSync(executable, { force: true }) } catch {}
153
+ try { fs.rmSync(target.metadataFile, { force: true }) } catch {}
154
+
155
+ const failures = []
156
+ for (const source of plan.uv) {
157
+ const versions = await versionsForSource(source, { allowUnpinned: plan.allowUnpinned, fetcher, log })
158
+ for (const version of versions) {
159
+ try {
160
+ try { fs.rmSync(executable, { force: true }) } catch {}
161
+ log(`downloading uv ${version} from ${source.label}`)
162
+ const url = `${source.base}/${version}/${plan.runtime.asset}`
163
+ const bytes = await fetchBytes(fetcher, url)
164
+ const digest = await archiveDigest(source, version, plan.runtime, fetcher, log)
165
+ verifyRuntimeArchive(bytes, digest)
166
+ await installUvArchive({ bytes, runtime: plan.runtime, executable, bin })
167
+ if (process.platform !== 'win32') fs.chmodSync(executable, 0o700)
168
+ const installed = executableFingerprint(executable)
169
+ if (!installed) throw new Error('managed runtime executable is not a regular file')
170
+ writeJson(target.metadataFile, {
171
+ version,
172
+ archive: plan.runtime.asset,
173
+ archiveSha256: digest,
174
+ executableBytes: installed.bytes,
175
+ executableSha256: installed.sha256,
176
+ source: source.id,
177
+ })
178
+ return { version, source: source.id, executable }
179
+ } catch (error) {
180
+ const message = describeFetchError(error)
181
+ failures.push(`${source.label} ${version}: ${message}`)
182
+ log(`uv source failed (${source.label} ${version}): ${message}`)
183
+ }
184
+ }
185
+ }
186
+ throw new Error([
187
+ 'managed uv download failed; every configured source was tried:',
188
+ ...failures.map((line) => ` ${line}`),
189
+ ` ${downloadGuidance()}`,
190
+ ].join('\n'))
191
+ }
192
+
193
+ async function latestManagedPython(source, plan, fetcher, log) {
194
+ if (!plan.allowUnpinned || !source.base || !source.latestOk) return null
195
+ try {
196
+ const listing = await fetchText(fetcher, `${source.base}/LatestRelease/`)
197
+ const build = pickLatestPythonBuild(listing, { triple: plan.runtime.pythonTriple, series: MANAGED_PYTHON_SERIES })
198
+ return build ? build.version : null
199
+ } catch (error) {
200
+ log(`${source.label}: CPython listing unavailable (${describeFetchError(error)}); staying on pinned ${MANAGED_PYTHON}`)
201
+ return null
202
+ }
203
+ }
204
+
205
+ async function ensureManagedPythonVersion({ plan, uvVersion, run, log, fetcher, executable, uvEnv }) {
206
+ const failures = []
207
+ // A rolling uv (newest mirror release) only knows the Python builds published
208
+ // around its own release. Pairing it with an older pinned CPython is how you
209
+ // get "unknown Python version": let the mirror pick, then fall back to pinned.
210
+ const followMirror = plan.allowUnpinned && uvVersion !== UV_VERSION
211
+ for (const source of plan.python) {
212
+ const versions = [MANAGED_PYTHON]
213
+ if (followMirror) {
214
+ const latest = await latestManagedPython(source, plan, fetcher, log)
215
+ if (latest && latest !== MANAGED_PYTHON) versions.unshift(latest)
216
+ }
217
+ for (const version of versions) {
218
+ // The process runner inherits the host environment. Set the official base
219
+ // explicitly so fallback cannot keep using a failing inherited mirror.
220
+ const env = { ...uvEnv, UV_PYTHON_INSTALL_MIRROR: source.base || PYTHON_OFFICIAL_BASE }
221
+ log(`installing managed Python ${version} via ${source.label}`)
222
+ try {
223
+ const installed = await run(executable, ['python', 'install', version, '--no-progress'], { env, timeoutMs: 300_000 })
224
+ if (installed.code !== 0) {
225
+ const detail = (installed.stderr || installed.stdout || '').trim().split(/\r?\n/).slice(-3).join(' | ')
226
+ failures.push(`${source.label} ${version}: ${detail || `exit ${installed.code}`}`)
227
+ continue
228
+ }
229
+ const found = await run(executable, ['python', 'find', '--no-python-downloads', version], { env, timeoutMs: 20_000 })
230
+ const python = path.resolve(String(found.stdout || '').trim())
231
+ const inside = python.startsWith(path.resolve(env.UV_PYTHON_INSTALL_DIR) + path.sep) && fs.existsSync(python)
232
+ if (found.code !== 0 || !inside) {
233
+ failures.push(`${source.label} ${version}: managed Python escaped its engine directory`)
234
+ continue
235
+ }
236
+ return { python, version }
237
+ } catch (error) {
238
+ const message = describeFetchError(error)
239
+ failures.push(`${source.label} ${version}: ${message}`)
240
+ log(`Python source failed (${source.label} ${version}): ${message}`)
241
+ }
242
+ }
243
+ }
244
+ throw new Error([
245
+ 'managed Python installation failed; every configured source was tried:',
246
+ ...failures.map((line) => ` ${line}`),
247
+ ` ${downloadGuidance()}`,
248
+ ].join('\n'))
249
+ }
250
+
251
+ export async function ensureManagedPython({ run, log = () => {}, fetcher = fetch, settings = {}, env = process.env } = {}) {
252
+ const plan = resolveEngineSources({ settings, env, platform: process.platform, arch: process.arch })
253
+ if (!plan.runtime.supported) throw new Error(runtimeGuidance(plan.runtime))
254
+
49
255
  const root = ensureDir(engineDir('runtime'))
50
- const bin = ensureDir(path.join(root, `uv-${UV_VERSION}`))
51
- const executable = path.join(bin, process.platform === 'win32' ? 'uv.exe' : 'uv')
52
- const env = {
256
+ const exeName = process.platform === 'win32' ? 'uv.exe' : 'uv'
257
+ const pinnedDir = path.join(root, `uv-${UV_VERSION}`)
258
+ const rollingDir = path.join(root, 'uv')
259
+ const targetDir = plan.allowUnpinned ? rollingDir : pinnedDir
260
+ ensureDir(targetDir)
261
+ const layout = (dir) => ({ bin: dir, executable: path.join(dir, exeName), metadataFile: path.join(dir, 'verified.json') })
262
+ const target = layout(targetDir)
263
+ // Unpinned mode must not reuse the pinned uv: pairing 0.13.6 with a rolling
264
+ // mirror's CPython is exactly the "unknown Python version" dead end.
265
+ const bins = plan.allowUnpinned ? [target] : [target, layout(rollingDir)]
266
+ const uvEnv = {
53
267
  UV_PYTHON_INSTALL_DIR: ensureDir(path.join(root, 'python')),
54
268
  UV_CACHE_DIR: ensureDir(path.join(root, 'cache')),
55
269
  UV_PYTHON_BIN_DIR: ensureDir(path.join(root, 'bin')),
56
270
  UV_NO_PROGRESS: '1', UV_PYTHON_PREFERENCE: 'only-managed', UV_NO_MODIFY_PATH: '1', UV_NO_CONFIG: '1',
57
271
  }
58
- const metadataFile = path.join(bin, 'verified.json')
59
- const metadata = verifiedRuntimeMetadata(metadataFile, asset)
60
- const fingerprint = executableFingerprint(executable)
61
- const reusable = Boolean(metadata && fingerprint && metadata.executableBytes === fingerprint.bytes && metadata.executableSha256 === fingerprint.sha256)
62
- if (!reusable) {
63
- if (fingerprint || fs.existsSync(executable)) log(`managed uv ${UV_VERSION} is missing trusted metadata or was modified; replacing it`)
64
- try { fs.rmSync(executable, { force: true }) } catch {}
65
- try { fs.rmSync(metadataFile, { force: true }) } catch {}
66
- log(`no usable Python with pip; downloading pinned uv ${UV_VERSION}`)
67
- const response = await fetcher(`https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${asset[0]}`, { signal: AbortSignal.timeout(120_000) })
68
- if (!response.ok || Number(response.headers.get('content-length')) > 64 * 1024 * 1024) throw new Error('managed runtime download failed or is too large')
69
- const chunks = []
70
- let size = 0
71
- for await (const chunk of response.body) {
72
- size += chunk.length
73
- if (size > 64 * 1024 * 1024) throw new Error('managed runtime download exceeds 64 MB')
74
- chunks.push(chunk)
75
- }
76
- const bytes = Buffer.concat(chunks)
77
- verifyRuntimeArchive(bytes, asset[1])
78
- const temporary = `${executable}.tmp-${crypto.randomUUID()}`
79
- if (asset[0].endsWith('.zip')) {
80
- const files = unzipSync(bytes, { filter: item => item.name === 'uv.exe' && item.originalSize < 100 * 1024 * 1024 })
81
- if (!files['uv.exe']) throw new Error('managed runtime archive has no uv executable')
82
- fs.writeFileSync(temporary, files['uv.exe'], { mode: 0o700, flag: 'wx' })
83
- } else {
84
- const archive = path.join(bin, `download-${crypto.randomUUID()}.tar.gz`)
85
- fs.writeFileSync(archive, bytes, { mode: 0o600, flag: 'wx' })
86
- try {
87
- const { x } = await import('tar')
88
- await x({ file: archive, cwd: bin, strip: 1, strict: true,
89
- filter: (name, entry) => entry.type === 'File' && /^uv-[a-z0-9_-]+\/uv$/.test(name) && entry.size < 100 * 1024 * 1024 })
90
- if (!fs.existsSync(executable)) throw new Error('managed runtime archive has no uv executable')
91
- } finally { fs.rmSync(archive, { force: true }) }
92
- }
93
- if (fs.existsSync(temporary)) fs.renameSync(temporary, executable)
94
- if (process.platform !== 'win32') fs.chmodSync(executable, 0o700)
95
- const installedFingerprint = executableFingerprint(executable)
96
- if (!installedFingerprint) throw new Error('managed runtime executable is not a regular file')
97
- writeJson(metadataFile, { version: UV_VERSION, archive: asset[0], archiveSha256: asset[1], executableBytes: installedFingerprint.bytes, executableSha256: installedFingerprint.sha256 })
272
+
273
+ const uv = await ensureUv({ plan, log, fetcher, bins, target })
274
+ const executable = uv.executable
275
+
276
+ const version = await run(executable, ['--version'], { env: uvEnv, timeoutMs: 20_000 })
277
+ const reported = String(version.stdout || '').trim()
278
+ if (version.code !== 0 || !new RegExp(`^uv\\s+${uv.version.replace(/\./g, '\\.')}(\\s|$)`).test(reported)) {
279
+ throw new Error(`managed uv version mismatch: expected uv ${uv.version}, got ${reported || `exit ${version.code}`}`)
98
280
  }
99
- const version = await run(executable, ['--version'], { env, timeoutMs: 20_000 })
100
- if (version.code !== 0 || !version.stdout.startsWith(`uv ${UV_VERSION} `) && version.stdout.trim() !== `uv ${UV_VERSION}`) throw new Error('managed uv version mismatch')
101
- log(`installing managed Python ${MANAGED_PYTHON} inside the plugin engine directory`)
102
- const installed = await run(executable, ['python', 'install', MANAGED_PYTHON, '--no-progress'], { env, timeoutMs: 300_000 })
103
- if (installed.code !== 0) throw new Error('managed Python installation failed; set DSH_MEMU_PYTHON')
104
- const found = await run(executable, ['python', 'find', '--no-python-downloads', MANAGED_PYTHON], { env, timeoutMs: 20_000 })
105
- const python = path.resolve(found.stdout.trim())
106
- if (found.code !== 0 || !python.startsWith(path.resolve(env.UV_PYTHON_INSTALL_DIR) + path.sep) || !fs.existsSync(python)) throw new Error('managed Python escaped its engine directory')
107
- if (process.platform === 'darwin') {
108
- // python-build-standalone interpreters ship Developer-ID-signed with the
109
- // hardened runtime, so macOS library validation rejects the ad-hoc-signed
110
- // .so files inside PyPI wheels ("different Team IDs" dlopen failure). Our
111
- // own managed interpreter is safe to re-sign ad-hoc, which drops the
112
- // hardened runtime flag before any venv is created from it.
113
- const resign = await run('/usr/bin/codesign', ['--force', '--sign', '-', python], { env, timeoutMs: 60_000 })
114
- if (resign.code !== 0) log(`ad-hoc re-sign of managed Python failed (continuing): ${(resign.stderr || resign.stdout || '').trim()}`)
115
- else log('managed Python re-signed ad-hoc to avoid macOS library validation errors')
281
+
282
+ const managed = await ensureManagedPythonVersion({ plan, uvVersion: uv.version, run, log, fetcher, executable, uvEnv })
283
+ log(`managed runtime ready: uv ${uv.version} (${uv.source}), Python ${managed.version}`)
284
+ return {
285
+ kind: 'python',
286
+ cmd: managed.python,
287
+ prefix: [],
288
+ version: {
289
+ major: 3,
290
+ minor: Number(String(managed.version).split('.')[1]) || 12,
291
+ raw: managed.version,
292
+ },
293
+ hasPip: false,
294
+ uvPath: executable,
295
+ uvEnv,
296
+ source: `managed-uv:${uv.source}`,
116
297
  }
117
- return { kind: 'python', cmd: python, prefix: [], version: { major: 3, minor: 12, raw: MANAGED_PYTHON }, hasPip: false, uvPath: executable, uvEnv: env, source: 'managed-uv' }
118
298
  }
package/lib/media.js CHANGED
@@ -272,7 +272,7 @@ export function attachmentRefs(libraryId, refs) {
272
272
  sha256: sha, bytes: blob.bytes, w: blob.w, h: blob.h, mime: blob.mime,
273
273
  caption: blob.caption, captionBy: blob.captionBy, addedAt: blob.firstSeenAt,
274
274
  lastUsedAt: blob.lastUsedAt, useCount: blob.useCount,
275
- missing: blob.missing || !fs.existsSync(blobFile(libraryId, sha, blob.ext)),
275
+ missing: !fs.existsSync(blobFile(libraryId, sha, blob.ext)),
276
276
  }
277
277
  })
278
278
  }