screenhand 0.2.0 → 0.3.1

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 (212) hide show
  1. package/README.md +165 -446
  2. package/bin/darwin-arm64/macos-bridge +0 -0
  3. package/dist/mcp-desktop.js +3615 -400
  4. package/dist/scripts/export-help-center.js +112 -0
  5. package/dist/scripts/marketing-loop.js +117 -0
  6. package/dist/scripts/observer-daemon.js +288 -0
  7. package/dist/scripts/orchestrator-daemon.js +399 -0
  8. package/dist/scripts/threads-campaign.js +208 -0
  9. package/dist/src/community/fetcher.js +109 -0
  10. package/dist/src/community/index.js +6 -0
  11. package/dist/src/community/publisher.js +191 -0
  12. package/dist/src/community/remote-api.js +121 -0
  13. package/dist/src/community/types.js +3 -0
  14. package/dist/src/community/validator.js +95 -0
  15. package/dist/src/context-tracker.js +489 -0
  16. package/dist/src/ingestion/coverage-auditor.js +233 -0
  17. package/dist/src/ingestion/doc-parser.js +164 -0
  18. package/dist/src/ingestion/index.js +8 -0
  19. package/dist/src/ingestion/menu-scanner.js +152 -0
  20. package/dist/src/ingestion/reference-merger.js +186 -0
  21. package/dist/src/ingestion/shortcut-extractor.js +180 -0
  22. package/dist/src/ingestion/tutorial-extractor.js +170 -0
  23. package/dist/src/ingestion/types.js +3 -0
  24. package/dist/src/jobs/manager.js +82 -14
  25. package/dist/src/jobs/runner.js +138 -15
  26. package/dist/src/learning/engine.js +356 -0
  27. package/dist/src/learning/index.js +9 -0
  28. package/dist/src/learning/locator-policy.js +120 -0
  29. package/dist/src/learning/pattern-policy.js +89 -0
  30. package/dist/src/learning/recovery-policy.js +116 -0
  31. package/dist/src/learning/sensor-policy.js +115 -0
  32. package/dist/src/learning/timing-model.js +204 -0
  33. package/dist/src/learning/topology-policy.js +90 -0
  34. package/dist/src/learning/types.js +9 -0
  35. package/dist/src/logging/timeline-logger.js +4 -1
  36. package/dist/src/memory/playbook-seeds.js +200 -0
  37. package/dist/src/memory/recall.js +60 -8
  38. package/dist/src/memory/service.js +30 -5
  39. package/dist/src/memory/store.js +34 -5
  40. package/dist/src/native/bridge-client.js +253 -31
  41. package/dist/src/observer/state.js +199 -0
  42. package/dist/src/observer/types.js +43 -0
  43. package/dist/src/orchestrator/state.js +68 -0
  44. package/dist/src/orchestrator/types.js +22 -0
  45. package/dist/src/perception/ax-source.js +162 -0
  46. package/dist/src/perception/cdp-source.js +162 -0
  47. package/dist/src/perception/coordinator.js +771 -0
  48. package/dist/src/perception/frame-differ.js +287 -0
  49. package/dist/src/perception/index.js +22 -0
  50. package/dist/src/perception/manager.js +199 -0
  51. package/dist/src/perception/types.js +47 -0
  52. package/dist/src/perception/vision-source.js +399 -0
  53. package/dist/src/planner/deterministic.js +298 -0
  54. package/dist/src/planner/executor.js +870 -0
  55. package/dist/src/planner/goal-store.js +92 -0
  56. package/dist/src/planner/index.js +21 -0
  57. package/dist/src/planner/planner.js +520 -0
  58. package/dist/src/planner/tool-registry.js +71 -0
  59. package/dist/src/planner/types.js +22 -0
  60. package/dist/src/platform/explorer.js +213 -0
  61. package/dist/src/platform/help-center-markdown.js +527 -0
  62. package/dist/src/platform/learner.js +257 -0
  63. package/dist/src/playbook/engine.js +296 -11
  64. package/dist/src/playbook/mcp-recorder.js +204 -0
  65. package/dist/src/playbook/recorder.js +3 -2
  66. package/dist/src/playbook/runner.js +1 -1
  67. package/dist/src/playbook/store.js +139 -10
  68. package/dist/src/recovery/detectors.js +156 -0
  69. package/dist/src/recovery/engine.js +327 -0
  70. package/dist/src/recovery/index.js +20 -0
  71. package/dist/src/recovery/strategies.js +274 -0
  72. package/dist/src/recovery/types.js +20 -0
  73. package/dist/src/runtime/accessibility-adapter.js +55 -18
  74. package/dist/src/runtime/applescript-adapter.js +8 -2
  75. package/dist/src/runtime/cdp-chrome-adapter.js +1 -1
  76. package/dist/src/runtime/executor.js +23 -3
  77. package/dist/src/runtime/locator-cache.js +24 -2
  78. package/dist/src/runtime/service.js +59 -15
  79. package/dist/src/runtime/session-manager.js +4 -1
  80. package/dist/src/runtime/vision-adapter.js +2 -1
  81. package/dist/src/state/app-map-types.js +72 -0
  82. package/dist/src/state/app-map.js +1974 -0
  83. package/dist/src/state/entity-tracker.js +108 -0
  84. package/dist/src/state/fusion.js +96 -0
  85. package/dist/src/state/index.js +21 -0
  86. package/dist/src/state/ladder-generator.js +236 -0
  87. package/dist/src/state/persistence.js +156 -0
  88. package/dist/src/state/types.js +17 -0
  89. package/dist/src/state/world-model.js +1456 -0
  90. package/dist/src/util/atomic-write.js +19 -4
  91. package/dist/src/util/sanitize.js +146 -0
  92. package/dist-app-maps/com.figma.Desktop.json +959 -0
  93. package/dist-app-maps/com.hnc.Discord.json +1146 -0
  94. package/dist-app-maps/notion.id.json +2831 -0
  95. package/dist-playbooks/canva-screenhand-carousel.json +445 -0
  96. package/dist-playbooks/codex-desktop.json +76 -0
  97. package/dist-playbooks/competitor-research-stack.json +122 -0
  98. package/dist-playbooks/davinci-color-grade.json +153 -0
  99. package/dist-playbooks/davinci-edit-timeline.json +162 -0
  100. package/dist-playbooks/davinci-render.json +114 -0
  101. package/dist-playbooks/devto.json +52 -0
  102. package/dist-playbooks/discord.json +41 -0
  103. package/dist-playbooks/google-flow-create-project.json +59 -0
  104. package/dist-playbooks/google-flow-edit-image.json +90 -0
  105. package/dist-playbooks/google-flow-edit-video.json +90 -0
  106. package/dist-playbooks/google-flow-generate-image.json +68 -0
  107. package/dist-playbooks/google-flow-generate-video.json +191 -0
  108. package/dist-playbooks/google-flow-open-project.json +48 -0
  109. package/dist-playbooks/google-flow-open-scenebuilder.json +64 -0
  110. package/dist-playbooks/google-flow-search-assets.json +64 -0
  111. package/dist-playbooks/instagram.json +57 -0
  112. package/dist-playbooks/linkedin.json +52 -0
  113. package/dist-playbooks/n8n.json +43 -0
  114. package/dist-playbooks/reddit.json +52 -0
  115. package/dist-playbooks/threads.json +59 -0
  116. package/dist-playbooks/x-twitter.json +59 -0
  117. package/dist-playbooks/youtube.json +59 -0
  118. package/dist-references/canva.json +646 -0
  119. package/dist-references/codex-desktop.json +305 -0
  120. package/dist-references/davinci-resolve-keyboard.json +594 -0
  121. package/dist-references/davinci-resolve-menu-map.json +1139 -0
  122. package/dist-references/davinci-resolve-menus-batch1.json +116 -0
  123. package/dist-references/davinci-resolve-menus-batch2.json +372 -0
  124. package/dist-references/davinci-resolve-menus-batch3.json +330 -0
  125. package/dist-references/davinci-resolve-menus-batch4.json +297 -0
  126. package/dist-references/davinci-resolve-shortcuts.json +333 -0
  127. package/dist-references/devpost.json +186 -0
  128. package/dist-references/devto.json +317 -0
  129. package/dist-references/discord.json +549 -0
  130. package/dist-references/figma.json +1186 -0
  131. package/dist-references/finder.json +146 -0
  132. package/dist-references/google-ads-transparency.json +95 -0
  133. package/dist-references/google-flow.json +649 -0
  134. package/dist-references/instagram.json +341 -0
  135. package/dist-references/linkedin.json +324 -0
  136. package/dist-references/meta-ad-library.json +86 -0
  137. package/dist-references/n8n.json +387 -0
  138. package/dist-references/notes.json +27 -0
  139. package/dist-references/notion.json +163 -0
  140. package/dist-references/reddit.json +341 -0
  141. package/dist-references/threads.json +337 -0
  142. package/dist-references/x-twitter.json +403 -0
  143. package/dist-references/youtube.json +373 -0
  144. package/native/macos-bridge/Package.swift +22 -0
  145. package/native/macos-bridge/Sources/AccessibilityBridge.swift +482 -0
  146. package/native/macos-bridge/Sources/AppManagement.swift +339 -0
  147. package/native/macos-bridge/Sources/CoreGraphicsBridge.swift +537 -0
  148. package/native/macos-bridge/Sources/ObserverBridge.swift +120 -0
  149. package/native/macos-bridge/Sources/StreamCapture.swift +136 -0
  150. package/native/macos-bridge/Sources/VisionBridge.swift +238 -0
  151. package/native/macos-bridge/Sources/main.swift +498 -0
  152. package/native/windows-bridge/AppManagement.cs +234 -0
  153. package/native/windows-bridge/InputBridge.cs +436 -0
  154. package/native/windows-bridge/Program.cs +270 -0
  155. package/native/windows-bridge/ScreenCapture.cs +453 -0
  156. package/native/windows-bridge/UIAutomationBridge.cs +571 -0
  157. package/native/windows-bridge/WindowsBridge.csproj +17 -0
  158. package/package.json +12 -1
  159. package/scripts/postinstall.cjs +127 -0
  160. package/dist/.audit-log.jsonl +0 -55
  161. package/dist/.screenhand/memory/.lock +0 -1
  162. package/dist/.screenhand/memory/actions.jsonl +0 -85
  163. package/dist/.screenhand/memory/errors.jsonl +0 -5
  164. package/dist/.screenhand/memory/errors.jsonl.bak +0 -4
  165. package/dist/.screenhand/memory/state.json +0 -35
  166. package/dist/.screenhand/memory/state.json.bak +0 -35
  167. package/dist/.screenhand/memory/strategies.jsonl +0 -12
  168. package/dist/agent/cli.js +0 -73
  169. package/dist/agent/loop.js +0 -258
  170. package/dist/config.js +0 -9
  171. package/dist/index.js +0 -56
  172. package/dist/logging/timeline-logger.js +0 -29
  173. package/dist/mcp/mcp-stdio-server.js +0 -448
  174. package/dist/mcp/server.js +0 -347
  175. package/dist/mcp-entry.js +0 -59
  176. package/dist/memory/recall.js +0 -160
  177. package/dist/memory/research.js +0 -98
  178. package/dist/memory/seeds.js +0 -89
  179. package/dist/memory/session.js +0 -161
  180. package/dist/memory/store.js +0 -391
  181. package/dist/memory/types.js +0 -4
  182. package/dist/monitor/codex-monitor.js +0 -377
  183. package/dist/monitor/task-queue.js +0 -84
  184. package/dist/monitor/types.js +0 -49
  185. package/dist/native/bridge-client.js +0 -174
  186. package/dist/native/macos-bridge-client.js +0 -5
  187. package/dist/npm-publish-helper.js +0 -117
  188. package/dist/npm-token-cdp.js +0 -113
  189. package/dist/npm-token-create.js +0 -135
  190. package/dist/npm-token-finish.js +0 -126
  191. package/dist/playbook/engine.js +0 -193
  192. package/dist/playbook/index.js +0 -4
  193. package/dist/playbook/recorder.js +0 -519
  194. package/dist/playbook/runner.js +0 -392
  195. package/dist/playbook/store.js +0 -166
  196. package/dist/playbook/types.js +0 -4
  197. package/dist/runtime/accessibility-adapter.js +0 -377
  198. package/dist/runtime/app-adapter.js +0 -48
  199. package/dist/runtime/applescript-adapter.js +0 -283
  200. package/dist/runtime/ax-role-map.js +0 -80
  201. package/dist/runtime/browser-adapter.js +0 -36
  202. package/dist/runtime/cdp-chrome-adapter.js +0 -505
  203. package/dist/runtime/composite-adapter.js +0 -205
  204. package/dist/runtime/executor.js +0 -250
  205. package/dist/runtime/locator-cache.js +0 -12
  206. package/dist/runtime/planning-loop.js +0 -47
  207. package/dist/runtime/service.js +0 -372
  208. package/dist/runtime/session-manager.js +0 -28
  209. package/dist/runtime/state-observer.js +0 -105
  210. package/dist/runtime/vision-adapter.js +0 -208
  211. package/dist/test-mcp-protocol.js +0 -138
  212. package/dist/types.js +0 -1
@@ -1,89 +0,0 @@
1
- /**
2
- * Predefined seed strategies — common macOS desktop workflows.
3
- * Loaded on first boot so the memory system has knowledge from day one.
4
- */
5
- let seedCounter = 0;
6
- function makeFingerprint(tools) {
7
- return tools.join("→");
8
- }
9
- function seed(task, steps, tags) {
10
- seedCounter++;
11
- return {
12
- id: `seed_${String(seedCounter).padStart(3, "0")}`,
13
- task,
14
- steps,
15
- totalDurationMs: 0,
16
- successCount: 10,
17
- failCount: 0,
18
- lastUsed: new Date().toISOString(),
19
- tags,
20
- fingerprint: makeFingerprint(steps.map((s) => s.tool)),
21
- };
22
- }
23
- export const SEED_STRATEGIES = [
24
- // 1. Take a photo with Photo Booth
25
- seed("Take a photo with Photo Booth", [
26
- { tool: "launch", params: { bundleId: "com.apple.PhotoBooth" } },
27
- { tool: "ui_press", params: { title: "Take Photo" } },
28
- ], ["photo", "booth", "camera"]),
29
- // 2. Open a URL in Chrome
30
- seed("Open a URL in Chrome", [
31
- { tool: "launch", params: { bundleId: "com.google.Chrome" } },
32
- { tool: "browser_navigate", params: { url: "" } },
33
- ], ["chrome", "browse", "url"]),
34
- // 3. Save current document
35
- seed("Save current document", [
36
- { tool: "focus", params: { bundleId: "" } },
37
- { tool: "key", params: { combo: "cmd+s" } },
38
- ], ["save", "document"]),
39
- // 4. Copy from one app and paste into another
40
- seed("Copy from one app and paste into another", [
41
- { tool: "focus", params: { bundleId: "" } },
42
- { tool: "key", params: { combo: "cmd+c" } },
43
- { tool: "focus", params: { bundleId: "" } },
44
- { tool: "key", params: { combo: "cmd+v" } },
45
- ], ["copy", "paste"]),
46
- // 5. Navigate to a folder in Finder
47
- seed("Navigate to a folder in Finder", [
48
- { tool: "focus", params: { bundleId: "com.apple.finder" } },
49
- { tool: "key", params: { combo: "cmd+shift+g" } },
50
- { tool: "type_text", params: { text: "" } },
51
- ], ["finder", "folder", "navigate"]),
52
- // 6. Create a new folder in Finder
53
- seed("Create a new folder in Finder", [
54
- { tool: "focus", params: { bundleId: "com.apple.finder" } },
55
- { tool: "key", params: { combo: "cmd+shift+n" } },
56
- { tool: "type_text", params: { text: "" } },
57
- ], ["finder", "folder", "create"]),
58
- // 7. Close the current window
59
- seed("Close the current window", [
60
- { tool: "focus", params: { bundleId: "" } },
61
- { tool: "key", params: { combo: "cmd+w" } },
62
- ], ["close", "window"]),
63
- // 8. Select all and copy
64
- seed("Select all content and copy", [
65
- { tool: "focus", params: { bundleId: "" } },
66
- { tool: "key", params: { combo: "cmd+a" } },
67
- { tool: "key", params: { combo: "cmd+c" } },
68
- ], ["select", "all", "copy"]),
69
- // 9. List running apps
70
- seed("List all running applications", [
71
- { tool: "apps", params: {} },
72
- ], ["apps", "list", "running"]),
73
- // 10. Inspect app UI tree
74
- seed("Inspect an app's UI element tree", [
75
- { tool: "focus", params: { bundleId: "" } },
76
- { tool: "ui_tree", params: { pid: 0 } },
77
- ], ["inspect", "tree", "accessibility"]),
78
- // 11. Open a new tab in Chrome and navigate
79
- seed("Open a new Chrome tab and navigate to URL", [
80
- { tool: "focus", params: { bundleId: "com.google.Chrome" } },
81
- { tool: "key", params: { combo: "cmd+t" } },
82
- { tool: "browser_navigate", params: { url: "" } },
83
- ], ["chrome", "tab", "new"]),
84
- // 12. Export as PDF via menu
85
- seed("Export document as PDF", [
86
- { tool: "focus", params: { bundleId: "" } },
87
- { tool: "menu_click", params: { menuPath: "File/Export as PDF" } },
88
- ], ["export", "pdf"]),
89
- ];
@@ -1,161 +0,0 @@
1
- /**
2
- * Learning Memory — Session tracking with auto-save
3
- *
4
- * Tracks a rolling buffer of actions within a "task session".
5
- * Auto-saves strategies when a successful sequence is detected:
6
- * - 3+ consecutive successes followed by a gap (>60s) or session end
7
- * - Or explicit endSession() call
8
- */
9
- import { MemoryStore } from "./store.js";
10
- const SESSION_GAP_MS = 60_000; // 60s gap = new session
11
- const MAX_BUFFER_SIZE = 100;
12
- const MIN_AUTO_SAVE_STEPS = 3; // Need at least 3 successful steps to auto-save
13
- export class SessionTracker {
14
- store;
15
- sessionId;
16
- taskDescription = null;
17
- buffer = [];
18
- lastActionTime = 0;
19
- constructor(store) {
20
- this.store = store;
21
- this.sessionId = SessionTracker.generateId();
22
- }
23
- static generateId() {
24
- return "s_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
25
- }
26
- /** Start (or restart) a named task session */
27
- startSession(taskDescription) {
28
- // Auto-save previous session if it had successful actions
29
- this.tryAutoSave();
30
- this.sessionId = SessionTracker.generateId();
31
- this.taskDescription = taskDescription ?? null;
32
- this.buffer = [];
33
- this.lastActionTime = Date.now();
34
- return this.sessionId;
35
- }
36
- /** Get the current session ID, auto-rotating if stale */
37
- getSessionId() {
38
- const now = Date.now();
39
- if (this.lastActionTime > 0 && now - this.lastActionTime > SESSION_GAP_MS) {
40
- // Session gap detected — auto-save previous sequence then start fresh
41
- this.tryAutoSave();
42
- this.sessionId = SessionTracker.generateId();
43
- this.buffer = [];
44
- this.taskDescription = null;
45
- }
46
- return this.sessionId;
47
- }
48
- /** Record an action into the current session buffer */
49
- recordAction(entry) {
50
- const now = Date.now();
51
- if (this.lastActionTime > 0 && now - this.lastActionTime > SESSION_GAP_MS) {
52
- // Gap detected — auto-save then start new session
53
- this.tryAutoSave();
54
- this.sessionId = SessionTracker.generateId();
55
- this.buffer = [];
56
- this.taskDescription = null;
57
- }
58
- this.lastActionTime = now;
59
- this.buffer.push(entry);
60
- if (this.buffer.length > MAX_BUFFER_SIZE) {
61
- this.buffer.shift();
62
- }
63
- }
64
- /** End the session and save a strategy if successful */
65
- endSession(success, taskDescription) {
66
- const task = taskDescription ?? this.taskDescription;
67
- if (!success || !task || this.buffer.length === 0) {
68
- this.buffer = [];
69
- return null;
70
- }
71
- const strategy = this.buildStrategy(task, this.buffer);
72
- this.store.appendStrategy(strategy);
73
- this.buffer = [];
74
- return strategy;
75
- }
76
- /** Get the current session's action buffer */
77
- getBuffer() {
78
- return [...this.buffer];
79
- }
80
- /** Get recent tool names (for strategy hint matching) */
81
- getRecentToolNames(limit = 10) {
82
- return this.buffer.slice(-limit).map((a) => a.tool);
83
- }
84
- /** Get current task description */
85
- getTaskDescription() {
86
- return this.taskDescription;
87
- }
88
- // ── auto-save logic ────────────────────────────
89
- /**
90
- * Try to auto-save the current buffer as a strategy.
91
- * Only saves if there are MIN_AUTO_SAVE_STEPS+ consecutive successes.
92
- * Uses tool sequence as task description if no explicit one was given.
93
- */
94
- tryAutoSave() {
95
- if (this.buffer.length < MIN_AUTO_SAVE_STEPS)
96
- return;
97
- // Find the longest trailing streak of successes
98
- let successStreak = [];
99
- for (let i = this.buffer.length - 1; i >= 0; i--) {
100
- if (this.buffer[i].success) {
101
- successStreak.unshift(this.buffer[i]);
102
- }
103
- else {
104
- break;
105
- }
106
- }
107
- if (successStreak.length < MIN_AUTO_SAVE_STEPS)
108
- return;
109
- // Build a task description from the tool sequence if none provided
110
- const task = this.taskDescription ?? this.inferTaskDescription(successStreak);
111
- const strategy = this.buildStrategy(task, successStreak);
112
- this.store.appendStrategy(strategy);
113
- }
114
- /** Infer a task description from a sequence of actions */
115
- inferTaskDescription(actions) {
116
- const tools = [...new Set(actions.map((a) => a.tool))];
117
- // Extract key param values (bundle IDs, titles, URLs, etc.)
118
- const keyParams = [];
119
- for (const a of actions) {
120
- for (const [key, val] of Object.entries(a.params)) {
121
- if (typeof val === "string" && val.length > 2 && val.length < 60) {
122
- if (["bundleId", "title", "url", "text", "script", "selector", "menuPath"].includes(key)) {
123
- keyParams.push(val);
124
- }
125
- }
126
- }
127
- }
128
- const paramHint = keyParams.length > 0 ? ` (${keyParams.slice(0, 3).join(", ")})` : "";
129
- return `${tools.join(" → ")}${paramHint}`;
130
- }
131
- buildStrategy(task, actions) {
132
- const steps = actions.map((a) => ({
133
- tool: a.tool,
134
- params: a.params,
135
- }));
136
- const totalDurationMs = actions.reduce((sum, a) => sum + a.durationMs, 0);
137
- const tags = extractTags(task, steps);
138
- const fingerprint = MemoryStore.makeFingerprint(steps.map((s) => s.tool));
139
- return {
140
- id: "str_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
141
- task,
142
- steps,
143
- totalDurationMs,
144
- successCount: 1,
145
- failCount: 0,
146
- lastUsed: new Date().toISOString(),
147
- tags,
148
- fingerprint,
149
- };
150
- }
151
- }
152
- /** Extract tags from task description and tool names */
153
- function extractTags(task, steps) {
154
- const tags = new Set();
155
- const words = task.toLowerCase().split(/\W+/).filter((w) => w.length >= 3);
156
- for (const w of words)
157
- tags.add(w);
158
- for (const s of steps)
159
- tags.add(s.tool);
160
- return [...tags];
161
- }
@@ -1,391 +0,0 @@
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
- }
@@ -1,4 +0,0 @@
1
- /**
2
- * Learning Memory — Data types
3
- */
4
- export {};