screenhand 0.1.0 → 0.2.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.
Files changed (86) hide show
  1. package/LICENSE +661 -21
  2. package/README.md +208 -38
  3. package/dist/.audit-log.jsonl +55 -0
  4. package/dist/.screenhand/memory/.lock +1 -0
  5. package/dist/.screenhand/memory/actions.jsonl +85 -0
  6. package/dist/.screenhand/memory/errors.jsonl +5 -0
  7. package/dist/.screenhand/memory/errors.jsonl.bak +4 -0
  8. package/dist/.screenhand/memory/state.json +35 -0
  9. package/dist/.screenhand/memory/state.json.bak +35 -0
  10. package/dist/.screenhand/memory/strategies.jsonl +12 -0
  11. package/dist/agent/cli.js +73 -0
  12. package/dist/agent/loop.js +258 -0
  13. package/dist/index.js +1 -0
  14. package/dist/mcp/mcp-stdio-server.js +164 -0
  15. package/dist/mcp-desktop.js +2731 -0
  16. package/dist/mcp-entry.js +7 -10
  17. package/dist/monitor/codex-monitor.js +377 -0
  18. package/dist/monitor/task-queue.js +84 -0
  19. package/dist/monitor/types.js +49 -0
  20. package/dist/native/bridge-client.js +2 -1
  21. package/dist/npm-publish-helper.js +117 -0
  22. package/dist/npm-token-cdp.js +113 -0
  23. package/dist/npm-token-create.js +135 -0
  24. package/dist/npm-token-finish.js +126 -0
  25. package/dist/playbook/engine.js +193 -0
  26. package/dist/playbook/index.js +4 -0
  27. package/dist/playbook/recorder.js +519 -0
  28. package/dist/playbook/runner.js +392 -0
  29. package/dist/playbook/store.js +166 -0
  30. package/dist/playbook/types.js +4 -0
  31. package/dist/scripts/codex-monitor-daemon.js +335 -0
  32. package/dist/scripts/supervisor-daemon.js +272 -0
  33. package/dist/scripts/worker-daemon.js +228 -0
  34. package/dist/src/agent/cli.js +82 -0
  35. package/dist/src/agent/loop.js +274 -0
  36. package/dist/src/config.js +25 -0
  37. package/dist/src/index.js +72 -0
  38. package/dist/src/jobs/manager.js +237 -0
  39. package/dist/src/jobs/runner.js +683 -0
  40. package/dist/src/jobs/store.js +102 -0
  41. package/dist/src/jobs/types.js +30 -0
  42. package/dist/src/jobs/worker.js +97 -0
  43. package/dist/src/logging/timeline-logger.js +45 -0
  44. package/dist/src/mcp/mcp-stdio-server.js +464 -0
  45. package/dist/src/mcp/server.js +363 -0
  46. package/dist/src/mcp-entry.js +60 -0
  47. package/dist/src/memory/recall.js +170 -0
  48. package/dist/src/memory/research.js +104 -0
  49. package/dist/src/memory/seeds.js +101 -0
  50. package/dist/src/memory/service.js +421 -0
  51. package/dist/src/memory/session.js +169 -0
  52. package/dist/src/memory/store.js +422 -0
  53. package/dist/src/memory/types.js +17 -0
  54. package/dist/src/monitor/codex-monitor.js +382 -0
  55. package/dist/src/monitor/task-queue.js +97 -0
  56. package/dist/src/monitor/types.js +62 -0
  57. package/dist/src/native/bridge-client.js +190 -0
  58. package/dist/src/native/macos-bridge-client.js +21 -0
  59. package/dist/src/playbook/engine.js +201 -0
  60. package/dist/src/playbook/index.js +20 -0
  61. package/dist/src/playbook/recorder.js +535 -0
  62. package/dist/src/playbook/runner.js +408 -0
  63. package/dist/src/playbook/store.js +183 -0
  64. package/dist/src/playbook/types.js +17 -0
  65. package/dist/src/runtime/accessibility-adapter.js +393 -0
  66. package/dist/src/runtime/app-adapter.js +64 -0
  67. package/dist/src/runtime/applescript-adapter.js +299 -0
  68. package/dist/src/runtime/ax-role-map.js +96 -0
  69. package/dist/src/runtime/browser-adapter.js +52 -0
  70. package/dist/src/runtime/cdp-chrome-adapter.js +521 -0
  71. package/dist/src/runtime/composite-adapter.js +221 -0
  72. package/dist/src/runtime/execution-contract.js +159 -0
  73. package/dist/src/runtime/executor.js +266 -0
  74. package/dist/src/runtime/locator-cache.js +28 -0
  75. package/dist/src/runtime/planning-loop.js +63 -0
  76. package/dist/src/runtime/service.js +388 -0
  77. package/dist/src/runtime/session-manager.js +60 -0
  78. package/dist/src/runtime/state-observer.js +121 -0
  79. package/dist/src/runtime/vision-adapter.js +224 -0
  80. package/dist/src/supervisor/locks.js +186 -0
  81. package/dist/src/supervisor/supervisor.js +403 -0
  82. package/dist/src/supervisor/types.js +30 -0
  83. package/dist/src/test-mcp-protocol.js +154 -0
  84. package/dist/src/types.js +17 -0
  85. package/dist/src/util/atomic-write.js +118 -0
  86. package/package.json +12 -9
@@ -0,0 +1,422 @@
1
+ // Copyright (C) 2025 Clazro Technology Private Limited
2
+ // SPDX-License-Identifier: AGPL-3.0-only
3
+ //
4
+ // This file is part of ScreenHand.
5
+ //
6
+ // ScreenHand is free software: you can redistribute it and/or modify
7
+ // it under the terms of the GNU Affero General Public License as
8
+ // published by the Free Software Foundation, version 3.
9
+ //
10
+ // ScreenHand is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with ScreenHand. If not, see <https://www.gnu.org/licenses/>.
17
+ /**
18
+ * Learning Memory — JSONL persistence layer (production-ready)
19
+ *
20
+ * - All data cached in-memory for zero-latency reads
21
+ * - Disk writes are non-blocking, buffered, flushed on exit
22
+ * - Per-line JSONL parsing — corrupted lines are skipped, not fatal
23
+ * - Cache size limits with LRU eviction
24
+ * - File locking for multi-instance safety
25
+ */
26
+ import fs from "node:fs";
27
+ import path from "node:path";
28
+ import { writeFileAtomicSync } from "../util/atomic-write.js";
29
+ import { SEED_STRATEGIES } from "./seeds.js";
30
+ const MAX_ACTION_FILE_BYTES = 10 * 1024 * 1024; // 10 MB
31
+ const MAX_STRATEGIES = 500;
32
+ const MAX_ERRORS = 200;
33
+ export class MemoryStore {
34
+ dir;
35
+ // ── in-memory caches ──
36
+ strategiesCache = [];
37
+ errorsCache = [];
38
+ /** Fingerprint → Strategy index for O(1) exact lookup */
39
+ fingerprintIndex = new Map();
40
+ actionCount = 0;
41
+ actionSuccessCount = 0;
42
+ toolCounts = new Map();
43
+ initialized = false;
44
+ dirCreated = false;
45
+ /** True if ensureDir() had to create the memory directory (first boot) */
46
+ justCreatedDir = false;
47
+ // ── write buffer for flush-on-exit ──
48
+ pendingActionWrites = [];
49
+ flushTimer = null;
50
+ lockPath;
51
+ hasLock = false;
52
+ // Global flag — only register exit handlers once across all instances
53
+ static exitHandlerRegistered = false;
54
+ static activeInstance = null;
55
+ constructor(baseDir) {
56
+ this.dir = path.join(baseDir, ".screenhand", "memory");
57
+ this.lockPath = path.join(this.dir, ".lock");
58
+ }
59
+ /** Load caches from disk. Call once at startup. */
60
+ init() {
61
+ if (this.initialized)
62
+ return;
63
+ this.initialized = true;
64
+ this.ensureDir();
65
+ this.acquireLock();
66
+ this.registerExitHandler();
67
+ // Detect first boot: memory directory was just created (didn't exist before ensureDir)
68
+ const isFirstBoot = this.justCreatedDir;
69
+ this.strategiesCache = this.readLinesSafe("strategies.jsonl");
70
+ if (this.strategiesCache.length === 0 && isFirstBoot) {
71
+ for (const s of SEED_STRATEGIES)
72
+ this.strategiesCache.push(s);
73
+ this.writeLinesSync("strategies.jsonl", this.strategiesCache);
74
+ }
75
+ this.enforceStrategyLimit();
76
+ this.rebuildFingerprintIndex();
77
+ this.errorsCache = this.readLinesSafe("errors.jsonl");
78
+ this.enforceErrorLimit();
79
+ // Build action stats without caching all entries
80
+ const actions = this.readLinesSafe("actions.jsonl");
81
+ this.actionCount = actions.length;
82
+ for (const a of actions) {
83
+ if (a.success)
84
+ this.actionSuccessCount++;
85
+ this.toolCounts.set(a.tool, (this.toolCounts.get(a.tool) ?? 0) + 1);
86
+ }
87
+ }
88
+ // ── file locking ──────────────────────────────
89
+ acquireLock() {
90
+ try {
91
+ // Check for stale lock (PID no longer running)
92
+ if (fs.existsSync(this.lockPath)) {
93
+ const lockContent = fs.readFileSync(this.lockPath, "utf-8").trim();
94
+ const lockPid = parseInt(lockContent, 10);
95
+ if (lockPid && !this.isProcessRunning(lockPid)) {
96
+ // Stale lock — remove it
97
+ fs.unlinkSync(this.lockPath);
98
+ }
99
+ }
100
+ // Write our PID
101
+ fs.writeFileSync(this.lockPath, String(process.pid), { flag: "wx" });
102
+ this.hasLock = true;
103
+ }
104
+ catch {
105
+ // Another instance holds the lock — we still work but skip writes
106
+ // to avoid corruption. Reads are from our own cache (stale but safe).
107
+ this.hasLock = false;
108
+ }
109
+ }
110
+ releaseLock() {
111
+ if (this.hasLock) {
112
+ try {
113
+ fs.unlinkSync(this.lockPath);
114
+ }
115
+ catch { /* ignore */ }
116
+ this.hasLock = false;
117
+ }
118
+ }
119
+ isProcessRunning(pid) {
120
+ try {
121
+ process.kill(pid, 0);
122
+ return true;
123
+ }
124
+ catch {
125
+ return false;
126
+ }
127
+ }
128
+ // ── exit handling ─────────────────────────────
129
+ registerExitHandler() {
130
+ MemoryStore.activeInstance = this;
131
+ if (MemoryStore.exitHandlerRegistered)
132
+ return;
133
+ MemoryStore.exitHandlerRegistered = true;
134
+ const flush = () => MemoryStore.activeInstance?.flushSync();
135
+ process.on("beforeExit", flush);
136
+ process.on("exit", flush);
137
+ // SIGINT/SIGTERM — flush then re-raise
138
+ for (const sig of ["SIGINT", "SIGTERM"]) {
139
+ process.on(sig, () => {
140
+ flush();
141
+ process.exit(128 + (sig === "SIGINT" ? 2 : 15));
142
+ });
143
+ }
144
+ }
145
+ /** Synchronously flush all pending action writes to disk */
146
+ flushSync() {
147
+ if (this.pendingActionWrites.length === 0)
148
+ return;
149
+ if (!this.hasLock)
150
+ return;
151
+ try {
152
+ this.ensureDir();
153
+ const data = this.pendingActionWrites.join("");
154
+ fs.appendFileSync(this.filePath("actions.jsonl"), data);
155
+ this.pendingActionWrites = [];
156
+ }
157
+ catch {
158
+ // Non-critical on exit
159
+ }
160
+ this.releaseLock();
161
+ }
162
+ // ── helpers ────────────────────────────────────
163
+ ensureDir() {
164
+ if (!this.dirCreated) {
165
+ if (!fs.existsSync(this.dir)) {
166
+ fs.mkdirSync(this.dir, { recursive: true });
167
+ this.justCreatedDir = true;
168
+ }
169
+ this.dirCreated = true;
170
+ }
171
+ }
172
+ filePath(name) {
173
+ return path.join(this.dir, name);
174
+ }
175
+ /**
176
+ * Parse JSONL safely — skip corrupted lines instead of crashing.
177
+ * Returns all successfully parsed entries.
178
+ */
179
+ readLinesSafe(file) {
180
+ const fp = this.filePath(file);
181
+ if (!fs.existsSync(fp))
182
+ return [];
183
+ let text;
184
+ try {
185
+ text = fs.readFileSync(fp, "utf-8").trim();
186
+ }
187
+ catch {
188
+ return [];
189
+ }
190
+ if (!text)
191
+ return [];
192
+ const results = [];
193
+ for (const line of text.split("\n")) {
194
+ const trimmed = line.trim();
195
+ if (!trimmed)
196
+ continue;
197
+ try {
198
+ results.push(JSON.parse(trimmed));
199
+ }
200
+ catch {
201
+ // Skip corrupted line — don't crash
202
+ }
203
+ }
204
+ return results;
205
+ }
206
+ /** Sync full rewrite — atomic temp+rename (only if we hold lock). */
207
+ writeLinesSync(file, items) {
208
+ if (!this.hasLock)
209
+ return;
210
+ this.ensureDir();
211
+ const data = items.map((i) => JSON.stringify(i)).join("\n") + (items.length ? "\n" : "");
212
+ writeFileAtomicSync(this.filePath(file), data);
213
+ }
214
+ /** Flush all pending action writes to disk synchronously. */
215
+ async flush() {
216
+ // Cancel any debounced timer
217
+ if (this.flushTimer) {
218
+ clearTimeout(this.flushTimer);
219
+ this.flushTimer = null;
220
+ }
221
+ if (this.pendingActionWrites.length > 0 && this.hasLock) {
222
+ this.ensureDir();
223
+ const data = this.pendingActionWrites.join("");
224
+ this.pendingActionWrites = [];
225
+ fs.appendFileSync(this.filePath("actions.jsonl"), data);
226
+ }
227
+ }
228
+ fileSize(file) {
229
+ const fp = this.filePath(file);
230
+ if (!fs.existsSync(fp))
231
+ return 0;
232
+ try {
233
+ return fs.statSync(fp).size;
234
+ }
235
+ catch {
236
+ return 0;
237
+ }
238
+ }
239
+ // ── actions (buffered async write) ─────────────
240
+ appendAction(entry) {
241
+ // Update in-memory stats
242
+ this.actionCount++;
243
+ if (entry.success)
244
+ this.actionSuccessCount++;
245
+ this.toolCounts.set(entry.tool, (this.toolCounts.get(entry.tool) ?? 0) + 1);
246
+ if (!this.hasLock)
247
+ return;
248
+ this.rotateActionsIfNeeded();
249
+ // Buffer the write
250
+ this.pendingActionWrites.push(JSON.stringify(entry) + "\n");
251
+ // Schedule batch flush (debounced 100ms)
252
+ if (!this.flushTimer) {
253
+ this.flushTimer = setTimeout(() => {
254
+ this.flushTimer = null;
255
+ if (this.pendingActionWrites.length === 0)
256
+ return;
257
+ this.ensureDir();
258
+ const data = this.pendingActionWrites.join("");
259
+ this.pendingActionWrites = [];
260
+ fs.appendFile(this.filePath("actions.jsonl"), data, () => { });
261
+ }, 100);
262
+ }
263
+ }
264
+ rotateActionsIfNeeded() {
265
+ if (this.fileSize("actions.jsonl") >= MAX_ACTION_FILE_BYTES) {
266
+ const src = this.filePath("actions.jsonl");
267
+ const dst = this.filePath("actions.1.jsonl");
268
+ try {
269
+ if (fs.existsSync(dst))
270
+ fs.unlinkSync(dst);
271
+ fs.renameSync(src, dst);
272
+ }
273
+ catch {
274
+ // Non-critical
275
+ }
276
+ }
277
+ }
278
+ /** Read actions from disk (only used by stats/clear, not in hot path) */
279
+ readActions() {
280
+ return this.readLinesSafe("actions.jsonl");
281
+ }
282
+ // ── strategies (cached + fingerprint indexed + LRU capped) ──
283
+ rebuildFingerprintIndex() {
284
+ this.fingerprintIndex.clear();
285
+ for (const s of this.strategiesCache) {
286
+ if (s.fingerprint) {
287
+ this.fingerprintIndex.set(s.fingerprint, s);
288
+ }
289
+ }
290
+ }
291
+ /** Evict least-recently-used strategies beyond MAX_STRATEGIES */
292
+ enforceStrategyLimit() {
293
+ if (this.strategiesCache.length <= MAX_STRATEGIES)
294
+ return;
295
+ // Sort by lastUsed ascending (oldest first), remove from the front
296
+ this.strategiesCache.sort((a, b) => new Date(a.lastUsed).getTime() - new Date(b.lastUsed).getTime());
297
+ this.strategiesCache = this.strategiesCache.slice(-MAX_STRATEGIES);
298
+ }
299
+ appendStrategy(strategy) {
300
+ // Ensure fingerprint exists
301
+ if (!strategy.fingerprint) {
302
+ strategy.fingerprint = MemoryStore.makeFingerprint(strategy.steps.map((s) => s.tool));
303
+ }
304
+ const idx = this.strategiesCache.findIndex((s) => s.task === strategy.task);
305
+ if (idx >= 0) {
306
+ const old = this.strategiesCache[idx];
307
+ this.strategiesCache[idx] = {
308
+ ...strategy,
309
+ successCount: old.successCount + 1,
310
+ failCount: old.failCount ?? 0,
311
+ lastUsed: strategy.lastUsed,
312
+ };
313
+ this.fingerprintIndex.set(strategy.fingerprint, this.strategiesCache[idx]);
314
+ }
315
+ else {
316
+ this.strategiesCache.push(strategy);
317
+ this.fingerprintIndex.set(strategy.fingerprint, strategy);
318
+ this.enforceStrategyLimit();
319
+ // Rebuild index after eviction
320
+ if (this.strategiesCache.length >= MAX_STRATEGIES) {
321
+ this.rebuildFingerprintIndex();
322
+ }
323
+ }
324
+ this.writeLinesSync("strategies.jsonl", this.strategiesCache);
325
+ }
326
+ /** O(1) exact lookup by tool sequence fingerprint */
327
+ lookupByFingerprint(fingerprint) {
328
+ return this.fingerprintIndex.get(fingerprint);
329
+ }
330
+ /** Record that a recalled strategy succeeded or failed */
331
+ recordStrategyOutcome(fingerprint, success) {
332
+ const strategy = this.fingerprintIndex.get(fingerprint);
333
+ if (!strategy)
334
+ return;
335
+ if (success) {
336
+ strategy.successCount++;
337
+ strategy.lastUsed = new Date().toISOString();
338
+ }
339
+ else {
340
+ strategy.failCount = (strategy.failCount ?? 0) + 1;
341
+ }
342
+ this.writeLinesSync("strategies.jsonl", this.strategiesCache);
343
+ }
344
+ /** Read from cache — ~0ms */
345
+ readStrategies() {
346
+ return this.strategiesCache;
347
+ }
348
+ /** Generate a fingerprint from a tool sequence */
349
+ static makeFingerprint(tools) {
350
+ return tools.join("→");
351
+ }
352
+ // ── errors (cached + LRU capped) ──────────────
353
+ /** Evict least-recently-seen errors beyond MAX_ERRORS */
354
+ enforceErrorLimit() {
355
+ if (this.errorsCache.length <= MAX_ERRORS)
356
+ return;
357
+ this.errorsCache.sort((a, b) => new Date(a.lastSeen).getTime() - new Date(b.lastSeen).getTime());
358
+ this.errorsCache = this.errorsCache.slice(-MAX_ERRORS);
359
+ }
360
+ appendError(pattern) {
361
+ const idx = this.errorsCache.findIndex((e) => e.tool === pattern.tool && e.error === pattern.error);
362
+ if (idx >= 0) {
363
+ this.errorsCache[idx] = {
364
+ ...this.errorsCache[idx],
365
+ occurrences: this.errorsCache[idx].occurrences + 1,
366
+ lastSeen: pattern.lastSeen,
367
+ resolution: pattern.resolution ?? this.errorsCache[idx].resolution,
368
+ };
369
+ }
370
+ else {
371
+ this.errorsCache.push(pattern);
372
+ this.enforceErrorLimit();
373
+ }
374
+ this.writeLinesSync("errors.jsonl", this.errorsCache);
375
+ }
376
+ /** Read from cache — ~0ms */
377
+ readErrors() {
378
+ return this.errorsCache;
379
+ }
380
+ // ── stats (from in-memory counters) ────────────
381
+ getStats() {
382
+ const topTools = [...this.toolCounts.entries()]
383
+ .sort((a, b) => b[1] - a[1])
384
+ .slice(0, 10)
385
+ .map(([tool, count]) => ({ tool, count }));
386
+ const diskUsageBytes = this.fileSize("actions.jsonl") +
387
+ this.fileSize("strategies.jsonl") +
388
+ this.fileSize("errors.jsonl");
389
+ return {
390
+ totalActions: this.actionCount,
391
+ totalStrategies: this.strategiesCache.length,
392
+ totalErrors: this.errorsCache.length,
393
+ diskUsageBytes,
394
+ topTools,
395
+ successRate: this.actionCount > 0 ? this.actionSuccessCount / this.actionCount : 0,
396
+ };
397
+ }
398
+ // ── clear ──────────────────────────────────────
399
+ clear(what) {
400
+ const targets = what === "all"
401
+ ? ["actions", "strategies", "errors"]
402
+ : [what];
403
+ for (const category of targets) {
404
+ const fp = this.filePath(`${category}.jsonl`);
405
+ if (fs.existsSync(fp))
406
+ fs.writeFileSync(fp, "");
407
+ if (category === "actions") {
408
+ this.actionCount = 0;
409
+ this.actionSuccessCount = 0;
410
+ this.toolCounts.clear();
411
+ this.pendingActionWrites = [];
412
+ }
413
+ else if (category === "strategies") {
414
+ this.strategiesCache = [];
415
+ this.fingerprintIndex.clear();
416
+ }
417
+ else if (category === "errors") {
418
+ this.errorsCache = [];
419
+ }
420
+ }
421
+ }
422
+ }
@@ -0,0 +1,17 @@
1
+ // Copyright (C) 2025 Clazro Technology Private Limited
2
+ // SPDX-License-Identifier: AGPL-3.0-only
3
+ //
4
+ // This file is part of ScreenHand.
5
+ //
6
+ // ScreenHand is free software: you can redistribute it and/or modify
7
+ // it under the terms of the GNU Affero General Public License as
8
+ // published by the Free Software Foundation, version 3.
9
+ //
10
+ // ScreenHand is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with ScreenHand. If not, see <https://www.gnu.org/licenses/>.
17
+ export {};