screenhand 0.1.0

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,391 @@
1
+ /**
2
+ * Learning Memory — JSONL persistence layer (production-ready)
3
+ *
4
+ * - All data cached in-memory for zero-latency reads
5
+ * - Disk writes are non-blocking, buffered, flushed on exit
6
+ * - Per-line JSONL parsing — corrupted lines are skipped, not fatal
7
+ * - Cache size limits with LRU eviction
8
+ * - File locking for multi-instance safety
9
+ */
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { SEED_STRATEGIES } from "./seeds.js";
13
+ const MAX_ACTION_FILE_BYTES = 10 * 1024 * 1024; // 10 MB
14
+ const MAX_STRATEGIES = 500;
15
+ const MAX_ERRORS = 200;
16
+ export class MemoryStore {
17
+ dir;
18
+ // ── in-memory caches ──
19
+ strategiesCache = [];
20
+ errorsCache = [];
21
+ /** Fingerprint → Strategy index for O(1) exact lookup */
22
+ fingerprintIndex = new Map();
23
+ actionCount = 0;
24
+ actionSuccessCount = 0;
25
+ toolCounts = new Map();
26
+ initialized = false;
27
+ dirCreated = false;
28
+ /** True if ensureDir() had to create the memory directory (first boot) */
29
+ justCreatedDir = false;
30
+ // ── write buffer for flush-on-exit ──
31
+ pendingActionWrites = [];
32
+ flushTimer = null;
33
+ lockPath;
34
+ hasLock = false;
35
+ // Global flag — only register exit handlers once across all instances
36
+ static exitHandlerRegistered = false;
37
+ static activeInstance = null;
38
+ constructor(baseDir) {
39
+ this.dir = path.join(baseDir, ".screenhand", "memory");
40
+ this.lockPath = path.join(this.dir, ".lock");
41
+ }
42
+ /** Load caches from disk. Call once at startup. */
43
+ init() {
44
+ if (this.initialized)
45
+ return;
46
+ this.initialized = true;
47
+ this.ensureDir();
48
+ this.acquireLock();
49
+ this.registerExitHandler();
50
+ // Detect first boot: memory directory was just created (didn't exist before ensureDir)
51
+ const isFirstBoot = this.justCreatedDir;
52
+ this.strategiesCache = this.readLinesSafe("strategies.jsonl");
53
+ if (this.strategiesCache.length === 0 && isFirstBoot) {
54
+ for (const s of SEED_STRATEGIES)
55
+ this.strategiesCache.push(s);
56
+ this.writeLinesAsync("strategies.jsonl", this.strategiesCache);
57
+ }
58
+ this.enforceStrategyLimit();
59
+ this.rebuildFingerprintIndex();
60
+ this.errorsCache = this.readLinesSafe("errors.jsonl");
61
+ this.enforceErrorLimit();
62
+ // Build action stats without caching all entries
63
+ const actions = this.readLinesSafe("actions.jsonl");
64
+ this.actionCount = actions.length;
65
+ for (const a of actions) {
66
+ if (a.success)
67
+ this.actionSuccessCount++;
68
+ this.toolCounts.set(a.tool, (this.toolCounts.get(a.tool) ?? 0) + 1);
69
+ }
70
+ }
71
+ // ── file locking ──────────────────────────────
72
+ acquireLock() {
73
+ try {
74
+ // Check for stale lock (PID no longer running)
75
+ if (fs.existsSync(this.lockPath)) {
76
+ const lockContent = fs.readFileSync(this.lockPath, "utf-8").trim();
77
+ const lockPid = parseInt(lockContent, 10);
78
+ if (lockPid && !this.isProcessRunning(lockPid)) {
79
+ // Stale lock — remove it
80
+ fs.unlinkSync(this.lockPath);
81
+ }
82
+ }
83
+ // Write our PID
84
+ fs.writeFileSync(this.lockPath, String(process.pid), { flag: "wx" });
85
+ this.hasLock = true;
86
+ }
87
+ catch {
88
+ // Another instance holds the lock — we still work but skip writes
89
+ // to avoid corruption. Reads are from our own cache (stale but safe).
90
+ this.hasLock = false;
91
+ }
92
+ }
93
+ releaseLock() {
94
+ if (this.hasLock) {
95
+ try {
96
+ fs.unlinkSync(this.lockPath);
97
+ }
98
+ catch { /* ignore */ }
99
+ this.hasLock = false;
100
+ }
101
+ }
102
+ isProcessRunning(pid) {
103
+ try {
104
+ process.kill(pid, 0);
105
+ return true;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ // ── exit handling ─────────────────────────────
112
+ registerExitHandler() {
113
+ MemoryStore.activeInstance = this;
114
+ if (MemoryStore.exitHandlerRegistered)
115
+ return;
116
+ MemoryStore.exitHandlerRegistered = true;
117
+ const flush = () => MemoryStore.activeInstance?.flushSync();
118
+ process.on("beforeExit", flush);
119
+ process.on("exit", flush);
120
+ // SIGINT/SIGTERM — flush then re-raise
121
+ for (const sig of ["SIGINT", "SIGTERM"]) {
122
+ process.on(sig, () => {
123
+ flush();
124
+ process.exit(128 + (sig === "SIGINT" ? 2 : 15));
125
+ });
126
+ }
127
+ }
128
+ /** Synchronously flush all pending action writes to disk */
129
+ flushSync() {
130
+ if (this.pendingActionWrites.length === 0)
131
+ return;
132
+ if (!this.hasLock)
133
+ return;
134
+ try {
135
+ this.ensureDir();
136
+ const data = this.pendingActionWrites.join("");
137
+ fs.appendFileSync(this.filePath("actions.jsonl"), data);
138
+ this.pendingActionWrites = [];
139
+ }
140
+ catch {
141
+ // Non-critical on exit
142
+ }
143
+ this.releaseLock();
144
+ }
145
+ // ── helpers ────────────────────────────────────
146
+ ensureDir() {
147
+ if (!this.dirCreated) {
148
+ if (!fs.existsSync(this.dir)) {
149
+ fs.mkdirSync(this.dir, { recursive: true });
150
+ this.justCreatedDir = true;
151
+ }
152
+ this.dirCreated = true;
153
+ }
154
+ }
155
+ filePath(name) {
156
+ return path.join(this.dir, name);
157
+ }
158
+ /**
159
+ * Parse JSONL safely — skip corrupted lines instead of crashing.
160
+ * Returns all successfully parsed entries.
161
+ */
162
+ readLinesSafe(file) {
163
+ const fp = this.filePath(file);
164
+ if (!fs.existsSync(fp))
165
+ return [];
166
+ let text;
167
+ try {
168
+ text = fs.readFileSync(fp, "utf-8").trim();
169
+ }
170
+ catch {
171
+ return [];
172
+ }
173
+ if (!text)
174
+ return [];
175
+ const results = [];
176
+ for (const line of text.split("\n")) {
177
+ const trimmed = line.trim();
178
+ if (!trimmed)
179
+ continue;
180
+ try {
181
+ results.push(JSON.parse(trimmed));
182
+ }
183
+ catch {
184
+ // Skip corrupted line — don't crash
185
+ }
186
+ }
187
+ return results;
188
+ }
189
+ /** Non-blocking full rewrite — fire and forget (only if we hold lock) */
190
+ writeLinesAsync(file, items) {
191
+ if (!this.hasLock)
192
+ return;
193
+ this.ensureDir();
194
+ const data = items.map((i) => JSON.stringify(i)).join("\n") + (items.length ? "\n" : "");
195
+ fs.writeFile(this.filePath(file), data, () => { });
196
+ }
197
+ fileSize(file) {
198
+ const fp = this.filePath(file);
199
+ if (!fs.existsSync(fp))
200
+ return 0;
201
+ try {
202
+ return fs.statSync(fp).size;
203
+ }
204
+ catch {
205
+ return 0;
206
+ }
207
+ }
208
+ // ── actions (buffered async write) ─────────────
209
+ appendAction(entry) {
210
+ // Update in-memory stats
211
+ this.actionCount++;
212
+ if (entry.success)
213
+ this.actionSuccessCount++;
214
+ this.toolCounts.set(entry.tool, (this.toolCounts.get(entry.tool) ?? 0) + 1);
215
+ if (!this.hasLock)
216
+ return;
217
+ this.rotateActionsIfNeeded();
218
+ // Buffer the write
219
+ this.pendingActionWrites.push(JSON.stringify(entry) + "\n");
220
+ // Schedule batch flush (debounced 100ms)
221
+ if (!this.flushTimer) {
222
+ this.flushTimer = setTimeout(() => {
223
+ this.flushTimer = null;
224
+ if (this.pendingActionWrites.length === 0)
225
+ return;
226
+ this.ensureDir();
227
+ const data = this.pendingActionWrites.join("");
228
+ this.pendingActionWrites = [];
229
+ fs.appendFile(this.filePath("actions.jsonl"), data, () => { });
230
+ }, 100);
231
+ }
232
+ }
233
+ rotateActionsIfNeeded() {
234
+ if (this.fileSize("actions.jsonl") >= MAX_ACTION_FILE_BYTES) {
235
+ const src = this.filePath("actions.jsonl");
236
+ const dst = this.filePath("actions.1.jsonl");
237
+ try {
238
+ if (fs.existsSync(dst))
239
+ fs.unlinkSync(dst);
240
+ fs.renameSync(src, dst);
241
+ }
242
+ catch {
243
+ // Non-critical
244
+ }
245
+ }
246
+ }
247
+ /** Read actions from disk (only used by stats/clear, not in hot path) */
248
+ readActions() {
249
+ return this.readLinesSafe("actions.jsonl");
250
+ }
251
+ // ── strategies (cached + fingerprint indexed + LRU capped) ──
252
+ rebuildFingerprintIndex() {
253
+ this.fingerprintIndex.clear();
254
+ for (const s of this.strategiesCache) {
255
+ if (s.fingerprint) {
256
+ this.fingerprintIndex.set(s.fingerprint, s);
257
+ }
258
+ }
259
+ }
260
+ /** Evict least-recently-used strategies beyond MAX_STRATEGIES */
261
+ enforceStrategyLimit() {
262
+ if (this.strategiesCache.length <= MAX_STRATEGIES)
263
+ return;
264
+ // Sort by lastUsed ascending (oldest first), remove from the front
265
+ this.strategiesCache.sort((a, b) => new Date(a.lastUsed).getTime() - new Date(b.lastUsed).getTime());
266
+ this.strategiesCache = this.strategiesCache.slice(-MAX_STRATEGIES);
267
+ }
268
+ appendStrategy(strategy) {
269
+ // Ensure fingerprint exists
270
+ if (!strategy.fingerprint) {
271
+ strategy.fingerprint = MemoryStore.makeFingerprint(strategy.steps.map((s) => s.tool));
272
+ }
273
+ const idx = this.strategiesCache.findIndex((s) => s.task === strategy.task);
274
+ if (idx >= 0) {
275
+ const old = this.strategiesCache[idx];
276
+ this.strategiesCache[idx] = {
277
+ ...strategy,
278
+ successCount: old.successCount + 1,
279
+ failCount: old.failCount ?? 0,
280
+ lastUsed: strategy.lastUsed,
281
+ };
282
+ this.fingerprintIndex.set(strategy.fingerprint, this.strategiesCache[idx]);
283
+ }
284
+ else {
285
+ this.strategiesCache.push(strategy);
286
+ this.fingerprintIndex.set(strategy.fingerprint, strategy);
287
+ this.enforceStrategyLimit();
288
+ // Rebuild index after eviction
289
+ if (this.strategiesCache.length >= MAX_STRATEGIES) {
290
+ this.rebuildFingerprintIndex();
291
+ }
292
+ }
293
+ this.writeLinesAsync("strategies.jsonl", this.strategiesCache);
294
+ }
295
+ /** O(1) exact lookup by tool sequence fingerprint */
296
+ lookupByFingerprint(fingerprint) {
297
+ return this.fingerprintIndex.get(fingerprint);
298
+ }
299
+ /** Record that a recalled strategy succeeded or failed */
300
+ recordStrategyOutcome(fingerprint, success) {
301
+ const strategy = this.fingerprintIndex.get(fingerprint);
302
+ if (!strategy)
303
+ return;
304
+ if (success) {
305
+ strategy.successCount++;
306
+ strategy.lastUsed = new Date().toISOString();
307
+ }
308
+ else {
309
+ strategy.failCount = (strategy.failCount ?? 0) + 1;
310
+ }
311
+ this.writeLinesAsync("strategies.jsonl", this.strategiesCache);
312
+ }
313
+ /** Read from cache — ~0ms */
314
+ readStrategies() {
315
+ return this.strategiesCache;
316
+ }
317
+ /** Generate a fingerprint from a tool sequence */
318
+ static makeFingerprint(tools) {
319
+ return tools.join("→");
320
+ }
321
+ // ── errors (cached + LRU capped) ──────────────
322
+ /** Evict least-recently-seen errors beyond MAX_ERRORS */
323
+ enforceErrorLimit() {
324
+ if (this.errorsCache.length <= MAX_ERRORS)
325
+ return;
326
+ this.errorsCache.sort((a, b) => new Date(a.lastSeen).getTime() - new Date(b.lastSeen).getTime());
327
+ this.errorsCache = this.errorsCache.slice(-MAX_ERRORS);
328
+ }
329
+ appendError(pattern) {
330
+ const idx = this.errorsCache.findIndex((e) => e.tool === pattern.tool && e.error === pattern.error);
331
+ if (idx >= 0) {
332
+ this.errorsCache[idx] = {
333
+ ...this.errorsCache[idx],
334
+ occurrences: this.errorsCache[idx].occurrences + 1,
335
+ lastSeen: pattern.lastSeen,
336
+ resolution: pattern.resolution ?? this.errorsCache[idx].resolution,
337
+ };
338
+ }
339
+ else {
340
+ this.errorsCache.push(pattern);
341
+ this.enforceErrorLimit();
342
+ }
343
+ this.writeLinesAsync("errors.jsonl", this.errorsCache);
344
+ }
345
+ /** Read from cache — ~0ms */
346
+ readErrors() {
347
+ return this.errorsCache;
348
+ }
349
+ // ── stats (from in-memory counters) ────────────
350
+ getStats() {
351
+ const topTools = [...this.toolCounts.entries()]
352
+ .sort((a, b) => b[1] - a[1])
353
+ .slice(0, 10)
354
+ .map(([tool, count]) => ({ tool, count }));
355
+ const diskUsageBytes = this.fileSize("actions.jsonl") +
356
+ this.fileSize("strategies.jsonl") +
357
+ this.fileSize("errors.jsonl");
358
+ return {
359
+ totalActions: this.actionCount,
360
+ totalStrategies: this.strategiesCache.length,
361
+ totalErrors: this.errorsCache.length,
362
+ diskUsageBytes,
363
+ topTools,
364
+ successRate: this.actionCount > 0 ? this.actionSuccessCount / this.actionCount : 0,
365
+ };
366
+ }
367
+ // ── clear ──────────────────────────────────────
368
+ clear(what) {
369
+ const targets = what === "all"
370
+ ? ["actions", "strategies", "errors"]
371
+ : [what];
372
+ for (const category of targets) {
373
+ const fp = this.filePath(`${category}.jsonl`);
374
+ if (fs.existsSync(fp))
375
+ fs.writeFileSync(fp, "");
376
+ if (category === "actions") {
377
+ this.actionCount = 0;
378
+ this.actionSuccessCount = 0;
379
+ this.toolCounts.clear();
380
+ this.pendingActionWrites = [];
381
+ }
382
+ else if (category === "strategies") {
383
+ this.strategiesCache = [];
384
+ this.fingerprintIndex.clear();
385
+ }
386
+ else if (category === "errors") {
387
+ this.errorsCache = [];
388
+ }
389
+ }
390
+ }
391
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Learning Memory — Data types
3
+ */
4
+ export {};
@@ -0,0 +1,173 @@
1
+ import { spawn } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import path from "node:path";
4
+ import { createInterface } from "node:readline";
5
+ /**
6
+ * Per-method timeout overrides (ms).
7
+ * Methods not listed here use the default 10s timeout.
8
+ */
9
+ const METHOD_TIMEOUTS = {
10
+ "app.launch": 30_000,
11
+ "cg.captureScreen": 15_000,
12
+ "cg.captureWindow": 15_000,
13
+ "vision.ocr": 20_000,
14
+ "vision.findText": 20_000,
15
+ };
16
+ /**
17
+ * Resolves the correct native bridge binary path for the current platform.
18
+ */
19
+ function defaultBinaryPath() {
20
+ const base = import.meta.dirname ?? process.cwd();
21
+ if (process.platform === "win32") {
22
+ return path.resolve(base, "../../native/windows-bridge/bin/Release/net8.0-windows/windows-bridge.exe");
23
+ }
24
+ // macOS (default)
25
+ return path.resolve(base, "../../native/macos-bridge/.build/release/macos-bridge");
26
+ }
27
+ /**
28
+ * Platform-aware native bridge client.
29
+ * Spawns the correct bridge binary (macOS Swift or Windows C#) based on the OS,
30
+ * communicating via the same JSON-RPC-over-stdio protocol.
31
+ *
32
+ * Drop-in replacement for the original MacOSBridgeClient.
33
+ */
34
+ export class BridgeClient extends EventEmitter {
35
+ process = null;
36
+ nextId = 1;
37
+ pending = new Map();
38
+ binaryPath;
39
+ restarting = false;
40
+ started = false;
41
+ constructor(binaryPath) {
42
+ super();
43
+ this.binaryPath = binaryPath ?? defaultBinaryPath();
44
+ }
45
+ async start() {
46
+ if (this.started)
47
+ return;
48
+ await this.spawn();
49
+ this.started = true;
50
+ }
51
+ async stop() {
52
+ this.started = false;
53
+ if (this.process) {
54
+ this.process.kill();
55
+ this.process = null;
56
+ }
57
+ // Reject all pending
58
+ for (const [id, pending] of this.pending) {
59
+ clearTimeout(pending.timer);
60
+ pending.reject(new Error("Bridge stopped"));
61
+ this.pending.delete(id);
62
+ }
63
+ }
64
+ async call(method, params, timeoutMs) {
65
+ const effectiveTimeout = timeoutMs ?? METHOD_TIMEOUTS[method] ?? 10_000;
66
+ if (!this.process || this.process.exitCode !== null) {
67
+ await this.restart();
68
+ }
69
+ const id = this.nextId++;
70
+ const request = { id, method };
71
+ if (params) {
72
+ request.params = params;
73
+ }
74
+ return new Promise((resolve, reject) => {
75
+ const timer = setTimeout(() => {
76
+ this.pending.delete(id);
77
+ reject(new Error(`Bridge call "${method}" timed out after ${effectiveTimeout}ms`));
78
+ }, effectiveTimeout);
79
+ this.pending.set(id, {
80
+ resolve: resolve,
81
+ reject,
82
+ timer,
83
+ });
84
+ const line = JSON.stringify(request) + "\n";
85
+ this.process.stdin.write(line);
86
+ });
87
+ }
88
+ async ping() {
89
+ return this.call("ping");
90
+ }
91
+ async checkPermissions() {
92
+ return this.call("check_permissions");
93
+ }
94
+ async spawn() {
95
+ const child = spawn(this.binaryPath, [], {
96
+ stdio: ["pipe", "pipe", "pipe"],
97
+ });
98
+ child.on("error", (err) => {
99
+ this.emit("error", err);
100
+ if (this.started) {
101
+ this.restart().catch(() => { });
102
+ }
103
+ });
104
+ child.on("exit", (code) => {
105
+ this.emit("exit", code);
106
+ if (this.started && !this.restarting) {
107
+ this.restart().catch(() => { });
108
+ }
109
+ });
110
+ // Parse stdout line by line
111
+ const rl = createInterface({ input: child.stdout });
112
+ rl.on("line", (line) => {
113
+ this.handleLine(line);
114
+ });
115
+ // Log stderr
116
+ child.stderr?.on("data", (data) => {
117
+ this.emit("stderr", data.toString());
118
+ });
119
+ this.process = child;
120
+ }
121
+ handleLine(line) {
122
+ let response;
123
+ try {
124
+ response = JSON.parse(line);
125
+ }
126
+ catch {
127
+ return; // Ignore malformed lines
128
+ }
129
+ // Event (streaming notification from observer)
130
+ if (response.event) {
131
+ this.emit("ax-event", response.event);
132
+ return;
133
+ }
134
+ // Response to a pending request
135
+ const pending = this.pending.get(response.id);
136
+ if (!pending)
137
+ return;
138
+ this.pending.delete(response.id);
139
+ clearTimeout(pending.timer);
140
+ if (response.error) {
141
+ pending.reject(new Error(response.error.message));
142
+ }
143
+ else {
144
+ pending.resolve(response.result);
145
+ }
146
+ }
147
+ async restart() {
148
+ if (this.restarting)
149
+ return;
150
+ this.restarting = true;
151
+ // Reject all pending requests
152
+ for (const [id, pending] of this.pending) {
153
+ clearTimeout(pending.timer);
154
+ pending.reject(new Error("Bridge process crashed, restarting"));
155
+ this.pending.delete(id);
156
+ }
157
+ try {
158
+ if (this.process) {
159
+ this.process.kill();
160
+ this.process = null;
161
+ }
162
+ await this.spawn();
163
+ this.emit("restart");
164
+ }
165
+ finally {
166
+ this.restarting = false;
167
+ }
168
+ }
169
+ }
170
+ /**
171
+ * @deprecated Use BridgeClient instead. This alias exists for backward compatibility.
172
+ */
173
+ export const MacOSBridgeClient = BridgeClient;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @deprecated Import from "./bridge-client.js" instead.
3
+ * This file re-exports for backward compatibility.
4
+ */
5
+ export { BridgeClient, BridgeClient as MacOSBridgeClient } from "./bridge-client.js";