An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(actions): add the form and keyboard actions
Shahriar46c1feec3e40
diff --git a/lib/actions/page/fill-input.ts b/lib/actions/page/fill-input.tsnew file mode 100644index 0000000..91a26f4--- /dev/null+++ b/lib/actions/page/fill-input.ts@@ -0,0 +1,43 @@+import { z } from 'zod';+import { ActionError, defineAction } from '../core';+import { describeElement, resolveTarget, targetSchema } from './dom';+import { keyboardInit } from './keyboard';++export const fillInput = defineAction({+ name: 'page.fillInput',+ description: 'Fill a text input, textarea, or contenteditable element like a user typing.',+ input: z.object({+ target: targetSchema.describe('Element to type into'),+ value: z.string().describe('Text to enter'),+ clear: z.boolean().default(true).describe('Replace existing content instead of appending'),+ pressEnter: z.boolean().default(false).describe('Press Enter afterwards, which submits many forms'),+ }),+ execute({ target, value, clear, pressEnter }) {+ const el = resolveTarget(target);+ el.focus();+ let next: string;+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {+ next = clear ? value : el.value + value;+ // React/Vue ignore direct .value writes on controlled inputs, so use the native prototype setter.+ const proto =+ el instanceof HTMLInputElement ? HTMLInputElement.prototype : HTMLTextAreaElement.prototype;+ Object.getOwnPropertyDescriptor(proto, 'value')!.set!.call(el, next);+ el.dispatchEvent(new InputEvent('input', { bubbles: true, data: value, inputType: 'insertText' }));+ el.dispatchEvent(new Event('change', { bubbles: true }));+ } else if (el.isContentEditable) {+ next = clear ? value : (el.textContent ?? '') + value;+ el.textContent = next;+ el.dispatchEvent(new InputEvent('input', { bubbles: true, data: value, inputType: 'insertText' }));+ } else {+ throw new ActionError(`<${el.tagName.toLowerCase()}> is not an editable element`, 'INVALID_TARGET');+ }+ if (pressEnter) {+ const enter = keyboardInit('Enter');+ const notPrevented = el.dispatchEvent(new KeyboardEvent('keydown', enter));+ el.dispatchEvent(new KeyboardEvent('keyup', enter));+ // A real Enter submits only when the keydown wasn't cancelled, and never from a textarea.+ if (notPrevented && !(el instanceof HTMLTextAreaElement)) el.closest('form')?.requestSubmit();+ }+ return { element: describeElement(el), value: next };+ },+});diff --git a/lib/actions/page/focus-input.ts b/lib/actions/page/focus-input.tsnew file mode 100644index 0000000..31adc4e--- /dev/null+++ b/lib/actions/page/focus-input.ts@@ -0,0 +1,38 @@+import { z } from 'zod';+import { defineAction } from '../core';+import { describeElement, resolveTarget, targetSchema } from './dom';++export const focusInput = defineAction({+ name: 'page.focusInput',+ description: 'Focus an input or editable element and place the caret, or select all its content.',+ input: z.object({+ target: targetSchema.describe('The input, textarea, or editable element to focus'),+ caret: z+ .enum(['start', 'end', 'all'])+ .default('end')+ .describe('Where to leave the caret, or select all content'),+ }),+ execute({ target, caret }) {+ const el = resolveTarget(target);+ el.focus();+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {+ if (caret === 'all') {+ el.select();+ } else {+ const position = caret === 'start' ? 0 : el.value.length;+ // Some input types (email, number) throw on setSelectionRange.+ try {+ el.setSelectionRange(position, position);+ } catch {}+ }+ } else if (el.isContentEditable) {+ const range = document.createRange();+ range.selectNodeContents(el);+ if (caret !== 'all') range.collapse(caret === 'start');+ const selection = getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ }+ return describeElement(el);+ },+});diff --git a/lib/actions/page/press-key.ts b/lib/actions/page/press-key.tsnew file mode 100644index 0000000..c94db94--- /dev/null+++ b/lib/actions/page/press-key.ts@@ -0,0 +1,51 @@+import { z } from 'zod';+import { defineAction } from '../core';+import { describeElement, resolveTarget, targetSchema } from './dom';+import { keyboardInit } from './keyboard';++export const pressKey = defineAction({+ name: 'page.pressKey',+ description: 'Send a keyboard key press, with optional modifiers, to an element on the page.',+ input: z.object({+ key: z.string().describe('DOM KeyboardEvent.key value, e.g. "Enter", "Escape", "ArrowDown", "a"'),+ modifiers: z+ .array(z.enum(['ctrl', 'shift', 'alt', 'meta']))+ .default([])+ .describe('Modifier keys held during the press'),+ target: targetSchema+ .optional()+ .describe('Element to receive the key; defaults to the currently focused element'),+ }),+ execute({ key, modifiers, target }) {+ const el = target+ ? resolveTarget(target)+ : ((document.activeElement as HTMLElement | null) ?? document.body);+ try {+ el.focus();+ } catch {}+ const init = keyboardInit(key, modifiers);+ const notPrevented = el.dispatchEvent(new KeyboardEvent('keydown', init));+ const printable = key.length === 1 && !init.ctrlKey && !init.metaKey;+ if (notPrevented && (printable || key === 'Enter')) {+ el.dispatchEvent(new KeyboardEvent('keypress', init));+ }+ if (printable && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) {+ const start = el.selectionStart ?? el.value.length;+ const end = el.selectionEnd ?? el.value.length;+ const next = el.value.slice(0, start) + key + el.value.slice(end);+ // Synthetic key events never insert text; write through the native value setter so+ // framework-controlled inputs (e.g. React) observe the change.+ const proto = el instanceof HTMLInputElement ? HTMLInputElement.prototype : HTMLTextAreaElement.prototype;+ Object.getOwnPropertyDescriptor(proto, 'value')?.set?.call(el, next);+ const caret = start + key.length;+ try {+ el.setSelectionRange(caret, caret);+ } catch {}+ el.dispatchEvent(new InputEvent('input', { bubbles: true, data: key, inputType: 'insertText' }));+ }+ el.dispatchEvent(new KeyboardEvent('keyup', init));+ // Synthetic Enter performs no default action; emulate implicit form submission from a single input.+ if (key === 'Enter' && notPrevented && el instanceof HTMLInputElement) el.form?.requestSubmit();+ return { key, modifiers, receivedBy: describeElement(el) };+ },+});diff --git a/lib/actions/page/select-option.ts b/lib/actions/page/select-option.tsnew file mode 100644index 0000000..91082e9--- /dev/null+++ b/lib/actions/page/select-option.ts@@ -0,0 +1,49 @@+import { z } from 'zod';+import { ActionError, defineAction } from '../core';+import { resolveTarget, targetSchema } from './dom';++export const selectOption = defineAction({+ name: 'page.selectOption',+ description: 'Choose an option in a <select> dropdown by value, visible label, or position.',+ input: z.object({+ target: targetSchema.describe('The select element'),+ value: z.string().optional().describe('Match by option value'),+ label: z.string().optional().describe('Match by visible option text, case-insensitive'),+ index: z.number().int().nonnegative().optional().describe('Match by option position'),+ }),+ execute({ target, value, label, index }) {+ const el = resolveTarget(target);+ if (!(el instanceof HTMLSelectElement)) {+ throw new ActionError(`Target <${el.tagName.toLowerCase()}> is not a <select>`, 'INVALID_TARGET');+ }+ const options = [...el.options];+ let option: HTMLOptionElement | undefined;+ if (value !== undefined) {+ option = options.find((opt) => opt.value === value);+ } else if (label !== undefined) {+ const needle = label.trim().toLowerCase();+ option = options.find((opt) => (opt.label || opt.text).trim().toLowerCase() === needle);+ } else if (index !== undefined) {+ option = options[index];+ } else {+ throw new ActionError('Provide a "value", "label", or "index" to choose', 'INVALID_INPUT');+ }+ if (!option) {+ const labels = options.slice(0, 20).map((opt) => (opt.label || opt.text).trim());+ throw new ActionError(+ `No option matches ${JSON.stringify({ value, label, index })}; options are: ${labels.join(', ')}`,+ 'TARGET_NOT_FOUND',+ );+ }+ // Set through the native setter so frameworks with controlled selects (React) see the change.+ Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(+ el,+ option.value,+ );+ el.dispatchEvent(new Event('input', { bubbles: true }));+ el.dispatchEvent(new Event('change', { bubbles: true }));+ return {+ selected: { value: option.value, label: option.label || option.text, index: option.index },+ };+ },+});diff --git a/lib/actions/page/select-text.ts b/lib/actions/page/select-text.tsnew file mode 100644index 0000000..73e7e04--- /dev/null+++ b/lib/actions/page/select-text.ts@@ -0,0 +1,76 @@+import { z } from 'zod';+import { ActionError, defineAction } from '../core';+import { isVisible, resolveTarget, targetSchema } from './dom';++export const selectText = defineAction({+ name: 'page.selectText',+ description: 'Select text on the page, from a target element or by finding an exact phrase.',+ input: z.object({+ target: targetSchema.optional().describe('Element whose entire text content to select'),+ search: z.string().optional().describe('Exact text to find and select, case-insensitive'),+ occurrence: z+ .number()+ .int()+ .nonnegative()+ .default(0)+ .describe('Which match to select when the text appears multiple times'),+ }),+ execute({ target, search, occurrence }) {+ if (Boolean(target) === Boolean(search)) {+ throw new ActionError('Provide either "target" or "search"', 'INVALID_INPUT');+ }+ const range = document.createRange();+ if (target) {+ range.selectNodeContents(resolveTarget(target));+ } else if (search) {+ const segments = visibleTextSegments();+ const flat = segments.map((s) => s.node.data).join('');+ const needle = search.toLowerCase();+ let hit = -1;+ for (let from = 0, i = 0; i <= occurrence; i++) {+ hit = flat.toLowerCase().indexOf(needle, from);+ if (hit === -1) break;+ from = hit + 1;+ }+ if (hit === -1) {+ throw new ActionError(`Text "${search}" not found on the page`, 'TARGET_NOT_FOUND');+ }+ range.setStart(...pointAt(segments, hit));+ range.setEnd(...pointAt(segments, hit + search.length));+ }+ const selection = getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ const anchor = range.startContainer;+ (anchor instanceof Element ? anchor : anchor.parentElement)?.scrollIntoView({ block: 'center' });+ return { selectedText: (selection?.toString() ?? '').slice(0, 500) };+ },+});++interface Segment {+ node: Text;+ start: number;+}++function visibleTextSegments(): Segment[] {+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);+ const segments: Segment[] = [];+ let offset = 0;+ let node: Text | null;+ while ((node = walker.nextNode() as Text | null)) {+ const parent = node.parentElement;+ if (!parent || parent.closest('script,style') || !isVisible(parent)) continue;+ segments.push({ node, start: offset });+ offset += node.data.length;+ }+ return segments;+}++/** Map an offset in the concatenated text back to a (node, offset) DOM point. */+function pointAt(segments: Segment[], offset: number): [Text, number] {+ for (const seg of segments) {+ if (offset <= seg.start + seg.node.data.length) return [seg.node, offset - seg.start];+ }+ const last = segments[segments.length - 1];+ return [last.node, last.node.data.length];+}diff --git a/lib/actions/page/submit-form.ts b/lib/actions/page/submit-form.tsnew file mode 100644index 0000000..2fc4212--- /dev/null+++ b/lib/actions/page/submit-form.ts@@ -0,0 +1,33 @@+import { z } from 'zod';+import { ActionError, defineAction } from '../core';+import { cssPath, resolveTarget, targetSchema } from './dom';++export const submitForm = defineAction({+ name: 'page.submitForm',+ description: 'Submit a form, firing its submit event and validation as if the user pressed Enter.',+ input: z.object({+ target: targetSchema+ .optional()+ .describe('The form, or any element inside it; defaults to the first form on the page'),+ }),+ execute({ target }) {+ const form = target+ ? resolveTarget(target).closest('form')+ : document.querySelector('form');+ if (!form) {+ throw new ActionError('No form found to submit', 'TARGET_NOT_FOUND');+ }+ // requestSubmit runs validation and submit handlers; form.submit() bypasses both.+ if (typeof form.requestSubmit === 'function') {+ form.requestSubmit();+ } else {+ form.submit();+ }+ // Read attributes, not the IDL props: a control named "action"/"method" shadows them with a DOM node.+ return {+ form: cssPath(form),+ action: form.getAttribute('action') || undefined,+ method: (form.getAttribute('method') || 'get').toLowerCase(),+ };+ },+});