@clipy/cli 0.18.0 → 0.19.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 (56) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +210 -9
  3. package/dist/context/importCmd.js +1 -1
  4. package/dist/context/ytdlp.js +1 -1
  5. package/dist/context-core/arec.js +1 -1
  6. package/dist/index.js +1042 -88
  7. package/dist/local/arec.js +186 -0
  8. package/dist/local/commands.js +1103 -0
  9. package/dist/local/deps.js +42 -0
  10. package/dist/local/media.js +154 -0
  11. package/dist/local/pipeline.js +530 -0
  12. package/dist/local/ports.js +1 -0
  13. package/dist/local/speechEngine.js +260 -0
  14. package/dist/local/transcriptFile.js +54 -0
  15. package/dist/local/vendor/capture/capture.js +442 -0
  16. package/dist/local/vendor/capture/check.js +103 -0
  17. package/dist/local/vendor/capture/children.js +69 -0
  18. package/dist/local/vendor/capture/ffmpegArgs.js +108 -0
  19. package/dist/local/vendor/capture/index.js +36 -0
  20. package/dist/local/vendor/capture/proc.js +71 -0
  21. package/dist/local/vendor/capture/scripts.js +107 -0
  22. package/dist/local/vendor/capture/sidecar.js +199 -0
  23. package/dist/local/vendor/capture/sources.js +272 -0
  24. package/dist/local/vendor/capture/types.js +1 -0
  25. package/dist/local/vendor/capture/virtualDisplay.js +170 -0
  26. package/dist/local/vendor/capture/xauth.js +68 -0
  27. package/dist/local/vendor/config/errors.js +12 -0
  28. package/dist/local/vendor/config/index.js +241 -0
  29. package/dist/local/vendor/config/paths.js +37 -0
  30. package/dist/local/vendor/config/presets.js +61 -0
  31. package/dist/local/vendor/config/schema.js +66 -0
  32. package/dist/local/vendor/moments/generated/drawStrokes.js +127 -0
  33. package/dist/local/vendor/moments/generated/keyMomentsCursorContext.js +568 -0
  34. package/dist/local/vendor/moments/generated/keyMomentsFusion.js +406 -0
  35. package/dist/local/vendor/moments/generated/localMomentPlan.js +178 -0
  36. package/dist/local/vendor/moments/generated/types.js +1 -0
  37. package/dist/local/vendor/moments/index.js +147 -0
  38. package/dist/local/vendor/moments/llm.js +158 -0
  39. package/dist/local/vendor/transcribe/audio.js +251 -0
  40. package/dist/local/vendor/transcribe/chunking.js +250 -0
  41. package/dist/local/vendor/transcribe/index.js +89 -0
  42. package/dist/local/vendor/transcribe/local.js +221 -0
  43. package/dist/local/vendor/transcribe/localWorker.js +79 -0
  44. package/dist/local/vendor/transcribe/models.js +369 -0
  45. package/dist/local/vendor/transcribe/providers/assemblyai.js +61 -0
  46. package/dist/local/vendor/transcribe/providers/common.js +105 -0
  47. package/dist/local/vendor/transcribe/providers/deepgram.js +59 -0
  48. package/dist/local/vendor/transcribe/providers/elevenlabs.js +43 -0
  49. package/dist/local/vendor/transcribe/providers/gemini.js +102 -0
  50. package/dist/local/vendor/transcribe/providers/http.js +214 -0
  51. package/dist/local/vendor/transcribe/providers/openai.js +48 -0
  52. package/dist/local/vendor/transcribe/tar.js +53 -0
  53. package/dist/local/vendor/transcribe/types.js +1 -0
  54. package/dist/macBridge.js +78 -9
  55. package/dist/skill.js +46 -1
  56. package/package.json +19 -9
@@ -0,0 +1,272 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/capture/src/sources.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * What can be recorded on each OS, from the tools that are already there:
5
+ * ffmpeg itself everywhere, plus xrandr/xdpyinfo/xwininfo on Linux when
6
+ * installed and PowerShell on Windows. Parsers are pure and unit tested.
7
+ */
8
+ import { encodePowerShell, windowsScreensScript } from "./scripts.js";
9
+ import { currentPlatform, ffmpegPath, realRunner } from "./proc.js";
10
+ import { xEnv } from "./xauth.js";
11
+ // ---------------------------------------------------------------------------
12
+ // Linux
13
+ // ---------------------------------------------------------------------------
14
+ /**
15
+ * `xrandr --listmonitors` (or `--listactivemonitors`):
16
+ * ` 0: +*eDP-1 1920/344x1080/194+0+0 eDP-1`. `*` marks the primary.
17
+ */
18
+ export function parseXrandrMonitors(text) {
19
+ const out = [];
20
+ for (const line of text.split("\n")) {
21
+ const m = /^\s*(\d+):\s+([+*]*)(\S+)\s+(\d+)\/\d+x(\d+)\/\d+\+(-?\d+)\+(-?\d+)/.exec(line);
22
+ if (!m)
23
+ continue;
24
+ out.push({
25
+ name: m[3],
26
+ primary: m[2].includes("*"),
27
+ width: Number(m[4]),
28
+ height: Number(m[5]),
29
+ x: Number(m[6]),
30
+ y: Number(m[7]),
31
+ });
32
+ }
33
+ return out;
34
+ }
35
+ /** `xdpyinfo`: ` dimensions: 1280x720 pixels (339x191 millimeters)`. */
36
+ export function parseXdpyinfoSize(text) {
37
+ const m = /dimensions:\s+(\d+)x(\d+)\s+pixels/.exec(text);
38
+ return m ? { width: Number(m[1]), height: Number(m[2]) } : null;
39
+ }
40
+ /** The X screen size from ffmpeg's own probe of the display, so a display
41
+ * can be recorded without any X11 utilities installed. */
42
+ export function parseProbedScreenSize(ffmpegStderr) {
43
+ const m = /Video: [^\n]*?(\d{2,5})x(\d{2,5})/.exec(ffmpegStderr);
44
+ return m ? { width: Number(m[1]), height: Number(m[2]) } : null;
45
+ }
46
+ /** `xprop -root _NET_CLIENT_LIST`: the managed top-level windows. */
47
+ export function parseClientList(text) {
48
+ const m = /_NET_CLIENT_LIST\(WINDOW\): window id # (.*)/.exec(text);
49
+ if (!m)
50
+ return [];
51
+ return m[1]
52
+ .split(",")
53
+ .map((s) => s.trim())
54
+ .filter((s) => /^0x[0-9a-f]+$/i.test(s))
55
+ .map((s) => parseInt(s, 16));
56
+ }
57
+ /** `xwininfo -id <id>`: absolute geometry and whether it is on screen. */
58
+ export function parseWindowGeometry(text) {
59
+ const num = (label) => {
60
+ const m = new RegExp(`${label}:\\s+(-?\\d+)`).exec(text);
61
+ return m ? Number(m[1]) : null;
62
+ };
63
+ const x = num("Absolute upper-left X");
64
+ const y = num("Absolute upper-left Y");
65
+ const width = num("Width");
66
+ const height = num("Height");
67
+ if (x === null || y === null || width === null || height === null)
68
+ return null;
69
+ return { x, y, width, height, viewable: /Map State:\s+IsViewable/.test(text) };
70
+ }
71
+ /** `xprop -id <id> _NET_WM_NAME WM_NAME WM_CLASS`: title and owning app. */
72
+ export function parseWindowProps(text) {
73
+ const quoted = (re) => {
74
+ const m = re.exec(text);
75
+ return m ? m[1].replace(/\\"/g, '"') : "";
76
+ };
77
+ const title = quoted(/_NET_WM_NAME\([^)]*\) = "((?:[^"\\]|\\.)*)"/) || quoted(/WM_NAME\([^)]*\) = "((?:[^"\\]|\\.)*)"/);
78
+ const cls = /WM_CLASS\([^)]*\) = "((?:[^"\\]|\\.)*)", "((?:[^"\\]|\\.)*)"/.exec(text);
79
+ return { title, app: cls ? cls[2] : "" };
80
+ }
81
+ /** The X display's monitors, or the whole screen as one display. */
82
+ export async function linuxScreens(xDisplay, run = realRunner, env = process.env) {
83
+ const xenv = xEnv(env, xDisplay);
84
+ const monitors = await run("xrandr", ["--listmonitors"], xenv);
85
+ const screens = monitors.status === 0 ? parseXrandrMonitors(monitors.stdout) : [];
86
+ if (screens.length > 0)
87
+ return primaryFirst(screens);
88
+ let size = null;
89
+ const dpy = await run("xdpyinfo", [], xenv);
90
+ if (dpy.status === 0)
91
+ size = parseXdpyinfoSize(dpy.stdout);
92
+ if (!size) {
93
+ const ffmpeg = ffmpegPath("linux", env);
94
+ if (ffmpeg) {
95
+ const probe = await run(ffmpeg, ["-hide_banner", "-f", "x11grab", "-i", xDisplay, "-frames:v", "1", "-f", "null", "-"], xenv);
96
+ size = parseProbedScreenSize(probe.stderr);
97
+ }
98
+ }
99
+ return size ? [{ name: `screen ${xDisplay}`, x: 0, y: 0, primary: true, ...size }] : [];
100
+ }
101
+ async function linuxWindows(xDisplay, run, env) {
102
+ const xenv = xEnv(env, xDisplay);
103
+ const list = await run("xprop", ["-root", "_NET_CLIENT_LIST"], xenv);
104
+ if (list.status !== 0)
105
+ return [];
106
+ const out = [];
107
+ for (const id of parseClientList(list.stdout)) {
108
+ const hex = `0x${id.toString(16)}`;
109
+ const info = await run("xwininfo", ["-id", hex], xenv);
110
+ const g = info.status === 0 ? parseWindowGeometry(info.stdout) : null;
111
+ if (!g || !g.viewable || g.width < 32 || g.height < 32)
112
+ continue;
113
+ const props = parseWindowProps((await run("xprop", ["-id", hex, "_NET_WM_NAME", "WM_NAME", "WM_CLASS"], xenv)).stdout);
114
+ if (!props.title && !props.app)
115
+ continue;
116
+ const name = props.app && props.title ? `${props.app}: ${props.title}` : props.title || props.app;
117
+ out.push({ id: `window:${hex}`, kind: "window", name, width: g.width, height: g.height });
118
+ }
119
+ return out;
120
+ }
121
+ /** `ffmpeg -f avfoundation -list_devices true -i ""` (stderr). */
122
+ export function parseAvfoundationDevices(text) {
123
+ const out = { video: [], audio: [] };
124
+ let section = null;
125
+ for (const line of text.split("\n")) {
126
+ if (/AVFoundation video devices/i.test(line))
127
+ section = "video";
128
+ else if (/AVFoundation audio devices/i.test(line))
129
+ section = "audio";
130
+ else if (section) {
131
+ const m = /\]\s*\[(\d+)\]\s+(.+?)\s*$/.exec(line);
132
+ if (m)
133
+ out[section].push({ index: Number(m[1]), name: m[2] });
134
+ }
135
+ }
136
+ return out;
137
+ }
138
+ /** The "Capture screen N" devices, in screen order. */
139
+ export function avfoundationScreens(devices) {
140
+ return devices.video
141
+ .map((d) => ({ ...d, m: /^Capture screen (\d+)$/i.exec(d.name) }))
142
+ .filter((d) => d.m)
143
+ .map((d) => ({ index: d.index, name: d.name, screen: Number(d.m[1]) }))
144
+ .sort((a, b) => a.screen - b.screen);
145
+ }
146
+ export async function listAvfoundation(run = realRunner, env = process.env) {
147
+ const ffmpeg = ffmpegPath("darwin", env);
148
+ if (!ffmpeg)
149
+ return null;
150
+ const r = await run(ffmpeg, ["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""], env);
151
+ if (r.status === null)
152
+ return null;
153
+ return parseAvfoundationDevices(r.stderr + r.stdout);
154
+ }
155
+ // ---------------------------------------------------------------------------
156
+ // Windows
157
+ // ---------------------------------------------------------------------------
158
+ /** `ffmpeg -f dshow -list_devices true -i dummy` (stderr), old and new formats. */
159
+ export function parseDshowAudioDevices(text) {
160
+ const out = [];
161
+ let legacyAudio = false;
162
+ for (const line of text.split("\n")) {
163
+ if (/DirectShow audio devices/i.test(line))
164
+ legacyAudio = true;
165
+ else if (/DirectShow video devices/i.test(line))
166
+ legacyAudio = false;
167
+ if (/Alternative name/i.test(line))
168
+ continue;
169
+ const tagged = /\]\s+"(.+)"\s+\((audio|video|none)\)\s*$/.exec(line);
170
+ if (tagged) {
171
+ if (tagged[2] === "audio")
172
+ out.push(tagged[1]);
173
+ continue;
174
+ }
175
+ const legacy = /\]\s+"(.+)"\s*$/.exec(line);
176
+ if (legacy && legacyAudio)
177
+ out.push(legacy[1]);
178
+ }
179
+ return out;
180
+ }
181
+ /** The `S <json>` line PowerShell prints for Screen.AllScreens. */
182
+ export function parseScreensLine(text) {
183
+ for (const line of text.split(/\r?\n/)) {
184
+ if (!line.startsWith("S "))
185
+ continue;
186
+ try {
187
+ const raw = JSON.parse(line.slice(2));
188
+ const list = Array.isArray(raw) ? raw : [raw];
189
+ return list
190
+ .filter((s) => !!s && typeof s === "object")
191
+ .map((s, i) => ({
192
+ name: typeof s.name === "string" && s.name ? s.name : `Display ${i + 1}`,
193
+ primary: s.primary === true,
194
+ x: Number(s.x) || 0,
195
+ y: Number(s.y) || 0,
196
+ width: Number(s.width) || 0,
197
+ height: Number(s.height) || 0,
198
+ }))
199
+ .filter((s) => s.width > 0 && s.height > 0);
200
+ }
201
+ catch {
202
+ return [];
203
+ }
204
+ }
205
+ return [];
206
+ }
207
+ export async function windowsScreens(run = realRunner, env = process.env) {
208
+ const r = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encodePowerShell(windowsScreensScript())], env);
209
+ return r.status === 0 ? primaryFirst(parseScreensLine(r.stdout)) : [];
210
+ }
211
+ /** The main display first, so display:0 is always the main one. */
212
+ export function primaryFirst(screens) {
213
+ const i = screens.findIndex((s) => s.primary);
214
+ return i > 0 ? [screens[i], ...screens.filter((_, j) => j !== i)] : screens;
215
+ }
216
+ export async function listDshowAudio(run = realRunner, env = process.env) {
217
+ const ffmpeg = ffmpegPath("win32", env);
218
+ if (!ffmpeg)
219
+ return [];
220
+ const r = await run(ffmpeg, ["-hide_banner", "-f", "dshow", "-list_devices", "true", "-i", "dummy"], env);
221
+ return parseDshowAudioDevices(r.stderr + r.stdout);
222
+ }
223
+ /** "display:0" / "0" / "window:0x1a00003". */
224
+ export function parseSourceId(id) {
225
+ if (id === undefined || id === "" || id === "main")
226
+ return { kind: "display", index: 0 };
227
+ const display = /^(?:display:)?(\d+)$/.exec(id);
228
+ if (display)
229
+ return { kind: "display", index: Number(display[1]) };
230
+ const window = /^window:(0x[0-9a-f]+|\d+)$/i.exec(id);
231
+ if (window)
232
+ return { kind: "window", id: window[1].startsWith("0x") || window[1].startsWith("0X") ? parseInt(window[1], 16) : Number(window[1]) };
233
+ throw new Error(`unknown capture source "${id}" (expected display:N or window:0x...)`);
234
+ }
235
+ export async function listSources(platform = currentPlatform(), opts = {}) {
236
+ const run = opts.run ?? realRunner;
237
+ const env = opts.env ?? process.env;
238
+ if (platform === "linux") {
239
+ const xDisplay = opts.xDisplay ?? env.DISPLAY;
240
+ if (!xDisplay)
241
+ return [];
242
+ const screens = await linuxScreens(xDisplay, run, env);
243
+ const displays = screens.map((s, i) => ({
244
+ id: `display:${i}`,
245
+ kind: "display",
246
+ name: s.primary && screens.length > 1 ? `${s.name} (main)` : s.name,
247
+ width: s.width,
248
+ height: s.height,
249
+ }));
250
+ return [...displays, ...(await linuxWindows(xDisplay, run, env))];
251
+ }
252
+ if (platform === "darwin") {
253
+ const devices = await listAvfoundation(run, env);
254
+ if (!devices)
255
+ return [];
256
+ return avfoundationScreens(devices).map((d, i) => ({
257
+ id: `display:${i}`,
258
+ kind: "display",
259
+ name: i === 0 ? `${d.name} (main)` : d.name,
260
+ }));
261
+ }
262
+ const screens = await windowsScreens(run, env);
263
+ if (screens.length === 0)
264
+ return [{ id: "display:0", kind: "display", name: "Display 1 (main)" }];
265
+ return screens.map((s, i) => ({
266
+ id: `display:${i}`,
267
+ kind: "display",
268
+ name: s.primary ? `${s.name} (main)` : s.name,
269
+ width: s.width,
270
+ height: s.height,
271
+ }));
272
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,170 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/capture/src/virtualDisplay.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * A private X display (Xvfb) on Linux: something only the agent draws on, so
5
+ * the user's own screen, pointer and keyboard are never involved.
6
+ *
7
+ * Xvfb listens on no TCP port and, when `xauth` is installed, starts with
8
+ * access control on: a random cookie in an Xauthority file only this user can
9
+ * read. Processes of this user are then also allowed by name (localuser), so
10
+ * `DISPLAY=:N <app>` keeps working for the user who started it; other users on
11
+ * the machine cannot connect. Without `xauth` it starts as before, open to
12
+ * local clients, and says so in `warnings`.
13
+ */
14
+ import { execFileSync, spawn } from "node:child_process";
15
+ import { randomBytes } from "node:crypto";
16
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
17
+ import { tmpdir, userInfo } from "node:os";
18
+ import { join } from "node:path";
19
+ import { atExit, trackChild } from "./children.js";
20
+ import { even } from "./ffmpegArgs.js";
21
+ import { findExecutable, sleep } from "./proc.js";
22
+ import { ALLOW_LOCAL_USER_SCRIPT, forgetXAuthority, OPEN_DISPLAY_SCRIPT, registerXAuthority } from "./xauth.js";
23
+ export function validateDisplaySize(width, height) {
24
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width < 320 || height < 240 || width > 7680 || height > 4320) {
25
+ throw new Error(`virtual display size must be between 320x240 and 7680x4320 (got ${width}x${height})`);
26
+ }
27
+ return { width: even(width), height: even(height) };
28
+ }
29
+ function freeDisplayNumber() {
30
+ for (let n = 90; n < 200; n++) {
31
+ if (!existsSync(`/tmp/.X11-unix/X${n}`) && !existsSync(`/tmp/.X${n}-lock`))
32
+ return n;
33
+ }
34
+ throw new Error("no free X display number between :90 and :199");
35
+ }
36
+ function gone(child) {
37
+ return child.exitCode !== null || child.signalCode !== null;
38
+ }
39
+ async function terminate(child, graceMs = 3000) {
40
+ if (gone(child))
41
+ return;
42
+ const exited = new Promise((r) => child.once("exit", () => r()));
43
+ child.kill("SIGTERM");
44
+ const timer = setTimeout(() => child.kill("SIGKILL"), graceMs);
45
+ await exited;
46
+ clearTimeout(timer);
47
+ }
48
+ /** A folder only this user can open, holding an Xauthority file with a fresh cookie for `display`. */
49
+ function writeAuthority(xauthPath, display) {
50
+ const dir = mkdtempSync(join(tmpdir(), "clipy-xvfb-"));
51
+ const file = join(dir, "Xauthority");
52
+ try {
53
+ execFileSync(xauthPath, ["-q", "-f", file, "add", display, "MIT-MAGIC-COOKIE-1", randomBytes(16).toString("hex")], {
54
+ stdio: "ignore",
55
+ timeout: 5000,
56
+ });
57
+ return existsSync(file) ? { dir, file } : (rmSync(dir, { recursive: true, force: true }), null);
58
+ }
59
+ catch {
60
+ rmSync(dir, { recursive: true, force: true });
61
+ return null;
62
+ }
63
+ }
64
+ /**
65
+ * Let every process of this user connect without the cookie, so
66
+ * `DISPLAY=:N <app>` works for them. Best effort, and checked: true only when
67
+ * a client without the cookie really connects (some X servers ignore the
68
+ * grant).
69
+ */
70
+ function allowThisUser(display, xauthority, dir) {
71
+ const env = { ...process.env, DISPLAY: display, XAUTHORITY: xauthority };
72
+ const python = findExecutable("python3", "linux");
73
+ let user;
74
+ try {
75
+ user = userInfo().username;
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ const run = (cmd, args, runEnv) => {
81
+ try {
82
+ execFileSync(cmd, args, { env: runEnv, stdio: "ignore", timeout: 5000 });
83
+ return true;
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ };
89
+ const xhost = findExecutable("xhost", "linux");
90
+ const granted = (xhost !== null && run(xhost, [`+si:localuser:${user}`], env)) ||
91
+ (python !== null && run(python, ["-c", ALLOW_LOCAL_USER_SCRIPT, user], env));
92
+ if (!granted)
93
+ return false;
94
+ // Without the cookie: an Xauthority path that does not exist.
95
+ return python === null || run(python, ["-c", OPEN_DISPLAY_SCRIPT], { ...process.env, DISPLAY: display, XAUTHORITY: join(dir, "none") });
96
+ }
97
+ export async function startVirtualDisplay(opts = {}) {
98
+ if (process.platform !== "linux")
99
+ throw new Error("a virtual display needs Linux with Xvfb");
100
+ const xvfbPath = findExecutable("Xvfb", "linux");
101
+ if (!xvfbPath)
102
+ throw new Error("a virtual display needs Xvfb (Debian/Ubuntu: `sudo apt install xvfb`, Fedora: `sudo dnf install xorg-x11-server-Xvfb`)");
103
+ const size = validateDisplaySize(opts.width ?? 1280, opts.height ?? 720);
104
+ const xauthPath = findExecutable("xauth", "linux");
105
+ // Two starts can race for the same free number; Xvfb then exits at once
106
+ // and the next number is tried.
107
+ for (let attempt = 0; attempt < 5; attempt++) {
108
+ const n = freeDisplayNumber() + attempt;
109
+ const display = `:${n}`;
110
+ const warnings = [];
111
+ const auth = xauthPath ? writeAuthority(xauthPath, display) : null;
112
+ if (!auth) {
113
+ warnings.push(xauthPath
114
+ ? "xauth could not write a cookie, so the virtual display has no access control: other local users can connect to it"
115
+ : "xauth is not installed (Debian/Ubuntu: `sudo apt install xauth`), so the virtual display has no access control: other local users can connect to it");
116
+ }
117
+ const removeAuthNow = () => {
118
+ if (auth)
119
+ rmSync(auth.dir, { recursive: true, force: true });
120
+ };
121
+ // If the process exits without stop(), the cookie still goes.
122
+ const cancelExitCleanup = atExit(removeAuthNow);
123
+ const removeAuth = () => {
124
+ cancelExitCleanup();
125
+ removeAuthNow();
126
+ };
127
+ const args = [display, "-screen", "0", `${size.width}x${size.height}x24`, "-nolisten", "tcp", ...(auth ? ["-auth", auth.file] : [])];
128
+ const xvfb = trackChild(spawn(xvfbPath, args, { stdio: "ignore" }));
129
+ let spawnError = null;
130
+ xvfb.on("error", (err) => {
131
+ spawnError = err;
132
+ });
133
+ const deadline = Date.now() + 5000;
134
+ while (Date.now() < deadline && !gone(xvfb) && !spawnError && !existsSync(`/tmp/.X11-unix/X${n}`))
135
+ await sleep(50);
136
+ if (spawnError) {
137
+ removeAuth();
138
+ throw new Error(`Xvfb could not start: ${spawnError.message}`);
139
+ }
140
+ if (gone(xvfb) || !existsSync(`/tmp/.X11-unix/X${n}`)) {
141
+ await terminate(xvfb);
142
+ removeAuth();
143
+ continue;
144
+ }
145
+ // The socket appears just before the server accepts connections.
146
+ await sleep(150);
147
+ if (auth) {
148
+ registerXAuthority(display, auth.file);
149
+ if (!allowThisUser(display, auth.file, auth.dir)) {
150
+ warnings.push(`apps launched on ${display} need XAUTHORITY=${auth.file} as well as DISPLAY=${display}`);
151
+ }
152
+ }
153
+ let stopped = null;
154
+ return {
155
+ display,
156
+ pid: xvfb.pid,
157
+ xauthority: auth?.file ?? null,
158
+ warnings,
159
+ env: (base = process.env) => ({ ...base, DISPLAY: display, ...(auth ? { XAUTHORITY: auth.file } : {}) }),
160
+ stop() {
161
+ stopped ??= terminate(xvfb).finally(() => {
162
+ forgetXAuthority(display);
163
+ removeAuth();
164
+ });
165
+ return stopped;
166
+ },
167
+ };
168
+ }
169
+ throw new Error("Xvfb did not start");
170
+ }
@@ -0,0 +1,68 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/capture/src/xauth.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * X authority for the private displays this package starts.
5
+ *
6
+ * A virtual display is started with access control on: only clients holding
7
+ * its cookie (an Xauthority file readable by this user alone) can connect,
8
+ * and, when it can be arranged, any process of this same user. Other users on
9
+ * the machine cannot read or draw on it.
10
+ *
11
+ * Every X client this package runs against a display it started (ffmpeg, the
12
+ * pointer helper, xrandr and friends) gets that display's XAUTHORITY through
13
+ * `xEnv`.
14
+ */
15
+ /** display name (":91") -> its Xauthority file */
16
+ const authorities = new Map();
17
+ export function registerXAuthority(display, file) {
18
+ authorities.set(display, file);
19
+ }
20
+ export function forgetXAuthority(display) {
21
+ authorities.delete(display);
22
+ }
23
+ /** The Xauthority file of a display this process started, if any. */
24
+ export function xAuthorityFor(display) {
25
+ return display ? authorities.get(display) : undefined;
26
+ }
27
+ /** `env` with DISPLAY set to `xDisplay`, plus XAUTHORITY when it is a display this process started. */
28
+ export function xEnv(env, xDisplay) {
29
+ if (!xDisplay)
30
+ return env;
31
+ const auth = authorities.get(xDisplay);
32
+ return { ...env, DISPLAY: xDisplay, ...(auth ? { XAUTHORITY: auth } : {}) };
33
+ }
34
+ /**
35
+ * python3 -c <this> <user>: allow every process of <user> on the display
36
+ * (server-interpreted "localuser", what `xhost +si:localuser:<user>` does).
37
+ * Needs only libX11, like the pointer helper.
38
+ */
39
+ export const ALLOW_LOCAL_USER_SCRIPT = String.raw `
40
+ import ctypes, ctypes.util, sys
41
+ x = ctypes.cdll.LoadLibrary(ctypes.util.find_library("X11") or "libX11.so.6")
42
+ class SI(ctypes.Structure):
43
+ _fields_ = [("typelength", ctypes.c_int), ("valuelength", ctypes.c_int), ("type", ctypes.c_char_p), ("value", ctypes.c_char_p)]
44
+ class Host(ctypes.Structure):
45
+ _fields_ = [("family", ctypes.c_int), ("length", ctypes.c_int), ("address", ctypes.c_void_p)]
46
+ x.XOpenDisplay.restype = ctypes.c_void_p
47
+ x.XOpenDisplay.argtypes = [ctypes.c_char_p]
48
+ x.XAddHost.argtypes = [ctypes.c_void_p, ctypes.POINTER(Host)]
49
+ x.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]
50
+ x.XCloseDisplay.argtypes = [ctypes.c_void_p]
51
+ d = x.XOpenDisplay(None)
52
+ if not d:
53
+ sys.exit(2)
54
+ user = sys.argv[1].encode()
55
+ si = SI(9, len(user), b"localuser", user)
56
+ host = Host(5, ctypes.sizeof(SI), ctypes.cast(ctypes.pointer(si), ctypes.c_void_p))
57
+ x.XAddHost(d, ctypes.byref(host))
58
+ x.XSync(d, 0)
59
+ x.XCloseDisplay(d)
60
+ `;
61
+ /** python3 -c <this>: exit 0 when the X display in $DISPLAY accepts a connection. */
62
+ export const OPEN_DISPLAY_SCRIPT = String.raw `
63
+ import ctypes, ctypes.util, sys
64
+ x = ctypes.cdll.LoadLibrary(ctypes.util.find_library("X11") or "libX11.so.6")
65
+ x.XOpenDisplay.restype = ctypes.c_void_p
66
+ x.XOpenDisplay.argtypes = [ctypes.c_char_p]
67
+ sys.exit(0 if x.XOpenDisplay(None) else 1)
68
+ `;
@@ -0,0 +1,12 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/config/src/errors.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * A settings problem the user can fix. The message names the file or env var
5
+ * and the field, and never contains an API key, so it is safe to print as is.
6
+ */
7
+ export class ConfigError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "ConfigError";
11
+ }
12
+ }