Repository navigation
Expand file tree
/
Copy pathContextScript.js
More file actions
563 lines (485 loc) · 17.8 KB
/
Copy pathContextScript.js
File metadata and controls
563 lines (485 loc) · 17.8 KB
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// /ContextScript.js
import { PluginRegistry } from './modules/core/PluginRegistry.js';
import { Configuration } from './modules/core/Configuration.js';
import { Settings } from './modules/core/Settings.js';
import { EventCapture } from './modules/EventCapture.js';
import { MouseRecognizer } from './modules/MouseRecognizer.js';
import { KeyboardRecognizer } from './modules/KeyboardRecognizer.js';
import { GlobalKeyRecognizer } from './modules/GlobalKeyRecognizer.js';
import { ScrollRecognizer } from './modules/ScrollRecognizer.js';
import { ClipboardRecognizer } from './modules/ClipboardRecognizer.js';
import { FormRecognizer } from './modules/FormRecognizer.js';
import { WindowRecognizer } from './modules/WindowRecognizer.js';
import { DragDropRecognizer } from './modules/DragDropRecognizer.js';
import { MediaRecognizer } from './modules/MediaRecognizer.js';
import { TouchRecognizer } from './modules/TouchRecognizer.js';
import { PointerRecognizer } from './modules/PointerRecognizer.js';
import { DeveloperRecognizer } from './modules/DeveloperRecognizer.js';
import { NavigationRecognizer } from './modules/NavigationRecognizer.js';
import { Coalescer } from './modules/Coalescer.js';
import { TextFormatter } from './modules/TextFormatter.js';
import { RecordingIndicator } from './modules/ui/RecordingIndicator.js';
import { TranscriptOutput } from './modules/ui/TranscriptOutput.js';
import { InstructionOverlay } from './modules/ui/InstructionOverlay.js';
class ContextScript {
static instance = null;
constructor() {
if (ContextScript.instance) {
return ContextScript.instance;
}
ContextScript.instance = this;
// Initialize plugin registry and register built-in plugins
this.#registry = new PluginRegistry();
this.#registerBuiltinPlugins();
// Initialize configuration after plugins are registered
this.#config = new Configuration(this.#registry);
this.#config.onCategoryChange = (category, enabled) => {
this.#handleCategoryChange(category, enabled);
};
// Initialize core modules
this.#eventCapture = new EventCapture();
this.#coalescer = new Coalescer();
this.#textFormatter = new TextFormatter(this.#registry);
this.#recordingIndicator = new RecordingIndicator();
this.#transcriptOutput = new TranscriptOutput();
this.#instructionOverlay = new InstructionOverlay();
this.#bindEventHandlers();
}
// Public API
// Configuration options
streamToConsole = true;
headless = false;
onEvent = null;
eventFilter = null;
// Access to configuration for programmatic use
get config() {
return this.#config;
}
// Format a raw event object into its display text representation.
// Returns the formatted string, or null if the event type has no formatter.
formatEvent(event) {
return this.#textFormatter.formatEvent(event);
}
// Starts recording user actions.
start() {
if (this.#isRecording) {
console.log('Already recording.');
return;
}
this.#isRecording = true;
this.#startTime = Date.now();
this.#coalescer.reset();
// Reset all registered plugins
for (const plugin of this.#registry.getAllPlugins()) {
if (plugin.reset) {
plugin.reset();
}
}
// Get event definitions only for enabled categories
const enabledCategories = this.#config.getEnabledCategories();
const eventDefs = this.#registry.getEventDefinitions(enabledCategories);
this.#eventCapture.start(eventDefs);
// Start polling for scroll if scroll category is enabled
const scrollPlugin = this.#registry.getPlugin('scroll');
if (scrollPlugin && this.#config.isEnabled('scroll')) {
scrollPlugin.startPolling();
}
// Install API hooks for developer category if enabled
const developerPlugin = this.#registry.getPlugin('developer');
if (developerPlugin && this.#config.isEnabled('developer')) {
developerPlugin.install((action) => this.#emitToCoalescer(action));
}
// Install History API interceptors for navigation category if enabled
const navigationPlugin = this.#registry.getPlugin('navigation');
if (navigationPlugin && this.#config.isEnabled('navigation')) {
navigationPlugin.install((action) => this.#emitToCoalescer(action));
}
if (!this.headless) {
this.#recordingIndicator.show();
console.log('Recording started. Press Command+Escape to end recording.');
}
}
/**
* Ends recording and optionally shows the transcript.
* @param {Object} options - End options
* @param {boolean} options.silent - If true, returns transcript without showing UI (default: false)
* @param {string} options.format - Export format: 'plaintext', 'json', 'xml', 'markdown' (default: 'plaintext')
* @returns {string} The formatted transcript
*/
end(options = {}) {
const { silent = false, format = 'plaintext' } = options;
if (!this.#isRecording) {
console.log('Not recording.');
return '';
}
this.#isRecording = false;
this.#eventCapture.stop();
// Stop polling for scroll
const scrollPlugin = this.#registry.getPlugin('scroll');
if (scrollPlugin) {
scrollPlugin.stopPolling();
}
// Uninstall API hooks for developer
const developerPlugin = this.#registry.getPlugin('developer');
if (developerPlugin) {
developerPlugin.uninstall();
}
// Uninstall History API interceptors for navigation
const navigationPlugin = this.#registry.getPlugin('navigation');
if (navigationPlugin) {
navigationPlugin.uninstall();
}
if (!this.headless) {
this.#recordingIndicator.hide();
}
this.#flushPendingEvents();
const duration = Date.now() - this.#startTime;
const events = this.#coalescer.events;
const transcript = this.#textFormatter.formatAs(events, duration, format);
if (!this.headless) {
console.log(transcript);
// Only show UI if not in silent mode
if (!silent) {
this.#transcriptOutput.show({
events,
duration,
formatter: this.#textFormatter
});
}
}
return transcript;
}
get isRecording() {
return this.#isRecording;
}
/**
* Gets the current transcript without stopping recording.
* Useful for LLM tools to peek at progress or capture after user stops via shortcut.
* @param {string} format - Export format: 'plaintext', 'json', 'xml', 'markdown' (default: 'plaintext')
* @returns {string} The formatted transcript
*/
getTranscript(format = 'plaintext') {
this.#flushPendingEvents();
const duration = Date.now() - this.#startTime;
const events = this.#coalescer.events;
return this.#textFormatter.formatAs(events, duration, format);
}
/**
* Gets the raw events array for programmatic access.
* @returns {Array} Copy of the events array
*/
getEvents() {
this.#flushPendingEvents();
return [...this.#coalescer.events];
}
/**
* Shows an instruction overlay to the user before recording.
* Useful for AI agents to display a message asking users to demonstrate an issue.
* @param {Object} options - Display options
* @param {string} options.message - Custom message to display (optional)
* @returns {Promise<{startRecording: boolean}>} Resolves with startRecording: true if user clicked Start, false if dismissed
*/
async prompt(options = {}) {
const result = await this.#instructionOverlay.show(options);
if (result.startRecording && !this.#isRecording) {
this.start();
}
return result;
}
// Private
#isRecording = false;
#startTime = 0;
#registry;
#config;
#eventCapture;
#coalescer;
#textFormatter;
#recordingIndicator;
#transcriptOutput;
#instructionOverlay;
#keydownHandler;
#shouldEmit(action) {
if (!this.eventFilter) return true;
try { return this.eventFilter(action) !== false; }
catch { return true; }
}
#emitToCoalescer(action) {
if (this.#shouldEmit(action)) {
this.#coalescer.add(action);
}
}
// Registers the built-in recognizer plugins.
#registerBuiltinPlugins() {
this.#registry.register(new MouseRecognizer());
this.#registry.register(new KeyboardRecognizer());
this.#registry.register(new GlobalKeyRecognizer());
this.#registry.register(new ScrollRecognizer());
this.#registry.register(new ClipboardRecognizer());
this.#registry.register(new FormRecognizer());
this.#registry.register(new WindowRecognizer());
this.#registry.register(new DragDropRecognizer());
this.#registry.register(new MediaRecognizer());
this.#registry.register(new TouchRecognizer());
this.#registry.register(new PointerRecognizer());
this.#registry.register(new DeveloperRecognizer());
this.#registry.register(new NavigationRecognizer());
}
// Binds the event handlers between modules.
#bindEventHandlers() {
// Route events from EventCapture to appropriate plugins
this.#eventCapture.onEvent = (type, event) => {
this.#handleEvent(type, event);
};
// Flush GlobalKeyRecognizer before adding non-globalkey events
// This ensures correct event ordering (e.g., typed keys appear before the click that interrupted them)
this.#coalescer.onBeforeAdd = (event) => {
// Don't flush for globalkey events (they come from GlobalKeyRecognizer itself)
if (event.type === 'shortcut' || event.type === 'global-type') {
return;
}
// Don't reset for developer events (console logs, errors, etc.)
// These shouldn't reset the log counter - only user-initiated events should
const developerEventTypes = [
'console_log', 'console_warn', 'console_error', 'console_info', 'console_debug',
'fetch_error', 'fetch_status', 'uncaught_error', 'unhandled_rejection', 'logs_truncated'
];
if (developerEventTypes.includes(event.type)) {
return;
}
// Flush GlobalKeyRecognizer's pending buffer
const globalKeyPlugin = this.#registry.getPlugin('globalkey');
if (globalKeyPlugin && globalKeyPlugin.flush) {
globalKeyPlugin.flush();
}
// Reset developer log counter on user events (for truncation feature)
const developerPlugin = this.#registry.getPlugin('developer');
if (developerPlugin && developerPlugin.resetLogCounter) {
developerPlugin.resetLogCounter();
}
};
// Route actions from coalescer to formatter for streaming output and token counting
this.#coalescer.onEvent = (event) => {
const line = this.#textFormatter.formatEvent(event);
if (line) {
if (this.streamToConsole) {
console.log(line);
}
if (this.onEvent) {
this.onEvent({ event, formatted: line });
}
// Update token estimate
this.#updateTokenEstimate();
}
};
// Global keyboard shortcuts
this.#keydownHandler = (e) => {
// Cmd+Escape ends recording
if (e.metaKey && e.key === 'Escape') {
e.preventDefault();
this.end();
return;
}
// Launch shortcut toggles recording
if (Settings.matchesShortcut(e, Settings.get('launchShortcut'))) {
e.preventDefault();
if (this.#isRecording) {
this.end();
} else {
this.start();
}
}
};
document.addEventListener('keydown', this.#keydownHandler);
// Dump transcript to console if browser closes while recording
// This allows LLM tools to capture the transcript from console logs
window.addEventListener('beforeunload', () => {
if (this.#isRecording) {
this.#flushPendingEvents();
const duration = Date.now() - this.#startTime;
const events = this.#coalescer.events;
const transcript = this.#textFormatter.format(events, duration);
console.log('=== ContextScript Recording (browser closing) ===');
console.log(transcript);
console.log('=== End Recording ===');
}
});
}
// Routes events to the appropriate plugin handlers.
#handleEvent(type, event) {
const entries = this.#registry.getPluginsForEvent(type);
for (const { plugin } of entries) {
// Skip if this plugin's category is disabled
if (!this.#config.isEnabled(plugin.category)) {
continue;
}
const handler = plugin.handlers[type];
if (handler) {
// Create emit function that routes actions to coalescer
const emit = (action) => {
this.#emitToCoalescer(action);
};
handler(event, emit);
}
}
}
// Handles category enable/disable changes during recording.
#handleCategoryChange(category, enabled) {
if (!this.#isRecording) {
return;
}
const plugins = this.#registry.getPluginsByCategory(category);
if (enabled) {
// Re-attach listeners for this category
const eventDefs = [];
for (const plugin of plugins) {
if (plugin.events) {
eventDefs.push(...plugin.events);
}
// Start polling if scroll was re-enabled
if (plugin.id === 'scroll' && plugin.startPolling) {
plugin.startPolling();
}
// Install API hooks if developer was re-enabled
if (plugin.id === 'developer' && plugin.install) {
plugin.install((action) => this.#emitToCoalescer(action));
}
// Install History API interceptors if navigation was re-enabled
if (plugin.id === 'navigation' && plugin.install) {
plugin.install((action) => this.#emitToCoalescer(action));
}
}
this.#eventCapture.addListeners(eventDefs);
} else {
// Remove listeners for this category
const eventTypes = new Set();
for (const plugin of plugins) {
if (plugin.events) {
for (const eventDef of plugin.events) {
eventTypes.add(eventDef.type);
}
}
// Stop polling if scroll was disabled
if (plugin.id === 'scroll' && plugin.stopPolling) {
plugin.stopPolling();
}
// Uninstall API hooks if developer was disabled
if (plugin.id === 'developer' && plugin.uninstall) {
plugin.uninstall();
}
// Uninstall History API interceptors if navigation was disabled
if (plugin.id === 'navigation' && plugin.uninstall) {
plugin.uninstall();
}
}
this.#eventCapture.removeListeners(Array.from(eventTypes));
}
}
// Flushes any pending buffered events from plugins.
#flushPendingEvents() {
for (const plugin of this.#registry.getAllPlugins()) {
if (plugin.flush) {
plugin.flush();
}
}
}
// Updates the token estimate displayed in the recording indicator.
#updateTokenEstimate() {
const events = this.#coalescer.events;
const duration = Date.now() - this.#startTime;
const transcript = this.#textFormatter.format(events, duration);
const tokens = RecordingIndicator.estimateTokens(transcript);
this.#recordingIndicator.updateTokens(tokens);
}
}
// Singleton instance - created once on module load
let recorderInstance = null;
// Gets or creates the singleton recorder instance
function getRecorderInstance() {
if (!recorderInstance) {
recorderInstance = new ContextScript();
}
return recorderInstance;
}
// Initialize the recorder instance immediately so the global shortcut handler is registered
getRecorderInstance();
// Create a proxy for console configuration API
// Allows: ContextScript.help, ContextScript.scroll = false, etc.
const createConfigProxy = () => {
const recorder = getRecorderInstance();
return new Proxy({}, {
get(_target, prop) {
// Toggle recording when just accessing ContextScript
if (prop === Symbol.toPrimitive || prop === 'valueOf' || prop === 'toString') {
return () => {
if (recorder.isRecording) {
recorder.end();
} else {
recorder.start();
}
return recorder;
};
}
// Show help
if (prop === 'help') {
recorder.config.showHelp();
return recorder;
}
// Return the recorder instance
if (prop === 'instance') {
return recorder;
}
// Check if it's a category toggle
if (recorder.config.hasCategory(prop)) {
return recorder.config.isEnabled(prop);
}
// Handle maskPasswords option
if (prop === 'maskPasswords') {
return KeyboardRecognizer.maskPasswords;
}
// Handle shortcut getter
if (prop === 'shortcut') {
return Settings.get('launchShortcut');
}
// Handle resetShortcut function
if (prop === 'resetShortcut') {
return () => {
Settings.reset('launchShortcut');
console.log(`Shortcut reset to: ${Settings.DEFAULTS.launchShortcut}`);
};
}
// Default: return property from recorder (bind methods so private fields work)
const value = recorder[prop];
if (typeof value === 'function') {
return value.bind(recorder);
}
return value;
},
set(_target, prop, value) {
// Handle category toggles
if (recorder.config.hasCategory(prop)) {
recorder.config.setEnabled(prop, value);
console.log(`${prop} capture: ${value ? 'enabled' : 'disabled'}`);
return true;
}
// Handle maskPasswords option
if (prop === 'maskPasswords') {
KeyboardRecognizer.maskPasswords = value;
console.log(`Password masking: ${value ? 'enabled' : 'disabled'}`);
return true;
}
// Handle shortcut setter
if (prop === 'shortcut') {
Settings.set('launchShortcut', value);
console.log(`Launch shortcut set to: ${value}`);
return true;
}
// Default: set on recorder
recorder[prop] = value;
return true;
}
});
};
// Expose ContextScript globally for console use
// Allows: ContextScript.start(), ContextScript.end(), ContextScript.scroll = false, etc.
window.ContextScript = createConfigProxy();
export { ContextScript };