codex-in-chrome 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +362 -2
- package/assets/logo.png +0 -0
- package/assets/logo.svg +9 -0
- package/bin/cli.mjs +41 -0
- package/dist/server.mjs +39416 -0
- package/extension/background.js +2222 -0
- package/extension/dom.js +178 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/manifest.json +35 -0
- package/extension/overlay.js +278 -0
- package/package.json +43 -6
- package/rules/AGENTS.md +10 -0
- package/scripts/install.mjs +271 -0
- package/skills/codex-in-chrome/SKILL.md +34 -0
|
@@ -0,0 +1,2222 @@
|
|
|
1
|
+
const DEFAULT_GROUP_TITLE = 'Codex';
|
|
2
|
+
const DEFAULT_GROUP_COLOR = 'blue';
|
|
3
|
+
const BRIDGE_PORT = 38955;
|
|
4
|
+
const BRIDGE_WS_URL = `ws://127.0.0.1:${BRIDGE_PORT}`;
|
|
5
|
+
|
|
6
|
+
let ws = null;
|
|
7
|
+
// Background mode: agent tabs are never brought to the front, so the user can
|
|
8
|
+
// keep working in their own tabs while the agent acts (and records) behind them.
|
|
9
|
+
let backgroundMode = false;
|
|
10
|
+
// Stealth mode: interact like a real person (human typing cadence with randomized
|
|
11
|
+
// flight and dwell times, curved mouse movement trajectories, click dwell times,
|
|
12
|
+
// and avoidance of programmatic value injection).
|
|
13
|
+
let stealthMode = false;
|
|
14
|
+
const cursorPositions = new Map(); // tabId -> {x, y}
|
|
15
|
+
let reconnectTimer = null;
|
|
16
|
+
let keepaliveTimer = null;
|
|
17
|
+
const attachedDebugTabs = new Set();
|
|
18
|
+
|
|
19
|
+
chrome.debugger.onDetach.addListener(source => {
|
|
20
|
+
if (source?.tabId !== undefined) {
|
|
21
|
+
attachedDebugTabs.delete(source.tabId);
|
|
22
|
+
consoleOn.delete(source.tabId);
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
function setBadge(connected) {
|
|
27
|
+
chrome.action
|
|
28
|
+
.setBadgeText({text: connected ? 'ON' : '...'})
|
|
29
|
+
.catch(() => {});
|
|
30
|
+
chrome.action
|
|
31
|
+
.setBadgeBackgroundColor({color: connected ? '#2563EB' : '#64748B'})
|
|
32
|
+
.catch(() => {});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// While Codex isn't running nothing listens on the port, and Chrome logs every
|
|
36
|
+
// failed attempt on the extension's Errors page. Back off (2s -> 15s) so that
|
|
37
|
+
// list doesn't flood; reset as soon as a connection succeeds.
|
|
38
|
+
let failures = 0;
|
|
39
|
+
let nextTryAt = 0;
|
|
40
|
+
function backoffMs() {
|
|
41
|
+
return Math.min(2000 * 2 ** failures, 15000);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function scheduleReconnect(delayMs = backoffMs()) {
|
|
45
|
+
if (reconnectTimer) return;
|
|
46
|
+
reconnectTimer = setTimeout(() => {
|
|
47
|
+
reconnectTimer = null;
|
|
48
|
+
connectWs();
|
|
49
|
+
}, delayMs);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const __codexLog = (globalThis.__codexLog = []);
|
|
53
|
+
function logBridge(msg) {
|
|
54
|
+
__codexLog.push(`${Date.now()}: ${msg}`);
|
|
55
|
+
if (__codexLog.length > 30) __codexLog.shift();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function connectWs() {
|
|
59
|
+
logBridge(`connectWs called (cur=${ws?.readyState})`);
|
|
60
|
+
if (Date.now() < nextTryAt) return;
|
|
61
|
+
if (
|
|
62
|
+
ws &&
|
|
63
|
+
(ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)
|
|
64
|
+
) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (probing) return;
|
|
68
|
+
probing = true;
|
|
69
|
+
// Ask quietly first: a refused WebSocket is logged on the extension's
|
|
70
|
+
// Errors page every time, a caught fetch failure is not.
|
|
71
|
+
fetch(`http://127.0.0.1:${BRIDGE_PORT}/health`, {cache: 'no-store'})
|
|
72
|
+
.then(r => r.ok)
|
|
73
|
+
.catch(() => false)
|
|
74
|
+
.then(up => {
|
|
75
|
+
probing = false;
|
|
76
|
+
if (up) openSocket();
|
|
77
|
+
else {
|
|
78
|
+
failures++;
|
|
79
|
+
setBadge(false);
|
|
80
|
+
scheduleReconnect();
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
let probing = false;
|
|
86
|
+
function openSocket() {
|
|
87
|
+
if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) return;
|
|
88
|
+
try {
|
|
89
|
+
const socket = new WebSocket(BRIDGE_WS_URL);
|
|
90
|
+
ws = socket;
|
|
91
|
+
|
|
92
|
+
socket.onopen = () => {
|
|
93
|
+
socket.__opened = true;
|
|
94
|
+
logBridge('ws open');
|
|
95
|
+
failures = 0;
|
|
96
|
+
nextTryAt = 0;
|
|
97
|
+
setBadge(true);
|
|
98
|
+
socket.send(
|
|
99
|
+
JSON.stringify({
|
|
100
|
+
type: 'hello',
|
|
101
|
+
extensionId: chrome.runtime.id,
|
|
102
|
+
version: chrome.runtime.getManifest().version,
|
|
103
|
+
}),
|
|
104
|
+
);
|
|
105
|
+
if (keepaliveTimer) clearInterval(keepaliveTimer);
|
|
106
|
+
keepaliveTimer = setInterval(() => {
|
|
107
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
108
|
+
socket.send(JSON.stringify({type: 'ping'}));
|
|
109
|
+
}
|
|
110
|
+
}, 15000);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
socket.onmessage = async event => {
|
|
114
|
+
let req;
|
|
115
|
+
try {
|
|
116
|
+
req = JSON.parse(event.data);
|
|
117
|
+
} catch {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (!req?.id || !req?.method) return;
|
|
121
|
+
try {
|
|
122
|
+
const result = await dispatchCommand(req.method, req.params || {});
|
|
123
|
+
socket.send(JSON.stringify({id: req.id, ok: true, result}));
|
|
124
|
+
} catch (err) {
|
|
125
|
+
socket.send(
|
|
126
|
+
JSON.stringify({
|
|
127
|
+
id: req.id,
|
|
128
|
+
ok: false,
|
|
129
|
+
error: err?.message || String(err),
|
|
130
|
+
}),
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
socket.onclose = ev => {
|
|
136
|
+
logBridge(`ws close code=${ev?.code} reason=${ev?.reason}`);
|
|
137
|
+
if (ws === socket) ws = null;
|
|
138
|
+
if (keepaliveTimer) {
|
|
139
|
+
clearInterval(keepaliveTimer);
|
|
140
|
+
keepaliveTimer = null;
|
|
141
|
+
}
|
|
142
|
+
setBadge(false);
|
|
143
|
+
// A bridge that was up and went away is usually another Codex window
|
|
144
|
+
// taking over the port: retry fast first, then back off.
|
|
145
|
+
if (socket.__opened) {
|
|
146
|
+
failures = 0;
|
|
147
|
+
nextTryAt = 0;
|
|
148
|
+
scheduleReconnect(700);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (!ev?.wasClean) failures++;
|
|
152
|
+
nextTryAt = Date.now() + backoffMs() - 50;
|
|
153
|
+
scheduleReconnect();
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
socket.onerror = ev => {
|
|
157
|
+
logBridge(`ws error type=${ev?.type}`);
|
|
158
|
+
try {
|
|
159
|
+
socket.close();
|
|
160
|
+
} catch {}
|
|
161
|
+
};
|
|
162
|
+
} catch (err) {
|
|
163
|
+
logBridge(`ws catch ${err?.message || err}`);
|
|
164
|
+
setBadge(false);
|
|
165
|
+
failures++;
|
|
166
|
+
scheduleReconnect();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
chrome.alarms.create('codex-pilot-reconnect', {periodInMinutes: 0.4});
|
|
171
|
+
chrome.alarms.onAlarm.addListener(alarm => {
|
|
172
|
+
if (alarm.name === 'codex-pilot-reconnect') {
|
|
173
|
+
connectWs();
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
chrome.runtime.onStartup.addListener(() => connectWs());
|
|
177
|
+
chrome.runtime.onInstalled.addListener(() => connectWs());
|
|
178
|
+
// Clicking the icon retries right away, skipping the backoff.
|
|
179
|
+
chrome.action.onClicked.addListener(() => {
|
|
180
|
+
failures = 0;
|
|
181
|
+
nextTryAt = 0;
|
|
182
|
+
connectWs();
|
|
183
|
+
});
|
|
184
|
+
let currentMethod = 'idle';
|
|
185
|
+
chrome.tabs.onActivated.addListener(info => {
|
|
186
|
+
logBridge(`tab ${info.tabId} activated during ${currentMethod}`);
|
|
187
|
+
connectWs();
|
|
188
|
+
});
|
|
189
|
+
connectWs();
|
|
190
|
+
|
|
191
|
+
async function findGroup(groupTitle = DEFAULT_GROUP_TITLE) {
|
|
192
|
+
const groups = await chrome.tabGroups.query({title: groupTitle});
|
|
193
|
+
return groups[0] ?? null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function listGroupTabs(groupTitle = DEFAULT_GROUP_TITLE) {
|
|
197
|
+
const group = await findGroup(groupTitle);
|
|
198
|
+
if (!group) {
|
|
199
|
+
return {groupId: null, title: groupTitle, tabs: []};
|
|
200
|
+
}
|
|
201
|
+
const tabs = await chrome.tabs.query({groupId: group.id});
|
|
202
|
+
tabs.sort((a, b) => a.index - b.index);
|
|
203
|
+
return {
|
|
204
|
+
groupId: group.id,
|
|
205
|
+
title: group.title || groupTitle,
|
|
206
|
+
color: group.color,
|
|
207
|
+
windowId: group.windowId,
|
|
208
|
+
tabs: tabs.map(t => ({
|
|
209
|
+
tabId: t.id,
|
|
210
|
+
index: t.index,
|
|
211
|
+
windowId: t.windowId,
|
|
212
|
+
active: t.active,
|
|
213
|
+
url: t.url || t.pendingUrl || '',
|
|
214
|
+
title: t.title || '',
|
|
215
|
+
})),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Resolves as soon as the page DOM is usable (interactive), not when every
|
|
220
|
+
// image/ad has finished, which makes navigation-heavy steps much faster.
|
|
221
|
+
async function waitForTabReady(tabId, timeoutMs = 10000) {
|
|
222
|
+
const start = Date.now();
|
|
223
|
+
await new Promise(r => setTimeout(r, 80));
|
|
224
|
+
while (Date.now() - start < timeoutMs) {
|
|
225
|
+
const tab = await chrome.tabs.get(tabId).catch(() => null);
|
|
226
|
+
if (!tab) return null;
|
|
227
|
+
if (tab.status === 'complete') return tab;
|
|
228
|
+
const url = tab.url || tab.pendingUrl || '';
|
|
229
|
+
if (/^https?:/.test(url) && !tab.pendingUrl) {
|
|
230
|
+
const res = await chrome.scripting
|
|
231
|
+
.executeScript({target: {tabId}, func: () => document.readyState})
|
|
232
|
+
.catch(() => null);
|
|
233
|
+
const rs = res?.[0]?.result;
|
|
234
|
+
if (rs === 'interactive' || rs === 'complete') return tab;
|
|
235
|
+
}
|
|
236
|
+
await new Promise(r => setTimeout(r, 120));
|
|
237
|
+
}
|
|
238
|
+
return await chrome.tabs.get(tabId).catch(() => null);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function ensureOverlay(tabId, statusText) {
|
|
242
|
+
try {
|
|
243
|
+
await chrome.scripting.executeScript({
|
|
244
|
+
target: {tabId},
|
|
245
|
+
files: ['dom.js', 'overlay.js'],
|
|
246
|
+
});
|
|
247
|
+
if (statusText) {
|
|
248
|
+
await chrome.scripting.executeScript({
|
|
249
|
+
target: {tabId},
|
|
250
|
+
func: msg => window.__codexPilotOverlay?.setStatus(msg),
|
|
251
|
+
args: [statusText],
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
} catch {
|
|
255
|
+
// Restricted URLs (chrome://, Chrome Web Store) cannot be scripted.
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function openTab(
|
|
260
|
+
url = 'about:blank',
|
|
261
|
+
groupTitle = DEFAULT_GROUP_TITLE,
|
|
262
|
+
color = DEFAULT_GROUP_COLOR,
|
|
263
|
+
active = true,
|
|
264
|
+
session = 'default',
|
|
265
|
+
) {
|
|
266
|
+
const existingGroup = await findGroup(groupTitle);
|
|
267
|
+
let targetWindowId = existingGroup?.windowId;
|
|
268
|
+
if (targetWindowId === undefined) {
|
|
269
|
+
const win = await chrome.windows
|
|
270
|
+
.getLastFocused({windowTypes: ['normal']})
|
|
271
|
+
.catch(() => null);
|
|
272
|
+
targetWindowId = win?.id;
|
|
273
|
+
}
|
|
274
|
+
if (targetWindowId === undefined) {
|
|
275
|
+
const allWins = await chrome.windows
|
|
276
|
+
.getAll({windowTypes: ['normal']})
|
|
277
|
+
.catch(() => []);
|
|
278
|
+
targetWindowId = allWins[0]?.id;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Open blank, attach the debugger, then load: page-load requests, console
|
|
282
|
+
// errors and dialogs are all captured.
|
|
283
|
+
const tab = await chrome.tabs.create({
|
|
284
|
+
url: 'about:blank',
|
|
285
|
+
active: active && !backgroundMode,
|
|
286
|
+
...(targetWindowId !== undefined ? {windowId: targetWindowId} : {}),
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
const groupId = await chrome.tabs.group({
|
|
290
|
+
tabIds: [tab.id],
|
|
291
|
+
...(existingGroup
|
|
292
|
+
? {groupId: existingGroup.id}
|
|
293
|
+
: {createProperties: {windowId: tab.windowId}}),
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
await chrome.tabGroups.update(groupId, {
|
|
297
|
+
title: groupTitle,
|
|
298
|
+
color,
|
|
299
|
+
collapsed: false,
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
claimTab(tab.id, session);
|
|
303
|
+
await ensureDebugger(tab.id);
|
|
304
|
+
if (url && url !== 'about:blank') {
|
|
305
|
+
await chrome.tabs.update(tab.id, {url});
|
|
306
|
+
// Don't mistake the old about:blank for the loaded page.
|
|
307
|
+
for (let i = 0; i < 20; i++) {
|
|
308
|
+
const t = await chrome.tabs.get(tab.id).catch(() => null);
|
|
309
|
+
if (!t || t.status === 'loading' || (t.url && t.url !== 'about:blank')) break;
|
|
310
|
+
await sleep(25);
|
|
311
|
+
}
|
|
312
|
+
await waitForTabReady(tab.id);
|
|
313
|
+
}
|
|
314
|
+
const fresh = await chrome.tabs.get(tab.id).catch(() => tab);
|
|
315
|
+
await ensureOverlay(
|
|
316
|
+
tab.id,
|
|
317
|
+
`Tab Group "${groupTitle}" • ${fresh.title || 'Ready'}`,
|
|
318
|
+
);
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
tabId: fresh.id,
|
|
322
|
+
groupId,
|
|
323
|
+
windowId: fresh.windowId,
|
|
324
|
+
url: fresh.url || fresh.pendingUrl || url,
|
|
325
|
+
title: fresh.title || '',
|
|
326
|
+
stealth: stealthMode,
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// Several Codex sessions can share one Chrome. Each session gets its own
|
|
331
|
+
// current tab; a tab belongs to the session that opened or last used it, and
|
|
332
|
+
// a tab whose session has been quiet for 10 minutes (or is unknown) can be
|
|
333
|
+
// adopted by another session.
|
|
334
|
+
const tabOwner = new Map(); // tabId -> session
|
|
335
|
+
const sessionTab = new Map(); // session -> tabId
|
|
336
|
+
const sessionSeen = new Map(); // session -> last command time
|
|
337
|
+
const SESSION_IDLE_MS = 10 * 60 * 1000;
|
|
338
|
+
|
|
339
|
+
function claimTab(tabId, session = 'default') {
|
|
340
|
+
tabOwner.set(tabId, session);
|
|
341
|
+
sessionTab.set(session, tabId);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function ownedByOther(tabId, session) {
|
|
345
|
+
const owner = tabOwner.get(tabId);
|
|
346
|
+
if (!owner || owner === session) return false;
|
|
347
|
+
return Date.now() - (sessionSeen.get(owner) || 0) < SESSION_IDLE_MS;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function resolveGroupTab(tabId, groupTitle = DEFAULT_GROUP_TITLE, session = 'default') {
|
|
351
|
+
const info = await listGroupTabs(groupTitle);
|
|
352
|
+
if (tabId !== undefined && tabId !== null) {
|
|
353
|
+
const found = info.tabs.find(t => t.tabId === tabId);
|
|
354
|
+
if (!found) {
|
|
355
|
+
throw new Error(
|
|
356
|
+
`Tab ${tabId} is not inside the "${groupTitle}" tab group.`,
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
if (!ownedByOther(found.tabId, session)) claimTab(found.tabId, session);
|
|
360
|
+
return found;
|
|
361
|
+
}
|
|
362
|
+
const mineId = sessionTab.get(session);
|
|
363
|
+
const mine = info.tabs.find(t => t.tabId === mineId);
|
|
364
|
+
if (mine) return mine;
|
|
365
|
+
const free = info.tabs.filter(t => !ownedByOther(t.tabId, session));
|
|
366
|
+
const pick = free.find(t => t.active) || free[free.length - 1];
|
|
367
|
+
if (pick) {
|
|
368
|
+
claimTab(pick.tabId, session);
|
|
369
|
+
return pick;
|
|
370
|
+
}
|
|
371
|
+
return await openTab('about:blank', groupTitle, DEFAULT_GROUP_COLOR, true, session);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async function ensureGroup(
|
|
375
|
+
groupTitle = DEFAULT_GROUP_TITLE,
|
|
376
|
+
color = DEFAULT_GROUP_COLOR,
|
|
377
|
+
initialUrl,
|
|
378
|
+
session = 'default',
|
|
379
|
+
) {
|
|
380
|
+
const existing = await listGroupTabs(groupTitle);
|
|
381
|
+
if (initialUrl) {
|
|
382
|
+
const opened = await openTab(initialUrl, groupTitle, color, true, session);
|
|
383
|
+
const updated = await listGroupTabs(groupTitle);
|
|
384
|
+
return {opened, ...updated};
|
|
385
|
+
}
|
|
386
|
+
if (existing.tabs.length === 0) {
|
|
387
|
+
const opened = await openTab('about:blank', groupTitle, color, true, session);
|
|
388
|
+
const updated = await listGroupTabs(groupTitle);
|
|
389
|
+
return {opened, ...updated};
|
|
390
|
+
}
|
|
391
|
+
return existing;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
async function activateTab(tabId, groupTitle = DEFAULT_GROUP_TITLE, session = 'default') {
|
|
395
|
+
const target = await resolveGroupTab(tabId, groupTitle, session);
|
|
396
|
+
const tab = await chrome.tabs.update(target.tabId, {active: true});
|
|
397
|
+
if (tab?.windowId !== undefined) {
|
|
398
|
+
await chrome.windows.update(tab.windowId, {focused: true}).catch(() => {});
|
|
399
|
+
}
|
|
400
|
+
await ensureOverlay(tab.id, `Tab Group "${groupTitle}" • ${tab.title || ''}`);
|
|
401
|
+
return {
|
|
402
|
+
tabId: tab.id,
|
|
403
|
+
windowId: tab.windowId,
|
|
404
|
+
url: tab.url || '',
|
|
405
|
+
title: tab.title || '',
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async function closeTab(tabId, groupTitle = DEFAULT_GROUP_TITLE, session = 'default') {
|
|
410
|
+
const target = await resolveGroupTab(tabId, groupTitle, session);
|
|
411
|
+
await chrome.tabs.remove(target.tabId);
|
|
412
|
+
attachedDebugTabs.delete(target.tabId);
|
|
413
|
+
return {closedTabId: target.tabId};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function closeGroup(groupTitle = DEFAULT_GROUP_TITLE, session = 'default') {
|
|
417
|
+
const info = await listGroupTabs(groupTitle);
|
|
418
|
+
if (!info.groupId || info.tabs.length === 0) {
|
|
419
|
+
return {closedCount: 0};
|
|
420
|
+
}
|
|
421
|
+
// Never close tabs another Codex session is still using.
|
|
422
|
+
const ids = info.tabs.filter(t => !ownedByOther(t.tabId, session)).map(t => t.tabId);
|
|
423
|
+
if (!ids.length) return {closedCount: 0, kept: info.tabs.length};
|
|
424
|
+
for (const id of ids) attachedDebugTabs.delete(id);
|
|
425
|
+
await chrome.tabs.remove(ids);
|
|
426
|
+
const kept = info.tabs.length - ids.length;
|
|
427
|
+
return {closedCount: ids.length, ...(kept ? {kept} : {})};
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const dialogLog = new Map(); // tabId -> ["confirm: Leave site? (accepted)"]
|
|
431
|
+
|
|
432
|
+
chrome.debugger.onEvent.addListener((source, method, params) => {
|
|
433
|
+
if (method !== 'Page.javascriptDialogOpening') return;
|
|
434
|
+
const tabId = source.tabId;
|
|
435
|
+
// Agent tabs never get stuck on alert/confirm/prompt/beforeunload popups.
|
|
436
|
+
chrome.debugger
|
|
437
|
+
.sendCommand({tabId}, 'Page.handleJavaScriptDialog', {
|
|
438
|
+
accept: true,
|
|
439
|
+
promptText: params.defaultPrompt || '',
|
|
440
|
+
})
|
|
441
|
+
.catch(() => {});
|
|
442
|
+
const list = dialogLog.get(tabId) || [];
|
|
443
|
+
list.push(`${params.type}: ${String(params.message || '').slice(0, 120)} (accepted)`);
|
|
444
|
+
dialogLog.set(tabId, list.slice(-5));
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
async function injectStealthScripts(tabId) {
|
|
448
|
+
const code = `
|
|
449
|
+
try {
|
|
450
|
+
Object.defineProperty(Object.getPrototypeOf(navigator), 'webdriver', {
|
|
451
|
+
get: () => undefined,
|
|
452
|
+
configurable: true,
|
|
453
|
+
});
|
|
454
|
+
} catch (e) {
|
|
455
|
+
try {
|
|
456
|
+
Object.defineProperty(navigator, 'webdriver', {
|
|
457
|
+
get: () => undefined,
|
|
458
|
+
configurable: true,
|
|
459
|
+
});
|
|
460
|
+
} catch (e2) {}
|
|
461
|
+
}
|
|
462
|
+
`;
|
|
463
|
+
await chrome.debugger
|
|
464
|
+
.sendCommand({tabId}, 'Page.addScriptToEvaluateOnNewDocument', {source: code})
|
|
465
|
+
.catch(() => {});
|
|
466
|
+
await sendCdp(tabId, 'Runtime.evaluate', {expression: code}).catch(() => {});
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async function ensureDebugger(tabId) {
|
|
470
|
+
if (attachedDebugTabs.has(tabId)) return true;
|
|
471
|
+
try {
|
|
472
|
+
await chrome.debugger.attach({tabId}, '1.3');
|
|
473
|
+
attachedDebugTabs.add(tabId);
|
|
474
|
+
await chrome.debugger.sendCommand({tabId}, 'Page.enable').catch(() => {});
|
|
475
|
+
// Network + browser log capture for pilot_logs (cheap, buffered here).
|
|
476
|
+
// Runtime (console.*) is only enabled on the first console read, because
|
|
477
|
+
// some bot checks look for it.
|
|
478
|
+
await chrome.debugger.sendCommand({tabId}, 'Network.enable').catch(() => {});
|
|
479
|
+
await chrome.debugger.sendCommand({tabId}, 'Log.enable').catch(() => {});
|
|
480
|
+
// Focus emulation makes Chrome keep rendering this tab even when it is in the
|
|
481
|
+
// background or its window is covered, so clicks, screenshots and recordings
|
|
482
|
+
// keep working while the user does something else.
|
|
483
|
+
await chrome.debugger
|
|
484
|
+
.sendCommand({tabId}, 'Emulation.setFocusEmulationEnabled', {enabled: true})
|
|
485
|
+
.catch(() => {});
|
|
486
|
+
if (stealthMode) {
|
|
487
|
+
await injectStealthScripts(tabId);
|
|
488
|
+
}
|
|
489
|
+
return true;
|
|
490
|
+
} catch (err) {
|
|
491
|
+
if (String(err?.message || '').includes('Another debugger')) {
|
|
492
|
+
attachedDebugTabs.add(tabId);
|
|
493
|
+
return true;
|
|
494
|
+
}
|
|
495
|
+
return false;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
async function sendCdp(tabId, method, params = {}) {
|
|
500
|
+
return await chrome.debugger.sendCommand({tabId}, method, params);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const SNAPSHOT_FN = (limit, viewportOnly, query) => {
|
|
504
|
+
const D = window.__codexDom;
|
|
505
|
+
const SEL = D.INTERACTIVE;
|
|
506
|
+
const NATIVE = 'a, button, input, textarea, select, summary, [role], [contenteditable]';
|
|
507
|
+
const words = String(query || '')
|
|
508
|
+
.toLowerCase()
|
|
509
|
+
.split(/[\s,]+/)
|
|
510
|
+
.filter(w => w.length > 1);
|
|
511
|
+
let next = window.__codexNextUid || 1;
|
|
512
|
+
const vh = innerHeight;
|
|
513
|
+
const vw = innerWidth;
|
|
514
|
+
const labels = new Map();
|
|
515
|
+
const items = [];
|
|
516
|
+
let more = false;
|
|
517
|
+
for (const el of D.all(SEL)) {
|
|
518
|
+
const b = D.box(el);
|
|
519
|
+
if (b.width < 2 || b.height < 2) continue;
|
|
520
|
+
const st = (el.ownerDocument.defaultView || window).getComputedStyle(el);
|
|
521
|
+
if (st.visibility === 'hidden' || st.display === 'none') continue;
|
|
522
|
+
if (viewportOnly && !words.length && (b.y + b.height < 0 || b.y > vh || b.x + b.width < 0 || b.x > vw)) continue;
|
|
523
|
+
const tag = el.tagName.toLowerCase();
|
|
524
|
+
const role = el.getAttribute('role') || '';
|
|
525
|
+
const type = el.getAttribute('type') || '';
|
|
526
|
+
const lab = D.label(el).slice(0, 60);
|
|
527
|
+
if (!lab && !el.matches(NATIVE)) continue; // unlabeled tabindex divs are noise
|
|
528
|
+
// Skip a nested control that just repeats its parent (e.g. <a><button>Buy</button></a>).
|
|
529
|
+
let dup = false;
|
|
530
|
+
for (let p = el.parentElement, i = 0; p && i < 4; p = p.parentElement, i++) {
|
|
531
|
+
if (labels.has(p) && labels.get(p) === lab) {
|
|
532
|
+
dup = true;
|
|
533
|
+
break;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
if (dup) continue;
|
|
537
|
+
let href = tag === 'a' ? el.getAttribute('href') || '' : '';
|
|
538
|
+
if (href && !href.startsWith('javascript:')) {
|
|
539
|
+
try {
|
|
540
|
+
const u = new URL(href, location.href);
|
|
541
|
+
href = u.origin === location.origin ? u.pathname + u.search : u.href;
|
|
542
|
+
} catch {}
|
|
543
|
+
}
|
|
544
|
+
let val = '';
|
|
545
|
+
if (tag === 'select') val = el.selectedOptions?.[0]?.text?.trim() || '';
|
|
546
|
+
else if ((tag === 'input' && !/^(checkbox|radio|submit|button|reset|image|file)$/i.test(type)) || tag === 'textarea')
|
|
547
|
+
val = String(el.value || '');
|
|
548
|
+
const states = [];
|
|
549
|
+
if (/^(checkbox|radio)$/i.test(type)) states.push(el.checked ? 'checked' : 'unchecked');
|
|
550
|
+
else if (el.hasAttribute('aria-checked')) states.push(el.getAttribute('aria-checked') === 'true' ? 'checked' : 'unchecked');
|
|
551
|
+
if (el.disabled || el.getAttribute('aria-disabled') === 'true') states.push('disabled');
|
|
552
|
+
if (el.hasAttribute('aria-expanded')) states.push(el.getAttribute('aria-expanded') === 'true' ? 'expanded' : 'collapsed');
|
|
553
|
+
if (el.getAttribute('aria-selected') === 'true') states.push('selected');
|
|
554
|
+
let score = 0;
|
|
555
|
+
if (words.length) {
|
|
556
|
+
const hay = `${tag} ${type} ${role} ${lab} ${href} ${el.getAttribute('placeholder') || ''} ${el.getAttribute('name') || ''}`.toLowerCase();
|
|
557
|
+
score = words.filter(w => hay.includes(w)).length;
|
|
558
|
+
if (!score) continue;
|
|
559
|
+
}
|
|
560
|
+
// Keep the same uid for an element across snapshots so diffs stay small
|
|
561
|
+
// and earlier uids remain valid.
|
|
562
|
+
let uid = el.getAttribute('data-codex-uid');
|
|
563
|
+
if (!uid) {
|
|
564
|
+
uid = `e${next++}`;
|
|
565
|
+
el.setAttribute('data-codex-uid', uid);
|
|
566
|
+
}
|
|
567
|
+
labels.set(el, lab);
|
|
568
|
+
items.push({uid, tag, type, role, label: lab, href: href.slice(0, 80), value: val.slice(0, 40), state: states.join(','), score});
|
|
569
|
+
if (!words.length && items.length >= limit) {
|
|
570
|
+
more = true;
|
|
571
|
+
break;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
window.__codexNextUid = next;
|
|
575
|
+
let out = items;
|
|
576
|
+
if (words.length) out = items.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
577
|
+
return {
|
|
578
|
+
title: document.title,
|
|
579
|
+
url: location.href,
|
|
580
|
+
elements: out.map(({score, ...e}) => e),
|
|
581
|
+
...(words.length ? {matches: items.length} : {}),
|
|
582
|
+
...(more ? {more: true} : {}),
|
|
583
|
+
};
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
// Cross-origin iframes (payment fields, embedded forms) are separate documents
|
|
587
|
+
// the top page can't read, so they are scripted one frame at a time. Only
|
|
588
|
+
// frames directly inside the page are handled.
|
|
589
|
+
async function crossOriginFrames(tabId) {
|
|
590
|
+
const res = await chrome.scripting
|
|
591
|
+
.executeScript({
|
|
592
|
+
target: {tabId, allFrames: true},
|
|
593
|
+
func: () => {
|
|
594
|
+
if (window === top) return null;
|
|
595
|
+
try {
|
|
596
|
+
void parent.document;
|
|
597
|
+
return null; // same-origin: already covered by the top page walk
|
|
598
|
+
} catch {}
|
|
599
|
+
if (parent !== top) return null;
|
|
600
|
+
return {href: location.href, title: document.title, w: innerWidth, h: innerHeight};
|
|
601
|
+
},
|
|
602
|
+
})
|
|
603
|
+
.catch(() => []);
|
|
604
|
+
return res
|
|
605
|
+
.filter(r => r.result && r.result.w > 4 && r.result.h > 4)
|
|
606
|
+
.map(r => ({frameId: r.frameId, ...r.result}))
|
|
607
|
+
.slice(0, 8);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
async function frameOffset(tabId, fr) {
|
|
611
|
+
return await execIn(
|
|
612
|
+
tabId,
|
|
613
|
+
(href, w, h) => {
|
|
614
|
+
const D = window.__codexDom;
|
|
615
|
+
let origin = '';
|
|
616
|
+
try {
|
|
617
|
+
origin = new URL(href).origin;
|
|
618
|
+
} catch {}
|
|
619
|
+
let best = null;
|
|
620
|
+
let bestScore = -1;
|
|
621
|
+
for (const f of D.all('iframe, frame')) {
|
|
622
|
+
let same = false;
|
|
623
|
+
try {
|
|
624
|
+
same = Boolean(f.contentDocument);
|
|
625
|
+
} catch {}
|
|
626
|
+
if (same) continue;
|
|
627
|
+
let score = 0;
|
|
628
|
+
try {
|
|
629
|
+
const src = new URL(f.src, location.href);
|
|
630
|
+
if (src.origin === origin) score += 2;
|
|
631
|
+
if (href.startsWith(src.href)) score += 1;
|
|
632
|
+
} catch {}
|
|
633
|
+
if (Math.abs(f.clientWidth - w) <= 1 && Math.abs(f.clientHeight - h) <= 1) score += 2;
|
|
634
|
+
if (score > bestScore) {
|
|
635
|
+
bestScore = score;
|
|
636
|
+
best = f;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
if (!best) return null;
|
|
640
|
+
const b = D.box(best);
|
|
641
|
+
return {x: b.x + best.clientLeft, y: b.y + best.clientTop};
|
|
642
|
+
},
|
|
643
|
+
[fr.href, fr.w, fr.h],
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
async function frameSnapshot(tabId, fr, limit, query) {
|
|
648
|
+
await chrome.scripting.executeScript({target: {tabId, frameIds: [fr.frameId]}, files: ['dom.js']}).catch(() => {});
|
|
649
|
+
const res = await chrome.scripting
|
|
650
|
+
.executeScript({target: {tabId, frameIds: [fr.frameId]}, func: SNAPSHOT_FN, args: [limit, false, query || '']})
|
|
651
|
+
.catch(() => null);
|
|
652
|
+
const r = res?.[0]?.result;
|
|
653
|
+
if (!r) return null;
|
|
654
|
+
r.elements = r.elements.map(e => ({...e, uid: `f${fr.frameId}:${e.uid}`}));
|
|
655
|
+
return r;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
const hostOf = href => {
|
|
659
|
+
try {
|
|
660
|
+
return new URL(href).host;
|
|
661
|
+
} catch {
|
|
662
|
+
return href.slice(0, 40);
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
async function buildPageSnapshot(tabId, maxElements = 80, viewportOnly = false, query = '', frame = null) {
|
|
667
|
+
await ensureOverlay(tabId);
|
|
668
|
+
for (let i = 0; i < 10; i++) {
|
|
669
|
+
const pending = await execIn(tabId, () => window.__codexDom?.framesPending() || 0).catch(() => 0);
|
|
670
|
+
if (!pending) break;
|
|
671
|
+
await sleep(100);
|
|
672
|
+
}
|
|
673
|
+
if (frame) {
|
|
674
|
+
// Controls of one cross-origin iframe (uid "f7" from a snapshot line).
|
|
675
|
+
const id = Number(String(frame).replace(/^f/, ''));
|
|
676
|
+
const fr = (await crossOriginFrames(tabId)).find(f => f.frameId === id);
|
|
677
|
+
if (!fr) throw new Error(`Frame ${frame} not found (take a new snapshot).`);
|
|
678
|
+
const r = await frameSnapshot(tabId, fr, maxElements, query);
|
|
679
|
+
if (!r) throw new Error(`Frame ${frame} can't be scripted.`);
|
|
680
|
+
return {...r, title: `[frame ${hostOf(fr.href)}] ${r.title}`};
|
|
681
|
+
}
|
|
682
|
+
const [{result}] = await chrome.scripting.executeScript({
|
|
683
|
+
target: {tabId},
|
|
684
|
+
func: SNAPSHOT_FN,
|
|
685
|
+
args: [maxElements, Boolean(viewportOnly), query || ''],
|
|
686
|
+
});
|
|
687
|
+
// One summary line per cross-origin iframe (keeps snapshots short); a query
|
|
688
|
+
// also searches inside them.
|
|
689
|
+
for (const fr of await crossOriginFrames(tabId)) {
|
|
690
|
+
const r = await frameSnapshot(tabId, fr, query ? maxElements : 200, query);
|
|
691
|
+
if (!r || !result) continue;
|
|
692
|
+
if (query) {
|
|
693
|
+
result.elements.push(...r.elements);
|
|
694
|
+
result.matches = (result.matches || 0) + (r.matches || 0);
|
|
695
|
+
} else if (r.elements.length) {
|
|
696
|
+
result.elements.push({
|
|
697
|
+
uid: `f${fr.frameId}`,
|
|
698
|
+
tag: 'iframe',
|
|
699
|
+
type: '',
|
|
700
|
+
role: '',
|
|
701
|
+
label: `${hostOf(fr.href)}${fr.title ? ` - ${fr.title.slice(0, 30)}` : ''}`,
|
|
702
|
+
href: '',
|
|
703
|
+
value: '',
|
|
704
|
+
state: `${r.elements.length}${r.more ? '+' : ''} controls; pilot_snapshot frame=f${fr.frameId}`,
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const dialogs = dialogLog.get(tabId);
|
|
709
|
+
if (dialogs?.length && result) {
|
|
710
|
+
result.dialogs = dialogs;
|
|
711
|
+
dialogLog.delete(tabId);
|
|
712
|
+
}
|
|
713
|
+
return result;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const LOCATE_FN = async (u, sel, txt, px, py, lbl, doClickAnim, attrName, forInput, instant) => {
|
|
717
|
+
const D = window.__codexDom;
|
|
718
|
+
window.__codexInstant = instant;
|
|
719
|
+
let el = null;
|
|
720
|
+
let point = null;
|
|
721
|
+
if (u) el = D.byUid(u);
|
|
722
|
+
if (!el && sel) {
|
|
723
|
+
try {
|
|
724
|
+
el = D.one(sel);
|
|
725
|
+
} catch {}
|
|
726
|
+
}
|
|
727
|
+
if (!el && txt) {
|
|
728
|
+
const needle = txt.trim().toLowerCase();
|
|
729
|
+
const list = D.all(`${D.INTERACTIVE}, label, [aria-label], [title]`).filter(n => {
|
|
730
|
+
const b = D.box(n);
|
|
731
|
+
return b.width > 1 && b.height > 1;
|
|
732
|
+
});
|
|
733
|
+
const name = n => D.label(n).toLowerCase();
|
|
734
|
+
el = list.find(n => name(n) === needle) || list.find(n => name(n).includes(needle)) || null;
|
|
735
|
+
}
|
|
736
|
+
if (el && forInput && el.tagName === 'LABEL' && el.control) el = el.control;
|
|
737
|
+
if (!el && typeof px === 'number' && typeof py === 'number') {
|
|
738
|
+
point = {x: px, y: py};
|
|
739
|
+
el = D.atPoint(px, py);
|
|
740
|
+
}
|
|
741
|
+
if (!el && !point) {
|
|
742
|
+
// Offer the closest controls so the model can retry without a new snapshot.
|
|
743
|
+
const words = String(txt || sel || '').toLowerCase().split(/[^a-z0-9]+/).filter(w => w.length > 1);
|
|
744
|
+
let next = window.__codexNextUid || 1;
|
|
745
|
+
const scored = [];
|
|
746
|
+
for (const n of D.all(D.INTERACTIVE)) {
|
|
747
|
+
const b = D.box(n);
|
|
748
|
+
if (b.width < 2 || b.height < 2) continue;
|
|
749
|
+
const name = D.label(n).slice(0, 50);
|
|
750
|
+
if (!name) continue;
|
|
751
|
+
const lower = name.toLowerCase();
|
|
752
|
+
const score = words.filter(w => lower.includes(w)).length;
|
|
753
|
+
if (words.length && !score) continue;
|
|
754
|
+
let id = n.getAttribute('data-codex-uid');
|
|
755
|
+
if (!id) {
|
|
756
|
+
id = `e${next++}`;
|
|
757
|
+
n.setAttribute('data-codex-uid', id);
|
|
758
|
+
}
|
|
759
|
+
scored.push({score, line: `[${id}] ${n.getAttribute('role') || n.tagName.toLowerCase()} "${name}"`});
|
|
760
|
+
}
|
|
761
|
+
window.__codexNextUid = next;
|
|
762
|
+
scored.sort((a, b) => b.score - a.score);
|
|
763
|
+
return {found: false, near: scored.slice(0, 5).map(x => x.line), stale: Boolean(u)};
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
if (el && attrName) {
|
|
767
|
+
D.all(`[${attrName}]`).forEach(n => n.removeAttribute(attrName));
|
|
768
|
+
el.setAttribute(attrName, '1');
|
|
769
|
+
}
|
|
770
|
+
let scrolled = false;
|
|
771
|
+
if (el && !point) {
|
|
772
|
+
const pre = D.box(el);
|
|
773
|
+
if (pre.y < 0 || pre.y + pre.height > innerHeight || pre.x < 0 || pre.x + pre.width > innerWidth) {
|
|
774
|
+
el.scrollIntoView({behavior: 'instant', block: 'center', inline: 'center'});
|
|
775
|
+
scrolled = true;
|
|
776
|
+
// No in-page timer here: background tabs throttle them to ~1s, and
|
|
777
|
+
// the instant scroll has already updated layout.
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
const b = point
|
|
781
|
+
? {x: point.x, y: point.y, width: 0, height: 0, cx: point.x, cy: point.y}
|
|
782
|
+
: D.box(el);
|
|
783
|
+
const tag = el ? el.tagName.toLowerCase() : '';
|
|
784
|
+
const type = el?.type || '';
|
|
785
|
+
const role = el?.getAttribute?.('role') || '';
|
|
786
|
+
const kind = !el
|
|
787
|
+
? 'other'
|
|
788
|
+
: tag === 'select'
|
|
789
|
+
? 'select'
|
|
790
|
+
: (tag === 'input' && /^(checkbox|radio)$/i.test(type)) || /^(checkbox|radio|switch|menuitemcheckbox)$/.test(role)
|
|
791
|
+
? 'check'
|
|
792
|
+
: tag === 'textarea' || (tag === 'input' && !/^(button|submit|reset|image|file|range|color)$/i.test(type))
|
|
793
|
+
? 'text'
|
|
794
|
+
: el.isContentEditable
|
|
795
|
+
? 'editable'
|
|
796
|
+
: 'other';
|
|
797
|
+
const elLabel = (el ? D.label(el) : '').slice(0, 40) || tag || `${px},${py}`;
|
|
798
|
+
const textLabel = lbl || elLabel;
|
|
799
|
+
if (window.__codexPilotOverlay) {
|
|
800
|
+
const rect = point ? null : b;
|
|
801
|
+
if (doClickAnim) await window.__codexPilotOverlay.clickAt(b.cx, b.cy, textLabel, rect);
|
|
802
|
+
else await window.__codexPilotOverlay.moveTo(b.cx, b.cy, textLabel, 200, rect);
|
|
803
|
+
}
|
|
804
|
+
return {
|
|
805
|
+
found: true,
|
|
806
|
+
rect: b,
|
|
807
|
+
tag,
|
|
808
|
+
type,
|
|
809
|
+
kind,
|
|
810
|
+
scrolled,
|
|
811
|
+
label: elLabel,
|
|
812
|
+
options: tag === 'select' ? Array.from(el.options).slice(0, 40).map(o => o.text.trim()) : undefined,
|
|
813
|
+
checked:
|
|
814
|
+
kind === 'check' ? ('checked' in el ? el.checked : el.getAttribute('aria-checked') === 'true') : undefined,
|
|
815
|
+
// Likely to load a new page: a real link or a form submit button.
|
|
816
|
+
nav: (() => {
|
|
817
|
+
const a = el.closest?.('a[href]');
|
|
818
|
+
if (a) {
|
|
819
|
+
const h = a.getAttribute('href') || '';
|
|
820
|
+
return !h.startsWith('#') && !/^javascript:/i.test(h) && a.target !== '_blank' && !a.hasAttribute('download');
|
|
821
|
+
}
|
|
822
|
+
const btn = el.closest?.('button, input[type="submit"], input[type="image"]');
|
|
823
|
+
return Boolean(btn?.form && (btn.type || 'submit') === 'submit');
|
|
824
|
+
})(),
|
|
825
|
+
};
|
|
826
|
+
};
|
|
827
|
+
|
|
828
|
+
function locateArgs({uid, selector, text, x, y, label, clickAnim, markAttr, forInput}, instant) {
|
|
829
|
+
return [
|
|
830
|
+
uid || null,
|
|
831
|
+
selector || null,
|
|
832
|
+
text || null,
|
|
833
|
+
typeof x === 'number' ? x : null,
|
|
834
|
+
typeof y === 'number' ? y : null,
|
|
835
|
+
label || null,
|
|
836
|
+
Boolean(clickAnim),
|
|
837
|
+
markAttr || null,
|
|
838
|
+
Boolean(forInput),
|
|
839
|
+
instant,
|
|
840
|
+
];
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
async function locateInFrame(tabId, fr, opts, instant) {
|
|
844
|
+
await chrome.scripting.executeScript({target: {tabId, frameIds: [fr.frameId]}, files: ['dom.js']}).catch(() => {});
|
|
845
|
+
const res = await chrome.scripting
|
|
846
|
+
.executeScript({target: {tabId, frameIds: [fr.frameId]}, func: LOCATE_FN, args: locateArgs(opts, true)})
|
|
847
|
+
.catch(() => null);
|
|
848
|
+
const result = res?.[0]?.result;
|
|
849
|
+
if (!result?.found) return null;
|
|
850
|
+
const off = await frameOffset(tabId, fr);
|
|
851
|
+
if (!off) return null;
|
|
852
|
+
const r = result.rect;
|
|
853
|
+
result.rect = {x: r.x + off.x, y: r.y + off.y, width: r.width, height: r.height, cx: r.cx + off.x, cy: r.cy + off.y};
|
|
854
|
+
result.frameId = fr.frameId;
|
|
855
|
+
if (!instant) {
|
|
856
|
+
await execIn(tabId, (x, y, l) => window.__codexPilotOverlay?.moveTo(x, y, l, 200), [result.rect.cx, result.rect.cy, result.label]).catch(
|
|
857
|
+
() => {},
|
|
858
|
+
);
|
|
859
|
+
}
|
|
860
|
+
return result;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
async function locateAndAnimate(tabId, opts) {
|
|
864
|
+
const instant = backgroundMode && !recordings.has(tabId);
|
|
865
|
+
const m = /^f(\d+):(e\d+)$/.exec(opts.uid || '');
|
|
866
|
+
if (m) {
|
|
867
|
+
const fr = (await crossOriginFrames(tabId)).find(f => f.frameId === Number(m[1]));
|
|
868
|
+
const r = fr && (await locateInFrame(tabId, fr, {...opts, uid: m[2]}, instant));
|
|
869
|
+
if (!r) throw new Error(`Not found: uid ${opts.uid} (the frame changed; take a new snapshot).`);
|
|
870
|
+
return r;
|
|
871
|
+
}
|
|
872
|
+
await ensureOverlay(tabId);
|
|
873
|
+
const [{result}] = await chrome.scripting.executeScript({
|
|
874
|
+
target: {tabId},
|
|
875
|
+
func: LOCATE_FN,
|
|
876
|
+
args: locateArgs(opts, instant),
|
|
877
|
+
});
|
|
878
|
+
if (!result?.found && !opts.uid && (opts.text || opts.selector)) {
|
|
879
|
+
// Not on the page itself: try cross-origin iframes (card fields, embedded forms).
|
|
880
|
+
for (const fr of await crossOriginFrames(tabId)) {
|
|
881
|
+
const r = await locateInFrame(tabId, fr, opts, instant);
|
|
882
|
+
if (r) return r;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
if (!result?.found) {
|
|
886
|
+
const {uid, selector, text} = opts;
|
|
887
|
+
const what = uid ? `uid ${uid}` : selector ? `selector ${selector}` : `text "${text}"`;
|
|
888
|
+
const hint = uid ? ' (uids reset when the page changes)' : '';
|
|
889
|
+
const near = result?.near?.length ? ` Closest: ${result.near.join(' | ')}` : ' Run pilot_snapshot.';
|
|
890
|
+
throw new Error(`Not found: ${what}${hint}.${near}`);
|
|
891
|
+
}
|
|
892
|
+
return result;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// ---------------------------------------------------------------------------
|
|
896
|
+
// Trusted input through CDP (works on background tabs, never moves the user's
|
|
897
|
+
// real mouse or keyboard).
|
|
898
|
+
// ---------------------------------------------------------------------------
|
|
899
|
+
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
900
|
+
const MOD_BITS = {alt: 1, ctrl: 2, control: 2, meta: 4, cmd: 4, command: 4, win: 4, windows: 4, shift: 8};
|
|
901
|
+
function modBits(mods) {
|
|
902
|
+
return String(mods || '')
|
|
903
|
+
.toLowerCase()
|
|
904
|
+
.split('+')
|
|
905
|
+
.reduce((m, k) => m | (MOD_BITS[k.trim()] || 0), 0);
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
function randomBetween(min, max) {
|
|
909
|
+
return min + Math.random() * (max - min);
|
|
910
|
+
}
|
|
911
|
+
function randomInt(min, max) {
|
|
912
|
+
return Math.floor(randomBetween(min, max + 1));
|
|
913
|
+
}
|
|
914
|
+
function randomGaussian(mean, stdev) {
|
|
915
|
+
const u = 1 - Math.random();
|
|
916
|
+
const v = Math.random();
|
|
917
|
+
const z = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
|
|
918
|
+
return mean + z * stdev;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
const hoverActive = new Set(); // tabs whose pointer was left over a hover target
|
|
922
|
+
|
|
923
|
+
async function stealthMouseMove(tabId, targetX, targetY) {
|
|
924
|
+
const cur = cursorPositions.get(tabId) || {
|
|
925
|
+
x: Math.max(100, Math.round(targetX - randomBetween(120, 220))),
|
|
926
|
+
y: Math.max(100, Math.round(targetY - randomBetween(80, 180))),
|
|
927
|
+
};
|
|
928
|
+
const startX = cur.x;
|
|
929
|
+
const startY = cur.y;
|
|
930
|
+
const dx = targetX - startX;
|
|
931
|
+
const dy = targetY - startY;
|
|
932
|
+
const dist = Math.hypot(dx, dy);
|
|
933
|
+
|
|
934
|
+
if (dist < 4) {
|
|
935
|
+
await sendCdp(tabId, 'Input.dispatchMouseEvent', {type: 'mouseMoved', x: Math.round(targetX), y: Math.round(targetY)});
|
|
936
|
+
cursorPositions.set(tabId, {x: targetX, y: targetY});
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
const steps = Math.min(20, Math.max(5, Math.floor(dist / 25)));
|
|
941
|
+
const curveDeviation = (Math.random() - 0.5) * Math.min(dist * 0.35, 70);
|
|
942
|
+
const midX = (startX + targetX) / 2 - (dy / dist) * curveDeviation;
|
|
943
|
+
const midY = (startY + targetY) / 2 + (dx / dist) * curveDeviation;
|
|
944
|
+
|
|
945
|
+
for (let i = 1; i <= steps; i++) {
|
|
946
|
+
const t = i / steps;
|
|
947
|
+
const ease = 1 - Math.pow(1 - t, 3);
|
|
948
|
+
const inv = 1 - ease;
|
|
949
|
+
let x = inv * inv * startX + 2 * inv * ease * midX + ease * ease * targetX;
|
|
950
|
+
let y = inv * inv * startY + 2 * inv * ease * midY + ease * ease * targetY;
|
|
951
|
+
|
|
952
|
+
if (i < steps) {
|
|
953
|
+
x += (Math.random() - 0.5) * 1.5;
|
|
954
|
+
y += (Math.random() - 0.5) * 1.5;
|
|
955
|
+
}
|
|
956
|
+
x = Math.round(x);
|
|
957
|
+
y = Math.round(y);
|
|
958
|
+
|
|
959
|
+
await sendCdp(tabId, 'Input.dispatchMouseEvent', {type: 'mouseMoved', x, y});
|
|
960
|
+
await sleep(randomInt(6, 15));
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
cursorPositions.set(tabId, {x: targetX, y: targetY});
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
async function mouseClick(tabId, x, y, {button = 'left', clicks = 1, modifiers = 0, stealth = false} = {}) {
|
|
967
|
+
const isStealth = Boolean(stealth || stealthMode);
|
|
968
|
+
if (isStealth) {
|
|
969
|
+
await withFrames(tabId, async () => {
|
|
970
|
+
await stealthMouseMove(tabId, x, y);
|
|
971
|
+
});
|
|
972
|
+
await sleep(randomInt(35, 75));
|
|
973
|
+
} else if (!backgroundMode || pumpDepth.has(tabId) || recordings.has(tabId)) {
|
|
974
|
+
await sendCdp(tabId, 'Input.dispatchMouseEvent', {type: 'mouseMoved', x, y, modifiers});
|
|
975
|
+
cursorPositions.set(tabId, {x, y});
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
for (let n = 1; n <= clicks; n++) {
|
|
979
|
+
await sendCdp(tabId, 'Input.dispatchMouseEvent', {type: 'mousePressed', x, y, button, clickCount: n, modifiers});
|
|
980
|
+
if (isStealth) {
|
|
981
|
+
await sleep(Math.max(35, Math.min(110, Math.round(randomGaussian(65, 18)))));
|
|
982
|
+
}
|
|
983
|
+
await sendCdp(tabId, 'Input.dispatchMouseEvent', {type: 'mouseReleased', x, y, button, clickCount: n, modifiers});
|
|
984
|
+
if (isStealth && n < clicks) {
|
|
985
|
+
await sleep(Math.max(50, Math.min(130, Math.round(randomGaussian(80, 20)))));
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
if (isStealth) {
|
|
990
|
+
await sleep(randomInt(30, 60));
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
const KEY_DEFS = {
|
|
995
|
+
enter: ['Enter', 'Enter', 13, '\r'],
|
|
996
|
+
return: ['Enter', 'Enter', 13, '\r'],
|
|
997
|
+
tab: ['Tab', 'Tab', 9],
|
|
998
|
+
escape: ['Escape', 'Escape', 27],
|
|
999
|
+
esc: ['Escape', 'Escape', 27],
|
|
1000
|
+
backspace: ['Backspace', 'Backspace', 8],
|
|
1001
|
+
delete: ['Delete', 'Delete', 46],
|
|
1002
|
+
space: [' ', 'Space', 32, ' '],
|
|
1003
|
+
arrowup: ['ArrowUp', 'ArrowUp', 38],
|
|
1004
|
+
arrowdown: ['ArrowDown', 'ArrowDown', 40],
|
|
1005
|
+
arrowleft: ['ArrowLeft', 'ArrowLeft', 37],
|
|
1006
|
+
arrowright: ['ArrowRight', 'ArrowRight', 39],
|
|
1007
|
+
up: ['ArrowUp', 'ArrowUp', 38],
|
|
1008
|
+
down: ['ArrowDown', 'ArrowDown', 40],
|
|
1009
|
+
left: ['ArrowLeft', 'ArrowLeft', 37],
|
|
1010
|
+
right: ['ArrowRight', 'ArrowRight', 39],
|
|
1011
|
+
home: ['Home', 'Home', 36],
|
|
1012
|
+
end: ['End', 'End', 35],
|
|
1013
|
+
pageup: ['PageUp', 'PageUp', 33],
|
|
1014
|
+
pagedown: ['PageDown', 'PageDown', 34],
|
|
1015
|
+
insert: ['Insert', 'Insert', 45],
|
|
1016
|
+
};
|
|
1017
|
+
const EDIT_COMMANDS = {a: 'selectAll', c: 'copy', x: 'cut', v: 'paste', z: 'undo', y: 'redo'};
|
|
1018
|
+
|
|
1019
|
+
function keyDef(name) {
|
|
1020
|
+
const k = name.toLowerCase();
|
|
1021
|
+
if (KEY_DEFS[k]) return KEY_DEFS[k];
|
|
1022
|
+
if (/^f([1-9]|1[0-2])$/.test(k)) return [k.toUpperCase(), k.toUpperCase(), 111 + Number(k.slice(1))];
|
|
1023
|
+
if (name.length === 1) {
|
|
1024
|
+
const up = name.toUpperCase();
|
|
1025
|
+
const code = /[a-z]/i.test(name) ? `Key${up}` : /\d/.test(name) ? `Digit${name}` : '';
|
|
1026
|
+
return [name, code, /[a-z0-9]/i.test(name) ? up.charCodeAt(0) : 0, name];
|
|
1027
|
+
}
|
|
1028
|
+
return [name, name, 0];
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
async function pressCombo(tabId, combo, {stealth = false} = {}) {
|
|
1032
|
+
const isStealth = Boolean(stealth || stealthMode);
|
|
1033
|
+
const parts = combo.split('+').filter(Boolean);
|
|
1034
|
+
const main = parts.pop() || combo;
|
|
1035
|
+
const modifiers = modBits(parts.join('+'));
|
|
1036
|
+
let [key, code, keyCode, txt] = keyDef(main);
|
|
1037
|
+
if (modifiers & 8 && key.length === 1) {
|
|
1038
|
+
key = key.toUpperCase();
|
|
1039
|
+
if (txt) txt = txt.toUpperCase();
|
|
1040
|
+
}
|
|
1041
|
+
const text = modifiers & 7 ? undefined : txt; // ctrl/alt/meta combos type nothing
|
|
1042
|
+
const cmd = modifiers & 6 ? EDIT_COMMANDS[main.toLowerCase()] : undefined;
|
|
1043
|
+
const base = {key, code, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode, modifiers};
|
|
1044
|
+
const down = {type: text ? 'keyDown' : 'rawKeyDown', ...base, ...(text ? {text, unmodifiedText: text} : {})};
|
|
1045
|
+
try {
|
|
1046
|
+
await sendCdp(tabId, 'Input.dispatchKeyEvent', {...down, ...(cmd ? {commands: [cmd]} : {})});
|
|
1047
|
+
} catch {
|
|
1048
|
+
await sendCdp(tabId, 'Input.dispatchKeyEvent', down);
|
|
1049
|
+
}
|
|
1050
|
+
if (isStealth) {
|
|
1051
|
+
await sleep(Math.max(30, Math.min(90, Math.round(randomGaussian(50, 12)))));
|
|
1052
|
+
}
|
|
1053
|
+
await sendCdp(tabId, 'Input.dispatchKeyEvent', {type: 'keyUp', ...base});
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
async function pressKeys(tabId, keys, repeat = 1, {stealth = false} = {}) {
|
|
1057
|
+
const isStealth = Boolean(stealth || stealthMode);
|
|
1058
|
+
const combos = String(keys).trim().split(/\s+/).filter(Boolean);
|
|
1059
|
+
for (let i = 0; i < repeat; i++) {
|
|
1060
|
+
for (const c of combos) {
|
|
1061
|
+
await pressCombo(tabId, c, {stealth: isStealth});
|
|
1062
|
+
if (isStealth) await sleep(randomInt(35, 75));
|
|
1063
|
+
}
|
|
1064
|
+
if (isStealth && i < repeat - 1) await sleep(randomInt(60, 120));
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
async function typeText(tabId, value, perKey, {stealth = false} = {}) {
|
|
1069
|
+
const isStealth = Boolean(stealth || stealthMode);
|
|
1070
|
+
if (!perKey && !isStealth) {
|
|
1071
|
+
await sendCdp(tabId, 'Input.insertText', {text: value});
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
for (let i = 0; i < value.length; i++) {
|
|
1075
|
+
const ch = value[i];
|
|
1076
|
+
if (ch === '\n') {
|
|
1077
|
+
await pressCombo(tabId, 'Enter', {stealth: isStealth});
|
|
1078
|
+
} else {
|
|
1079
|
+
await sendCdp(tabId, 'Input.dispatchKeyEvent', {type: 'keyDown', key: ch, text: ch, unmodifiedText: ch});
|
|
1080
|
+
if (isStealth) {
|
|
1081
|
+
const dwell = Math.max(30, Math.min(85, Math.round(randomGaussian(50, 12))));
|
|
1082
|
+
await sleep(dwell);
|
|
1083
|
+
}
|
|
1084
|
+
await sendCdp(tabId, 'Input.dispatchKeyEvent', {type: 'keyUp', key: ch});
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
if (isStealth && i < value.length - 1) {
|
|
1088
|
+
let flight = Math.max(40, Math.min(180, Math.round(randomGaussian(85, 25))));
|
|
1089
|
+
if (ch === ' ') {
|
|
1090
|
+
flight += randomInt(35, 90);
|
|
1091
|
+
} else if (/[.,!?;:]/.test(ch)) {
|
|
1092
|
+
flight += randomInt(50, 130);
|
|
1093
|
+
} else if (/[A-Z]/.test(ch)) {
|
|
1094
|
+
flight += randomInt(20, 50);
|
|
1095
|
+
}
|
|
1096
|
+
if (Math.random() < 0.04) {
|
|
1097
|
+
flight += randomInt(100, 200);
|
|
1098
|
+
}
|
|
1099
|
+
await sleep(flight);
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
function normalizeUrl(url) {
|
|
1105
|
+
const u = String(url || '').trim();
|
|
1106
|
+
if (!u || /^[a-z][a-z0-9+.-]*:/i.test(u)) return u || 'about:blank';
|
|
1107
|
+
return `https://${u}`;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// Main-frame navigation state per tab, fed by CDP page events, so actions
|
|
1111
|
+
// can wait for the page they caused instead of guessing with sleeps.
|
|
1112
|
+
const nav = new Map(); // tabId -> {started, committed, stopped, same}
|
|
1113
|
+
const mainFrame = new Map(); // tabId -> frameId
|
|
1114
|
+
const navOf = tabId => {
|
|
1115
|
+
if (!nav.has(tabId)) nav.set(tabId, {});
|
|
1116
|
+
return nav.get(tabId);
|
|
1117
|
+
};
|
|
1118
|
+
function resetNav(tabId) {
|
|
1119
|
+
nav.set(tabId, {});
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
// After an action: if it started a main-frame navigation, wait for the new
|
|
1123
|
+
// page; otherwise return after a short look. likelyNav widens the look for
|
|
1124
|
+
// links and submit buttons, whose navigation can start late on hidden tabs.
|
|
1125
|
+
async function settle(tabId, likelyNav = false) {
|
|
1126
|
+
const lookUntil = Date.now() + (likelyNav ? 500 : 60);
|
|
1127
|
+
for (;;) {
|
|
1128
|
+
await sleep(25);
|
|
1129
|
+
const n = navOf(tabId);
|
|
1130
|
+
if (n.started || n.committed) break;
|
|
1131
|
+
if (Date.now() >= lookUntil) return;
|
|
1132
|
+
}
|
|
1133
|
+
const end = Date.now() + 10000;
|
|
1134
|
+
const softEnd = Date.now() + 1500;
|
|
1135
|
+
for (;;) {
|
|
1136
|
+
const n = navOf(tabId);
|
|
1137
|
+
if (n.committed) {
|
|
1138
|
+
await waitForTabReady(tabId, Math.max(0, end - Date.now()));
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
// Same-document change, download, or a cancelled navigation.
|
|
1142
|
+
if (n.same || n.stopped) return;
|
|
1143
|
+
if (Date.now() > softEnd) {
|
|
1144
|
+
const t = await chrome.tabs.get(tabId).catch(() => null);
|
|
1145
|
+
if (t?.status !== 'loading') return;
|
|
1146
|
+
}
|
|
1147
|
+
if (Date.now() > end) return;
|
|
1148
|
+
await sleep(30);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
// ---------------------------------------------------------------------------
|
|
1153
|
+
// Console + network capture (pilot_logs), drag data, cleared when the tab
|
|
1154
|
+
// navigates to another site.
|
|
1155
|
+
// ---------------------------------------------------------------------------
|
|
1156
|
+
const consoleLog = new Map(); // tabId -> [{level, text}]
|
|
1157
|
+
const netLog = new Map(); // tabId -> Map(requestId -> entry)
|
|
1158
|
+
const consoleOn = new Set();
|
|
1159
|
+
const dragData = new Map();
|
|
1160
|
+
const tabOrigin = new Map();
|
|
1161
|
+
|
|
1162
|
+
function pushConsole(tabId, level, text) {
|
|
1163
|
+
const list = consoleLog.get(tabId) || [];
|
|
1164
|
+
list.push({level, text: String(text).slice(0, 400)});
|
|
1165
|
+
if (list.length > 400) list.splice(0, list.length - 400);
|
|
1166
|
+
consoleLog.set(tabId, list);
|
|
1167
|
+
}
|
|
1168
|
+
function netOf(tabId) {
|
|
1169
|
+
let m = netLog.get(tabId);
|
|
1170
|
+
if (!m) netLog.set(tabId, (m = new Map()));
|
|
1171
|
+
return m;
|
|
1172
|
+
}
|
|
1173
|
+
const argText = a =>
|
|
1174
|
+
a.type === 'string' ? a.value : a.value !== undefined ? JSON.stringify(a.value) : a.description || a.type;
|
|
1175
|
+
|
|
1176
|
+
chrome.debugger.onEvent.addListener((source, method, p) => {
|
|
1177
|
+
const tabId = source.tabId;
|
|
1178
|
+
if (tabId === undefined) return;
|
|
1179
|
+
switch (method) {
|
|
1180
|
+
case 'Input.dragIntercepted':
|
|
1181
|
+
dragData.set(tabId, p.data);
|
|
1182
|
+
break;
|
|
1183
|
+
case 'Runtime.consoleAPICalled':
|
|
1184
|
+
pushConsole(tabId, p.type, (p.args || []).map(argText).join(' '));
|
|
1185
|
+
break;
|
|
1186
|
+
case 'Runtime.exceptionThrown': {
|
|
1187
|
+
const d = p.exceptionDetails || {};
|
|
1188
|
+
pushConsole(tabId, 'exception', d.exception?.description || d.text);
|
|
1189
|
+
break;
|
|
1190
|
+
}
|
|
1191
|
+
case 'Log.entryAdded':
|
|
1192
|
+
pushConsole(tabId, p.entry.level, `${p.entry.text}${p.entry.url ? ` (${p.entry.url})` : ''}`);
|
|
1193
|
+
break;
|
|
1194
|
+
case 'Network.requestWillBeSent': {
|
|
1195
|
+
const m = netOf(tabId);
|
|
1196
|
+
m.set(p.requestId, {method: p.request.method, url: p.request.url, type: (p.type || '').toLowerCase(), status: 'pending'});
|
|
1197
|
+
if (m.size > 500) m.delete(m.keys().next().value);
|
|
1198
|
+
break;
|
|
1199
|
+
}
|
|
1200
|
+
case 'Network.responseReceived': {
|
|
1201
|
+
const e = netOf(tabId).get(p.requestId);
|
|
1202
|
+
if (e) {
|
|
1203
|
+
e.status = p.response.status;
|
|
1204
|
+
e.mime = p.response.mimeType;
|
|
1205
|
+
}
|
|
1206
|
+
break;
|
|
1207
|
+
}
|
|
1208
|
+
case 'Network.loadingFinished': {
|
|
1209
|
+
const e = netOf(tabId).get(p.requestId);
|
|
1210
|
+
if (e) e.size = p.encodedDataLength;
|
|
1211
|
+
break;
|
|
1212
|
+
}
|
|
1213
|
+
case 'Network.loadingFailed': {
|
|
1214
|
+
const e = netOf(tabId).get(p.requestId);
|
|
1215
|
+
if (e) e.status = p.canceled ? 'canceled' : `failed ${p.errorText}`;
|
|
1216
|
+
break;
|
|
1217
|
+
}
|
|
1218
|
+
case 'Page.frameRequestedNavigation':
|
|
1219
|
+
case 'Page.frameStartedLoading':
|
|
1220
|
+
if (!mainFrame.has(tabId) || p.frameId === mainFrame.get(tabId)) navOf(tabId).started = true;
|
|
1221
|
+
break;
|
|
1222
|
+
case 'Page.navigatedWithinDocument':
|
|
1223
|
+
if (p.frameId === mainFrame.get(tabId)) navOf(tabId).same = true;
|
|
1224
|
+
break;
|
|
1225
|
+
case 'Page.frameStoppedLoading':
|
|
1226
|
+
if (p.frameId === mainFrame.get(tabId) && navOf(tabId).started && !navOf(tabId).committed) navOf(tabId).stopped = true;
|
|
1227
|
+
break;
|
|
1228
|
+
case 'Page.frameNavigated': {
|
|
1229
|
+
if (p.frame.parentId) break;
|
|
1230
|
+
mainFrame.set(tabId, p.frame.id);
|
|
1231
|
+
navOf(tabId).committed = true;
|
|
1232
|
+
let origin = '';
|
|
1233
|
+
try {
|
|
1234
|
+
origin = new URL(p.frame.url).origin;
|
|
1235
|
+
} catch {}
|
|
1236
|
+
if (tabOrigin.has(tabId) && tabOrigin.get(tabId) !== origin) {
|
|
1237
|
+
consoleLog.delete(tabId);
|
|
1238
|
+
netLog.delete(tabId);
|
|
1239
|
+
}
|
|
1240
|
+
tabOrigin.set(tabId, origin);
|
|
1241
|
+
break;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
});
|
|
1245
|
+
|
|
1246
|
+
async function execIn(tabId, func, args = [], frameId = null) {
|
|
1247
|
+
const target = frameId == null ? {tabId} : {tabId, frameIds: [frameId]};
|
|
1248
|
+
const [{result}] = await chrome.scripting.executeScript({target, func, args});
|
|
1249
|
+
return result;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
|
|
1253
|
+
function focusProps() {
|
|
1254
|
+
return backgroundMode ? {} : {active: true};
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
// Foreground mode: bring the agent tab to the front so the user can watch.
|
|
1258
|
+
// Background mode: leave the user's tab alone and keep the agent tab rendering
|
|
1259
|
+
// through the debugger (focus emulation) instead.
|
|
1260
|
+
async function prepTab(tabId) {
|
|
1261
|
+
if (backgroundMode) {
|
|
1262
|
+
await ensureDebugger(tabId);
|
|
1263
|
+
} else {
|
|
1264
|
+
await chrome.tabs.update(tabId, {active: true});
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// ---------------------------------------------------------------------------
|
|
1269
|
+
// Background tab recording (CDP screencast)
|
|
1270
|
+
// Frames come from Page.startScreencast on the agent tab itself, not from the
|
|
1271
|
+
// screen, so whatever the user does in other tabs or windows never shows up in
|
|
1272
|
+
// the recording and never interrupts it. JPEG frames stream to the MCP server
|
|
1273
|
+
// over the bridge socket; the server writes them to disk and encodes the video.
|
|
1274
|
+
// ---------------------------------------------------------------------------
|
|
1275
|
+
const recordings = new Map(); // tabId -> {recId, opts, frames}
|
|
1276
|
+
const frameWaiters = new Map(); // tabId -> resolve, for screenshot frame pumping
|
|
1277
|
+
const pumpDepth = new Map(); // tabId -> nesting count
|
|
1278
|
+
|
|
1279
|
+
// A background tab gets almost no rendering frames, and Chrome ties mouse
|
|
1280
|
+
// moves, rAF and captures to frames, so each can stall ~1s. A tiny screencast
|
|
1281
|
+
// makes Chrome render the tab continuously while fn runs. A running recording
|
|
1282
|
+
// already does this.
|
|
1283
|
+
async function withFrames(tabId, fn) {
|
|
1284
|
+
if (!backgroundMode || recordings.has(tabId)) return await fn();
|
|
1285
|
+
const depth = pumpDepth.get(tabId) || 0;
|
|
1286
|
+
pumpDepth.set(tabId, depth + 1);
|
|
1287
|
+
if (depth === 0) {
|
|
1288
|
+
const first = new Promise(r => {
|
|
1289
|
+
frameWaiters.set(tabId, r);
|
|
1290
|
+
setTimeout(r, 600);
|
|
1291
|
+
});
|
|
1292
|
+
await sendCdp(tabId, 'Page.startScreencast', {format: 'jpeg', quality: 1, maxWidth: 32, maxHeight: 32}).catch(() => {});
|
|
1293
|
+
await first;
|
|
1294
|
+
frameWaiters.delete(tabId);
|
|
1295
|
+
}
|
|
1296
|
+
try {
|
|
1297
|
+
return await fn();
|
|
1298
|
+
} finally {
|
|
1299
|
+
const d = (pumpDepth.get(tabId) || 1) - 1;
|
|
1300
|
+
if (d <= 0) {
|
|
1301
|
+
pumpDepth.delete(tabId);
|
|
1302
|
+
await sendCdp(tabId, 'Page.stopScreencast').catch(() => {});
|
|
1303
|
+
} else pumpDepth.set(tabId, d);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
async function startScreencast(tabId, opts) {
|
|
1308
|
+
await chrome.debugger.sendCommand({tabId}, 'Page.startScreencast', {
|
|
1309
|
+
format: 'jpeg',
|
|
1310
|
+
quality: opts.quality,
|
|
1311
|
+
maxWidth: opts.maxWidth,
|
|
1312
|
+
maxHeight: opts.maxHeight,
|
|
1313
|
+
everyNthFrame: opts.everyNthFrame,
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
async function setRecBadge(tabId, on) {
|
|
1318
|
+
await chrome.scripting
|
|
1319
|
+
.executeScript({
|
|
1320
|
+
target: {tabId},
|
|
1321
|
+
func: v => window.__codexPilotOverlay?.setRecording?.(v),
|
|
1322
|
+
args: [on],
|
|
1323
|
+
})
|
|
1324
|
+
.catch(() => {});
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
function sendBridgeEvent(msg) {
|
|
1328
|
+
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
1329
|
+
ws.send(JSON.stringify(msg));
|
|
1330
|
+
return true;
|
|
1331
|
+
}
|
|
1332
|
+
return false;
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
chrome.debugger.onEvent.addListener((source, method, params) => {
|
|
1336
|
+
if (method !== 'Page.screencastFrame') return;
|
|
1337
|
+
const tabId = source.tabId;
|
|
1338
|
+
chrome.debugger
|
|
1339
|
+
.sendCommand({tabId}, 'Page.screencastFrameAck', {sessionId: params.sessionId})
|
|
1340
|
+
.catch(() => {});
|
|
1341
|
+
frameWaiters.get(tabId)?.();
|
|
1342
|
+
const rec = recordings.get(tabId);
|
|
1343
|
+
if (!rec) return;
|
|
1344
|
+
// Chrome can push 60+ frames/s. Keep at most ~2x the output fps, but always
|
|
1345
|
+
// keep the newest frame so the video never ends on a stale picture.
|
|
1346
|
+
const now = Date.now();
|
|
1347
|
+
rec.pending = {data: params.data, ts: now};
|
|
1348
|
+
const wait = rec.gap - (now - rec.lastSent);
|
|
1349
|
+
if (wait <= 0) flushFrame(rec);
|
|
1350
|
+
else if (!rec.timer) rec.timer = setTimeout(() => flushFrame(rec), wait);
|
|
1351
|
+
});
|
|
1352
|
+
|
|
1353
|
+
function flushFrame(rec) {
|
|
1354
|
+
clearTimeout(rec.timer);
|
|
1355
|
+
rec.timer = null;
|
|
1356
|
+
if (!rec.pending) return;
|
|
1357
|
+
sendBridgeEvent({type: 'frame', recId: rec.recId, ts: rec.pending.ts, data: rec.pending.data});
|
|
1358
|
+
rec.pending = null;
|
|
1359
|
+
rec.lastSent = Date.now();
|
|
1360
|
+
rec.frames++;
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
chrome.tabs.onUpdated.addListener(async (tabId, info) => {
|
|
1364
|
+
const rec = recordings.get(tabId);
|
|
1365
|
+
if (!rec || info.status !== 'complete') return;
|
|
1366
|
+
// A navigation drops the overlay and, on a process swap, can stop the screencast.
|
|
1367
|
+
await ensureOverlay(tabId);
|
|
1368
|
+
if (rec.opts.badge) await setRecBadge(tabId, true);
|
|
1369
|
+
await startScreencast(tabId, rec.opts).catch(() => {});
|
|
1370
|
+
});
|
|
1371
|
+
|
|
1372
|
+
chrome.tabs.onRemoved.addListener(tabId => {
|
|
1373
|
+
const owner = tabOwner.get(tabId);
|
|
1374
|
+
tabOwner.delete(tabId);
|
|
1375
|
+
if (owner && sessionTab.get(owner) === tabId) sessionTab.delete(owner);
|
|
1376
|
+
nav.delete(tabId);
|
|
1377
|
+
mainFrame.delete(tabId);
|
|
1378
|
+
const rec = recordings.get(tabId);
|
|
1379
|
+
if (!rec) return;
|
|
1380
|
+
recordings.delete(tabId);
|
|
1381
|
+
sendBridgeEvent({type: 'recordEnded', recId: rec.recId, reason: 'tab closed'});
|
|
1382
|
+
});
|
|
1383
|
+
|
|
1384
|
+
chrome.debugger.onDetach.addListener(source => {
|
|
1385
|
+
const rec = recordings.get(source?.tabId);
|
|
1386
|
+
if (!rec) return;
|
|
1387
|
+
recordings.delete(source.tabId);
|
|
1388
|
+
sendBridgeEvent({type: 'recordEnded', recId: rec.recId, reason: 'debugger detached'});
|
|
1389
|
+
});
|
|
1390
|
+
|
|
1391
|
+
async function recordStart(tabId, params) {
|
|
1392
|
+
if (recordings.has(tabId)) {
|
|
1393
|
+
throw new Error(`Tab ${tabId} is already being recorded (${recordings.get(tabId).recId}).`);
|
|
1394
|
+
}
|
|
1395
|
+
if (!(await ensureDebugger(tabId))) {
|
|
1396
|
+
throw new Error('Could not attach chrome.debugger to the tab for recording.');
|
|
1397
|
+
}
|
|
1398
|
+
const opts = {
|
|
1399
|
+
quality: params.quality ?? 70,
|
|
1400
|
+
maxWidth: params.maxWidth ?? 1280,
|
|
1401
|
+
maxHeight: params.maxHeight ?? 1280,
|
|
1402
|
+
everyNthFrame: params.everyNthFrame ?? 1,
|
|
1403
|
+
badge: params.badge !== false,
|
|
1404
|
+
};
|
|
1405
|
+
recordings.set(tabId, {
|
|
1406
|
+
recId: params.recId,
|
|
1407
|
+
opts,
|
|
1408
|
+
frames: 0,
|
|
1409
|
+
gap: 1000 / (2 * Math.max(1, params.fps ?? 15)),
|
|
1410
|
+
lastSent: 0,
|
|
1411
|
+
pending: null,
|
|
1412
|
+
timer: null,
|
|
1413
|
+
});
|
|
1414
|
+
await ensureOverlay(tabId);
|
|
1415
|
+
if (opts.badge) await setRecBadge(tabId, true);
|
|
1416
|
+
try {
|
|
1417
|
+
await startScreencast(tabId, opts);
|
|
1418
|
+
} catch (err) {
|
|
1419
|
+
recordings.delete(tabId);
|
|
1420
|
+
throw err;
|
|
1421
|
+
}
|
|
1422
|
+
return {recId: params.recId, tabId};
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
async function recordStop(recId) {
|
|
1426
|
+
for (const [tabId, rec] of recordings) {
|
|
1427
|
+
if (recId && rec.recId !== recId) continue;
|
|
1428
|
+
flushFrame(rec);
|
|
1429
|
+
recordings.delete(tabId);
|
|
1430
|
+
await chrome.debugger.sendCommand({tabId}, 'Page.stopScreencast').catch(() => {});
|
|
1431
|
+
if (rec.opts.badge) await setRecBadge(tabId, false);
|
|
1432
|
+
return {recId: rec.recId, tabId, frames: rec.frames};
|
|
1433
|
+
}
|
|
1434
|
+
return {recId, frames: 0, missing: true};
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
// ---------------------------------------------------------------------------
|
|
1438
|
+
// Screenshots (also work on background tabs, via CDP)
|
|
1439
|
+
// ---------------------------------------------------------------------------
|
|
1440
|
+
async function shrinkImage(base64, format, maxWidth, quality = 0.6) {
|
|
1441
|
+
const bin = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
|
|
1442
|
+
const bmp = await createImageBitmap(new Blob([bin], {type: `image/${format}`}));
|
|
1443
|
+
const k = Math.min(1, maxWidth / bmp.width);
|
|
1444
|
+
const w = Math.round(bmp.width * k);
|
|
1445
|
+
const h = Math.round(bmp.height * k);
|
|
1446
|
+
const canvas = new OffscreenCanvas(w, h);
|
|
1447
|
+
canvas.getContext('2d').drawImage(bmp, 0, 0, w, h);
|
|
1448
|
+
bmp.close();
|
|
1449
|
+
const buf = new Uint8Array(await (await canvas.convertToBlob({type: 'image/jpeg', quality})).arrayBuffer());
|
|
1450
|
+
let str = '';
|
|
1451
|
+
for (let i = 0; i < buf.length; i += 0x8000) str += String.fromCharCode(...buf.subarray(i, i + 0x8000));
|
|
1452
|
+
return {base64: btoa(str), imgWidth: w};
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
async function takeScreenshot(tabId, params) {
|
|
1456
|
+
const format = params.format === 'png' ? 'png' : 'jpeg';
|
|
1457
|
+
const hasDbg = await ensureDebugger(tabId);
|
|
1458
|
+
if (!hasDbg) {
|
|
1459
|
+
await chrome.tabs.update(tabId, {active: true});
|
|
1460
|
+
const tab = await chrome.tabs.get(tabId);
|
|
1461
|
+
const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {
|
|
1462
|
+
format,
|
|
1463
|
+
...(format === 'jpeg' ? {quality: params.quality ?? 80} : {}),
|
|
1464
|
+
});
|
|
1465
|
+
return {base64: dataUrl.split(',')[1], format};
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// Work out the clip in CSS pixels: an element, the full page, or the viewport.
|
|
1469
|
+
let target = null;
|
|
1470
|
+
if (params.uid || params.selector) {
|
|
1471
|
+
await ensureOverlay(tabId);
|
|
1472
|
+
const [{result}] = await chrome.scripting.executeScript({
|
|
1473
|
+
target: {tabId},
|
|
1474
|
+
func: (u, sel) => {
|
|
1475
|
+
const D = window.__codexDom;
|
|
1476
|
+
const el = u ? D.byUid(u) : D.one(sel);
|
|
1477
|
+
if (!el) return null;
|
|
1478
|
+
el.scrollIntoView({block: 'center', inline: 'center'});
|
|
1479
|
+
const r = D.box(el);
|
|
1480
|
+
return {x: r.x + window.scrollX, y: r.y + window.scrollY, width: r.width, height: r.height};
|
|
1481
|
+
},
|
|
1482
|
+
args: [params.uid || null, params.selector || null],
|
|
1483
|
+
});
|
|
1484
|
+
if (!result) throw new Error('Screenshot target element not found. Run pilot_snapshot first.');
|
|
1485
|
+
target = result;
|
|
1486
|
+
}
|
|
1487
|
+
const metrics = await sendCdp(tabId, 'Page.getLayoutMetrics');
|
|
1488
|
+
|
|
1489
|
+
const vv = metrics.cssVisualViewport || metrics.visualViewport;
|
|
1490
|
+
const dprRes = await chrome.scripting
|
|
1491
|
+
.executeScript({target: {tabId}, func: () => window.devicePixelRatio})
|
|
1492
|
+
.catch(() => null);
|
|
1493
|
+
const dpr = dprRes?.[0]?.result || 1;
|
|
1494
|
+
let clip;
|
|
1495
|
+
const region = Array.isArray(params.region) && params.region.length === 4 ? params.region : null;
|
|
1496
|
+
if (region) {
|
|
1497
|
+
const [x0, y0, x1, y1] = region;
|
|
1498
|
+
clip = {x: vv.pageX + Math.min(x0, x1), y: vv.pageY + Math.min(y0, y1), width: Math.abs(x1 - x0), height: Math.abs(y1 - y0)};
|
|
1499
|
+
target = clip;
|
|
1500
|
+
} else if (target) {
|
|
1501
|
+
clip = target;
|
|
1502
|
+
} else if (params.fullPage) {
|
|
1503
|
+
const cs = metrics.cssContentSize || metrics.contentSize;
|
|
1504
|
+
clip = {x: 0, y: 0, width: cs.width, height: Math.min(cs.height, 16000)};
|
|
1505
|
+
} else {
|
|
1506
|
+
clip = {x: vv.pageX, y: vv.pageY, width: vv.clientWidth, height: vv.clientHeight};
|
|
1507
|
+
}
|
|
1508
|
+
const maxWidth = params.maxWidth || 0;
|
|
1509
|
+
// Regions are zoomed: re-rendered at up to 4x so small UI is readable.
|
|
1510
|
+
const scale = region
|
|
1511
|
+
? Math.min(2, Math.max(1, (maxWidth || 900) / (clip.width * dpr)))
|
|
1512
|
+
: maxWidth
|
|
1513
|
+
? Math.min(1, maxWidth / (clip.width * dpr))
|
|
1514
|
+
: 1;
|
|
1515
|
+
const setHud = visible =>
|
|
1516
|
+
chrome.scripting
|
|
1517
|
+
.executeScript({
|
|
1518
|
+
target: {tabId},
|
|
1519
|
+
func: v => {
|
|
1520
|
+
const h = document.getElementById('__codex_pilot_hud_host__');
|
|
1521
|
+
if (h) h.style.visibility = v ? 'visible' : 'hidden';
|
|
1522
|
+
},
|
|
1523
|
+
args: [visible],
|
|
1524
|
+
})
|
|
1525
|
+
.catch(() => {});
|
|
1526
|
+
if (params.clean) await setHud(false);
|
|
1527
|
+
// A hidden tab barely produces frames, so a capture can wait seconds for
|
|
1528
|
+
// one. A tiny screencast makes Chrome render it right away (a running
|
|
1529
|
+
// recording already does this).
|
|
1530
|
+
return await withFrames(tabId, async () => { try {
|
|
1531
|
+
const shot = s =>
|
|
1532
|
+
sendCdp(tabId, 'Page.captureScreenshot', {
|
|
1533
|
+
format,
|
|
1534
|
+
...(format === 'jpeg' ? {quality: params.quality ?? 80} : {}),
|
|
1535
|
+
// A plain viewport shot needs no clip; a clip is only for elements,
|
|
1536
|
+
// regions, full pages, or scaling.
|
|
1537
|
+
...(target || params.fullPage || s !== 1 ? {clip: {...clip, scale: s}} : {}),
|
|
1538
|
+
captureBeyondViewport: Boolean(params.fullPage || (target && !region)),
|
|
1539
|
+
});
|
|
1540
|
+
const timeout = new Promise((_, rej) => setTimeout(() => rej(new Error('capture timeout')), 8000));
|
|
1541
|
+
// Upscaled captures can stall on a background tab; fall back to scale 1.
|
|
1542
|
+
const {data} = await Promise.race([shot(scale), timeout]).catch(err => {
|
|
1543
|
+
if (scale > 1) return shot(1);
|
|
1544
|
+
throw err;
|
|
1545
|
+
});
|
|
1546
|
+
const out = {
|
|
1547
|
+
base64: data,
|
|
1548
|
+
format,
|
|
1549
|
+
cssWidth: Math.round(clip.width),
|
|
1550
|
+
imgWidth: Math.round(clip.width * (target || params.fullPage || scale !== 1 ? scale : dpr)),
|
|
1551
|
+
viewport: !target && !params.fullPage,
|
|
1552
|
+
};
|
|
1553
|
+
// Small JPEG for the model, made from the same capture (a second capture
|
|
1554
|
+
// of a background tab can take seconds).
|
|
1555
|
+
if (params.preview) {
|
|
1556
|
+
const p = await shrinkImage(data, format, params.previewWidth || 1024).catch(() => null);
|
|
1557
|
+
if (p) out.preview = {...p, cssWidth: out.cssWidth, viewport: out.viewport};
|
|
1558
|
+
}
|
|
1559
|
+
return out;
|
|
1560
|
+
} finally {
|
|
1561
|
+
if (params.clean) await setHud(true);
|
|
1562
|
+
} });
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
async function dispatchCommand(method, params) {
|
|
1566
|
+
if (typeof params.background === 'boolean') backgroundMode = params.background;
|
|
1567
|
+
if (typeof params.stealth === 'boolean') {
|
|
1568
|
+
stealthMode = params.stealth;
|
|
1569
|
+
if (stealthMode && attachedDebugTabs.size > 0) {
|
|
1570
|
+
for (const tid of attachedDebugTabs) {
|
|
1571
|
+
injectStealthScripts(tid).catch(() => {});
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
params.session = params.session || 'default';
|
|
1576
|
+
sessionSeen.set(params.session, Date.now());
|
|
1577
|
+
currentMethod = method;
|
|
1578
|
+
const groupTitle = params.groupTitle || DEFAULT_GROUP_TITLE;
|
|
1579
|
+
const groupColor = params.groupColor || DEFAULT_GROUP_COLOR;
|
|
1580
|
+
|
|
1581
|
+
switch (method) {
|
|
1582
|
+
case 'ensureGroup': {
|
|
1583
|
+
return await ensureGroup(groupTitle, groupColor, params.initialUrl, params.session);
|
|
1584
|
+
}
|
|
1585
|
+
case 'listTabs': {
|
|
1586
|
+
const info = await listGroupTabs(groupTitle);
|
|
1587
|
+
const mine = sessionTab.get(params.session);
|
|
1588
|
+
info.tabs = info.tabs.map(t => ({...t, current: t.tabId === mine, other: ownedByOther(t.tabId, params.session)}));
|
|
1589
|
+
return info;
|
|
1590
|
+
}
|
|
1591
|
+
case 'openTab': {
|
|
1592
|
+
const groupHasTabs = (await listGroupTabs(groupTitle)).tabs.length > 0;
|
|
1593
|
+
if (params.reuse || (params.newTab === false && groupHasTabs)) {
|
|
1594
|
+
const cur = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1595
|
+
await ensureDebugger(cur.tabId);
|
|
1596
|
+
await chrome.tabs.update(cur.tabId, {url: normalizeUrl(params.url), ...focusProps()});
|
|
1597
|
+
await waitForTabReady(cur.tabId);
|
|
1598
|
+
const snap = await buildPageSnapshot(cur.tabId, 60);
|
|
1599
|
+
return {tabId: cur.tabId, snapshot: snap};
|
|
1600
|
+
}
|
|
1601
|
+
const tabInfo = await openTab(normalizeUrl(params.url), groupTitle, groupColor, true, params.session);
|
|
1602
|
+
const snap = await buildPageSnapshot(tabInfo.tabId, 60).catch(() => null);
|
|
1603
|
+
return {tabInfo, snapshot: snap};
|
|
1604
|
+
}
|
|
1605
|
+
case 'selectTab': {
|
|
1606
|
+
const info = await listGroupTabs(groupTitle);
|
|
1607
|
+
const match = info.tabs.find(
|
|
1608
|
+
t =>
|
|
1609
|
+
(params.tabId !== undefined && t.tabId === params.tabId) ||
|
|
1610
|
+
(params.urlIncludes && t.url.includes(params.urlIncludes)),
|
|
1611
|
+
);
|
|
1612
|
+
if (!match) {
|
|
1613
|
+
throw new Error(`Matching tab not found in "${groupTitle}" group.`);
|
|
1614
|
+
}
|
|
1615
|
+
return await activateTab(match.tabId, groupTitle, params.session);
|
|
1616
|
+
}
|
|
1617
|
+
case 'navigate': {
|
|
1618
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1619
|
+
await ensureDebugger(tab.tabId);
|
|
1620
|
+
const how = String(params.url || '').trim().toLowerCase();
|
|
1621
|
+
if (how === 'back') await chrome.tabs.goBack(tab.tabId);
|
|
1622
|
+
else if (how === 'forward') await chrome.tabs.goForward(tab.tabId);
|
|
1623
|
+
else if (how === 'reload') await chrome.tabs.reload(tab.tabId);
|
|
1624
|
+
else await chrome.tabs.update(tab.tabId, {url: normalizeUrl(params.url), ...focusProps()});
|
|
1625
|
+
await sleep(how === 'back' || how === 'forward' ? 150 : 0);
|
|
1626
|
+
await waitForTabReady(tab.tabId);
|
|
1627
|
+
const snap = await buildPageSnapshot(tab.tabId, 60);
|
|
1628
|
+
return {tabId: tab.tabId, snapshot: snap};
|
|
1629
|
+
}
|
|
1630
|
+
case 'snapshot': {
|
|
1631
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1632
|
+
return await buildPageSnapshot(tab.tabId, params.maxElements || 80, params.viewportOnly, params.query, params.frame);
|
|
1633
|
+
}
|
|
1634
|
+
case 'click': {
|
|
1635
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1636
|
+
await prepTab(tab.tabId);
|
|
1637
|
+
resetNav(tab.tabId);
|
|
1638
|
+
const isStealth = typeof params.stealth === 'boolean' ? params.stealth : stealthMode;
|
|
1639
|
+
const targeted = params.uid || params.selector || params.text;
|
|
1640
|
+
const button = ['left', 'right', 'middle'].includes(params.button) ? params.button : 'left';
|
|
1641
|
+
const clicks = Math.min(Math.max(Number(params.clicks) || 1, 1), 3);
|
|
1642
|
+
const loc = await locateAndAnimate(tab.tabId, {
|
|
1643
|
+
uid: params.uid,
|
|
1644
|
+
selector: params.selector,
|
|
1645
|
+
text: params.text,
|
|
1646
|
+
x: targeted ? undefined : params.x,
|
|
1647
|
+
y: targeted ? undefined : params.y,
|
|
1648
|
+
label: params.hover ? `Hovering ${params.uid || params.text || ''}` : undefined,
|
|
1649
|
+
clickAnim: !params.hover,
|
|
1650
|
+
markAttr: 'data-codex-target',
|
|
1651
|
+
});
|
|
1652
|
+
if (loc.tag === 'select' && !params.hover && button === 'left') {
|
|
1653
|
+
// A native <select> popup would open on the user's screen; pick with pilot_fill instead.
|
|
1654
|
+
return {clickedLabel: loc.label, note: `options: ${loc.options.join(' | ')} (choose with pilot_fill)`, snapshot: null};
|
|
1655
|
+
}
|
|
1656
|
+
const hasDbg = await ensureDebugger(tab.tabId);
|
|
1657
|
+
if (hasDbg) {
|
|
1658
|
+
if (params.hover) {
|
|
1659
|
+
await withFrames(tab.tabId, async () => {
|
|
1660
|
+
if (isStealth) {
|
|
1661
|
+
await stealthMouseMove(tab.tabId, loc.rect.cx, loc.rect.cy);
|
|
1662
|
+
await sleep(randomInt(120, 240));
|
|
1663
|
+
} else {
|
|
1664
|
+
await sendCdp(tab.tabId, 'Input.dispatchMouseEvent', {type: 'mouseMoved', x: loc.rect.cx, y: loc.rect.cy});
|
|
1665
|
+
await sleep(120); // let hover menus open
|
|
1666
|
+
}
|
|
1667
|
+
});
|
|
1668
|
+
hoverActive.add(tab.tabId);
|
|
1669
|
+
} else {
|
|
1670
|
+
if (button === 'right') {
|
|
1671
|
+
// Let page menus open but never the native one (it would pop up over the user's work).
|
|
1672
|
+
await execIn(tab.tabId, () => {
|
|
1673
|
+
const h = e => e.preventDefault();
|
|
1674
|
+
window.addEventListener('contextmenu', h);
|
|
1675
|
+
setTimeout(() => window.removeEventListener('contextmenu', h), 1500);
|
|
1676
|
+
}).catch(() => {});
|
|
1677
|
+
}
|
|
1678
|
+
// Moving the cursor can change the layout (a hover menu closes, a sticky
|
|
1679
|
+
// header appears), so re-measure the target after it arrives.
|
|
1680
|
+
let pt = {x: loc.rect.cx, y: loc.rect.cy};
|
|
1681
|
+
if (isStealth && loc.rect.width > 6 && loc.rect.height > 6) {
|
|
1682
|
+
const maxOffX = Math.min(loc.rect.width * 0.25, 12);
|
|
1683
|
+
const maxOffY = Math.min(loc.rect.height * 0.25, 8);
|
|
1684
|
+
pt = {
|
|
1685
|
+
x: Math.round(pt.x + (Math.random() - 0.5) * 2 * maxOffX),
|
|
1686
|
+
y: Math.round(pt.y + (Math.random() - 0.5) * 2 * maxOffY),
|
|
1687
|
+
};
|
|
1688
|
+
}
|
|
1689
|
+
const remeasure = targeted && (hoverActive.has(tab.tabId) || !backgroundMode);
|
|
1690
|
+
hoverActive.delete(tab.tabId);
|
|
1691
|
+
const run = async () => {
|
|
1692
|
+
if (remeasure) {
|
|
1693
|
+
if (isStealth) {
|
|
1694
|
+
await stealthMouseMove(tab.tabId, pt.x, pt.y);
|
|
1695
|
+
} else {
|
|
1696
|
+
await sendCdp(tab.tabId, 'Input.dispatchMouseEvent', {type: 'mouseMoved', ...pt});
|
|
1697
|
+
}
|
|
1698
|
+
await sleep(40);
|
|
1699
|
+
const now = await execIn(tab.tabId, () => {
|
|
1700
|
+
const el = window.__codexDom?.one('[data-codex-target="1"]');
|
|
1701
|
+
return el ? window.__codexDom.box(el) : null;
|
|
1702
|
+
}).catch(() => null);
|
|
1703
|
+
if (now && now.width) pt = {x: now.cx, y: now.cy};
|
|
1704
|
+
}
|
|
1705
|
+
await mouseClick(tab.tabId, pt.x, pt.y, {button, clicks, modifiers: modBits(params.modifiers), stealth: isStealth});
|
|
1706
|
+
};
|
|
1707
|
+
// Pump frames only when a move is needed (after a hover) or in stealth mode.
|
|
1708
|
+
if (remeasure || isStealth) await withFrames(tab.tabId, run);
|
|
1709
|
+
else await run();
|
|
1710
|
+
}
|
|
1711
|
+
} else {
|
|
1712
|
+
await execIn(tab.tabId, () => {
|
|
1713
|
+
const el = window.__codexDom.one('[data-codex-target="1"]');
|
|
1714
|
+
el?.focus?.();
|
|
1715
|
+
el?.click?.();
|
|
1716
|
+
});
|
|
1717
|
+
}
|
|
1718
|
+
await settle(tab.tabId, Boolean(loc?.nav));
|
|
1719
|
+
const snap = params.withSnapshot === false ? null : await buildPageSnapshot(tab.tabId, 60);
|
|
1720
|
+
return {clickedLabel: loc.label, snapshot: snap};
|
|
1721
|
+
}
|
|
1722
|
+
case 'fill': {
|
|
1723
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1724
|
+
await prepTab(tab.tabId);
|
|
1725
|
+
const hasDbg = await ensureDebugger(tab.tabId);
|
|
1726
|
+
const value = params.value == null ? '' : String(params.value);
|
|
1727
|
+
const targeted = Boolean(params.uid || params.selector || params.text);
|
|
1728
|
+
const clear = params.clear ?? targeted;
|
|
1729
|
+
const isStealth = typeof params.stealth === 'boolean' ? params.stealth : stealthMode;
|
|
1730
|
+
let loc = null;
|
|
1731
|
+
let note = '';
|
|
1732
|
+
if (targeted) {
|
|
1733
|
+
loc = await locateAndAnimate(tab.tabId, {
|
|
1734
|
+
uid: params.uid,
|
|
1735
|
+
selector: params.selector,
|
|
1736
|
+
text: params.text,
|
|
1737
|
+
label: `Filling ${params.uid || params.text || 'field'}`,
|
|
1738
|
+
clickAnim: true,
|
|
1739
|
+
markAttr: 'data-codex-target',
|
|
1740
|
+
forInput: true,
|
|
1741
|
+
});
|
|
1742
|
+
}
|
|
1743
|
+
const kind = loc?.kind || 'focused';
|
|
1744
|
+
const ex = (f, a = []) => execIn(tab.tabId, f, a, loc?.frameId ?? null);
|
|
1745
|
+
let typeIt = isStealth || kind === 'editable' || kind === 'focused' || kind === 'other' || Boolean(params.typing);
|
|
1746
|
+
|
|
1747
|
+
if (kind === 'select') {
|
|
1748
|
+
const r = await ex(val => {
|
|
1749
|
+
const el = window.__codexDom.one('[data-codex-target="1"]');
|
|
1750
|
+
const v = val.trim().toLowerCase();
|
|
1751
|
+
const opts = Array.from(el.options);
|
|
1752
|
+
const opt =
|
|
1753
|
+
opts.find(o => o.value === val) ||
|
|
1754
|
+
opts.find(o => o.text.trim().toLowerCase() === v) ||
|
|
1755
|
+
opts.find(o => o.text.trim().toLowerCase().includes(v));
|
|
1756
|
+
if (!opt) return {ok: false, options: opts.slice(0, 40).map(o => o.text.trim())};
|
|
1757
|
+
el.value = opt.value;
|
|
1758
|
+
el.dispatchEvent(new Event('input', {bubbles: true}));
|
|
1759
|
+
el.dispatchEvent(new Event('change', {bubbles: true}));
|
|
1760
|
+
return {ok: true, text: opt.text.trim()};
|
|
1761
|
+
},
|
|
1762
|
+
[value],
|
|
1763
|
+
);
|
|
1764
|
+
if (!r.ok) throw new Error(`No option "${value}". Options: ${r.options.join(' | ')}`);
|
|
1765
|
+
note = ` -> "${r.text}"`;
|
|
1766
|
+
} else if (kind === 'check') {
|
|
1767
|
+
const want = /^(true|on|yes|1|checked|check)$/i.test(value);
|
|
1768
|
+
if (loc.checked !== want) {
|
|
1769
|
+
if (hasDbg) await mouseClick(tab.tabId, loc.rect.cx, loc.rect.cy, {stealth: isStealth});
|
|
1770
|
+
else await ex(() => window.__codexDom.one('[data-codex-target="1"]')?.click());
|
|
1771
|
+
}
|
|
1772
|
+
note = want ? ' (checked)' : ' (unchecked)';
|
|
1773
|
+
} else if (kind === 'text' && !typeIt) {
|
|
1774
|
+
const ok = await ex((val, shouldClear) => {
|
|
1775
|
+
const el = window.__codexDom.one('[data-codex-target="1"]');
|
|
1776
|
+
if (!el) return false;
|
|
1777
|
+
el.focus();
|
|
1778
|
+
const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
|
1779
|
+
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
|
|
1780
|
+
const nextVal = shouldClear ? val : `${el.value || ''}${val}`;
|
|
1781
|
+
if (setter) setter.call(el, nextVal);
|
|
1782
|
+
else el.value = nextVal;
|
|
1783
|
+
el.dispatchEvent(new Event('input', {bubbles: true}));
|
|
1784
|
+
el.dispatchEvent(new Event('change', {bubbles: true}));
|
|
1785
|
+
return el.value === nextVal;
|
|
1786
|
+
},
|
|
1787
|
+
[value, clear],
|
|
1788
|
+
);
|
|
1789
|
+
// Some frameworks reject programmatic values; type it for real instead.
|
|
1790
|
+
if (!ok) typeIt = true;
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
if (typeIt && kind !== 'select' && kind !== 'check') {
|
|
1794
|
+
if (!hasDbg) throw new Error('Typing needs the debugger (close DevTools on this tab).');
|
|
1795
|
+
if (loc) {
|
|
1796
|
+
await mouseClick(tab.tabId, loc.rect.cx, loc.rect.cy, {stealth: isStealth});
|
|
1797
|
+
if (isStealth && clear) {
|
|
1798
|
+
await pressCombo(tab.tabId, 'ctrl+a', {stealth: true});
|
|
1799
|
+
await sleep(randomInt(35, 75));
|
|
1800
|
+
await pressCombo(tab.tabId, 'Backspace', {stealth: true});
|
|
1801
|
+
await sleep(randomInt(45, 90));
|
|
1802
|
+
} else {
|
|
1803
|
+
await ex(shouldClear => {
|
|
1804
|
+
const el = window.__codexDom.one('[data-codex-target="1"]');
|
|
1805
|
+
if (!el) return;
|
|
1806
|
+
if (document.activeElement !== el && !el.contains(document.activeElement)) el.focus();
|
|
1807
|
+
const doc = el.ownerDocument;
|
|
1808
|
+
if (typeof el.select === 'function' && 'value' in el) {
|
|
1809
|
+
if (shouldClear) el.select();
|
|
1810
|
+
else el.setSelectionRange?.(el.value.length, el.value.length);
|
|
1811
|
+
return;
|
|
1812
|
+
}
|
|
1813
|
+
const range = doc.createRange();
|
|
1814
|
+
range.selectNodeContents(el);
|
|
1815
|
+
if (!shouldClear) range.collapse(false);
|
|
1816
|
+
const sel = doc.getSelection();
|
|
1817
|
+
sel.removeAllRanges();
|
|
1818
|
+
sel.addRange(range);
|
|
1819
|
+
},
|
|
1820
|
+
[clear],
|
|
1821
|
+
);
|
|
1822
|
+
}
|
|
1823
|
+
} else if (clear) {
|
|
1824
|
+
await pressCombo(tab.tabId, 'ctrl+a', {stealth: isStealth});
|
|
1825
|
+
if (isStealth) await sleep(randomInt(35, 75));
|
|
1826
|
+
await pressCombo(tab.tabId, 'Backspace', {stealth: isStealth});
|
|
1827
|
+
if (isStealth) await sleep(randomInt(45, 90));
|
|
1828
|
+
}
|
|
1829
|
+
if (value) await typeText(tab.tabId, value, Boolean(params.typing || isStealth), {stealth: isStealth});
|
|
1830
|
+
else if (clear && !isStealth) await pressCombo(tab.tabId, 'Backspace');
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
if (params.submit) {
|
|
1834
|
+
resetNav(tab.tabId);
|
|
1835
|
+
if (hasDbg) await pressCombo(tab.tabId, 'Enter');
|
|
1836
|
+
else {
|
|
1837
|
+
await ex(() => window.__codexDom.one('[data-codex-target="1"]')?.form?.requestSubmit?.());
|
|
1838
|
+
}
|
|
1839
|
+
await settle(tab.tabId, true);
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
const fresh = await chrome.tabs.get(tab.tabId);
|
|
1843
|
+
const snap = params.withSnapshot ? await buildPageSnapshot(tab.tabId, 60).catch(() => null) : null;
|
|
1844
|
+
return {label: loc?.label || 'focused element', note, url: fresh.url || '', snapshot: snap};
|
|
1845
|
+
}
|
|
1846
|
+
case 'search': {
|
|
1847
|
+
// Load the results page directly: one navigation instead of
|
|
1848
|
+
// home page -> type -> submit -> results.
|
|
1849
|
+
const q = encodeURIComponent(params.query);
|
|
1850
|
+
const url =
|
|
1851
|
+
params.engine === 'google'
|
|
1852
|
+
? `https://www.google.com/search?q=${q}`
|
|
1853
|
+
: params.engine === 'bing'
|
|
1854
|
+
? `https://www.bing.com/search?q=${q}`
|
|
1855
|
+
: `https://duckduckgo.com/?q=${q}`;
|
|
1856
|
+
return await dispatchCommand('openTab', {...params, url, newTab: params.newTab ?? false});
|
|
1857
|
+
}
|
|
1858
|
+
case 'upload': {
|
|
1859
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1860
|
+
await prepTab(tab.tabId);
|
|
1861
|
+
const loc = await locateAndAnimate(tab.tabId, {
|
|
1862
|
+
uid: params.uid,
|
|
1863
|
+
selector: params.selector || (params.uid ? null : 'input[type="file"]'),
|
|
1864
|
+
label: `Uploading ${params.filePaths.map(p => p.split(/[\\/]/).pop()).join(', ')}`,
|
|
1865
|
+
clickAnim: false,
|
|
1866
|
+
markAttr: 'data-codex-upload',
|
|
1867
|
+
});
|
|
1868
|
+
const hasDbg = await ensureDebugger(tab.tabId);
|
|
1869
|
+
if (!hasDbg) throw new Error('Could not attach chrome.debugger for file upload.');
|
|
1870
|
+
if (loc.tag === 'input' && loc.type === 'file') {
|
|
1871
|
+
const {root} = await sendCdp(tab.tabId, 'DOM.getDocument', {depth: -1, pierce: true});
|
|
1872
|
+
let {nodeId} = await sendCdp(tab.tabId, 'DOM.querySelector', {nodeId: root.nodeId, selector: '[data-codex-upload="1"]'});
|
|
1873
|
+
if (!nodeId) {
|
|
1874
|
+
// Inside a shadow root or iframe: search the whole tree.
|
|
1875
|
+
const {searchId, resultCount} = await sendCdp(tab.tabId, 'DOM.performSearch', {query: '[data-codex-upload="1"]'});
|
|
1876
|
+
if (resultCount) ({nodeIds: [nodeId]} = await sendCdp(tab.tabId, 'DOM.getSearchResults', {searchId, fromIndex: 0, toIndex: 1}));
|
|
1877
|
+
await sendCdp(tab.tabId, 'DOM.discardSearchResults', {searchId}).catch(() => {});
|
|
1878
|
+
}
|
|
1879
|
+
if (!nodeId) throw new Error('File input element disappeared before upload.');
|
|
1880
|
+
await sendCdp(tab.tabId, 'DOM.setFileInputFiles', {nodeId, files: params.filePaths});
|
|
1881
|
+
} else {
|
|
1882
|
+
// A drop zone, not an <input type=file>: drop the files onto it.
|
|
1883
|
+
const data = {items: [], files: params.filePaths, dragOperationsMask: 1};
|
|
1884
|
+
for (const type of ['dragEnter', 'dragOver', 'drop']) {
|
|
1885
|
+
await sendCdp(tab.tabId, 'Input.dispatchDragEvent', {type, x: loc.rect.cx, y: loc.rect.cy, data});
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
await ensureOverlay(tab.tabId, 'Codex • File uploaded ✔');
|
|
1889
|
+
return {filePaths: params.filePaths, dropped: !(loc.tag === 'input' && loc.type === 'file')};
|
|
1890
|
+
}
|
|
1891
|
+
case 'scroll': {
|
|
1892
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1893
|
+
const isStealth = typeof params.stealth === 'boolean' ? params.stealth : stealthMode;
|
|
1894
|
+
const px = params.pixels || 600;
|
|
1895
|
+
const targeted = params.uid || params.selector || typeof params.x === 'number';
|
|
1896
|
+
const dir = params.direction || (targeted ? undefined : 'down');
|
|
1897
|
+
if (targeted && !dir) {
|
|
1898
|
+
const loc = await locateAndAnimate(tab.tabId, {uid: params.uid, selector: params.selector, label: 'Scrolling into view', clickAnim: false});
|
|
1899
|
+
return {direction: 'into view', label: loc.label};
|
|
1900
|
+
}
|
|
1901
|
+
const delta = {down: [0, px], up: [0, -px], right: [px, 0], left: [-px, 0], bottom: [0, 1e7], top: [0, -1e7]}[dir];
|
|
1902
|
+
let loc = null;
|
|
1903
|
+
if (targeted) {
|
|
1904
|
+
loc = await locateAndAnimate(tab.tabId, {
|
|
1905
|
+
uid: params.uid,
|
|
1906
|
+
selector: params.selector,
|
|
1907
|
+
x: params.x,
|
|
1908
|
+
y: params.y,
|
|
1909
|
+
label: `Scrolling ${dir}`,
|
|
1910
|
+
clickAnim: false,
|
|
1911
|
+
markAttr: 'data-codex-target',
|
|
1912
|
+
});
|
|
1913
|
+
} else {
|
|
1914
|
+
await ensureOverlay(tab.tabId, `Scrolling ${dir}...`);
|
|
1915
|
+
}
|
|
1916
|
+
// Scrolls the page, or (if the page itself can't move, as in Gmail/Slack and
|
|
1917
|
+
// many SPAs) the panel under the target / the middle of the screen.
|
|
1918
|
+
const scrollFn = (dx, dy, targeted, px, py) => {
|
|
1919
|
+
const D = window.__codexDom;
|
|
1920
|
+
const se = document.scrollingElement || document.documentElement;
|
|
1921
|
+
const tryScroll = el => {
|
|
1922
|
+
const before = [el.scrollLeft, el.scrollTop];
|
|
1923
|
+
el.scrollBy({left: dx, top: dy, behavior: 'instant'});
|
|
1924
|
+
return el.scrollLeft !== before[0] || el.scrollTop !== before[1];
|
|
1925
|
+
};
|
|
1926
|
+
let start = null;
|
|
1927
|
+
if (targeted) start = D.one('[data-codex-target="1"]') || (typeof px === 'number' ? D.atPoint(px, py) : null);
|
|
1928
|
+
if (!start && tryScroll(se)) return {y: Math.round(se.scrollTop), height: se.scrollHeight};
|
|
1929
|
+
if (!start) start = D.atPoint(innerWidth / 2, innerHeight / 2);
|
|
1930
|
+
for (const el of D.scrollChain(start)) {
|
|
1931
|
+
if (tryScroll(el)) {
|
|
1932
|
+
return el === se
|
|
1933
|
+
? {y: Math.round(se.scrollTop), height: se.scrollHeight}
|
|
1934
|
+
: {inner: true, y: Math.round(el.scrollTop), height: el.scrollHeight};
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
return {moved: false, y: Math.round(se.scrollTop), height: se.scrollHeight};
|
|
1938
|
+
};
|
|
1939
|
+
|
|
1940
|
+
let r;
|
|
1941
|
+
if (isStealth && Math.abs(delta[0]) < 1e6 && Math.abs(delta[1]) < 1e6) {
|
|
1942
|
+
const steps = 3;
|
|
1943
|
+
const sDx = Math.round(delta[0] / steps);
|
|
1944
|
+
const sDy = Math.round(delta[1] / steps);
|
|
1945
|
+
let anyMoved = false;
|
|
1946
|
+
for (let i = 0; i < steps; i++) {
|
|
1947
|
+
const cur = await execIn(tab.tabId, scrollFn, [sDx, sDy, Boolean(targeted), params.x ?? null, params.y ?? null]);
|
|
1948
|
+
if (cur && cur.moved !== false) anyMoved = true;
|
|
1949
|
+
r = cur;
|
|
1950
|
+
await sleep(randomInt(25, 45));
|
|
1951
|
+
}
|
|
1952
|
+
if (anyMoved && r && r.moved === false) delete r.moved;
|
|
1953
|
+
} else {
|
|
1954
|
+
r = await execIn(tab.tabId, scrollFn, [delta[0], delta[1], Boolean(targeted), params.x ?? null, params.y ?? null]);
|
|
1955
|
+
}
|
|
1956
|
+
await sleep(60);
|
|
1957
|
+
return {direction: dir, label: loc?.label, ...r};
|
|
1958
|
+
}
|
|
1959
|
+
case 'press': {
|
|
1960
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1961
|
+
if (!(await ensureDebugger(tab.tabId))) throw new Error('Could not attach debugger to press keys.');
|
|
1962
|
+
resetNav(tab.tabId);
|
|
1963
|
+
const isStealth = typeof params.stealth === 'boolean' ? params.stealth : stealthMode;
|
|
1964
|
+
await pressKeys(tab.tabId, params.key, Math.min(Math.max(Number(params.repeat) || 1, 1), 100), {stealth: isStealth});
|
|
1965
|
+
await settle(tab.tabId, /enter/i.test(String(params.key)));
|
|
1966
|
+
return {key: params.key};
|
|
1967
|
+
}
|
|
1968
|
+
case 'read': {
|
|
1969
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1970
|
+
await ensureOverlay(tab.tabId, 'Reading page content...');
|
|
1971
|
+
return await execIn(
|
|
1972
|
+
tab.tabId,
|
|
1973
|
+
(limit, uid, sel, all) => {
|
|
1974
|
+
const D = window.__codexDom;
|
|
1975
|
+
let root = uid ? D.byUid(uid) : sel ? D.one(sel) : null;
|
|
1976
|
+
let scope = root ? 'element' : 'page';
|
|
1977
|
+
if (!root && !all) {
|
|
1978
|
+
// Article first, like a reader view; all=true for the whole page.
|
|
1979
|
+
const main = document.querySelector('main, [role="main"], article');
|
|
1980
|
+
if (main && (main.innerText || '').trim().length > 300) {
|
|
1981
|
+
root = main;
|
|
1982
|
+
scope = 'main';
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
const text = ((root || document.body)?.innerText || '').replace(/\n{3,}/g, '\n\n').trim();
|
|
1986
|
+
return {title: document.title, url: location.href, scope, text: text.slice(0, limit), truncated: text.length > limit};
|
|
1987
|
+
},
|
|
1988
|
+
[params.maxChars || 8000, params.uid || null, params.selector || null, Boolean(params.all)],
|
|
1989
|
+
);
|
|
1990
|
+
}
|
|
1991
|
+
case 'eval': {
|
|
1992
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
1993
|
+
if (!(await ensureDebugger(tab.tabId))) throw new Error('Could not attach debugger for JS eval.');
|
|
1994
|
+
const opts = {returnByValue: true, awaitPromise: true, userGesture: true};
|
|
1995
|
+
// REPL mode: statements, const/let and top-level await all work; the last
|
|
1996
|
+
// expression is the result. A function expression is called.
|
|
1997
|
+
let res = await sendCdp(tab.tabId, 'Runtime.evaluate', {expression: params.expression, replMode: true, ...opts});
|
|
1998
|
+
if (!res.exceptionDetails && res.result?.type === 'function') {
|
|
1999
|
+
res = await sendCdp(tab.tabId, 'Runtime.evaluate', {expression: `(${params.expression})()`, ...opts});
|
|
2000
|
+
}
|
|
2001
|
+
if (res.exceptionDetails) {
|
|
2002
|
+
const d = res.exceptionDetails;
|
|
2003
|
+
throw new Error(d.exception?.description || d.text || 'Evaluation failed');
|
|
2004
|
+
}
|
|
2005
|
+
return res.result?.value ?? null;
|
|
2006
|
+
}
|
|
2007
|
+
case 'screenshot': {
|
|
2008
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
2009
|
+
return await takeScreenshot(tab.tabId, params);
|
|
2010
|
+
}
|
|
2011
|
+
case 'recordStart': {
|
|
2012
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
2013
|
+
const res = await recordStart(tab.tabId, params);
|
|
2014
|
+
return {...res, url: tab.url, title: tab.title};
|
|
2015
|
+
}
|
|
2016
|
+
case 'recordStop': {
|
|
2017
|
+
return await recordStop(params.recId);
|
|
2018
|
+
}
|
|
2019
|
+
case 'setMode': {
|
|
2020
|
+
return {background: backgroundMode};
|
|
2021
|
+
}
|
|
2022
|
+
case 'drag': {
|
|
2023
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
2024
|
+
await prepTab(tab.tabId);
|
|
2025
|
+
if (!(await ensureDebugger(tab.tabId))) throw new Error('Could not attach debugger for drag.');
|
|
2026
|
+
const where = async (spec, label) => {
|
|
2027
|
+
const m = /^\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*$/.exec(String(spec));
|
|
2028
|
+
if (m) return await locateAndAnimate(tab.tabId, {x: Number(m[1]), y: Number(m[2]), label, clickAnim: false});
|
|
2029
|
+
const isUid = /^(f\d+:)?e\d+$/.test(String(spec));
|
|
2030
|
+
return await locateAndAnimate(tab.tabId, {
|
|
2031
|
+
uid: isUid ? spec : undefined,
|
|
2032
|
+
selector: isUid ? undefined : spec,
|
|
2033
|
+
label,
|
|
2034
|
+
clickAnim: false,
|
|
2035
|
+
});
|
|
2036
|
+
};
|
|
2037
|
+
let a = await where(params.from, 'Dragging');
|
|
2038
|
+
const b = await where(params.to, 'Dropping');
|
|
2039
|
+
if (b.scrolled) a = await where(params.from, 'Dragging');
|
|
2040
|
+
const from = {x: a.rect.cx, y: a.rect.cy};
|
|
2041
|
+
const to = {x: b.rect.cx, y: b.rect.cy};
|
|
2042
|
+
dragData.delete(tab.tabId);
|
|
2043
|
+
resetNav(tab.tabId);
|
|
2044
|
+
await sendCdp(tab.tabId, 'Input.setInterceptDrags', {enabled: true}).catch(() => {});
|
|
2045
|
+
await withFrames(tab.tabId, async () => { try {
|
|
2046
|
+
await sendCdp(tab.tabId, 'Input.dispatchMouseEvent', {type: 'mouseMoved', ...from});
|
|
2047
|
+
await sendCdp(tab.tabId, 'Input.dispatchMouseEvent', {type: 'mousePressed', ...from, button: 'left', buttons: 1, clickCount: 1});
|
|
2048
|
+
const steps = 12;
|
|
2049
|
+
for (let i = 1; i <= steps; i++) {
|
|
2050
|
+
await sendCdp(tab.tabId, 'Input.dispatchMouseEvent', {
|
|
2051
|
+
type: 'mouseMoved',
|
|
2052
|
+
x: from.x + ((to.x - from.x) * i) / steps,
|
|
2053
|
+
y: from.y + ((to.y - from.y) * i) / steps,
|
|
2054
|
+
button: 'left',
|
|
2055
|
+
buttons: 1,
|
|
2056
|
+
});
|
|
2057
|
+
await sleep(16);
|
|
2058
|
+
}
|
|
2059
|
+
await sleep(50);
|
|
2060
|
+
const data = dragData.get(tab.tabId);
|
|
2061
|
+
if (data) {
|
|
2062
|
+
// HTML5 drag and drop (draggable=true lists, kanban boards).
|
|
2063
|
+
for (const type of ['dragEnter', 'dragOver', 'drop']) {
|
|
2064
|
+
await sendCdp(tab.tabId, 'Input.dispatchDragEvent', {type, ...to, data});
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
await sendCdp(tab.tabId, 'Input.dispatchMouseEvent', {type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1});
|
|
2068
|
+
} finally {
|
|
2069
|
+
await sendCdp(tab.tabId, 'Input.setInterceptDrags', {enabled: false}).catch(() => {});
|
|
2070
|
+
} });
|
|
2071
|
+
await settle(tab.tabId);
|
|
2072
|
+
const snap = params.withSnapshot === false ? null : await buildPageSnapshot(tab.tabId, 60);
|
|
2073
|
+
return {from: a.label, to: b.label, html5: dragData.has(tab.tabId), snapshot: snap};
|
|
2074
|
+
}
|
|
2075
|
+
case 'wait': {
|
|
2076
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
2077
|
+
const start = Date.now();
|
|
2078
|
+
if (!params.text && !params.selector) {
|
|
2079
|
+
await sleep(Math.min(params.ms ?? 1000, 30000));
|
|
2080
|
+
return {ok: true, ms: Date.now() - start};
|
|
2081
|
+
}
|
|
2082
|
+
const timeout = Math.min(params.timeout ?? 10000, 60000);
|
|
2083
|
+
for (;;) {
|
|
2084
|
+
const present = await execIn(
|
|
2085
|
+
tab.tabId,
|
|
2086
|
+
(txt, sel) => {
|
|
2087
|
+
if (sel) {
|
|
2088
|
+
const D = window.__codexDom;
|
|
2089
|
+
try {
|
|
2090
|
+
return Boolean(D ? D.one(sel) : document.querySelector(sel));
|
|
2091
|
+
} catch {
|
|
2092
|
+
return false;
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
return (document.body?.innerText || '').toLowerCase().includes(txt.toLowerCase());
|
|
2096
|
+
},
|
|
2097
|
+
[params.text || '', params.selector || null],
|
|
2098
|
+
).catch(() => false);
|
|
2099
|
+
if (present !== Boolean(params.gone)) {
|
|
2100
|
+
const snap = params.withSnapshot ? await buildPageSnapshot(tab.tabId, 60).catch(() => null) : null;
|
|
2101
|
+
return {ok: true, ms: Date.now() - start, snapshot: snap};
|
|
2102
|
+
}
|
|
2103
|
+
if (Date.now() - start > timeout) return {ok: false, ms: Date.now() - start};
|
|
2104
|
+
await sleep(150);
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
case 'viewport': {
|
|
2108
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
2109
|
+
if (!(await ensureDebugger(tab.tabId))) throw new Error('Could not attach debugger.');
|
|
2110
|
+
// Emulated per tab: the user's real window is never resized.
|
|
2111
|
+
const size = () => execIn(tab.tabId, () => [innerWidth, innerHeight]).catch(() => null);
|
|
2112
|
+
const before = await size();
|
|
2113
|
+
// A background tab applies the new size on its next frame; until then
|
|
2114
|
+
// the page reports the old one and clicks would aim at stale positions.
|
|
2115
|
+
const settled = async ok =>
|
|
2116
|
+
withFrames(tab.tabId, async () => {
|
|
2117
|
+
for (let end = Date.now() + 1000; Date.now() < end; ) {
|
|
2118
|
+
const now = await size();
|
|
2119
|
+
if (now && ok(now)) return;
|
|
2120
|
+
await sleep(40);
|
|
2121
|
+
}
|
|
2122
|
+
});
|
|
2123
|
+
if (params.reset) {
|
|
2124
|
+
await sendCdp(tab.tabId, 'Emulation.clearDeviceMetricsOverride');
|
|
2125
|
+
await sendCdp(tab.tabId, 'Emulation.setTouchEmulationEnabled', {enabled: false}).catch(() => {});
|
|
2126
|
+
const real = await chrome.tabs.get(tab.tabId);
|
|
2127
|
+
await settled(([w, h]) => Math.abs(w - real.width) <= 1 && Math.abs(h - real.height) <= 1);
|
|
2128
|
+
return {reset: true};
|
|
2129
|
+
}
|
|
2130
|
+
const w = Math.round(params.width);
|
|
2131
|
+
const h = Math.round(params.height);
|
|
2132
|
+
await sendCdp(tab.tabId, 'Emulation.setDeviceMetricsOverride', {
|
|
2133
|
+
width: w,
|
|
2134
|
+
height: h,
|
|
2135
|
+
deviceScaleFactor: params.mobile ? 2 : 0,
|
|
2136
|
+
mobile: Boolean(params.mobile),
|
|
2137
|
+
});
|
|
2138
|
+
await sendCdp(tab.tabId, 'Emulation.setTouchEmulationEnabled', {enabled: Boolean(params.mobile)}).catch(() => {});
|
|
2139
|
+
// Mobile pages without a viewport tag lay out at 980px, so there only wait for a change.
|
|
2140
|
+
await settled(([iw, ih]) => (params.mobile ? iw !== before?.[0] || ih !== before?.[1] : iw === w && ih === h));
|
|
2141
|
+
return {width: w, height: h, mobile: Boolean(params.mobile)};
|
|
2142
|
+
}
|
|
2143
|
+
case 'logs': {
|
|
2144
|
+
const tab = await resolveGroupTab(params.tabId, groupTitle, params.session);
|
|
2145
|
+
if (!(await ensureDebugger(tab.tabId))) throw new Error('Could not attach debugger.');
|
|
2146
|
+
const limit = Math.min(params.limit || 50, 300);
|
|
2147
|
+
let re = null;
|
|
2148
|
+
if (params.pattern) {
|
|
2149
|
+
try {
|
|
2150
|
+
re = new RegExp(params.pattern, 'i');
|
|
2151
|
+
} catch {
|
|
2152
|
+
re = new RegExp(params.pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
if (params.kind === 'network') {
|
|
2156
|
+
let rows = [...netOf(tab.tabId).values()];
|
|
2157
|
+
if (re) rows = rows.filter(r => re.test(r.url) || re.test(r.method) || re.test(String(r.status)));
|
|
2158
|
+
if (params.onlyErrors) rows = rows.filter(r => typeof r.status !== 'number' || r.status >= 400);
|
|
2159
|
+
const total = rows.length;
|
|
2160
|
+
const lines = rows.slice(-limit).map(r => {
|
|
2161
|
+
const kb = r.size ? ` ${Math.max(1, Math.round(r.size / 1024))}KB` : '';
|
|
2162
|
+
return `${r.status} ${r.method} ${r.type} ${r.url.slice(0, 160)}${kb}`;
|
|
2163
|
+
});
|
|
2164
|
+
if (params.clear) netOf(tab.tabId).clear();
|
|
2165
|
+
return {lines, total};
|
|
2166
|
+
}
|
|
2167
|
+
if (!consoleOn.has(tab.tabId)) {
|
|
2168
|
+
// Enabling Runtime replays the console messages the page already logged.
|
|
2169
|
+
consoleOn.add(tab.tabId);
|
|
2170
|
+
await sendCdp(tab.tabId, 'Runtime.enable').catch(() => {});
|
|
2171
|
+
await sleep(150);
|
|
2172
|
+
}
|
|
2173
|
+
let rows = consoleLog.get(tab.tabId) || [];
|
|
2174
|
+
if (params.onlyErrors) rows = rows.filter(r => /^(error|exception|assert)$/.test(r.level));
|
|
2175
|
+
if (re) rows = rows.filter(r => re.test(r.text) || re.test(r.level));
|
|
2176
|
+
const total = rows.length;
|
|
2177
|
+
const lines = rows.slice(-limit).map(r => `${r.level}: ${r.text}`);
|
|
2178
|
+
if (params.clear) consoleLog.delete(tab.tabId);
|
|
2179
|
+
return {lines, total};
|
|
2180
|
+
}
|
|
2181
|
+
case 'downloads': {
|
|
2182
|
+
const recent = () => chrome.downloads.search({orderBy: ['-startTime'], limit: params.limit || 5});
|
|
2183
|
+
if (params.wait) {
|
|
2184
|
+
// Wait for a download started in the last minute (or from now on) to finish.
|
|
2185
|
+
const since = Date.now() - 60000;
|
|
2186
|
+
const deadline = Date.now() + Math.min(params.timeout ?? 60000, 300000);
|
|
2187
|
+
for (;;) {
|
|
2188
|
+
const [d] = await recent();
|
|
2189
|
+
if (d && Date.parse(d.startTime) >= since && d.state !== 'in_progress') break;
|
|
2190
|
+
if (Date.now() > deadline) break;
|
|
2191
|
+
await sleep(300);
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
return (await recent()).map(d => ({
|
|
2195
|
+
file: d.filename,
|
|
2196
|
+
url: d.finalUrl || d.url,
|
|
2197
|
+
state: d.state,
|
|
2198
|
+
error: d.error,
|
|
2199
|
+
bytes: d.totalBytes > 0 ? d.totalBytes : d.bytesReceived,
|
|
2200
|
+
started: d.startTime,
|
|
2201
|
+
}));
|
|
2202
|
+
}
|
|
2203
|
+
case 'closeTab': {
|
|
2204
|
+
return await closeTab(params.tabId, groupTitle, params.session);
|
|
2205
|
+
}
|
|
2206
|
+
case 'closeGroup': {
|
|
2207
|
+
return await closeGroup(groupTitle, params.session);
|
|
2208
|
+
}
|
|
2209
|
+
default:
|
|
2210
|
+
throw new Error(`Unknown method: ${method}`);
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
globalThis.__codexPilot = {
|
|
2215
|
+
dispatchCommand,
|
|
2216
|
+
ensureGroup,
|
|
2217
|
+
openTab,
|
|
2218
|
+
listGroupTabs,
|
|
2219
|
+
activateTab,
|
|
2220
|
+
closeTab,
|
|
2221
|
+
closeGroup,
|
|
2222
|
+
};
|