coding-agent-search 0.5.0

Unified TUI search over local coding agent histories
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/**
 * cass Archive Session Management
 *
 * Handles session lifecycle, key storage, and activity monitoring.
 * Balances security with usability by supporting multiple storage options.
 */

import { getArchiveScopeId } from './storage.js';

// Session configuration
export const SESSION_CONFIG = {
    // Default session duration: 4 hours
    DEFAULT_DURATION_MS: 4 * 60 * 60 * 1000,

    // Warning before expiry: 5 minutes
    WARNING_BEFORE_MS: 5 * 60 * 1000,

    // Idle timeout for activity-based extension: 15 minutes
    IDLE_TIMEOUT_MS: 15 * 60 * 1000,

    // Storage options
    STORAGE_MEMORY: 'memory',       // Most secure, lost on refresh
    STORAGE_SESSION: 'session',     // Survives refresh, not tabs
    STORAGE_LOCAL: 'local',         // Persists across sessions (least secure)

    // Storage key bases
    KEY_SESSION_TOKEN: 'cass_session',
    KEY_EXPIRY: 'cass_expiry',
    KEY_STORAGE_PREF: 'cass_storage_pref',
};

function getScopedSessionKeys() {
    const scopeId = getArchiveScopeId();
    return {
        TOKEN: `${SESSION_CONFIG.KEY_SESSION_TOKEN}_${scopeId}`,
        EXPIRY: `${SESSION_CONFIG.KEY_EXPIRY}_${scopeId}`,
        STORAGE_PREF: `${SESSION_CONFIG.KEY_STORAGE_PREF}_${scopeId}`,
    };
}

function encodeBytes(bytes) {
    return btoa(String.fromCharCode(...bytes));
}

function decodeBytes(base64) {
    return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
}

function getPersistentStorages() {
    const storages = [];

    try {
        if (typeof sessionStorage !== 'undefined') {
            storages.push(sessionStorage);
        }
    } catch (error) {
        // Ignore unavailable storage backends and fall back to memory-only behavior.
    }

    try {
        if (typeof localStorage !== 'undefined') {
            storages.push(localStorage);
        }
    } catch (error) {
        // Ignore unavailable storage backends and fall back to memory-only behavior.
    }

    return storages;
}

/**
 * In-memory storage fallback
 */
class MemoryStorage {
    constructor() {
        this.data = new Map();
    }

    getItem(key) {
        return this.data.get(key) || null;
    }

    setItem(key, value) {
        this.data.set(key, value);
    }

    removeItem(key) {
        this.data.delete(key);
    }

    clear() {
        this.data.clear();
    }
}

/**
 * Session Manager
 *
 * Manages the session lifecycle, including key storage, expiry, and cleanup.
 */
export class SessionManager {
    constructor(options = {}) {
        this.duration = options.duration || SESSION_CONFIG.DEFAULT_DURATION_MS;
        this.storage = options.storage || SESSION_CONFIG.STORAGE_SESSION;
        this.onExpired = options.onExpired || (() => {});
        this.onWarning = options.onWarning || (() => {});

        this.dek = null;              // Current DEK (in memory)
        this.expiryTs = 0;            // Current session expiry timestamp
        this.persistent = false;      // Whether the session is persisted in storage
        this.expiryTimeout = null;    // Expiry timer
        this.warningTimeout = null;   // Warning timer
        this.memoryStorage = new MemoryStorage();
        this.cleanupHandlersInstalled = false;

        // Bind methods for event handlers
        this.handleVisibilityChange = this.handleVisibilityChange.bind(this);
        this.handleBeforeUnload = this.handleBeforeUnload.bind(this);
    }

    /**
     * Start a new session with the derived DEK
     * @param {Uint8Array} dek - The Data Encryption Key
     * @param {boolean} rememberMe - Whether to persist the session
     */
    async startSession(dek, rememberMe = false) {
        this.clearStorage();
        this.dek = dek;

        const expiry = Date.now() + this.duration;
        this.expiryTs = expiry;
        this.persistent = rememberMe && this.storage !== SESSION_CONFIG.STORAGE_MEMORY;

        if (this.persistent) {
            const storage = this.getStorage();
            const sessionKeys = getScopedSessionKeys();
            storage.setItem(sessionKeys.TOKEN, encodeBytes(dek));
            storage.setItem(sessionKeys.EXPIRY, expiry.toString());
        }

        // Set timers
        this.setTimers(expiry);

        // Set up cleanup handlers
        this.setupCleanupHandlers();

        console.log(`[Session] Started, expires at ${new Date(expiry).toISOString()}`);
    }

    /**
     * Attempt to restore a previous session
     * @returns {Uint8Array|null} The DEK if restored, null otherwise
     */
    async restoreSession() {
        const storage = this.getStorage();
        const sessionKeys = getScopedSessionKeys();
        const token = storage.getItem(sessionKeys.TOKEN);
        const expiry = parseInt(
            storage.getItem(sessionKeys.EXPIRY) || '0',
            10
        );

        if (!token || Date.now() > expiry) {
            console.log('[Session] No valid session to restore');
            this.clearStorage();
            return null;
        }

        try {
            const dek = decodeBytes(token);
            this.dek = dek;
            this.expiryTs = expiry;
            this.persistent = true;

            // Reset timers with remaining time
            this.setTimers(expiry);
            this.setupCleanupHandlers();

            console.log(`[Session] Restored, expires at ${new Date(expiry).toISOString()}`);
            return dek;
        } catch (error) {
            console.error('[Session] Failed to restore:', error);
            this.clearStorage();
            return null;
        }
    }

    /**
     * End the current session and cleanup
     */
    endSession() {
        console.log('[Session] Ending session');

        // Clear DEK from memory (zeroize)
        if (this.dek) {
            this.dek.fill(0);
            this.dek = null;
        }

        // Clear timers
        this.clearTimers();
        this.expiryTs = 0;
        this.persistent = false;

        // Clear storage
        this.clearStorage();

        // Remove cleanup handlers
        this.removeCleanupHandlers();
    }

    /**
     * Extend the current session
     * @param {number} additionalMs - Additional time in milliseconds
     * @returns {boolean} Whether the extension was successful
     */
    extendSession(additionalMs = null) {
        if (!this.dek) {
            console.warn('[Session] No active session to extend');
            return false;
        }

        const extension = additionalMs || this.duration;
        const storage = this.getStorage();

        // Calculate new expiry
        const sessionKeys = getScopedSessionKeys();
        const currentExpiry = this.expiryTs || parseInt(storage.getItem(sessionKeys.EXPIRY) || '0', 10);
        const newExpiry = Math.max(Date.now(), currentExpiry) + extension;
        this.expiryTs = newExpiry;

        // Update storage
        if (this.persistent) {
            storage.setItem(sessionKeys.EXPIRY, newExpiry.toString());
        }

        // Reset timers
        this.setTimers(newExpiry);

        console.log(`[Session] Extended to ${new Date(newExpiry).toISOString()}`);
        return true;
    }

    /**
     * Get the current DEK
     * @returns {Uint8Array|null}
     */
    getDek() {
        return this.dek;
    }

    /**
     * Check if a session is active
     * @returns {boolean}
     */
    isActive() {
        return this.dek !== null;
    }

    /**
     * Get remaining session time in milliseconds
     * @returns {number}
     */
    getRemainingTime() {
        return Math.max(0, this.expiryTs - Date.now());
    }

    /**
     * Set expiry and warning timers
     */
    setTimers(expiry) {
        this.clearTimers();

        const remaining = expiry - Date.now();

        // Expiry timer
        if (remaining > 0) {
            this.expiryTimeout = setTimeout(() => {
                this.endSession();
                this.onExpired();
            }, remaining);

            // Warning timer
            const warningTime = remaining - SESSION_CONFIG.WARNING_BEFORE_MS;
            if (warningTime > 0) {
                this.warningTimeout = setTimeout(() => {
                    this.onWarning(SESSION_CONFIG.WARNING_BEFORE_MS);
                }, warningTime);
            }
        }
    }

    /**
     * Clear all timers
     */
    clearTimers() {
        if (this.expiryTimeout) {
            clearTimeout(this.expiryTimeout);
            this.expiryTimeout = null;
        }
        if (this.warningTimeout) {
            clearTimeout(this.warningTimeout);
            this.warningTimeout = null;
        }
    }

    /**
     * Get the appropriate storage based on preference
     */
    getStorage() {
        switch (this.storage) {
            case SESSION_CONFIG.STORAGE_LOCAL:
                try {
                    if (typeof localStorage !== 'undefined') {
                        return localStorage;
                    }
                } catch (error) {
                    // Fall back to memory-only storage below.
                }
                return this.memoryStorage;
            case SESSION_CONFIG.STORAGE_SESSION:
                try {
                    if (typeof sessionStorage !== 'undefined') {
                        return sessionStorage;
                    }
                } catch (error) {
                    // Fall back to memory-only storage below.
                }
                return this.memoryStorage;
            case SESSION_CONFIG.STORAGE_MEMORY:
            default:
                return this.memoryStorage;
        }
    }

    /**
     * Clear all session data from storage
     */
    clearStorage() {
        const sessionKeys = getScopedSessionKeys();
        this.memoryStorage.removeItem(sessionKeys.TOKEN);
        this.memoryStorage.removeItem(sessionKeys.EXPIRY);
        for (const storage of getPersistentStorages()) {
            storage.removeItem(sessionKeys.TOKEN);
            storage.removeItem(sessionKeys.EXPIRY);
        }
    }

    /**
     * Set up cleanup handlers for page visibility and unload
     */
    setupCleanupHandlers() {
        if (this.cleanupHandlersInstalled) {
            return;
        }
        document.addEventListener('visibilitychange', this.handleVisibilityChange);
        window.addEventListener('beforeunload', this.handleBeforeUnload);
        this.cleanupHandlersInstalled = true;
    }

    /**
     * Remove cleanup handlers
     */
    removeCleanupHandlers() {
        if (!this.cleanupHandlersInstalled) {
            return;
        }
        document.removeEventListener('visibilitychange', this.handleVisibilityChange);
        window.removeEventListener('beforeunload', this.handleBeforeUnload);
        this.cleanupHandlersInstalled = false;
    }

    /**
     * Handle page visibility change
     */
    handleVisibilityChange() {
        if (document.hidden) {
            // Page is hidden - could be used to pause timers
            console.log('[Session] Page hidden');
        } else {
            // Page is visible - check session validity
            console.log('[Session] Page visible');
            const remaining = this.getRemainingTime();
            if (remaining <= 0 && this.dek) {
                this.endSession();
                this.onExpired();
            }
        }
    }

    /**
     * Handle page unload
     */
    handleBeforeUnload() {
        // Zeroize DEK on page unload for memory-only sessions
        if (this.storage === SESSION_CONFIG.STORAGE_MEMORY && this.dek) {
            this.dek.fill(0);
        }
    }
}

/**
 * Activity Monitor
 *
 * Extends session on user activity to prevent premature expiry.
 */
export class ActivityMonitor {
    constructor(sessionManager, options = {}) {
        this.session = sessionManager;
        this.idleTimeout = options.idleTimeout || SESSION_CONFIG.IDLE_TIMEOUT_MS;
        this.lastActivity = Date.now();
        this.enabled = false;

        // Bind method for event handlers
        this.onActivity = this.onActivity.bind(this);
    }

    /**
     * Start monitoring user activity
     */
    start() {
        if (this.enabled) return;

        const events = ['mousedown', 'keydown', 'scroll', 'touchstart', 'mousemove'];
        events.forEach(event => {
            document.addEventListener(event, this.onActivity, { passive: true });
        });

        this.enabled = true;
        console.log('[Activity] Monitoring started');
    }

    /**
     * Stop monitoring user activity
     */
    stop() {
        if (!this.enabled) return;

        const events = ['mousedown', 'keydown', 'scroll', 'touchstart', 'mousemove'];
        events.forEach(event => {
            document.removeEventListener(event, this.onActivity);
        });

        this.enabled = false;
        console.log('[Activity] Monitoring stopped');
    }

    /**
     * Handle user activity
     */
    onActivity() {
        const now = Date.now();

        // Extend session if user was idle
        if (now - this.lastActivity > this.idleTimeout) {
            console.log('[Activity] User returned from idle, extending session');
            this.session.extendSession();
        }

        this.lastActivity = now;
    }

    /**
     * Get time since last activity
     */
    getIdleTime() {
        return Date.now() - this.lastActivity;
    }
}

/**
 * Create a default session manager with activity monitoring
 */
export function createSessionManager(options = {}) {
    const session = new SessionManager({
        duration: options.duration || SESSION_CONFIG.DEFAULT_DURATION_MS,
        storage: options.storage || SESSION_CONFIG.STORAGE_SESSION,
        onExpired: options.onExpired,
        onWarning: options.onWarning,
    });

    const activity = new ActivityMonitor(session, {
        idleTimeout: options.idleTimeout || SESSION_CONFIG.IDLE_TIMEOUT_MS,
    });

    return { session, activity };
}

// Export default instance
export default {
    SESSION_CONFIG,
    SessionManager,
    ActivityMonitor,
    createSessionManager,
};