@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
@@ -0,0 +1,473 @@
1
+ import fs from 'node:fs';
2
+ import crypto from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { causyneHome } from '../utils/paths.js';
5
+ import {
6
+ openCortexDatabase,
7
+ computeNativeEmbedding,
8
+ computeSimilarityScore,
9
+ readExtendedMemoryStats,
10
+ type CortexDatabase
11
+ } from './cortexEngine.js';
12
+
13
+ // Diagnostics, off by default: console output during a turn overwrites the
14
+ // prompt's live region. See src/cortex/provisioner.js for the full reason.
15
+ function debugLog(message: string): void {
16
+ if (process.env.CAUSYNE_DEBUG !== '1') return;
17
+ process.stderr.write(`[causyne] ${message}\n`);
18
+ }
19
+
20
+ const CORTEX_DIR = causyneHome();
21
+ const CORTEX_DB_FILE = path.join(CORTEX_DIR, 'cortex.db');
22
+
23
+ /**
24
+ * How long a memory keeps half its weight. Thirty days.
25
+ *
26
+ * A lesson from last week is usually about the code as it is now; one from
27
+ * March is usually about code that no longer exists. Decay does not delete it —
28
+ * it just stops an ancient memory outranking a recent one on a tie.
29
+ */
30
+ const RECENCY_HALF_LIFE_MS = 30 * 24 * 60 * 60 * 1000;
31
+
32
+ /**
33
+ * OBLIVION adaptive memory stability constants:
34
+ * S = BASE_HALF_LIFE * (1 + hits * REINFORCEMENT_ALPHA) * tierMultiplier
35
+ * R = e^(-t/S) — adaptive retention that rewards retrieved memories with slower decay
36
+ */
37
+ const REINFORCEMENT_ALPHA = 0.2;
38
+
39
+ const TIER_MULTIPLIERS: Record<string, number> = {
40
+ condensed: 2.0, // L1: Topic summaries persist longer
41
+ creative: 1.5, // L2: Creative successes are valuable
42
+ mistake: 1.0 // L3: Mistakes decay normally unless reinforced
43
+ };
44
+
45
+ /** Similarity below this is noise, whatever the recency. */
46
+ const MIN_SIMILARITY = 0.18;
47
+
48
+ /** Rows scored per search. Beyond this the newest win, so search stays O(1)-ish. */
49
+ const MAX_CANDIDATES = 500;
50
+
51
+ /** Ceiling on stored memories per workspace before the oldest are retired. */
52
+ const MAX_MEMORIES_PER_WORKSPACE = 2000;
53
+
54
+ /**
55
+ * Common continuation, affirmation, or trivial words that must NEVER trigger
56
+ * historical memory injection. Searching Cortex on "continue" or "next" is what
57
+ * caused catastrophic task hijacking hallucinations (e.g. Suika project bug).
58
+ */
59
+ const CONTINUATION_WORDS_PATTERN = /^(continue|next|proceed|ok|go|fix|retry|more|run|yes|y|lanjut|teruskan|buka|open|open it)\b/i;
60
+
61
+ /**
62
+ * Evaluates whether a prompt carries substantive task content eligible for Cortex retrieval.
63
+ */
64
+ export function isSearchablePrompt(prompt: unknown): boolean {
65
+ if (typeof prompt !== 'string') return false;
66
+ const trimmed = prompt.trim();
67
+ if (trimmed.length < 15) return false;
68
+ if (CONTINUATION_WORDS_PATTERN.test(trimmed) && trimmed.length < 30) return false;
69
+ return true;
70
+ }
71
+
72
+ /** The dedup key: same lesson, same row, however many times it is learned. */
73
+ function fingerprintOf(text: string): string {
74
+ const normalised = String(text || '').toLowerCase().replace(/\s+/g, ' ').trim();
75
+ return crypto.createHash('sha256').update(normalised).digest('hex').slice(0, 32);
76
+ }
77
+
78
+ /** Type as a COLUMN, not as a prefix a LIKE has to scan for. */
79
+ function kindOf(text: string): string {
80
+ const value = String(text || '');
81
+ if (value.startsWith('CREATIVE SUCCESS:')) return 'creative';
82
+ if (value.startsWith('[PAST MISTAKE')) return 'mistake';
83
+ return 'condensed';
84
+ }
85
+
86
+ export interface StoredMemoryRow {
87
+ id: string;
88
+ text: string;
89
+ embedding_vector: string;
90
+ timestamp: number;
91
+ workspace: string;
92
+ kind: string;
93
+ fingerprint: string | null;
94
+ hits: number;
95
+ }
96
+
97
+ export interface ScoredMemory {
98
+ id: string;
99
+ text: string;
100
+ kind: string;
101
+ timestamp: number;
102
+ hits: number;
103
+ similarity: number;
104
+ retention: number;
105
+ score: number;
106
+ }
107
+
108
+ export interface UpsertMemoryOptions {
109
+ workspace?: string;
110
+ kind?: string | null;
111
+ searchableText?: string | null;
112
+ }
113
+
114
+ export interface CreativePattern {
115
+ project: string;
116
+ designApproach: string;
117
+ colorPalette: string;
118
+ fonts: string;
119
+ }
120
+
121
+ export class VectorDB {
122
+ public extractor: null = null;
123
+ public isInitialized: boolean = false;
124
+ public isNeural: boolean = false;
125
+ public db: CortexDatabase | null = null;
126
+
127
+ async ensureDb(): Promise<void> {
128
+ if (this.db) return;
129
+
130
+ if (!fs.existsSync(CORTEX_DIR)) {
131
+ fs.mkdirSync(CORTEX_DIR, { recursive: true, mode: 0o700 });
132
+ }
133
+
134
+ this.db = await openCortexDatabase(CORTEX_DB_FILE);
135
+
136
+ // Create the task_memories table if it doesn't exist
137
+ // embedding_vector is stored as a JSON string array of floats
138
+ this.db.exec(`
139
+ CREATE TABLE IF NOT EXISTS task_memories (
140
+ id TEXT PRIMARY KEY,
141
+ text TEXT NOT NULL,
142
+ embedding_vector TEXT NOT NULL,
143
+ timestamp INTEGER NOT NULL
144
+ )
145
+ `);
146
+
147
+ this.migrateSchema();
148
+ }
149
+
150
+ /**
151
+ * Bring an existing store up to the current schema, additively.
152
+ */
153
+ migrateSchema(): void {
154
+ if (!this.db) return;
155
+ const columns = new Set(this.db.prepare('PRAGMA table_info(task_memories)').all().map((c: any) => c.name));
156
+
157
+ if (!columns.has('workspace')) this.db.exec("ALTER TABLE task_memories ADD COLUMN workspace TEXT DEFAULT ''");
158
+ if (!columns.has('kind')) this.db.exec("ALTER TABLE task_memories ADD COLUMN kind TEXT DEFAULT 'mistake'");
159
+ if (!columns.has('fingerprint')) this.db.exec('ALTER TABLE task_memories ADD COLUMN fingerprint TEXT');
160
+ if (!columns.has('hits')) this.db.exec('ALTER TABLE task_memories ADD COLUMN hits INTEGER DEFAULT 0');
161
+
162
+ // Backfill derived columns for legacy rows
163
+ const stale = this.db.prepare('SELECT id, text FROM task_memories WHERE fingerprint IS NULL').all();
164
+ if (stale.length > 0) {
165
+ const setRow = this.db.prepare('UPDATE task_memories SET fingerprint = ?, kind = ? WHERE id = ?');
166
+ const run = this.db.transaction((rows: any[]) => {
167
+ for (const row of rows) setRow.run(fingerprintOf(row.text), kindOf(row.text), row.id);
168
+ });
169
+ run(stale);
170
+ }
171
+
172
+ // Collapse legacy duplicates
173
+ const groups = this.db.prepare(
174
+ `SELECT fingerprint, workspace, COUNT(*) c FROM task_memories
175
+ WHERE fingerprint IS NOT NULL
176
+ GROUP BY fingerprint, workspace HAVING c > 1`
177
+ ).all();
178
+
179
+ if (groups.length > 0) {
180
+ const db = this.db;
181
+ const collapse = db.transaction((rows: any[]) => {
182
+ for (const group of rows) {
183
+ const copies = db.prepare(
184
+ `SELECT id, hits FROM task_memories
185
+ WHERE fingerprint = ? AND workspace = ? ORDER BY timestamp DESC`
186
+ ).all(group.fingerprint, group.workspace);
187
+
188
+ const keep = copies[0];
189
+ if (!keep) continue;
190
+ const totalHits = copies.reduce((sum: number, row: any) => sum + (row.hits || 0), 0);
191
+ db.prepare('UPDATE task_memories SET hits = ? WHERE id = ?').run(totalHits, keep.id);
192
+ for (const row of copies.slice(1)) {
193
+ db.prepare('DELETE FROM task_memories WHERE id = ?').run(row.id);
194
+ }
195
+ }
196
+ });
197
+ collapse(groups);
198
+ debugLog(`[CORTEX] collapsed ${groups.length} duplicate group(s)`);
199
+ }
200
+
201
+ // Indices for instant lookup
202
+ this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_ws_time ON task_memories(workspace, timestamp DESC)');
203
+ this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_kind ON task_memories(kind, timestamp DESC)');
204
+ this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_fingerprint ON task_memories(fingerprint, workspace)');
205
+ }
206
+
207
+ async init(): Promise<void> {
208
+ if (this.isInitialized) return;
209
+ await this.ensureDb();
210
+ this.extractor = null;
211
+ this.isNeural = false;
212
+ this.isInitialized = true;
213
+ }
214
+
215
+ async embed(text: string): Promise<number[]> {
216
+ if (!this.isInitialized) await this.init();
217
+ return computeNativeEmbedding(text);
218
+ }
219
+
220
+ cosineSimilarity(vecA: number[], vecB: number[]): number {
221
+ let dotProduct = 0;
222
+ let normA = 0;
223
+ let normB = 0;
224
+ const len = Math.min(vecA.length, vecB.length);
225
+ for (let i = 0; i < len; i++) {
226
+ const a = vecA[i] ?? 0;
227
+ const b = vecB[i] ?? 0;
228
+ dotProduct += a * b;
229
+ normA += a * a;
230
+ normB += b * b;
231
+ }
232
+ if (normA === 0 || normB === 0) return 0;
233
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
234
+ }
235
+
236
+ /**
237
+ * A mistake and how it was recovered from. Scoped to the project it happened in.
238
+ */
239
+ async saveMemory(
240
+ taskGoal: string,
241
+ errorEncountered: string,
242
+ resolution: string,
243
+ workspace: string = process.cwd()
244
+ ): Promise<{ id: string; created: boolean }> {
245
+ const searchableText = `Goal: ${taskGoal}\nError: ${errorEncountered}`;
246
+ const fullText = `[PAST MISTAKE RECOVERED]\nGoal: ${taskGoal}\nError: ${errorEncountered}\nResolution: ${resolution}`;
247
+ const result = await this.upsertMemory(fullText, { workspace, kind: 'mistake', searchableText });
248
+ debugLog(`[CORTEX] mistake ${result.created ? 'recorded' : 'reinforced'}`);
249
+ return result;
250
+ }
251
+
252
+ /** A condensed run of chat history, kept against the project it summarises. */
253
+ async saveCondensedMemory(
254
+ summaryText: string,
255
+ workspace: string = process.cwd()
256
+ ): Promise<{ id: string; created: boolean }> {
257
+ const fullText = `[CONDENSED CHAT HISTORY]\n${summaryText}`;
258
+ return this.upsertMemory(fullText, { workspace, kind: 'condensed' });
259
+ }
260
+
261
+ async search(
262
+ queryText: string,
263
+ topK: number = 3,
264
+ options: { workspace?: string } = {}
265
+ ): Promise<ScoredMemory[]> {
266
+ // Guard against continuation / short queries to prevent task hijacking hallucinations
267
+ if (!isSearchablePrompt(queryText)) {
268
+ return [];
269
+ }
270
+
271
+ await this.ensureDb();
272
+ if (!this.db) return [];
273
+
274
+ const workspace = String(options.workspace ?? process.cwd() ?? '');
275
+ const rows: StoredMemoryRow[] = this.db.prepare(
276
+ `SELECT id, text, embedding_vector, timestamp, kind, hits
277
+ FROM task_memories
278
+ WHERE workspace = ? OR workspace = ''
279
+ ORDER BY timestamp DESC
280
+ LIMIT ?`
281
+ ).all(workspace, MAX_CANDIDATES);
282
+
283
+ if (rows.length === 0) return [];
284
+
285
+ const queryEmbedding = await this.embed(queryText);
286
+ const now = Date.now();
287
+
288
+ const scored: ScoredMemory[] = [];
289
+ for (const memory of rows) {
290
+ let similarity: number;
291
+ try {
292
+ const memVec = JSON.parse(memory.embedding_vector);
293
+ similarity = computeSimilarityScore(queryEmbedding, memVec, queryText, memory.text, Boolean(this.isNeural));
294
+ } catch (_e) {
295
+ continue; // a corrupt vector is skipped, never fatal
296
+ }
297
+ if (similarity <= MIN_SIMILARITY) continue;
298
+
299
+ const ageMs = Math.max(0, now - (memory.timestamp || 0));
300
+ // OBLIVION: S = BASE_HALF_LIFE * (1 + hits * REINFORCEMENT_ALPHA) * tierMultiplier
301
+ // R = e^(-t/S) — adaptive retention that rewards reinforced memories with slower decay
302
+ const tierMult = TIER_MULTIPLIERS[memory.kind] ?? 1.0;
303
+ const stability = Math.max(1, RECENCY_HALF_LIFE_MS * (1 + (memory.hits || 0) * REINFORCEMENT_ALPHA) * tierMult);
304
+ const retention = Math.exp(-ageMs / stability);
305
+ scored.push({
306
+ id: memory.id,
307
+ text: memory.text,
308
+ kind: memory.kind,
309
+ timestamp: memory.timestamp,
310
+ hits: memory.hits || 0,
311
+ similarity,
312
+ retention,
313
+ score: similarity * retention
314
+ });
315
+ }
316
+
317
+ scored.sort((a, b) => b.score - a.score);
318
+ const matches = scored.slice(0, topK);
319
+
320
+ // Reinforce retrieved memories: incrementing hits increases memory stability S
321
+ if (matches.length > 0) {
322
+ try {
323
+ const bump = this.db.prepare('UPDATE task_memories SET hits = hits + 1 WHERE id = ?');
324
+ const run = this.db.transaction((ids: string[]) => { for (const id of ids) bump.run(id); });
325
+ run(matches.map(m => m.id));
326
+ } catch (_e) { /* telemetry must never fail a retrieval */ }
327
+ }
328
+
329
+ return matches;
330
+ }
331
+
332
+ /**
333
+ * Write a memory, or refresh the one that already says this.
334
+ */
335
+ async upsertMemory(
336
+ text: string,
337
+ { workspace = '', kind = null, searchableText = null }: UpsertMemoryOptions = {}
338
+ ): Promise<{ id: string; created: boolean }> {
339
+ await this.ensureDb();
340
+ if (!this.db) throw new Error('Database not initialized');
341
+
342
+ const fingerprint = fingerprintOf(text);
343
+ const scope = String(workspace || '');
344
+
345
+ const existing = this.db.prepare(
346
+ 'SELECT id FROM task_memories WHERE fingerprint = ? AND workspace = ?'
347
+ ).get(fingerprint, scope);
348
+
349
+ if (existing) {
350
+ this.db.prepare('UPDATE task_memories SET timestamp = ?, hits = hits + 1 WHERE id = ?')
351
+ .run(Date.now(), existing.id);
352
+ debugLog(`[CORTEX] memory reinforced rather than duplicated: ${fingerprint.slice(0, 8)}`);
353
+ return { id: existing.id, created: false };
354
+ }
355
+
356
+ const embedding = await this.embed(searchableText || text);
357
+ const id = `mem_${Date.now()}_${crypto.randomBytes(3).toString('hex')}`;
358
+
359
+ this.db.prepare(
360
+ `INSERT INTO task_memories (id, text, embedding_vector, timestamp, workspace, kind, fingerprint, hits)
361
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0)`
362
+ ).run(id, text, JSON.stringify(embedding), Date.now(), scope, kind || kindOf(text), fingerprint);
363
+
364
+ this.pruneWorkspace(scope);
365
+ return { id, created: true };
366
+ }
367
+
368
+ /**
369
+ * Retire the least useful memories once a workspace passes its ceiling.
370
+ */
371
+ pruneWorkspace(workspace: string, max: number = MAX_MEMORIES_PER_WORKSPACE): number {
372
+ if (!this.db) return 0;
373
+ try {
374
+ const { c } = this.db.prepare('SELECT COUNT(*) c FROM task_memories WHERE workspace = ?').get(workspace);
375
+ if (c <= max) return 0;
376
+ const result = this.db.prepare(
377
+ `DELETE FROM task_memories WHERE id IN (
378
+ SELECT id FROM task_memories WHERE workspace = ?
379
+ ORDER BY hits ASC, timestamp ASC LIMIT ?
380
+ )`
381
+ ).run(workspace, c - max);
382
+ return result.changes;
383
+ } catch (_e) {
384
+ return 0;
385
+ }
386
+ }
387
+
388
+ /** Everything stored, for `/cortex`. Vectors excluded — they are unreadable. */
389
+ async inventory(options: { workspace?: string } = {}): Promise<any[]> {
390
+ await this.ensureDb();
391
+ if (!this.db) return [];
392
+ const workspace = options.workspace;
393
+ const rows = workspace
394
+ ? this.db.prepare(
395
+ `SELECT id, text, kind, timestamp, hits, workspace FROM task_memories
396
+ WHERE workspace = ? OR workspace = '' ORDER BY timestamp DESC LIMIT 200`
397
+ ).all(String(workspace))
398
+ : this.db.prepare(
399
+ 'SELECT id, text, kind, timestamp, hits, workspace FROM task_memories ORDER BY timestamp DESC LIMIT 200'
400
+ ).all();
401
+ return rows;
402
+ }
403
+
404
+ /** Counts, for a one-line answer to "is my digital brain actually on?". */
405
+ async stats(): Promise<{
406
+ total: number;
407
+ distinct: number;
408
+ byKind: Array<{ kind: string; c: number }>;
409
+ workspaces: number;
410
+ newest: number;
411
+ isNeural: boolean;
412
+ engineType: string;
413
+ episodicCount: number;
414
+ factsCount: number;
415
+ }> {
416
+ await this.ensureDb();
417
+ if (!this.db) throw new Error('Database not initialized');
418
+ const total = this.db.prepare('SELECT COUNT(*) c FROM task_memories').get().c;
419
+ const byKind = this.db.prepare('SELECT kind, COUNT(*) c FROM task_memories GROUP BY kind').all();
420
+ const workspaces = this.db.prepare("SELECT COUNT(DISTINCT workspace) c FROM task_memories WHERE workspace != ''").get().c;
421
+ const newest = this.db.prepare('SELECT MAX(timestamp) t FROM task_memories').get().t || 0;
422
+ const distinct = this.db.prepare('SELECT COUNT(DISTINCT fingerprint) c FROM task_memories').get().c;
423
+ const extended = readExtendedMemoryStats();
424
+ return {
425
+ total,
426
+ distinct,
427
+ byKind,
428
+ workspaces,
429
+ newest,
430
+ isNeural: Boolean(this.isNeural),
431
+ engineType: 'native (semantic vector + sqlite)',
432
+ episodicCount: extended.episodicCount,
433
+ factsCount: extended.factsCount
434
+ };
435
+ }
436
+
437
+ /** Forget one memory, or every memory in a workspace. */
438
+ async forget({ id = null, workspace = null }: { id?: string | null; workspace?: string | null } = {}): Promise<number> {
439
+ await this.ensureDb();
440
+ if (!this.db) return 0;
441
+ if (id) return this.db.prepare('DELETE FROM task_memories WHERE id = ?').run(id).changes;
442
+ if (workspace !== null) {
443
+ return this.db.prepare('DELETE FROM task_memories WHERE workspace = ?').run(String(workspace)).changes;
444
+ }
445
+ return 0;
446
+ }
447
+
448
+ /**
449
+ * A design approach that worked, so the next one deliberately differs.
450
+ */
451
+ async saveCreativePattern(pattern: CreativePattern): Promise<{ id: string; created: boolean }> {
452
+ const text = `CREATIVE SUCCESS: Built "${pattern.project}" using ${pattern.designApproach} style. Colors: ${pattern.colorPalette}. Fonts: ${pattern.fonts}.`;
453
+ const result = await this.upsertMemory(text, { workspace: '', kind: 'creative' });
454
+ debugLog(`[CORTEX] creative pattern ${result.created ? 'saved' : 'reinforced'}: ${pattern.designApproach}`);
455
+ return result;
456
+ }
457
+
458
+ // Anti-Slop: Retrieve recent creative patterns for the "DO NOT REPEAT" directive
459
+ async getRecentCreativePatterns(limit: number = 5): Promise<string[]> {
460
+ await this.ensureDb();
461
+ if (!this.db) return [];
462
+ try {
463
+ const results = this.db.prepare(
464
+ 'SELECT text FROM task_memories WHERE kind = ? ORDER BY timestamp DESC LIMIT ?'
465
+ ).all('creative', limit);
466
+ return results.map((r: any) => r.text);
467
+ } catch (_e) {
468
+ return [];
469
+ }
470
+ }
471
+ }
472
+
473
+ export const cortexDb = new VectorDB();
package/src/reporting.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { TOOL_DEFINITIONS } from './tools/registry.js';
4
4
  import { CORE_TOOLS, PACKS, PACK_PLAYBOOKS } from './toolPacks.js';
5
- import { resolveCharPool } from './contextManager.js';
5
+ import { resolveCharPool, resolveModelContextTokens } from './contextManager.js';
6
6
  import { TokenTracker } from './tokenTracker.js';
7
7
  import { loadConfig } from './config.js';
8
8
  import { listSpills, getOutputDir } from './outputStore.js';
@@ -53,7 +53,23 @@ function schemaTokens(names) {
53
53
  export function buildContextReport() {
54
54
  const config = loadConfig();
55
55
  const tier = config.tier || 'premium';
56
- const charPool = resolveCharPool(tier, config.contextCharPool);
56
+ const provider = config.provider || 'default';
57
+ const model = config.model || 'default';
58
+ const charPool = resolveCharPool(tier, config.contextCharPool, {
59
+ provider,
60
+ model,
61
+ overrideTokens: config.contextTokens || config.maxContextTokens
62
+ });
63
+
64
+ const modelTokens = resolveModelContextTokens({
65
+ provider,
66
+ model,
67
+ overrideTokens: config.contextTokens || config.maxContextTokens
68
+ });
69
+
70
+ const approxTokenPool = modelTokens > 0
71
+ ? modelTokens
72
+ : Math.round(charPool / APPROX_CHARS_PER_TOKEN);
57
73
 
58
74
  const packs = Object.entries(PACKS).map(([name, tools]) => ({
59
75
  name,
@@ -66,10 +82,10 @@ export function buildContextReport() {
66
82
 
67
83
  return {
68
84
  tier,
69
- provider: config.provider || 'default',
70
- model: config.model || 'default',
85
+ provider,
86
+ model,
71
87
  charPool,
72
- approxTokenPool: Math.round(charPool / APPROX_CHARS_PER_TOKEN),
88
+ approxTokenPool,
73
89
  core: { tools: CORE_TOOLS.length, tokens: schemaTokens(CORE_TOOLS) },
74
90
  packs,
75
91
  allTools: TOOL_DEFINITIONS.length,
@@ -124,7 +140,14 @@ export async function buildUsageText() {
124
140
  const budget = config.tokenBudget || {};
125
141
  const lines = [];
126
142
 
127
- lines.push('Token usage (BYOK — billed by your provider, not by Causyne)');
143
+ const provider = config.provider || 'default';
144
+ const isAgy = isAntigravityProvider(provider);
145
+ const isAcp = isAcpProvider(provider);
146
+ const billingNote = (isAgy || isAcp)
147
+ ? '(Local CLI / ACP peer)'
148
+ : '(BYOK — billed by your provider, not by Causyne)';
149
+
150
+ lines.push(`Token usage ${billingNote}`);
128
151
  lines.push(` Provider / model : ${config.provider || 'default'} / ${config.model || 'default'}`);
129
152
  lines.push(` This task : ${formatNumber(usage.taskTokens)} tokens $${Number(usage.taskCostUsd || 0).toFixed(4)}`);
130
153
  lines.push(` Today : ${formatNumber(usage.dailyTokens)} tokens $${Number(usage.costUsd || 0).toFixed(4)}`);
@@ -215,7 +238,7 @@ export function printCheckpoints(limit = 15) {
215
238
  * here, in one place, and each surface renders the single result it is given.
216
239
  */
217
240
  function runUndo(taskId, options = {}) {
218
- const opts = { dryRun: options.dryRun, full: options.full };
241
+ const opts = { dryRun: options.dryRun, full: options.full, workspaceRoot: options.workspaceRoot };
219
242
  return options.step
220
243
  ? undoStep({ dryRun: options.dryRun })
221
244
  : (taskId ? undoTask(taskId, opts) : undoLast(opts));
@@ -489,6 +489,19 @@ export function restoreSessionFromSnapshot(file, snapshot) {
489
489
  return false;
490
490
  }
491
491
  }
492
+ export function renameSession(id, newTitle) {
493
+ const session = readSession(id);
494
+ const cleanTitle = String(newTitle ?? '').trim();
495
+ if (!session || !cleanTitle)
496
+ return false;
497
+ return appendEvent(sessionTranscriptFile(session.id), {
498
+ version: 1,
499
+ type: 'messages.replaced',
500
+ at: Date.now(),
501
+ messages: session.messages,
502
+ title: cleanTitle
503
+ });
504
+ }
492
505
  export function deleteSession(id) {
493
506
  const safe = safeSessionId(id);
494
507
  if (!safe)
@@ -537,6 +537,19 @@ export function restoreSessionFromSnapshot(file: string, snapshot: Buffer): bool
537
537
  }
538
538
  }
539
539
 
540
+ export function renameSession(id: unknown, newTitle: string): boolean {
541
+ const session = readSession(id);
542
+ const cleanTitle = String(newTitle ?? '').trim();
543
+ if (!session || !cleanTitle) return false;
544
+ return appendEvent(sessionTranscriptFile(session.id), {
545
+ version: 1,
546
+ type: 'messages.replaced',
547
+ at: Date.now(),
548
+ messages: session.messages,
549
+ title: cleanTitle
550
+ });
551
+ }
552
+
540
553
  export function deleteSession(id: unknown): boolean {
541
554
  const safe = safeSessionId(id);
542
555
  if (!safe) return false;
@@ -24,12 +24,16 @@ export class TokenTracker {
24
24
  budget;
25
25
  taskTokens;
26
26
  taskCostUsd;
27
+ sessionTokens;
28
+ sessionCostUsd;
27
29
  largestStepTokens;
28
30
  constructor() {
29
31
  this.config = loadConfig();
30
32
  this.budget = this.config.tokenBudget || { enabled: false };
31
33
  this.taskTokens = 0;
32
34
  this.taskCostUsd = 0;
35
+ this.sessionTokens = 0;
36
+ this.sessionCostUsd = 0;
33
37
  this.largestStepTokens = 0;
34
38
  this.ensureUsageDir();
35
39
  }
@@ -178,7 +182,9 @@ export class TokenTracker {
178
182
  const cost = unitPrice * (quantityUnits || 1);
179
183
  const equivalentTokens = Math.round(cost / 0.000002);
180
184
  this.taskTokens += equivalentTokens;
185
+ this.sessionTokens = (this.sessionTokens || 0) + equivalentTokens;
181
186
  this.taskCostUsd += cost;
187
+ this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
182
188
  const cumulative = await this.getCumulativeUsage();
183
189
  const daily = await this.getDailyUsage();
184
190
  daily.totalTokens += equivalentTokens;
@@ -313,9 +319,11 @@ export class TokenTracker {
313
319
  usedTokens: daily.totalTokens,
314
320
  dailyTokens: daily.totalTokens,
315
321
  taskTokens: this.taskTokens,
322
+ sessionTokens: this.sessionTokens || this.taskTokens || 0,
316
323
  lifetimeTokens: cumulative.totalTokens,
317
324
  costUsd: daily.totalCostUsd,
318
325
  taskCostUsd: this.taskCostUsd,
326
+ sessionCostUsd: this.sessionCostUsd || this.taskCostUsd || 0,
319
327
  lifetimeCostUsd: cumulative.totalCostUsd,
320
328
  isDemo: false
321
329
  };
@@ -351,12 +359,24 @@ export class TokenTracker {
351
359
  this.taskCostUsd = 0;
352
360
  this.largestStepTokens = 0;
353
361
  }
362
+ resetSession() {
363
+ this.sessionTokens = 0;
364
+ this.sessionCostUsd = 0;
365
+ this.taskTokens = 0;
366
+ this.taskCostUsd = 0;
367
+ this.largestStepTokens = 0;
368
+ }
369
+ reset() {
370
+ this.resetSession();
371
+ }
354
372
  settle(extra, daily, cumulative) {
355
373
  return {
356
374
  usedTokens: daily.totalTokens,
357
375
  dailyTokens: daily.totalTokens,
358
376
  dailyCostUsd: daily.totalCostUsd || 0,
359
377
  dailyLimit: Number(this.budget && this.budget.maxTokensPerDay) || 0,
378
+ sessionTokens: this.sessionTokens || this.taskTokens || 0,
379
+ sessionCostUsd: this.sessionCostUsd || this.taskCostUsd || 0,
360
380
  taskTokens: this.taskTokens,
361
381
  taskCostUsd: this.taskCostUsd,
362
382
  taskLimit: Number(this.budget && this.budget.maxTokensPerTask) || 0,
@@ -393,9 +413,11 @@ export class TokenTracker {
393
413
  }
394
414
  const freshStep = freshInput + cTokens;
395
415
  this.taskTokens += freshStep;
416
+ this.sessionTokens = (this.sessionTokens || 0) + freshStep;
396
417
  this.largestStepTokens = Math.max(this.largestStepTokens || 0, freshStep);
397
418
  const cost = this.calculateCost(promptTokens, completionTokens, usageDetail);
398
419
  this.taskCostUsd += cost;
420
+ this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
399
421
  const { daily, cumulative } = await withUsageLock(async () => {
400
422
  const cumulative = await this.getCumulativeUsage();
401
423
  const daily = await this.getDailyUsage();