@causyne/agent 1.20.13 → 1.20.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +1 -1
  2. package/src/SmartTools.js +33 -0
  3. package/src/SmartTools.ts +37 -0
  4. package/src/acp/client.js +157 -4
  5. package/src/acp/client.ts +152 -5
  6. package/src/agentLoop.js +857 -178
  7. package/src/agentLoop.ts +865 -183
  8. package/src/browser/browserRuntime.js +8 -1
  9. package/src/browser/browserRuntime.ts +8 -1
  10. package/src/browser/causyneBrowser.js +20 -4
  11. package/src/browser/causyneBrowser.ts +20 -4
  12. package/src/browser/urlPolicy.js +35 -0
  13. package/src/browser/urlPolicy.ts +34 -0
  14. package/src/cliMode.js +6 -2
  15. package/src/commands.js +14 -0
  16. package/src/contextManager.d.ts +1 -0
  17. package/src/core/contextCompactor.js +277 -0
  18. package/src/core/contextCompactor.ts +353 -0
  19. package/src/decideTools.js +157 -0
  20. package/src/decideTools.ts +195 -0
  21. package/src/decisionPolicy.js +5 -3
  22. package/src/decisionPolicy.ts +5 -3
  23. package/src/implementationPlan.js +284 -0
  24. package/src/implementationPlan.ts +275 -0
  25. package/src/observer/coldObserver.js +10 -4
  26. package/src/observer/coldObserver.ts +15 -7
  27. package/src/observer/evidence.js +11 -5
  28. package/src/observer/evidence.ts +13 -6
  29. package/src/observer.js +196 -0
  30. package/src/observer.ts +287 -0
  31. package/src/providers/acp.js +362 -109
  32. package/src/providers/acp.ts +359 -111
  33. package/src/providers/antigravity.js +133 -105
  34. package/src/providers/antigravity.ts +130 -109
  35. package/src/providers/base.d.ts +3 -0
  36. package/src/providers/budgetEnforcer.js +23 -2
  37. package/src/providers/budgetEnforcer.ts +20 -5
  38. package/src/provisioning/capabilityProvisioner.js +14 -10
  39. package/src/sandbox.js +4 -2
  40. package/src/saveTools.js +146 -0
  41. package/src/saveTools.ts +169 -0
  42. package/src/session/cachePressure.js +77 -0
  43. package/src/session/cachePressure.ts +122 -0
  44. package/src/smartToolsUse.js +96 -15
  45. package/src/smartToolsUse.ts +133 -15
  46. package/src/taskShape.js +7 -7
  47. package/src/taskShape.ts +7 -7
  48. package/src/timeMachine.js +55 -20
  49. package/src/timeMachine.ts +64 -20
  50. package/src/toolPacks.js +217 -310
  51. package/src/toolPacks.ts +505 -0
  52. package/src/tools/deferredMcpSearch.js +21 -13
  53. package/src/tools/deferredMcpSearch.ts +23 -15
  54. package/src/tools/updatePlan.js +2 -2
  55. package/src/tools/updatePlan.ts +2 -2
  56. package/src/toolsList.js +203 -0
  57. package/src/toolsList.ts +224 -0
  58. package/src/tui/chatRenderer.js +49 -14
  59. package/src/tui/codeStreamRenderer.js +16 -5
  60. package/src/tui/codeStreamRenderer.ts +14 -4
  61. package/src/tui/prompt.js +4 -2
  62. package/src/tui/sessionSidebar.js +10 -2
  63. package/src/tui/sessionSidebar.ts +10 -3
  64. package/src/tui/stageSurface.js +27 -1
  65. package/src/tui/text.d.ts +1 -0
  66. package/src/tui/turnRail.js +274 -0
  67. package/src/tui/turnRail.ts +334 -0
  68. package/src/types/contracts.ts +103 -0
  69. package/src/verificationPlan.js +141 -0
  70. package/src/verificationPlan.ts +166 -0
  71. package/src/toolPacks.d.ts +0 -10
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @file src/saveTools.ts
3
+ * saveTools — stage 4 of the tool pipeline.
4
+ *
5
+ * user intent -> ToolsList -> decideTools -> SmartTools -> saveTools -> AgentLoop
6
+ *
7
+ * Owns the set of tools admitted for a conversation. Admission is append-only
8
+ * and ordered: tool schemas sit at the front of every provider's cached prefix,
9
+ * so stable ordering avoids unnecessary prefix changes. Adding definitions can
10
+ * still invalidate provider caches; savings must be measured, not assumed.
11
+ *
12
+ * The set is persisted per session so a resumed conversation starts with the
13
+ * tools it already earned, instead of searching for them again.
14
+ *
15
+ * Authorship: Strict TypeScript (Causyne Agent).
16
+ */
17
+ import { createHash } from 'node:crypto';
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { causyneHome } from './utils/paths.js';
21
+ import { atomicWriteFileSync } from './infra/atomicWriter.js';
22
+ const MAX_NAMES = 10000;
23
+ const MAX_RECORDS = 50;
24
+ const MAX_FILES = 200;
25
+ const NAME = /^[A-Za-z0-9_.:@/-]{1,200}$/;
26
+ export class SavedTools {
27
+ packs;
28
+ tools;
29
+ order;
30
+ history = [];
31
+ /** Passing existing collections lets a caller keep its own references valid. */
32
+ constructor(shared = {}) {
33
+ this.packs = shared.packs ?? new Set();
34
+ this.tools = shared.tools ?? new Set();
35
+ this.order = shared.order ?? [];
36
+ }
37
+ admitPack(name) {
38
+ if (!name || this.packs.has(name))
39
+ return false;
40
+ this.packs.add(name);
41
+ this.order.push(name);
42
+ return true;
43
+ }
44
+ admitTool(name) {
45
+ if (!name || this.tools.has(name))
46
+ return false;
47
+ this.tools.add(name);
48
+ return true;
49
+ }
50
+ admit(refined) {
51
+ const addedPacks = refined.packs.filter((name) => this.admitPack(name));
52
+ const addedTools = refined.tools.filter((name) => this.admitTool(name));
53
+ if (addedPacks.length > 0 || addedTools.length > 0) {
54
+ this.history.push({ at: Date.now(), source: refined.source, tools: addedTools, packs: addedPacks, reasons: refined.reasons });
55
+ if (this.history.length > MAX_RECORDS)
56
+ this.history.splice(0, this.history.length - MAX_RECORDS);
57
+ }
58
+ return { addedTools, addedPacks };
59
+ }
60
+ records() {
61
+ return this.history;
62
+ }
63
+ toState() {
64
+ return { packs: [...this.packs], tools: [...this.tools], order: [...this.order] };
65
+ }
66
+ /** Restore without reordering what is already admitted. */
67
+ restore(state) {
68
+ const addedPacks = state.order.filter((name) => state.packs.includes(name) && this.admitPack(name));
69
+ for (const name of state.packs)
70
+ if (this.admitPack(name))
71
+ addedPacks.push(name);
72
+ const addedTools = state.tools.filter((name) => this.admitTool(name));
73
+ return { addedTools, addedPacks };
74
+ }
75
+ }
76
+ function directory() {
77
+ const dir = path.join(causyneHome(), 'tool-sessions');
78
+ try {
79
+ if (!fs.existsSync(dir)) {
80
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
81
+ }
82
+ else {
83
+ const mode = fs.statSync(dir).mode & 0o777;
84
+ if ((mode & 0o100) === 0)
85
+ fs.chmodSync(dir, 0o700);
86
+ }
87
+ }
88
+ catch {
89
+ // fallback if concurrent or read-only
90
+ }
91
+ return dir;
92
+ }
93
+ /** The session id is hashed so it can never escape the directory or collide with a path. */
94
+ export function savedToolsPath(sessionId) {
95
+ const digest = createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 32);
96
+ return path.join(directory(), `${digest}.json`);
97
+ }
98
+ function names(value) {
99
+ if (!Array.isArray(value))
100
+ return [];
101
+ return value.filter((item) => typeof item === 'string' && NAME.test(item)).slice(0, MAX_NAMES);
102
+ }
103
+ /** Never throws: a missing or damaged file is the same as no saved tools. */
104
+ export function readSavedTools(sessionId) {
105
+ try {
106
+ const raw = JSON.parse(fs.readFileSync(savedToolsPath(sessionId), 'utf8'));
107
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
108
+ return null;
109
+ const record = raw;
110
+ const state = { packs: names(record['packs']), tools: names(record['tools']), order: names(record['order']) };
111
+ return state.packs.length + state.tools.length > 0 ? state : null;
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ }
117
+ function prune() {
118
+ try {
119
+ const entries = fs.readdirSync(directory())
120
+ .filter((file) => file.endsWith('.json'))
121
+ .map((file) => ({ file, at: fs.statSync(path.join(directory(), file)).mtimeMs }))
122
+ .sort((a, b) => b.at - a.at);
123
+ for (const stale of entries.slice(MAX_FILES))
124
+ fs.rmSync(path.join(directory(), stale.file), { force: true });
125
+ }
126
+ catch {
127
+ // housekeeping must never block a task
128
+ }
129
+ }
130
+ /** Never throws: persistence is an optimisation, not a dependency. */
131
+ export function writeSavedTools(sessionId, state) {
132
+ try {
133
+ const bounded = {
134
+ packs: names(state.packs),
135
+ tools: names(state.tools),
136
+ order: names(state.order)
137
+ };
138
+ fs.mkdirSync(directory(), { recursive: true, mode: 0o700 });
139
+ atomicWriteFileSync(savedToolsPath(sessionId), JSON.stringify(bounded), { mode: 0o600 });
140
+ prune();
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * @file src/saveTools.ts
3
+ * saveTools — stage 4 of the tool pipeline.
4
+ *
5
+ * user intent -> ToolsList -> decideTools -> SmartTools -> saveTools -> AgentLoop
6
+ *
7
+ * Owns the set of tools admitted for a conversation. Admission is append-only
8
+ * and ordered: tool schemas sit at the front of every provider's cached prefix,
9
+ * so stable ordering avoids unnecessary prefix changes. Adding definitions can
10
+ * still invalidate provider caches; savings must be measured, not assumed.
11
+ *
12
+ * The set is persisted per session so a resumed conversation starts with the
13
+ * tools it already earned, instead of searching for them again.
14
+ *
15
+ * Authorship: Strict TypeScript (Causyne Agent).
16
+ */
17
+
18
+ import { createHash } from 'node:crypto';
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { causyneHome } from './utils/paths.js';
22
+ import { atomicWriteFileSync } from './infra/atomicWriter.js';
23
+ import type { RefinedToolDecision } from './smartToolsUse.js';
24
+
25
+ export interface SavedToolsState {
26
+ packs: string[];
27
+ tools: string[];
28
+ order: string[];
29
+ }
30
+
31
+ export interface AdmissionRecord {
32
+ readonly at: number;
33
+ readonly source: string;
34
+ readonly tools: readonly string[];
35
+ readonly packs: readonly string[];
36
+ readonly reasons: readonly string[];
37
+ }
38
+
39
+ export interface AdmissionResult {
40
+ readonly addedTools: string[];
41
+ readonly addedPacks: string[];
42
+ }
43
+
44
+ const MAX_NAMES = 10000;
45
+ const MAX_RECORDS = 50;
46
+ const MAX_FILES = 200;
47
+ const NAME = /^[A-Za-z0-9_.:@/-]{1,200}$/;
48
+
49
+ export class SavedTools {
50
+ readonly packs: Set<string>;
51
+ readonly tools: Set<string>;
52
+ readonly order: string[];
53
+ private readonly history: AdmissionRecord[] = [];
54
+
55
+ /** Passing existing collections lets a caller keep its own references valid. */
56
+ constructor(shared: { packs?: Set<string>; tools?: Set<string>; order?: string[] } = {}) {
57
+ this.packs = shared.packs ?? new Set<string>();
58
+ this.tools = shared.tools ?? new Set<string>();
59
+ this.order = shared.order ?? [];
60
+ }
61
+
62
+ admitPack(name: string): boolean {
63
+ if (!name || this.packs.has(name)) return false;
64
+ this.packs.add(name);
65
+ this.order.push(name);
66
+ return true;
67
+ }
68
+
69
+ admitTool(name: string): boolean {
70
+ if (!name || this.tools.has(name)) return false;
71
+ this.tools.add(name);
72
+ return true;
73
+ }
74
+
75
+ admit(refined: Pick<RefinedToolDecision, 'source' | 'tools' | 'packs' | 'reasons'>): AdmissionResult {
76
+ const addedPacks = refined.packs.filter((name) => this.admitPack(name));
77
+ const addedTools = refined.tools.filter((name) => this.admitTool(name));
78
+ if (addedPacks.length > 0 || addedTools.length > 0) {
79
+ this.history.push({ at: Date.now(), source: refined.source, tools: addedTools, packs: addedPacks, reasons: refined.reasons });
80
+ if (this.history.length > MAX_RECORDS) this.history.splice(0, this.history.length - MAX_RECORDS);
81
+ }
82
+ return { addedTools, addedPacks };
83
+ }
84
+
85
+ records(): readonly AdmissionRecord[] {
86
+ return this.history;
87
+ }
88
+
89
+ toState(): SavedToolsState {
90
+ return { packs: [...this.packs], tools: [...this.tools], order: [...this.order] };
91
+ }
92
+
93
+ /** Restore without reordering what is already admitted. */
94
+ restore(state: SavedToolsState): AdmissionResult {
95
+ const addedPacks = state.order.filter((name) => state.packs.includes(name) && this.admitPack(name));
96
+ for (const name of state.packs) if (this.admitPack(name)) addedPacks.push(name);
97
+ const addedTools = state.tools.filter((name) => this.admitTool(name));
98
+ return { addedTools, addedPacks };
99
+ }
100
+ }
101
+
102
+ function directory(): string {
103
+ const dir = path.join(causyneHome(), 'tool-sessions');
104
+ try {
105
+ if (!fs.existsSync(dir)) {
106
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
107
+ } else {
108
+ const mode = fs.statSync(dir).mode & 0o777;
109
+ if ((mode & 0o100) === 0) fs.chmodSync(dir, 0o700);
110
+ }
111
+ } catch {
112
+ // fallback if concurrent or read-only
113
+ }
114
+ return dir;
115
+ }
116
+
117
+ /** The session id is hashed so it can never escape the directory or collide with a path. */
118
+ export function savedToolsPath(sessionId: string): string {
119
+ const digest = createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 32);
120
+ return path.join(directory(), `${digest}.json`);
121
+ }
122
+
123
+ function names(value: unknown): string[] {
124
+ if (!Array.isArray(value)) return [];
125
+ return value.filter((item): item is string => typeof item === 'string' && NAME.test(item)).slice(0, MAX_NAMES);
126
+ }
127
+
128
+ /** Never throws: a missing or damaged file is the same as no saved tools. */
129
+ export function readSavedTools(sessionId: string): SavedToolsState | null {
130
+ try {
131
+ const raw: unknown = JSON.parse(fs.readFileSync(savedToolsPath(sessionId), 'utf8'));
132
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null;
133
+ const record = raw as Record<string, unknown>;
134
+ const state: SavedToolsState = { packs: names(record['packs']), tools: names(record['tools']), order: names(record['order']) };
135
+ return state.packs.length + state.tools.length > 0 ? state : null;
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+
141
+ function prune(): void {
142
+ try {
143
+ const entries = fs.readdirSync(directory())
144
+ .filter((file) => file.endsWith('.json'))
145
+ .map((file) => ({ file, at: fs.statSync(path.join(directory(), file)).mtimeMs }))
146
+ .sort((a, b) => b.at - a.at);
147
+ for (const stale of entries.slice(MAX_FILES)) fs.rmSync(path.join(directory(), stale.file), { force: true });
148
+ } catch {
149
+ // housekeeping must never block a task
150
+ }
151
+ }
152
+
153
+ /** Never throws: persistence is an optimisation, not a dependency. */
154
+ export function writeSavedTools(sessionId: string, state: SavedToolsState): boolean {
155
+ try {
156
+ const bounded: SavedToolsState = {
157
+ packs: names(state.packs),
158
+ tools: names(state.tools),
159
+ order: names(state.order)
160
+ };
161
+ fs.mkdirSync(directory(), { recursive: true, mode: 0o700 });
162
+ atomicWriteFileSync(savedToolsPath(sessionId), JSON.stringify(bounded), { mode: 0o600 });
163
+ prune();
164
+ return true;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @file src/session/cachePressure.ts
3
+ * Causyne Agent — Process Cache Pressure Monitor & Cold Session Eviction
4
+ *
5
+ * Adapted from Hermes Agent (gateway/agent_cache_pressure.py) and OpenCode session management.
6
+ * Monitors process RSS against memory thresholds and evicts cold sessions from memory
7
+ * while strictly protecting the most recent warm sessions to preserve KV prompt cache value.
8
+ *
9
+ * Authorship: Strict TypeScript (Causyne Agent).
10
+ */
11
+ import * as os from 'node:os';
12
+ export class SessionCachePressure {
13
+ config;
14
+ constructor(customConfig) {
15
+ this.config = {
16
+ autoBudgetFraction: customConfig?.autoBudgetFraction ?? 0.65,
17
+ autoBudgetFloorMb: customConfig?.autoBudgetFloorMb ?? 512,
18
+ maxEvictionsPerPass: customConfig?.maxEvictionsPerPass ?? 16,
19
+ protectRecent: customConfig?.protectRecent ?? 8,
20
+ };
21
+ }
22
+ getConfig() {
23
+ return { ...this.config };
24
+ }
25
+ getProcessMemoryUsageMb() {
26
+ const memory = process.memoryUsage();
27
+ return Math.round(memory.rss / (1024 * 1024));
28
+ }
29
+ calculateThresholdMb(totalSystemMemoryMb) {
30
+ const totalMb = totalSystemMemoryMb ?? Math.round(os.totalmem() / (1024 * 1024));
31
+ const calculatedBudget = Math.round(totalMb * this.config.autoBudgetFraction);
32
+ return Math.max(this.config.autoBudgetFloorMb, calculatedBudget);
33
+ }
34
+ isUnderPressure(totalSystemMemoryMb) {
35
+ const rssMb = this.getProcessMemoryUsageMb();
36
+ const thresholdMb = this.calculateThresholdMb(totalSystemMemoryMb);
37
+ return rssMb > thresholdMb;
38
+ }
39
+ /**
40
+ * Evaluates memory pressure and identifies cold sessions to evict.
41
+ * Protects the hottest `protectRecent` sessions and pinned sessions.
42
+ */
43
+ evaluateEvictions(sessions, forceCheck = false, mockRssMb) {
44
+ const rssMb = mockRssMb ?? this.getProcessMemoryUsageMb();
45
+ const thresholdMb = this.calculateThresholdMb();
46
+ const underPressure = forceCheck || rssMb > thresholdMb;
47
+ if (!underPressure || sessions.length <= this.config.protectRecent) {
48
+ return {
49
+ underPressure,
50
+ rssMb,
51
+ thresholdMb,
52
+ evictedSessionIds: [],
53
+ reclaimedBytes: 0,
54
+ };
55
+ }
56
+ // Sort descending by lastActiveAt (hottest first)
57
+ const sorted = [...sessions].sort((a, b) => b.lastActiveAt - a.lastActiveAt);
58
+ // Protect the top `protectRecent` warm sessions
59
+ const protectedIds = new Set(sorted.slice(0, this.config.protectRecent).map(s => s.id));
60
+ // Candidates for eviction: oldest first (excluding protected and pinned)
61
+ const candidates = sorted
62
+ .slice(this.config.protectRecent)
63
+ .filter(s => !s.isPinned && !protectedIds.has(s.id))
64
+ .reverse(); // Oldest first
65
+ const toEvict = candidates.slice(0, this.config.maxEvictionsPerPass);
66
+ const evictedSessionIds = toEvict.map(s => s.id);
67
+ const reclaimedBytes = toEvict.reduce((sum, s) => sum + s.estimatedBytes, 0);
68
+ return {
69
+ underPressure,
70
+ rssMb,
71
+ thresholdMb,
72
+ evictedSessionIds,
73
+ reclaimedBytes,
74
+ };
75
+ }
76
+ }
77
+ export const defaultCachePressure = new SessionCachePressure();
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @file src/session/cachePressure.ts
3
+ * Causyne Agent — Process Cache Pressure Monitor & Cold Session Eviction
4
+ *
5
+ * Adapted from Hermes Agent (gateway/agent_cache_pressure.py) and OpenCode session management.
6
+ * Monitors process RSS against memory thresholds and evicts cold sessions from memory
7
+ * while strictly protecting the most recent warm sessions to preserve KV prompt cache value.
8
+ *
9
+ * Authorship: Strict TypeScript (Causyne Agent).
10
+ */
11
+
12
+ import * as os from 'node:os';
13
+
14
+ export interface CachePressureConfig {
15
+ /** Fraction of available system/cgroup memory to treat as threshold (default: 0.65). */
16
+ autoBudgetFraction: number;
17
+ /** Minimum memory floor in MB before pressure triggers (default: 512 MB). */
18
+ autoBudgetFloorMb: number;
19
+ /** Maximum number of sessions to evict in a single pass (default: 16). */
20
+ maxEvictionsPerPass: number;
21
+ /** Number of most-recently-active sessions to protect from eviction (default: 8). */
22
+ protectRecent: number;
23
+ }
24
+
25
+ export interface SessionMemoryRecord {
26
+ id: string;
27
+ lastActiveAt: number;
28
+ estimatedBytes: number;
29
+ isPinned?: boolean;
30
+ }
31
+
32
+ export interface EvictionResult {
33
+ underPressure: boolean;
34
+ rssMb: number;
35
+ thresholdMb: number;
36
+ evictedSessionIds: string[];
37
+ reclaimedBytes: number;
38
+ }
39
+
40
+ export class SessionCachePressure {
41
+ private config: CachePressureConfig;
42
+
43
+ constructor(customConfig?: Partial<CachePressureConfig>) {
44
+ this.config = {
45
+ autoBudgetFraction: customConfig?.autoBudgetFraction ?? 0.65,
46
+ autoBudgetFloorMb: customConfig?.autoBudgetFloorMb ?? 512,
47
+ maxEvictionsPerPass: customConfig?.maxEvictionsPerPass ?? 16,
48
+ protectRecent: customConfig?.protectRecent ?? 8,
49
+ };
50
+ }
51
+
52
+ public getConfig(): Readonly<CachePressureConfig> {
53
+ return { ...this.config };
54
+ }
55
+
56
+ public getProcessMemoryUsageMb(): number {
57
+ const memory = process.memoryUsage();
58
+ return Math.round(memory.rss / (1024 * 1024));
59
+ }
60
+
61
+ public calculateThresholdMb(totalSystemMemoryMb?: number): number {
62
+ const totalMb = totalSystemMemoryMb ?? Math.round(os.totalmem() / (1024 * 1024));
63
+ const calculatedBudget = Math.round(totalMb * this.config.autoBudgetFraction);
64
+ return Math.max(this.config.autoBudgetFloorMb, calculatedBudget);
65
+ }
66
+
67
+ public isUnderPressure(totalSystemMemoryMb?: number): boolean {
68
+ const rssMb = this.getProcessMemoryUsageMb();
69
+ const thresholdMb = this.calculateThresholdMb(totalSystemMemoryMb);
70
+ return rssMb > thresholdMb;
71
+ }
72
+
73
+ /**
74
+ * Evaluates memory pressure and identifies cold sessions to evict.
75
+ * Protects the hottest `protectRecent` sessions and pinned sessions.
76
+ */
77
+ public evaluateEvictions(
78
+ sessions: SessionMemoryRecord[],
79
+ forceCheck = false,
80
+ mockRssMb?: number
81
+ ): EvictionResult {
82
+ const rssMb = mockRssMb ?? this.getProcessMemoryUsageMb();
83
+ const thresholdMb = this.calculateThresholdMb();
84
+ const underPressure = forceCheck || rssMb > thresholdMb;
85
+
86
+ if (!underPressure || sessions.length <= this.config.protectRecent) {
87
+ return {
88
+ underPressure,
89
+ rssMb,
90
+ thresholdMb,
91
+ evictedSessionIds: [],
92
+ reclaimedBytes: 0,
93
+ };
94
+ }
95
+
96
+ // Sort descending by lastActiveAt (hottest first)
97
+ const sorted = [...sessions].sort((a, b) => b.lastActiveAt - a.lastActiveAt);
98
+
99
+ // Protect the top `protectRecent` warm sessions
100
+ const protectedIds = new Set(sorted.slice(0, this.config.protectRecent).map(s => s.id));
101
+
102
+ // Candidates for eviction: oldest first (excluding protected and pinned)
103
+ const candidates = sorted
104
+ .slice(this.config.protectRecent)
105
+ .filter(s => !s.isPinned && !protectedIds.has(s.id))
106
+ .reverse(); // Oldest first
107
+
108
+ const toEvict = candidates.slice(0, this.config.maxEvictionsPerPass);
109
+ const evictedSessionIds = toEvict.map(s => s.id);
110
+ const reclaimedBytes = toEvict.reduce((sum, s) => sum + s.estimatedBytes, 0);
111
+
112
+ return {
113
+ underPressure,
114
+ rssMb,
115
+ thresholdMb,
116
+ evictedSessionIds,
117
+ reclaimedBytes,
118
+ };
119
+ }
120
+ }
121
+
122
+ export const defaultCachePressure = new SessionCachePressure();