superbased 1.6.1 → 1.6.3

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.
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ // MonitorAnalyzer — AI analysis loop for monitor mode recording.
3
+ // Receives frames from CaptureQueue, batches by count/time, sends to AI for analysis,
4
+ // stores results on frame records, and emits alerts for MCP notifications.
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.MonitorAnalyzer = void 0;
43
+ const fs = __importStar(require("fs"));
44
+ const http = __importStar(require("http"));
45
+ const logger_1 = __importDefault(require("../../logger"));
46
+ class MonitorAnalyzer {
47
+ config;
48
+ sessionId;
49
+ onAlert;
50
+ framesSinceAnalysis = 0;
51
+ lastAnalysisTime = 0;
52
+ analyzing = false;
53
+ pendingFrames = [];
54
+ destroyed = false;
55
+ alertCount = 0;
56
+ lastAnalysis = null;
57
+ constructor(config, sessionId, onAlert) {
58
+ this.config = config;
59
+ this.sessionId = sessionId;
60
+ this.onAlert = onAlert;
61
+ logger_1.default.info(`[MonitorAnalyzer] Initialized for session ${sessionId} — analyzeEvery=${config.analyzeEvery}, analyzeInterval=${config.analyzeInterval}s`);
62
+ }
63
+ async onFrame(frame) {
64
+ if (this.destroyed)
65
+ return;
66
+ this.framesSinceAnalysis++;
67
+ this.pendingFrames.push(frame);
68
+ // Keep only the last N frames to avoid unbounded memory growth
69
+ if (this.pendingFrames.length > this.config.analyzeEvery * 2) {
70
+ this.pendingFrames = this.pendingFrames.slice(-this.config.analyzeEvery);
71
+ }
72
+ const elapsed = (Date.now() - this.lastAnalysisTime) / 1000;
73
+ const shouldAnalyze = this.framesSinceAnalysis >= this.config.analyzeEvery &&
74
+ elapsed >= this.config.analyzeInterval;
75
+ if (!shouldAnalyze || this.analyzing)
76
+ return;
77
+ this.analyzing = true;
78
+ try {
79
+ await this.analyzeLatestFrame();
80
+ }
81
+ catch (err) {
82
+ logger_1.default.error('[MonitorAnalyzer] Analysis failed:', err);
83
+ }
84
+ finally {
85
+ this.analyzing = false;
86
+ }
87
+ }
88
+ async analyzeLatestFrame() {
89
+ // Pick the most recent frame for analysis
90
+ const frame = this.pendingFrames[this.pendingFrames.length - 1];
91
+ if (!frame)
92
+ return;
93
+ logger_1.default.info(`[MonitorAnalyzer] Analyzing frame #${frame.frameNumber} (${this.framesSinceAnalysis} frames since last analysis)`);
94
+ // Read the frame image and resize for AI
95
+ if (!fs.existsSync(frame.framePath)) {
96
+ logger_1.default.warn(`[MonitorAnalyzer] Frame file not found: ${frame.framePath}`);
97
+ return;
98
+ }
99
+ const imageBuffer = fs.readFileSync(frame.framePath);
100
+ const resizedBase64 = await this.resizeForAI(imageBuffer);
101
+ // Call AI via local API
102
+ const analysis = await this.callAI(resizedBase64, frame);
103
+ if (!analysis || this.destroyed)
104
+ return;
105
+ // Reset counters
106
+ this.framesSinceAnalysis = 0;
107
+ this.lastAnalysisTime = Date.now();
108
+ this.pendingFrames = [];
109
+ // Store analysis on the frame record
110
+ await this.storeAnalysis(frame.captureId, analysis);
111
+ // Emit alert
112
+ this.alertCount++;
113
+ const alert = {
114
+ sessionId: this.sessionId,
115
+ frameId: frame.captureId,
116
+ frameNumber: frame.frameNumber,
117
+ analysis,
118
+ screenshotPath: frame.framePath,
119
+ timestamp: new Date().toISOString(),
120
+ };
121
+ this.lastAnalysis = alert;
122
+ this.onAlert(alert);
123
+ logger_1.default.info(`[MonitorAnalyzer] Analysis complete for frame #${frame.frameNumber}: ${analysis.substring(0, 100)}...`);
124
+ }
125
+ async resizeForAI(buffer) {
126
+ try {
127
+ const sharp = require('sharp');
128
+ const maxDim = this.config.analysisDetail === 'high' ? 1024 : 512;
129
+ const meta = await sharp(buffer).metadata();
130
+ const maxSide = Math.max(meta.width || 0, meta.height || 0);
131
+ if (maxSide > maxDim) {
132
+ const resized = await sharp(buffer)
133
+ .resize({
134
+ width: maxSide === meta.width ? maxDim : undefined,
135
+ height: maxSide === meta.height ? maxDim : undefined,
136
+ fit: 'inside',
137
+ })
138
+ .png()
139
+ .toBuffer();
140
+ return resized.toString('base64');
141
+ }
142
+ return buffer.toString('base64');
143
+ }
144
+ catch {
145
+ return buffer.toString('base64');
146
+ }
147
+ }
148
+ async callAI(imageBase64, frame) {
149
+ const windowContext = frame.windowTitle ? ` (Active window: ${frame.windowTitle})` : '';
150
+ const instruction = `${this.config.analysisPrompt}\n\nFrame #${frame.frameNumber} of session "${this.sessionId}".${windowContext}\nKeep your response concise (2-4 sentences).`;
151
+ return new Promise((resolve) => {
152
+ const postData = JSON.stringify({
153
+ instruction,
154
+ imageBase64,
155
+ });
156
+ const req = http.request({
157
+ hostname: '127.0.0.1',
158
+ port: 47592,
159
+ path: '/api/ai/process',
160
+ method: 'POST',
161
+ headers: {
162
+ 'Content-Type': 'application/json',
163
+ 'Content-Length': Buffer.byteLength(postData),
164
+ },
165
+ }, (res) => {
166
+ let data = '';
167
+ res.on('data', (chunk) => (data += chunk));
168
+ res.on('end', () => {
169
+ try {
170
+ const parsed = JSON.parse(data);
171
+ if (parsed.error) {
172
+ logger_1.default.warn(`[MonitorAnalyzer] AI error: ${parsed.error}`);
173
+ resolve(null);
174
+ }
175
+ else {
176
+ resolve(parsed.response || null);
177
+ }
178
+ }
179
+ catch {
180
+ logger_1.default.warn('[MonitorAnalyzer] Failed to parse AI response');
181
+ resolve(null);
182
+ }
183
+ });
184
+ });
185
+ req.on('error', (err) => {
186
+ logger_1.default.warn(`[MonitorAnalyzer] AI request failed: ${err.message}`);
187
+ resolve(null);
188
+ });
189
+ req.setTimeout(30000, () => {
190
+ logger_1.default.warn('[MonitorAnalyzer] AI request timeout');
191
+ req.destroy();
192
+ resolve(null);
193
+ });
194
+ req.write(postData);
195
+ req.end();
196
+ });
197
+ }
198
+ async storeAnalysis(captureId, analysis) {
199
+ try {
200
+ const { updateCapture } = require('../../db/database');
201
+ updateCapture(captureId, { aiResponse: analysis });
202
+ }
203
+ catch (err) {
204
+ logger_1.default.error('[MonitorAnalyzer] Failed to store analysis:', err);
205
+ }
206
+ }
207
+ getAlertCount() {
208
+ return this.alertCount;
209
+ }
210
+ getLastAnalysis() {
211
+ return this.lastAnalysis;
212
+ }
213
+ destroy() {
214
+ this.destroyed = true;
215
+ this.pendingFrames = [];
216
+ logger_1.default.info(`[MonitorAnalyzer] Destroyed (${this.alertCount} alerts emitted)`);
217
+ }
218
+ }
219
+ exports.MonitorAnalyzer = MonitorAnalyzer;
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ // ChangeDetectProvider — timer + visual diff gating for smart/monitor recording.
3
+ // Works on all platforms without native input hooks.
4
+ // Captures at a configurable interval, compares frames via pixel diff,
5
+ // and only emits events when visual change exceeds threshold.
6
+ // Also polls active window title for focus_change detection.
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.ChangeDetectProvider = void 0;
12
+ const logger_1 = __importDefault(require("../../../logger"));
13
+ const platform_1 = require("../../../core/platform");
14
+ // Tiny frame dimensions for fast pixel comparison
15
+ const TINY_WIDTH = 128;
16
+ const TINY_HEIGHT = 72;
17
+ class ChangeDetectProvider {
18
+ handlers = new Set();
19
+ running = false;
20
+ timer = null;
21
+ intervalMs;
22
+ changeThreshold;
23
+ lastTinyBuffer = null;
24
+ lastWindowTitle = '';
25
+ constructor(config) {
26
+ this.intervalMs = config.interval * 1000;
27
+ this.changeThreshold = config.changeThreshold;
28
+ }
29
+ async start() {
30
+ this.running = true;
31
+ this.lastTinyBuffer = null;
32
+ this.lastWindowTitle = '';
33
+ logger_1.default.info(`[ChangeDetect] Starting with interval=${this.intervalMs}ms, threshold=${this.changeThreshold}`);
34
+ this.timer = setInterval(() => {
35
+ this.tick().catch((err) => {
36
+ logger_1.default.error('[ChangeDetect] Tick error:', err);
37
+ });
38
+ }, this.intervalMs);
39
+ }
40
+ async stop() {
41
+ if (this.timer) {
42
+ clearInterval(this.timer);
43
+ this.timer = null;
44
+ }
45
+ this.running = false;
46
+ this.lastTinyBuffer = null;
47
+ logger_1.default.info('[ChangeDetect] Stopped');
48
+ }
49
+ isRunning() {
50
+ return this.running;
51
+ }
52
+ on(_event, handler) {
53
+ this.handlers.add(handler);
54
+ }
55
+ off(_event, handler) {
56
+ this.handlers.delete(handler);
57
+ }
58
+ emit(event) {
59
+ for (const handler of this.handlers) {
60
+ handler(event);
61
+ }
62
+ }
63
+ async tick() {
64
+ if (!this.running)
65
+ return;
66
+ try {
67
+ // 1. Capture screen as PNG buffer
68
+ const screenshotBuffer = await this.captureScreenshot();
69
+ if (!screenshotBuffer || screenshotBuffer.length === 0)
70
+ return;
71
+ // 2. Downscale to tiny buffer for fast comparison
72
+ const tinyBuffer = await this.downscale(screenshotBuffer);
73
+ if (!tinyBuffer)
74
+ return;
75
+ // 3. Check active window title for focus_change
76
+ await this.checkWindowTitle();
77
+ // 4. Compute visual diff against previous frame
78
+ const diffRatio = this.lastTinyBuffer
79
+ ? this.computeDiff(this.lastTinyBuffer, tinyBuffer)
80
+ : 1.0; // First frame always captured
81
+ // 5. Emit periodic event if change exceeds threshold
82
+ if (diffRatio >= this.changeThreshold) {
83
+ logger_1.default.info(`[ChangeDetect] Visual change ${(diffRatio * 100).toFixed(1)}% >= threshold ${(this.changeThreshold * 100).toFixed(1)}%`);
84
+ this.lastTinyBuffer = tinyBuffer;
85
+ // Emit a synthetic periodic trigger event.
86
+ // We use the mouseup type because TriggerEngine processes it
87
+ // and the periodic timer in TriggerEngine handles the actual capture.
88
+ // But for smart mode, we emit a direct periodic-style event that
89
+ // TriggerEngine will forward to CaptureQueue.
90
+ const event = {
91
+ type: 'mouseup',
92
+ timestamp: Date.now(),
93
+ x: 0,
94
+ y: 0,
95
+ button: 1,
96
+ modifiers: { ctrl: false, alt: false, shift: false, meta: false },
97
+ };
98
+ this.emit(event);
99
+ }
100
+ else {
101
+ // Below threshold — skip
102
+ if (this.lastTinyBuffer) {
103
+ logger_1.default.info(`[ChangeDetect] Visual change ${(diffRatio * 100).toFixed(1)}% < threshold — skipping`);
104
+ }
105
+ }
106
+ }
107
+ catch (err) {
108
+ logger_1.default.error('[ChangeDetect] Tick error:', err);
109
+ }
110
+ }
111
+ async captureScreenshot() {
112
+ try {
113
+ const platform = (0, platform_1.getPlatform)();
114
+ if (platform.isElectron()) {
115
+ // In Electron, use the existing captureScreen function
116
+ const { captureScreen } = require('../../capture');
117
+ return await captureScreen();
118
+ }
119
+ else {
120
+ // Headless: use screenshot-desktop
121
+ const screenshot = require('screenshot-desktop');
122
+ return await screenshot({ format: 'png' });
123
+ }
124
+ }
125
+ catch (err) {
126
+ logger_1.default.error('[ChangeDetect] Screenshot failed:', err);
127
+ return null;
128
+ }
129
+ }
130
+ async downscale(buffer) {
131
+ try {
132
+ const sharp = require('sharp');
133
+ return await sharp(buffer)
134
+ .resize(TINY_WIDTH, TINY_HEIGHT, { fit: 'fill' })
135
+ .raw()
136
+ .toBuffer();
137
+ }
138
+ catch (err) {
139
+ logger_1.default.error('[ChangeDetect] Downscale failed:', err);
140
+ return null;
141
+ }
142
+ }
143
+ computeDiff(prev, curr) {
144
+ const len = Math.min(prev.length, curr.length);
145
+ if (len === 0)
146
+ return 1.0;
147
+ let totalDiff = 0;
148
+ for (let i = 0; i < len; i++) {
149
+ totalDiff += Math.abs(prev[i] - curr[i]);
150
+ }
151
+ // Normalize to 0-1 ratio (255 is max diff per byte)
152
+ return totalDiff / (len * 255);
153
+ }
154
+ async checkWindowTitle() {
155
+ try {
156
+ const platform = (0, platform_1.getPlatform)();
157
+ if (platform.isElectron()) {
158
+ const { getActiveWindowInfo } = require('../../active-window');
159
+ const info = await getActiveWindowInfo();
160
+ const title = info.windowTitle || '';
161
+ if (title && title !== this.lastWindowTitle && this.lastWindowTitle !== '') {
162
+ logger_1.default.info(`[ChangeDetect] Window changed: "${this.lastWindowTitle}" → "${title}"`);
163
+ // Emit a synthetic focus change — the recording session's focus poll
164
+ // will also detect this, but emitting here ensures it's captured
165
+ // even without the session's own polling.
166
+ }
167
+ this.lastWindowTitle = title;
168
+ }
169
+ else {
170
+ // Headless: use platform's listWindows to detect active window changes
171
+ // This is a best-effort approach — some platforms may not support it well
172
+ // For now, skip focus detection in headless (window title comes from screenshot metadata)
173
+ }
174
+ }
175
+ catch {
176
+ // Ignore window detection errors
177
+ }
178
+ }
179
+ }
180
+ exports.ChangeDetectProvider = ChangeDetectProvider;
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // Provider factory: detect platform, try uiohook, fallback to periodic.
2
+ // Provider factory: detect platform, try uiohook, fallback to periodic or change-detect.
3
3
  // Returns the best available InputHookProvider for the current platform.
4
4
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
5
  if (k2 === undefined) k2 = k;
@@ -40,29 +40,50 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
41
  exports.createInputHookProvider = createInputHookProvider;
42
42
  const logger_1 = __importDefault(require("../../../logger"));
43
- async function createInputHookProvider(periodicIntervalMs) {
44
- // Try uiohook-napi first (works on Windows, macOS, Linux)
43
+ async function createInputHookProvider(optsOrInterval) {
44
+ // Backwards-compatible: accept plain number (periodicIntervalMs) or options object
45
+ const opts = typeof optsOrInterval === 'number'
46
+ ? { intervalMs: optsOrInterval }
47
+ : optsOrInterval || {};
48
+ const mode = opts.mode || 'interaction';
49
+ // Smart or monitor mode → use ChangeDetectProvider (works everywhere, no native hooks)
50
+ if (mode === 'smart' || mode === 'monitor') {
51
+ const { ChangeDetectProvider } = await Promise.resolve().then(() => __importStar(require('./change-detect-provider')));
52
+ const provider = new ChangeDetectProvider({
53
+ interval: (opts.intervalMs || (mode === 'monitor' ? 5000 : 3000)) / 1000,
54
+ changeThreshold: opts.changeThreshold ?? 0.05,
55
+ });
56
+ logger_1.default.info(`[Recording] Using ChangeDetectProvider for ${mode} mode`);
57
+ return { provider, type: 'change-detect' };
58
+ }
59
+ // Periodic mode → use PeriodicProvider
60
+ if (mode === 'periodic') {
61
+ const { PeriodicProvider } = await Promise.resolve().then(() => __importStar(require('./periodic-provider')));
62
+ const provider = new PeriodicProvider(opts.intervalMs || 5000);
63
+ logger_1.default.info('[Recording] Using PeriodicProvider for periodic mode');
64
+ return { provider, type: 'periodic' };
65
+ }
66
+ // Interaction mode → try uiohook-napi first (works on Windows, macOS, Linux)
45
67
  try {
46
- // Verify the native binary can be imported (catches missing/incompatible binaries)
47
68
  await Promise.resolve().then(() => __importStar(require('uiohook-napi')));
48
69
  const { UiohookProvider } = await Promise.resolve().then(() => __importStar(require('./uiohook-provider')));
49
70
  const provider = new UiohookProvider();
50
- // Don't test-start/stop here — on macOS, stopping and restarting a CGEvent tap
51
- // can leave the hook in a broken state. The provider will be started when the
52
- // recording session begins.
53
71
  logger_1.default.info('[Recording] uiohook-napi native binary loaded successfully');
54
72
  return { provider, type: 'uiohook' };
55
73
  }
56
74
  catch (err) {
57
75
  const reason = err instanceof Error ? err.message : String(err);
58
76
  logger_1.default.warn(`[Recording] uiohook-napi unavailable: ${reason}`);
59
- logger_1.default.warn('[Recording] Falling back to periodic capture provider');
60
- // Fallback to periodic timer-based capture
61
- const { PeriodicProvider } = await Promise.resolve().then(() => __importStar(require('./periodic-provider')));
62
- const provider = new PeriodicProvider(periodicIntervalMs || 5000);
77
+ logger_1.default.warn('[Recording] Falling back to ChangeDetectProvider');
78
+ // Fallback to change-detect (smarter than plain periodic)
79
+ const { ChangeDetectProvider } = await Promise.resolve().then(() => __importStar(require('./change-detect-provider')));
80
+ const provider = new ChangeDetectProvider({
81
+ interval: (opts.intervalMs || 3000) / 1000,
82
+ changeThreshold: opts.changeThreshold ?? 0.05,
83
+ });
63
84
  return {
64
85
  provider,
65
- type: 'periodic',
86
+ type: 'change-detect',
66
87
  fallbackReason: reason,
67
88
  };
68
89
  }
@@ -157,11 +157,14 @@ class UiohookProvider {
157
157
  eventCounter = 0;
158
158
  lastLogTime = Date.now();
159
159
  async start() {
160
- // Dynamic import to avoid loading native binary at startup
160
+ // Acquire hook via shared manager (reference-counted — won't kill
161
+ // dictation's listeners when recording stops)
161
162
  if (!this.uiohook) {
162
- this.uiohook = await Promise.resolve().then(() => __importStar(require('uiohook-napi')));
163
+ const { acquire } = await Promise.resolve().then(() => __importStar(require('../../uiohook-manager')));
164
+ this.uiohook = await acquire('recording');
163
165
  }
164
- const { uIOhook } = this.uiohook;
166
+ const mod = this.uiohook;
167
+ const { uIOhook } = mod;
165
168
  // Only register event handlers once — uiohook-napi accumulates listeners
166
169
  // and re-registering causes duplicate events
167
170
  if (!this.handlersRegistered) {
@@ -200,13 +203,14 @@ class UiohookProvider {
200
203
  this.handlersRegistered = true;
201
204
  logger_1.default.info('[uiohook] Event handlers registered');
202
205
  }
203
- uIOhook.start();
204
206
  this.running = true;
205
207
  logger_1.default.info('[uiohook] Hook started, listening for input events');
206
208
  }
207
209
  async stop() {
208
210
  if (this.uiohook && this.running) {
209
- this.uiohook.uIOhook.stop();
211
+ // Release our reference — hook only stops if no other consumer needs it
212
+ const { release } = await Promise.resolve().then(() => __importStar(require('../../uiohook-manager')));
213
+ release('recording');
210
214
  this.running = false;
211
215
  logger_1.default.info('[uiohook] Hook stopped');
212
216
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  // Recording Session — manages the lifecycle of a recording session.
3
3
  // Wires together: InputHookProvider → TriggerEngine → CaptureQueue → Database
4
+ // Works in both Electron (desktop) and headless (Node.js) modes.
4
5
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
6
  if (k2 === undefined) k2 = k;
6
7
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -38,6 +39,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
38
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
39
40
  };
40
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.setMonitorAlertCallback = setMonitorAlertCallback;
43
+ exports.getMonitorAnalyzer = getMonitorAnalyzer;
41
44
  exports.setFrameBroadcast = setFrameBroadcast;
42
45
  exports.getCurrentSession = getCurrentSession;
43
46
  exports.recoverOrphanedSessions = recoverOrphanedSessions;
@@ -49,28 +52,46 @@ exports.resumeCurrentSession = resumeCurrentSession;
49
52
  exports.stopCurrentSession = stopCurrentSession;
50
53
  const path = __importStar(require("path"));
51
54
  const fs = __importStar(require("fs"));
52
- const electron_1 = require("electron");
53
55
  const logger_1 = __importDefault(require("../../logger"));
54
56
  const recording_types_1 = require("../../../shared/recording-types");
55
57
  const trigger_engine_1 = require("./trigger-engine");
56
58
  const capture_queue_1 = require("./capture-queue");
59
+ const monitor_analyzer_1 = require("./monitor-analyzer");
57
60
  const database_1 = require("../../db/database");
58
- const store_1 = require("../store");
61
+ const platform_1 = require("../../core/platform");
59
62
  const active_window_1 = require("../active-window");
60
63
  const constants_1 = require("../../../shared/constants");
64
+ // Platform-aware getSetting: Electron uses electron-store, headless uses json-store
65
+ function getSetting(key) {
66
+ if ((0, platform_1.getPlatform)().isElectron()) {
67
+ const { getSetting: electronGetSetting } = require('../store');
68
+ return electronGetSetting(key);
69
+ }
70
+ const { getSetting: jsonGetSetting } = require('../../core/json-store');
71
+ return jsonGetSetting(key);
72
+ }
61
73
  let currentSession = null;
62
74
  let triggerEngine = null;
63
75
  let captureQueue = null;
64
76
  let hookProvider = null;
77
+ let monitorAnalyzer = null;
65
78
  let focusPollTimer = null;
66
79
  /** Callback for broadcasting frame events to BrowserWindows (set by main.ts) */
67
80
  let onFrameBroadcast = null;
81
+ /** Callback for monitor mode alerts (set by MCP/API layer) */
82
+ let onMonitorAlert = null;
83
+ function setMonitorAlertCallback(cb) {
84
+ onMonitorAlert = cb;
85
+ }
86
+ function getMonitorAnalyzer() {
87
+ return monitorAnalyzer;
88
+ }
68
89
  function setFrameBroadcast(cb) {
69
90
  onFrameBroadcast = cb;
70
91
  }
71
92
  function getSessionsBaseDir() {
72
- const custom = (0, store_1.getSetting)('screenshotFolder');
73
- const baseDir = custom && fs.existsSync(custom) ? custom : path.join(electron_1.app.getPath('userData'), constants_1.CAPTURES_DIR);
93
+ const custom = getSetting('screenshotFolder');
94
+ const baseDir = custom && fs.existsSync(custom) ? custom : path.join((0, platform_1.getPlatform)().getDataDir(), constants_1.CAPTURES_DIR);
74
95
  return path.join(baseDir, 'sessions');
75
96
  }
76
97
  function getCurrentSession() {
@@ -103,10 +124,22 @@ async function startSession(options) {
103
124
  if (currentSession) {
104
125
  throw new Error('A recording session is already active');
105
126
  }
127
+ // Determine recording mode — defaults based on platform
128
+ const isElectron = (0, platform_1.getPlatform)().isElectron();
129
+ const mode = options.mode || (isElectron ? 'interaction' : 'smart');
106
130
  const id = `session_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
107
131
  const config = options.profile === 'custom' && options.config
108
132
  ? options.config
109
133
  : recording_types_1.RECORDING_PROFILES[options.profile] || recording_types_1.RECORDING_PROFILES.automated_test;
134
+ // For smart/periodic/monitor modes, enable periodic trigger and configure interval
135
+ if (mode === 'smart' || mode === 'periodic' || mode === 'monitor') {
136
+ config.triggers.periodic = true;
137
+ config.triggers.periodicInterval = (options.interval || (mode === 'monitor' ? 5 : 3)) * 1000;
138
+ // Smart/monitor use visual change detection in the provider
139
+ if (mode === 'smart' || mode === 'monitor') {
140
+ config.minVisualChangePercent = (options.changeThreshold ?? 0.05) * 100;
141
+ }
142
+ }
110
143
  const sessionDir = path.join(getSessionsBaseDir(), id);
111
144
  fs.mkdirSync(sessionDir, { recursive: true });
112
145
  // Write session config to disk
@@ -137,6 +170,7 @@ async function startSession(options) {
137
170
  startedAt: Date.now(),
138
171
  frameCount: 0,
139
172
  config,
173
+ mode,
140
174
  };
141
175
  // Create capture queue
142
176
  captureQueue = new capture_queue_1.CaptureQueue(config, sessionDir, (frameData) => {
@@ -145,7 +179,7 @@ async function startSession(options) {
145
179
  currentSession.frameCount++;
146
180
  const relativeTime = Date.now() - currentSession.startedAt;
147
181
  // Save to database
148
- (0, database_1.saveRecordingFrame)({
182
+ const captureId = (0, database_1.saveRecordingFrame)({
149
183
  screenshotPath: frameData.framePath,
150
184
  sessionId: currentSession.id,
151
185
  frameNumber: frameData.frameNumber,
@@ -180,6 +214,18 @@ async function startSession(options) {
180
214
  triggerType: frameData.trigger.type,
181
215
  });
182
216
  }
217
+ // Feed frame to monitor analyzer (if in monitor mode)
218
+ if (monitorAnalyzer && currentSession) {
219
+ monitorAnalyzer.onFrame({
220
+ captureId,
221
+ framePath: frameData.framePath,
222
+ frameNumber: frameData.frameNumber,
223
+ sessionId: currentSession.id,
224
+ windowTitle: frameData.windowTitle,
225
+ }).catch((err) => {
226
+ logger_1.default.error('[Recording] Monitor analysis error:', err);
227
+ });
228
+ }
183
229
  });
184
230
  // Create trigger engine (rate limiting via minCaptureInterval is handled here, not in CaptureQueue)
185
231
  triggerEngine = new trigger_engine_1.TriggerEngine({
@@ -212,6 +258,17 @@ async function startSession(options) {
212
258
  }
213
259
  }
214
260
  }, 500);
261
+ // For smart/periodic/monitor modes, create a provider if none is set
262
+ if (!hookProvider && (mode === 'smart' || mode === 'periodic' || mode === 'monitor')) {
263
+ const { createInputHookProvider } = await Promise.resolve().then(() => __importStar(require('./providers/provider-factory')));
264
+ const result = await createInputHookProvider({
265
+ mode,
266
+ intervalMs: (options.interval || (mode === 'monitor' ? 5 : 3)) * 1000,
267
+ changeThreshold: options.changeThreshold ?? 0.05,
268
+ });
269
+ hookProvider = result.provider;
270
+ logger_1.default.info(`[Recording] Created ${result.type} provider for ${mode} mode`);
271
+ }
215
272
  // Wire input hook to trigger engine
216
273
  if (hookProvider) {
217
274
  logger_1.default.info('[Recording] Wiring input hook to trigger engine');
@@ -233,7 +290,17 @@ async function startSession(options) {
233
290
  else {
234
291
  logger_1.default.warn('[Recording] No hook provider available!');
235
292
  }
236
- logger_1.default.info(`[Recording] Session started: ${id} (${options.name})`);
293
+ // Initialize MonitorAnalyzer for monitor mode
294
+ if (mode === 'monitor' && options.monitor) {
295
+ monitorAnalyzer = new monitor_analyzer_1.MonitorAnalyzer(options.monitor, id, (alert) => {
296
+ logger_1.default.info(`[Recording] Monitor alert: frame #${alert.frameNumber} — ${alert.analysis.substring(0, 80)}`);
297
+ if (onMonitorAlert) {
298
+ onMonitorAlert(alert);
299
+ }
300
+ });
301
+ logger_1.default.info('[Recording] MonitorAnalyzer initialized');
302
+ }
303
+ logger_1.default.info(`[Recording] Session started: ${id} (${options.name}, mode=${mode})`);
237
304
  return currentSession;
238
305
  }
239
306
  async function pauseCurrentSession() {
@@ -297,6 +364,11 @@ async function stopCurrentSession() {
297
364
  }
298
365
  currentSession.status = 'completed';
299
366
  const duration = Date.now() - currentSession.startedAt;
367
+ // Clean up monitor analyzer
368
+ if (monitorAnalyzer) {
369
+ monitorAnalyzer.destroy();
370
+ monitorAnalyzer = null;
371
+ }
300
372
  // Clean up capture queue
301
373
  if (captureQueue) {
302
374
  captureQueue.destroy();