omowright 0.0.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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -2
  3. package/TOOLS.md +487 -0
  4. package/bin/omowright-cloak.mjs +112 -0
  5. package/package.json +57 -4
  6. package/presets/agent-events/SKILL.md +75 -0
  7. package/presets/captcha/SKILL.md +129 -0
  8. package/presets/chrome/SKILL.md +88 -0
  9. package/presets/cloak-bridge/SKILL.md +43 -0
  10. package/presets/network/SKILL.md +126 -0
  11. package/presets/visual-browse/SKILL.md +103 -0
  12. package/skills/omowright/SKILL.md +193 -0
  13. package/skills/omowright/references/1password.md +118 -0
  14. package/skills/omowright/references/browserskill.md +195 -0
  15. package/skills/omowright/references/eval-kernel.md +100 -0
  16. package/skills/omowright/references/frames-layers-human.md +123 -0
  17. package/skills/omowright/references/quickstart.md +109 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +179 -0
  20. package/src/aria-hidden.js +47 -0
  21. package/src/bridge-schemas.js +44 -0
  22. package/src/bridge-transport.js +83 -0
  23. package/src/browser-context.js +105 -0
  24. package/src/browser-process.js +127 -0
  25. package/src/bsk/browser-signals.js +90 -0
  26. package/src/bsk/browsers.js +114 -0
  27. package/src/bsk/connect.js +75 -0
  28. package/src/bsk/daemon-info.js +100 -0
  29. package/src/bsk/external-extension.js +110 -0
  30. package/src/bsk/identify-browser.js +88 -0
  31. package/src/bsk/install-cli.js +81 -0
  32. package/src/bsk/ipc-client.js +236 -0
  33. package/src/bsk/onboard.js +140 -0
  34. package/src/bsk/screenshot.js +49 -0
  35. package/src/bsk/session.js +131 -0
  36. package/src/bsk/snapshot.js +56 -0
  37. package/src/bsk/targets.js +25 -0
  38. package/src/captcha-wait.js +79 -0
  39. package/src/captcha.js +142 -0
  40. package/src/cdp-errors.js +23 -0
  41. package/src/cdp-methods.js +69 -0
  42. package/src/chrome-profile.js +176 -0
  43. package/src/chrome.js +194 -0
  44. package/src/cloak-profile.js +266 -0
  45. package/src/connection.js +234 -0
  46. package/src/console-events.js +12 -0
  47. package/src/cookies.js +39 -0
  48. package/src/core.js +1702 -0
  49. package/src/cua.js +74 -0
  50. package/src/dialog-policy.js +80 -0
  51. package/src/emulate.js +127 -0
  52. package/src/events.js +111 -0
  53. package/src/frames-snapshot.js +138 -0
  54. package/src/har.js +103 -0
  55. package/src/human-handoff.js +124 -0
  56. package/src/index.js +89 -0
  57. package/src/injected.js +3 -0
  58. package/src/instance-lock.js +74 -0
  59. package/src/instances.js +490 -0
  60. package/src/internal-capability.js +1 -0
  61. package/src/launch-endpoint.js +185 -0
  62. package/src/layers.js +138 -0
  63. package/src/llm.js +201 -0
  64. package/src/lock-backend-win32.js +54 -0
  65. package/src/lock-backend.js +81 -0
  66. package/src/native-host-win32.js +201 -0
  67. package/src/network-events.js +223 -0
  68. package/src/network-snoop.js +229 -0
  69. package/src/nul-frames.js +28 -0
  70. package/src/open-shadow-query.js +101 -0
  71. package/src/owner-only.js +196 -0
  72. package/src/page-bundle.js +1478 -0
  73. package/src/page-events.js +45 -0
  74. package/src/page-routes.js +94 -0
  75. package/src/page-setup.js +239 -0
  76. package/src/pipe.js +418 -0
  77. package/src/process-start-time.js +64 -0
  78. package/src/routes.js +256 -0
  79. package/src/running-browser.js +85 -0
  80. package/src/scroll-collect.js +73 -0
  81. package/src/serial-emitter.js +17 -0
  82. package/src/shared-connections.js +285 -0
  83. package/src/snapshot-diff.js +75 -0
  84. package/src/text-matching.js +101 -0
  85. package/src/trace.js +183 -0
  86. package/src/url-match.js +148 -0
  87. package/src/viewport.js +12 -0
package/src/layers.js ADDED
@@ -0,0 +1,138 @@
1
+ export async function describeLayers(page, { grid = 5 } = {}) {
2
+ return page.evaluate(gridSize => {
3
+ const width = Math.round(globalThis.visualViewport?.width ?? globalThis.innerWidth ?? 0);
4
+ const height = Math.round(globalThis.visualViewport?.height ?? globalThis.innerHeight ?? 0);
5
+ const viewport = { width, height };
6
+ const total = gridSize * gridSize;
7
+ const hits = new Map();
8
+
9
+ function pierceTopmost(x, y) {
10
+ const stack = document.elementsFromPoint(x, y);
11
+ let el = stack[0] ?? null;
12
+ const seen = new Set();
13
+ while (el?.shadowRoot && typeof el.shadowRoot.elementsFromPoint === "function") {
14
+ if (seen.has(el)) break;
15
+ seen.add(el);
16
+ const inner = el.shadowRoot.elementsFromPoint(x, y) ?? [];
17
+ const next = inner.find(node => node && node !== el);
18
+ if (!next) break;
19
+ el = next;
20
+ }
21
+ return el;
22
+ }
23
+
24
+ function parentOf(node) {
25
+ if (!node) return null;
26
+ if (node.parentElement) return node.parentElement;
27
+ const root = node.getRootNode?.();
28
+ return root?.host ?? null;
29
+ }
30
+
31
+ function promote(el) {
32
+ const minArea = 0.5 * width * height;
33
+ let node = el;
34
+ while (node && node.nodeType === 1) {
35
+ const position = getComputedStyle(node).position;
36
+ if (position === "fixed" || position === "sticky" || position === "absolute") {
37
+ const rect = node.getBoundingClientRect();
38
+ if (rect.width * rect.height >= minArea) return node;
39
+ }
40
+ node = parentOf(node);
41
+ }
42
+ return el;
43
+ }
44
+
45
+ function labelledByText(el) {
46
+ const ids = (el.getAttribute("aria-labelledby") || "").trim();
47
+ if (!ids) return "";
48
+ return ids.split(/\s+/).map(id => document.getElementById(id)?.textContent?.trim() ?? "").filter(Boolean).join(" ");
49
+ }
50
+
51
+ function elementName(el) {
52
+ const ariaLabel = el.getAttribute("aria-label");
53
+ if (ariaLabel) return ariaLabel;
54
+ const labelled = labelledByText(el);
55
+ if (labelled) return labelled;
56
+ const heading = el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();
57
+ if (heading) return heading;
58
+ return ((el.innerText || el.textContent || "").trim().replace(/\s+/g, " ")).slice(0, 80);
59
+ }
60
+
61
+ function selectorHint(el) {
62
+ if (el.id) return `#${el.id}`;
63
+ const classes = [...el.classList].join(".");
64
+ return classes ? `${el.tagName.toLowerCase()}.${classes}` : el.tagName.toLowerCase();
65
+ }
66
+
67
+ function describe(el, coverage) {
68
+ return {
69
+ tagName: el.tagName,
70
+ role: el.getAttribute("role") || "",
71
+ name: elementName(el),
72
+ coverage,
73
+ position: getComputedStyle(el).position,
74
+ selectorHint: selectorHint(el),
75
+ ariaModal: el.getAttribute("aria-modal") === "true",
76
+ };
77
+ }
78
+
79
+ function isMainContent(el) {
80
+ if (el === document.documentElement || el === document.body) return true;
81
+ if (el.tagName === "MAIN") return true;
82
+ return (el.getAttribute("role") || "").toLowerCase() === "main";
83
+ }
84
+
85
+ function isBlocking(el, info) {
86
+ if (info.coverage < 0.6) return false;
87
+ if (getComputedStyle(el).pointerEvents === "none") return false;
88
+ const role = (info.role || "").toLowerCase();
89
+ if (role === "dialog" || role === "alertdialog") return true;
90
+ if (info.ariaModal) return true;
91
+ if (isMainContent(el)) return false;
92
+ return info.position === "fixed" || info.position === "absolute";
93
+ }
94
+
95
+ const insetX = width * 0.05;
96
+ const insetY = height * 0.05;
97
+ const spanX = width * 0.9;
98
+ const spanY = height * 0.9;
99
+ for (let row = 0; row < gridSize; row++) {
100
+ for (let col = 0; col < gridSize; col++) {
101
+ const x = insetX + ((col + 0.5) * spanX) / gridSize;
102
+ const y = insetY + ((row + 0.5) * spanY) / gridSize;
103
+ const top = pierceTopmost(x, y);
104
+ if (!top) continue;
105
+ const candidate = promote(top);
106
+ hits.set(candidate, (hits.get(candidate) ?? 0) + 1);
107
+ }
108
+ }
109
+
110
+ const candidates = [...hits.entries()]
111
+ .map(([el, count]) => {
112
+ const info = describe(el, total > 0 ? count / total : 0);
113
+ return { el, info };
114
+ })
115
+ .sort((a, b) => b.info.coverage - a.info.coverage);
116
+
117
+ const blockingEntry = candidates.find(entry => isBlocking(entry.el, entry.info));
118
+ return {
119
+ blocking: blockingEntry ? blockingEntry.info : null,
120
+ candidates: candidates.map(entry => entry.info),
121
+ viewport,
122
+ };
123
+ }, grid);
124
+ }
125
+
126
+ export function layersHeader(result) {
127
+ const blocking = result?.blocking;
128
+ if (!blocking) return "@layers none";
129
+ const who = blocking.role || blocking.tagName;
130
+ const pct = Math.round(blocking.coverage * 100);
131
+ return `@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`;
132
+ }
133
+
134
+ export async function snapshotWithLayers(page, snapshotOptions) {
135
+ const snapshot = await page.snapshot(snapshotOptions);
136
+ const layers = await describeLayers(page);
137
+ return { ...snapshot, layers, tree: `${layersHeader(layers)}\n${snapshot.tree}` };
138
+ }
package/src/llm.js ADDED
@@ -0,0 +1,201 @@
1
+ const SNAPSHOT_PARSE_ERROR =
2
+ "compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";
3
+
4
+ export function compactSnapshot(snapshot) {
5
+ const obj = typeof snapshot === "string" ? JSON.parse(snapshot) : snapshot;
6
+ if (obj?.full === false && obj.diff) {
7
+ const { added, changed, removed, focused } = obj.diff;
8
+ const lines = [
9
+ ...added.map(node => `+ ${node.tree}`),
10
+ ...changed.map(node => `~ ${node.tree}`),
11
+ ];
12
+ if (removed.length) lines.push(`- ${refRanges(removed)}`);
13
+ lines.push(`@focused ${focused ?? "none"}`);
14
+ return lines.join("\n");
15
+ }
16
+ if (!obj || typeof obj.tree !== "string") throw new TypeError(SNAPSHOT_PARSE_ERROR);
17
+ return obj.tree;
18
+ }
19
+
20
+ function refRanges(refs) {
21
+ const sorted = refs.map(ref => {
22
+ const [, prefix, number] = /^((?:f\d+)?e)(\d+)$/.exec(ref);
23
+ return { prefix, number: Number(number) };
24
+ }).sort((a, b) => a.prefix.localeCompare(b.prefix) || a.number - b.number);
25
+ const ranges = [];
26
+ for (let i = 0; i < sorted.length; i++) {
27
+ const first = sorted[i];
28
+ let last = first;
29
+ while (sorted[i + 1]?.prefix === first.prefix && sorted[i + 1].number === last.number + 1) last = sorted[++i];
30
+ ranges.push(first === last ? `${first.prefix}${first.number}` : `${first.prefix}${first.number}-${last.prefix}${last.number}`);
31
+ }
32
+ return ranges.join(", ");
33
+ }
34
+
35
+ export function snapshotTokens(snapshot) {
36
+ const text = typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot);
37
+ return { bytes: Buffer.byteLength(text, "utf8"), estTokens: Math.ceil(Buffer.byteLength(text, "utf8") / 4) };
38
+ }
39
+
40
+ export const toolSchemas = [
41
+ {
42
+ name: "newTab",
43
+ description: "Open a tab and return its page. Waits for interactivity.",
44
+ parameters: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
45
+ },
46
+ {
47
+ name: "attachPage",
48
+ description: "Attach to an existing tab by targetId from listTargets().",
49
+ parameters: { type: "object", properties: { targetId: { type: "string" } }, required: ["targetId"] },
50
+ },
51
+ {
52
+ name: "page.goto",
53
+ description: "Navigate the page; resolves when the page looks interactive.",
54
+ parameters: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
55
+ },
56
+ {
57
+ name: "page.snapshot",
58
+ description: "PRIMARY page read. Snapshot once, act on refs, then use {diff:true} for changes. Full fallbacks carry full:true and a reason. Options: diff, maxDepth, maxChars, interactive, showHidden, selector, ref.",
59
+ parameters: { type: "object", properties: { options: { type: "object" } } },
60
+ },
61
+ {
62
+ name: "page.locator",
63
+ description: "Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",
64
+ parameters: { type: "object", properties: { selectorOrRef: { type: "string" } }, required: ["selectorOrRef"] },
65
+ },
66
+ {
67
+ name: "page.evaluate",
68
+ description: "Run JS in the page and return the result.",
69
+ parameters: { type: "object", properties: { expression: { type: "string" } }, required: ["expression"] },
70
+ },
71
+ {
72
+ name: "page.screenshot",
73
+ description: "Capture page image bytes (path, fullPage, clip, type, quality).",
74
+ parameters: { type: "object", properties: { options: { type: "object" } } },
75
+ },
76
+ {
77
+ name: "page.pdf",
78
+ description: "Print the page to PDF bytes (path, format, margin, printBackground).",
79
+ parameters: { type: "object", properties: { options: { type: "object" } } },
80
+ },
81
+ {
82
+ name: "compactSnapshot",
83
+ description: "Compact page.snapshot() before reading: full results become raw trees; diffs use +/~ lines and removed ref ranges. Refs resolve in-page.",
84
+ parameters: { type: "object", properties: { snapshot: {} }, required: ["snapshot"] },
85
+ },
86
+ {
87
+ name: "createCua",
88
+ description: "Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",
89
+ parameters: { type: "object", properties: { page: {} }, required: ["page"] },
90
+ },
91
+ {
92
+ name: "createCaptcha",
93
+ description: "Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",
94
+ parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
95
+ },
96
+ {
97
+ name: "createChromeApi",
98
+ description: "Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",
99
+ parameters: { type: "object", properties: { connection: {}, options: { type: "object" } }, required: ["connection"] },
100
+ },
101
+ {
102
+ name: "injectCookies",
103
+ description: "Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",
104
+ parameters: { type: "object", properties: { page: {}, cookies: { type: "array" } }, required: ["page", "cookies"] },
105
+ },
106
+ {
107
+ name: "createNetworkSnoop",
108
+ description: "Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",
109
+ parameters: { type: "object", properties: { page: {}, match: {}, bodies: { type: "boolean" }, maxEntries: { type: "number" }, maxBodyBytes: { type: "number" } }, required: ["page"] },
110
+ },
111
+ {
112
+ name: "snoop.waitFor",
113
+ description: "Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",
114
+ parameters: { type: "object", properties: { match: {}, timeoutMs: { type: "number" } } },
115
+ },
116
+ {
117
+ name: "snoop.popJson",
118
+ description: "Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",
119
+ parameters: { type: "object", properties: {} },
120
+ },
121
+ {
122
+ name: "snoop.summary",
123
+ description: "Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",
124
+ parameters: { type: "object", properties: { max: { type: "number" } } },
125
+ },
126
+ {
127
+ name: "collectWhileScrolling",
128
+ description: "Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",
129
+ parameters: { type: "object", properties: { page: {}, snoop: {}, minItems: { type: "number" }, maxScrolls: { type: "number" }, extract: {}, scroll: { type: "string", enum: ["wheel", "end"] }, settleMs: { type: "number" } }, required: ["page", "snoop"] },
130
+ },
131
+ {
132
+ name: "createTrace",
133
+ description: "Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",
134
+ parameters: { type: "object", properties: { page: {}, dir: { type: "string" }, screenshots: { type: "boolean" }, network: { type: "boolean" }, console: { type: "boolean" }, maxBodyBytes: { type: "number" }, events: {} }, required: ["page", "dir"] },
135
+ },
136
+ {
137
+ name: "trace.step",
138
+ description: "Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",
139
+ parameters: { type: "object", properties: { name: { type: "string" }, fn: {} }, required: ["name", "fn"] },
140
+ },
141
+ {
142
+ name: "trace.stop",
143
+ description: "Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",
144
+ parameters: { type: "object", properties: {} },
145
+ },
146
+ {
147
+ name: "reconcileFrames",
148
+ description: "Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",
149
+ parameters: { type: "object", properties: { page: {} }, required: ["page"] },
150
+ },
151
+ {
152
+ name: "snapshotWithFrames",
153
+ description: "Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",
154
+ parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
155
+ },
156
+ {
157
+ name: "connectPipe.dialogPolicy",
158
+ description: "Wire connectPipe({dialogPolicy}), connect(url, {dialogPolicy}) and setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; a throwing policy accepts.",
159
+ parameters: { type: "object", properties: { accept: { type: "boolean" }, promptText: { type: "string" } } },
160
+ },
161
+ {
162
+ name: "requestHuman",
163
+ description: "Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",
164
+ parameters: { type: "object", properties: { page: {}, prompt: { type: "string" }, until: {}, timeoutMs: { type: "number" }, pollMs: { type: "number" }, signal: {} }, required: ["page"] },
165
+ },
166
+ {
167
+ name: "describeLayers",
168
+ description: "Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",
169
+ parameters: { type: "object", properties: { page: {}, grid: { type: "number" } }, required: ["page"] },
170
+ },
171
+ {
172
+ name: "snapshotWithLayers",
173
+ description: "Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",
174
+ parameters: { type: "object", properties: { page: {}, options: { type: "object" } }, required: ["page"] },
175
+ },
176
+ {
177
+ name: "emulate",
178
+ description: "Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",
179
+ parameters: { type: "object", properties: { page: {}, preset: {} }, required: ["page", "preset"] },
180
+ },
181
+ {
182
+ name: "createRoutes",
183
+ description: "Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",
184
+ parameters: { type: "object", properties: { page: {} }, required: ["page"] },
185
+ },
186
+ {
187
+ name: "route.continue",
188
+ description: "Continue an intercepted request, optionally overriding url, method, headers, or postData.",
189
+ parameters: { type: "object", properties: { url: { type: "string" }, method: { type: "string" }, headers: { type: "object" }, postData: {} } },
190
+ },
191
+ {
192
+ name: "route.fulfill",
193
+ description: "Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",
194
+ parameters: { type: "object", properties: { status: { type: "number" }, headers: { type: "object" }, contentType: { type: "string" }, body: {} } },
195
+ },
196
+ {
197
+ name: "route.abort",
198
+ description: "Abort an intercepted request with a CDP errorReason (defaults to Failed).",
199
+ parameters: { type: "object", properties: { reason: { type: "string" } } },
200
+ },
201
+ ];
@@ -0,0 +1,54 @@
1
+ import { dlopen, ptr } from "bun:ffi";
2
+ import path from "node:path";
3
+
4
+ const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
5
+ const { symbols } = dlopen(path.win32.join(systemRoot, "System32", "ntdll.dll"), {
6
+ // NTSTATUS is returned in the same native call, unlike GetLastError's
7
+ // thread-local state, whose preservation across FFI/JS is not guaranteed.
8
+ NtCreateFile: {
9
+ args: ["buffer", "u32", "buffer", "buffer", "ptr", "u32", "u32", "u32", "u32", "ptr", "u32"],
10
+ returns: "u32",
11
+ },
12
+ NtClose: { args: ["u64"], returns: "u32" },
13
+ RtlNtStatusToDosError: { args: ["u32"], returns: "u32" },
14
+ });
15
+
16
+ function nativeError(operation, lockPath, status) {
17
+ const error = symbols.RtlNtStatusToDosError(status);
18
+ return Object.assign(
19
+ new Error(`instance lock ${operation} failed for ${lockPath} (Windows error ${error}, NTSTATUS 0x${status.toString(16)})`),
20
+ { code: "ERR_INSTANCE_LOCK" },
21
+ );
22
+ }
23
+
24
+ export function tryAcquireWindows(lockPath) {
25
+ // Bun Windows is 64-bit: UNICODE_STRING has its pointer at offset 8 and
26
+ // OBJECT_ATTRIBUTES is 48 bytes. Translate the Win32 extended namespace to NT.
27
+ const filename = Buffer.from(`${path.toNamespacedPath(path.resolve(lockPath)).replace(/^\\\\\?\\/, "\\??\\")}\0`, "utf16le");
28
+ const name = Buffer.alloc(16);
29
+ name.writeUInt16LE(filename.length - 2, 0);
30
+ name.writeUInt16LE(filename.length, 2);
31
+ name.writeBigUInt64LE(BigInt(ptr(filename)), 8);
32
+ const attributes = Buffer.alloc(48);
33
+ attributes.writeUInt32LE(48, 0);
34
+ attributes.writeBigUInt64LE(BigInt(ptr(name)), 16);
35
+ attributes.writeUInt32LE(0x40, 24); // OBJ_CASE_INSENSITIVE, not OBJ_INHERIT.
36
+ const handleOut = Buffer.alloc(8);
37
+ const ioStatus = Buffer.alloc(16);
38
+ // GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, share mode 0, FILE_OPEN_IF
39
+ // (OPEN_ALWAYS), synchronous non-directory file. NULL security descriptor
40
+ // inherits the registry's DACL; no truncation, deletion, or inheritance.
41
+ const status = symbols.NtCreateFile(
42
+ handleOut, 0xc0100000, attributes, ioStatus, null, 0x80, 0, 3, 0x60, null, 0,
43
+ );
44
+ // STATUS_SHARING_VIOLATION is exactly ERROR_SHARING_VIOLATION (32).
45
+ if (status === 0xc0000043) return null;
46
+ if (status >= 0x80000000) throw nativeError("NtCreateFile", lockPath, status);
47
+ const handle = handleOut.readBigUInt64LE();
48
+ return {
49
+ release() {
50
+ const status = symbols.NtClose(handle);
51
+ if (status >= 0x80000000) throw nativeError("NtClose", lockPath, status);
52
+ },
53
+ };
54
+ }
@@ -0,0 +1,81 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { open } from "node:fs/promises";
4
+
5
+ // xnu bsd/sys/fcntl.h: O_EXLOCK and O_NONBLOCK. Node does not export O_EXLOCK.
6
+ const DARWIN_EXCLUSIVE_NONBLOCK = 0x20 | 0x4;
7
+ // libuv include/uv/win.h: UV_FS_O_EXLOCK makes CreateFile's share mode zero.
8
+ const WINDOWS_EXCLUSIVE = 0x10000000;
9
+ const probedPaths = new Set();
10
+
11
+ async function lockLinux(fd) {
12
+ return new Promise((resolve, reject) => {
13
+ const child = spawn("flock", ["-n", "3"], {
14
+ stdio: ["ignore", "ignore", "pipe", fd],
15
+ });
16
+ let stderr = "";
17
+ child.stderr.setEncoding("utf8");
18
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
19
+ child.once("error", (error) => {
20
+ reject(error.code === "ENOENT"
21
+ ? new Error(`instance lock needs the flock utility (util-linux or busybox) on Linux: ${error.message}`, { cause: error })
22
+ : error);
23
+ });
24
+ // close follows exit and drains stderr, so real utility errors are intact.
25
+ child.once("close", (code, signal) => {
26
+ if (code === 0) resolve(true);
27
+ // util-linux and BusyBox are silent on EWOULDBLOCK. BusyBox also
28
+ // returns 1 for real errors, but prints their errno description.
29
+ else if (code === 1 && stderr.trim() === "") resolve(false);
30
+ else reject(Object.assign(
31
+ new Error(`instance lock flock failed (${signal ?? code}): ${stderr.trim()}`),
32
+ { code: "ERR_INSTANCE_LOCK" },
33
+ ));
34
+ });
35
+ });
36
+ }
37
+
38
+ export async function tryAcquire(lockPath) {
39
+ const platform = process.platform;
40
+ // Bun on Windows drops libuv's exclusive-open bit. Use the same kernel
41
+ // share reservation directly; Node and non-Windows runtimes never load FFI.
42
+ if (platform === "win32" && process.versions.bun) {
43
+ const { tryAcquireWindows } = await import("./lock-backend-win32.js");
44
+ return tryAcquireWindows(lockPath);
45
+ }
46
+ let flags = constants.O_RDWR | constants.O_CREAT;
47
+ if (platform === "darwin") flags |= DARWIN_EXCLUSIVE_NONBLOCK;
48
+ else if (platform === "win32") flags |= WINDOWS_EXCLUSIVE;
49
+ else if (platform !== "linux") throw new Error(`instance lock is unsupported on ${platform}`);
50
+
51
+ let handle;
52
+ try {
53
+ handle = await open(lockPath, flags, 0o600);
54
+ } catch (error) {
55
+ if (platform === "darwin" && ["EAGAIN", "EWOULDBLOCK"].includes(error.code)) return null;
56
+ if (platform === "win32" && error.code === "EBUSY") return null;
57
+ throw error;
58
+ }
59
+ try {
60
+ if (platform === "linux" && !await lockLinux(handle.fd)) {
61
+ await handle.close();
62
+ return null;
63
+ }
64
+ } catch (error) {
65
+ await handle.close();
66
+ throw error;
67
+ }
68
+ // The runtime opens close-on-exec; only the one-shot flock child receives it.
69
+ // Never unlink: another opener must always reach the same kernel object.
70
+ return { release: () => handle.close() };
71
+ }
72
+
73
+ export async function probeOnce(lockPath) {
74
+ if (probedPaths.has(lockPath)) return;
75
+ const second = await tryAcquire(lockPath);
76
+ if (second !== null) {
77
+ await second.release();
78
+ throw new Error(`instance lock is not enforced for ${lockPath} on this runtime and filesystem`);
79
+ }
80
+ probedPaths.add(lockPath);
81
+ }