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.
- package/AGENTS.md +3 -1
- package/CHANGELOG.md +15 -0
- package/README.md +34 -15
- package/README.zh.md +35 -13
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/preset-mount.js +13 -7
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +38 -7
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +97 -13
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/preset-mount.test.mjs +12 -4
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
- package/tests/worker-lifecycle.test.mjs +2 -1
package/lib/state.js
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
import {
|
|
9
9
|
createBackup, deleteBackupEntry, listBackupEntries, restoreFromBackup,
|
|
10
10
|
} from './backup.js'
|
|
11
|
+
import { createBoundedCache } from './bounded-cache.js'
|
|
11
12
|
import { migrateIndexVisibility } from './visibility.js'
|
|
12
13
|
import { memuDbFor, memuGlobalDbFor, removeActiveLibrary } from './vector-profile.js'
|
|
13
14
|
import { normalizeEmotion, derivedValence } from './mood.js'
|
|
@@ -100,6 +101,14 @@ export const DEFAULT_SETTINGS = {
|
|
|
100
101
|
curatorModel: null,
|
|
101
102
|
autoInstallEngine: true,
|
|
102
103
|
pipIndexes: [],
|
|
104
|
+
// Where the managed engine bootstrap downloads from. 'auto' tries domestic
|
|
105
|
+
// mirrors before GitHub; 'official' flips that; 'custom' uses the URLs below.
|
|
106
|
+
// engineAllowUnpinned is the explicit opt-in for rolling mirrors that only
|
|
107
|
+
// keep their newest release (digests then come from the mirror's sha256.sum).
|
|
108
|
+
engineSource: 'auto',
|
|
109
|
+
engineUvMirror: '',
|
|
110
|
+
enginePythonMirror: '',
|
|
111
|
+
engineAllowUnpinned: false,
|
|
103
112
|
// Fresh installs start with the plugin fully alive: auto-install, the
|
|
104
113
|
// new-session prompt, domestic texture, and idle consolidation are all on.
|
|
105
114
|
// These stay ordinary switches, and an existing saved choice is preserved.
|
|
@@ -166,6 +175,19 @@ export const DEFAULT_SETTINGS = {
|
|
|
166
175
|
// Worker tool-log detail: 'none' stores no tool rows, 'errors' stores error results,
|
|
167
176
|
// and 'summary' stores one summary row.
|
|
168
177
|
consolidationTurnLogTools: 'none',
|
|
178
|
+
// Retention passes are read-only until the explicit dry-run gate is disabled.
|
|
179
|
+
retentionDryRun: true,
|
|
180
|
+
retentionBoundTurnLogsEnabled: true,
|
|
181
|
+
retentionBoundTurnLogDays: 30,
|
|
182
|
+
retentionOrphanTurnLogsEnabled: false,
|
|
183
|
+
retentionOrphanTurnLogDays: 90,
|
|
184
|
+
retentionMaintenanceLedgerEnabled: true,
|
|
185
|
+
retentionMaintenanceLedgerDays: 180,
|
|
186
|
+
retentionSessionBindingsEnabled: false,
|
|
187
|
+
retentionSessionBindingDays: 180,
|
|
188
|
+
retentionVectorPruneEnabled: true,
|
|
189
|
+
retentionVectorKeepGenerations: 2,
|
|
190
|
+
retentionVectorDays: 7,
|
|
169
191
|
// A positive age marks cleanup candidates; deletion always needs a user action.
|
|
170
192
|
purgeArchivedAfterDays: 0,
|
|
171
193
|
// 升级后的一次性实体碎片自愈(lib/index.js startEntityRepairPass)。默认开,但它**只**合并
|
|
@@ -436,13 +458,16 @@ export function updateSettings(patch) {
|
|
|
436
458
|
unpinBudgetPerSession: [1, 20], unpinCooldownMinutes: [0, 1440], sleepAfterIdleMinutes: [1, 1440],
|
|
437
459
|
openLoopRemindDays: [1, 365],
|
|
438
460
|
autoCurateEveryHours: [0, 8760], autoCurateSessionLimit: [1, 10], purgeArchivedAfterDays: [0, 36500],
|
|
461
|
+
retentionBoundTurnLogDays: [1, 36500], retentionOrphanTurnLogDays: [1, 36500],
|
|
462
|
+
retentionMaintenanceLedgerDays: [1, 36500], retentionSessionBindingDays: [1, 36500],
|
|
463
|
+
retentionVectorKeepGenerations: [1, 100], retentionVectorDays: [1, 36500],
|
|
439
464
|
activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
|
|
440
465
|
activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
|
|
441
466
|
midTurnMinSteps: [1, 64], midTurnMinUnits: [1, 200], midTurnMinChars: [0, 200000],
|
|
442
467
|
midTurnMaxPerTurn: [1, 10], midTurnCooldownMs: [0, 600000], midTurnTokens: [120, 2000],
|
|
443
468
|
midTurnFullUnits: [1, 200], midTurnFullChars: [0, 200000],
|
|
444
469
|
}
|
|
445
|
-
const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'] }
|
|
470
|
+
const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'], engineSource: ['auto', 'mirror', 'official', 'custom'] }
|
|
446
471
|
for (const [key, value] of Object.entries(patch || {})) {
|
|
447
472
|
if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
|
|
448
473
|
if (enums[key]) {
|
|
@@ -505,6 +530,21 @@ export function updateSettings(patch) {
|
|
|
505
530
|
}
|
|
506
531
|
}
|
|
507
532
|
clean[key] = zone
|
|
533
|
+
} else if (key === 'engineUvMirror' || key === 'enginePythonMirror') {
|
|
534
|
+
// 空串是「没有自定义镜像」,合法;非空必须是替换 GitHub releases/download
|
|
535
|
+
// 前缀的基地址(<base>/<tag>/<asset>),与 pipIndexes 同一把尺:
|
|
536
|
+
// 带账号密码的 URL 会被宿主请求头拒绝,宁可在保存时就拒绝。
|
|
537
|
+
if (typeof value !== 'string') throw new Error(`setting ${key} must be a string`)
|
|
538
|
+
const trimmed = value.trim().replace(/\/+$/, '')
|
|
539
|
+
if (trimmed) {
|
|
540
|
+
try {
|
|
541
|
+
const url = new URL(trimmed)
|
|
542
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error('bad base URL')
|
|
543
|
+
} catch {
|
|
544
|
+
throw new Error(`${key} must be an HTTP(S) base URL without embedded credentials, query or fragment`)
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
clean[key] = trimmed
|
|
508
548
|
} else if (key === 'pipIndexes' || key === 'promptDomains' || key === 'inboundToolNames') {
|
|
509
549
|
if (!Array.isArray(value) || value.length > 20 || value.some(item => typeof item !== 'string')) throw new Error(`invalid setting ${key}`)
|
|
510
550
|
if (key === 'promptDomains' && value.some(item => !/^[a-z0-9][a-z0-9_-]{0,23}$/.test(item))) throw new Error('invalid domain id')
|
|
@@ -617,7 +657,7 @@ export function setWorkspacePolicy(scopeKey, patch = {}) {
|
|
|
617
657
|
for (const binding of Object.values(draft.sessions || {})) {
|
|
618
658
|
const inFolder = binding.scopeKey === key
|
|
619
659
|
|| (binding.libraryId && draft.libraries[binding.libraryId]?.scopeKey === key)
|
|
620
|
-
if (inFolder && !binding.libraryId && library) binding.libraryId = library[0]
|
|
660
|
+
if (inFolder && binding.useLibrary !== false && !binding.libraryId && library) binding.libraryId = library[0]
|
|
621
661
|
}
|
|
622
662
|
}
|
|
623
663
|
return draft
|
|
@@ -1028,6 +1068,13 @@ export function recentMemoryRefs(binding, memoryClock, dedupeTurns) {
|
|
|
1028
1068
|
.map(item => ({ ...item.ref }))
|
|
1029
1069
|
}
|
|
1030
1070
|
|
|
1071
|
+
// The compatibility timestamps follow the same bounded id window on both admission paths.
|
|
1072
|
+
function pruneInjectedAt(binding) {
|
|
1073
|
+
const kept = new Set(binding.injectedIds || [])
|
|
1074
|
+
binding.injectedAt = Object.fromEntries(Object.entries(binding.injectedAt || {})
|
|
1075
|
+
.filter(([id]) => kept.has(id) && id !== '__anchor__').slice(-400))
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1031
1078
|
/** Commit one immutable message after its exact body entered host history. No entry bodies. */
|
|
1032
1079
|
export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
|
|
1033
1080
|
if (!sessionId || typeof options.messageId !== 'string' || !Number.isFinite(Number(memoryClock))) return null
|
|
@@ -1076,6 +1123,7 @@ export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
|
|
|
1076
1123
|
binding.injectionOwnerClocks[key] = Number(memoryClock)
|
|
1077
1124
|
}
|
|
1078
1125
|
for (const id of ids) applyEffect(`id:${id}`, Number(memoryClock), 'injectedAt', id)
|
|
1126
|
+
pruneInjectedAt(binding)
|
|
1079
1127
|
const actions = structuredClone(options.actions || {})
|
|
1080
1128
|
const patch = actions.patch || {}
|
|
1081
1129
|
if (actions.anchor) { patch.anchorPushed = true; patch.reinjectPending = false }
|
|
@@ -1187,6 +1235,7 @@ export function markInjected(sessionId, ids, turn) {
|
|
|
1187
1235
|
binding.injectionOwners[`id:${id}`] = owner
|
|
1188
1236
|
}
|
|
1189
1237
|
binding.injectedAt = at
|
|
1238
|
+
pruneInjectedAt(binding)
|
|
1190
1239
|
binding.lastInjectedTurn = turn ?? binding.lastInjectedTurn ?? 0
|
|
1191
1240
|
// 主动记忆抑制要一个"最近一次真正注入了记忆"的墙钟时间;turn 号不能跨会话比较。
|
|
1192
1241
|
binding.lastInjectedAt = stamp()
|
|
@@ -1485,6 +1534,7 @@ export function rollbackInjectionForTurn(sessionId, hostTurn, { messageIds = [],
|
|
|
1485
1534
|
delete binding.injectionOwners[key]
|
|
1486
1535
|
}
|
|
1487
1536
|
}
|
|
1537
|
+
pruneInjectedAt(binding) // 回滚旧 effect 不能复活已离开 400 项窗口的时间戳。
|
|
1488
1538
|
if (targets.length) rolled = { ids: targets.flatMap(record => record.refs.map(ref => ref.id)), guideKey: null, anniversaries: 0, nudges: 0 }
|
|
1489
1539
|
const record = binding.injectionRollback
|
|
1490
1540
|
if (!record || record.hostTurn !== turn) return state
|
|
@@ -1555,8 +1605,71 @@ export function globalDbPath() {
|
|
|
1555
1605
|
// memory text) is the expensive part. Validity is mtime+size, so an external
|
|
1556
1606
|
// change is always picked up. Callers mutate the returned object and save it
|
|
1557
1607
|
// straight away — that is the shape every writer already had.
|
|
1558
|
-
const indexCache =
|
|
1608
|
+
const indexCache = createBoundedCache({ name: 'index', maxBytes: 256 * 1024 * 1024, maxEntries: 64, ttlMs: 300000 })
|
|
1559
1609
|
const indexBases = new WeakMap()
|
|
1610
|
+
const indexRevisions = new WeakMap()
|
|
1611
|
+
const indexExpiryTimes = new WeakMap()
|
|
1612
|
+
const indexRevisionWindows = new WeakMap()
|
|
1613
|
+
const readOnlyViews = new WeakSet()
|
|
1614
|
+
const INDEX_OBSERVATION_FIELDS = new Set(['injectCount', 'lastInjectAt', 'lastAccessAt', 'accessCount', 'vector', 'vectorPending'])
|
|
1615
|
+
|
|
1616
|
+
export function indexCacheStats() { return indexCache.stats() }
|
|
1617
|
+
export function indexDataRevision(index) { return indexRevisions.get(index) || null }
|
|
1618
|
+
export function indexReadRevision(index) {
|
|
1619
|
+
const revision = indexRevisions.get(index)
|
|
1620
|
+
if (!revision) return null
|
|
1621
|
+
const now = Date.now()
|
|
1622
|
+
const day = localCalendarDay(new Date(now))
|
|
1623
|
+
const cached = indexRevisionWindows.get(index)
|
|
1624
|
+
// Hot reads are O(1); only an exact expiry crossing or clock rollback searches.
|
|
1625
|
+
if (cached && cached.day === day && now >= cached.start && now < cached.end) return cached.key
|
|
1626
|
+
const times = indexExpiryTimes.get(index) || []
|
|
1627
|
+
let lo = 0, hi = times.length
|
|
1628
|
+
while (lo < hi) {
|
|
1629
|
+
const mid = (lo + hi) >>> 1
|
|
1630
|
+
if (times[mid] <= now) lo = mid + 1
|
|
1631
|
+
else hi = mid
|
|
1632
|
+
}
|
|
1633
|
+
// valid_from/valid_to use the host calendar day, independent of decay buckets.
|
|
1634
|
+
const key = `${revision}:${day}:${lo}`
|
|
1635
|
+
indexRevisionWindows.set(index, { day, start: lo ? times[lo - 1] : -Infinity, end: times[lo] ?? Infinity, key })
|
|
1636
|
+
return key
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
function freezeIndex(value) {
|
|
1640
|
+
if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value
|
|
1641
|
+
for (const child of Object.values(value)) freezeIndex(child)
|
|
1642
|
+
return Object.freeze(value)
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
// P1: O(N) content/qualification hashing belongs to cold admission and successful
|
|
1646
|
+
// writes, never hot query hits. Observational writes retain the same corpus key.
|
|
1647
|
+
function indexContentRevision(index) {
|
|
1648
|
+
const hash = crypto.createHash('sha256')
|
|
1649
|
+
for (const [id, entry] of Object.entries(index.entries || {})) {
|
|
1650
|
+
const semantic = { ...entry }
|
|
1651
|
+
for (const key of INDEX_OBSERVATION_FIELDS) delete semantic[key]
|
|
1652
|
+
hash.update(id).update('\u0000').update(JSON.stringify(semantic)).update('\u0000')
|
|
1653
|
+
}
|
|
1654
|
+
return hash.digest('hex')
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
function indexStat(file) {
|
|
1658
|
+
try {
|
|
1659
|
+
const stat = fs.statSync(file, { bigint: true })
|
|
1660
|
+
return `${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.ino}`
|
|
1661
|
+
} catch { return null }
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
function indexRecord(index, stat) {
|
|
1665
|
+
const revision = indexContentRevision(index)
|
|
1666
|
+
freezeIndex(index)
|
|
1667
|
+
const expiries = Object.values(index.entries || {}).filter(entry => entry.expiresAt)
|
|
1668
|
+
.map(entry => Date.parse(entry.expiresAt) || 0).sort((a, b) => a - b)
|
|
1669
|
+
indexRevisions.set(index, revision)
|
|
1670
|
+
indexExpiryTimes.set(index, expiries)
|
|
1671
|
+
return { stat, index, revision, expiries, view: null }
|
|
1672
|
+
}
|
|
1560
1673
|
|
|
1561
1674
|
// The sidebar paints a snapshot of both indexes, and nothing used to tell it when
|
|
1562
1675
|
// that snapshot had gone stale: a memory written by a tool call, or from the
|
|
@@ -1620,41 +1733,72 @@ export function memoryStamp() {
|
|
|
1620
1733
|
return parts.join("|")
|
|
1621
1734
|
}
|
|
1622
1735
|
|
|
1623
|
-
function cachedIndex(file, loader, normalize) {
|
|
1624
|
-
const
|
|
1625
|
-
|
|
1626
|
-
if (
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1736
|
+
function cachedIndex(file, loader, normalize, readOnly = false) {
|
|
1737
|
+
const stat = indexStat(file)
|
|
1738
|
+
let record = indexCache.get(file)
|
|
1739
|
+
if (!record || !stat || record.stat !== stat) {
|
|
1740
|
+
const index = loader()
|
|
1741
|
+
record = indexRecord(index, stat)
|
|
1742
|
+
// A failed-read fallback must never shadow a recovered real file.
|
|
1743
|
+
if (stat && !readFailure(file)) indexCache.set(file, record)
|
|
1744
|
+
}
|
|
1745
|
+
if (readOnly && process.env.DSH_MEMU_INDEX_COW !== '0') {
|
|
1746
|
+
if (!record.view) {
|
|
1747
|
+
let view = record.index
|
|
1748
|
+
if (normalize && Object.values(view.entries).some(entry => entry.visibility === 'session' || 'sessionId' in entry)) {
|
|
1749
|
+
view = structuredClone(view)
|
|
1750
|
+
normalize(view)
|
|
1751
|
+
freezeIndex(view)
|
|
1752
|
+
}
|
|
1753
|
+
indexRevisions.set(view, record.revision)
|
|
1754
|
+
indexExpiryTimes.set(view, record.expiries)
|
|
1755
|
+
readOnlyViews.add(view)
|
|
1756
|
+
record.view = view
|
|
1757
|
+
// A migrated view has separate retained bodies and must be accounted too.
|
|
1758
|
+
if (view !== record.index && stat && !readFailure(file)) indexCache.set(file, record)
|
|
1759
|
+
}
|
|
1760
|
+
return record.view
|
|
1761
|
+
}
|
|
1762
|
+
return indexSnapshot(record.index, normalize)
|
|
1632
1763
|
}
|
|
1633
1764
|
|
|
1634
|
-
//
|
|
1635
|
-
//
|
|
1636
|
-
// upgrade: `writeIndex` diffs against the baseline, sees the change, and checks the file
|
|
1637
|
-
// still matches what we read before accepting it.
|
|
1765
|
+
// Writers keep an isolated mutable clone and the exact raw baseline for CAS.
|
|
1766
|
+
// Pure readers explicitly opt into the frozen view; migration only changes it.
|
|
1638
1767
|
function indexSnapshot(index, normalize) {
|
|
1639
|
-
const baseline = structuredClone(index)
|
|
1768
|
+
const baseline = process.env.DSH_MEMU_INDEX_COW === '0' ? structuredClone(index) : index
|
|
1640
1769
|
const copy = structuredClone(index)
|
|
1641
1770
|
if (normalize) normalize(copy)
|
|
1642
1771
|
indexBases.set(copy, baseline)
|
|
1772
|
+
indexRevisions.set(copy, indexRevisions.get(index))
|
|
1773
|
+
indexExpiryTimes.set(copy, indexExpiryTimes.get(index))
|
|
1643
1774
|
return copy
|
|
1644
1775
|
}
|
|
1645
1776
|
|
|
1646
1777
|
function rememberIndex(file, index) {
|
|
1647
|
-
const stat =
|
|
1648
|
-
if (stat) indexCache.set(file,
|
|
1778
|
+
const stat = indexStat(file)
|
|
1779
|
+
if (stat) indexCache.set(file, indexRecord(structuredClone(index), stat))
|
|
1649
1780
|
}
|
|
1650
1781
|
|
|
1651
1782
|
const indexWriteListeners = new Set()
|
|
1783
|
+
const indexCommitListeners = new Set()
|
|
1784
|
+
export function onIndexCommit(listener) {
|
|
1785
|
+
indexCommitListeners.add(listener)
|
|
1786
|
+
return () => indexCommitListeners.delete(listener)
|
|
1787
|
+
}
|
|
1788
|
+
function notifyIndexCommit(libraryId, before, after) {
|
|
1789
|
+
if (!indexCommitListeners.size) return
|
|
1790
|
+
for (const listener of indexCommitListeners) {
|
|
1791
|
+
try { listener({ libraryId, before, after }) }
|
|
1792
|
+
catch (error) { warn(`derived index update failed: ${error?.code || 'RT_UPDATE_FAILED'}`) }
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1652
1795
|
export function onPrivateIndexWrite(listener) {
|
|
1653
1796
|
indexWriteListeners.add(listener)
|
|
1654
1797
|
return () => indexWriteListeners.delete(listener)
|
|
1655
1798
|
}
|
|
1656
1799
|
|
|
1657
1800
|
function writeIndex(file, index) {
|
|
1801
|
+
if (readOnlyViews.has(index)) throw new TypeError('read-only index view cannot be saved; load a mutable snapshot')
|
|
1658
1802
|
return withFileLock(file, () => {
|
|
1659
1803
|
const base = indexBases.get(index)
|
|
1660
1804
|
let next = index
|
|
@@ -1684,7 +1828,7 @@ function writeIndex(file, index) {
|
|
|
1684
1828
|
})
|
|
1685
1829
|
}
|
|
1686
1830
|
|
|
1687
|
-
export function loadPrivateIndex(libraryId) {
|
|
1831
|
+
export function loadPrivateIndex(libraryId, { readOnly = false } = {}) {
|
|
1688
1832
|
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
1689
1833
|
const file = path.join(indexDir(), `${libraryId}.json`)
|
|
1690
1834
|
return cachedIndex(file, () => {
|
|
@@ -1698,7 +1842,11 @@ export function loadPrivateIndex(libraryId) {
|
|
|
1698
1842
|
// the level ever existed. Only the view is upgraded; the baseline stays the raw file
|
|
1699
1843
|
// so the next ordinary write persists the conversion (see `indexSnapshot`).
|
|
1700
1844
|
migrateIndexVisibility(index, stamp())
|
|
1701
|
-
})
|
|
1845
|
+
}, readOnly)
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
export function readPrivateIndex(libraryId) {
|
|
1849
|
+
return loadPrivateIndex(libraryId, { readOnly: true })
|
|
1702
1850
|
}
|
|
1703
1851
|
|
|
1704
1852
|
/**
|
|
@@ -1715,7 +1863,12 @@ export function savePrivateIndex(libraryId, index, { bumpRevision = true } = {})
|
|
|
1715
1863
|
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
1716
1864
|
if (!validIndex(index)) throw new Error('invalid memory index shape')
|
|
1717
1865
|
const file = path.join(indexDir(), `${libraryId}.json`)
|
|
1866
|
+
const before = indexCommitListeners.size ? readPrivateIndex(libraryId) : null
|
|
1718
1867
|
const saved = writeIndex(file, index)
|
|
1868
|
+
if (before) {
|
|
1869
|
+
try { notifyIndexCommit(libraryId, before, readPrivateIndex(libraryId)) }
|
|
1870
|
+
catch (error) { warn(`derived index notification failed: ${error?.code || 'RT_UPDATE_FAILED'}`) }
|
|
1871
|
+
}
|
|
1719
1872
|
if (bumpRevision) bumpMemoryRevision()
|
|
1720
1873
|
noteMemoryWrite('private', libraryId)
|
|
1721
1874
|
for (const listener of indexWriteListeners) {
|
|
@@ -1723,12 +1876,16 @@ export function savePrivateIndex(libraryId, index, { bumpRevision = true } = {})
|
|
|
1723
1876
|
}
|
|
1724
1877
|
}
|
|
1725
1878
|
|
|
1726
|
-
export function loadGlobalIndex() {
|
|
1879
|
+
export function loadGlobalIndex({ readOnly = false } = {}) {
|
|
1727
1880
|
return cachedIndex(GLOBAL_INDEX(), () => {
|
|
1728
1881
|
let raw = readJson(GLOBAL_INDEX(), null)
|
|
1729
1882
|
if (raw !== null) raw = assertJsonShape(GLOBAL_INDEX(), raw, validIndex)
|
|
1730
1883
|
return raw && typeof raw === 'object' ? { version: 1, entries: raw.entries || {} } : { version: 1, entries: {} }
|
|
1731
|
-
})
|
|
1884
|
+
}, undefined, readOnly)
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
export function readGlobalIndex() {
|
|
1888
|
+
return loadGlobalIndex({ readOnly: true })
|
|
1732
1889
|
}
|
|
1733
1890
|
|
|
1734
1891
|
function validIndex(value) {
|
|
@@ -1738,7 +1895,12 @@ function validIndex(value) {
|
|
|
1738
1895
|
|
|
1739
1896
|
export function saveGlobalIndex(index, { bumpRevision = true } = {}) {
|
|
1740
1897
|
if (!validIndex(index)) throw new Error('invalid memory index shape')
|
|
1898
|
+
const before = indexCommitListeners.size ? readGlobalIndex() : null
|
|
1741
1899
|
writeIndex(GLOBAL_INDEX(), index)
|
|
1900
|
+
if (before) {
|
|
1901
|
+
try { notifyIndexCommit(null, before, readGlobalIndex()) }
|
|
1902
|
+
catch (error) { warn(`derived index notification failed: ${error?.code || 'RT_UPDATE_FAILED'}`) }
|
|
1903
|
+
}
|
|
1742
1904
|
if (bumpRevision) bumpMemoryRevision()
|
|
1743
1905
|
noteMemoryWrite('global', null)
|
|
1744
1906
|
}
|
|
@@ -1806,7 +1968,8 @@ export async function backupDatabases(options = {}) {
|
|
|
1806
1968
|
// before a flush would silently capture the previous state.
|
|
1807
1969
|
let report
|
|
1808
1970
|
try {
|
|
1809
|
-
|
|
1971
|
+
const { checkpointMaintenanceLedger } = await import('./maintenance-ledger.js')
|
|
1972
|
+
report = await createBackup({ ...options, flushState, checkpointMaintenance: checkpointMaintenanceLedger })
|
|
1810
1973
|
} catch (error) {
|
|
1811
1974
|
// A refusal is the safety property working, not something to swallow: a
|
|
1812
1975
|
// database the engine could not snapshot aborts the backup, and the reason
|
|
@@ -1939,6 +2102,14 @@ export function pruneSessionBindings({ olderThanDays = 30, dryRun = true, now =
|
|
|
1939
2102
|
// Same predicate as the candidate pass, on the fresh copy: `at < cutoff` alone
|
|
1940
2103
|
// would still delete a binding that just came back with a stale lastTurnAt.
|
|
1941
2104
|
if (!Number.isFinite(at) || at >= cutoff) { revalidated.push(item.sessionId); continue }
|
|
2105
|
+
if (typeof isBusy === 'function') {
|
|
2106
|
+
let busy = false
|
|
2107
|
+
try { busy = isBusy(item.sessionId) === true } catch (error) {
|
|
2108
|
+
busy = true
|
|
2109
|
+
warn(`prune-session-bindings: apply liveness check failed for ${item.sessionId} (${error?.message || error}); kept`)
|
|
2110
|
+
}
|
|
2111
|
+
if (busy) { revalidated.push(item.sessionId); continue }
|
|
2112
|
+
}
|
|
1942
2113
|
delete next.sessions[item.sessionId]
|
|
1943
2114
|
removed.push(item.sessionId)
|
|
1944
2115
|
}
|
package/lib/temporal.js
CHANGED
|
@@ -111,7 +111,8 @@ function zonedCalendar(instant, timeZone) {
|
|
|
111
111
|
function candidate(index, sourceText, calendar, precision, dateSource, priority) {
|
|
112
112
|
if (!validCalendar(calendar.y, calendar.m, calendar.d)) return null
|
|
113
113
|
return {
|
|
114
|
-
absoluteDate: formatDate(calendar),
|
|
114
|
+
absoluteDate: precision === 'day' ? formatDate(calendar) : null,
|
|
115
|
+
datePrefix: precision === 'year' ? String(calendar.y) : `${calendar.y}-${pad2(calendar.m)}`,
|
|
115
116
|
precision,
|
|
116
117
|
sourceText: String(sourceText || '').trim(),
|
|
117
118
|
dateSource,
|
|
@@ -191,32 +192,49 @@ function weekCandidates(text, today) {
|
|
|
191
192
|
}
|
|
192
193
|
|
|
193
194
|
function monthDayCandidates(text, today) {
|
|
194
|
-
const re = /(
|
|
195
|
+
const re = /(下个?月|下月份?|上个?月|上月份?|本月|这个月份?)\s*(\d{1,2})\s*[号日]/g
|
|
195
196
|
return matchesOf(re, text, (match) => {
|
|
196
197
|
const day = Number(match[2])
|
|
197
|
-
const month = match[1].startsWith('下') ?
|
|
198
|
+
const month = addMonths(today, match[1].startsWith('下') ? 1 : match[1].startsWith('上') ? -1 : 0)
|
|
198
199
|
if (day < 1 || day > daysInMonth(month.y, month.m)) return null
|
|
199
200
|
return candidate(match.index, match[0], { y: month.y, m: month.m, d: day }, 'day', 'relative', 30)
|
|
200
201
|
})
|
|
201
202
|
}
|
|
202
203
|
|
|
203
204
|
function monthBoundaryCandidates(text, today) {
|
|
204
|
-
const re = /(
|
|
205
|
+
const re = /(下个?月|下月份?|上个?月|上月份?|本月|这个月份?|月)\s*(?:初|底|末)/g
|
|
205
206
|
return matchesOf(re, text, (match) => {
|
|
206
207
|
const prefix = match[1]
|
|
207
|
-
const month = prefix.startsWith('下') ?
|
|
208
|
+
const month = addMonths(today, prefix.startsWith('下') ? 1 : prefix.startsWith('上') ? -1 : 0)
|
|
208
209
|
return candidate(match.index, match[0], { y: month.y, m: month.m, d: daysInMonth(month.y, month.m) }, 'month', 'relative', 40)
|
|
209
210
|
})
|
|
210
211
|
}
|
|
211
212
|
|
|
213
|
+
const YEAR_OFFSETS = { 今年: 0, 明年: 1, 后年: 2, 去年: -1, 前年: -2, 年: 0 }
|
|
214
|
+
|
|
212
215
|
function yearBoundaryCandidates(text, today) {
|
|
216
|
+
return matchesOf(/(今年|明年|后年|去年|前年|年)年?(初|底|末)/g, text, match => candidate(
|
|
217
|
+
match.index, match[0], { y: today.y + YEAR_OFFSETS[match[1]], m: 1, d: 1 }, 'year', 'relative', 50,
|
|
218
|
+
))
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function periodCandidates(text, today) {
|
|
213
222
|
const out = []
|
|
214
|
-
for (const match of text.matchAll(
|
|
215
|
-
const
|
|
223
|
+
for (const match of text.matchAll(/(今年|明年|后年|去年|前年)(?:\s*(\d{1,2})月(?:\s*(\d{1,2})[日号])?)?/g)) {
|
|
224
|
+
const y = today.y + YEAR_OFFSETS[match[1]]
|
|
225
|
+
const m = Number(match[2] || 1), d = Number(match[3] || 1)
|
|
226
|
+
const precision = match[3] ? 'day' : match[2] ? 'month' : 'year'
|
|
227
|
+
const item = candidate(match.index, match[0], { y, m, d }, precision, 'relative', match[3] ? 25 : 60)
|
|
216
228
|
if (item) out.push(item)
|
|
217
229
|
}
|
|
218
|
-
for (const match of text.matchAll(/(
|
|
219
|
-
const
|
|
230
|
+
for (const match of text.matchAll(/(上个?月|上月份?|下个?月|下月份?|本月|这个月份?)(?!\s*\d)/g)) {
|
|
231
|
+
const month = addMonths(today, match[1].startsWith('下') ? 1 : match[1].startsWith('上') ? -1 : 0)
|
|
232
|
+
const item = candidate(match.index, match[0], { ...month, d: 1 }, 'month', 'relative', 60)
|
|
233
|
+
if (item) out.push(item)
|
|
234
|
+
}
|
|
235
|
+
for (const match of text.matchAll(/(\d{4})年(?:\s*(\d{1,2})月)?/g)) {
|
|
236
|
+
if (/^\s*\d/.test(text.slice(match.index + match[0].length))) continue
|
|
237
|
+
const item = candidate(match.index, match[0], { y: Number(match[1]), m: Number(match[2] || 1), d: 1 }, match[2] ? 'month' : 'year', 'explicit', 5)
|
|
220
238
|
if (item) out.push(item)
|
|
221
239
|
}
|
|
222
240
|
return out
|
|
@@ -252,6 +270,7 @@ function allCandidates(text, { now, timeZone } = {}) {
|
|
|
252
270
|
...monthDayCandidates(normalized, today),
|
|
253
271
|
...monthBoundaryCandidates(normalized, today),
|
|
254
272
|
...yearBoundaryCandidates(normalized, today),
|
|
273
|
+
...periodCandidates(normalized, today),
|
|
255
274
|
...offsetDayCandidates(normalized, today),
|
|
256
275
|
]
|
|
257
276
|
// 同一位置同一句只留最具体的一条(显式日期 > 相对日 > 周 > 月日 > 月底 > 年)。
|
|
@@ -261,12 +280,16 @@ function allCandidates(text, { now, timeZone } = {}) {
|
|
|
261
280
|
const current = best.get(key)
|
|
262
281
|
if (!current || item.priority < current.priority) best.set(key, item)
|
|
263
282
|
}
|
|
264
|
-
|
|
283
|
+
const selected = []
|
|
284
|
+
for (const item of [...best.values()].sort((a, b) => a.priority - b.priority || b.sourceText.length - a.sourceText.length)) {
|
|
285
|
+
if (!selected.some(other => item.index < other.index + other.sourceText.length && other.index < item.index + item.sourceText.length)) selected.push(item)
|
|
286
|
+
}
|
|
287
|
+
return selected.sort((a, b) => a.index - b.index || a.priority - b.priority)
|
|
265
288
|
}
|
|
266
289
|
|
|
267
290
|
/**
|
|
268
291
|
* 解析文本里最可信的一个日期表达。
|
|
269
|
-
* @returns {{absoluteDate: string, precision: 'day'|'month'|'year', sourceText: string,
|
|
292
|
+
* @returns {{absoluteDate: string|null, datePrefix?: string, precision: 'day'|'month'|'year', sourceText: string,
|
|
270
293
|
* dateSource: 'explicit'|'relative', index: number}|null}
|
|
271
294
|
*/
|
|
272
295
|
export function parseTemporalExpression(text, { now = new Date(), timeZone = DEFAULT_TIME_ZONE } = {}) {
|
|
@@ -276,6 +299,7 @@ export function parseTemporalExpression(text, { now = new Date(), timeZone = DEF
|
|
|
276
299
|
const chosen = ordered[0]
|
|
277
300
|
return {
|
|
278
301
|
absoluteDate: chosen.absoluteDate,
|
|
302
|
+
...(chosen.precision === 'day' ? {} : { datePrefix: chosen.datePrefix }),
|
|
279
303
|
precision: chosen.precision,
|
|
280
304
|
sourceText: chosen.sourceText,
|
|
281
305
|
dateSource: chosen.dateSource,
|
|
@@ -287,6 +311,7 @@ export function parseTemporalExpression(text, { now = new Date(), timeZone = DEF
|
|
|
287
311
|
export function extractTemporalExpressions(text, options = {}) {
|
|
288
312
|
return allCandidates(text, options).map((item) => ({
|
|
289
313
|
absoluteDate: item.absoluteDate,
|
|
314
|
+
...(item.precision === 'day' ? {} : { datePrefix: item.datePrefix }),
|
|
290
315
|
precision: item.precision,
|
|
291
316
|
sourceText: item.sourceText,
|
|
292
317
|
dateSource: item.dateSource,
|
|
@@ -298,7 +323,8 @@ export function extractTemporalExpressions(text, options = {}) {
|
|
|
298
323
|
export function resolveQueryDates(text, options = {}) {
|
|
299
324
|
const dates = []
|
|
300
325
|
for (const item of extractTemporalExpressions(text, options)) {
|
|
301
|
-
|
|
326
|
+
const key = item.absoluteDate || item.datePrefix
|
|
327
|
+
if (key && !dates.includes(key)) dates.push(key)
|
|
302
328
|
}
|
|
303
329
|
return dates
|
|
304
330
|
}
|
|
@@ -306,7 +332,7 @@ export function resolveQueryDates(text, options = {}) {
|
|
|
306
332
|
/** 有相对时间词、但可能解析不出来(例如只说“下周”)。 */
|
|
307
333
|
export function hasTemporalHint(text) {
|
|
308
334
|
const value = String(text ?? '').normalize('NFKC')
|
|
309
|
-
return
|
|
335
|
+
return /大后天|大前天|后天|前天|明天|昨天|今天|今日|明日|昨日|(?:上上|上|下个|下|这个|这|本)\s*(?:周|星期|礼拜)|上个?月|下个?月|本月|这个月|月初|月底|月末|今年|明年|后年|去年|前年|年初|年底|年末|\d{4}\s*[-/年]\s*\d|\d{4}年|\d\s*天\s*(?:之|以)?[前后]|(?<![a-z])(today|tomorrow|yesterday)(?![a-z])/i.test(value)
|
|
310
336
|
}
|
|
311
337
|
|
|
312
338
|
/** 严格 YYYY-MM-DD;非法日期返回 null(不猜)。 */
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { estTokens, cjkRatio } from './budget.js'
|
|
2
|
+
|
|
3
|
+
export const TOKEN_RATIO_BUCKETS = Object.freeze(['latin', 'mixed', 'cjk'])
|
|
4
|
+
export function tokenRatioBucket(text) {
|
|
5
|
+
const ratio = cjkRatio(text)
|
|
6
|
+
return ratio < 0.2 ? 'latin' : ratio < 0.7 ? 'mixed' : 'cjk'
|
|
7
|
+
}
|
|
8
|
+
const count = value => Number.isSafeInteger(value) && value >= 0 ? value : null
|
|
9
|
+
const emptyUsage = () => ({ inputTokens: null, cacheReadTokens: null, cacheWriteTokens: null, outputTokens: null, reasoningTokens: null, totalTokens: null })
|
|
10
|
+
|
|
11
|
+
/** Public assistant/message usage describes a WHOLE request, never a memory block. */
|
|
12
|
+
export function requestTokenUsage(event) {
|
|
13
|
+
if (event?.type !== 'assistant/message' || !event.data?.usage || typeof event.data.usage !== 'object') return null
|
|
14
|
+
const usage = Object.fromEntries(Object.keys(emptyUsage()).map(key => [key, count(event.data.usage[key])]))
|
|
15
|
+
if (!Object.values(usage).some(value => value !== null)) return null
|
|
16
|
+
// Optional cache counters stay unknown. Only an exact total-output pair or all
|
|
17
|
+
// three disjoint input counters can prove aggregate prompt usage.
|
|
18
|
+
const fromTotal = usage.totalTokens !== null && usage.outputTokens !== null && usage.totalTokens >= usage.outputTokens
|
|
19
|
+
? usage.totalTokens - usage.outputTokens : null
|
|
20
|
+
const fromParts = [usage.inputTokens, usage.cacheReadTokens, usage.cacheWriteTokens].every(value => value !== null)
|
|
21
|
+
? usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens : null
|
|
22
|
+
return { ...usage, promptTokens: fromTotal ?? fromParts, source: 'session/event.assistant/message.data.usage', attribution: 'whole-request' }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Bounded in-process reservations: no memory bodies, no tokenizer guesses. */
|
|
26
|
+
export function createTurnTokenLedger({ maxSessions = 128, maxTurns = 8, maxMessages = 256 } = {}) {
|
|
27
|
+
const sessions = new Map()
|
|
28
|
+
function entry(sessionId, turn, create = true) {
|
|
29
|
+
let turns = sessions.get(sessionId)
|
|
30
|
+
if (!turns && create) { turns = new Map(); sessions.set(sessionId, turns) }
|
|
31
|
+
let state = turns?.get(Number(turn))
|
|
32
|
+
if (!state && create) {
|
|
33
|
+
state = { messages: new Map(), requests: new Map(), anonymous: new WeakSet(), lastUsage: null }
|
|
34
|
+
turns.set(Number(turn), state)
|
|
35
|
+
while (turns.size > maxTurns) turns.delete(turns.keys().next().value)
|
|
36
|
+
}
|
|
37
|
+
while (sessions.size > maxSessions) sessions.delete(sessions.keys().next().value)
|
|
38
|
+
return state
|
|
39
|
+
}
|
|
40
|
+
const used = state => [...(state?.messages.values() || [])].reduce((sum, row) => sum + row.estimated, 0)
|
|
41
|
+
function room(sessionId, turn, limit) { return Math.max(0, (Number(limit) || 0) - used(entry(sessionId, turn, false))) }
|
|
42
|
+
function reserve(sessionId, turn, id, text, limit) {
|
|
43
|
+
const state = entry(sessionId, turn)
|
|
44
|
+
if (state.messages.has(id)) return true
|
|
45
|
+
if (state.messages.size >= maxMessages) return false
|
|
46
|
+
const estimated = estTokens(text)
|
|
47
|
+
if (estimated > room(sessionId, turn, limit)) return false
|
|
48
|
+
state.messages.set(id, { estimated, bucket: tokenRatioBucket(text), admitted: false })
|
|
49
|
+
return true
|
|
50
|
+
}
|
|
51
|
+
function admit(sessionId, turn, id) {
|
|
52
|
+
const row = entry(sessionId, turn, false)?.messages.get(id)
|
|
53
|
+
if (row) row.admitted = true
|
|
54
|
+
}
|
|
55
|
+
function release(sessionId, turn, id) {
|
|
56
|
+
const state = entry(sessionId, turn, false)
|
|
57
|
+
if (!state?.messages.get(id)?.admitted) state?.messages.delete(id)
|
|
58
|
+
}
|
|
59
|
+
function observeUsage(sessionId, turn, event) {
|
|
60
|
+
const usage = requestTokenUsage(event)
|
|
61
|
+
if (!usage) return false
|
|
62
|
+
const state = entry(sessionId, turn)
|
|
63
|
+
const data = event.data || {}
|
|
64
|
+
const requestId = typeof data.requestId === 'string' || Number.isSafeInteger(data.requestId) ? data.requestId : null
|
|
65
|
+
const id = requestId !== null ? 'request:' + requestId : Number.isSafeInteger(event.seq) ? 'seq:' + event.seq
|
|
66
|
+
: typeof event.id === 'string' ? 'event:' + event.id : null
|
|
67
|
+
if (id ? state.requests.has(id) : state.anonymous.has(event)) return false
|
|
68
|
+
if (state.requests.size >= maxMessages) return false
|
|
69
|
+
if (!id) state.anonymous.add(event)
|
|
70
|
+
state.requests.set(id ?? Symbol(), usage)
|
|
71
|
+
state.lastUsage = usage
|
|
72
|
+
return true
|
|
73
|
+
}
|
|
74
|
+
function snapshot(sessionId, turn, limit) {
|
|
75
|
+
const state = entry(sessionId, turn, false)
|
|
76
|
+
const rows = [...(state?.messages.values() || [])]
|
|
77
|
+
return {
|
|
78
|
+
schemaVersion: 1, turn: Number(turn), limit: Number(limit) || 0,
|
|
79
|
+
estimated: used(state), remaining: room(sessionId, turn, limit), messages: rows.length,
|
|
80
|
+
admittedEstimated: rows.filter(row => row.admitted).reduce((sum, row) => sum + row.estimated, 0),
|
|
81
|
+
reservedEstimated: rows.filter(row => !row.admitted).reduce((sum, row) => sum + row.estimated, 0),
|
|
82
|
+
estimator: 'budget.estTokens', memoryActual: null, calibration: 'unverified', calibrationFactor: null,
|
|
83
|
+
reason: 'public usage is whole-request; no memory-block attribution or public tokenizer verified',
|
|
84
|
+
ratioBuckets: Object.fromEntries(TOKEN_RATIO_BUCKETS.map(bucket => [bucket, {
|
|
85
|
+
messages: rows.filter(row => row.bucket === bucket).length,
|
|
86
|
+
estimated: rows.filter(row => row.bucket === bucket).reduce((sum, row) => sum + row.estimated, 0),
|
|
87
|
+
actual: null, status: 'unverified',
|
|
88
|
+
}])),
|
|
89
|
+
requestUsage: { requests: state?.requests.size || 0, last: state?.lastUsage || null, attribution: 'whole-request' },
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function finish(sessionId, turn) {
|
|
93
|
+
const state = entry(sessionId, turn, false)
|
|
94
|
+
if (!state) return
|
|
95
|
+
for (const [id, row] of state.messages) if (!row.admitted) state.messages.delete(id)
|
|
96
|
+
// Accepted reservations survive a failed retry with the same host turn.
|
|
97
|
+
// Unadmitted proposals were released above and may be retried.
|
|
98
|
+
}
|
|
99
|
+
return { room, reserve, admit, release, observeUsage, snapshot, finish, clear: sessionId => sessions.delete(sessionId) }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export const WORKER_FACTOR_DEFAULT = 3
|
|
103
|
+
export const WORKER_FACTOR_WINDOW = 16
|
|
104
|
+
/** Ratios measure retained input+visible output characters, not hidden reasoning. */
|
|
105
|
+
export function createDomainOutputFactors({ maxDomains = 32, window = WORKER_FACTOR_WINDOW } = {}) {
|
|
106
|
+
const domains = new Map()
|
|
107
|
+
const keyOf = domain => String(domain || 'general')
|
|
108
|
+
const clamp = value => Math.max(2, Math.min(4, value))
|
|
109
|
+
function snapshot(domain) {
|
|
110
|
+
const samples = domains.get(keyOf(domain)) || []
|
|
111
|
+
return { domain: keyOf(domain), factor: samples.length ? clamp(samples.reduce((sum, sample) => sum + sample, 0) / samples.length) : WORKER_FACTOR_DEFAULT,
|
|
112
|
+
samples: samples.length, window, source: samples.length ? 'observed-window-characters' : 'default', reasoning: 'unverified' }
|
|
113
|
+
}
|
|
114
|
+
function observe(domain, inputChars, outputChars) {
|
|
115
|
+
if (!Number.isSafeInteger(inputChars) || inputChars <= 0 || !Number.isSafeInteger(outputChars) || outputChars < 0) return false
|
|
116
|
+
const key = keyOf(domain)
|
|
117
|
+
const samples = domains.get(key) || []
|
|
118
|
+
// Bound each sample before averaging: one outlier must not poison 16 windows.
|
|
119
|
+
samples.push(clamp(1 + outputChars / inputChars))
|
|
120
|
+
if (samples.length > window) samples.splice(0, samples.length - window)
|
|
121
|
+
domains.delete(key); domains.set(key, samples)
|
|
122
|
+
while (domains.size > maxDomains) domains.delete(domains.keys().next().value)
|
|
123
|
+
return true
|
|
124
|
+
}
|
|
125
|
+
return { observe, snapshot }
|
|
126
|
+
}
|