@theokit/sdk 4.60.0 → 4.62.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 +108 -0
- package/dist/{agent-6ABK2DPG.js → agent-NVBFTY5H.js} +7 -7
- package/dist/{agent-6ABK2DPG.js.map → agent-NVBFTY5H.js.map} +1 -1
- package/dist/{agent-26RMDG4U.cjs → agent-VYPUO4UB.cjs} +8 -8
- package/dist/{agent-26RMDG4U.cjs.map → agent-VYPUO4UB.cjs.map} +1 -1
- package/dist/{chunk-KKK3FZ4A.cjs → chunk-2DG7KW4L.cjs} +3 -3
- package/dist/{chunk-KKK3FZ4A.cjs.map → chunk-2DG7KW4L.cjs.map} +1 -1
- package/dist/chunk-2UCFUSPW.cjs +468 -0
- package/dist/chunk-2UCFUSPW.cjs.map +1 -0
- package/dist/{chunk-Y2KJ7MYO.cjs → chunk-6OBIWHDR.cjs} +14 -14
- package/dist/{chunk-Y2KJ7MYO.cjs.map → chunk-6OBIWHDR.cjs.map} +1 -1
- package/dist/{chunk-23GPJGRR.cjs → chunk-AH6WD7JR.cjs} +250 -63
- package/dist/chunk-AH6WD7JR.cjs.map +1 -0
- package/dist/{chunk-3HDTP4ZO.cjs → chunk-CWHTMNNK.cjs} +4 -4
- package/dist/{chunk-3HDTP4ZO.cjs.map → chunk-CWHTMNNK.cjs.map} +1 -1
- package/dist/{chunk-E5MWNLRX.js → chunk-IBYRA5PM.js} +3 -3
- package/dist/{chunk-E5MWNLRX.js.map → chunk-IBYRA5PM.js.map} +1 -1
- package/dist/{chunk-43GFJ5SD.cjs → chunk-P5LCASTC.cjs} +19 -4
- package/dist/chunk-P5LCASTC.cjs.map +1 -0
- package/dist/{chunk-7OXXYBHD.js → chunk-QEKI3YKI.js} +3 -3
- package/dist/{chunk-7OXXYBHD.js.map → chunk-QEKI3YKI.js.map} +1 -1
- package/dist/{chunk-76XTUTKY.js → chunk-SKOCYA55.js} +200 -13
- package/dist/chunk-SKOCYA55.js.map +1 -0
- package/dist/chunk-WCLDJSMY.js +456 -0
- package/dist/chunk-WCLDJSMY.js.map +1 -0
- package/dist/{chunk-WG7R5W6R.js → chunk-YEXA3PGR.js} +3 -3
- package/dist/{chunk-WG7R5W6R.js.map → chunk-YEXA3PGR.js.map} +1 -1
- package/dist/{chunk-IACR5LEM.js → chunk-YXGAW7BB.js} +17 -2
- package/dist/chunk-YXGAW7BB.js.map +1 -0
- package/dist/{compact-session-YHFQIXV5.cjs → compact-session-GJXJD73F.cjs} +11 -11
- package/dist/{compact-session-YHFQIXV5.cjs.map → compact-session-GJXJD73F.cjs.map} +1 -1
- package/dist/{compact-session-QGDNP45U.js → compact-session-TSMQOIHO.js} +3 -3
- package/dist/{compact-session-QGDNP45U.js.map → compact-session-TSMQOIHO.js.map} +1 -1
- package/dist/cron.cjs +7 -7
- package/dist/cron.js +6 -6
- package/dist/eval.cjs +6 -6
- package/dist/eval.js +5 -5
- package/dist/{index-manager-KP2JAXKN.js → index-manager-AHAYJ33H.js} +4 -4
- package/dist/{index-manager-KP2JAXKN.js.map → index-manager-AHAYJ33H.js.map} +1 -1
- package/dist/{index-manager-YUORPS4G.cjs → index-manager-RHPFVFSC.cjs} +5 -5
- package/dist/{index-manager-YUORPS4G.cjs.map → index-manager-RHPFVFSC.cjs.map} +1 -1
- package/dist/index.cjs +69 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +42 -9
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-MLCJMYDG.cjs → inject-session-PPSO2IDD.cjs} +4 -4
- package/dist/{inject-session-MLCJMYDG.cjs.map → inject-session-PPSO2IDD.cjs.map} +1 -1
- package/dist/{inject-session-RBQZ45UM.js → inject-session-ZCQUB3IT.js} +3 -3
- package/dist/{inject-session-RBQZ45UM.js.map → inject-session-ZCQUB3IT.js.map} +1 -1
- package/dist/internal/memory/dreaming/phases.d.ts +21 -1
- package/dist/internal/memory/storage/index.cjs +10 -10
- package/dist/internal/memory/storage/index.js +1 -1
- package/dist/internal/memory/storage/memory-file.d.cts +41 -5
- package/dist/internal/memory/storage/memory-file.d.ts +41 -5
- package/dist/internal/memory/storage/threat-scan.d.cts +62 -0
- package/dist/internal/memory/storage/threat-scan.d.ts +62 -0
- package/dist/internal/memory/types.d.ts +28 -0
- package/dist/internal/runtime/memory/select-facts.d.ts +63 -0
- package/dist/internal/runtime/system-prompt/sources/memory-provider.d.ts +6 -1
- package/docs/error-codes.md +3 -2
- package/docs/harness-capability-map.md +9 -7
- package/docs/memory-decisions.md +207 -0
- package/package.json +1 -1
- package/dist/chunk-23GPJGRR.cjs.map +0 -1
- package/dist/chunk-43GFJ5SD.cjs.map +0 -1
- package/dist/chunk-76XTUTKY.js.map +0 -1
- package/dist/chunk-IACR5LEM.js.map +0 -1
- package/dist/chunk-JVERBPRD.js +0 -191
- package/dist/chunk-JVERBPRD.js.map +0 -1
- package/dist/chunk-NY25NBZB.cjs +0 -203
- package/dist/chunk-NY25NBZB.cjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,113 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.62.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 36bb21f: Memory recall is scored with BM25 instead of Jaccard, and rank fusion is damped for stores of
|
|
8
|
+
tens rather than hundreds.
|
|
9
|
+
|
|
10
|
+
**What changes for you:** which memories are selected when several are plausible. The store, the
|
|
11
|
+
budget and the API are unchanged; the ordering is not.
|
|
12
|
+
|
|
13
|
+
Measured on LongMemEval-S — 500 questions, 54 sessions each — through a public eval harness, with
|
|
14
|
+
its tokenised-substring `grep` adapter as the floor:
|
|
15
|
+
|
|
16
|
+
| | hit@5 | P@5 | R@5 | p50 |
|
|
17
|
+
| ----------------------- | --------- | --------- | --------- | -------- |
|
|
18
|
+
| Jaccard (4.61.0) | 80.0% | 0.236 | 0.670 | 205ms |
|
|
19
|
+
| `grep` (floor) | 89.0% | 0.295 | 0.807 | 2ms |
|
|
20
|
+
| **BM25 (this release)** | **96.8%** | **0.329** | **0.904** | **20ms** |
|
|
21
|
+
|
|
22
|
+
Jaccard lost to a naive substring match. The mechanism was isolated before it was fixed: on a
|
|
23
|
+
preference query, the term that discriminates appeared in 2 of 15 documents while a noise term
|
|
24
|
+
appeared in 14 — and Jaccard weighted them identically. Almost every document scored above zero,
|
|
25
|
+
fusion flattened what ordering remained, and recency decided a relevance question. IDF is the
|
|
26
|
+
whole fix, and the gain concentrates where that predicts:
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
single-session-preference 46.7% -> 86.7% (+40.0)
|
|
30
|
+
single-session-assistant 89.3% -> 100.0% (+10.7)
|
|
31
|
+
temporal-reasoning 85.7% -> 96.2% (+10.5)
|
|
32
|
+
multi-session 94.7% -> 96.2% (+1.5)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Also **10x faster**: the previous implementation called its scoring function from inside sort
|
|
36
|
+
comparators, re-tokenising every fact O(n log n) times per query.
|
|
37
|
+
|
|
38
|
+
Rank fusion damping moves from k = 60 to k = 5. Swept rather than chosen — the 500-question corpus
|
|
39
|
+
is insensitive to k once terms are IDF-weighted, while a 15-session corpus goes from 14/15 to
|
|
40
|
+
15/15. The sweep cannot separate 5 from 1, so the tie is broken on the principle that at k = 1
|
|
41
|
+
damping is nearly gone and fusion stops fusing.
|
|
42
|
+
|
|
43
|
+
**This improves the reliability of memory poisoning as well as of recall**, and the two cannot be
|
|
44
|
+
separated: the property that makes a planted entry work is the property that makes a real one
|
|
45
|
+
useful. See the accompanying patch note for the re-measured figures.
|
|
46
|
+
|
|
47
|
+
### Patch Changes
|
|
48
|
+
|
|
49
|
+
- Corrects a security figure published with 4.61.0, and adds the rule that produced the error.
|
|
50
|
+
|
|
51
|
+
The 4.61.0 notes said a planted memory entry made the agent perform the action it described in
|
|
52
|
+
**2 of 6 runs**. Re-measured against the published 4.61.0 itself, it is **6 of 6**. Registering
|
|
53
|
+
the permission engine still blocks it — 6 of 6, with zero errors.
|
|
54
|
+
|
|
55
|
+
The old figure was not a smaller version of the same risk; it was a measurement of a different
|
|
56
|
+
thing. It was taken against a retrieval path that did not recall the planted entry at all: on
|
|
57
|
+
4.60.0 the agent answered "Done." and never saw it, while on 4.61.0 it recites the entry
|
|
58
|
+
verbatim. Nothing about the attack changed between those runs — the recall path did.
|
|
59
|
+
|
|
60
|
+
**A poisoning rate measured against a retrieval path that does not recall the plant is a
|
|
61
|
+
measurement of how often the attack reached the model, not of how often the model resisted it.**
|
|
62
|
+
Any such figure has to record whether the plant was recalled, or it cannot be compared across
|
|
63
|
+
versions.
|
|
64
|
+
|
|
65
|
+
The consequence for anyone depending on this: improving recall is a change to the threat model,
|
|
66
|
+
not something orthogonal to it. The property that makes a planted memory work is the property
|
|
67
|
+
that makes a real one useful. **If anything other than your agent's own deliberate writes can
|
|
68
|
+
reach the memory directory, register the permission engine.**
|
|
69
|
+
|
|
70
|
+
Separately, the original proof constructed the engine as `new PermissionEngine({ rules: [] })`.
|
|
71
|
+
The constructor takes the rules positionally, so that was never a rule list, and nothing checked
|
|
72
|
+
because the script was JavaScript. A crash inside the engine and a gated call produce the same
|
|
73
|
+
observation. Re-run in TypeScript with `new PermissionEngine([])`, it gates: 6 of 6 blocked, 0
|
|
74
|
+
runs threw.
|
|
75
|
+
|
|
76
|
+
## 4.61.0
|
|
77
|
+
|
|
78
|
+
### Minor Changes
|
|
79
|
+
|
|
80
|
+
- 85d96ce: Memory files now match the Claude Code layout, and a memory is named after its subject.
|
|
81
|
+
|
|
82
|
+
**What changes on disk.** A memory used to be named after its whole text, cut at 64
|
|
83
|
+
characters; it is now named after its topic (~32 characters), the index header is
|
|
84
|
+
`# Memory Index`, and each index line reads `- [Title](slug.md) — summary`. Stores written
|
|
85
|
+
by earlier versions are still read; only new writes land under the new names.
|
|
86
|
+
|
|
87
|
+
**Why it matters beyond tidiness.** Naming a memory after its whole text put the entry's
|
|
88
|
+
content into its filename, and a filename is the most exposed field an entry has — it shows
|
|
89
|
+
in directory listings, shell completion, tool logs and stack traces, none of which require
|
|
90
|
+
opening the file. This closes that (#446) by construction rather than by detection: a rule
|
|
91
|
+
about sensitive values would have to recognise one, and secret-pattern redaction cannot
|
|
92
|
+
recognise an arbitrary passphrase. Naming a memory after its subject drops the tail of the
|
|
93
|
+
sentence whatever the tail happens to be.
|
|
94
|
+
|
|
95
|
+
**The trade this makes, stated because it is real.** A topic name is a lossy summary, and
|
|
96
|
+
lossy summaries collide — three different facts about the same subject would reduce to one
|
|
97
|
+
filename. Writes with different text now move aside to `topic-2` instead of overwriting, so
|
|
98
|
+
nothing is lost; re-recording the same text still lands on the same file and increments its
|
|
99
|
+
corroboration count.
|
|
100
|
+
|
|
101
|
+
`MemoryFact` accepts optional `title` and `description` for callers that want to author them
|
|
102
|
+
rather than have them derived.
|
|
103
|
+
|
|
104
|
+
**Not fixed by this release, and measured:** an uncorroborated entry marked `[unconfirmed]`
|
|
105
|
+
influences the model without constraining it (~62%, 95% CI [39%, 82%], n=32), and a planted
|
|
106
|
+
entry phrased as standing policy was sufficient for a live agent to perform the action it
|
|
107
|
+
described in 2 of 6 runs. Registering the permission engine blocked the executive case in
|
|
108
|
+
every run; it is opt-in. Any deployment whose memory directory is writable by anything other
|
|
109
|
+
than the agent's own deliberate writes should register it.
|
|
110
|
+
|
|
3
111
|
## 4.60.0
|
|
4
112
|
|
|
5
113
|
### Minor Changes
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
export { Agent } from './chunk-
|
|
1
|
+
export { Agent } from './chunk-SKOCYA55.js';
|
|
2
2
|
import './chunk-SUKXXLWD.js';
|
|
3
|
-
import './chunk-
|
|
3
|
+
import './chunk-YEXA3PGR.js';
|
|
4
4
|
import './chunk-K2BQQ445.js';
|
|
5
|
-
import './chunk-
|
|
5
|
+
import './chunk-QEKI3YKI.js';
|
|
6
6
|
import './chunk-MZ2FGBLZ.js';
|
|
7
7
|
import './chunk-2SFBB54R.js';
|
|
8
8
|
import './chunk-XN7NOENA.js';
|
|
9
9
|
import './chunk-H73MEMQB.js';
|
|
10
|
-
import './chunk-
|
|
10
|
+
import './chunk-WCLDJSMY.js';
|
|
11
11
|
import './chunk-YJDH3CKG.js';
|
|
12
|
-
import './chunk-
|
|
12
|
+
import './chunk-YXGAW7BB.js';
|
|
13
13
|
import './chunk-3E77SX4H.js';
|
|
14
14
|
import './chunk-WTMU7J4U.js';
|
|
15
15
|
import './chunk-5JLFFPCH.js';
|
|
@@ -51,5 +51,5 @@ import './chunk-3OR54XG4.js';
|
|
|
51
51
|
import './chunk-IDCKSLYH.js';
|
|
52
52
|
import './chunk-T7XEKOVW.js';
|
|
53
53
|
import './chunk-T7O6K6PX.js';
|
|
54
|
-
//# sourceMappingURL=agent-
|
|
55
|
-
//# sourceMappingURL=agent-
|
|
54
|
+
//# sourceMappingURL=agent-NVBFTY5H.js.map
|
|
55
|
+
//# sourceMappingURL=agent-NVBFTY5H.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-NVBFTY5H.js"}
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkAH6WD7JR_cjs = require('./chunk-AH6WD7JR.cjs');
|
|
4
4
|
require('./chunk-NGESVVJN.cjs');
|
|
5
|
-
require('./chunk-
|
|
5
|
+
require('./chunk-2DG7KW4L.cjs');
|
|
6
6
|
require('./chunk-BUUUWQMB.cjs');
|
|
7
|
-
require('./chunk-
|
|
7
|
+
require('./chunk-6OBIWHDR.cjs');
|
|
8
8
|
require('./chunk-P6H23T43.cjs');
|
|
9
9
|
require('./chunk-BV2MWEMV.cjs');
|
|
10
10
|
require('./chunk-EI2Q7SJ5.cjs');
|
|
11
11
|
require('./chunk-GHX4P3V2.cjs');
|
|
12
|
-
require('./chunk-
|
|
12
|
+
require('./chunk-2UCFUSPW.cjs');
|
|
13
13
|
require('./chunk-QI7WE46I.cjs');
|
|
14
|
-
require('./chunk-
|
|
14
|
+
require('./chunk-P5LCASTC.cjs');
|
|
15
15
|
require('./chunk-F3YZMOAU.cjs');
|
|
16
16
|
require('./chunk-4OTIXDMU.cjs');
|
|
17
17
|
require('./chunk-DQKERTND.cjs');
|
|
@@ -58,7 +58,7 @@ require('./chunk-NUKRL3I6.cjs');
|
|
|
58
58
|
|
|
59
59
|
Object.defineProperty(exports, "Agent", {
|
|
60
60
|
enumerable: true,
|
|
61
|
-
get: function () { return
|
|
61
|
+
get: function () { return chunkAH6WD7JR_cjs.Agent; }
|
|
62
62
|
});
|
|
63
|
-
//# sourceMappingURL=agent-
|
|
64
|
-
//# sourceMappingURL=agent-
|
|
63
|
+
//# sourceMappingURL=agent-VYPUO4UB.cjs.map
|
|
64
|
+
//# sourceMappingURL=agent-VYPUO4UB.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-VYPUO4UB.cjs"}
|
|
@@ -48,7 +48,7 @@ function persistTurnToTranscript(store, loc, sessionId, turn, onCompact) {
|
|
|
48
48
|
const count = (recordCounts.get(key) ?? 0) + 1;
|
|
49
49
|
recordCounts.set(key, count);
|
|
50
50
|
if (turn.autoCompact !== void 0) {
|
|
51
|
-
const { autoCompactIfNeeded } = await import('./compact-session-
|
|
51
|
+
const { autoCompactIfNeeded } = await import('./compact-session-GJXJD73F.cjs');
|
|
52
52
|
const fired = await autoCompactIfNeeded({
|
|
53
53
|
store,
|
|
54
54
|
loc,
|
|
@@ -114,5 +114,5 @@ exports.flushSessionWrites = flushSessionWrites;
|
|
|
114
114
|
exports.getSessionMessages = getSessionMessages;
|
|
115
115
|
exports.hydrateSession = hydrateSession;
|
|
116
116
|
exports.persistTurnToTranscript = persistTurnToTranscript;
|
|
117
|
-
//# sourceMappingURL=chunk-
|
|
118
|
-
//# sourceMappingURL=chunk-
|
|
117
|
+
//# sourceMappingURL=chunk-2DG7KW4L.cjs.map
|
|
118
|
+
//# sourceMappingURL=chunk-2DG7KW4L.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":["sessions","transcriptKey","hydratedKeys","persistTurn","diag","readSessionMessages"],"mappings":";;;;;;;AAwCA,IAAM,aAAA,uBAAoB,GAAA,EAA2B;AACrD,IAAM,YAAA,uBAAmB,GAAA,EAAoB;AAStC,SAAS,oBAAA,CAAqB,SAAiB,OAAA,EAA+B;AACnF,EAAA,MAAM,QAAA,GAAWA,0BAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB,EAAAA,0BAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAAA,0BAAA,CAAS,GAAA,CAAI,SAAS,QAAQ,CAAA;AAC9B,EAAA,cAAA,EAAe;AACjB;AAWO,IAAM,mBAAA,GAAsB,EAAA;AAEnC,SAAS,cAAA,GAAuB;AAC9B,EAAA,OAAOA,0BAAA,CAAS,OAAO,mBAAA,EAAqB;AAC1C,IAAA,MAAM,MAAA,GAASA,0BAAA,CAAS,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AACtC,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAAA,0BAAA,CAAS,OAAO,MAAM,CAAA;AACtB,IAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,EAC1B;AACF;AAeA,SAAS,kBAAkB,OAAA,EAAuB;AAChD,EAAA,MAAM,MAAA,GAASC,gCAAc,EAAA,EAAI,OAAO,EAAE,KAAA,CAAM,CAAA,GAAI,OAAA,CAAQ,MAAA,GAAS,CAAC,CAAA;AACtE,EAAA,KAAA,MAAW,CAAA,IAAK,CAAC,GAAGC,8BAAY,CAAA,EAAG,IAA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G,CAAA,EAAG;AAC3B,EAAAA,8BAAA,CAAa,IAAI,GAAG,CAAA;AAEpB,EAAA,MAAM,SAAA,GAAY,MAAMG,qCAAA,CAAoB,GAAA,CAAI,OAAO,OAAO,CAAA;AAC9D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAM5B,EAAAL,0BAAA,CAAS,GAAA,CAAI,SAAS,SAAS,CAAA;AACjC;AAQA,eAAsB,kBAAA,GAAoC;AACxD,EAAA,OAAO,aAAA,CAAc,OAAO,CAAA,EAAG;AAC7B,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,QAAQ,CAAA;AAC7C,IAAA,aAAA,CAAc,KAAA,EAAM;AACpB,IAAA,MAAM,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,EACvB;AACF;AAkBO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAAA,0BAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAOO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAMC,+BAAA,CAAc,GAAA,EAAK,OAAO,CAAA;AACtC,EAAA,MAAM,QAAQ,aAAA,CAAc,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AACxD,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,EAAE,CAAA;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-KKK3FZ4A.cjs","sourcesContent":["import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — the cache lives in a leaf; see session-cache.ts for the reason (cycle broken by extraction).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { diag } from \"../diagnostics.js\";\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n // `delete` + `set` reinserts at the END: a JS `Map` preserves insertion order, so the first key\n // is always the least recently touched. That is the entire LRU, with no new structure (parsimony\n // rungs 2/5 — the ordering we need is already a language guarantee).\n sessions.delete(agentId);\n sessions.set(agentId, existing);\n enforceCeiling();\n}\n\n/**\n * Ceiling on sessions kept in memory.\n *\n * The runtime only reads the **active** session; the rest is pure cache, rebuildable from the\n * on-disk transcript. 32 is deliberately generous — the primary removal path is the explicit\n * `discardSession()` at the end of the agent's life, and this ceiling is a safety net against a\n * long-lived process running hundreds of sessions (plan risk #2: a tight ceiling could evict a\n * session still referenced by an in-flight async path).\n */\nexport const MAX_CACHED_SESSIONS = 32;\n\nfunction enforceCeiling(): void {\n while (sessions.size > MAX_CACHED_SESSIONS) {\n const oldest = sessions.keys().next().value;\n if (oldest === undefined) return;\n sessions.delete(oldest);\n forgetBookkeeping(oldest);\n }\n}\n\n/**\n * Erases the bookkeeping for an `agentId` across EVERY `cwd` it appears in.\n *\n * The three maps are keyed by `transcriptKey(cwd, agentId)`; `sessions` is the only one keyed by the\n * raw `agentId`. The ceiling's first version deleted from all three using `sessions`' key — that is,\n * deleted nothing — and left `hydratedKeys` **orphaned**. Since `hydrateSession` returns early when\n * the marker is present, an evicted session came back **empty** instead of rehydrating from disk:\n * silent amnesia, and a regression new to M95, because before it nothing evicted.\n *\n * The ceiling only knows the `agentId`, not the `cwd`, so it scans by suffix — which is the format\n * `transcriptKey` produces. A scan rather than an index because these maps hold tens of entries, not\n * thousands: a reverse index here would be new structure for a problem that does not exist.\n */\nfunction forgetBookkeeping(agentId: string): void {\n const suffix = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` used to clear **two** of the four maps (`sessions`, `hydratedKeys`);\n * `pendingWrites` and `recordCounts` were never touched by id, so they grew for the life of the\n * process. Neither is large per entry — the leak is in count, not volume — but a cache with no owner\n * for removal is a cache that only grows.\n *\n * Returns the count so the caller can prove the removal; a second discard returns 0, which is what\n * makes the idempotency test possible without exposing the maps.\n */\nexport function discardSession(cwd: string, agentId: string): number {\n const key = transcriptKey(cwd, agentId);\n let removed = 0;\n // `sessions` is NOT erased here — and the distinction is measured, not aesthetic. It holds the\n // readable conversation, and there is a legitimate reader AFTER dispose: the golden\n // `two-concurrent-sends-serialize` calls `getSessionMessages(agentId)` after `agent.dispose()`.\n // Erasing it here returned an empty list and broke two goldens. What bounds it is the LRU ceiling\n // above; the three below are pure bookkeeping, with no post-dispose reader.\n //\n // The key is `transcriptKey(cwd, agentId)` in ALL THREE — not the raw `agentId`. The first version\n // erased two of them by `agentId` and therefore **never erased anything**; the test did not catch\n // it because it only asserted that the SECOND call returns 0, which is true either way.\n if (hydratedKeys.delete(key)) removed++;\n if (pendingWrites.delete(key)) removed++;\n if (recordCounts.delete(key)) removed++;\n return removed;\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n // sweeping these files (a nested root under refactor/). It is not new code and was not touched\n // by M75; refactoring SDK internals without review would trade a visible problem for a diff\n // risky. Tracked in usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`);\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\n/**\n * Drop the in-memory message cache for `agentId` and NOTHING else — the hydration marker in\n * `hydratedKeys` deliberately stays.\n *\n * That asymmetry is the feature, not an oversight, and it is what separates this from\n * `invalidateSessionCache`, which drops both. The single caller is the personality switch's\n * `reset: true` path (`internal/personality/switch.ts`): leaving the marker set makes\n * `hydrateSession` return early, so the next send starts from an EMPTY context instead of\n * replaying the pre-reset transcript off disk. Clearing the marker here would re-hydrate the\n * conversation the reset was asked to discard.\n *\n * The same shape read as a bug one function up: `forgetBookkeeping` documents an evicted session\n * coming back empty as \"silent amnesia\". The difference is intent — eviction wants the transcript\n * back, a reset does not. Anyone reaching for this to invalidate a cache wants\n * `invalidateSessionCache(cwd, agentId)` instead.\n */\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/session/agent-session.ts"],"names":["sessions","transcriptKey","hydratedKeys","persistTurn","diag","readSessionMessages"],"mappings":";;;;;;;AAwCA,IAAM,aAAA,uBAAoB,GAAA,EAA2B;AACrD,IAAM,YAAA,uBAAmB,GAAA,EAAoB;AAStC,SAAS,oBAAA,CAAqB,SAAiB,OAAA,EAA+B;AACnF,EAAA,MAAM,QAAA,GAAWA,0BAAA,CAAS,GAAA,CAAI,OAAO,KAAK,EAAC;AAC3C,EAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAIrB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AAuB;AAClD,EAAAA,0BAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAOO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAMC,+BAAA,CAAc,GAAA,EAAK,OAAO,CAAA;AACtC,EAAA,MAAM,QAAQ,aAAA,CAAc,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AACxD,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,EAAE,CAAA;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-2DG7KW4L.cjs","sourcesContent":["import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — the cache lives in a leaf; see session-cache.ts for the reason (cycle broken by extraction).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { diag } from \"../diagnostics.js\";\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n // `delete` + `set` reinserts at the END: a JS `Map` preserves insertion order, so the first key\n // is always the least recently touched. That is the entire LRU, with no new structure (parsimony\n // rungs 2/5 — the ordering we need is already a language guarantee).\n sessions.delete(agentId);\n sessions.set(agentId, existing);\n enforceCeiling();\n}\n\n/**\n * Ceiling on sessions kept in memory.\n *\n * The runtime only reads the **active** session; the rest is pure cache, rebuildable from the\n * on-disk transcript. 32 is deliberately generous — the primary removal path is the explicit\n * `discardSession()` at the end of the agent's life, and this ceiling is a safety net against a\n * long-lived process running hundreds of sessions (plan risk #2: a tight ceiling could evict a\n * session still referenced by an in-flight async path).\n */\nexport const MAX_CACHED_SESSIONS = 32;\n\nfunction enforceCeiling(): void {\n while (sessions.size > MAX_CACHED_SESSIONS) {\n const oldest = sessions.keys().next().value;\n if (oldest === undefined) return;\n sessions.delete(oldest);\n forgetBookkeeping(oldest);\n }\n}\n\n/**\n * Erases the bookkeeping for an `agentId` across EVERY `cwd` it appears in.\n *\n * The three maps are keyed by `transcriptKey(cwd, agentId)`; `sessions` is the only one keyed by the\n * raw `agentId`. The ceiling's first version deleted from all three using `sessions`' key — that is,\n * deleted nothing — and left `hydratedKeys` **orphaned**. Since `hydrateSession` returns early when\n * the marker is present, an evicted session came back **empty** instead of rehydrating from disk:\n * silent amnesia, and a regression new to M95, because before it nothing evicted.\n *\n * The ceiling only knows the `agentId`, not the `cwd`, so it scans by suffix — which is the format\n * `transcriptKey` produces. A scan rather than an index because these maps hold tens of entries, not\n * thousands: a reverse index here would be new structure for a problem that does not exist.\n */\nfunction forgetBookkeeping(agentId: string): void {\n const suffix = transcriptKey(\"\", agentId).slice(0 - agentId.length - 2);\n for (const k of [...hydratedKeys]) if (k.endsWith(suffix)) hydratedKeys.delete(k);\n for (const k of [...pendingWrites.keys()]) if (k.endsWith(suffix)) pendingWrites.delete(k);\n for (const k of [...recordCounts.keys()]) if (k.endsWith(suffix)) recordCounts.delete(k);\n}\n\n/**\n * Erases the agent's module bookkeeping and returns how many entries were removed.\n *\n * M95 — `invalidateSessionCache` used to clear **two** of the four maps (`sessions`, `hydratedKeys`);\n * `pendingWrites` and `recordCounts` were never touched by id, so they grew for the life of the\n * process. Neither is large per entry — the leak is in count, not volume — but a cache with no owner\n * for removal is a cache that only grows.\n *\n * Returns the count so the caller can prove the removal; a second discard returns 0, which is what\n * makes the idempotency test possible without exposing the maps.\n */\nexport function discardSession(cwd: string, agentId: string): number {\n const key = transcriptKey(cwd, agentId);\n let removed = 0;\n // `sessions` is NOT erased here — and the distinction is measured, not aesthetic. It holds the\n // readable conversation, and there is a legitimate reader AFTER dispose: the golden\n // `two-concurrent-sends-serialize` calls `getSessionMessages(agentId)` after `agent.dispose()`.\n // Erasing it here returned an empty list and broke two goldens. What bounds it is the LRU ceiling\n // above; the three below are pure bookkeeping, with no post-dispose reader.\n //\n // The key is `transcriptKey(cwd, agentId)` in ALL THREE — not the raw `agentId`. The first version\n // erased two of them by `agentId` and therefore **never erased anything**; the test did not catch\n // it because it only asserted that the SECOND call returns 0, which is true either way.\n if (hydratedKeys.delete(key)) removed++;\n if (pendingWrites.delete(key)) removed++;\n if (recordCounts.delete(key)) removed++;\n return removed;\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n // sweeping these files (a nested root under refactor/). It is not new code and was not touched\n // by M75; refactoring SDK internals without review would trade a visible problem for a diff\n // risky. Tracked in usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`);\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\n/**\n * Drop the in-memory message cache for `agentId` and NOTHING else — the hydration marker in\n * `hydratedKeys` deliberately stays.\n *\n * That asymmetry is the feature, not an oversight, and it is what separates this from\n * `invalidateSessionCache`, which drops both. The single caller is the personality switch's\n * `reset: true` path (`internal/personality/switch.ts`): leaving the marker set makes\n * `hydrateSession` return early, so the next send starts from an EMPTY context instead of\n * replaying the pre-reset transcript off disk. Clearing the marker here would re-hydrate the\n * conversation the reset was asked to discard.\n *\n * The same shape read as a bug one function up: `forgetBookkeeping` documents an evicted session\n * coming back empty as \"silent amnesia\". The difference is intent — eviction wants the transcript\n * back, a reset does not. Anyone reaching for this to invalidate a cache wants\n * `invalidateSessionCache(cwd, agentId)` instead.\n */\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
|