screenhand 0.1.1 → 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.
- package/README.md +458 -93
- package/dist/.audit-log.jsonl +55 -0
- package/dist/.screenhand/memory/.lock +1 -0
- package/dist/.screenhand/memory/actions.jsonl +85 -0
- package/dist/.screenhand/memory/errors.jsonl +5 -0
- package/dist/.screenhand/memory/errors.jsonl.bak +4 -0
- package/dist/.screenhand/memory/state.json +35 -0
- package/dist/.screenhand/memory/state.json.bak +35 -0
- package/dist/.screenhand/memory/strategies.jsonl +12 -0
- package/dist/agent/cli.js +73 -0
- package/dist/agent/loop.js +258 -0
- package/dist/config.js +9 -0
- package/dist/index.js +56 -0
- package/dist/logging/timeline-logger.js +29 -0
- package/dist/mcp/mcp-stdio-server.js +448 -0
- package/dist/mcp/server.js +347 -0
- package/dist/mcp-desktop.js +2731 -0
- package/dist/mcp-entry.js +59 -0
- package/dist/memory/recall.js +160 -0
- package/dist/memory/research.js +98 -0
- package/dist/memory/seeds.js +89 -0
- package/dist/memory/session.js +161 -0
- package/dist/memory/store.js +391 -0
- package/dist/memory/types.js +4 -0
- package/dist/monitor/codex-monitor.js +377 -0
- package/dist/monitor/task-queue.js +84 -0
- package/dist/monitor/types.js +49 -0
- package/dist/native/bridge-client.js +174 -0
- package/dist/native/macos-bridge-client.js +5 -0
- package/dist/npm-publish-helper.js +117 -0
- package/dist/npm-token-cdp.js +113 -0
- package/dist/npm-token-create.js +135 -0
- package/dist/npm-token-finish.js +126 -0
- package/dist/playbook/engine.js +193 -0
- package/dist/playbook/index.js +4 -0
- package/dist/playbook/recorder.js +519 -0
- package/dist/playbook/runner.js +392 -0
- package/dist/playbook/store.js +166 -0
- package/dist/playbook/types.js +4 -0
- package/dist/runtime/accessibility-adapter.js +377 -0
- package/dist/runtime/app-adapter.js +48 -0
- package/dist/runtime/applescript-adapter.js +283 -0
- package/dist/runtime/ax-role-map.js +80 -0
- package/dist/runtime/browser-adapter.js +36 -0
- package/dist/runtime/cdp-chrome-adapter.js +505 -0
- package/dist/runtime/composite-adapter.js +205 -0
- package/dist/runtime/executor.js +250 -0
- package/dist/runtime/locator-cache.js +12 -0
- package/dist/runtime/planning-loop.js +47 -0
- package/dist/runtime/service.js +372 -0
- package/dist/runtime/session-manager.js +28 -0
- package/dist/runtime/state-observer.js +105 -0
- package/dist/runtime/vision-adapter.js +208 -0
- package/dist/scripts/codex-monitor-daemon.js +335 -0
- package/dist/scripts/supervisor-daemon.js +272 -0
- package/dist/scripts/worker-daemon.js +228 -0
- package/dist/src/agent/cli.js +82 -0
- package/dist/src/agent/loop.js +274 -0
- package/{src/config.ts → dist/src/config.js} +5 -10
- package/{src/index.ts → dist/src/index.js} +32 -52
- package/dist/src/jobs/manager.js +237 -0
- package/dist/src/jobs/runner.js +683 -0
- package/dist/src/jobs/store.js +102 -0
- package/dist/src/jobs/types.js +30 -0
- package/dist/src/jobs/worker.js +97 -0
- package/dist/src/logging/timeline-logger.js +45 -0
- package/dist/src/mcp/mcp-stdio-server.js +464 -0
- package/dist/src/mcp/server.js +363 -0
- package/dist/src/mcp-entry.js +60 -0
- package/dist/src/memory/recall.js +170 -0
- package/dist/src/memory/research.js +104 -0
- package/dist/src/memory/seeds.js +101 -0
- package/dist/src/memory/service.js +421 -0
- package/dist/src/memory/session.js +169 -0
- package/dist/src/memory/store.js +422 -0
- package/dist/src/memory/types.js +17 -0
- package/dist/src/monitor/codex-monitor.js +382 -0
- package/dist/src/monitor/task-queue.js +97 -0
- package/dist/src/monitor/types.js +62 -0
- package/dist/src/native/bridge-client.js +190 -0
- package/{src/native/macos-bridge-client.ts → dist/src/native/macos-bridge-client.js} +0 -1
- package/dist/src/playbook/engine.js +201 -0
- package/dist/src/playbook/index.js +20 -0
- package/dist/src/playbook/recorder.js +535 -0
- package/dist/src/playbook/runner.js +408 -0
- package/dist/src/playbook/store.js +183 -0
- package/dist/src/playbook/types.js +17 -0
- package/dist/src/runtime/accessibility-adapter.js +393 -0
- package/dist/src/runtime/app-adapter.js +64 -0
- package/dist/src/runtime/applescript-adapter.js +299 -0
- package/dist/src/runtime/ax-role-map.js +96 -0
- package/dist/src/runtime/browser-adapter.js +52 -0
- package/dist/src/runtime/cdp-chrome-adapter.js +521 -0
- package/dist/src/runtime/composite-adapter.js +221 -0
- package/dist/src/runtime/execution-contract.js +159 -0
- package/dist/src/runtime/executor.js +266 -0
- package/{src/runtime/locator-cache.ts → dist/src/runtime/locator-cache.js} +10 -15
- package/dist/src/runtime/planning-loop.js +63 -0
- package/dist/src/runtime/service.js +388 -0
- package/dist/src/runtime/session-manager.js +60 -0
- package/dist/src/runtime/state-observer.js +121 -0
- package/dist/src/runtime/vision-adapter.js +224 -0
- package/dist/src/supervisor/locks.js +186 -0
- package/dist/src/supervisor/supervisor.js +403 -0
- package/dist/src/supervisor/types.js +30 -0
- package/dist/src/test-mcp-protocol.js +154 -0
- package/dist/src/types.js +17 -0
- package/dist/src/util/atomic-write.js +118 -0
- package/dist/test-mcp-protocol.js +138 -0
- package/dist/types.js +1 -0
- package/package.json +18 -4
- package/.claude/commands/automate.md +0 -28
- package/.claude/commands/debug-ui.md +0 -19
- package/.claude/commands/screenshot.md +0 -15
- package/.github/FUNDING.yml +0 -1
- package/.github/ISSUE_TEMPLATE/bug_report.md +0 -27
- package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
- package/.mcp.json +0 -8
- package/DESKTOP_MCP_GUIDE.md +0 -92
- package/SECURITY.md +0 -44
- package/docs/architecture.md +0 -47
- package/install-skills.sh +0 -19
- package/mcp-bridge.ts +0 -271
- package/mcp-desktop.ts +0 -1221
- package/native/macos-bridge/Package.swift +0 -21
- package/native/macos-bridge/Sources/AccessibilityBridge.swift +0 -261
- package/native/macos-bridge/Sources/AppManagement.swift +0 -129
- package/native/macos-bridge/Sources/CoreGraphicsBridge.swift +0 -242
- package/native/macos-bridge/Sources/ObserverBridge.swift +0 -120
- package/native/macos-bridge/Sources/VisionBridge.swift +0 -80
- package/native/macos-bridge/Sources/main.swift +0 -345
- package/native/windows-bridge/AppManagement.cs +0 -234
- package/native/windows-bridge/InputBridge.cs +0 -436
- package/native/windows-bridge/Program.cs +0 -265
- package/native/windows-bridge/ScreenCapture.cs +0 -329
- package/native/windows-bridge/UIAutomationBridge.cs +0 -571
- package/native/windows-bridge/WindowsBridge.csproj +0 -17
- package/playbooks/devpost.json +0 -186
- package/playbooks/instagram.json +0 -41
- package/playbooks/instagram_v2.json +0 -201
- package/playbooks/x_v1.json +0 -211
- package/scripts/devpost-live-loop.mjs +0 -421
- package/src/logging/timeline-logger.ts +0 -55
- package/src/mcp/server.ts +0 -449
- package/src/memory/recall.ts +0 -191
- package/src/memory/research.ts +0 -146
- package/src/memory/seeds.ts +0 -123
- package/src/memory/session.ts +0 -201
- package/src/memory/store.ts +0 -434
- package/src/memory/types.ts +0 -69
- package/src/native/bridge-client.ts +0 -239
- package/src/runtime/accessibility-adapter.ts +0 -487
- package/src/runtime/app-adapter.ts +0 -169
- package/src/runtime/applescript-adapter.ts +0 -376
- package/src/runtime/ax-role-map.ts +0 -102
- package/src/runtime/browser-adapter.ts +0 -129
- package/src/runtime/cdp-chrome-adapter.ts +0 -676
- package/src/runtime/composite-adapter.ts +0 -274
- package/src/runtime/executor.ts +0 -396
- package/src/runtime/planning-loop.ts +0 -81
- package/src/runtime/service.ts +0 -448
- package/src/runtime/session-manager.ts +0 -50
- package/src/runtime/state-observer.ts +0 -136
- package/src/runtime/vision-adapter.ts +0 -297
- package/src/types.ts +0 -297
- package/tests/bridge-client.test.ts +0 -176
- package/tests/browser-stealth.test.ts +0 -210
- package/tests/composite-adapter.test.ts +0 -64
- package/tests/mcp-server.test.ts +0 -151
- package/tests/memory-recall.test.ts +0 -339
- package/tests/memory-research.test.ts +0 -159
- package/tests/memory-seeds.test.ts +0 -120
- package/tests/memory-store.test.ts +0 -392
- package/tests/types.test.ts +0 -92
- package/tsconfig.check.json +0 -17
- package/tsconfig.json +0 -19
- package/vitest.config.ts +0 -8
|
@@ -0,0 +1,224 @@
|
|
|
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
|
+
const POLL_INTERVAL_MS = 200;
|
|
18
|
+
/**
|
|
19
|
+
* Vision-based adapter for apps with poor/no accessibility support.
|
|
20
|
+
* Uses screenshots + OCR to locate elements and CG events to interact.
|
|
21
|
+
*/
|
|
22
|
+
export class VisionAdapter {
|
|
23
|
+
bridge;
|
|
24
|
+
sessions = new Map();
|
|
25
|
+
sessionsByProfile = new Map();
|
|
26
|
+
constructor(bridge) {
|
|
27
|
+
this.bridge = bridge;
|
|
28
|
+
}
|
|
29
|
+
async attach(profile, reuseSessionId) {
|
|
30
|
+
const existing = this.sessionsByProfile.get(profile);
|
|
31
|
+
if (existing)
|
|
32
|
+
return existing.info;
|
|
33
|
+
await this.bridge.start();
|
|
34
|
+
const frontmost = await this.bridge.call("app.frontmost");
|
|
35
|
+
const info = {
|
|
36
|
+
sessionId: reuseSessionId ?? `vision_session_${profile}_${Date.now()}`,
|
|
37
|
+
profile,
|
|
38
|
+
createdAt: new Date().toISOString(),
|
|
39
|
+
adapterType: "vision",
|
|
40
|
+
};
|
|
41
|
+
const state = {
|
|
42
|
+
info,
|
|
43
|
+
pid: frontmost.pid,
|
|
44
|
+
bundleId: frontmost.bundleId,
|
|
45
|
+
appName: frontmost.name,
|
|
46
|
+
};
|
|
47
|
+
this.sessions.set(info.sessionId, state);
|
|
48
|
+
this.sessionsByProfile.set(profile, state);
|
|
49
|
+
return info;
|
|
50
|
+
}
|
|
51
|
+
async getAppContext(sessionId) {
|
|
52
|
+
const state = this.requireSession(sessionId);
|
|
53
|
+
return {
|
|
54
|
+
bundleId: state.bundleId,
|
|
55
|
+
appName: state.appName,
|
|
56
|
+
pid: state.pid,
|
|
57
|
+
windowTitle: state.appName,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
async getPageMeta(sessionId) {
|
|
61
|
+
const ctx = await this.getAppContext(sessionId);
|
|
62
|
+
return {
|
|
63
|
+
url: `app://${ctx.bundleId}`,
|
|
64
|
+
title: ctx.appName,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
async navigate(sessionId, url, _timeoutMs) {
|
|
68
|
+
if (url.startsWith("app://")) {
|
|
69
|
+
const bundleId = url.slice(6);
|
|
70
|
+
const result = await this.bridge.call("app.launch", { bundleId });
|
|
71
|
+
const state = this.requireSession(sessionId);
|
|
72
|
+
state.pid = result.pid;
|
|
73
|
+
state.bundleId = result.bundleId;
|
|
74
|
+
state.appName = result.appName;
|
|
75
|
+
}
|
|
76
|
+
return this.getPageMeta(sessionId);
|
|
77
|
+
}
|
|
78
|
+
async locate(sessionId, target, timeoutMs) {
|
|
79
|
+
const state = this.requireSession(sessionId);
|
|
80
|
+
const deadline = Date.now() + timeoutMs;
|
|
81
|
+
while (Date.now() < deadline) {
|
|
82
|
+
// Take a screenshot
|
|
83
|
+
const screenshotResult = await this.bridge.call("cg.captureScreen", {});
|
|
84
|
+
state.lastScreenshotPath = screenshotResult.path;
|
|
85
|
+
const searchText = this.getSearchText(target);
|
|
86
|
+
if (!searchText) {
|
|
87
|
+
// For coordinate targets, just return coordinates directly
|
|
88
|
+
if (target.type === "coordinates") {
|
|
89
|
+
return {
|
|
90
|
+
handleId: `vision_coords_${target.x}_${target.y}`,
|
|
91
|
+
locatorUsed: "vision:coordinates",
|
|
92
|
+
coordinates: { x: target.x, y: target.y, width: 1, height: 1 },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
// OCR the screenshot
|
|
98
|
+
const matches = await this.bridge.call("vision.findText", {
|
|
99
|
+
imagePath: screenshotResult.path,
|
|
100
|
+
searchText,
|
|
101
|
+
});
|
|
102
|
+
if (matches.length > 0) {
|
|
103
|
+
const best = matches.reduce((a, b) => (a.confidence > b.confidence ? a : b));
|
|
104
|
+
return {
|
|
105
|
+
handleId: `vision_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
|
106
|
+
locatorUsed: `vision:text:${searchText}`,
|
|
107
|
+
label: best.text,
|
|
108
|
+
coordinates: best.bounds,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
await sleep(POLL_INTERVAL_MS);
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
async click(_sessionId, element) {
|
|
116
|
+
if (!element.coordinates) {
|
|
117
|
+
throw new Error("Vision adapter requires coordinates to click");
|
|
118
|
+
}
|
|
119
|
+
const cx = element.coordinates.x + element.coordinates.width / 2;
|
|
120
|
+
const cy = element.coordinates.y + element.coordinates.height / 2;
|
|
121
|
+
await this.bridge.call("cg.mouseClick", { x: cx, y: cy });
|
|
122
|
+
}
|
|
123
|
+
async setValue(_sessionId, element, text, clear) {
|
|
124
|
+
// Click to focus
|
|
125
|
+
await this.click(_sessionId, element);
|
|
126
|
+
await sleep(100);
|
|
127
|
+
if (clear) {
|
|
128
|
+
await this.bridge.call("cg.keyCombo", { keys: ["cmd", "a"] });
|
|
129
|
+
await sleep(50);
|
|
130
|
+
}
|
|
131
|
+
await this.bridge.call("cg.typeText", { text });
|
|
132
|
+
}
|
|
133
|
+
async getValue(_sessionId, element) {
|
|
134
|
+
// Vision can't reliably read values; return label if available
|
|
135
|
+
return element.label ?? "";
|
|
136
|
+
}
|
|
137
|
+
async waitFor(sessionId, condition, timeoutMs) {
|
|
138
|
+
const deadline = Date.now() + timeoutMs;
|
|
139
|
+
while (Date.now() < deadline) {
|
|
140
|
+
if (condition.type === "text_appears") {
|
|
141
|
+
const found = await this.locate(sessionId, { type: "text", value: condition.text }, 200);
|
|
142
|
+
if (found)
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
else if (condition.type === "element_exists") {
|
|
146
|
+
const found = await this.locate(sessionId, condition.target, 200);
|
|
147
|
+
if (found)
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
else if (condition.type === "element_gone") {
|
|
151
|
+
const found = await this.locate(sessionId, condition.target, 200);
|
|
152
|
+
if (!found)
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
// Unsupported condition types
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
await sleep(POLL_INTERVAL_MS);
|
|
160
|
+
}
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
async extract(sessionId, _target, format) {
|
|
164
|
+
const state = this.requireSession(sessionId);
|
|
165
|
+
// Take a fresh screenshot and OCR it
|
|
166
|
+
const screenshotResult = await this.bridge.call("cg.captureScreen", {});
|
|
167
|
+
state.lastScreenshotPath = screenshotResult.path;
|
|
168
|
+
const ocrResult = await this.bridge.call("vision.ocr", { imagePath: screenshotResult.path });
|
|
169
|
+
if (format === "text") {
|
|
170
|
+
return ocrResult.text;
|
|
171
|
+
}
|
|
172
|
+
if (format === "json") {
|
|
173
|
+
return ocrResult;
|
|
174
|
+
}
|
|
175
|
+
// table format
|
|
176
|
+
return {
|
|
177
|
+
headers: ["text", "confidence", "x", "y", "width", "height"],
|
|
178
|
+
rows: ocrResult.regions.map((r) => [
|
|
179
|
+
r.text,
|
|
180
|
+
r.confidence,
|
|
181
|
+
r.bounds.x,
|
|
182
|
+
r.bounds.y,
|
|
183
|
+
r.bounds.width,
|
|
184
|
+
r.bounds.height,
|
|
185
|
+
]),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
async screenshot(_sessionId, region) {
|
|
189
|
+
const result = await this.bridge.call("cg.captureScreen", region ? { region } : {});
|
|
190
|
+
return result.path;
|
|
191
|
+
}
|
|
192
|
+
async keyCombo(_sessionId, keys) {
|
|
193
|
+
await this.bridge.call("cg.keyCombo", { keys });
|
|
194
|
+
}
|
|
195
|
+
async elementTree(_sessionId, _maxDepth, _root) {
|
|
196
|
+
throw new Error("Vision adapter does not support elementTree — use accessibility adapter");
|
|
197
|
+
}
|
|
198
|
+
// ── Private ──
|
|
199
|
+
requireSession(sessionId) {
|
|
200
|
+
const state = this.sessions.get(sessionId);
|
|
201
|
+
if (!state)
|
|
202
|
+
throw new Error(`Session not found: ${sessionId}`);
|
|
203
|
+
return state;
|
|
204
|
+
}
|
|
205
|
+
getSearchText(target) {
|
|
206
|
+
switch (target.type) {
|
|
207
|
+
case "text":
|
|
208
|
+
return target.value;
|
|
209
|
+
case "role":
|
|
210
|
+
return target.name;
|
|
211
|
+
case "selector":
|
|
212
|
+
return target.value;
|
|
213
|
+
case "ax_attribute":
|
|
214
|
+
return target.value;
|
|
215
|
+
case "image":
|
|
216
|
+
case "coordinates":
|
|
217
|
+
case "ax_path":
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function sleep(ms) {
|
|
223
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
224
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
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
|
+
* LeaseManager — filesystem-based session lease management.
|
|
19
|
+
*
|
|
20
|
+
* Each lease is a JSON lock file: {app}__{windowId}.lock
|
|
21
|
+
* Provides mutual exclusion so only one client controls a window at a time.
|
|
22
|
+
*/
|
|
23
|
+
import fs from "node:fs";
|
|
24
|
+
import path from "node:path";
|
|
25
|
+
import { writeFileAtomicSync } from "../util/atomic-write.js";
|
|
26
|
+
const DEFAULT_LEASE_TIMEOUT_MS = 300000; // 5 min
|
|
27
|
+
export class LeaseManager {
|
|
28
|
+
lockDir;
|
|
29
|
+
leaseTimeoutMs;
|
|
30
|
+
constructor(lockDir, leaseTimeoutMs = DEFAULT_LEASE_TIMEOUT_MS) {
|
|
31
|
+
this.lockDir = lockDir;
|
|
32
|
+
this.leaseTimeoutMs = leaseTimeoutMs;
|
|
33
|
+
fs.mkdirSync(this.lockDir, { recursive: true });
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Claim a window for a client. Fails if another active lease exists.
|
|
37
|
+
* Returns the new SessionLease, or null if the window is already claimed.
|
|
38
|
+
*/
|
|
39
|
+
claim(client, app, windowId) {
|
|
40
|
+
const existing = this.isLocked(app, windowId);
|
|
41
|
+
if (existing) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
const now = new Date();
|
|
45
|
+
const sessionId = "lease_" + Date.now().toString(36) + "_" + Math.random().toString(36).slice(2, 8);
|
|
46
|
+
const lease = {
|
|
47
|
+
sessionId,
|
|
48
|
+
client,
|
|
49
|
+
app,
|
|
50
|
+
windowId,
|
|
51
|
+
claimedAt: now.toISOString(),
|
|
52
|
+
lastHeartbeat: now.toISOString(),
|
|
53
|
+
expiresAt: new Date(now.getTime() + this.leaseTimeoutMs).toISOString(),
|
|
54
|
+
};
|
|
55
|
+
const lockFile = this.lockFilePath(app, windowId);
|
|
56
|
+
try {
|
|
57
|
+
fs.writeFileSync(lockFile, JSON.stringify(lease, null, 2), { flag: "wx" });
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
// File already exists (race condition) — another client claimed it
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
return lease;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Refresh heartbeat for an existing lease.
|
|
67
|
+
* Returns true if the lease was found and updated, false otherwise.
|
|
68
|
+
*/
|
|
69
|
+
heartbeat(sessionId) {
|
|
70
|
+
const leases = this.readAllLeases();
|
|
71
|
+
for (const { lease, filePath } of leases) {
|
|
72
|
+
if (lease.sessionId === sessionId) {
|
|
73
|
+
const now = new Date();
|
|
74
|
+
lease.lastHeartbeat = now.toISOString();
|
|
75
|
+
lease.expiresAt = new Date(now.getTime() + this.leaseTimeoutMs).toISOString();
|
|
76
|
+
writeFileAtomicSync(filePath, JSON.stringify(lease, null, 2));
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Release a lease by session ID.
|
|
84
|
+
* Returns true if the lease was found and removed, false otherwise.
|
|
85
|
+
*/
|
|
86
|
+
release(sessionId) {
|
|
87
|
+
const leases = this.readAllLeases();
|
|
88
|
+
for (const { lease, filePath } of leases) {
|
|
89
|
+
if (lease.sessionId === sessionId) {
|
|
90
|
+
try {
|
|
91
|
+
fs.unlinkSync(filePath);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// Already removed
|
|
95
|
+
}
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Get all active (non-expired) leases.
|
|
103
|
+
*/
|
|
104
|
+
getActive() {
|
|
105
|
+
const now = Date.now();
|
|
106
|
+
return this.readAllLeases()
|
|
107
|
+
.filter(({ lease }) => new Date(lease.expiresAt).getTime() > now)
|
|
108
|
+
.map(({ lease }) => lease);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Clean up expired leases by deleting their lock files.
|
|
112
|
+
* Returns the number of leases expired.
|
|
113
|
+
*/
|
|
114
|
+
expireStale() {
|
|
115
|
+
const now = Date.now();
|
|
116
|
+
let count = 0;
|
|
117
|
+
for (const { lease, filePath } of this.readAllLeases()) {
|
|
118
|
+
if (new Date(lease.expiresAt).getTime() <= now) {
|
|
119
|
+
try {
|
|
120
|
+
fs.unlinkSync(filePath);
|
|
121
|
+
count++;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// Already removed
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return count;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Check if a window is claimed by an active (non-expired) lease.
|
|
132
|
+
* Returns the lease if found, null otherwise.
|
|
133
|
+
*/
|
|
134
|
+
isLocked(app, windowId) {
|
|
135
|
+
const lockFile = this.lockFilePath(app, windowId);
|
|
136
|
+
try {
|
|
137
|
+
const data = fs.readFileSync(lockFile, "utf-8");
|
|
138
|
+
const lease = JSON.parse(data);
|
|
139
|
+
// Check if expired
|
|
140
|
+
if (new Date(lease.expiresAt).getTime() <= Date.now()) {
|
|
141
|
+
// Expired — clean up and report as unlocked
|
|
142
|
+
try {
|
|
143
|
+
fs.unlinkSync(lockFile);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
// Ignore
|
|
147
|
+
}
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
return lease;
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
// ── Private helpers ──
|
|
157
|
+
lockFilePath(app, windowId) {
|
|
158
|
+
// Sanitize app name for filesystem safety
|
|
159
|
+
const safeApp = app.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
160
|
+
return path.join(this.lockDir, `${safeApp}__${windowId}.lock`);
|
|
161
|
+
}
|
|
162
|
+
readAllLeases() {
|
|
163
|
+
const results = [];
|
|
164
|
+
let files;
|
|
165
|
+
try {
|
|
166
|
+
files = fs.readdirSync(this.lockDir);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return results;
|
|
170
|
+
}
|
|
171
|
+
for (const file of files) {
|
|
172
|
+
if (!file.endsWith(".lock"))
|
|
173
|
+
continue;
|
|
174
|
+
const filePath = path.join(this.lockDir, file);
|
|
175
|
+
try {
|
|
176
|
+
const data = fs.readFileSync(filePath, "utf-8");
|
|
177
|
+
const lease = JSON.parse(data);
|
|
178
|
+
results.push({ lease, filePath });
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
// Corrupt lock file — skip
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return results;
|
|
185
|
+
}
|
|
186
|
+
}
|