Repository navigation
Expand file tree
/
Copy pathhost-metadata.ts
More file actions
244 lines (220 loc) · 7.01 KB
/
Copy pathhost-metadata.ts
File metadata and controls
244 lines (220 loc) · 7.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import { execFileSync } from "node:child_process";
import { basename } from "node:path";
import type { HostApp } from "@monitor/contracts";
import type { CursorWindowSnapshot } from "./focus/cursor-window.js";
import { parseCursorWindowRef } from "./focus/cursor-window.js";
export interface HostMetadata {
hostApp: HostApp;
hostWindowRef: string | null;
hostSessionRef: string | null;
}
export interface DetectHostMetadataOptions {
termProgram?: string;
termProgramVersion?: string;
windowId?: string | null;
termSessionId?: string | null;
cursorTraceId?: string | null;
cursorAgent?: string | null;
cursorWindowRef?: string | null;
cursorWindowRefResolver?: () => string | null;
ttyRef?: string | null;
cwd?: string | null;
}
export function detectHostApp(
termProgram = process.env.TERM_PROGRAM ?? "",
termProgramVersion = process.env.TERM_PROGRAM_VERSION ?? "",
cursorTraceId = process.env.CURSOR_TRACE_ID ?? "",
cursorAgent = process.env.CURSOR_AGENT ?? ""
): HostApp {
const normalizedTermProgram = termProgram.toLowerCase();
if (normalizedTermProgram.includes("apple_terminal")) return "terminal";
if (normalizedTermProgram.includes("iterm")) return "iterm2";
if (
cursorTraceId ||
cursorAgent ||
normalizedTermProgram === "vscode" ||
termProgramVersion.includes("Cursor")
) {
return "cursor";
}
return "unknown";
}
export function resolveTtyRef(pid = process.pid): string | null {
try {
const ttyName = execFileSync("ps", ["-p", String(pid), "-o", "tty="], {
encoding: "utf8"
}).trim();
if (!ttyName || ttyName === "??") {
return null;
}
return ttyName.startsWith("/dev/") ? ttyName : `/dev/${ttyName}`;
} catch {
return null;
}
}
function parseCursorWindowSnapshotLines(lines: string[]): CursorWindowSnapshot | null {
const [
titleLine,
documentLine,
positionLine,
sizeLine,
windowNumberLine,
identifierLine
] = lines;
if (!titleLine) return null;
const parseNumberPair = (value: string | undefined): [number | null, number | null] => {
if (!value) return [null, null];
const match = /^\s*(-?\d+)\s*,\s*(-?\d+)\s*$/.exec(value);
if (!match) return [null, null];
return [Number(match[1]), Number(match[2])];
};
const parseOptionalInteger = (value: string | undefined): number | null => {
if (!value) return null;
const trimmed = value.trim();
if (!/^-?\d+$/.test(trimmed)) {
return null;
}
return Number(trimmed);
};
const [x, y] = parseNumberPair(positionLine);
const [width, height] = parseNumberPair(sizeLine);
const document = documentLine || null;
const workspaceMatch = /\/([^/]+?)(?:\/)?$/.exec(document ?? "");
return {
title: titleLine || null,
document,
workspace: workspaceMatch?.[1] ?? null,
x,
y,
width,
height,
windowNumber: parseOptionalInteger(windowNumberLine),
identifier: identifierLine || null
};
}
function serializeCursorWindowSnapshot(snapshot: CursorWindowSnapshot): string {
return `cursor-window:${JSON.stringify(snapshot)}`;
}
function normalizeCursorWindowRef(
windowRef: string | null,
cwd: string | null
): string | null {
const snapshot = parseCursorWindowRef(windowRef);
if (!snapshot) {
return windowRef;
}
const documentBasename = /\/([^/]+?)(?:\/)?$/.exec(snapshot.document ?? "")?.[1] ?? null;
const shouldNormalize =
!snapshot.workspace ||
snapshot.workspace === documentBasename ||
/\.[A-Za-z0-9]+$/.test(snapshot.workspace);
if (!shouldNormalize) {
return windowRef;
}
const workspace = cwd ? basename(cwd) : snapshot.workspace;
if (!workspace || workspace === snapshot.workspace) {
return windowRef;
}
return serializeCursorWindowSnapshot({
...snapshot,
workspace
});
}
export function resolveCursorWindowRef(): string | null {
try {
const output = execFileSync(
"osascript",
[
"-e",
'tell application "System Events"',
"-e",
'if not (exists process "Cursor") then return ""',
"-e",
'tell process "Cursor"',
"-e",
'if (count of windows) is 0 then return ""',
"-e",
"set targetWindow to front window",
"-e",
'set titleValue to (value of attribute "AXTitle" of targetWindow as text)',
"-e",
'set documentValue to (value of attribute "AXDocument" of targetWindow as text)',
"-e",
'set positionValue to (value of attribute "AXPosition" of targetWindow)',
"-e",
'set sizeValue to (value of attribute "AXSize" of targetWindow)',
"-e",
'set windowNumberValue to ""',
"-e",
'try',
"-e",
'set windowNumberValue to (value of attribute "AXWindowNumber" of targetWindow as text)',
"-e",
'end try',
"-e",
'set identifierValue to ""',
"-e",
'try',
"-e",
'set identifierValue to (value of attribute "AXIdentifier" of targetWindow as text)',
"-e",
'end try',
"-e",
'return titleValue & linefeed & documentValue & linefeed & (item 1 of positionValue as text) & "," & (item 2 of positionValue as text) & linefeed & (item 1 of sizeValue as text) & "," & (item 2 of sizeValue as text) & linefeed & windowNumberValue & linefeed & identifierValue',
"-e",
"end tell",
"-e",
"end tell"
],
{ encoding: "utf8" }
).trim();
if (!output) {
return null;
}
const snapshot = parseCursorWindowSnapshotLines(output.split(/\r?\n/));
return snapshot ? serializeCursorWindowSnapshot(snapshot) : null;
} catch {
return null;
}
}
export function detectHostMetadata(
options: DetectHostMetadataOptions = {}
): HostMetadata {
const termProgram = options.termProgram ?? process.env.TERM_PROGRAM ?? "";
const termProgramVersion =
options.termProgramVersion ?? process.env.TERM_PROGRAM_VERSION ?? "";
const cursorTraceId = options.cursorTraceId ?? process.env.CURSOR_TRACE_ID ?? null;
const cursorAgent = options.cursorAgent ?? process.env.CURSOR_AGENT ?? null;
const hostApp = detectHostApp(
termProgram,
termProgramVersion,
cursorTraceId ?? "",
cursorAgent ?? ""
);
const cursorWindowRef =
options.cursorWindowRef !== undefined
? options.cursorWindowRef
: hostApp === "cursor"
? (options.cursorWindowRefResolver ?? resolveCursorWindowRef)()
: null;
const cwd = options.cwd ?? process.cwd();
const termSessionId = options.termSessionId ?? process.env.TERM_SESSION_ID ?? null;
const ttyRef = options.ttyRef === undefined ? resolveTtyRef() : options.ttyRef;
if (hostApp === "cursor") {
return {
hostApp,
hostWindowRef:
cursorTraceId ??
options.windowId ??
process.env.WINDOWID ??
normalizeCursorWindowRef(cursorWindowRef, cwd) ??
null,
hostSessionRef: cursorAgent
};
}
return {
hostApp,
hostWindowRef: options.windowId ?? process.env.WINDOWID ?? termSessionId,
hostSessionRef: ttyRef ?? termSessionId
};
}