@causyne/agent 1.20.60 → 1.20.62

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 (41) hide show
  1. package/package.json +1 -1
  2. package/src/acp/agentCatalog.js +1 -1
  3. package/src/acp/agentCatalog.ts +1 -1
  4. package/src/acp/peerProfiles.js +3 -3
  5. package/src/acp/peerProfiles.ts +3 -3
  6. package/src/agentLoop.js +58 -22
  7. package/src/agentLoop.ts +64 -25
  8. package/src/checkpoints.js +23 -5
  9. package/src/cliMode.js +4 -2
  10. package/src/commands.js +503 -78
  11. package/src/contextManager.d.ts +3 -0
  12. package/src/contextManager.js +78 -5
  13. package/src/cortex/autoCondenser.js +105 -145
  14. package/src/cortex/autoCondenser.ts +185 -0
  15. package/src/cortex/cortexEngine.js +179 -0
  16. package/src/cortex/cortexEngine.ts +209 -0
  17. package/src/cortex/provisioner.js +12 -14
  18. package/src/cortex/provisioner.ts +29 -0
  19. package/src/cortex/vectorDb.js +307 -386
  20. package/src/cortex/vectorDb.ts +473 -0
  21. package/src/reporting.js +30 -7
  22. package/src/sessionJournal.js +13 -0
  23. package/src/sessionJournal.ts +13 -0
  24. package/src/tokenTracker.js +22 -0
  25. package/src/tokenTracker.ts +28 -0
  26. package/src/tui/chatRenderer.js +6 -2
  27. package/src/tui/completion.js +34 -15
  28. package/src/tui/composerControls.js +5 -0
  29. package/src/tui/composerControls.ts +5 -0
  30. package/src/tui/layout.js +1 -1
  31. package/src/tui/layout.ts +1 -1
  32. package/src/tui/observerPicker.js +323 -0
  33. package/src/tui/observerPicker.ts +386 -0
  34. package/src/tui/prompt.js +184 -22
  35. package/src/tui/stageSurface.js +18 -8
  36. package/src/tui/usageCard.js +178 -0
  37. package/src/tui/usageCard.ts +240 -0
  38. package/src/utils/paths.js +30 -1
  39. package/src/utils/paths.ts +32 -1
  40. package/src/cortex/autoCondenser.d.ts +0 -2
  41. package/src/cortex/vectorDb.d.ts +0 -1
@@ -1,4 +1,7 @@
1
1
  export function resolveCharPool(...args: any[]): any;
2
+ export function resolveModelContextTokens(options?: { provider?: string; model?: string; overrideTokens?: number }): number;
3
+ export const MODEL_CONTEXT_TOKENS: Record<string, number>;
4
+ export const CHAR_POOLS: Record<string, number>;
2
5
  export function measureMessages(...args: any[]): any;
3
6
  export function resultCapFor(...args: any[]): any;
4
7
  export function decayToolResults(...args: any[]): any;
@@ -79,14 +79,87 @@ export function resultCapFor(tool) {
79
79
  export const CHAR_POOLS = {
80
80
  super_max: 400000, // ~100k tokens
81
81
  max: 240000, // ~60k tokens
82
- premium: 180000, // ~45k tokens — the middle rung now buys a real context
83
- // bump over fast, not just the right to run (monetization
84
- // Move 3 / Gap #2 in docs/AGENT_MONETIZATION.md).
85
- default: 120000 // ~30k tokens (fast / starter / free)
82
+ premium: 180000, // ~45k tokens — legacy subscription tier pool
83
+ default: 120000 // ~30k tokens
86
84
  };
87
85
 
88
- export function resolveCharPool(tier, override) {
86
+ export const MODEL_CONTEXT_TOKENS = {
87
+ gemini_1m: 1000000,
88
+ gemini_2m: 2000000,
89
+ claude_200k: 200000,
90
+ openai_128k: 128000,
91
+ openai_200k: 200000,
92
+ astra_258k: 258000,
93
+ deepseek_128k: 128000,
94
+ qwen_128k: 128000,
95
+ mistral_128k: 128000,
96
+ grok_131k: 131072,
97
+ default_byok: 128000
98
+ };
99
+
100
+ export function resolveModelContextTokens(options = {}) {
101
+ const { provider = '', model = '', overrideTokens = 0 } = (options || {});
102
+ if (Number.isFinite(overrideTokens) && overrideTokens > 0) return overrideTokens;
103
+ const p = String(provider || '').toLowerCase();
104
+ const m = String(model || '').toLowerCase();
105
+
106
+ // Explicit Gemini 1.5 Pro or 2.0 Pro
107
+ if (m.includes('1.5-pro') || m.includes('2.0-pro') || m.includes('gemini-pro')) {
108
+ return MODEL_CONTEXT_TOKENS.gemini_2m;
109
+ }
110
+ // All other Gemini models, Antigravity ACP peer (Gemini Flash), etc.
111
+ if (p === 'antigravity' || p === 'agy' || m.includes('gemini') || p.includes('gemini')) {
112
+ return MODEL_CONTEXT_TOKENS.gemini_1m;
113
+ }
114
+ // Astra (as used in developer IDEs)
115
+ if (m.includes('astra')) {
116
+ return MODEL_CONTEXT_TOKENS.astra_258k;
117
+ }
118
+ // Claude / Anthropic
119
+ if (p === 'anthropic' || m.includes('claude') || m.includes('sonnet') || m.includes('opus') || m.includes('haiku')) {
120
+ return MODEL_CONTEXT_TOKENS.claude_200k;
121
+ }
122
+ // OpenAI o1 / o3
123
+ if (m.includes('o1') || m.includes('o3')) {
124
+ return MODEL_CONTEXT_TOKENS.openai_200k;
125
+ }
126
+ // OpenAI GPT-4o / GPT-4
127
+ if (p === 'openai' || m.includes('gpt-4')) {
128
+ return MODEL_CONTEXT_TOKENS.openai_128k;
129
+ }
130
+ // DeepSeek
131
+ if (p === 'deepseek' || m.includes('deepseek')) {
132
+ return MODEL_CONTEXT_TOKENS.deepseek_128k;
133
+ }
134
+ // Qwen
135
+ if (p === 'qwen' || p === 'dashscope' || m.includes('qwen')) {
136
+ return MODEL_CONTEXT_TOKENS.qwen_128k;
137
+ }
138
+ // Mistral
139
+ if (p === 'mistral' || m.includes('mistral') || m.includes('codestral')) {
140
+ return MODEL_CONTEXT_TOKENS.mistral_128k;
141
+ }
142
+ // Grok / xAI
143
+ if (p === 'xai' || m.includes('grok')) {
144
+ return MODEL_CONTEXT_TOKENS.grok_131k;
145
+ }
146
+
147
+ // Any other BYOK / ACP peer
148
+ if (p && p !== 'default') {
149
+ return MODEL_CONTEXT_TOKENS.default_byok;
150
+ }
151
+
152
+ return 0; // indicates fallback to subscription tier pool
153
+ }
154
+
155
+ export function resolveCharPool(tier, override, context = {}) {
89
156
  if (override && Number.isFinite(override) && override > 0) return override;
157
+
158
+ const modelTokens = resolveModelContextTokens(context);
159
+ if (modelTokens > 0) {
160
+ return modelTokens * 4; // 4 chars per token
161
+ }
162
+
90
163
  if (tier === 'super_max') return CHAR_POOLS.super_max;
91
164
  if (tier === 'max') return CHAR_POOLS.max;
92
165
  if (tier === 'premium' || tier === 'premium_annual') return CHAR_POOLS.premium;
@@ -1,149 +1,125 @@
1
1
  import { cortexDb } from './vectorDb.js';
2
-
3
2
  // Diagnostics, off by default: console output during a turn overwrites the
4
3
  // prompt's live region. See src/cortex/provisioner.js for the full reason.
5
4
  function debugLog(message) {
6
- if (process.env.CAUSYNE_DEBUG !== '1') return;
7
- process.stderr.write(`[causyne] ${message}\n`);
5
+ if (process.env.CAUSYNE_DEBUG !== '1')
6
+ return;
7
+ process.stderr.write(`[causyne] ${message}\n`);
8
8
  }
9
-
10
-
11
9
  // V5 Cortex — Tiered Auto-Condensation
12
10
  //
13
11
  // When the sliding window amputates older messages, that knowledge must not
14
12
  // simply evaporate: continuity across sessions is what turns a stateless text
15
13
  // predictor into something with a useful retained history.
16
14
  //
17
- // The original implementation fired an untracked LLM call on the user's own
18
- // BYOK key at every single amputation, feeding it the entire dropped chunk —
19
- // which on a saturated 400,000-character window could cost more than the
20
-
21
- // displayed. The answer is not to switch memory formation off; it is to make it
22
- // tiered:
23
- //
15
+ // The tiered design:
24
16
  // Tier 1 (always, free) — a deterministic structural summary is written to
25
17
  // the Cortex with no LLM involved. The brain always
26
18
  // learns something, on every provider, at zero cost.
27
19
  // Tier 2 (gated, billed) — semantic LLM condensation, but only when the
28
20
  // dropped chunk is materially large, capped per task,
29
21
  // with bounded input and fully tracked usage.
30
-
31
22
  const MAX_CONDENSE_CHARS = 24000;
32
23
  const MIN_CHARS_FOR_LLM_PASS = 6000;
33
24
  const DEFAULT_MAX_LLM_PASSES_PER_TASK = 3;
34
-
35
25
  function serialiseContent(content) {
36
- // An assistant message that only carries tool_calls has no content at all,
37
- // and JSON.stringify(undefined) returns undefined rather than a string.
38
- if (content == null) return '';
39
- return typeof content === 'string' ? content : (JSON.stringify(content) || '');
26
+ if (content == null)
27
+ return '';
28
+ return typeof content === 'string' ? content : (JSON.stringify(content) || '');
40
29
  }
41
-
42
30
  /**
43
31
  * Tier 1: structural facts extracted without any model call.
44
32
  * Records what was attempted, which files were touched and what failed —
45
33
  * exactly the things the agent asks itself again ten steps later.
46
34
  */
47
35
  export function buildStructuralSummary(droppedMessages) {
48
- const toolCounts = new Map();
49
- const touchedPaths = new Set();
50
- const failures = [];
51
- const userTurns = [];
52
-
53
- for (const msg of droppedMessages) {
54
- const content = serialiseContent(msg.content);
55
-
56
- if (msg.role === 'user' && typeof msg.content === 'string' && msg.content.length < 600) {
57
- userTurns.push(msg.content.trim());
58
- }
59
-
60
- if (msg.role === 'tool') {
61
- if (msg.name) toolCounts.set(msg.name, (toolCounts.get(msg.name) || 0) + 1);
62
-
63
- // Absolute paths are the highest-value breadcrumb in a dropped chunk.
64
- const paths = content.match(/\/[\w.\-/]+\.[a-zA-Z0-9]{1,6}/g);
65
- if (paths) for (const p of paths.slice(0, 6)) touchedPaths.add(p);
66
-
67
- try {
68
- const parsed = JSON.parse(content);
69
- if (parsed && parsed.success === false && parsed.error) {
70
- failures.push(`${msg.name || 'tool'}: ${String(parsed.error).slice(0, 140)}`);
36
+ const toolCounts = new Map();
37
+ const touchedPaths = new Set();
38
+ const failures = [];
39
+ const userTurns = [];
40
+ for (const msg of droppedMessages) {
41
+ const content = serialiseContent(msg.content);
42
+ if (msg.role === 'user' && typeof msg.content === 'string' && msg.content.length < 600) {
43
+ userTurns.push(msg.content.trim());
44
+ }
45
+ if (msg.role === 'tool') {
46
+ if (msg.name)
47
+ toolCounts.set(msg.name, (toolCounts.get(msg.name) || 0) + 1);
48
+ // Absolute paths are the highest-value breadcrumb in a dropped chunk.
49
+ const paths = content.match(/\/[\w.\-/]+\.[a-zA-Z0-9]{1,6}/g);
50
+ if (paths)
51
+ for (const p of paths.slice(0, 6))
52
+ touchedPaths.add(p);
53
+ try {
54
+ const parsed = JSON.parse(content);
55
+ if (parsed && parsed.success === false && parsed.error) {
56
+ failures.push(`${msg.name || 'tool'}: ${String(parsed.error).slice(0, 140)}`);
57
+ }
58
+ }
59
+ catch (_e) {
60
+ // Non-JSON tool output carries no structured verdict; skip it.
61
+ }
71
62
  }
72
- } catch (e) {
73
- // Non-JSON tool output carries no structured verdict; skip it.
74
- }
75
63
  }
76
- }
77
-
78
- const parts = [];
79
- if (userTurns.length > 0) {
80
- parts.push(`Requests in this segment: ${userTurns.slice(0, 3).join(' | ')}`);
81
- }
82
- if (toolCounts.size > 0) {
83
- const tools = [...toolCounts.entries()]
84
- .sort((a, b) => b[1] - a[1])
85
- .slice(0, 10)
86
- .map(([name, count]) => `${name}x${count}`)
87
- .join(', ');
88
- parts.push(`Tools used: ${tools}`);
89
- }
90
- if (touchedPaths.size > 0) {
91
- parts.push(`Files touched: ${[...touchedPaths].slice(0, 12).join(', ')}`);
92
- }
93
- if (failures.length > 0) {
94
- parts.push(`Failures encountered: ${failures.slice(0, 4).join(' | ')}`);
95
- }
96
-
97
- return parts.length > 0 ? parts.join('. ') : '';
64
+ const parts = [];
65
+ if (userTurns.length > 0) {
66
+ parts.push(`Requests in this segment: ${userTurns.slice(0, 3).join(' | ')}`);
67
+ }
68
+ if (toolCounts.size > 0) {
69
+ const tools = [...toolCounts.entries()]
70
+ .sort((a, b) => b[1] - a[1])
71
+ .slice(0, 10)
72
+ .map(([name, count]) => `${name}x${count}`)
73
+ .join(', ');
74
+ parts.push(`Tools used: ${tools}`);
75
+ }
76
+ if (touchedPaths.size > 0) {
77
+ parts.push(`Files touched: ${[...touchedPaths].slice(0, 12).join(', ')}`);
78
+ }
79
+ if (failures.length > 0) {
80
+ parts.push(`Failures encountered: ${failures.slice(0, 4).join(' | ')}`);
81
+ }
82
+ return parts.length > 0 ? parts.join('. ') : '';
98
83
  }
99
-
100
84
  /**
101
- * @param {Array} droppedMessages Messages leaving the active window.
102
- * @param {object} llm Provider used for the optional Tier 2 pass.
103
- * @param {object} tokenTracker Required for Tier 2 so usage is never hidden.
104
- * @param {object} options { maxLlmPasses, passesUsed, enableLlmPass }
105
- * @returns {Promise<{ structural: boolean, semantic: boolean }>}
85
+ * Condense dropped messages into Cortex memory.
106
86
  */
107
- export async function condenseAndSave(droppedMessages, llm, tokenTracker = null, options = {}) {
108
- const result = { structural: false, semantic: false };
109
- if (!droppedMessages || droppedMessages.length === 0) return result;
110
-
111
- // ---- Tier 1: always-on, zero cost -------------------------------------
112
- try {
113
- const structural = buildStructuralSummary(droppedMessages);
114
- if (structural) {
115
- await cortexDb.saveCondensedMemory(structural);
116
- result.structural = true;
87
+ export async function condenseAndSave(droppedMessages, llm = null, tokenTracker = null, options = {}) {
88
+ const result = { structural: false, semantic: false };
89
+ if (!droppedMessages || droppedMessages.length === 0)
90
+ return result;
91
+ // ---- Tier 1: always-on, zero cost -------------------------------------
92
+ try {
93
+ const structural = buildStructuralSummary(droppedMessages);
94
+ if (structural) {
95
+ await cortexDb.saveCondensedMemory(structural);
96
+ result.structural = true;
97
+ }
117
98
  }
118
- } catch (e) {
119
- debugLog(`[Auto-Condenser] Structural condensation failed: ${e.message}`);
120
- }
121
-
122
- // ---- Tier 2: gated semantic pass --------------------------------------
123
- if (!llm || options.enableLlmPass === false) return result;
124
-
125
- const maxPasses = Number.isInteger(options.maxLlmPasses)
126
- ? options.maxLlmPasses
127
- : DEFAULT_MAX_LLM_PASSES_PER_TASK;
128
- if ((options.passesUsed || 0) >= maxPasses) return result;
129
-
130
- let conversationText = droppedMessages.map(m => {
131
- let content = serialiseContent(m.content);
132
- // Tool payloads dominate the volume and are the least useful thing to
133
- // summarise verbatim.
134
- if (content.length > 2000) content = content.slice(0, 2000) + ' …[truncated]';
135
- return `${m.role.toUpperCase()}: ${content}`;
136
- }).join('\n\n');
137
-
138
- // A trivial chunk is not worth a model call; Tier 1 already captured it.
139
- if (conversationText.length < MIN_CHARS_FOR_LLM_PASS) return result;
140
-
141
- if (conversationText.length > MAX_CONDENSE_CHARS) {
142
- conversationText = conversationText.slice(-MAX_CONDENSE_CHARS);
143
- }
144
-
145
- try {
146
- const prompt = `You are an AI Memory Condenser for an autonomous agent.
99
+ catch (e) {
100
+ debugLog(`[Auto-Condenser] Structural condensation failed: ${e.message}`);
101
+ }
102
+ // ---- Tier 2: gated semantic pass --------------------------------------
103
+ if (!llm || options.enableLlmPass === false)
104
+ return result;
105
+ const maxPasses = Number.isInteger(options.maxLlmPasses)
106
+ ? options.maxLlmPasses
107
+ : DEFAULT_MAX_LLM_PASSES_PER_TASK;
108
+ if ((options.passesUsed || 0) >= maxPasses)
109
+ return result;
110
+ let conversationText = droppedMessages.map((m) => {
111
+ let content = serialiseContent(m.content);
112
+ if (content.length > 2000)
113
+ content = content.slice(0, 2000) + ' …[truncated]';
114
+ return `${String(m.role || '').toUpperCase()}: ${content}`;
115
+ }).join('\n\n');
116
+ if (conversationText.length < MIN_CHARS_FOR_LLM_PASS)
117
+ return result;
118
+ if (conversationText.length > MAX_CONDENSE_CHARS) {
119
+ conversationText = conversationText.slice(-MAX_CONDENSE_CHARS);
120
+ }
121
+ try {
122
+ const prompt = `You are an AI Memory Condenser for an autonomous agent.
147
123
  Below is a chunk of an older conversation between the User and the Assistant that is being pushed out of the short-term memory window due to length constraints.
148
124
  Your task is to summarize the KEY FACTS, DECISIONS, or OUTCOMES from this conversation snippet into 1-3 concise bullet points.
149
125
  - Do NOT include pleasantries, filler, or transient errors that were immediately fixed.
@@ -154,39 +130,23 @@ Conversation Snippet:
154
130
  ${conversationText}
155
131
 
156
132
  Provide only the bullet points.`;
157
-
158
- // maxTokens capped deliberately. The prompt asks for one to three bullet
159
- // points; without a ceiling a model that misreads the instruction can
160
- // return a full re-summary of the transcript it was given, at completion
161
- // rates. Module 4 stage 1 of the scaling plan: cap the output of anything
162
- // whose shape you already know.
163
- const response = await llm.chat([{ role: 'user', content: prompt }], {
164
- temperature: 0.1,
165
- maxTokens: 400
166
- });
167
-
168
- // This call spends the user's own BYOK credits. It used to bypass the
169
-
170
- // real bill.
171
- if (tokenTracker && response && response.usage) {
172
- await tokenTracker.trackUsage(
173
- response.usage.promptTokens || 0,
174
- response.usage.completionTokens || 0,
175
- null,
176
- response.usage
177
- );
133
+ const response = await llm.chat([{ role: 'user', content: prompt }], {
134
+ temperature: 0.1,
135
+ maxTokens: 400
136
+ });
137
+ if (tokenTracker && response && response.usage) {
138
+ await tokenTracker.trackUsage(response.usage.promptTokens || 0, response.usage.completionTokens || 0, null, response.usage);
139
+ }
140
+ if (response && response.content) {
141
+ const summary = String(response.content).trim();
142
+ if (summary && summary !== 'SKIP' && summary.length > 10) {
143
+ await cortexDb.saveCondensedMemory(summary);
144
+ result.semantic = true;
145
+ }
146
+ }
178
147
  }
179
-
180
- if (response && response.content) {
181
- const summary = response.content.trim();
182
- if (summary && summary !== 'SKIP' && summary.length > 10) {
183
- await cortexDb.saveCondensedMemory(summary);
184
- result.semantic = true;
185
- }
148
+ catch (e) {
149
+ debugLog(`[Auto-Condenser] Semantic condensation failed: ${e.message}`);
186
150
  }
187
- } catch (e) {
188
- debugLog(`[Auto-Condenser] Semantic condensation failed: ${e.message}`);
189
- }
190
-
191
- return result;
151
+ return result;
192
152
  }
@@ -0,0 +1,185 @@
1
+ import { cortexDb } from './vectorDb.js';
2
+
3
+ // Diagnostics, off by default: console output during a turn overwrites the
4
+ // prompt's live region. See src/cortex/provisioner.js for the full reason.
5
+ function debugLog(message: string): void {
6
+ if (process.env.CAUSYNE_DEBUG !== '1') return;
7
+ process.stderr.write(`[causyne] ${message}\n`);
8
+ }
9
+
10
+ // V5 Cortex — Tiered Auto-Condensation
11
+ //
12
+ // When the sliding window amputates older messages, that knowledge must not
13
+ // simply evaporate: continuity across sessions is what turns a stateless text
14
+ // predictor into something with a useful retained history.
15
+ //
16
+ // The tiered design:
17
+ // Tier 1 (always, free) — a deterministic structural summary is written to
18
+ // the Cortex with no LLM involved. The brain always
19
+ // learns something, on every provider, at zero cost.
20
+ // Tier 2 (gated, billed) — semantic LLM condensation, but only when the
21
+ // dropped chunk is materially large, capped per task,
22
+ // with bounded input and fully tracked usage.
23
+
24
+ const MAX_CONDENSE_CHARS = 24000;
25
+ const MIN_CHARS_FOR_LLM_PASS = 6000;
26
+ const DEFAULT_MAX_LLM_PASSES_PER_TASK = 3;
27
+
28
+ export interface CondenserOptions {
29
+ maxLlmPasses?: number;
30
+ passesUsed?: number;
31
+ enableLlmPass?: boolean;
32
+ }
33
+
34
+ export interface CondenserResult {
35
+ structural: boolean;
36
+ semantic: boolean;
37
+ }
38
+
39
+ function serialiseContent(content: unknown): string {
40
+ if (content == null) return '';
41
+ return typeof content === 'string' ? content : (JSON.stringify(content) || '');
42
+ }
43
+
44
+ /**
45
+ * Tier 1: structural facts extracted without any model call.
46
+ * Records what was attempted, which files were touched and what failed —
47
+ * exactly the things the agent asks itself again ten steps later.
48
+ */
49
+ export function buildStructuralSummary(droppedMessages: any[]): string {
50
+ const toolCounts = new Map<string, number>();
51
+ const touchedPaths = new Set<string>();
52
+ const failures: string[] = [];
53
+ const userTurns: string[] = [];
54
+
55
+ for (const msg of droppedMessages) {
56
+ const content = serialiseContent(msg.content);
57
+
58
+ if (msg.role === 'user' && typeof msg.content === 'string' && msg.content.length < 600) {
59
+ userTurns.push(msg.content.trim());
60
+ }
61
+
62
+ if (msg.role === 'tool') {
63
+ if (msg.name) toolCounts.set(msg.name, (toolCounts.get(msg.name) || 0) + 1);
64
+
65
+ // Absolute paths are the highest-value breadcrumb in a dropped chunk.
66
+ const paths = content.match(/\/[\w.\-/]+\.[a-zA-Z0-9]{1,6}/g);
67
+ if (paths) for (const p of paths.slice(0, 6)) touchedPaths.add(p);
68
+
69
+ try {
70
+ const parsed = JSON.parse(content);
71
+ if (parsed && parsed.success === false && parsed.error) {
72
+ failures.push(`${msg.name || 'tool'}: ${String(parsed.error).slice(0, 140)}`);
73
+ }
74
+ } catch (_e) {
75
+ // Non-JSON tool output carries no structured verdict; skip it.
76
+ }
77
+ }
78
+ }
79
+
80
+ const parts: string[] = [];
81
+ if (userTurns.length > 0) {
82
+ parts.push(`Requests in this segment: ${userTurns.slice(0, 3).join(' | ')}`);
83
+ }
84
+ if (toolCounts.size > 0) {
85
+ const tools = [...toolCounts.entries()]
86
+ .sort((a, b) => b[1] - a[1])
87
+ .slice(0, 10)
88
+ .map(([name, count]) => `${name}x${count}`)
89
+ .join(', ');
90
+ parts.push(`Tools used: ${tools}`);
91
+ }
92
+ if (touchedPaths.size > 0) {
93
+ parts.push(`Files touched: ${[...touchedPaths].slice(0, 12).join(', ')}`);
94
+ }
95
+ if (failures.length > 0) {
96
+ parts.push(`Failures encountered: ${failures.slice(0, 4).join(' | ')}`);
97
+ }
98
+
99
+ return parts.length > 0 ? parts.join('. ') : '';
100
+ }
101
+
102
+ /**
103
+ * Condense dropped messages into Cortex memory.
104
+ */
105
+ export async function condenseAndSave(
106
+ droppedMessages: any[],
107
+ llm: any = null,
108
+ tokenTracker: any = null,
109
+ options: CondenserOptions = {}
110
+ ): Promise<CondenserResult> {
111
+ const result: CondenserResult = { structural: false, semantic: false };
112
+ if (!droppedMessages || droppedMessages.length === 0) return result;
113
+
114
+ // ---- Tier 1: always-on, zero cost -------------------------------------
115
+ try {
116
+ const structural = buildStructuralSummary(droppedMessages);
117
+ if (structural) {
118
+ await cortexDb.saveCondensedMemory(structural);
119
+ result.structural = true;
120
+ }
121
+ } catch (e: any) {
122
+ debugLog(`[Auto-Condenser] Structural condensation failed: ${e.message}`);
123
+ }
124
+
125
+ // ---- Tier 2: gated semantic pass --------------------------------------
126
+ if (!llm || options.enableLlmPass === false) return result;
127
+
128
+ const maxPasses = Number.isInteger(options.maxLlmPasses)
129
+ ? (options.maxLlmPasses as number)
130
+ : DEFAULT_MAX_LLM_PASSES_PER_TASK;
131
+ if ((options.passesUsed || 0) >= maxPasses) return result;
132
+
133
+ let conversationText = droppedMessages.map((m: any) => {
134
+ let content = serialiseContent(m.content);
135
+ if (content.length > 2000) content = content.slice(0, 2000) + ' …[truncated]';
136
+ return `${String(m.role || '').toUpperCase()}: ${content}`;
137
+ }).join('\n\n');
138
+
139
+ if (conversationText.length < MIN_CHARS_FOR_LLM_PASS) return result;
140
+
141
+ if (conversationText.length > MAX_CONDENSE_CHARS) {
142
+ conversationText = conversationText.slice(-MAX_CONDENSE_CHARS);
143
+ }
144
+
145
+ try {
146
+ const prompt = `You are an AI Memory Condenser for an autonomous agent.
147
+ Below is a chunk of an older conversation between the User and the Assistant that is being pushed out of the short-term memory window due to length constraints.
148
+ Your task is to summarize the KEY FACTS, DECISIONS, or OUTCOMES from this conversation snippet into 1-3 concise bullet points.
149
+ - Do NOT include pleasantries, filler, or transient errors that were immediately fixed.
150
+ - Only include structural knowledge, architectural decisions, and final outcomes that the agent might need later.
151
+ - If there is nothing permanently useful in this chunk, reply with exactly: SKIP
152
+
153
+ Conversation Snippet:
154
+ ${conversationText}
155
+
156
+ Provide only the bullet points.`;
157
+
158
+ const response = await llm.chat([{ role: 'user', content: prompt }], {
159
+ temperature: 0.1,
160
+ maxTokens: 400
161
+ });
162
+
163
+ if (tokenTracker && response && response.usage) {
164
+ await tokenTracker.trackUsage(
165
+ response.usage.promptTokens || 0,
166
+ response.usage.completionTokens || 0,
167
+ null,
168
+ response.usage
169
+ );
170
+ }
171
+
172
+ if (response && response.content) {
173
+ const summary = String(response.content).trim();
174
+ if (summary && summary !== 'SKIP' && summary.length > 10) {
175
+ await cortexDb.saveCondensedMemory(summary);
176
+ result.semantic = true;
177
+ }
178
+ }
179
+ } catch (e: any) {
180
+ debugLog(`[Auto-Condenser] Semantic condensation failed: ${e.message}`);
181
+ }
182
+
183
+ return result;
184
+ }
185
+