diff --git a/internal/browserext/ext/background.js b/internal/browserext/ext/background.js index da88fbb1c..7dbcfa16a 100644 --- a/internal/browserext/ext/background.js +++ b/internal/browserext/ext/background.js @@ -3,9 +3,10 @@ // out in this browser's own tabs, signed in to whatever the user is. import { GATEWAY } from "./config.js"; -import { attach, fault, forget, send, settle, sleep, state, waitLoad, watch } from "./cdp.js"; +import { attach, fault, forget, read, send, settle, sleep, state, waitLoad, watch, watchConsole } from "./cdp.js"; import { find, take } from "./snapshot.js"; -import { press as keyPress, typeSlowly } from "./keys.js"; +import { press as keyPress } from "./keys.js"; +import * as human from "./human.js"; const VERSION = chrome.runtime.getManifest().version; const ACT_SNAPSHOT_MAX = 30000; @@ -141,15 +142,50 @@ function tabArg(v) { return Number(m[1]); } +// ours is whether a tab is an agent's: one a session works in, or one in +// a Magpie tab group +async function ours(tab) { + for (const v of sessions.values()) if (v === tab.id) return true; + if (tab.groupId === undefined || tab.groupId < 0) return false; + const g = await chrome.tabGroups.get(tab.groupId).catch(() => null); + return !!g && /^Magpie( \d+)?$/.test(g.title || ""); +} + +// what a call is told before its answer: session → text +const said = new Map(); +// the tab of its own a session was given for a user's tab it named: +// "session|tab" → tab +const copies = new Map(); + // the tab a call works in: the one it names, else the session's, else a // new one of the session's own. The user's tabs are theirs: an agent never -// starts in the one they are looking at (it navigated it away under them), -// and works in one of theirs only when it names it. +// acts in one of them, the one they are looking at or one behind it. One +// it names has its page opened in a tab of the agent's own, behind, in its +// group, signed in the same, and the agent goes on there. async function tabFor(session, args) { await loadSessions(); const named = tabArg(args.tab); if (named !== null) { - await chrome.tabs.get(named).catch(() => { throw fault("BAD_ARGS", `there is no tab t${named} now: call browser_tabs for the open ones`); }); + const tab = await chrome.tabs.get(named).catch(() => { throw fault("BAD_ARGS", `there is no tab t${named} now: call browser_tabs for the open ones`); }); + if (!(await ours(tab))) { + const key = session + "|" + named; + const was = copies.get(key); + if (was !== undefined && (await chrome.tabs.get(was).then(() => true, () => false))) { + sessions.set(session, was); + saveSessions(); + return was; + } + const url = tab.url || tab.pendingUrl || "about:blank"; + const copy = await open(session, url, false); + copies.set(key, copy.id); + // loaded before the call reads it + for (let end = Date.now() + 20000; Date.now() < end; await sleep(150)) { + const c = await chrome.tabs.get(copy.id).catch(() => null); + if (!c || c.status === "complete") break; + } + said.set(session, `t${named} is the user's own tab, which agents leave to them: its page (${url.slice(0, 200)}) is opened in t${copy.id}, a tab of your own behind theirs, and calls go there.`); + return copy.id; + } sessions.set(session, named); saveSessions(); return named; @@ -243,7 +279,17 @@ async function run(m) { try { const tool = TOOLS[m.tool]; if (!tool) return fail(`magpie's browser extension has no tool ${m.tool}: update it (magpie writes it again on start; reload it in chrome://extensions)`); - return await tool(m.session || "default", m.args || {}); + const session = m.session || "default"; + said.delete(session); + const r = await tool(session, m.args || {}); + const note = said.get(session); + if (note) { + said.delete(session); + const first = r.content && r.content.find((c) => c.type === "text"); + if (first) first.text = note + "\n\n" + first.text; + else (r.content = r.content || []).unshift(text(note)); + } + return r; } catch (e) { return failure(e); } @@ -293,7 +339,7 @@ const PRESSES = new Set(["button", "link", "clickable", "menuitem", "tab", "tree // one); null where a part can't be read async function look(t, el) { const tab = await chrome.tabs.get(t.tabId).catch(() => null); - const scroll = await send(t.tabId, "Runtime.evaluate", { expression: "scrollX + ',' + scrollY", returnByValue: true }).then((r) => r.result.value, () => null); + const scroll = await read(t, "scrollX + ',' + scrollY").catch(() => null); const doc = [await watch(t)]; if (el && (el.sid || el.frame)) doc.push(await watch(t, el.frame, el.sid)); return { url: tab && tab.url, scroll, reqs: t.reqs, doc: doc.map((d) => (d ? d[0] : null)) }; @@ -312,6 +358,10 @@ async function act(t, what, fn, el = null, press = false) { const shown = mine && all.find((x) => x.active && x.windowId === mine.windowId); const behind = shown && shown.id !== t.tabId ? shown : null; const was = press ? await look(t, el) : null; + // the window the user works in: a page that opens a window of its own + // (window.open with a size) doesn't take it from them + const focused = await chrome.windows.getLastFocused({ windowTypes: ["normal"] }).catch(() => null); + await human.pace(t); t.sentInput = false; let opened = null; // a tab the link opens comes up in front of the user's: their tab is @@ -320,6 +370,7 @@ async function act(t, what, fn, el = null, press = false) { if (before.has(tab.id) || !(tab.openerTabId === t.tabId || (behind && tab.openerTabId === behind.id) || !opened)) return; opened = tab; if (behind && (tab.openerTabId === t.tabId || tab.openerTabId === behind.id)) chrome.tabs.update(behind.id, { active: true }).catch(() => {}); + if (focused && tab.windowId !== focused.id && focused.focused) chrome.windows.update(focused.id, { focused: true }).catch(() => {}); }; chrome.tabs.onCreated.addListener(onCreated); let said; @@ -336,6 +387,7 @@ async function act(t, what, fn, el = null, press = false) { if (t.sentInput && !e.code) throw fault("OUTCOME_UNKNOWN", `${what.replace(/\.$/, "")} was under way when the page changed (${String(e.message || e).slice(0, 200)})`); throw e; } finally { + human.done(t); setTimeout(() => chrome.tabs.onCreated.removeListener(onCreated), 1500); } if (!t.dialog) await settle(t, 2500, 400, el ? [el] : []); @@ -347,10 +399,8 @@ async function act(t, what, fn, el = null, press = false) { if (opened && (opened.openerTabId === t.tabId || (behind && opened.openerTabId === behind.id))) { // a link that opens a new tab: the agent goes on in it, in its group, // and the user keeps the tab they had in front - if (behind) { - await chrome.tabs.update(behind.id, { active: true }).catch(() => {}); - if (t.by) await group(t.by, opened.id, opened.windowId).catch(() => {}); - } + if (behind) await chrome.tabs.update(behind.id, { active: true }).catch(() => {}); + if (t.by) await group(t.by, opened.id, opened.windowId).catch(() => {}); if (t.by) { sessions.set(t.by, opened.id); saveSessions(); } const nt = state(opened.id); await attach(opened.id); @@ -386,7 +436,10 @@ async function point(t, el) { const q = quads[0]; const xs = [q[0], q[2], q[4], q[6]], ys = [q[1], q[3], q[5], q[7]]; const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys); - const tries = [[0.5, 0.5], [0.3, 0.5], [0.7, 0.5], [0.5, 0.3], [0.5, 0.7], [0.2, 0.2], [0.8, 0.8]]; + // somewhere near the middle, as a person aims, then other spots when + // something covers it + const a = human.aim(x0, y0, x1, y1); + const tries = [[(a.x - x0) / (x1 - x0 || 1), (a.y - y0) / (y1 - y0 || 1)], [0.5, 0.5], [0.3, 0.5], [0.7, 0.5], [0.5, 0.3], [0.5, 0.7], [0.2, 0.2], [0.8, 0.8]]; let cover = ""; for (const [fx, fy] of tries) { const x = x0 + (x1 - x0) * fx, y = y0 + (y1 - y0) * fy; @@ -448,16 +501,8 @@ const BUTTONS = { left: "left", right: "right", middle: "middle" }; const MODS = { Alt: 1, Control: 2, Ctrl: 2, Meta: 4, Command: 4, Cmd: 4, Shift: 8 }; async function mouse(t, x, y, opts = {}) { - const button = BUTTONS[opts.button] || "left"; const modifiers = (opts.modifiers || []).reduce((a, m) => a | (MODS[m] || 0), 0); - const count = opts.double ? 2 : 1; - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x, y, modifiers }); - await sleep(30 + Math.random() * 40); - for (let i = 1; i <= count; i++) { - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x, y, button, clickCount: i, modifiers, buttons: 1 }); - await sleep(40 + Math.random() * 50); - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button, clickCount: i, modifiers }); - } + await human.click(t, x, y, { button: BUTTONS[opts.button] || "left", double: !!opts.double, modifiers }); } // opensATab is whether el is, or is in, a link that opens in a new tab @@ -511,6 +556,8 @@ const TOOLS = { if (action === "close") { const id = args.tab ? tabArg(args.tab) : sessions.get(session); if (id === undefined || id === null) throw fault("BAD_ARGS", "tab is needed"); + const tab = await chrome.tabs.get(id).catch(() => { throw fault("BAD_ARGS", `there is no tab t${id} now`); }); + if (!(await ours(tab))) throw fault("UNACTIONABLE", `t${id} is the user's own tab: agents close only their own (in a Magpie group); ask the user to close it`); await chrome.tabs.remove(id); return { content: [text(`Closed t${id}.`)] }; } @@ -585,7 +632,7 @@ const TOOLS = { const el = await find(t, args.ref); return act(t, `Hovering over ${el.ref}.`, async () => { const p = await point(t, el); - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y }); + await human.move(t, p.x, p.y); }, el); }, @@ -595,30 +642,42 @@ const TOOLS = { const t = await ready(session, args); const el = await find(t, args.ref); return act(t, `Typed into ${el.ref}${args.submit ? " and pressed Enter" : ""}.`, async () => { + // into the field as a person goes: a click on it, its old text + // selected and taken out with Backspace, then the keys const p = await point(t, el).catch(() => null); if (p) await mouse(t, p.x, p.y); - const ok = await call(t, el, `function(clear) { + const kind = await call(t, el, `function(clear) { const e = this; const edit = (x) => x && (x.isContentEditable || /^(INPUT|TEXTAREA)$/.test(x.tagName)); let to = edit(e) ? e : (e.querySelector && e.querySelector('input,textarea,[contenteditable=""],[contenteditable="true"]')) || e; if (document.activeElement !== to && !(to.contains && to.contains(document.activeElement))) to.focus(); const a = document.activeElement; - if (!edit(a) && !(a && a.isContentEditable)) return false; + if (!edit(a) && !(a && a.isContentEditable)) return ""; + let empty; if (/^(INPUT|TEXTAREA)$/.test(a.tagName)) { + empty = !a.value; if (clear) a.select(); else { try { const n = a.value.length; a.setSelectionRange(n, n); } catch {} } } else { + empty = !a.textContent.replace(/[\u200b\ufeff\s]/g, ""); const s = getSelection(), r = document.createRange(); r.selectNodeContents(a); if (!clear) r.collapse(false); s.removeAllRanges(); s.addRange(r); } - return true; + return (a.tagName === "INPUT" ? "line" : "lines") + (empty ? " empty" : ""); }`, [args.clear !== false]); - if (!ok) throw fault("UNACTIONABLE", `${el.ref} (${el.role} "${el.name}") doesn't take text: click the field itself`); - if (args.clear !== false) await keyPress(t, "Delete"); - if (args.slowly) await typeSlowly(t, args.text); - else if (args.text) await send(t.tabId, "Input.insertText", { text: args.text }); - if (args.submit) await keyPress(t, "Enter"); + if (!kind) throw fault("UNACTIONABLE", `${el.ref} (${el.role} "${el.name}") doesn't take text: click the field itself`); + if (args.clear !== false && !kind.endsWith("empty")) { + await sleep(120 + Math.random() * 200); + await keyPress(t, "Backspace"); + await sleep(150 + Math.random() * 250); + } + if (args.text) await human.type(t, args.text, { newline: kind.startsWith("line ") || kind === "line" ? "" : "Shift+Enter", press: (k) => keyPress(t, k) }); + if (args.submit) { + // a look over what was typed before sending it + await sleep(250 + Math.random() * 450); + await keyPress(t, "Enter"); + } }, el); }, @@ -628,7 +687,7 @@ const TOOLS = { let el = null; if (args.ref) el = await find(t, args.ref); return act(t, `Pressed ${args.key}.`, async () => { - if (el) await call(t, el, "function(){ this.focus() }"); + if (el) await call(t, el, "function(){ if (document.activeElement !== this && !this.contains(document.activeElement)) this.focus() }"); await keyPress(t, args.key); }, el); }, @@ -682,10 +741,10 @@ const TOOLS = { const dx = dir === "left" ? -amount : dir === "right" ? amount : 0; const dy = dir === "up" ? -amount : dir === "down" ? amount : 0; return act(t, `Scrolled ${dir} ${amount}px.`, async () => { - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: dx, deltaY: dy }); + // a little off the middle, where a hand rests + await human.wheel(t, x + (Math.random() - 0.5) * 60, y + (Math.random() - 0.5) * 60, dx, dy); await sleep(250); - const r = await send(t.tabId, "Runtime.evaluate", { expression: "[scrollX, scrollY, document.documentElement.scrollHeight, innerHeight]", returnByValue: true }); - const [sx, sy, h, ih] = r.result.value; + const [sx, sy, h, ih] = await read(t, "[scrollX, scrollY, document.documentElement.scrollHeight, innerHeight]"); return `Scrolled ${dir} ${amount}px; the page is at ${Math.round(sy)} of ${Math.max(0, h - ih)}px down${sx ? `, ${Math.round(sx)}px across` : ""}.`; }); }, @@ -698,16 +757,7 @@ const TOOLS = { return act(t, `Dragged ${a.ref} onto ${b.ref}.`, async () => { const p = await point(t, a); const q = await point(t, b); - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y }); - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x: p.x, y: p.y, button: "left", clickCount: 1, buttons: 1 }); - try { - for (let i = 1; i <= 12; i++) { - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x + ((q.x - p.x) * i) / 12, y: p.y + ((q.y - p.y) * i) / 12, button: "left", buttons: 1 }); - await sleep(25); - } - } finally { - await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x: q.x, y: q.y, button: "left", clickCount: 1 }); - } + await human.drag(t, p, q); }, a); }, @@ -755,9 +805,9 @@ const TOOLS = { const end = Date.now() + bound; for (;;) { if (t.dialog) return dialogOpen(t); - const r = await send(t.tabId, "Runtime.evaluate", { expression: "[location.href, document.body ? document.body.innerText : '']", returnByValue: true }).catch(() => null); - if (r && r.result && r.result.value) { - const [href, body] = r.result.value; + const v = await read(t, "[location.href, document.body ? document.body.innerText : '']").catch(() => null); + if (v) { + const [href, body] = v; const ok = (!args.text || body.includes(args.text)) && (!args.textGone || !body.includes(args.textGone)) && (!args.url || href.includes(args.url)); if (ok) break; } @@ -810,8 +860,11 @@ const TOOLS = { let r; if (args.ref) { const el = await find(t, args.ref); + // the script is the agent's, for the page's own JavaScript: the + // element as the page's world has it + const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: el.backend, objectGroup: "magpie-eval" }, el.sid); r = await send(t.tabId, "Runtime.callFunctionOn", { - objectId: el.objectId, returnByValue: true, awaitPromise: true, + objectId: o.object.objectId, returnByValue: true, awaitPromise: true, functionDeclaration: fn ? `function() { return (${src})(this); }` : `function() { return (${src}); }`, }, el.sid); } else { @@ -830,14 +883,21 @@ const TOOLS = { const t = await ready(session, args); if (t.dialog) return dialogOpen(t); const max = Math.min(Number(args.maxChars) || 40000, 200000); - const r = await send(t.tabId, "Runtime.evaluate", { expression: "document.body ? document.body.innerText : ''", returnByValue: true }); - let s = String(r.result.value || "").replace(/\n{3,}/g, "\n\n").trim(); + let s = String((await read(t, "document.body ? document.body.innerText : ''")) || "").replace(/\n{3,}/g, "\n\n").trim(); if (s.length > max) s = s.slice(0, max) + `\n… (cut at ${max} characters of ${s.length})`; return { content: [text(`${await head(t)}\n\n${s || "(the page has no text)"}`)] }; }, async browser_console(session, args) { const t = await ready(session, args); + // the console is read only once asked for (on a developer's own host + // from the start): a site can tell when it is + if (await watchConsole(t)) { + await sleep(300); + if (!t.logs.some((l) => l.level !== "network")) { + return { content: [text("Magpie Browser reads this tab's console from now on (it is off until asked for, since a site can tell it is read). What the page logs next shows here: do what logs it, then call console again." + (t.logs.length ? "\n\n" + t.logs.map((l) => `[${new Date(l.at).toISOString().slice(11, 19)}] ${l.level}: ${l.text}`).join("\n") : ""))] }; + } + } const levels = args.level === "errors" ? ["error", "assert"] : args.level === "network" ? ["network"] : null; let logs = t.logs.filter((l) => !levels || levels.includes(l.level)); const n = Math.min(Number(args.limit) || 50, 300); diff --git a/internal/browserext/ext/cdp.js b/internal/browserext/ext/cdp.js index 1a5a9c7a4..aa6a29669 100644 --- a/internal/browserext/ext/cdp.js +++ b/internal/browserext/ext/cdp.js @@ -1,9 +1,16 @@ // The DevTools protocol over chrome.debugger, one attachment per tab. A // tab stays attached while an agent works in it and is let go after a // quiet spell, so Chrome's "is debugging this browser" bar is up only -// while it is used. +// while it is used, and doesn't come and go between an agent's calls. +// +// The page never learns it is driven. Runtime is left off (a page can +// tell it is on: Chrome then reads what the page logs, and a logged +// object's getters run), save on a developer's own host or once an agent +// asks for the console. Everything magpie reads or runs in a page runs +// in an isolated world of its own, which the page's scripts can't see or +// patch: nothing of magpie's shows in the page's own JavaScript. -const IDLE_MS = 2 * 60 * 1000; +const IDLE_MS = 5 * 60 * 1000; const LOG_KEPT = 300; // tabId → what is known of the page while attached @@ -22,8 +29,12 @@ export function state(tabId) { // through a session of its own: frame id → session, and session → // { frame, parent session } children: new Map(), frameOf: new Map(), - worlds: new Map(), // "session|frame" → the isolated world settle reads + worlds: new Map(), // "session|frame" → magpie's isolated world there sentInput: false, + console: false, // Runtime is on: the page's logs are read + mouse: null, // where the mouse last was, {x, y} + lastInput: 0, // when the last action's input ended + lastWheel: 0, }; tabs.set(tabId, t); } @@ -54,9 +65,10 @@ export async function attach(tabId) { t.children.clear(); t.frameOf.clear(); t.worlds.clear(); + if (!t.console) t.console = await devHost(tabId); await Promise.all([ send(tabId, "Page.enable"), - send(tabId, "Runtime.enable"), + ...(t.console ? [send(tabId, "Runtime.enable")] : []), send(tabId, "Network.enable"), send(tabId, "DOM.enable"), send(tabId, "Accessibility.enable"), @@ -72,6 +84,25 @@ export async function attach(tabId) { return t; } +// devHost is whether a tab shows a developer's own page (localhost, a +// .test or .localhost name), whose logs are read from the start: no site +// there watches for a debugger +const DEV = /^(localhost|127\.\d+\.\d+\.\d+|\[::1\]|.+\.localhost|.+\.test)$/i; +async function devHost(tabId) { + const tab = await chrome.tabs.get(tabId).catch(() => null); + try { return DEV.test(new URL(tab && (tab.pendingUrl || tab.url)).hostname); } catch { return false; } +} + +// watchConsole turns Runtime on in a tab and its frames, so what the page +// logs from now on is read; asked for by browser_console +export async function watchConsole(t) { + if (t.console) return false; + t.console = true; + await send(t.tabId, "Runtime.enable").catch(() => {}); + for (const sid of t.frameOf.keys()) send(t.tabId, "Runtime.enable", {}, sid).catch(() => {}); + return true; +} + function why(m) { if (/chrome:\/\/|chrome-extension:\/\/|Cannot access|Cannot attach/i.test(m)) { return "Chrome doesn't let an extension control this page (a chrome:// page, the Web Store or another extension's page): open a web page in the tab first"; @@ -100,7 +131,7 @@ function autoAttach(tabId, sid) { async function child(t, sid) { await Promise.all([ - send(t.tabId, "Runtime.enable", {}, sid), + ...(t.console ? [send(t.tabId, "Runtime.enable", {}, sid)] : []), send(t.tabId, "Network.enable", {}, sid), send(t.tabId, "DOM.enable", {}, sid), send(t.tabId, "Accessibility.enable", {}, sid), @@ -194,6 +225,8 @@ chrome.debugger.onEvent.addListener((src, method, p) => { if (!p.frame.parentId) { t.mainFrame = p.frame.id; t.inflight.clear(); + // a developer's own page: its logs are read from the start + try { if (!t.console && DEV.test(new URL(p.frame.url).hostname)) watchConsole(t); } catch {} } break; case "Runtime.consoleAPICalled": { @@ -263,27 +296,69 @@ async function mainFrame(t) { return t.mainFrame; } +const STALE_WORLD = /Cannot find context|context with specified id|Execution context was destroyed|Inspected target navigated/i; + +// world is magpie's isolated world in a frame (the tab's main frame +// without one, or the frame of session sid): its execution context id, a +// new one for each document +export async function world(t, frame, sid) { + if (!frame) frame = sid ? t.frameOf.get(sid)?.frame : await mainFrame(t); + if (!frame) throw new Error("the page has no frame to read"); + const k = (sid || "") + "|" + frame; + let ctx = t.worlds.get(k); + if (!ctx) { + ctx = (await send(t.tabId, "Page.createIsolatedWorld", { frameId: frame, worldName: "magpie" }, sid)).executionContextId; + t.worlds.set(k, ctx); + } + return ctx; +} + +// inWorld runs fn(ctx) in magpie's world of a frame, in a new one when +// the document it had is gone +async function inWorld(t, where, fn) { + for (let i = 0; ; i++) { + let ctx; + try { + ctx = await world(t, where.frame, where.sid); + return await fn(ctx); + } catch (e) { + if (i > 0 || !STALE_WORLD.test(String(e && e.message || e))) throw e; + if (where.frame) t.worlds.delete((where.sid || "") + "|" + where.frame); + else for (const [k, v] of t.worlds) if (v === ctx) t.worlds.delete(k); + if (!where.frame && !where.sid) t.mainFrame = null; // a new document may be a new frame + } + } +} + +// read evaluates an expression in magpie's world of the main frame (or +// where: {frame, sid}) and answers its value +export async function read(t, expression, where = {}) { + return inWorld(t, where, async (contextId) => { + const r = await send(t.tabId, "Runtime.evaluate", { expression, contextId, returnByValue: true, awaitPromise: true }, where.sid); + if (r.exceptionDetails) throw new Error((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text); + return r.result.value; + }); +} + +// evaluate is read answering the remote object, for the caller to walk +export async function evaluate(t, expression, objectGroup, where = {}) { + return inWorld(t, where, async (contextId) => (await send(t.tabId, "Runtime.evaluate", { expression, contextId, objectGroup }, where.sid)).result); +} + +// resolve is an element (by backendNodeId) as an object in magpie's world +// of the frame its document is +export async function resolve(t, backendNodeId, where = {}, objectGroup = "magpie-act") { + return inWorld(t, where, async (executionContextId) => + (await send(t.tabId, "DOM.resolveNode", { backendNodeId, objectGroup, executionContextId }, where.sid)).object); +} + // watch reads the changes in a frame (the tab's main frame without one), // or null when it can't be read export async function watch(t, frame, sid) { - if (!frame) frame = sid ? t.frameOf.get(sid)?.frame : await mainFrame(t); - if (!frame) return null; - const k = (sid || "") + "|" + frame; - for (let i = 0; i < 2; i++) { - let ctx = t.worlds.get(k); - if (!ctx) { - try { - ctx = (await send(t.tabId, "Page.createIsolatedWorld", { frameId: frame, worldName: "magpie-watch" }, sid)).executionContextId; - t.worlds.set(k, ctx); - } catch { return null; } - } - try { - const r = await send(t.tabId, "Runtime.evaluate", { expression: WATCH, contextId: ctx, returnByValue: true }, sid); - if (r.result && Array.isArray(r.result.value)) return r.result.value; - } catch {} - t.worlds.delete(k); // a new document: a new world - } - return null; + try { + const v = await read(t, WATCH, { frame, sid }); + return Array.isArray(v) ? v : null; + } catch { return null; } } // settle waits for the page to go quiet after an action: no load under @@ -312,8 +387,8 @@ export async function waitLoad(t, bound = 30000) { while (Date.now() < end) { if (!t.loading) { try { - const r = await send(t.tabId, "Runtime.evaluate", { expression: "document.readyState", returnByValue: true }); - if (r.result.value === "complete" || r.result.value === "interactive") return true; + const v = await read(t, "document.readyState"); + if (v === "complete" || v === "interactive") return true; } catch {} } await sleep(150); diff --git a/internal/browserext/ext/human.js b/internal/browserext/ext/human.js new file mode 100644 index 000000000..de45ffeb5 --- /dev/null +++ b/internal/browserext/ext/human.js @@ -0,0 +1,245 @@ +// Input as a person makes it. A site that watches for automation reads +// how input arrives: a pointer that jumps to the exact middle of a button +// and clicks in the same instant, text that appears with no key pressed, +// a page scrolled in one leap, one action straight after another. Here the +// mouse travels a curved, uneven path to a point somewhere on the element, +// waits a moment and holds the button as a finger does; text is typed key +// by key with a typist's uneven rhythm (an input method's composition for +// Chinese, Japanese and Korean); a scroll is the wheel's notches; and an +// action waits a person's moment after the last one. + +import { send, sleep } from "./cdp.js"; + +const rand = (a, b) => a + Math.random() * (b - a); +// a normal draw (Box–Muller), for what clusters around a value +function gauss(mean, sd) { + let u = 0, v = 0; + while (!u) u = Math.random(); + while (!v) v = Math.random(); + return mean + sd * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); +} +const clamp = (x, a, b) => Math.min(b, Math.max(a, x)); + +// pace waits until a person's moment has passed since the last action in +// the tab: no one clicks the next thing in the same instant +export async function pace(t) { + const since = Date.now() - (t.lastInput || 0); + const want = clamp(gauss(750, 250), 350, 1600); + if (since < want) await sleep(want - since); +} + +export function done(t) { + t.lastInput = Date.now(); +} + +// aim is where on a box [x0, y0, x1, y1] to put the mouse: near the middle, +// rarely the exact middle, never at the edges +export function aim(x0, y0, x1, y1) { + const w = x1 - x0, h = y1 - y0; + const fx = clamp(gauss(0.5, 0.12), 0.25, 0.75); + const fy = clamp(gauss(0.5, 0.1), 0.3, 0.7); + return { x: x0 + w * fx, y: y0 + h * fy }; +} + +const ease = (s) => (s < 0.5 ? 2 * s * s : 1 - Math.pow(-2 * s + 2, 2) / 2); + +// move takes the mouse from where it was to (x, y) along a curve, quick in +// the middle and slow at both ends, a few pixels off a straight line; +// buttons is held down for a drag +export async function move(t, x, y, opts = {}) { + const buttons = opts.buttons || 0; + const modifiers = opts.modifiers || 0; + let from = t.mouse; + if (!from) { + // the first move in a tab comes in from somewhere off to one side + const m = await send(t.tabId, "Page.getLayoutMetrics").catch(() => null); + const vw = (m && (m.cssVisualViewport || m.layoutViewport)) || { clientWidth: 1000, clientHeight: 700 }; + from = { x: clamp(x + rand(-260, 260), 2, vw.clientWidth - 2), y: clamp(y + rand(120, 260) * (Math.random() < 0.5 ? -1 : 1), 2, vw.clientHeight - 2) }; + } + const dx = x - from.x, dy = y - from.y; + const dist = Math.hypot(dx, dy); + const steps = clamp(Math.round(dist / rand(18, 30)), dist < 3 ? 1 : 4, 40); + // two control points off the line, on one side: an arm's arc + const side = Math.random() < 0.5 ? -1 : 1; + const bend = clamp(dist * rand(0.05, 0.2), 0, 120) * side; + const nx = dist ? -dy / dist : 0, ny = dist ? dx / dist : 0; + const c1 = { x: from.x + dx * 0.3 + nx * bend, y: from.y + dy * 0.3 + ny * bend }; + const c2 = { x: from.x + dx * 0.7 + nx * bend * 0.6, y: from.y + dy * 0.7 + ny * bend * 0.6 }; + for (let i = 1; i <= steps; i++) { + const s = ease(i / steps), r = 1 - s; + let px = r * r * r * from.x + 3 * r * r * s * c1.x + 3 * r * s * s * c2.x + s * s * s * x; + let py = r * r * r * from.y + 3 * r * r * s * c1.y + 3 * r * s * s * c2.y + s * s * s * y; + if (i < steps) { px += rand(-0.7, 0.7); py += rand(-0.7, 0.7); } + await send(t.tabId, "Input.dispatchMouseEvent", { + type: "mouseMoved", x: Math.round(px * 100) / 100, y: Math.round(py * 100) / 100, modifiers, + button: buttons ? "left" : "none", buttons, + }); + t.mouse = { x: px, y: py }; + await sleep(rand(7, 17)); + } + t.mouse = { x, y }; +} + +const BUTTONS = { left: "left", right: "right", middle: "middle" }; +const BUTTON_BIT = { left: 1, right: 2, middle: 4 }; + +// click moves to (x, y), waits as a hand settles on the spot, and presses +// and lets go of the button (twice for a double click) +export async function click(t, x, y, opts = {}) { + const button = BUTTONS[opts.button] || "left"; + const modifiers = opts.modifiers || 0; + const count = opts.double ? 2 : 1; + await move(t, x, y, { modifiers }); + await sleep(clamp(gauss(110, 40), 45, 260)); + for (let i = 1; i <= count; i++) { + await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x, y, button, buttons: BUTTON_BIT[button], clickCount: i, modifiers }); + await sleep(clamp(gauss(80, 22), 40, 150)); + await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button, buttons: 0, clickCount: i, modifiers }); + if (i < count) await sleep(rand(70, 130)); + } +} + +// drag presses at one point, moves to the other with the button held and +// lets go there +export async function drag(t, p, q) { + await move(t, p.x, p.y); + await sleep(rand(80, 160)); + await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x: p.x, y: p.y, button: "left", buttons: 1, clickCount: 1 }); + try { + await sleep(rand(90, 180)); + await move(t, q.x, q.y, { buttons: 1 }); + await sleep(rand(80, 160)); + } finally { + await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x: q.x, y: q.y, button: "left", buttons: 0, clickCount: 1 }); + } +} + +// wheel scrolls by (dx, dy) at (x, y) a wheel notch at a time, the mouse +// moved there first +export async function wheel(t, x, y, dx, dy) { + if (!t.mouse || Math.hypot(t.mouse.x - x, t.mouse.y - y) > 40) await move(t, x, y); + const total = Math.abs(dx) + Math.abs(dy); + const notch = 100; + let n = Math.max(1, Math.round(total / notch)); + let left = { x: dx, y: dy }; + for (let i = 0; i < n; i++) { + const last = i === n - 1; + const sx = last ? left.x : Math.round(dx / n), sy = last ? left.y : Math.round(dy / n); + left = { x: left.x - sx, y: left.y - sy }; + await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: sx, deltaY: sy }); + // a flick turns a few notches quickly, then the finger comes back + await sleep(i % 4 === 3 ? rand(120, 260) : rand(28, 70)); + } +} + +// ---- keys ---------------------------------------------------------------- + +// a US layout: the key a character is on, and whether Shift is held +const SHIFTED = { "!": "1", "@": "2", "#": "3", "$": "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9", ")": "0", "_": "-", "+": "=", "{": "[", "}": "]", "|": "\\", ":": ";", "\"": "'", "<": ",", ">": ".", "?": "/", "~": "`" }; +const PUNCT = { "-": ["Minus", 189], "=": ["Equal", 187], "[": ["BracketLeft", 219], "]": ["BracketRight", 221], "\\": ["Backslash", 220], ";": ["Semicolon", 186], "'": ["Quote", 222], ",": ["Comma", 188], ".": ["Period", 190], "/": ["Slash", 191], "`": ["Backquote", 192], " ": ["Space", 32] }; + +// keyOf is the key a character is typed with on a US keyboard, or null +// when it isn't on one +export function keyOf(ch) { + let base = ch, shift = false; + if (/^[A-Z]$/.test(ch)) { base = ch.toLowerCase(); shift = true; } + else if (SHIFTED[ch]) { base = SHIFTED[ch]; shift = true; } + if (/^[a-z]$/.test(base)) return { key: ch, code: "Key" + base.toUpperCase(), keyCode: base.toUpperCase().charCodeAt(0), shift }; + if (/^[0-9]$/.test(base)) return { key: ch, code: "Digit" + base, keyCode: base.charCodeAt(0), shift }; + if (PUNCT[base]) return { key: ch, code: PUNCT[base][0], keyCode: PUNCT[base][1], shift }; + return null; +} + +// text typed through an input method: Chinese, Japanese, Korean +const IME = /[-ヿ㐀-䶿一-鿿豈-가- -〿-]/; + +async function shiftKey(t, down) { + await send(t.tabId, "Input.dispatchKeyEvent", { type: down ? "rawKeyDown" : "keyUp", key: "Shift", code: "ShiftLeft", windowsVirtualKeyCode: 16, modifiers: down ? 8 : 0 }); +} + +// the pause after a key: a typist is quicker inside a word than between +// words, and stops to think now and then; scaled down for a long text +function gap(ch, scale) { + let ms = clamp(gauss(105, 38), 38, 260); + if (ch === " ") ms += rand(10, 70); + else if (/[.,!?;:,。!?;:、]/.test(ch)) ms += rand(60, 220); + if (Math.random() < 0.035) ms += rand(250, 700); + return Math.max(10, ms * scale); +} + +// how long typing may take in all: the gateway waits 100s for a call +const TYPE_BUDGET_MS = 35000; + +// type types text into the focused element. newline is how a line break +// is typed there: "Shift+Enter" in a field where Enter sends (a chat box), +// "" where there are no lines (a one-line field drops it). +export async function type(t, text, opts = {}) { + const chars = [...String(text)]; + const est = chars.length * 120; + const scale = est > TYPE_BUDGET_MS ? TYPE_BUDGET_MS / est : 1; + const newline = opts.newline ?? "Shift+Enter"; + let held = false; + for (let i = 0; i < chars.length; i++) { + const ch = chars[i]; + if (ch === "\r") continue; + if (ch === "\n") { + if (held) { await shiftKey(t, false); held = false; } + if (newline) await opts.press(newline); + await sleep(gap(ch, scale)); + continue; + } + if (IME.test(ch)) { + if (held) { await shiftKey(t, false); held = false; } + // a word or two at a time: what an input method commits + let run = ch; + const len = Math.round(rand(1, 4)); + while (run.length < len && i + 1 < chars.length && IME.test(chars[i + 1])) run += chars[++i]; + await compose(t, run, scale); + await sleep(gap(run.slice(-1), scale) * 1.5); + continue; + } + const k = keyOf(ch); + if (!k) { + // an emoji or a letter no US key has: chosen from a picker, as a + // person enters one + if (held) { await shiftKey(t, false); held = false; } + await send(t.tabId, "Input.insertText", { text: ch }); + await sleep(gap(ch, scale) * 2); + continue; + } + if (k.shift !== held) { + await shiftKey(t, k.shift); + held = k.shift; + await sleep(rand(15, 45) * scale); + } + const mods = held ? 8 : 0; + await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyDown", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode, text: ch, unmodifiedText: k.shift ? ch : ch, modifiers: mods }); + // the key comes up while the next is already on its way down, now + // and then, as fingers roll + await sleep(clamp(gauss(55, 18), 18, 120) * Math.max(scale, 0.3)); + await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode, modifiers: mods }); + const next = chars[i + 1]; + if (held && !(next && keyOf(next) && keyOf(next).shift)) { await sleep(rand(10, 40) * scale); await shiftKey(t, false); held = false; } + await sleep(gap(ch, scale)); + } + if (held) await shiftKey(t, false); +} + +// compose enters text as an input method does: the keys go to it (key +// "Process"), the text under composition grows, and it is committed +async function compose(t, run, scale) { + const ime = (type) => send(t.tabId, "Input.dispatchKeyEvent", { type, key: "Process", code: "", windowsVirtualKeyCode: 229, nativeVirtualKeyCode: 229 }); + let ok = true; + for (let j = 1; j <= run.length && ok; j++) { + await ime("rawKeyDown"); + const part = run.slice(0, j); + ok = await send(t.tabId, "Input.imeSetComposition", { text: part, selectionStart: part.length, selectionEnd: part.length }).then(() => true, () => false); + await sleep(clamp(gauss(50, 15), 20, 100) * Math.max(scale, 0.3)); + await ime("keyUp"); + await sleep(clamp(gauss(140, 50), 50, 320) * scale); + } + await ime("rawKeyDown"); + await send(t.tabId, "Input.insertText", { text: run }); + await sleep(rand(20, 60) * Math.max(scale, 0.3)); + await ime("keyUp"); +} diff --git a/internal/browserext/ext/keys.js b/internal/browserext/ext/keys.js index 21e646da7..cd868dd0c 100644 --- a/internal/browserext/ext/keys.js +++ b/internal/browserext/ext/keys.js @@ -77,10 +77,14 @@ export async function press(t, combo) { const k = describe(keyName, !!(modifiers & 8)); const commands = []; if (mac && (modifiers & 4) && MAC_COMMANDS[k.key.toLowerCase()]) commands.push(MAC_COMMANDS[k.key.toLowerCase()]); + // held as a hand holds them: the modifiers a moment first, the key + // down for as long as a press lasts + const hold = (a, b) => sleep(a + Math.random() * (b - a)); let held = 0; for (const m of mods) { held |= MODS[m]; await send(t.tabId, "Input.dispatchKeyEvent", { type: "rawKeyDown", modifiers: held, key: m, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].keyCode }); + await hold(30, 80); } // a chord with Control, Alt or Meta types no text const typed = k.text && !(modifiers & 7); @@ -90,22 +94,11 @@ export async function press(t, combo) { ...(typed ? { text: k.text, unmodifiedText: k.text } : {}), ...(commands.length ? { commands } : {}), }); - await sleep(20); + await hold(50, 120); await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers, key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode }); for (const m of mods.reverse()) { + await hold(20, 60); held &= ~MODS[m]; await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers: held, key: m, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].keyCode }); } } - -// typeSlowly types text a key at a time, for a field that listens to -// each key (an autocomplete, a field that formats as you type). -export async function typeSlowly(t, text) { - for (const ch of String(text)) { - if (ch === "\n") { await press(t, "Enter"); continue; } - const k = /^[a-z0-9]$/i.test(ch) ? describe(ch.toLowerCase(), ch !== ch.toLowerCase()) : { key: ch, code: "", keyCode: 0, text: ch }; - await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyDown", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, text: k.text, unmodifiedText: k.text, modifiers: /[A-Z]/.test(ch) ? 8 : 0 }); - await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode }); - await sleep(30 + Math.random() * 50); - } -} diff --git a/internal/browserext/ext/manifest.json b/internal/browserext/ext/manifest.json index 3ee89a7c6..be316d5a8 100644 --- a/internal/browserext/ext/manifest.json +++ b/internal/browserext/ext/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 3, "name": "Magpie Browser", - "version": "0.1.5", + "version": "0.1.6", "description": "Lets the agents you run through Magpie use this browser: your tabs, signed in to the sites you use.", "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwjVk++2N/+l0PX53QSgXvBmDiyIOFXPDRTSo6l7HfM633QbDes2FXjS09l6hY33gsVX9eXE9O+94jQD2SVKSBn8V/EsL3f7mbNfkBqsZ4hYF3ogYxHUjJD6wjKHMFZQi54ArMZBI/psMUBbIjVTeuU9EGwnxoYU5umC8UHvEwkb4ZO0lprP3PGbHDjxrNi5fdFI8azVjyX0zlYlSw2wv0bCAZdkWuRoZWWgKdQwpdtRHrDQMnulWXT5DmNLYDpHgCreDrVaVLXzIAblSLOkZFo/T5xBiicmEbkWPbb8d3iE0OQStm1HYLdp4LLeKnnU6B7Kj/woOFt1uGIwoMqPzswIDAQAB", "minimum_chrome_version": "116", diff --git a/internal/browserext/ext/snapshot.js b/internal/browserext/ext/snapshot.js index 0509104df..e5267439c 100644 --- a/internal/browserext/ext/snapshot.js +++ b/internal/browserext/ext/snapshot.js @@ -2,7 +2,7 @@ // each element it can act on given a ref (e3) that stays the element's // from one snapshot to the next, for as long as the page keeps it. -import { fault, send } from "./cdp.js"; +import { evaluate, fault, read, resolve, send } from "./cdp.js"; const INTERACTIVE = new Set([ "button", "link", "textbox", "searchbox", "checkbox", "radio", "combobox", @@ -43,12 +43,14 @@ const CLICKABLE = `(() => { return out; })()`; -async function clickables(tabId) { +// run in magpie's isolated world: the page's scripts never see the scan +async function clickables(t) { + const tabId = t.tabId; const ids = new Set(); try { - const r = await send(tabId, "Runtime.evaluate", { expression: CLICKABLE, objectGroup: "magpie-snap" }); - if (!r.result || !r.result.objectId) return ids; - const props = await send(tabId, "Runtime.getProperties", { objectId: r.result.objectId, ownProperties: true }); + const r = await evaluate(t, CLICKABLE, "magpie-snap"); + if (!r || !r.objectId) return ids; + const props = await send(tabId, "Runtime.getProperties", { objectId: r.objectId, ownProperties: true }); await Promise.all(props.result.filter((p) => /^\d+$/.test(p.name) && p.value && p.value.objectId).map(async (p) => { try { const d = await send(tabId, "DOM.describeNode", { objectId: p.value.objectId }); @@ -115,9 +117,9 @@ export async function take(t, opts = {}) { const tabId = t.tabId; const [{ nodes }, clickable, inner, info] = await Promise.all([ send(tabId, "Accessibility.getFullAXTree"), - clickables(tabId), + clickables(t), frames(t), - send(tabId, "Runtime.evaluate", { expression: "[location.href, document.title]", returnByValue: true }).then((r) => r.result.value).catch(() => ["", ""]), + read(t, "[location.href, document.title]").catch(() => ["", ""]), ]); const [url, title] = info; // a new document starts its refs over; the same one keeps them @@ -285,17 +287,17 @@ export async function find(t, ref) { const r = t.refs.get(ref); if (!r) throw fault("STALE_REF", `ref ${ref} isn't in the latest snapshot of this tab: take a snapshot and use a ref from it`); try { - const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: r.backend, objectGroup: "magpie-act" }, r.sid); - const c = await send(t.tabId, "Runtime.callFunctionOn", { objectId: o.object.objectId, functionDeclaration: "function(){return this.isConnected}", returnByValue: true }, r.sid); - if (c.result.value) return { ...r, ref, objectId: o.object.objectId }; + const o = await resolve(t, r.backend, r); + const c = await send(t.tabId, "Runtime.callFunctionOn", { objectId: o.objectId, functionDeclaration: "function(){return this.isConnected}", returnByValue: true }, r.sid); + if (c.result.value) return { ...r, ref, objectId: o.objectId }; } catch {} // the page drew it again: the same role and name, if only one has it await take(t, { maxChars: 1 }); const same = [...t.refs].filter(([, v]) => v.role === r.role && v.name === r.name); if (same.length === 1) { const [nref, v] = same[0]; - const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: v.backend, objectGroup: "magpie-act" }, v.sid); - return { ...v, ref: nref, objectId: o.object.objectId }; + const o = await resolve(t, v.backend, v); + return { ...v, ref: nref, objectId: o.objectId }; } if (same.length > 1) throw fault("AMBIGUOUS", `${ref} (${r.role} "${r.name}") was redrawn and ${same.length} elements now match it: take a snapshot and pick one`); throw fault("STALE_REF", `${ref} (${r.role} "${r.name}") is no longer on the page: take a snapshot`); diff --git a/internal/gateway/browser_e2e_test.go b/internal/gateway/browser_e2e_test.go index 054b933f0..091bcb5bb 100644 --- a/internal/gateway/browser_e2e_test.go +++ b/internal/gateway/browser_e2e_test.go @@ -7,6 +7,7 @@ import ( "html" "image/jpeg" "io" + "math" "net/http" "net/http/httptest" "net/url" @@ -277,6 +278,9 @@ func realBrowserFrom(t *testing.T, ext func(*httptest.Server) string) (srv, site // behind another tab io.WriteString(w, `