@sriinnu/fiche 0.0.0-stage → 0.19.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 +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +288 -2
- package/SECURITY.md +53 -0
- package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
- package/assets/SPLEEN_LICENSE.txt +24 -0
- package/assets/UNIFONT_LICENSE.txt +476 -0
- package/assets/fiche-logo-dark.svg +61 -0
- package/assets/fiche-logo-light.svg +61 -0
- package/assets/fiche-logo.svg +71 -0
- package/assets/fiche-mark.svg +48 -0
- package/bin/cli.js +7 -0
- package/bin/mcp.js +8 -0
- package/dist/calibrate.d.ts +30 -0
- package/dist/calibrate.js +588 -0
- package/dist/core/anthropic-vision.d.ts +28 -0
- package/dist/core/anthropic-vision.js +34 -0
- package/dist/core/applicability.d.ts +63 -0
- package/dist/core/applicability.js +151 -0
- package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono10.js +64 -0
- package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono12.js +64 -0
- package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono14.js +64 -0
- package/dist/core/atlas-gray.d.ts +26 -0
- package/dist/core/atlas-gray.js +64 -0
- package/dist/core/atlas-jbmono10.d.ts +34 -0
- package/dist/core/atlas-jbmono10.js +71 -0
- package/dist/core/atlas-jbmono12.d.ts +34 -0
- package/dist/core/atlas-jbmono12.js +71 -0
- package/dist/core/atlas-jbmono14.d.ts +34 -0
- package/dist/core/atlas-jbmono14.js +71 -0
- package/dist/core/atlas.d.ts +34 -0
- package/dist/core/atlas.js +71 -0
- package/dist/core/baseline.d.ts +121 -0
- package/dist/core/baseline.js +200 -0
- package/dist/core/calibration.d.ts +86 -0
- package/dist/core/calibration.js +547 -0
- package/dist/core/casi-delta.d.ts +63 -0
- package/dist/core/casi-delta.js +1271 -0
- package/dist/core/claude-model-profiles.d.ts +53 -0
- package/dist/core/claude-model-profiles.js +160 -0
- package/dist/core/client-tool-round.d.ts +31 -0
- package/dist/core/client-tool-round.js +58 -0
- package/dist/core/codex-cache.d.ts +20 -0
- package/dist/core/codex-cache.js +59 -0
- package/dist/core/context-mmu.d.ts +350 -0
- package/dist/core/context-mmu.js +3028 -0
- package/dist/core/cpt-fit.d.ts +70 -0
- package/dist/core/cpt-fit.js +197 -0
- package/dist/core/env.d.ts +8 -0
- package/dist/core/env.js +15 -0
- package/dist/core/export.d.ts +127 -0
- package/dist/core/export.js +385 -0
- package/dist/core/factsheet.d.ts +77 -0
- package/dist/core/factsheet.js +494 -0
- package/dist/core/gemini-model-profiles.d.ts +20 -0
- package/dist/core/gemini-model-profiles.js +134 -0
- package/dist/core/google.d.ts +76 -0
- package/dist/core/google.js +1380 -0
- package/dist/core/gpt-model-profiles.d.ts +218 -0
- package/dist/core/gpt-model-profiles.js +570 -0
- package/dist/core/gpt-tokens.d.ts +14 -0
- package/dist/core/gpt-tokens.js +165 -0
- package/dist/core/history.d.ts +197 -0
- package/dist/core/history.js +1003 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/library.d.ts +80 -0
- package/dist/core/library.js +131 -0
- package/dist/core/measurement.d.ts +34 -0
- package/dist/core/measurement.js +280 -0
- package/dist/core/messages-chat-bridge.d.ts +23 -0
- package/dist/core/messages-chat-bridge.js +747 -0
- package/dist/core/messages-responses-bridge.d.ts +11 -0
- package/dist/core/messages-responses-bridge.js +893 -0
- package/dist/core/openai-history.d.ts +184 -0
- package/dist/core/openai-history.js +1279 -0
- package/dist/core/openai-savings.d.ts +57 -0
- package/dist/core/openai-savings.js +116 -0
- package/dist/core/openai.d.ts +68 -0
- package/dist/core/openai.js +2523 -0
- package/dist/core/pin.d.ts +199 -0
- package/dist/core/pin.js +1353 -0
- package/dist/core/png.d.ts +14 -0
- package/dist/core/png.js +188 -0
- package/dist/core/prefix-tape.d.ts +102 -0
- package/dist/core/prefix-tape.js +315 -0
- package/dist/core/price-id.d.ts +10 -0
- package/dist/core/price-id.js +26 -0
- package/dist/core/prices.generated.d.ts +36 -0
- package/dist/core/prices.generated.js +369 -0
- package/dist/core/pricing.d.ts +134 -0
- package/dist/core/pricing.js +335 -0
- package/dist/core/profile-base.d.ts +30 -0
- package/dist/core/profile-base.js +67 -0
- package/dist/core/provider-router.d.ts +51 -0
- package/dist/core/provider-router.js +121 -0
- package/dist/core/proxy.d.ts +252 -0
- package/dist/core/proxy.js +2929 -0
- package/dist/core/reader-tier.d.ts +24 -0
- package/dist/core/reader-tier.js +118 -0
- package/dist/core/render.d.ts +280 -0
- package/dist/core/render.js +1302 -0
- package/dist/core/request-guard.d.ts +31 -0
- package/dist/core/request-guard.js +126 -0
- package/dist/core/request-transform.d.ts +43 -0
- package/dist/core/request-transform.js +173 -0
- package/dist/core/schema-compiler.d.ts +64 -0
- package/dist/core/schema-compiler.js +1696 -0
- package/dist/core/schema-strip.d.ts +29 -0
- package/dist/core/schema-strip.js +173 -0
- package/dist/core/session-state.d.ts +219 -0
- package/dist/core/session-state.js +929 -0
- package/dist/core/stage-plugins.d.ts +45 -0
- package/dist/core/stage-plugins.js +205 -0
- package/dist/core/text-history.d.ts +74 -0
- package/dist/core/text-history.js +612 -0
- package/dist/core/text-hygiene.d.ts +160 -0
- package/dist/core/text-hygiene.js +2259 -0
- package/dist/core/toon.d.ts +29 -0
- package/dist/core/toon.js +425 -0
- package/dist/core/tracker.d.ts +223 -0
- package/dist/core/tracker.js +290 -0
- package/dist/core/transform.d.ts +589 -0
- package/dist/core/transform.js +3153 -0
- package/dist/core/types.d.ts +87 -0
- package/dist/core/types.js +8 -0
- package/dist/core/upstream-hosts.d.ts +127 -0
- package/dist/core/upstream-hosts.js +398 -0
- package/dist/core/vision-cost.d.ts +63 -0
- package/dist/core/vision-cost.js +137 -0
- package/dist/dashboard/fragments.d.ts +87 -0
- package/dist/dashboard/fragments.js +1515 -0
- package/dist/dashboard/types.d.ts +217 -0
- package/dist/dashboard/types.js +3 -0
- package/dist/dashboard/vendor.d.ts +3 -0
- package/dist/dashboard/vendor.js +6 -0
- package/dist/dashboard.d.ts +372 -0
- package/dist/dashboard.js +2731 -0
- package/dist/export-collect.d.ts +36 -0
- package/dist/export-collect.js +59 -0
- package/dist/file-tracker.d.ts +42 -0
- package/dist/file-tracker.js +234 -0
- package/dist/kosha-sync.d.ts +74 -0
- package/dist/kosha-sync.js +272 -0
- package/dist/launchd-socket.d.ts +22 -0
- package/dist/launchd-socket.js +210 -0
- package/dist/mcp/cli.d.ts +2 -0
- package/dist/mcp/cli.js +55 -0
- package/dist/mcp/server.d.ts +48 -0
- package/dist/mcp/server.js +987 -0
- package/dist/mmu-store.d.ts +31 -0
- package/dist/mmu-store.js +179 -0
- package/dist/node-fetch.d.ts +22 -0
- package/dist/node-fetch.js +489 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +244396 -0
- package/dist/request-decoding.d.ts +30 -0
- package/dist/request-decoding.js +85 -0
- package/dist/sessions.d.ts +179 -0
- package/dist/sessions.js +837 -0
- package/dist/stats.d.ts +114 -0
- package/dist/stats.js +439 -0
- package/dist/turn-report.d.ts +65 -0
- package/dist/turn-report.js +724 -0
- package/dist/warp/app-launch.d.ts +26 -0
- package/dist/warp/app-launch.js +155 -0
- package/dist/warp/ca.d.ts +74 -0
- package/dist/warp/ca.js +416 -0
- package/dist/warp/connect.d.ts +42 -0
- package/dist/warp/connect.js +686 -0
- package/dist/warp/der.d.ts +57 -0
- package/dist/warp/der.js +151 -0
- package/dist/warp/index.d.ts +79 -0
- package/dist/warp/index.js +650 -0
- package/dist/warp/resolve.d.ts +12 -0
- package/dist/warp/resolve.js +49 -0
- package/dist/warp/route.d.ts +71 -0
- package/dist/warp/route.js +134 -0
- package/dist/worker.d.ts +71 -0
- package/dist/worker.js +174 -0
- package/docs/SECURITY_MODEL.md +84 -0
- package/package.json +122 -4
- package/plugins/fiche-companion/README.md +42 -0
- package/plugins/fiche-companion/assets/logo.svg +48 -0
- package/plugins/fiche-companion/hooks.json +11 -0
- package/plugins/fiche-companion/mcp_config.json +8 -0
- package/plugins/fiche-companion/plugin.json +18 -0
- package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
- package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
- package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
- package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-session cache-liveness state for the history collapse.
|
|
3
|
+
*
|
|
4
|
+
* ## Why this exists
|
|
5
|
+
*
|
|
6
|
+
* The history grid is append-only: chunk N's pixels are a pure function of its
|
|
7
|
+
* message range, so old chunks stay byte-identical as the conversation grows and
|
|
8
|
+
* ride Anthropic's prompt cache as `cache_read` forever. That freeze is worth a
|
|
9
|
+
* lot — but only while a cache actually exists. Where there is none, the freeze
|
|
10
|
+
* protects nothing and the grid is free to be re-cut for *density* instead:
|
|
11
|
+
* {@link HistoryCollapseOptions.packFill} raises the freeze step until the pages
|
|
12
|
+
* are nearly full, which roughly halves image tokens on long sessions of short
|
|
13
|
+
* turns (#161: 317 images at 43% fill).
|
|
14
|
+
*
|
|
15
|
+
* ## How we know whether a cache exists
|
|
16
|
+
*
|
|
17
|
+
* The provider tells us, and that beats inferring it. {@link noteCacheOutcome}
|
|
18
|
+
* feeds each response's accounting back in: a `cache_read` proves the prefix was
|
|
19
|
+
* live, a `cache_create` proves one was just written. Only when both are zero is
|
|
20
|
+
* there nothing to lose by re-cutting.
|
|
21
|
+
*
|
|
22
|
+
* This module used to decide from the wall clock alone, treating any gap past the
|
|
23
|
+
* ephemeral 5-minute TTL as cold. That was wrong most of the times it fired —
|
|
24
|
+
* measured over 143 gaps on a production host, the cache was still warm in 66% of
|
|
25
|
+
* gaps past 5.5 minutes, 40% past 15 minutes, 13% past an hour. Claude Code marks
|
|
26
|
+
* some blocks with the 1-hour TTL, so the short constant never described this
|
|
27
|
+
* traffic. The worst case was a session repacked three times in one hour on
|
|
28
|
+
* ~10-minute gaps, each repack re-keying the whole prefix — and each preceded by a
|
|
29
|
+
* turn that had just *written* a cache, which the clock could not see.
|
|
30
|
+
*
|
|
31
|
+
* The clock survives only as a backstop for responses whose accounting never
|
|
32
|
+
* arrived: {@link COLD_HORIZON_MS}. And a rejected request still marks the session
|
|
33
|
+
* dead outright ({@link markCacheDead}) — but only a 413 or a too-long 400, not
|
|
34
|
+
* a transient 5xx: see {@link responseLeftNoCache}.
|
|
35
|
+
*
|
|
36
|
+
* ## Why the step is sticky
|
|
37
|
+
*
|
|
38
|
+
* Once a session has been repacked coarse, every later turn must keep at least
|
|
39
|
+
* that step. Falling back to the fine grid would re-cut the same messages into
|
|
40
|
+
* different chunks — every chunk's bytes change, and the whole history re-keys as
|
|
41
|
+
* `cache_create`. {@link recordFreezeStep} pins the floor; the collapse only ever
|
|
42
|
+
* doubles it.
|
|
43
|
+
*
|
|
44
|
+
* ## Why the state survives a restart
|
|
45
|
+
*
|
|
46
|
+
* The map lives in this process. A restart used to lose it, and the module
|
|
47
|
+
* called that an accepted failure mode: an unknown session is treated as WARM
|
|
48
|
+
* (no repack), so at worst we keep paying the old image count. That covers
|
|
49
|
+
* `cold`, but not the floor. {@link recordFreezeStep} exists because a render at
|
|
50
|
+
* a finer grid than the session was last frozen at re-keys every chunk (see
|
|
51
|
+
* above), and after a restart the floor is 0 again: the next collapse is free to
|
|
52
|
+
* pick a finer step than the one the cache was built on, and whether it does
|
|
53
|
+
* depends on that request's image budget — exactly what the pin was added to
|
|
54
|
+
* stop mattering.
|
|
55
|
+
*
|
|
56
|
+
* So the host may attach a {@link SessionStateStore}. Every mutation schedules a
|
|
57
|
+
* debounced save ({@link PERSIST_DEBOUNCE_MS}); the record shape on disk is the
|
|
58
|
+
* in-memory record plus its key. On configure the file is read back and records
|
|
59
|
+
* idle for more than {@link PERSIST_MAX_IDLE_MS} are dropped — past the cold
|
|
60
|
+
* horizon the clock already declares them cold, so nothing they pin is protecting
|
|
61
|
+
* a live cache. Records already in memory win over the file. The core never
|
|
62
|
+
* touches a filesystem: without a store the module behaves exactly as before.
|
|
63
|
+
*/
|
|
64
|
+
/** Default sessions tracked before the oldest is evicted. One small record each. */
|
|
65
|
+
const DEFAULT_SESSIONS_MAX = 512;
|
|
66
|
+
const MIN_SESSIONS_MAX = 64;
|
|
67
|
+
const MAX_SESSIONS_MAX = 8192;
|
|
68
|
+
let maxSessions = DEFAULT_SESSIONS_MAX;
|
|
69
|
+
/**
|
|
70
|
+
* Grace added to the provider TTL before we call a cache dead. Our clock is the
|
|
71
|
+
* request-arrival time, the provider's is its own; a request that lands one
|
|
72
|
+
* second inside the window can still miss. Only gaps clearly past the TTL flip
|
|
73
|
+
* the session cold, so a borderline case keeps the (cheap, correct) warm path.
|
|
74
|
+
*/
|
|
75
|
+
const COLD_GRACE_MS = 30_000;
|
|
76
|
+
/**
|
|
77
|
+
* Idle gap past which we treat an unobserved cache as gone.
|
|
78
|
+
*
|
|
79
|
+
* Not the ephemeral-tier TTL (`CACHE_TTL_SEC`, 5 minutes). Using that here declared sessions cold while their caches were
|
|
80
|
+
* demonstrably alive: 66% of gaps past 5.5 minutes still cache-read, 40% past
|
|
81
|
+
* 15 minutes, 13% past an hour (143 gaps, one production host). Claude Code marks
|
|
82
|
+
* some blocks with the 1-hour TTL, so the short constant never described this
|
|
83
|
+
* traffic.
|
|
84
|
+
*
|
|
85
|
+
* An hour plus the grace is where the evidence turns: past it, warmth is the
|
|
86
|
+
* exception. This is only a backstop anyway — {@link noteCacheOutcome} answers
|
|
87
|
+
* from the provider's own accounting whenever a response has been seen.
|
|
88
|
+
*/
|
|
89
|
+
const COLD_HORIZON_MS = 3_600_000 + COLD_GRACE_MS;
|
|
90
|
+
/** On-disk format tag. Bump when a field changes meaning; older files are ignored. */
|
|
91
|
+
const PERSIST_FORMAT = 1;
|
|
92
|
+
/**
|
|
93
|
+
* Records idle longer than this are not persisted and not restored. Well past
|
|
94
|
+
* {@link COLD_HORIZON_MS}, where the clock alone already declares the session
|
|
95
|
+
* cold and a repack is free — a pin that old protects nothing. 24 hours.
|
|
96
|
+
*/
|
|
97
|
+
const PERSIST_MAX_IDLE_MS = 24 * 3_600_000;
|
|
98
|
+
/**
|
|
99
|
+
* Coalesce saves. Every request touches `lastSeenMs`, and a Claude Code turn can
|
|
100
|
+
* be several requests in a burst; one write per burst is plenty. Short enough
|
|
101
|
+
* that a supervisor hard-kill (no signal on Windows) loses at most this window
|
|
102
|
+
* of clock updates — never a pin recorded on an earlier turn.
|
|
103
|
+
*/
|
|
104
|
+
const PERSIST_DEBOUNCE_MS = 250;
|
|
105
|
+
/** Maximum sealed epoch keys retained per session (head-retaining cap so epoch_0 is never evicted). */
|
|
106
|
+
const SEALED_EPOCH_KEYS_MAX = 512;
|
|
107
|
+
/** Maximum pinned skill names retained per session. */
|
|
108
|
+
const PINNED_SKILLS_MAX = 32;
|
|
109
|
+
/** Maximum persisted folded Markovian episode IDs per session. */
|
|
110
|
+
const FOLDED_EPISODE_IDS_MAX = 256;
|
|
111
|
+
/** Maximum per-session liveness scopes retained (e.g. opus vs haiku vs systemSha8). */
|
|
112
|
+
const LIVENESS_SCOPES_MAX = 16;
|
|
113
|
+
const sessions = new Map();
|
|
114
|
+
function touch(key) {
|
|
115
|
+
const existing = sessions.get(key);
|
|
116
|
+
if (existing) {
|
|
117
|
+
sessions.delete(key); // refresh LRU position
|
|
118
|
+
sessions.set(key, existing);
|
|
119
|
+
return existing;
|
|
120
|
+
}
|
|
121
|
+
const fresh = { lastSeenMs: 0, freezeStep: 0, cacheDead: false };
|
|
122
|
+
sessions.set(key, fresh);
|
|
123
|
+
evictToCapacity();
|
|
124
|
+
return fresh;
|
|
125
|
+
}
|
|
126
|
+
function evictToCapacity() {
|
|
127
|
+
while (sessions.size > maxSessions) {
|
|
128
|
+
const oldest = sessions.keys().next().value;
|
|
129
|
+
if (oldest === undefined)
|
|
130
|
+
break;
|
|
131
|
+
sessions.delete(oldest);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Configure the maximum tracked sessions kept in RAM (clamped to `[64, 8192]`),
|
|
136
|
+
* evicting oldest entries immediately if capacity shrinks.
|
|
137
|
+
*/
|
|
138
|
+
export function configureMaxSessions(limit) {
|
|
139
|
+
if (limit !== undefined && Number.isFinite(limit)) {
|
|
140
|
+
maxSessions = Math.min(MAX_SESSIONS_MAX, Math.max(MIN_SESSIONS_MAX, Math.floor(limit)));
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
maxSessions = DEFAULT_SESSIONS_MAX;
|
|
144
|
+
}
|
|
145
|
+
evictToCapacity();
|
|
146
|
+
return maxSessions;
|
|
147
|
+
}
|
|
148
|
+
/** Current maximum tracked session count. */
|
|
149
|
+
export function getMaxSessions() {
|
|
150
|
+
return maxSessions;
|
|
151
|
+
}
|
|
152
|
+
let store;
|
|
153
|
+
let saveTimer;
|
|
154
|
+
let dirty = false;
|
|
155
|
+
/**
|
|
156
|
+
* Attach (or with `undefined`, detach) the store and restore what it holds.
|
|
157
|
+
* Flushes pending changes to the previous store first. Returns how many
|
|
158
|
+
* sessions were restored. Never throws: a store that cannot be read leaves the
|
|
159
|
+
* map as it was — the pre-persistence behaviour, which is safe (unknown = warm).
|
|
160
|
+
*/
|
|
161
|
+
export function configureSessionStateStore(next, nowMs = Date.now()) {
|
|
162
|
+
flushSessionState();
|
|
163
|
+
store = next;
|
|
164
|
+
if (!next)
|
|
165
|
+
return 0;
|
|
166
|
+
let text;
|
|
167
|
+
try {
|
|
168
|
+
text = next.load();
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
return restoreSessionState(text, nowMs);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Merge a serialized snapshot into the map. Records already in memory win (they
|
|
177
|
+
* are newer by construction); records idle past {@link PERSIST_MAX_IDLE_MS} or
|
|
178
|
+
* malformed in any field are skipped. Returns the number restored.
|
|
179
|
+
*/
|
|
180
|
+
export function restoreSessionState(text, nowMs = Date.now()) {
|
|
181
|
+
if (!text)
|
|
182
|
+
return 0;
|
|
183
|
+
let parsed;
|
|
184
|
+
try {
|
|
185
|
+
parsed = JSON.parse(text);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return 0;
|
|
189
|
+
}
|
|
190
|
+
if (!isPersistedState(parsed))
|
|
191
|
+
return 0;
|
|
192
|
+
let restored = 0;
|
|
193
|
+
for (const entry of parsed.sessions) {
|
|
194
|
+
const rec = validRecord(entry, nowMs);
|
|
195
|
+
if (!rec || sessions.has(entry.key))
|
|
196
|
+
continue;
|
|
197
|
+
sessions.set(entry.key, rec);
|
|
198
|
+
restored++;
|
|
199
|
+
}
|
|
200
|
+
evictToCapacity();
|
|
201
|
+
return restored;
|
|
202
|
+
}
|
|
203
|
+
function isPersistedState(value) {
|
|
204
|
+
if (!value || typeof value !== 'object')
|
|
205
|
+
return false;
|
|
206
|
+
const v = value;
|
|
207
|
+
return v.format === PERSIST_FORMAT && Array.isArray(v.sessions);
|
|
208
|
+
}
|
|
209
|
+
function isBool(v) {
|
|
210
|
+
return typeof v === 'boolean';
|
|
211
|
+
}
|
|
212
|
+
function sanitizeStringArray(raw, maxLen, keepTail) {
|
|
213
|
+
if (!Array.isArray(raw))
|
|
214
|
+
return undefined;
|
|
215
|
+
const deduped = [];
|
|
216
|
+
const seen = new Set();
|
|
217
|
+
for (const item of raw) {
|
|
218
|
+
if (typeof item !== 'string' || item === '')
|
|
219
|
+
continue;
|
|
220
|
+
if (keepTail) {
|
|
221
|
+
if (seen.has(item)) {
|
|
222
|
+
const idx = deduped.indexOf(item);
|
|
223
|
+
if (idx >= 0)
|
|
224
|
+
deduped.splice(idx, 1);
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
seen.add(item);
|
|
228
|
+
}
|
|
229
|
+
deduped.push(item);
|
|
230
|
+
}
|
|
231
|
+
else if (!seen.has(item)) {
|
|
232
|
+
seen.add(item);
|
|
233
|
+
deduped.push(item);
|
|
234
|
+
if (deduped.length >= maxLen)
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (deduped.length === 0)
|
|
239
|
+
return undefined;
|
|
240
|
+
return keepTail && deduped.length > maxLen ? deduped.slice(-maxLen) : deduped;
|
|
241
|
+
}
|
|
242
|
+
function validRecord(entry, nowMs) {
|
|
243
|
+
if (!entry || typeof entry !== 'object')
|
|
244
|
+
return undefined;
|
|
245
|
+
const e = entry;
|
|
246
|
+
if (typeof e.key !== 'string' || e.key === '')
|
|
247
|
+
return undefined;
|
|
248
|
+
if (typeof e.lastSeenMs !== 'number' || !Number.isFinite(e.lastSeenMs) || e.lastSeenMs <= 0)
|
|
249
|
+
return undefined;
|
|
250
|
+
if (nowMs - e.lastSeenMs > PERSIST_MAX_IDLE_MS)
|
|
251
|
+
return undefined;
|
|
252
|
+
if (typeof e.freezeStep !== 'number' || !Number.isFinite(e.freezeStep) || e.freezeStep < 0)
|
|
253
|
+
return undefined;
|
|
254
|
+
if (!isBool(e.cacheDead))
|
|
255
|
+
return undefined;
|
|
256
|
+
const rec = { lastSeenMs: e.lastSeenMs, freezeStep: e.freezeStep, cacheDead: e.cacheDead };
|
|
257
|
+
if (isBool(e.lastCacheAlive))
|
|
258
|
+
rec.lastCacheAlive = e.lastCacheAlive;
|
|
259
|
+
if (isBool(e.everCacheAlive))
|
|
260
|
+
rec.everCacheAlive = e.everCacheAlive;
|
|
261
|
+
const sealed = sanitizeStringArray(e.sealedEpochKeys, SEALED_EPOCH_KEYS_MAX, false);
|
|
262
|
+
if (sealed)
|
|
263
|
+
rec.sealedEpochKeys = sealed;
|
|
264
|
+
const stage2Sealed = sanitizeStringArray(e.sealedStage2SlotKeys, SEALED_EPOCH_KEYS_MAX, false);
|
|
265
|
+
if (stage2Sealed)
|
|
266
|
+
rec.sealedStage2SlotKeys = stage2Sealed;
|
|
267
|
+
const skills = sanitizeStringArray(e.pinnedSkills, PINNED_SKILLS_MAX, false);
|
|
268
|
+
if (skills)
|
|
269
|
+
rec.pinnedSkills = skills;
|
|
270
|
+
if (typeof e.pinnedSkillCatalogHash === 'string' && e.pinnedSkillCatalogHash !== '') {
|
|
271
|
+
rec.pinnedSkillCatalogHash = e.pinnedSkillCatalogHash;
|
|
272
|
+
}
|
|
273
|
+
const folded = sanitizeStringArray(e.foldedMarkovEpisodeIds, FOLDED_EPISODE_IDS_MAX, false);
|
|
274
|
+
if (folded)
|
|
275
|
+
rec.foldedMarkovEpisodeIds = folded;
|
|
276
|
+
if (e.foldedMarkovCertificates && typeof e.foldedMarkovCertificates === 'object' && !Array.isArray(e.foldedMarkovCertificates)) {
|
|
277
|
+
const certs = {};
|
|
278
|
+
let count = 0;
|
|
279
|
+
for (const [k, v] of Object.entries(e.foldedMarkovCertificates)) {
|
|
280
|
+
if (typeof k === 'string' && k && typeof v === 'string' && v && count < FOLDED_EPISODE_IDS_MAX) {
|
|
281
|
+
certs[k] = v;
|
|
282
|
+
count++;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (count > 0)
|
|
286
|
+
rec.foldedMarkovCertificates = certs;
|
|
287
|
+
}
|
|
288
|
+
if (e.opticalHistoryPolicy === 'hybrid' || e.opticalHistoryPolicy === 'full') {
|
|
289
|
+
rec.opticalHistoryPolicy = e.opticalHistoryPolicy;
|
|
290
|
+
}
|
|
291
|
+
if (typeof e.primaryScope === 'string' && e.primaryScope) {
|
|
292
|
+
rec.primaryScope = e.primaryScope;
|
|
293
|
+
}
|
|
294
|
+
if (e.livenessScopes && typeof e.livenessScopes === 'object' && !Array.isArray(e.livenessScopes)) {
|
|
295
|
+
const scopes = {};
|
|
296
|
+
let sc = 0;
|
|
297
|
+
for (const [sk, rawScope] of Object.entries(e.livenessScopes)) {
|
|
298
|
+
if (sc >= LIVENESS_SCOPES_MAX || typeof sk !== 'string' || !sk || !rawScope || typeof rawScope !== 'object')
|
|
299
|
+
continue;
|
|
300
|
+
const sr = rawScope;
|
|
301
|
+
if (typeof sr.lastSeenMs !== 'number' || !Number.isFinite(sr.lastSeenMs) || sr.lastSeenMs < 0 ||
|
|
302
|
+
typeof sr.freezeStep !== 'number' || !Number.isFinite(sr.freezeStep) || sr.freezeStep < 0 ||
|
|
303
|
+
!isBool(sr.cacheDead)) {
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const cleanScope = {
|
|
307
|
+
lastSeenMs: sr.lastSeenMs,
|
|
308
|
+
freezeStep: sr.freezeStep,
|
|
309
|
+
cacheDead: sr.cacheDead,
|
|
310
|
+
};
|
|
311
|
+
if (isBool(sr.lastCacheAlive))
|
|
312
|
+
cleanScope.lastCacheAlive = sr.lastCacheAlive;
|
|
313
|
+
if (isBool(sr.everCacheAlive))
|
|
314
|
+
cleanScope.everCacheAlive = sr.everCacheAlive;
|
|
315
|
+
if (sr.opticalHistoryPolicy === 'hybrid' || sr.opticalHistoryPolicy === 'full') {
|
|
316
|
+
cleanScope.opticalHistoryPolicy = sr.opticalHistoryPolicy;
|
|
317
|
+
}
|
|
318
|
+
scopes[sk] = cleanScope;
|
|
319
|
+
sc++;
|
|
320
|
+
}
|
|
321
|
+
if (sc > 0)
|
|
322
|
+
rec.livenessScopes = scopes;
|
|
323
|
+
}
|
|
324
|
+
return rec;
|
|
325
|
+
}
|
|
326
|
+
/** The map as JSON, oldest session first (LRU order), stale records omitted. */
|
|
327
|
+
export function serializeSessionState(nowMs = Date.now()) {
|
|
328
|
+
const out = [];
|
|
329
|
+
for (const [key, rec] of sessions) {
|
|
330
|
+
if (rec.lastSeenMs <= 0 || nowMs - rec.lastSeenMs > PERSIST_MAX_IDLE_MS)
|
|
331
|
+
continue;
|
|
332
|
+
const item = {
|
|
333
|
+
key,
|
|
334
|
+
lastSeenMs: rec.lastSeenMs,
|
|
335
|
+
freezeStep: rec.freezeStep,
|
|
336
|
+
cacheDead: rec.cacheDead,
|
|
337
|
+
};
|
|
338
|
+
if (rec.lastCacheAlive !== undefined)
|
|
339
|
+
item.lastCacheAlive = rec.lastCacheAlive;
|
|
340
|
+
if (rec.everCacheAlive !== undefined)
|
|
341
|
+
item.everCacheAlive = rec.everCacheAlive;
|
|
342
|
+
if (rec.opticalHistoryPolicy !== undefined)
|
|
343
|
+
item.opticalHistoryPolicy = rec.opticalHistoryPolicy;
|
|
344
|
+
if (rec.primaryScope !== undefined)
|
|
345
|
+
item.primaryScope = rec.primaryScope;
|
|
346
|
+
if (rec.livenessScopes) {
|
|
347
|
+
const persistedScopes = {};
|
|
348
|
+
let sc = 0;
|
|
349
|
+
for (const [sk, sr] of Object.entries(rec.livenessScopes)) {
|
|
350
|
+
if (sc >= LIVENESS_SCOPES_MAX)
|
|
351
|
+
break;
|
|
352
|
+
persistedScopes[sk] = {
|
|
353
|
+
lastSeenMs: sr.lastSeenMs,
|
|
354
|
+
freezeStep: sr.freezeStep,
|
|
355
|
+
cacheDead: sr.cacheDead,
|
|
356
|
+
...(sr.lastCacheAlive !== undefined ? { lastCacheAlive: sr.lastCacheAlive } : {}),
|
|
357
|
+
...(sr.everCacheAlive !== undefined ? { everCacheAlive: sr.everCacheAlive } : {}),
|
|
358
|
+
...(sr.opticalHistoryPolicy !== undefined ? { opticalHistoryPolicy: sr.opticalHistoryPolicy } : {}),
|
|
359
|
+
};
|
|
360
|
+
sc++;
|
|
361
|
+
}
|
|
362
|
+
if (sc > 0)
|
|
363
|
+
item.livenessScopes = persistedScopes;
|
|
364
|
+
}
|
|
365
|
+
if (rec.sealedEpochKeys && rec.sealedEpochKeys.length > 0) {
|
|
366
|
+
item.sealedEpochKeys = rec.sealedEpochKeys.slice(0, SEALED_EPOCH_KEYS_MAX);
|
|
367
|
+
}
|
|
368
|
+
if (rec.sealedStage2SlotKeys && rec.sealedStage2SlotKeys.length > 0) {
|
|
369
|
+
item.sealedStage2SlotKeys = rec.sealedStage2SlotKeys.slice(0, SEALED_EPOCH_KEYS_MAX);
|
|
370
|
+
}
|
|
371
|
+
if (rec.pinnedSkills && rec.pinnedSkills.length > 0) {
|
|
372
|
+
item.pinnedSkills = rec.pinnedSkills.slice(0, PINNED_SKILLS_MAX);
|
|
373
|
+
}
|
|
374
|
+
if (rec.pinnedSkillCatalogHash !== undefined && rec.pinnedSkillCatalogHash !== '') {
|
|
375
|
+
item.pinnedSkillCatalogHash = rec.pinnedSkillCatalogHash;
|
|
376
|
+
}
|
|
377
|
+
if (rec.foldedMarkovEpisodeIds && rec.foldedMarkovEpisodeIds.length > 0) {
|
|
378
|
+
item.foldedMarkovEpisodeIds = rec.foldedMarkovEpisodeIds.slice(0, FOLDED_EPISODE_IDS_MAX);
|
|
379
|
+
}
|
|
380
|
+
if (rec.foldedMarkovCertificates) {
|
|
381
|
+
const certs = {};
|
|
382
|
+
let count = 0;
|
|
383
|
+
for (const [k, v] of Object.entries(rec.foldedMarkovCertificates)) {
|
|
384
|
+
if (count >= FOLDED_EPISODE_IDS_MAX)
|
|
385
|
+
break;
|
|
386
|
+
certs[k] = v;
|
|
387
|
+
count++;
|
|
388
|
+
}
|
|
389
|
+
if (count > 0)
|
|
390
|
+
item.foldedMarkovCertificates = certs;
|
|
391
|
+
}
|
|
392
|
+
out.push(item);
|
|
393
|
+
}
|
|
394
|
+
const state = { format: PERSIST_FORMAT, saved_at_ms: nowMs, sessions: out };
|
|
395
|
+
return JSON.stringify(state);
|
|
396
|
+
}
|
|
397
|
+
function scheduleSave() {
|
|
398
|
+
if (!store)
|
|
399
|
+
return;
|
|
400
|
+
dirty = true;
|
|
401
|
+
if (saveTimer)
|
|
402
|
+
return;
|
|
403
|
+
saveTimer = setTimeout(() => {
|
|
404
|
+
saveTimer = undefined;
|
|
405
|
+
flushSessionState();
|
|
406
|
+
}, PERSIST_DEBOUNCE_MS);
|
|
407
|
+
// Never keep the process alive for a bookkeeping write.
|
|
408
|
+
saveTimer.unref?.();
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Write pending changes now. Returns true when a save happened. Called by the
|
|
412
|
+
* debounce timer, on store change, and by the host on shutdown. A failing store
|
|
413
|
+
* is swallowed: persistence is an optimisation and must never fail a request.
|
|
414
|
+
*/
|
|
415
|
+
export function flushSessionState() {
|
|
416
|
+
if (saveTimer) {
|
|
417
|
+
clearTimeout(saveTimer);
|
|
418
|
+
saveTimer = undefined;
|
|
419
|
+
}
|
|
420
|
+
if (!store || !dirty)
|
|
421
|
+
return false;
|
|
422
|
+
dirty = false;
|
|
423
|
+
try {
|
|
424
|
+
store.save(serializeSessionState());
|
|
425
|
+
return true;
|
|
426
|
+
}
|
|
427
|
+
catch {
|
|
428
|
+
return false;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
/** Neutral answer for callers without a session identity (no fingerprint yet). */
|
|
432
|
+
const UNKNOWN_STATE = { cold: false, minFreezeStep: 0 };
|
|
433
|
+
/** Normalize a model ID to its liveness family so auxiliary Haiku calls never clobber main-thread liveness. */
|
|
434
|
+
export function normalizeSessionModelFamily(model) {
|
|
435
|
+
const raw = (model ?? '').trim().toLowerCase().replace(/\[[^\]]*\]/g, '');
|
|
436
|
+
if (!raw)
|
|
437
|
+
return '';
|
|
438
|
+
const tail = raw.includes('/') ? raw.slice(raw.lastIndexOf('/') + 1) : raw;
|
|
439
|
+
const bare = tail.split('@')[0];
|
|
440
|
+
if (bare.includes('claude') || bare.includes('anthropic')) {
|
|
441
|
+
if (bare.includes('haiku'))
|
|
442
|
+
return 'claude-haiku';
|
|
443
|
+
if (bare.includes('opus'))
|
|
444
|
+
return 'claude-opus';
|
|
445
|
+
if (bare.includes('sonnet'))
|
|
446
|
+
return 'claude-sonnet';
|
|
447
|
+
if (bare.includes('fable'))
|
|
448
|
+
return 'claude-fable';
|
|
449
|
+
return 'claude';
|
|
450
|
+
}
|
|
451
|
+
return bare.replace(/-\d{8}$/, '').replace(/-\d{4}-\d{2}-\d{2}$/, '');
|
|
452
|
+
}
|
|
453
|
+
function resolveScopeKey(opts) {
|
|
454
|
+
if (!opts)
|
|
455
|
+
return undefined;
|
|
456
|
+
if (opts.scope)
|
|
457
|
+
return opts.scope;
|
|
458
|
+
const family = opts.modelFamily ?? (opts.model ? normalizeSessionModelFamily(opts.model) : '');
|
|
459
|
+
if (family && opts.systemSha8)
|
|
460
|
+
return `${family}:${opts.systemSha8}`;
|
|
461
|
+
if (family)
|
|
462
|
+
return family;
|
|
463
|
+
if (opts.systemSha8)
|
|
464
|
+
return opts.systemSha8;
|
|
465
|
+
return undefined;
|
|
466
|
+
}
|
|
467
|
+
function isAuxiliaryScope(scope) {
|
|
468
|
+
return scope !== undefined && (scope === 'claude-haiku' || scope.startsWith('claude-haiku:'));
|
|
469
|
+
}
|
|
470
|
+
function getOrCreateScopeRecord(rec, scope) {
|
|
471
|
+
if (!rec.livenessScopes)
|
|
472
|
+
rec.livenessScopes = {};
|
|
473
|
+
const existing = rec.livenessScopes[scope];
|
|
474
|
+
if (existing)
|
|
475
|
+
return existing;
|
|
476
|
+
const keys = Object.keys(rec.livenessScopes);
|
|
477
|
+
if (keys.length >= LIVENESS_SCOPES_MAX) {
|
|
478
|
+
let oldestKey = keys[0];
|
|
479
|
+
for (const k of keys) {
|
|
480
|
+
if (k !== rec.primaryScope && (oldestKey === rec.primaryScope || rec.livenessScopes[k].lastSeenMs < rec.livenessScopes[oldestKey].lastSeenMs)) {
|
|
481
|
+
oldestKey = k;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
if (oldestKey !== undefined && oldestKey !== rec.primaryScope) {
|
|
485
|
+
delete rec.livenessScopes[oldestKey];
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const fresh = { lastSeenMs: 0, freezeStep: 0, cacheDead: false };
|
|
489
|
+
rec.livenessScopes[scope] = fresh;
|
|
490
|
+
return fresh;
|
|
491
|
+
}
|
|
492
|
+
function computeCold(target, nowMs) {
|
|
493
|
+
const known = target.lastSeenMs > 0;
|
|
494
|
+
const idleMs = nowMs - target.lastSeenMs;
|
|
495
|
+
const serverSaysAlive = target.lastCacheAlive === true;
|
|
496
|
+
const serverSaysGone = target.lastCacheAlive === false && target.everCacheAlive === true;
|
|
497
|
+
const beyondHorizon = known && idleMs > COLD_HORIZON_MS;
|
|
498
|
+
return target.cacheDead || (!serverSaysAlive && (serverSaysGone || beyondHorizon));
|
|
499
|
+
}
|
|
500
|
+
function applyHistoryRequestToTarget(target, nowMs) {
|
|
501
|
+
const cold = computeCold(target, nowMs);
|
|
502
|
+
target.lastSeenMs = nowMs;
|
|
503
|
+
target.cacheDead = false; // consumed: this request gets the repack
|
|
504
|
+
if (cold) {
|
|
505
|
+
target.repackInFlightCount = (target.repackInFlightCount ?? 0) + 1;
|
|
506
|
+
target.repackGeneration = (target.repackGeneration ?? 0) + 1;
|
|
507
|
+
target.lastCacheAlive = undefined;
|
|
508
|
+
}
|
|
509
|
+
return { cold, minFreezeStep: target.freezeStep };
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Record a request for `sessionKey` and report what the history collapse may
|
|
513
|
+
* assume about the upstream cache. Call once per transformed request, BEFORE the
|
|
514
|
+
* collapse runs; it advances the session's last-seen clock.
|
|
515
|
+
*
|
|
516
|
+
* A session we have never seen counts as warm (see module docs) — unknown must
|
|
517
|
+
* never authorize a repack.
|
|
518
|
+
*/
|
|
519
|
+
export function noteHistoryRequest(sessionKey, nowMsOrOpts = Date.now()) {
|
|
520
|
+
if (!sessionKey)
|
|
521
|
+
return UNKNOWN_STATE;
|
|
522
|
+
const nowMs = typeof nowMsOrOpts === 'number' ? nowMsOrOpts : (nowMsOrOpts.nowMs ?? Date.now());
|
|
523
|
+
const scope = typeof nowMsOrOpts === 'number' ? undefined : resolveScopeKey(nowMsOrOpts);
|
|
524
|
+
const rec = touch(sessionKey);
|
|
525
|
+
if (scope) {
|
|
526
|
+
if (!rec.primaryScope && !isAuxiliaryScope(scope)) {
|
|
527
|
+
rec.primaryScope = scope;
|
|
528
|
+
}
|
|
529
|
+
const scoped = getOrCreateScopeRecord(rec, scope);
|
|
530
|
+
const result = applyHistoryRequestToTarget(scoped, nowMs);
|
|
531
|
+
if (rec.primaryScope === scope || (!rec.primaryScope && !isAuxiliaryScope(scope))) {
|
|
532
|
+
applyHistoryRequestToTarget(rec, nowMs);
|
|
533
|
+
}
|
|
534
|
+
else if (rec.lastSeenMs <= 0) {
|
|
535
|
+
// Keep record non-stale for persistence without triggering primary coldness.
|
|
536
|
+
rec.lastSeenMs = nowMs;
|
|
537
|
+
}
|
|
538
|
+
scheduleSave();
|
|
539
|
+
return result;
|
|
540
|
+
}
|
|
541
|
+
const result = applyHistoryRequestToTarget(rec, nowMs);
|
|
542
|
+
scheduleSave();
|
|
543
|
+
return result;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Non-mutating read checking whether `sessionKey`'s upstream cache is currently cold.
|
|
547
|
+
* Unknown/unseen sessions return `false` (warm by default).
|
|
548
|
+
*/
|
|
549
|
+
export function isSessionCacheCold(sessionKey, nowMsOrOpts = Date.now()) {
|
|
550
|
+
if (!sessionKey)
|
|
551
|
+
return false;
|
|
552
|
+
const rec = sessions.get(sessionKey);
|
|
553
|
+
if (!rec)
|
|
554
|
+
return false;
|
|
555
|
+
const nowMs = typeof nowMsOrOpts === 'number' ? nowMsOrOpts : (nowMsOrOpts.nowMs ?? Date.now());
|
|
556
|
+
const scope = typeof nowMsOrOpts === 'number' ? undefined : resolveScopeKey(nowMsOrOpts);
|
|
557
|
+
if (scope) {
|
|
558
|
+
const scoped = rec.livenessScopes?.[scope];
|
|
559
|
+
if (scoped)
|
|
560
|
+
return computeCold(scoped, nowMs);
|
|
561
|
+
if (isAuxiliaryScope(scope) && rec.primaryScope && rec.primaryScope !== scope) {
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
return computeCold(rec, nowMs);
|
|
566
|
+
}
|
|
567
|
+
export function getPinnedOpticalHistoryPolicy(sessionKey, opts) {
|
|
568
|
+
if (!sessionKey)
|
|
569
|
+
return undefined;
|
|
570
|
+
const rec = sessions.get(sessionKey);
|
|
571
|
+
if (!rec)
|
|
572
|
+
return undefined;
|
|
573
|
+
const scope = resolveScopeKey(opts);
|
|
574
|
+
if (scope && rec.livenessScopes?.[scope]?.opticalHistoryPolicy !== undefined) {
|
|
575
|
+
return rec.livenessScopes[scope].opticalHistoryPolicy;
|
|
576
|
+
}
|
|
577
|
+
if (scope && isAuxiliaryScope(scope) && rec.primaryScope && rec.primaryScope !== scope) {
|
|
578
|
+
return undefined;
|
|
579
|
+
}
|
|
580
|
+
return rec.opticalHistoryPolicy;
|
|
581
|
+
}
|
|
582
|
+
export function setPinnedOpticalHistoryPolicy(sessionKey, policy, opts) {
|
|
583
|
+
if (!sessionKey)
|
|
584
|
+
return;
|
|
585
|
+
const rec = touch(sessionKey);
|
|
586
|
+
if (rec.lastSeenMs <= 0)
|
|
587
|
+
rec.lastSeenMs = Date.now();
|
|
588
|
+
const scope = resolveScopeKey(opts);
|
|
589
|
+
if (scope) {
|
|
590
|
+
const scoped = getOrCreateScopeRecord(rec, scope);
|
|
591
|
+
if (scoped.lastSeenMs <= 0)
|
|
592
|
+
scoped.lastSeenMs = rec.lastSeenMs;
|
|
593
|
+
if (scoped.opticalHistoryPolicy !== policy) {
|
|
594
|
+
scoped.opticalHistoryPolicy = policy;
|
|
595
|
+
scheduleSave();
|
|
596
|
+
}
|
|
597
|
+
if (rec.primaryScope === scope || (!rec.primaryScope && !isAuxiliaryScope(scope))) {
|
|
598
|
+
if (rec.opticalHistoryPolicy !== policy) {
|
|
599
|
+
rec.opticalHistoryPolicy = policy;
|
|
600
|
+
scheduleSave();
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
if (rec.opticalHistoryPolicy !== policy) {
|
|
606
|
+
rec.opticalHistoryPolicy = policy;
|
|
607
|
+
scheduleSave();
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
export function recordSealedEpochKey(sessionKey, epochKey) {
|
|
611
|
+
if (!sessionKey || !epochKey)
|
|
612
|
+
return;
|
|
613
|
+
const rec = touch(sessionKey);
|
|
614
|
+
if (rec.lastSeenMs <= 0)
|
|
615
|
+
rec.lastSeenMs = Date.now();
|
|
616
|
+
if (!rec.sealedEpochKeys) {
|
|
617
|
+
rec.sealedEpochKeys = [epochKey];
|
|
618
|
+
scheduleSave();
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
if (rec.sealedEpochKeys.includes(epochKey))
|
|
622
|
+
return;
|
|
623
|
+
if (rec.sealedEpochKeys.length >= SEALED_EPOCH_KEYS_MAX)
|
|
624
|
+
return; // retain earliest head epochs
|
|
625
|
+
rec.sealedEpochKeys.push(epochKey);
|
|
626
|
+
scheduleSave();
|
|
627
|
+
}
|
|
628
|
+
export function hasSealedEpochKey(sessionKey, epochKey) {
|
|
629
|
+
if (!sessionKey || !epochKey)
|
|
630
|
+
return false;
|
|
631
|
+
const rec = sessions.get(sessionKey);
|
|
632
|
+
return Boolean(rec?.sealedEpochKeys?.includes(epochKey));
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Record a Stage-2 text-hygiene or hybrid optical slot seal key (head-retaining
|
|
636
|
+
* cap 512) so any compression performed at the uncached frontier replays
|
|
637
|
+
* bit-identically once downstream cache_control breakpoints cover that slot.
|
|
638
|
+
*/
|
|
639
|
+
export function recordStage2SealKey(sessionKey, slotKey) {
|
|
640
|
+
if (!sessionKey || !slotKey)
|
|
641
|
+
return;
|
|
642
|
+
const rec = touch(sessionKey);
|
|
643
|
+
if (rec.lastSeenMs <= 0)
|
|
644
|
+
rec.lastSeenMs = Date.now();
|
|
645
|
+
if (!rec.sealedStage2SlotKeys) {
|
|
646
|
+
rec.sealedStage2SlotKeys = [slotKey];
|
|
647
|
+
scheduleSave();
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
if (rec.sealedStage2SlotKeys.includes(slotKey))
|
|
651
|
+
return;
|
|
652
|
+
if (rec.sealedStage2SlotKeys.length >= SEALED_EPOCH_KEYS_MAX)
|
|
653
|
+
return;
|
|
654
|
+
rec.sealedStage2SlotKeys.push(slotKey);
|
|
655
|
+
scheduleSave();
|
|
656
|
+
}
|
|
657
|
+
export function hasStage2SealKey(sessionKey, slotKey) {
|
|
658
|
+
if (!sessionKey || !slotKey)
|
|
659
|
+
return false;
|
|
660
|
+
const rec = sessions.get(sessionKey);
|
|
661
|
+
return Boolean(rec?.sealedStage2SlotKeys?.includes(slotKey));
|
|
662
|
+
}
|
|
663
|
+
export function recordFoldedEpisodeId(sessionKey, episodeId, certificate) {
|
|
664
|
+
if (!sessionKey || !episodeId)
|
|
665
|
+
return;
|
|
666
|
+
const rec = touch(sessionKey);
|
|
667
|
+
if (rec.lastSeenMs <= 0)
|
|
668
|
+
rec.lastSeenMs = Date.now();
|
|
669
|
+
let updated = false;
|
|
670
|
+
if (!rec.foldedMarkovEpisodeIds) {
|
|
671
|
+
rec.foldedMarkovEpisodeIds = [episodeId];
|
|
672
|
+
updated = true;
|
|
673
|
+
}
|
|
674
|
+
else if (!rec.foldedMarkovEpisodeIds.includes(episodeId) && rec.foldedMarkovEpisodeIds.length < FOLDED_EPISODE_IDS_MAX) {
|
|
675
|
+
rec.foldedMarkovEpisodeIds.push(episodeId);
|
|
676
|
+
updated = true;
|
|
677
|
+
}
|
|
678
|
+
if (certificate) {
|
|
679
|
+
if (!rec.foldedMarkovCertificates)
|
|
680
|
+
rec.foldedMarkovCertificates = {};
|
|
681
|
+
if (rec.foldedMarkovCertificates[episodeId] !== certificate && Object.keys(rec.foldedMarkovCertificates).length < FOLDED_EPISODE_IDS_MAX) {
|
|
682
|
+
rec.foldedMarkovCertificates[episodeId] = certificate;
|
|
683
|
+
updated = true;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (updated)
|
|
687
|
+
scheduleSave();
|
|
688
|
+
}
|
|
689
|
+
export function getFoldedEpisodeCertificate(sessionKey, episodeId) {
|
|
690
|
+
if (!sessionKey || !episodeId)
|
|
691
|
+
return undefined;
|
|
692
|
+
return sessions.get(sessionKey)?.foldedMarkovCertificates?.[episodeId];
|
|
693
|
+
}
|
|
694
|
+
export function hasFoldedEpisodeId(sessionKey, episodeId) {
|
|
695
|
+
if (!sessionKey || !episodeId)
|
|
696
|
+
return false;
|
|
697
|
+
const rec = sessions.get(sessionKey);
|
|
698
|
+
return Boolean(rec?.foldedMarkovEpisodeIds?.includes(episodeId));
|
|
699
|
+
}
|
|
700
|
+
export function hasAnyFoldedEpisodeId(sessionKey) {
|
|
701
|
+
if (!sessionKey)
|
|
702
|
+
return false;
|
|
703
|
+
const rec = sessions.get(sessionKey);
|
|
704
|
+
return Boolean(rec?.foldedMarkovEpisodeIds && rec.foldedMarkovEpisodeIds.length > 0);
|
|
705
|
+
}
|
|
706
|
+
export function getPinnedSessionSkills(sessionKey, catalogHash) {
|
|
707
|
+
if (!sessionKey || !catalogHash)
|
|
708
|
+
return undefined;
|
|
709
|
+
const rec = sessions.get(sessionKey);
|
|
710
|
+
if (!rec || rec.pinnedSkillCatalogHash !== catalogHash || !rec.pinnedSkills) {
|
|
711
|
+
return undefined;
|
|
712
|
+
}
|
|
713
|
+
return [...rec.pinnedSkills];
|
|
714
|
+
}
|
|
715
|
+
export function setPinnedSessionSkills(sessionKey, catalogHash, skills) {
|
|
716
|
+
if (!sessionKey || !catalogHash)
|
|
717
|
+
return;
|
|
718
|
+
const cleaned = sanitizeStringArray(skills, PINNED_SKILLS_MAX, false);
|
|
719
|
+
const rec = touch(sessionKey);
|
|
720
|
+
if (rec.lastSeenMs <= 0)
|
|
721
|
+
rec.lastSeenMs = Date.now();
|
|
722
|
+
if (!cleaned) {
|
|
723
|
+
if (rec.pinnedSkills !== undefined || rec.pinnedSkillCatalogHash !== undefined) {
|
|
724
|
+
delete rec.pinnedSkills;
|
|
725
|
+
delete rec.pinnedSkillCatalogHash;
|
|
726
|
+
scheduleSave();
|
|
727
|
+
}
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
const sameHash = rec.pinnedSkillCatalogHash === catalogHash;
|
|
731
|
+
const sameSkills = sameHash &&
|
|
732
|
+
rec.pinnedSkills !== undefined &&
|
|
733
|
+
rec.pinnedSkills.length === cleaned.length &&
|
|
734
|
+
rec.pinnedSkills.every((s, idx) => s === cleaned[idx]);
|
|
735
|
+
if (sameSkills)
|
|
736
|
+
return;
|
|
737
|
+
rec.pinnedSkills = cleaned;
|
|
738
|
+
rec.pinnedSkillCatalogHash = catalogHash;
|
|
739
|
+
scheduleSave();
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Feed the provider's cache accounting back in, once per response.
|
|
743
|
+
*
|
|
744
|
+
* `read > 0` proves the prefix was live. `create > 0` proves one was just
|
|
745
|
+
* written, which is the case the wall clock got wrong: a turn that paid to build
|
|
746
|
+
* a cache looks identical to a turn that found none, and repacking on top of it
|
|
747
|
+
* discards the thing just paid for.
|
|
748
|
+
*
|
|
749
|
+
* Both zero means nothing is cached for this session, so a repack costs nothing
|
|
750
|
+
* — unless the session just repacked under an implicit-cache provider
|
|
751
|
+
* (`cacheCreateTokens === undefined`), where a cold miss on that repack turn is
|
|
752
|
+
* expected while the provider populates its new implicit cache.
|
|
753
|
+
*/
|
|
754
|
+
function applyCacheOutcomeToTarget(target, alive, cacheCreateTokens) {
|
|
755
|
+
if (alive) {
|
|
756
|
+
target.cacheDead = false;
|
|
757
|
+
target.repackInFlightCount = 0;
|
|
758
|
+
target.lastCacheAlive = true;
|
|
759
|
+
target.everCacheAlive = true;
|
|
760
|
+
}
|
|
761
|
+
else if ((target.repackInFlightCount ?? 0) > 0 && cacheCreateTokens === undefined) {
|
|
762
|
+
// Implicit-cache provider reporting expected zero-read on a freshly repacked turn.
|
|
763
|
+
target.repackInFlightCount = Math.max(0, (target.repackInFlightCount ?? 0) - 1);
|
|
764
|
+
target.lastCacheAlive = undefined;
|
|
765
|
+
}
|
|
766
|
+
else {
|
|
767
|
+
target.repackInFlightCount = Math.max(0, (target.repackInFlightCount ?? 0) - 1);
|
|
768
|
+
target.lastCacheAlive = false;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
export function noteCacheOutcome(sessionKey, cacheReadTokens, cacheCreateTokens, opts) {
|
|
772
|
+
if (!sessionKey)
|
|
773
|
+
return;
|
|
774
|
+
const rec = sessions.get(sessionKey);
|
|
775
|
+
if (!rec)
|
|
776
|
+
return; // never transformed under this key — nothing to attribute
|
|
777
|
+
const alive = (cacheReadTokens ?? 0) > 0 || (cacheCreateTokens ?? 0) > 0;
|
|
778
|
+
const scope = resolveScopeKey(opts);
|
|
779
|
+
if (scope) {
|
|
780
|
+
const scoped = getOrCreateScopeRecord(rec, scope);
|
|
781
|
+
applyCacheOutcomeToTarget(scoped, alive, cacheCreateTokens);
|
|
782
|
+
if (rec.primaryScope === scope || (!rec.primaryScope && !isAuxiliaryScope(scope))) {
|
|
783
|
+
applyCacheOutcomeToTarget(rec, alive, cacheCreateTokens);
|
|
784
|
+
}
|
|
785
|
+
scheduleSave();
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
applyCacheOutcomeToTarget(rec, alive, cacheCreateTokens);
|
|
789
|
+
if (rec.primaryScope && rec.livenessScopes?.[rec.primaryScope]) {
|
|
790
|
+
applyCacheOutcomeToTarget(rec.livenessScopes[rec.primaryScope], alive, cacheCreateTokens);
|
|
791
|
+
}
|
|
792
|
+
scheduleSave();
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Pin the grid this session was last rendered at. Monotonic: the floor only ever
|
|
796
|
+
* rises, because a later, finer render would re-key every chunk it re-cuts.
|
|
797
|
+
*/
|
|
798
|
+
export function recordFreezeStep(sessionKey, step, opts) {
|
|
799
|
+
if (!sessionKey || !step || !Number.isFinite(step) || step <= 0)
|
|
800
|
+
return;
|
|
801
|
+
const rec = touch(sessionKey);
|
|
802
|
+
const scope = resolveScopeKey(opts);
|
|
803
|
+
let changed = false;
|
|
804
|
+
if (scope) {
|
|
805
|
+
const scoped = getOrCreateScopeRecord(rec, scope);
|
|
806
|
+
if (step > scoped.freezeStep) {
|
|
807
|
+
scoped.freezeStep = step;
|
|
808
|
+
changed = true;
|
|
809
|
+
}
|
|
810
|
+
if ((rec.primaryScope === scope || (!rec.primaryScope && !isAuxiliaryScope(scope))) && step > rec.freezeStep) {
|
|
811
|
+
rec.freezeStep = step;
|
|
812
|
+
changed = true;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
else if (step > rec.freezeStep) {
|
|
816
|
+
rec.freezeStep = step;
|
|
817
|
+
changed = true;
|
|
818
|
+
}
|
|
819
|
+
if (changed)
|
|
820
|
+
scheduleSave();
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Mark this session's upstream cache as gone: the last request was rejected, so
|
|
824
|
+
* nothing was cached and the next one may re-cut the grid for density. Call on
|
|
825
|
+
* the failure paths that leave no cache entry (oversized request → opaque 500).
|
|
826
|
+
*/
|
|
827
|
+
export function markCacheDead(sessionKey, opts) {
|
|
828
|
+
if (!sessionKey)
|
|
829
|
+
return;
|
|
830
|
+
const rec = touch(sessionKey);
|
|
831
|
+
const scope = resolveScopeKey(opts);
|
|
832
|
+
if (scope) {
|
|
833
|
+
const scoped = getOrCreateScopeRecord(rec, scope);
|
|
834
|
+
scoped.cacheDead = true;
|
|
835
|
+
if (rec.primaryScope === scope || (!rec.primaryScope && !isAuxiliaryScope(scope))) {
|
|
836
|
+
rec.cacheDead = true;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
else {
|
|
840
|
+
rec.cacheDead = true;
|
|
841
|
+
if (rec.primaryScope && rec.livenessScopes?.[rec.primaryScope]) {
|
|
842
|
+
rec.livenessScopes[rec.primaryScope].cacheDead = true;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
scheduleSave();
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Did this response leave the upstream prefix cache unpopulated?
|
|
849
|
+
*
|
|
850
|
+
* A cache entry is written by a request the provider actually *accepted*. Three
|
|
851
|
+
* outcomes mean it never got that far, so the frozen grid we were protecting
|
|
852
|
+
* protects nothing and the next turn may re-cut for density:
|
|
853
|
+
*
|
|
854
|
+
* - `413` — the payload was rejected outright;
|
|
855
|
+
* - `400` whose body says the prompt is too long (Anthropic's wording varies:
|
|
856
|
+
* `prompt is too long`, `prompt_too_long`, `request_too_large`).
|
|
857
|
+
*
|
|
858
|
+
* NOT any 5xx, which is what this used to say. Production disagreed: of 20871
|
|
859
|
+
* requests on one host the 5xx population was 177 × `529 overloaded`, 2 × `500`
|
|
860
|
+
* and 1 × `503` — and 129 of 250 repacks fired directly after one of them. A 529
|
|
861
|
+
* means the provider declined to process the request; the prefix cache it never
|
|
862
|
+
* touched is still there, and re-cutting the grid threw it away for nothing.
|
|
863
|
+
*
|
|
864
|
+
* Nor any other 4xx. A bad key or a rate limit says nothing about the cache.
|
|
865
|
+
*
|
|
866
|
+
* A cache that genuinely died needs no error to be noticed: {@link
|
|
867
|
+
* noteCacheOutcome} sees the next response report neither a read nor a write, and
|
|
868
|
+
* that is both accurate and free.
|
|
869
|
+
*/
|
|
870
|
+
export function responseLeftNoCache(status, errorBody) {
|
|
871
|
+
if (status === 413)
|
|
872
|
+
return true;
|
|
873
|
+
if (status === 400 && errorBody) {
|
|
874
|
+
return /prompt[\s_-]*(is\s*)?too[\s_-]*long|request[\s_-]*too[\s_-]*large|too many (images|tokens)/i
|
|
875
|
+
.test(errorBody);
|
|
876
|
+
}
|
|
877
|
+
return false;
|
|
878
|
+
}
|
|
879
|
+
import { resetGlobalPrefixTape } from './prefix-tape.js';
|
|
880
|
+
/** Test seam: drop all session state and any pending save. The store stays attached. */
|
|
881
|
+
export function resetSessionState() {
|
|
882
|
+
sessions.clear();
|
|
883
|
+
if (saveTimer) {
|
|
884
|
+
clearTimeout(saveTimer);
|
|
885
|
+
saveTimer = undefined;
|
|
886
|
+
}
|
|
887
|
+
dirty = false;
|
|
888
|
+
resetGlobalPrefixTape();
|
|
889
|
+
}
|
|
890
|
+
/** Test/inspection seam: inspect a session without mutating its clock. */
|
|
891
|
+
export function peekSessionState(sessionKey) {
|
|
892
|
+
const rec = sessions.get(sessionKey);
|
|
893
|
+
if (!rec)
|
|
894
|
+
return undefined;
|
|
895
|
+
return {
|
|
896
|
+
...rec,
|
|
897
|
+
justRepacked: (rec.repackInFlightCount ?? 0) > 0,
|
|
898
|
+
...(rec.sealedEpochKeys ? { sealedEpochKeys: [...rec.sealedEpochKeys] } : {}),
|
|
899
|
+
...(rec.sealedStage2SlotKeys ? { sealedStage2SlotKeys: [...rec.sealedStage2SlotKeys] } : {}),
|
|
900
|
+
...(rec.pinnedSkills ? { pinnedSkills: [...rec.pinnedSkills] } : {}),
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
/** Complete client boilerplate elements, with no user prose between them. */
|
|
904
|
+
const BOILERPLATE_ELEMENT_RE = /<(system-notice|system-reminder|local-command-caveat|local-command-stdout|local-command-stderr|command-name|command-message|command-args)>[\s\S]*?<\/\1>/g;
|
|
905
|
+
export function isBoilerplateText(text) {
|
|
906
|
+
return text.replace(BOILERPLATE_ELEMENT_RE, '').trim() === '';
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Pick the text that identifies a conversation, from the text blocks of its
|
|
910
|
+
* opening user turn(s) in order (everything before the first assistant message).
|
|
911
|
+
*
|
|
912
|
+
* Blocks that are wholly a harness envelope are skipped: they are boilerplate
|
|
913
|
+
* the client injects into every session (omp opens each one with the same
|
|
914
|
+
* `<system-notice>` device inventory; Claude Code with the project's CLAUDE.md
|
|
915
|
+
* `<system-reminder>` and local slash-command output), so keying on them merges
|
|
916
|
+
* every concurrent session into one record, and each session's cache outcomes
|
|
917
|
+
* then re-cut the others' history grids. The first non-envelope block is the
|
|
918
|
+
* user's own prompt. When every block is an envelope, the first one is still
|
|
919
|
+
* better than no key. Capped at 4 KiB.
|
|
920
|
+
*/
|
|
921
|
+
export function sessionAnchorText(texts) {
|
|
922
|
+
const anchor = texts.find((t) => !isBoilerplateText(t)) ?? texts[0] ?? '';
|
|
923
|
+
return anchor.slice(0, 4096);
|
|
924
|
+
}
|
|
925
|
+
/** Inspection seam: how many sessions are currently tracked. */
|
|
926
|
+
export function sessionStateSize() {
|
|
927
|
+
return sessions.size;
|
|
928
|
+
}
|
|
929
|
+
//# sourceMappingURL=session-state.js.map
|