@animus-labs/cortex 0.2.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.
Files changed (293) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +73 -0
  3. package/dist/budget-guard.d.ts +75 -0
  4. package/dist/budget-guard.d.ts.map +1 -0
  5. package/dist/budget-guard.js +142 -0
  6. package/dist/budget-guard.js.map +1 -0
  7. package/dist/compaction/compaction.d.ts +99 -0
  8. package/dist/compaction/compaction.d.ts.map +1 -0
  9. package/dist/compaction/compaction.js +302 -0
  10. package/dist/compaction/compaction.js.map +1 -0
  11. package/dist/compaction/failsafe.d.ts +57 -0
  12. package/dist/compaction/failsafe.d.ts.map +1 -0
  13. package/dist/compaction/failsafe.js +135 -0
  14. package/dist/compaction/failsafe.js.map +1 -0
  15. package/dist/compaction/index.d.ts +381 -0
  16. package/dist/compaction/index.d.ts.map +1 -0
  17. package/dist/compaction/index.js +979 -0
  18. package/dist/compaction/index.js.map +1 -0
  19. package/dist/compaction/microcompaction.d.ts +219 -0
  20. package/dist/compaction/microcompaction.d.ts.map +1 -0
  21. package/dist/compaction/microcompaction.js +536 -0
  22. package/dist/compaction/microcompaction.js.map +1 -0
  23. package/dist/compaction/observational/buffering.d.ts +225 -0
  24. package/dist/compaction/observational/buffering.d.ts.map +1 -0
  25. package/dist/compaction/observational/buffering.js +354 -0
  26. package/dist/compaction/observational/buffering.js.map +1 -0
  27. package/dist/compaction/observational/constants.d.ts +70 -0
  28. package/dist/compaction/observational/constants.d.ts.map +1 -0
  29. package/dist/compaction/observational/constants.js +507 -0
  30. package/dist/compaction/observational/constants.js.map +1 -0
  31. package/dist/compaction/observational/index.d.ts +219 -0
  32. package/dist/compaction/observational/index.d.ts.map +1 -0
  33. package/dist/compaction/observational/index.js +641 -0
  34. package/dist/compaction/observational/index.js.map +1 -0
  35. package/dist/compaction/observational/observer.d.ts +97 -0
  36. package/dist/compaction/observational/observer.d.ts.map +1 -0
  37. package/dist/compaction/observational/observer.js +424 -0
  38. package/dist/compaction/observational/observer.js.map +1 -0
  39. package/dist/compaction/observational/recall-tool.d.ts +27 -0
  40. package/dist/compaction/observational/recall-tool.d.ts.map +1 -0
  41. package/dist/compaction/observational/recall-tool.js +93 -0
  42. package/dist/compaction/observational/recall-tool.js.map +1 -0
  43. package/dist/compaction/observational/reflector.d.ts +94 -0
  44. package/dist/compaction/observational/reflector.d.ts.map +1 -0
  45. package/dist/compaction/observational/reflector.js +167 -0
  46. package/dist/compaction/observational/reflector.js.map +1 -0
  47. package/dist/compaction/observational/types.d.ts +271 -0
  48. package/dist/compaction/observational/types.d.ts.map +1 -0
  49. package/dist/compaction/observational/types.js +15 -0
  50. package/dist/compaction/observational/types.js.map +1 -0
  51. package/dist/context-manager.d.ts +134 -0
  52. package/dist/context-manager.d.ts.map +1 -0
  53. package/dist/context-manager.js +170 -0
  54. package/dist/context-manager.js.map +1 -0
  55. package/dist/cortex-agent.d.ts +1020 -0
  56. package/dist/cortex-agent.d.ts.map +1 -0
  57. package/dist/cortex-agent.js +3589 -0
  58. package/dist/cortex-agent.js.map +1 -0
  59. package/dist/error-classifier.d.ts +48 -0
  60. package/dist/error-classifier.d.ts.map +1 -0
  61. package/dist/error-classifier.js +152 -0
  62. package/dist/error-classifier.js.map +1 -0
  63. package/dist/event-bridge.d.ts +166 -0
  64. package/dist/event-bridge.d.ts.map +1 -0
  65. package/dist/event-bridge.js +381 -0
  66. package/dist/event-bridge.js.map +1 -0
  67. package/dist/index.d.ts +55 -0
  68. package/dist/index.d.ts.map +1 -0
  69. package/dist/index.js +57 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/mcp-client.d.ts +119 -0
  72. package/dist/mcp-client.d.ts.map +1 -0
  73. package/dist/mcp-client.js +474 -0
  74. package/dist/mcp-client.js.map +1 -0
  75. package/dist/model-wrapper.d.ts +58 -0
  76. package/dist/model-wrapper.d.ts.map +1 -0
  77. package/dist/model-wrapper.js +86 -0
  78. package/dist/model-wrapper.js.map +1 -0
  79. package/dist/noop-logger.d.ts +4 -0
  80. package/dist/noop-logger.d.ts.map +1 -0
  81. package/dist/noop-logger.js +8 -0
  82. package/dist/noop-logger.js.map +1 -0
  83. package/dist/prompt-diagnostics.d.ts +47 -0
  84. package/dist/prompt-diagnostics.d.ts.map +1 -0
  85. package/dist/prompt-diagnostics.js +230 -0
  86. package/dist/prompt-diagnostics.js.map +1 -0
  87. package/dist/provider-manager.d.ts +224 -0
  88. package/dist/provider-manager.d.ts.map +1 -0
  89. package/dist/provider-manager.js +563 -0
  90. package/dist/provider-manager.js.map +1 -0
  91. package/dist/provider-registry.d.ts +115 -0
  92. package/dist/provider-registry.d.ts.map +1 -0
  93. package/dist/provider-registry.js +305 -0
  94. package/dist/provider-registry.js.map +1 -0
  95. package/dist/schema-converter.d.ts +20 -0
  96. package/dist/schema-converter.d.ts.map +1 -0
  97. package/dist/schema-converter.js +48 -0
  98. package/dist/schema-converter.js.map +1 -0
  99. package/dist/skill-preprocessor.d.ts +46 -0
  100. package/dist/skill-preprocessor.d.ts.map +1 -0
  101. package/dist/skill-preprocessor.js +237 -0
  102. package/dist/skill-preprocessor.js.map +1 -0
  103. package/dist/skill-registry.d.ts +107 -0
  104. package/dist/skill-registry.d.ts.map +1 -0
  105. package/dist/skill-registry.js +330 -0
  106. package/dist/skill-registry.js.map +1 -0
  107. package/dist/skill-tool.d.ts +54 -0
  108. package/dist/skill-tool.d.ts.map +1 -0
  109. package/dist/skill-tool.js +88 -0
  110. package/dist/skill-tool.js.map +1 -0
  111. package/dist/sub-agent-manager.d.ts +90 -0
  112. package/dist/sub-agent-manager.d.ts.map +1 -0
  113. package/dist/sub-agent-manager.js +192 -0
  114. package/dist/sub-agent-manager.js.map +1 -0
  115. package/dist/token-estimator.d.ts +23 -0
  116. package/dist/token-estimator.d.ts.map +1 -0
  117. package/dist/token-estimator.js +27 -0
  118. package/dist/token-estimator.js.map +1 -0
  119. package/dist/tool-contract.d.ts +68 -0
  120. package/dist/tool-contract.d.ts.map +1 -0
  121. package/dist/tool-contract.js +35 -0
  122. package/dist/tool-contract.js.map +1 -0
  123. package/dist/tool-result-persistence.d.ts +89 -0
  124. package/dist/tool-result-persistence.d.ts.map +1 -0
  125. package/dist/tool-result-persistence.js +152 -0
  126. package/dist/tool-result-persistence.js.map +1 -0
  127. package/dist/tools/bash/index.d.ts +71 -0
  128. package/dist/tools/bash/index.d.ts.map +1 -0
  129. package/dist/tools/bash/index.js +485 -0
  130. package/dist/tools/bash/index.js.map +1 -0
  131. package/dist/tools/bash/interactive.d.ts +47 -0
  132. package/dist/tools/bash/interactive.d.ts.map +1 -0
  133. package/dist/tools/bash/interactive.js +262 -0
  134. package/dist/tools/bash/interactive.js.map +1 -0
  135. package/dist/tools/bash/safety.d.ts +149 -0
  136. package/dist/tools/bash/safety.d.ts.map +1 -0
  137. package/dist/tools/bash/safety.js +1116 -0
  138. package/dist/tools/bash/safety.js.map +1 -0
  139. package/dist/tools/edit.d.ts +57 -0
  140. package/dist/tools/edit.d.ts.map +1 -0
  141. package/dist/tools/edit.js +310 -0
  142. package/dist/tools/edit.js.map +1 -0
  143. package/dist/tools/glob.d.ts +34 -0
  144. package/dist/tools/glob.d.ts.map +1 -0
  145. package/dist/tools/glob.js +268 -0
  146. package/dist/tools/glob.js.map +1 -0
  147. package/dist/tools/grep.d.ts +53 -0
  148. package/dist/tools/grep.d.ts.map +1 -0
  149. package/dist/tools/grep.js +673 -0
  150. package/dist/tools/grep.js.map +1 -0
  151. package/dist/tools/index.d.ts +62 -0
  152. package/dist/tools/index.d.ts.map +1 -0
  153. package/dist/tools/index.js +52 -0
  154. package/dist/tools/index.js.map +1 -0
  155. package/dist/tools/read.d.ts +43 -0
  156. package/dist/tools/read.d.ts.map +1 -0
  157. package/dist/tools/read.js +459 -0
  158. package/dist/tools/read.js.map +1 -0
  159. package/dist/tools/runtime.d.ts +62 -0
  160. package/dist/tools/runtime.d.ts.map +1 -0
  161. package/dist/tools/runtime.js +116 -0
  162. package/dist/tools/runtime.js.map +1 -0
  163. package/dist/tools/shared/cwd-tracker.d.ts +32 -0
  164. package/dist/tools/shared/cwd-tracker.d.ts.map +1 -0
  165. package/dist/tools/shared/cwd-tracker.js +44 -0
  166. package/dist/tools/shared/cwd-tracker.js.map +1 -0
  167. package/dist/tools/shared/edit-history.d.ts +55 -0
  168. package/dist/tools/shared/edit-history.d.ts.map +1 -0
  169. package/dist/tools/shared/edit-history.js +72 -0
  170. package/dist/tools/shared/edit-history.js.map +1 -0
  171. package/dist/tools/shared/edit-matcher.d.ts +83 -0
  172. package/dist/tools/shared/edit-matcher.d.ts.map +1 -0
  173. package/dist/tools/shared/edit-matcher.js +359 -0
  174. package/dist/tools/shared/edit-matcher.js.map +1 -0
  175. package/dist/tools/shared/file-mutation-lock.d.ts +22 -0
  176. package/dist/tools/shared/file-mutation-lock.d.ts.map +1 -0
  177. package/dist/tools/shared/file-mutation-lock.js +35 -0
  178. package/dist/tools/shared/file-mutation-lock.js.map +1 -0
  179. package/dist/tools/shared/gitignore.d.ts +17 -0
  180. package/dist/tools/shared/gitignore.d.ts.map +1 -0
  181. package/dist/tools/shared/gitignore.js +59 -0
  182. package/dist/tools/shared/gitignore.js.map +1 -0
  183. package/dist/tools/shared/pdf-extractor.d.ts +96 -0
  184. package/dist/tools/shared/pdf-extractor.d.ts.map +1 -0
  185. package/dist/tools/shared/pdf-extractor.js +196 -0
  186. package/dist/tools/shared/pdf-extractor.js.map +1 -0
  187. package/dist/tools/shared/read-registry.d.ts +66 -0
  188. package/dist/tools/shared/read-registry.d.ts.map +1 -0
  189. package/dist/tools/shared/read-registry.js +65 -0
  190. package/dist/tools/shared/read-registry.js.map +1 -0
  191. package/dist/tools/shared/safe-env.d.ts +18 -0
  192. package/dist/tools/shared/safe-env.d.ts.map +1 -0
  193. package/dist/tools/shared/safe-env.js +70 -0
  194. package/dist/tools/shared/safe-env.js.map +1 -0
  195. package/dist/tools/sub-agent.d.ts +91 -0
  196. package/dist/tools/sub-agent.d.ts.map +1 -0
  197. package/dist/tools/sub-agent.js +89 -0
  198. package/dist/tools/sub-agent.js.map +1 -0
  199. package/dist/tools/task-output.d.ts +38 -0
  200. package/dist/tools/task-output.d.ts.map +1 -0
  201. package/dist/tools/task-output.js +186 -0
  202. package/dist/tools/task-output.js.map +1 -0
  203. package/dist/tools/tool-search/index.d.ts +40 -0
  204. package/dist/tools/tool-search/index.d.ts.map +1 -0
  205. package/dist/tools/tool-search/index.js +110 -0
  206. package/dist/tools/tool-search/index.js.map +1 -0
  207. package/dist/tools/tool-search/registry.d.ts +82 -0
  208. package/dist/tools/tool-search/registry.d.ts.map +1 -0
  209. package/dist/tools/tool-search/registry.js +238 -0
  210. package/dist/tools/tool-search/registry.js.map +1 -0
  211. package/dist/tools/undo-edit.d.ts +51 -0
  212. package/dist/tools/undo-edit.d.ts.map +1 -0
  213. package/dist/tools/undo-edit.js +231 -0
  214. package/dist/tools/undo-edit.js.map +1 -0
  215. package/dist/tools/web-fetch/cache.d.ts +49 -0
  216. package/dist/tools/web-fetch/cache.d.ts.map +1 -0
  217. package/dist/tools/web-fetch/cache.js +89 -0
  218. package/dist/tools/web-fetch/cache.js.map +1 -0
  219. package/dist/tools/web-fetch/index.d.ts +53 -0
  220. package/dist/tools/web-fetch/index.d.ts.map +1 -0
  221. package/dist/tools/web-fetch/index.js +513 -0
  222. package/dist/tools/web-fetch/index.js.map +1 -0
  223. package/dist/tools/write.d.ts +59 -0
  224. package/dist/tools/write.d.ts.map +1 -0
  225. package/dist/tools/write.js +316 -0
  226. package/dist/tools/write.js.map +1 -0
  227. package/dist/types.d.ts +881 -0
  228. package/dist/types.d.ts.map +1 -0
  229. package/dist/types.js +16 -0
  230. package/dist/types.js.map +1 -0
  231. package/dist/working-tags.d.ts +44 -0
  232. package/dist/working-tags.d.ts.map +1 -0
  233. package/dist/working-tags.js +103 -0
  234. package/dist/working-tags.js.map +1 -0
  235. package/package.json +87 -0
  236. package/src/budget-guard.ts +170 -0
  237. package/src/compaction/compaction.ts +386 -0
  238. package/src/compaction/failsafe.ts +185 -0
  239. package/src/compaction/index.ts +1199 -0
  240. package/src/compaction/microcompaction.ts +709 -0
  241. package/src/compaction/observational/buffering.ts +430 -0
  242. package/src/compaction/observational/constants.ts +532 -0
  243. package/src/compaction/observational/index.ts +837 -0
  244. package/src/compaction/observational/observer.ts +510 -0
  245. package/src/compaction/observational/recall-tool.ts +130 -0
  246. package/src/compaction/observational/reflector.ts +221 -0
  247. package/src/compaction/observational/types.ts +343 -0
  248. package/src/context-manager.ts +237 -0
  249. package/src/cortex-agent.ts +4297 -0
  250. package/src/error-classifier.ts +199 -0
  251. package/src/event-bridge.ts +508 -0
  252. package/src/index.ts +292 -0
  253. package/src/mcp-client.ts +582 -0
  254. package/src/model-wrapper.ts +128 -0
  255. package/src/noop-logger.ts +9 -0
  256. package/src/prompt-diagnostics.ts +296 -0
  257. package/src/provider-manager.ts +823 -0
  258. package/src/provider-registry.ts +386 -0
  259. package/src/schema-converter.ts +51 -0
  260. package/src/skill-preprocessor.ts +314 -0
  261. package/src/skill-registry.ts +378 -0
  262. package/src/skill-tool.ts +130 -0
  263. package/src/sub-agent-manager.ts +236 -0
  264. package/src/token-estimator.ts +26 -0
  265. package/src/tool-contract.ts +113 -0
  266. package/src/tool-result-persistence.ts +197 -0
  267. package/src/tools/bash/index.ts +633 -0
  268. package/src/tools/bash/interactive.ts +302 -0
  269. package/src/tools/bash/safety.ts +1297 -0
  270. package/src/tools/edit.ts +422 -0
  271. package/src/tools/glob.ts +330 -0
  272. package/src/tools/grep.ts +819 -0
  273. package/src/tools/index.ts +110 -0
  274. package/src/tools/read.ts +580 -0
  275. package/src/tools/runtime.ts +173 -0
  276. package/src/tools/shared/cwd-tracker.ts +50 -0
  277. package/src/tools/shared/edit-history.ts +96 -0
  278. package/src/tools/shared/edit-matcher.ts +457 -0
  279. package/src/tools/shared/file-mutation-lock.ts +40 -0
  280. package/src/tools/shared/gitignore.ts +61 -0
  281. package/src/tools/shared/pdf-extractor.ts +290 -0
  282. package/src/tools/shared/read-registry.ts +93 -0
  283. package/src/tools/shared/safe-env.ts +82 -0
  284. package/src/tools/sub-agent.ts +171 -0
  285. package/src/tools/task-output.ts +236 -0
  286. package/src/tools/tool-search/index.ts +167 -0
  287. package/src/tools/tool-search/registry.ts +278 -0
  288. package/src/tools/undo-edit.ts +314 -0
  289. package/src/tools/web-fetch/cache.ts +112 -0
  290. package/src/tools/web-fetch/index.ts +604 -0
  291. package/src/tools/write.ts +385 -0
  292. package/src/types.ts +1057 -0
  293. package/src/working-tags.ts +118 -0
@@ -0,0 +1,381 @@
1
+ /**
2
+ * Compaction composition: wires all three layers into the transformContext chain.
3
+ *
4
+ * Layer 1 (Microcompaction): tool result trimming at threshold crossings
5
+ * Layer 2 (Compaction): conversation summarization via LLM
6
+ * Layer 3 (Failsafe): emergency truncation, purely mechanical
7
+ *
8
+ * All three layers run inside transformContext, which fires before every LLM
9
+ * call. Compaction is fully self-contained within Cortex; no external calls
10
+ * from the backend are needed to trigger it. Layer 2 fires when token usage
11
+ * exceeds 70% of the context window and a completeFn + source accessors are
12
+ * provided. Layer 3 fires whenever tokens exceed 90% of the model's context
13
+ * window.
14
+ *
15
+ * References:
16
+ * - compaction-strategy.md
17
+ * - phase-5-compaction.md (5.5)
18
+ */
19
+ import type { AgentMessage, AgentContext } from '../context-manager.js';
20
+ import type { CortexLogger, CortexCompactionConfig, AdaptiveThresholdConfig, CompactionResult, CompactionDegradedInfo, CompactionExhaustedInfo } from '../types.js';
21
+ import type { CompleteFn, BeforeCompactionHandler, PostCompactionHandler, CompactionErrorHandler } from './compaction.js';
22
+ import type { ObservationalMemoryState, ObservationEvent, ReflectionEvent } from './observational/types.js';
23
+ import { type CacheRetention } from '../provider-registry.js';
24
+ export { MicrocompactionEngine, capToolResult } from './microcompaction.js';
25
+ export type { TrimAction, TrimState } from './microcompaction.js';
26
+ export { runCompaction, shouldCompact, partitionHistory, buildSummaryMessage } from './compaction.js';
27
+ export type { CompleteFn } from './compaction.js';
28
+ export { emergencyTruncate, shouldTruncate, isContextOverflow } from './failsafe.js';
29
+ export type { FailsafeTruncationResult } from './failsafe.js';
30
+ export { ObservationalMemoryEngine } from './observational/index.js';
31
+ export type { ObservationalMemoryConfig, ObservationalMemoryState, ObservationChunk, ObservationEvent, ReflectionEvent, RecallResult, RecallConfig } from './observational/types.js';
32
+ export { createRecallTool } from './observational/recall-tool.js';
33
+ export declare const ADAPTIVE_DEFAULTS: AdaptiveThresholdConfig;
34
+ export declare const DEFAULT_COMPACTION_CONFIG: CortexCompactionConfig;
35
+ /**
36
+ * Build a full compaction config from partial overrides.
37
+ */
38
+ export declare function buildCompactionConfig(partial?: Partial<CortexCompactionConfig>): CortexCompactionConfig;
39
+ /**
40
+ * Compute the effective Layer 2 compaction threshold adjusted by interaction
41
+ * recency. When the user has not interacted recently, the threshold is lowered
42
+ * (i.e., compaction fires sooner), reducing token costs for idle sessions.
43
+ *
44
+ * @param baseThreshold - The configured Layer 2 threshold (e.g., 0.70)
45
+ * @param adaptiveConfig - Adaptive threshold configuration
46
+ * @param lastInteractionTime - Timestamp (ms) of the last user interaction, or null if never
47
+ * @param now - Current timestamp (ms), injectable for testing
48
+ * @returns The adjusted threshold (always >= 0)
49
+ */
50
+ export declare function computeAdaptiveThreshold(baseThreshold: number, adaptiveConfig: AdaptiveThresholdConfig, lastInteractionTime: number | null, now?: number): number;
51
+ /**
52
+ * CompactionManager orchestrates all three compaction layers.
53
+ *
54
+ * It is stateful: it tracks the current token count and the microcompaction
55
+ * cache. The CortexAgent creates one instance and delegates all compaction
56
+ * decisions to it. Compaction is fully autonomous: all three layers run
57
+ * inside applyInTransformContext(), which fires before every LLM call.
58
+ */
59
+ export declare class CompactionManager {
60
+ private readonly config;
61
+ private readonly microcompaction;
62
+ private readonly slotCount;
63
+ private readonly _strategy;
64
+ private observationalEngine;
65
+ /** Post-hoc current-context token count, updated after each parent LLM call. */
66
+ private _currentContextTokenCount;
67
+ /** Context budget for Layer 1/2 compaction decisions (may be artificially limited). */
68
+ private _contextWindow;
69
+ /** Actual model context window for Layer 3 failsafe (never artificially limited). */
70
+ private _modelContextWindow;
71
+ /**
72
+ * Timestamp (ms) of the last user interaction. Used by the adaptive
73
+ * threshold system to decide how aggressively to compact. Updated by
74
+ * the consumer (backend) when a message-triggered tick fires.
75
+ * Null means no interaction has been recorded yet.
76
+ */
77
+ private _lastInteractionTime;
78
+ /**
79
+ * Timestamp (ms) of the last LLM call. Used by L1 to decide whether the
80
+ * prompt cache has gone cold. Updated automatically in
81
+ * updateCurrentContextTokenCount() (which fires after every LLM response).
82
+ * Null means no LLM call has been recorded yet (treated as cold).
83
+ */
84
+ private _lastLlmCallTimestamp;
85
+ /**
86
+ * Effective cache TTL (ms) for the current provider + cache retention.
87
+ * Zero means caching is unsupported or disabled, in which case L1 treats
88
+ * the cache as perpetually cold (trim freely). Set via setCacheInfo().
89
+ */
90
+ private _providerCacheTtlMs;
91
+ /** Consumer handlers for compaction lifecycle events. */
92
+ private beforeCompactionHandlers;
93
+ private postCompactionHandlers;
94
+ private compactionErrorHandlers;
95
+ private compactionResultHandlers;
96
+ private compactionDegradedHandlers;
97
+ private compactionExhaustedHandlers;
98
+ /** Consecutive Layer 2 failure count for circuit breaker. Reset on success. */
99
+ private _consecutiveLayer2Failures;
100
+ /** LLM completion function, set by CortexAgent. */
101
+ private completeFn;
102
+ /** Logger for compaction diagnostics. */
103
+ private logger;
104
+ constructor(config: CortexCompactionConfig, slotCount: number);
105
+ /** Get the compaction strategy. */
106
+ get strategy(): 'observational' | 'classic';
107
+ /**
108
+ * Set the context budget (the effective limit for Layer 1/2 compaction).
109
+ * This may be smaller than the model's actual context window when a
110
+ * user-configured limit is applied.
111
+ */
112
+ setContextWindow(contextWindow: number): void;
113
+ /**
114
+ * Set the model's actual context window (for Layer 3 failsafe only).
115
+ * Layer 3 emergency truncation uses this to avoid dropping messages
116
+ * when the model still has capacity, even if the user-configured
117
+ * budget has been exceeded.
118
+ *
119
+ * Also used as a proxy for the utility model context window until the
120
+ * actual utility model window is set via setUtilityModelContextWindow().
121
+ */
122
+ setModelContextWindow(modelContextWindow: number): void;
123
+ /**
124
+ * Set the LLM completion function for Layer 2 summarization.
125
+ */
126
+ setCompleteFn(fn: CompleteFn): void;
127
+ /**
128
+ * Set the LLM completion function for observational memory (utility model).
129
+ */
130
+ setObservationalCompleteFn(fn: CompleteFn): void;
131
+ /**
132
+ * Update the utility model context window for observer/reflector clamps.
133
+ */
134
+ setUtilityModelContextWindow(utilityModelContextWindow: number): void;
135
+ /**
136
+ * Set a logger for compaction diagnostics.
137
+ */
138
+ setLogger(logger: CortexLogger): void;
139
+ /**
140
+ * Signal when the user last interacted with the system.
141
+ * The consumer (backend) calls this during GATHER when a message-triggered
142
+ * tick fires. For interval ticks, it is not called, so the timestamp
143
+ * naturally ages.
144
+ */
145
+ setLastInteractionTime(timestamp: number): void;
146
+ /**
147
+ * Get the timestamp of the last user interaction, or null if none recorded.
148
+ */
149
+ get lastInteractionTime(): number | null;
150
+ /**
151
+ * Set the active provider and cache retention. Resolves the effective
152
+ * cache TTL from PROVIDER_CACHE_CONFIG and stores it for L1's cache-aware
153
+ * gating. Called by CortexAgent at construction, on provider changes, and
154
+ * on cache retention changes.
155
+ *
156
+ * @param provider - The active provider name (e.g., "anthropic", "openai")
157
+ * @param cacheRetention - The configured cache retention ('none' | 'short' | 'long')
158
+ */
159
+ setCacheInfo(provider: string, cacheRetention: CacheRetention): void;
160
+ /**
161
+ * Check whether the prompt cache has gone cold (or is unused).
162
+ *
163
+ * Returns true when:
164
+ * - Caching is unsupported / disabled (TTL <= 0), OR
165
+ * - No LLM call has been recorded yet, OR
166
+ * - The elapsed time since the last LLM call >= the cache TTL.
167
+ *
168
+ * @param now - Current timestamp (ms), injectable for testing
169
+ */
170
+ isCacheCold(now?: number): boolean;
171
+ /**
172
+ * Get the effective cache TTL (ms) for the current provider + retention.
173
+ * Zero means caching is unsupported or disabled.
174
+ */
175
+ get providerCacheTtlMs(): number;
176
+ /**
177
+ * Get the timestamp of the last LLM call, or null if none recorded.
178
+ */
179
+ get lastLlmCallTimestamp(): number | null;
180
+ /**
181
+ * Compute the effective Layer 2 compaction threshold, adjusted for
182
+ * interaction recency when adaptive thresholds are enabled.
183
+ *
184
+ * @param now - Current timestamp (ms), injectable for testing
185
+ */
186
+ getEffectiveThreshold(now?: number): number;
187
+ /**
188
+ * Update the post-hoc current-context token count from LLM usage data.
189
+ */
190
+ updateCurrentContextTokenCount(inputTokens: number): void;
191
+ /**
192
+ * Get the post-hoc current-context token count from the most recent parent turn.
193
+ */
194
+ get currentContextTokenCount(): number;
195
+ /**
196
+ * Get the context budget (effective limit for Layer 1/2).
197
+ */
198
+ get contextWindow(): number;
199
+ /**
200
+ * Get the model's actual context window (for Layer 3 failsafe).
201
+ */
202
+ get modelContextWindow(): number;
203
+ /**
204
+ * Get the current context usage ratio.
205
+ */
206
+ get usageRatio(): number;
207
+ /**
208
+ * Estimate current context tokens from a transformed AgentContext snapshot.
209
+ *
210
+ * Returns the larger of:
211
+ * - the heuristic estimate of the provided context snapshot
212
+ * - the post-hoc token count from the most recent parent turn
213
+ *
214
+ * This mirrors the compaction decision logic so consumers can reason about
215
+ * context pressure using the same semantics Cortex uses internally.
216
+ */
217
+ estimateCurrentContextTokens(context: AgentContext): number;
218
+ /**
219
+ * Register a handler called before compaction starts (awaited).
220
+ */
221
+ onBeforeCompaction(handler: BeforeCompactionHandler): void;
222
+ /**
223
+ * Register a handler called after compaction completes.
224
+ */
225
+ onPostCompaction(handler: PostCompactionHandler): void;
226
+ /**
227
+ * Register a handler called if compaction fails.
228
+ */
229
+ onCompactionError(handler: CompactionErrorHandler): void;
230
+ /**
231
+ * Register a handler that receives the CompactionResult (for CortexAgent event emission).
232
+ */
233
+ onCompactionResult(handler: (result: CompactionResult) => void): void;
234
+ /**
235
+ * Register a handler called when Layer 2 failed and Layer 3 was used as fallback.
236
+ */
237
+ onCompactionDegraded(handler: (info: CompactionDegradedInfo) => void): void;
238
+ /**
239
+ * Register a handler called when all compaction layers have failed.
240
+ */
241
+ onCompactionExhausted(handler: (info: CompactionExhaustedInfo) => void): void;
242
+ /**
243
+ * Called at turn_end to trigger async buffer checks.
244
+ */
245
+ onTurnEnd(totalTokens: number, contextWindow: number, messages: AgentMessage[], slotCount: number): void;
246
+ /**
247
+ * Register observation event handler.
248
+ */
249
+ onObservation(handler: (event: ObservationEvent) => void): void;
250
+ /**
251
+ * Register reflection event handler.
252
+ */
253
+ onReflection(handler: (event: ReflectionEvent) => void): void;
254
+ /**
255
+ * Get observational memory state for persistence.
256
+ */
257
+ getObservationalMemoryState(): ObservationalMemoryState | null;
258
+ /**
259
+ * Restore observational memory state from a previous session.
260
+ */
261
+ restoreObservationalMemoryState(state: ObservationalMemoryState): void;
262
+ /**
263
+ * Force a synchronous observation cycle.
264
+ */
265
+ triggerObservation(messages: AgentMessage[], slotCount: number): Promise<void>;
266
+ /**
267
+ * Kick off an initial async buffer on unobserved messages.
268
+ * Called during session resumption for a head start before the first prompt().
269
+ */
270
+ kickstartBuffer(messages: AgentMessage[], slotCount: number): void;
271
+ /**
272
+ * Get the observation slot content string (for ContextManager.setSlot).
273
+ */
274
+ getObservationSlotContent(): string;
275
+ /**
276
+ * Whether observations have been produced (non-empty observation text).
277
+ */
278
+ hasObservations(): boolean;
279
+ /**
280
+ * Whether the recall tool should be registered.
281
+ */
282
+ hasRecallTool(): boolean;
283
+ /**
284
+ * Get the recall config if available.
285
+ */
286
+ getRecallConfig(): import("./observational/types.js").RecallConfig | undefined;
287
+ /**
288
+ * Current token count of activated observations only.
289
+ * Returns 0 when not using the observational strategy.
290
+ */
291
+ getObservationTokenCount(): number;
292
+ /**
293
+ * Whether the observer or reflector is currently running in the background.
294
+ * Returns false when not using the observational strategy.
295
+ */
296
+ isObservationalProcessing(): boolean;
297
+ /**
298
+ * Whether the observer specifically is in-flight.
299
+ */
300
+ isObserverInFlight(): boolean;
301
+ /**
302
+ * Whether the reflector specifically is in-flight.
303
+ */
304
+ isReflectorInFlight(): boolean;
305
+ /**
306
+ * Cap a tool result at insertion time (before it enters conversation history).
307
+ */
308
+ capToolResult(content: string): string;
309
+ /**
310
+ * Apply insertion-time cap to all uncapped tool results in the source
311
+ * messages array (mutates in place).
312
+ *
313
+ * Called from the transformContext hook on `agent.state.messages` so that
314
+ * Tier 1 capping is automatically applied when tool results enter
315
+ * conversation history through pi-agent-core's internal tool execution
316
+ * loop. The cap is applied at most once per tool result part; already
317
+ * capped content (containing the insertion marker) is skipped.
318
+ *
319
+ * @param messages - The source messages array (mutated in place)
320
+ * @param slotCount - Number of slot messages to skip at the start
321
+ */
322
+ applyInsertionCap(messages: AgentMessage[], slotCount: number): Promise<void>;
323
+ /**
324
+ * Apply compaction layers to the context in transformContext.
325
+ *
326
+ * This is the main entry point called from CortexAgent.getTransformContextHook().
327
+ * It is fully self-contained: all three compaction layers are integrated here,
328
+ * triggered autonomously based on token thresholds. No external calls from
329
+ * the backend are needed to trigger compaction.
330
+ *
331
+ * Execution order:
332
+ * 1. Layer 1 (microcompaction): tool result trimming at threshold crossings
333
+ * 2. Layer 2 (summarization): if tokens exceed 70% after Layer 1, run LLM
334
+ * summarization on agent.state.messages (the original transcript), then
335
+ * rebuild context from the updated messages
336
+ * 3. Layer 3 (failsafe): if tokens still exceed 90% after Layers 1-2,
337
+ * emergency truncation drops the oldest turns
338
+ *
339
+ * @param context - The AgentContext from transformContext
340
+ * @param getHistory - Function to get conversation history from the context
341
+ * @param setHistory - Function to set conversation history in the context
342
+ * @param getSourceHistory - Function to get the original transcript history (agent.state.messages post-slot)
343
+ * @param setSourceHistory - Function to replace the original transcript history (agent.state.messages)
344
+ * @returns Modified context with compacted history
345
+ */
346
+ applyInTransformContext(context: AgentContext, getHistory: (ctx: AgentContext) => AgentMessage[], setHistory: (ctx: AgentContext, history: AgentMessage[]) => AgentContext, getSourceHistory?: () => AgentMessage[], setSourceHistory?: (history: AgentMessage[]) => void): Promise<AgentContext>;
347
+ /**
348
+ * Manually check if compaction is needed and run it.
349
+ *
350
+ * This is a convenience API for consumers who want to trigger compaction
351
+ * outside the agentic loop (e.g., for testing or manual maintenance).
352
+ * The primary compaction trigger is `applyInTransformContext`, which runs
353
+ * automatically before every LLM call.
354
+ *
355
+ * @param getHistory - Get current conversation history
356
+ * @param setHistory - Replace conversation history
357
+ * @returns CompactionResult if compaction ran, null otherwise
358
+ */
359
+ checkAndRunCompaction(getHistory: () => AgentMessage[], setHistory: (history: AgentMessage[]) => void): Promise<CompactionResult | null>;
360
+ /**
361
+ * Handle a context overflow error by performing emergency truncation.
362
+ * Called when the API returns a context overflow error.
363
+ *
364
+ * @param getHistory - Get current conversation history
365
+ * @param setHistory - Replace conversation history
366
+ */
367
+ handleOverflowError(getHistory: () => AgentMessage[], setHistory: (history: AgentMessage[]) => void): void;
368
+ /**
369
+ * Clear all state and handlers.
370
+ */
371
+ destroy(): void;
372
+ /**
373
+ * Estimate tokens for a set of history messages.
374
+ */
375
+ private estimateHistoryTokens;
376
+ /**
377
+ * Estimate total context tokens from an AgentContext object.
378
+ */
379
+ private estimateContextTokens;
380
+ }
381
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/compaction/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,KAAK,EACV,YAAY,EACZ,sBAAsB,EACtB,uBAAuB,EACvB,gBAAgB,EAEhB,sBAAsB,EACtB,uBAAuB,EACxB,MAAM,aAAa,CAAC;AASrB,OAAO,KAAK,EAAE,UAAU,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAO1H,OAAO,KAAK,EAA6B,wBAAwB,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,0BAA0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