API reference.
Complete reference for @isoldex/sentinel. For a guided introduction, see the Getting Started docs.
Sentinel class
The main class. Wraps a Playwright browser instance, manages the LLM provider, and exposes all automation methods.
new Sentinel(options)
import { Sentinel } from '@isoldex/sentinel';
const sentinel = new Sentinel({
apiKey: process.env.GEMINI_API_KEY!,
headless: true,
browser: 'chromium',
verbose: 1,
enableCaching: true,
});
await sentinel.init();
// ...
await sentinel.close();sentinel.init()
Launches the managed browser and creates its context. Call before managed navigation and actions; extend(page) attaches to a caller-owned page without init(). Returns Promise<void>.
sentinel.goto(url)
Navigates through the Sentinel driver, invalidates cached state and attempts blocker recovery. Use sentinel.page.goto(url, options) when you need Playwright navigation options.
sentinel.close()
Closes all pages, the browser context, and the browser. Always call in a finally block.
Static methods
Sentinel.parallel(tasks, options)
const results = await Sentinel.parallel(
[
{ url: 'https://site-a.com', goal: 'Extract product name and price' },
{ url: 'https://site-b.com', goal: 'Extract product name and price' },
],
{
apiKey: process.env.GEMINI_API_KEY!,
concurrency: 2,
headless: true,
}
);
// results: ParallelResult[]
results.forEach((r) => {
if (r.success) console.log(r.data);
else console.error(r.error);
});act()
Executes a single natural-language action. Returns an ActionResult.
sentinel.act(instruction, options?)
const clickResult = await sentinel.act('click the login button');
const result = await sentinel.act('fill email with %email%', {
variables: { email: 'user@example.com' },
retries: 2, // retries after the first attempt (3 attempts total)
});
console.log(clickResult.success);
console.log(result.success, result.message);
console.log(result.selector); // optional CSS selector
if (!result.success) console.log(result.attempts); // optional ActionAttempt[]All action types
// All supported action types:
await sentinel.act('click the submit button');
await sentinel.act('fill the email field with user@example.com');
await sentinel.act('append " (edited)" to the title field');
await sentinel.act('hover over the user avatar');
await sentinel.act('press Enter');
await sentinel.act('select "Germany" from the country dropdown');
await sentinel.act('double-click the image');
await sentinel.act('right-click the file row');
await sentinel.act('scroll down 300 pixels');
await sentinel.act('scroll up');
await sentinel.act('scroll to the footer');extract()
Extracts structured data from the current page. Accepts a Zod schema or a JSON Schema object. Returns the typed extracted data directly (not wrapped in a result object).
sentinel.extract(instruction, schema)
import { z } from 'zod';
// With Zod schema (recommended — gives full TypeScript inference)
const product = await sentinel.extract(
'Extract product name, price, and rating',
z.object({
name: z.string(),
price: z.string(),
rating: z.number(),
})
);
// product is typed as { name: string; price: string; rating: number }
console.log(product.name);
// With plain JSON schema
const raw = await sentinel.extract(
'Extract all review titles',
{ type: 'object', properties: { titles: { type: 'array', items: { type: 'string' } } } }
);observe()
Returns an ObserveResult[] array of suggested interactions, with descriptions and optional selectors, methods and arguments. Useful for debugging, building dynamic agents, or deciding what action to take next.
sentinel.observe(instruction?)
const elements = await sentinel.observe();
const checkoutActions = await sentinel.observe('find buttons in the checkout section');
// ObserveResult[]: description plus optional selector, method and arguments.
for (const action of checkoutActions) {
console.log(action.description, action.selector, action.method);
}run() — Agent
Runs an autonomous agent loop. The agent plans, executes, verifies, and reflects until the goal is achieved or maxSteps is exceeded. Includes built-in loop detection.
sentinel.run(goal, options?)
const controller = new AbortController();
const result = await sentinel.run('Find the cheapest laptop under €500', {
maxSteps: 25,
timeoutMs: 60_000,
signal: controller.signal,
onStep: (event) => {
console.log(event.stepNumber, event.type, event.instruction);
console.log(event.success, event.pageUrl, event.reasoning);
},
});
console.log(result.goalAchieved, result.totalSteps, result.message);
console.log(result.aborted); // true when the supplied signal cancelled the run
console.log(result.data, result.selectors, result.history);runStream(goal, options?)
Returns an AsyncGenerator of AgentStepEvent values followed by a final AgentResult. Breaking or throwing out of the loop cancels the background run and waits for its current step to unwind. Both run() and runStream() check cancellation between steps and after planning; they do not forcibly interrupt an in-flight provider call.
for await (const event of sentinel.runStream('Extract the top stories', {
maxSteps: 15,
timeoutMs: 60_000,
})) {
if ('stepNumber' in event) console.log(event.stepNumber, event.instruction);
else console.log(event.goalAchieved, event.data);
}fillForm(data, options?)
Maps a Record<string, unknown> to form fields and returns Promise<AgentResult>. Accepts the same AgentRunOptions as run(): maxSteps, onStep, timeoutMs and signal.
const controller = new AbortController();
const result = await sentinel.fillForm({ name: 'Alice', country: 'Austria' }, {
maxSteps: 10,
timeoutMs: 30_000,
signal: controller.signal,
});
console.log(result.success, result.aborted);intercept<T>(urlPattern, trigger)
Captures matching response bodies while trigger runs and returns Promise<T[]>. A pattern without wildcards is a literal substring; wildcard patterns support ** (including slashes), * (except slashes) and ? (one non-slash character).
const responses = await sentinel.intercept('graphql', async () => {
await sentinel.act('Click the search button');
});
console.log(responses);Session & Navigation
Session persistence (cookies + localStorage)
import { Sentinel } from '@isoldex/sentinel';
const sessionPath = './sessions/github.json';
const sentinel = new Sentinel({
apiKey: process.env.GEMINI_API_KEY!,
sessionPath, // loaded on init() when the file exists
});
await sentinel.init();
await sentinel.goto('https://github.com/login');
if (await sentinel.page.locator('input[type="password"]').isVisible()) {
await sentinel.act('fill username with %user%', {
variables: { user: process.env.GITHUB_USER! },
});
await sentinel.act('fill password with %password%', {
variables: { password: process.env.GITHUB_PASS! },
});
await sentinel.act('click sign in');
// Complete any required authentication before saving.
await sentinel.saveSession(sessionPath);
}
await sentinel.close();userDataDir — IndexedDB / Service Workers
// Persist IndexedDB, WebSQL, Service Workers (e.g. WhatsApp Web, Notion)
const sentinel = new Sentinel({
apiKey: process.env.GEMINI_API_KEY!,
userDataDir: './profiles/whatsapp',
});
await sentinel.init();
await sentinel.goto('https://web.whatsapp.com');
// QR scan only needed on first run| Property | Type | Default | Description |
|---|---|---|---|
| saveSession(filePath) | Promise<void> | — | Writes cookies and localStorage to the required file path; sessionPath loads this file on init(). |
Tab management
sentinel.newTab / switchTab / closeTab / tabCount
const tabIndex = await sentinel.newTab('https://example.com');
await sentinel.switchTab(0);
await sentinel.switchTab(tabIndex);
console.log(sentinel.tabCount); // synchronous number getter
await sentinel.closeTab(tabIndex); // index is required| Property | Type | Default | Description |
|---|---|---|---|
| newTab(url?) | Promise<number> | — | Returns the index of the new tab. |
| switchTab(index) | Promise<void> | — | Activates a tab by numeric index. |
| closeTab(index) | Promise<void> | — | Closes the tab at the required numeric index. |
| tabCount | number | — | Synchronous getter for the number of open tabs. |
Record & Replay
Record actions, export as TypeScript or JSON
sentinel.startRecording('login-flow'); // synchronous
await sentinel.goto('https://github.com');
await sentinel.act('click Sign in');
const workflow = sentinel.stopRecording(); // RecordedWorkflow object
const code = sentinel.exportWorkflowAsCode(workflow); // TypeScript string
const json = sentinel.exportWorkflowAsJSON(workflow); // JSON string
await sentinel.replay(workflow);| Property | Type | Default | Description |
|---|---|---|---|
| startRecording(name?) | void | — | Begins recording navigation and successful actions. |
| stopRecording() | RecordedWorkflow | — | Stops and returns the recorded workflow object. |
| exportWorkflowAsCode(workflow) | string | — | Converts a workflow object into TypeScript source. |
| exportWorkflowAsJSON(workflow) | string | — | Serializes a workflow object as JSON. |
| replay(workflow) | Promise<void> | — | Replays the supplied workflow object. |
Vision
When visionFallback: true is set, Sentinel automatically falls back to screenshot-based grounding when the accessibility tree fails to locate an element (Canvas, complex Shadow DOM, non-standard widgets).
sentinel.screenshot() / describeScreen()
// Enable vision grounding (screenshot fallback for Canvas / Shadow DOM)
const sentinel = new Sentinel({
apiKey: process.env.GEMINI_API_KEY!,
visionFallback: true,
});
// Take a screenshot (returns Buffer)
const buf = await sentinel.screenshot();
// Describe current screen state
const description = await sentinel.describeScreen();
console.log(description);
// "A checkout page with a total of €349 visible in the top right..."| Property | Type | Default | Description |
|---|---|---|---|
| screenshot() | Promise<Buffer> | — | Takes a full-page screenshot and returns the PNG buffer. |
| describeScreen() | Promise<string> | — | Returns an LLM-generated natural-language description of the current viewport. |
Page extension
sentinel.extend(page) enriches an existing Playwright Page object with AI methods without creating a new browser instance. Ideal for incremental adoption in existing Playwright test suites.
sentinel.extend(page)
import { chromium } from 'playwright';
import { Sentinel, z } from '@isoldex/sentinel';
const browser = await chromium.launch();
const page = await browser.newPage();
const sentinel = new Sentinel({ apiKey: process.env.GEMINI_API_KEY! });
// Use the returned ExtendedPage to get the additional TypeScript methods.
const ai = await sentinel.extend(page);
try {
await page.goto('https://example.com');
const data = await ai.extract('get the page title', z.object({ title: z.string() }));
console.log(data.title);
} finally {
await browser.close(); // caller owns the supplied browser
}Events & token tracking
sentinel.on() / getTokenUsage() / exportLogs()
sentinel.on('action', (event) => {
console.log(event.instruction, event.result.success);
});
sentinel.on('navigate', (event) => console.log(event.url));
sentinel.on('close', () => console.log('Browser closed'));
const usage = sentinel.getTokenUsage();
console.log(usage.totalInputTokens, usage.totalOutputTokens, usage.totalTokens);
console.log(usage.estimatedCostUsd, usage.pricingKnown);
// Unknown model pricing is not a reliable zero-cost estimate.
sentinel.exportLogs('./session-costs.json'); // writes JSON; returns void| Property | Type | Default | Description |
|---|---|---|---|
| on('action', cb) | this | — | EventEmitter listener; receives { instruction, result: ActionResult }. |
| on('navigate', cb) | this | — | Receives { url } after navigation. |
| on('close', cb) | this | — | Fires when the browser closes. |
| getTokenUsage() | ReturnType<Sentinel['getTokenUsage']> | — | Totals, per-operation entries, estimatedCostUsd and pricingKnown. |
| exportLogs(filePath) | void | — | Writes token usage JSON to the required path. |
| sentinel.page | Page | — | Underlying Playwright page. |
| sentinel.context | BrowserContext | — | Underlying Playwright browser context. |
SentinelOptions
| Property | Type | Default | Description |
|---|---|---|---|
| apiKey | string | — | Gemini key, required only when provider is absent; also needed for plannerModel. |
| provider | LLMProvider | Gemini | Custom provider with its own credentials; no dummy apiKey needed. |
| headless | boolean | false | Library browser mode. MCP and the test fixture default to headless. |
| browser | 'chromium' | 'firefox' | 'webkit' | 'chromium' | CDP/AOM requires Chromium. |
| viewport | { width: number; height: number } | 1920×1080 | Browser viewport. |
| verbose | 0 | 1 | 2 | 3 | 1 | 0 silent, 1 key actions, 2 reasoning, 3 full debug. |
| enableCaching | boolean | true | Cache parsed page state between calls; separate from locator and prompt caches. |
| mode | 'aom' | 'hybrid' | 'vision' | 'aom' | Element detection strategy. |
| visionFallback | boolean | false | Deprecated alias; prefer mode: hybrid. |
| plannerModel | string | — | Separate Gemini planning model; requires apiKey. |
| plannerProvider | LLMProvider | — | Custom provider used for planning. |
| mfa | { type: 'totp'; secret: string; digits?: number; period?: number } | — | TOTP configuration. |
| sessionPath | string | — | Session file to load on init() if it exists. |
| userDataDir | string | — | Persistent browser profile; takes precedence over sessionPath. |
| proxy | ProxyOptions | IProxyProvider | — | Static proxy or dynamic proxy provider. |
| humanLike | boolean | false | Human-like input delays. |
| stealth | boolean | false | Optional playwright-extra and puppeteer-extra-plugin-stealth integration. |
| domSettleTimeoutMs | number | 5000 | DOM settling budget, internally capped at 8000 ms. |
| locatorCache | boolean | string | false | Successful locators, scoped by URL/instruction; string persists to disk. |
| promptCache | boolean | string | false | LLM response cache; string persists to disk. |
| patternCache | boolean | string | true | Widget interaction patterns; string persists to disk. |
| maxElements | number | 50 | Target budget for relevant page elements supplied to act(). |
| maxTokens | number | — | Cumulative token budget; checked on subsequent model calls. |
| maxCostUsd | number | — | Estimated cost budget; inspect pricingKnown for unpriced models. |
| rateLimit | number | — | Per-host navigation requests per second; omitted or 0 disables. |
| logFormat | false | true | string | false | Plain text, JSON stdout or JSON log-file path. |
| logger | Logger | — | Custom logging sink; overrides logFormat. |
| costAuditPath | string | — | Persist token costs. parallel() writes a separate numbered file per task. |
| captcha | 'auto' | 'skip' | 'manual' | { strategy; timeoutMs? } | 'auto' | CAPTCHA strategy; manual requires a visible browser. |
ActOptions
| Property | Type | Default | Description |
|---|---|---|---|
| variables | Record<string, string> | — | Substitute %name% placeholders. Use for secrets so locator/pattern caches retain placeholders. |
| retries | number | 2 | Retries after the initial attempt; default allows 3 attempts total. |
| previousFailures | string[] | — | Verifier feedback, normally populated internally for replanning. |
ActionResult
| Property | Type | Default | Description |
|---|---|---|---|
| success | boolean | — | Whether the requested action succeeded. |
| message | string | — | Human-readable outcome. |
| action | string | undefined | — | Technical action label, when available. |
| selector | string | undefined | — | CSS selector when one could be derived. |
| attempts | ActionAttempt[] | undefined | — | Optional failure diagnostics: { path, error }, not a numeric attempt count. |
AgentRunOptions
| Property | Type | Default | Description |
|---|---|---|---|
| maxSteps | number | 15 | Maximum agent steps. |
| timeoutMs | number | — | Wall-clock budget, checked between steps and after planning. |
| signal | AbortSignal | — | Cancel before further actions; in-flight calls finish unwinding. |
| onStep | (event: AgentStepEvent) => void | — | Progress callback. |
AgentStepEvent
| Property | Type | Default | Description |
|---|---|---|---|
| stepNumber | number | — | 1-based step number. |
| type | 'act' | 'extract' | — | Kind of step. |
| instruction | string | — | Instruction executed. |
| reasoning | string | — | Planning explanation. |
| success | boolean | — | Step outcome. |
| pageUrl / pageTitle | string | — | Page context for the step. |
| data | any (optional) | — | Data extracted during this step. |
AgentResult
| Property | Type | Default | Description |
|---|---|---|---|
| success | boolean | — | Whether the run succeeded; cancellation returns false. |
| goalAchieved | boolean | — | Whether the final goal was achieved. |
| totalSteps | number | — | Number of executed steps. |
| message | string | — | Outcome, stop or timeout explanation. |
| aborted | boolean | undefined | — | true when cancelled via AbortSignal. |
| history | AgentStepEvent[] | — | Step-by-step history. |
| data | any (optional) | — | Extracted payload. |
| selectors | Record<string, string> | undefined | — | Derived selectors for successful actions. |
ParallelTask / ParallelResult / ParallelOptions
ParallelTask
| Property | Type | Default | Description |
|---|---|---|---|
| url | string | — | Starting URL. |
| goal | string | — | Goal for this session. |
| maxSteps | number | 15 | Per-task step limit. |
ParallelResult
| Property | Type | Default | Description |
|---|---|---|---|
| index | number | — | Position in the input tasks array. |
| url / goal | string | — | Original task. |
| success / goalAchieved | boolean | — | Run outcome. |
| totalSteps | number | — | Executed steps. |
| message | string | — | Outcome explanation. |
| data | unknown (optional) | — | Extracted payload. |
| error | string | undefined | — | Unhandled task error, if any. |
ParallelOptions
| Property | Type | Default | Description |
|---|---|---|---|
| concurrency | number | 3 | Maximum simultaneous browser sessions. |
| onProgress | (completed, total, result) => void | — | Called whenever a task finishes. |
| ...SentinelOptions | SentinelOptions | — | parallel() accepts SentinelOptions & ParallelOptions. Each worker gets its own browser and numbered cost audit file. |
ProxyOptions
| Property | Type | Default | Description |
|---|---|---|---|
| server | string | — | Proxy server URL, e.g. 'http://proxy.example.com:8080'. |
| username | string | — | Proxy authentication username. |
| password | string | — | Proxy authentication password. |
| bypass | string | — | Comma-separated list of hosts to bypass the proxy for. |
LLMProvider interface
Implement this interface to use any LLM with Sentinel. Pass the instance as provider in SentinelOptions.
import { z } from '@isoldex/sentinel';
// These structural helper shapes are shown here for reference.
type SchemaInput<T> = z.ZodType<T> | Record<string, unknown>;
type GenerateOptions = { systemInstruction?: string; maxOutputTokens?: number };
type TokenUsage = { inputTokens: number; outputTokens: number; totalTokens: number; estimatedCostUsd?: number };
interface LLMProvider {
generateStructuredData<T>(prompt: string, schema: SchemaInput<T>, options?: GenerateOptions): Promise<T>;
generateText(prompt: string, systemInstruction?: string): Promise<string>;
analyzeImage?(prompt: string, imageBase64: string, mimeType?: string): Promise<string>;
onTokenUsage?: (usage: TokenUsage) => void;
readonly modelName?: string; // enables model-specific cost accounting
}See the LLM Providers page for built-in implementations (GeminiProvider, OpenAIProvider, ClaudeProvider, OllamaProvider).
Error classes
All errors extend SentinelError which extends the native Error.
Error hierarchy
import { SentinelError, CaptchaDetectedError } from '@isoldex/sentinel';
try {
const result = await sentinel.act('click the checkout button');
if (!result.success) console.error(result.message, result.attempts);
} catch (error) {
// Operational failures (provider, browser, CAPTCHA, budgets) may throw.
if (error instanceof CaptchaDetectedError) console.error(error.type);
else if (error instanceof SentinelError) console.error(error.code, error.context);
else throw error;
}| Property | Type | Default | Description |
|---|---|---|---|
| SentinelError | class | — | Base class. All Sentinel errors extend this. |
| ActionError | class | — | Typed action failure; carries code and optional context. act() also returns success: false for ordinary unsuccessful attempts. |
| ExtractionError | class | — | Thrown when extract() cannot parse the LLM response into the requested schema. |
| NavigationError | class | — | Thrown on navigation failure (timeout, network error, invalid URL). |
| AgentError | class | — | Agent error type. Step limits and loop detection normally return an unsuccessful AgentResult. |
| NotInitializedError | class | — | Initialization error type. Some methods throw a plain Error when used before init(). |