@jjh32456/longlive 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
package/src/codec.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// @local/dsh-longlive — codec
|
|
2
|
+
//
|
|
3
|
+
// DSH session logs are multi-frame zstd streams (`session.v4.jsonl.zstd`):
|
|
4
|
+
// frame 1 : exactly one JSON line -> the session header
|
|
5
|
+
// frame n : a chunk of JSON lines -> events
|
|
6
|
+
// Every event carries a monotonically increasing `seq` starting at 0.
|
|
7
|
+
//
|
|
8
|
+
// Nothing here reads message content beyond the fields needed to fold the
|
|
9
|
+
// Surface and hash the visible messages. No network, no third-party deps.
|
|
10
|
+
|
|
11
|
+
import zlib from 'node:zlib';
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
|
|
14
|
+
export const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
15
|
+
export const HEADER_VERSION = 4;
|
|
16
|
+
|
|
17
|
+
const ZSTD_CHECKSUM_FLAG = zlib.constants.ZSTD_c_checksumFlag ?? 1;
|
|
18
|
+
|
|
19
|
+
/** Compress one chunk with the same settings the host uses (checksum on). */
|
|
20
|
+
export function compressFrame(text) {
|
|
21
|
+
return zlib.zstdCompressSync(Buffer.from(text, 'utf8'), {
|
|
22
|
+
params: { [ZSTD_CHECKSUM_FLAG]: 1 },
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Decompress one frame. Throws when the bytes are not one valid zstd frame. */
|
|
27
|
+
export function decompressFrame(frame) {
|
|
28
|
+
return zlib.zstdDecompressSync(frame).toString('utf8');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const ZSTD_MAGIC_LE = 0xfd2fb528; // bytes 28 B5 2F FD, read little-endian
|
|
32
|
+
const SKIPPABLE_MAGIC_MIN = 0x184d2a50;
|
|
33
|
+
const SKIPPABLE_MAGIC_MAX = 0x184d2a5f;
|
|
34
|
+
const DICTIONARY_ID_BYTES = [0, 1, 2, 4];
|
|
35
|
+
const CONTENT_SIZE_BYTES = [0, 2, 4, 8];
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Length in bytes of exactly one zstd frame starting at `start`, read from the
|
|
39
|
+
* frame structure itself (RFC 8878 §3.1): frame header, then block headers
|
|
40
|
+
* until the last block, then the optional content checksum.
|
|
41
|
+
*
|
|
42
|
+
* Nothing here searches for the next magic: a magic byte pair inside compressed
|
|
43
|
+
* payload is invisible to this walk, which is the whole point (see splitFrames).
|
|
44
|
+
*/
|
|
45
|
+
export function zstdFrameLength(buf, start = 0) {
|
|
46
|
+
const bad = (what, at) => new Error(`corrupt session log: ${what} at byte ${at}`);
|
|
47
|
+
let p = start;
|
|
48
|
+
if (p + 4 > buf.length) throw bad('truncated zstd frame magic', p);
|
|
49
|
+
const magic = buf.readUInt32LE(p);
|
|
50
|
+
if (magic >= SKIPPABLE_MAGIC_MIN && magic <= SKIPPABLE_MAGIC_MAX) {
|
|
51
|
+
if (p + 8 > buf.length) throw bad('truncated skippable zstd frame header', p);
|
|
52
|
+
const size = buf.readUInt32LE(p + 4);
|
|
53
|
+
if (p + 8 + size > buf.length) throw bad(`truncated skippable zstd frame (${size} payload bytes)`, p);
|
|
54
|
+
return p + 8 + size;
|
|
55
|
+
}
|
|
56
|
+
if (magic !== ZSTD_MAGIC_LE) throw bad('no zstd frame magic', p);
|
|
57
|
+
p += 4;
|
|
58
|
+
|
|
59
|
+
if (p + 1 > buf.length) throw bad('truncated zstd frame header', p);
|
|
60
|
+
const descriptor = buf[p];
|
|
61
|
+
p += 1;
|
|
62
|
+
const contentSizeFlag = descriptor >>> 6;
|
|
63
|
+
const singleSegment = (descriptor >>> 5) & 1;
|
|
64
|
+
const checksumFlag = (descriptor >>> 2) & 1;
|
|
65
|
+
const dictionaryFlag = descriptor & 3;
|
|
66
|
+
if ((descriptor >>> 3) & 1) throw bad('reserved bit set in the zstd frame header', start);
|
|
67
|
+
|
|
68
|
+
if (!singleSegment) {
|
|
69
|
+
if (p + 1 > buf.length) throw bad('truncated zstd window descriptor', p);
|
|
70
|
+
p += 1;
|
|
71
|
+
}
|
|
72
|
+
p += DICTIONARY_ID_BYTES[dictionaryFlag];
|
|
73
|
+
p += contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : CONTENT_SIZE_BYTES[contentSizeFlag];
|
|
74
|
+
if (p > buf.length) throw bad('truncated zstd frame header fields', start);
|
|
75
|
+
|
|
76
|
+
for (;;) {
|
|
77
|
+
if (p + 3 > buf.length) throw bad('truncated zstd block header', p);
|
|
78
|
+
const header = buf.readUIntLE(p, 3);
|
|
79
|
+
p += 3;
|
|
80
|
+
const lastBlock = header & 1;
|
|
81
|
+
const blockType = (header >>> 1) & 3;
|
|
82
|
+
const blockSize = header >>> 3;
|
|
83
|
+
if (blockType === 3) throw bad('reserved zstd block type', p - 3);
|
|
84
|
+
// An RLE block stores one byte whatever its decompressed size claims.
|
|
85
|
+
p += blockType === 1 ? 1 : blockSize;
|
|
86
|
+
if (p > buf.length) throw bad('truncated zstd block payload', p);
|
|
87
|
+
if (lastBlock) break;
|
|
88
|
+
}
|
|
89
|
+
if (checksumFlag) p += 4;
|
|
90
|
+
if (p > buf.length) throw bad('truncated zstd content checksum', p);
|
|
91
|
+
return p;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Split a log buffer into its physical zstd frames.
|
|
96
|
+
*
|
|
97
|
+
* Boundaries come from the frame structure (zstdFrameLength), not from scanning
|
|
98
|
+
* for the magic: a compressed payload that happens to contain 28 B5 2F FD used
|
|
99
|
+
* to be read as a frame boundary, which cut one frame into two and left the log
|
|
100
|
+
* unparseable. Each computed slice is then decompressed as a proof, so a corrupt
|
|
101
|
+
* log still fails loudly instead of yielding frames nobody can read.
|
|
102
|
+
*/
|
|
103
|
+
export function splitFrames(buf) {
|
|
104
|
+
const firstMagic = buf.indexOf(MAGIC, 0);
|
|
105
|
+
if (firstMagic < 0) throw new Error('not a zstd session log: frame magic 28 B5 2F FD not found');
|
|
106
|
+
if (firstMagic !== 0) throw new Error(`corrupt session log: ${firstMagic} stray bytes before the first frame`);
|
|
107
|
+
|
|
108
|
+
const frames = [];
|
|
109
|
+
let cursor = 0;
|
|
110
|
+
while (cursor < buf.length) {
|
|
111
|
+
const end = zstdFrameLength(buf, cursor);
|
|
112
|
+
try {
|
|
113
|
+
decompressFrame(buf.subarray(cursor, end));
|
|
114
|
+
} catch (error) {
|
|
115
|
+
throw new Error(`corrupt session log: zstd frame ${frames.length} at byte ${cursor} ` +
|
|
116
|
+
`(${end - cursor} bytes) does not decompress: ${error.message}`);
|
|
117
|
+
}
|
|
118
|
+
frames.push({ start: cursor, end, bytes: end - cursor });
|
|
119
|
+
cursor = end;
|
|
120
|
+
}
|
|
121
|
+
return frames;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Read + decompress + parse a session log buffer. */
|
|
125
|
+
export function parseSession(buf) {
|
|
126
|
+
const frames = splitFrames(buf);
|
|
127
|
+
const texts = frames.map((f) => decompressFrame(buf.subarray(f.start, f.end)));
|
|
128
|
+
const text = texts.join('');
|
|
129
|
+
const lines = text.split('\n').filter((line) => line.length > 0);
|
|
130
|
+
if (lines.length === 0) throw new Error('corrupt session log: empty');
|
|
131
|
+
let header;
|
|
132
|
+
let events;
|
|
133
|
+
try {
|
|
134
|
+
header = JSON.parse(lines[0]);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
throw new Error(`corrupt session log: first frame is not a JSON header (${error.message})`);
|
|
137
|
+
}
|
|
138
|
+
if (header.type !== 'session') throw new Error('corrupt session log: the first line is not a session header');
|
|
139
|
+
if (header.version !== HEADER_VERSION) {
|
|
140
|
+
throw new Error(`unsupported session format: header version ${header.version}, this plugin supports v${HEADER_VERSION}`);
|
|
141
|
+
}
|
|
142
|
+
events = lines.slice(1).map((line, index) => {
|
|
143
|
+
try {
|
|
144
|
+
return JSON.parse(line);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
throw new Error(`corrupt session log: event line ${index + 2} is not JSON (${error.message})`);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
assertContiguous(events);
|
|
150
|
+
return { frames, texts, header, events, bytes: buf.length };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Every event must satisfy `seq === array index`. */
|
|
154
|
+
export function assertContiguous(events) {
|
|
155
|
+
for (let i = 0; i < events.length; i += 1) {
|
|
156
|
+
if (events[i].seq !== i) {
|
|
157
|
+
throw new Error(`corrupt session log: event at index ${i} has seq ${events[i].seq} (expected ${i}); seq must be contiguous from 0`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Serialize a session the way the host does: one header frame, then chunks.
|
|
164
|
+
* `eventsPerFrame` only affects size/IO, never semantics.
|
|
165
|
+
*/
|
|
166
|
+
export function encodeSession(header, events, { eventsPerFrame = 2000 } = {}) {
|
|
167
|
+
assertContiguous(events);
|
|
168
|
+
const out = [];
|
|
169
|
+
out.push(compressFrame(JSON.stringify(header) + '\n'));
|
|
170
|
+
for (let i = 0; i < events.length; i += eventsPerFrame) {
|
|
171
|
+
const chunk = events.slice(i, i + eventsPerFrame).map((e) => JSON.stringify(e) + '\n').join('');
|
|
172
|
+
out.push(compressFrame(chunk));
|
|
173
|
+
}
|
|
174
|
+
return Buffer.concat(out);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Deterministic JSON: sorted keys, so hashes do not depend on key order. */
|
|
178
|
+
export function stableStringify(value) {
|
|
179
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
180
|
+
if (Array.isArray(value)) return `[${value.map((v) => stableStringify(v)).join(',')}]`;
|
|
181
|
+
const keys = Object.keys(value).sort();
|
|
182
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** sha256 of a buffer, hex. */
|
|
186
|
+
export function sha256(buf) {
|
|
187
|
+
return crypto.createHash('sha256').update(buf).digest('hex');
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const VOLATILE_KEYS = new Set([
|
|
191
|
+
'seq', 'turn', 'step', 'time', 'surfaceOp',
|
|
192
|
+
'startSeq', 'endSeq', 'start', 'end',
|
|
193
|
+
'sourceEventSeqs', 'shadowedSeqs', 'shadowedRange', 'shadowedTokenCount',
|
|
194
|
+
'messageSeqs', 'headerSeq', 'sourceEventSeq', 'throughSeq', 'compactionId',
|
|
195
|
+
]);
|
|
196
|
+
|
|
197
|
+
/** Strip coordinates that legitimately change when seqs/turns are renumbered. */
|
|
198
|
+
function projectValue(value) {
|
|
199
|
+
if (Array.isArray(value)) return value.map(projectValue);
|
|
200
|
+
if (value === null || typeof value !== 'object') return value;
|
|
201
|
+
const out = {};
|
|
202
|
+
for (const key of Object.keys(value)) {
|
|
203
|
+
if (VOLATILE_KEYS.has(key)) continue;
|
|
204
|
+
out[key] = projectValue(value[key]);
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Types that can appear in the model-visible message list. */
|
|
210
|
+
export const MESSAGE_TYPES = new Set([
|
|
211
|
+
'system/message', 'developer/message', 'user/message', 'assistant/message', 'tool/result',
|
|
212
|
+
]);
|
|
213
|
+
|
|
214
|
+
function rangeOf(surfaceOp) {
|
|
215
|
+
if (!surfaceOp || typeof surfaceOp !== 'object') return null;
|
|
216
|
+
const start = surfaceOp.startSeq ?? surfaceOp.start;
|
|
217
|
+
const end = surfaceOp.endSeq ?? surfaceOp.end;
|
|
218
|
+
if (typeof start !== 'number' || typeof end !== 'number') return null;
|
|
219
|
+
return { start, end };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Fold the event log into the Surface (append / replace), mirroring the
|
|
224
|
+
* host's `foldSurface`.
|
|
225
|
+
*
|
|
226
|
+
* A replace names its span by SURFACE POSITION, not by numeric seq order: the
|
|
227
|
+
* replacement node takes the first node's position, so after an earlier
|
|
228
|
+
* replacement the declared `start` seq can be greater than `end`
|
|
229
|
+
* (`CompactionResult.shadowedRange` documents exactly that). Resolving both
|
|
230
|
+
* edges positionally — instead of testing `start <= seq <= end` — is what keeps
|
|
231
|
+
* a second cut from leaving the previous pointer visible.
|
|
232
|
+
*
|
|
233
|
+
* Returns nodes in surface order: [{ seq, type, event }].
|
|
234
|
+
*/
|
|
235
|
+
export function foldSurface(events) {
|
|
236
|
+
const nodes = [];
|
|
237
|
+
for (const event of events) {
|
|
238
|
+
const op = event.surfaceOp;
|
|
239
|
+
if (op === 'append') {
|
|
240
|
+
nodes.push({ seq: event.seq, type: event.type, event });
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const range = rangeOf(op);
|
|
244
|
+
if (!range) continue; // log-only events (no surfaceOp) never enter the Surface
|
|
245
|
+
const startIndex = nodes.findIndex((node) => node.seq === range.start);
|
|
246
|
+
const endIndex = nodes.findIndex((node) => node.seq === range.end);
|
|
247
|
+
if (startIndex < 0 || endIndex < startIndex) continue;
|
|
248
|
+
nodes.splice(startIndex, endIndex - startIndex + 1, { seq: event.seq, type: event.type, event });
|
|
249
|
+
}
|
|
250
|
+
return nodes;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Digest of the model-visible messages implied by this log.
|
|
255
|
+
*
|
|
256
|
+
* This is the plugin's deterministic stand-in for the host's deriveMessages:
|
|
257
|
+
* fold the Surface, keep message-like nodes, project out coordinates that are
|
|
258
|
+
* allowed to change on truncation (seq / turn / step / references), and hash
|
|
259
|
+
* the rest. Two logs with the same visible conversation hash the same.
|
|
260
|
+
*/
|
|
261
|
+
export function deriveMessagesDigest(header, events) {
|
|
262
|
+
const nodes = foldSurface(events).filter((node) => MESSAGE_TYPES.has(node.type));
|
|
263
|
+
const projected = nodes.map((node) => ({
|
|
264
|
+
type: node.type,
|
|
265
|
+
data: projectValue(node.event.data ?? {}),
|
|
266
|
+
}));
|
|
267
|
+
const text = stableStringify(projected);
|
|
268
|
+
return { count: projected.length, chars: text.length, sha256: sha256(Buffer.from(text, 'utf8')) };
|
|
269
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Binding of the host-free cut core to the real compaction seam.
|
|
2
|
+
//
|
|
3
|
+
// This module is imported by `entry.js` inside a try/catch. Only the compaction
|
|
4
|
+
// package is required; `createUserMessage` is optional because engine-core.js
|
|
5
|
+
// has an equivalent fallback. The two module ids can be redirected by env for
|
|
6
|
+
// the mock-host suite (the same seam dsh-live-compact uses for its failure
|
|
7
|
+
// drills); production never sets them.
|
|
8
|
+
|
|
9
|
+
import { createCutEngine } from './engine-core.js';
|
|
10
|
+
|
|
11
|
+
const compactionId = process.env.DSH_HOT_TRUNCATE_HOST_COMPACTION || '@deepseek-ai/dsh-compaction';
|
|
12
|
+
const llmId = process.env.DSH_HOT_TRUNCATE_HOST_LLM || '@deepseek-ai/dsh-llm';
|
|
13
|
+
|
|
14
|
+
const host = await import(compactionId);
|
|
15
|
+
const CompactionEngine = host.CompactionEngine ?? host.default;
|
|
16
|
+
if (typeof CompactionEngine !== 'function') {
|
|
17
|
+
throw new Error(`hot-truncate: ${compactionId} exports no CompactionEngine`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
let createUserMessage = null;
|
|
21
|
+
let contextOverflowCode = null;
|
|
22
|
+
try {
|
|
23
|
+
const llm = await import(llmId);
|
|
24
|
+
createUserMessage = llm.createUserMessage ?? null;
|
|
25
|
+
contextOverflowCode = llm.CONTEXT_WINDOW_EXCEEDED_CODE ?? null;
|
|
26
|
+
} catch {
|
|
27
|
+
// Optional: engine-core falls back to an identified frozen message object
|
|
28
|
+
// and the documented literal failure code.
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const HotTruncateEngine = createCutEngine({
|
|
32
|
+
CompactionEngine,
|
|
33
|
+
CompactionId: host.CompactionId,
|
|
34
|
+
ManualCompactionError: host.ManualCompactionError,
|
|
35
|
+
compactCheckpointSource: host.compactCheckpointSource,
|
|
36
|
+
isCompactCheckpointSource: host.isCompactCheckpointSource,
|
|
37
|
+
toolPairingBalancedBefore: host.toolPairingBalancedBefore,
|
|
38
|
+
toolPairingBalancedAfter: host.toolPairingBalancedAfter,
|
|
39
|
+
...(contextOverflowCode === null ? {} : { contextOverflowCode }),
|
|
40
|
+
createUserMessage: createUserMessage ?? undefined,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
export default HotTruncateEngine;
|
|
44
|
+
export { HotTruncateEngine };
|