# Kitsune docs ## Challenge records URL: /docs/concepts/challenges Understand the challenge verdict and the record fields that explain it. # Challenge records A `challenge` verdict means the page showed an interstitial or an unresolved verification widget. A `blocked` verdict can come from an HTTP access error or recognized text on the page. ## Read the record - `reason` describes what Kitsune detected. - `meta.matched`, when present, identifies the marker or widget kind. - `meta.attempt` identifies the browser attempt that produced the record. The CLI counts `blocked` and `challenge` toward its rejection rate. See [Result records](/docs/reference/records) for the other verdicts. ## Plugin handling A session can have one active [solver plugin](/docs/guides/solvers). The plugin host hands an eligible browser challenge to that plugin. Generic interstitials can remain `challenge`. Use the [Plugin API](/docs/reference/plugin-api#challenges-and-results) to interpret hook results. --- ## How a crawl works URL: /docs/concepts/how-it-works Follow a URL from transport and extraction to a result record. # How a crawl works `kit.crawl()` and the CLI return a [result record](/docs/reference/records) with the source URL, extraction tier, verdict, reason, and any data. ## Choose a transport 1. A matching site plugin can handle the URL with its own crawl function. 2. Otherwise, Kitsune tries HTTP. If the response contains enough useful content, it returns the HTTP result. 3. Kitsune opens the page in Chrome when the response needs rendering or the recipe requires the browser. A recipe with a form query or `forceBrowser: true` starts here. The browser may retry a failed attempt with a longer settle time. Its final result identifies the extraction path, such as `browser:selectors`. ## Extract and classify Chrome reads the fields or expression in the [recipe](/docs/guides/recipes), or extracts common page data such as text, headings, and links. When a selector recipe returns nothing, Kitsune can return generic data under `browser:auto-fallback`. Read `verdict` together with `tier`. An `ok` verdict says the returned data was usable at that tier. A fallback record can be `ok` and still lack your recipe’s fields. ## Pacing Each session tracks a delay per host. `Kitsune.launch({ paceMs })` sets the starting delay in code. Failures increase the delay and successful crawls bring it back toward the starting value. See [CLI environment variables](/docs/reference/cli#environment) for the current behavior of CLI pacing configuration. --- ## Write a plugin URL: /docs/concepts/plugins Add a hook that tags browser crawl records. # Write a plugin Plugins extend a session with named hooks. This example uses a `record` hook to tag the output for downstream processing. ## Writing one Create `packages/kitsune/stamp.ts`: ```ts import { definePlugin } from './src/index.ts' export default definePlugin({ name: 'example:stamp', record: (record) => ({ ...record, meta: { ...record.meta, source: 'example' }, }), }) ``` From the repository root: ```bash bun run kitsune crawl https://example.com --selector a --plugin ./stamp.ts --json ``` Look for `"source":"example"` in the record’s `meta`. The CLI resolves `./stamp.ts` from `packages/kitsune`. The example uses `--selector` to open Chrome because `record` hooks run on browser and site plugin results. ## Loading one Pass plugins to `Kitsune.launch({ plugins: [plugin] })` from TypeScript. With the CLI, repeat `--plugin` for each module or set `KITSUNE_PLUGINS` to a comma-separated list. Each module default-exports a plugin or a factory. ## Choose a hook - Use `setup` and `close` for session resources. - Use `response` to observe browser attempts and `record` to change the final browser or site plugin result. - Use `site` when matching URLs need a custom crawl flow. The [Plugin API](/docs/reference/plugin-api) lists each callback, its inputs, and when it runs. --- ## Getting started URL: /docs/getting-started Run your first CLI crawl and find the result it writes. # Getting started ## 1. Set up Kitsune You’ll need Bun 1.3+ and Google Chrome in `/Applications` on macOS. The CLI launches Chrome at startup, even when the page can be fetched over HTTP. From the Kitsune checkout: ```bash bun install ``` ## 2. Crawl a page From the repository root: ```bash bun run kitsune crawl https://example.com ``` Look for a result marked `OK` with the tier `[http]`. Kitsune found content in the HTTP response. ## 3. Extract a field Pass a CSS selector to read a specific element in Chrome: ```bash bun run kitsune crawl https://example.com --selector a --json ``` The first output line is a JSON record. Its `data.value` contains the first link’s text, currently `Learn more`. Each command also writes a JSONL file under `packages/kitsune/kitsune-results/`. The `results:` line gives the exact path. ## Next steps - [Use Kitsune in TypeScript](/docs/typescript) to work with a record in code. - [Extract data with recipes](/docs/guides/recipes) to reuse a set of fields. - [Troubleshoot a crawl](/docs/guides/debugging) if setup or extraction fails. --- ## Automate browser actions URL: /docs/guides/browser-control Fill a field, click a button, and read a result with Kitsune. # Automate browser actions Use the browser methods when a page needs input before it shows the data you want. This example works with a self-contained page. ## Fill and submit a form After [setting up Kitsune](/docs/typescript), save this as `browser.ts` at the repository root: ```ts import { Kitsune } from 'kitsune' const page = `
` const kit = await Kitsune.launch() try { await kit.goto('data:text/html,' + encodeURIComponent(page)) await kit.type('input[name="name"]', 'Kitsune') await kit.click('button[type="submit"]') if (!(await kit.waitForText('Kitsune', 5_000))) { throw new Error('The form did not show a result') } console.log(await kit.text('output')) } finally { await kit.close() } ``` Run `bun run browser.ts`. It prints `Kitsune` after the form updates. ## Wait for a result `goto()` waits for the page load event, then settles for two seconds by default. For content that appears after an action, use `waitFor(selector)` or `waitForText(text)`. Both return `false` on timeout, so check the return value before reading. ## The error Before an action like `click()` or `type()`, Kitsune checks that the element can receive input. If it times out, the error gives the selector and the check that failed, such as `visible`, `enabled`, or `unobscured`. Inspect the matching element in Chrome and check for overlays or disabled controls. See the [Kitsune API](/docs/reference/kit-api) for screenshots, files, frames, and other browser methods. --- ## Troubleshoot a crawl URL: /docs/guides/debugging Check Chrome setup, inspect a page, and interpret a failed extraction. # Troubleshoot a crawl Start with the record’s `verdict` and `reason`. If the reason is `error`, read the `error` field for the underlying message. ## Check the environment ```bash bun run kitsune doctor ``` Check the `chrome` line first. Kitsune expects Google Chrome in `/Applications` on macOS. Proxy and plugin checks matter only when your run uses those features. ## Inspect the page ```bash bun run kitsune probe https://example.com ``` Compare the HTTP status with the final browser URL and page summary. This can show a redirect, an empty page, or content that only appears after Chrome loads the page. ## Find the next check | What you see | Where to look | | --- | --- | | `empty` with `selector empty` | Test the CSS selector in DevTools on the rendered page. | | `ok` with `browser:auto-fallback` | The page has content, but the recipe fields were empty. Check the selectors and the `each` container. | | `empty` with `thin body (js shell?)` | Use `probe` to see what rendered. If the page changes after an action, wait for the content with [browser control](/docs/guides/browser-control). | | `challenge` or `blocked` | Check the reported marker and confirm the site allows automated access. See [Challenge records](/docs/concepts/challenges). | | `chrome: no page target` | Close any other Kitsune session using the same [debugging port](/docs/reference/cli#commands-and-writes). | | A proxy error | Check the address, credentials, and [destination port policy](/docs/guides/proxies#port-restrictions). | See [Result records](/docs/reference/records) for all verdicts and tiers. --- ## Proxy configuration URL: /docs/guides/proxies Configure a network proxy for a Kitsune session. # Proxy configuration To route a crawl through a proxy on your network, set `PROXY_URL` for the CLI or pass a proxy to `Kitsune.launch({ proxy })`. Keep credentials in environment variables. ## Formats | Form | Example | | --- | --- | | URL | `http://user:pass@proxy.example:8080` | | SOCKS URL | `socks5://user:pass@proxy.example:1080` | | Auth shorthand | `user:pass@proxy.example:8080` or `proxy.example:8080@user:pass` | | Colon-separated | `proxy.example:8080:user:pass` or `user:pass:proxy.example:8080` | | Host and port | `proxy.example:8080` | The default scheme is HTTP. Percent-encode reserved characters in credentials when you use URL syntax. ## Lists and precedence A command-line `--proxy SPEC` takes precedence. The CLI checks `PROXY_URL`, `PROXIES`, then `PROXY_LIST` when the flag is absent. Lists accept newlines, commas, semicolons, or a JSON array. Each launched browser session selects one entry. ## Port restrictions A proxy can respond to a general connectivity check while refusing a particular destination port. Confirm that your network policy allows the host and port you’re trying to reach. `bun run kitsune doctor` checks connectivity through the proxy against a test endpoint on port 443. --- ## Extract data with recipes URL: /docs/guides/recipes Save a named set of CSS selectors and reuse it from the CLI. # Extract data with recipes A recipe gives names to the fields you want to extract. Use it when `--selector` is too limited or the same page layout appears at several URLs. ## Save a recipe Create `packages/kitsune/recipes/example-domain.json`: ```json { "name": "example-domain", "match": ["example.com"], "forceBrowser": true, "extract": { "mode": "selectors", "fields": { "link": "a", "description": "p" }, "attr": { "link": "href" } } } ``` From the repository root, run: ```bash bun run kitsune crawl https://example.com --recipe example-domain --json ``` Look for `tier: "browser:selectors"` and a URL in `data.link`. With `match` set, the CLI also picks the recipe automatically for matching hosts. When several recipes match, the longest match string wins. ## Extract a list Set `each` to the selector for a row or card. Kitsune resolves each field inside that element. Use `attr` for fields whose values come from an attribute: ```json { "mode": "selectors", "each": ".article", "fields": { "title": "h2", "url": "a" }, "attr": { "url": "href" } } ``` ## Extraction modes | Mode | Reads | | --- | --- | | `auto` | Common page data such as the title, text, headings, and links. | | `selectors` | An object of named fields, or a list when `each` is set. Attributes can be `text`, `href`, `src`, or `value`. | | `js` | A JSON-serializable value returned by `expression`. | | `json` | The page body parsed as JSON. | ## Adapt the recipe - Set `forceBrowser: true` when you need the configured fields. Otherwise HTTP can return its generic extract first. - For a search form, set `query.input` and `query.submit` to CSS selectors and pass the input through `--value`. Add `query.waitFor` if a results container appears after submission. - Use `classify.emptyPatterns` for an expected no-results message and `classify.expect` for a marker that must appear in the result. These rules inspect the browser extraction. - Use `kitsune init ` to scaffold a recipe from a page. It overwrites an existing recipe with the generated name. If every selector misses, Kitsune falls back to generic extraction and sets the tier to `browser:auto-fallback`. For a custom workflow with several actions or branches, [write a plugin](/docs/concepts/plugins#writing-one). --- ## Solver plugins URL: /docs/guides/solvers Find the bundled adapters and understand how Kitsune selects one per session. # Solver plugins Kitsune includes CapMonster, Capsolver, and 2Captcha adapters under `packages/kitsune/plugins/`. A session has one active solver. The CLI can select it explicitly with `--solver`, or the first registered solver becomes active. Use `bun run kitsune plugins` to inspect your configured plugins. The inventory marks the selected adapter with `SOLVER*`. See [Challenge records](/docs/concepts/challenges) for the verdict and [Plugin API](/docs/reference/plugin-api#challenges-and-results) for the hook and result types. --- ## Kitsune docs URL: /docs Crawl web pages, extract structured data, and automate Chrome with Bun and TypeScript. # Kitsune docs **[Get started with your first crawl](/docs/getting-started)** ## Choose what to do next - [Use Kitsune in TypeScript](/docs/typescript) to crawl from your own script. - [Extract data with recipes](/docs/guides/recipes) to reuse the same fields across pages. - [Automate browser actions](/docs/guides/browser-control) to fill forms, click buttons, and read results. --- ## CLI URL: /docs/reference/cli Implemented commands, flags, environment variables and output behavior. # CLI From a checkout, install workspaces with `bun install` at the repo root, then run `bun run kitsune ` or `bun run --cwd packages/kitsune kitsune `. Both run in the crawler package directory. To keep the root as the working directory, invoke `bun packages/kitsune/src/cli.ts ` directly. The parser supports `--flag value` and bare `--flag`, not `--flag=value` or short options. Put the URL/file positional argument before bare boolean flags, which otherwise consume the next non-flag token. Only `--plugin` and `--proxy` have implemented repeatable-value handling. Unknown flags are parsed but not validated. No command prints help through a special `--help` implementation: no command prints usage and exits 0; an unknown command prints usage and exits 1. Caught errors print `error: ` to stderr and exit 1. ## Commands and writes | Command | Behavior | Writes / stdout | | --- | --- | --- | | `kitsune crawl ` | Recipe-aware crawl; optional selector or link following. | New `kitsune-results/crawl--.jsonl`, result lines and summary. | | `kitsune batch ` | Serial crawl of trimmed lines beginning with `http://` or `https://`, recipes selected per URL. | New `kitsune-results/batch--.jsonl`, human result lines, progress every 10 URLs and summary. | | `kitsune probe ` | Plain HTTP diagnostic, then browser diagnostic with 3000 ms settle. | HTTP status/time/bytes/verdict; final browser URL/readiness/verdict/title/content counts, forms (up to 8 fields each), 240-character text sample. No result file. | | `kitsune init ` | Inspects with browser, scaffolds a recipe. | `packages/kitsune/recipes/.json` in a source checkout, pretty JSON and refinement hint. Existing recipe at that path is overwritten. | | `kitsune sites` | Loads package recipes. | Name, match patterns, extraction mode; no file. | | `kitsune plugins` | Imports configured plugins without launching Chrome. | Plugin inventory, active solver marker and multiple-solver note; no file. | | `kitsune doctor` | Checks Chrome, proxies, solver keys and egress. | Check lines and parsed proxy form; no file. | Chrome-backed commands use fixed CDP ports: crawl `9420`, batch `9421`, probe `9422`, init `9423`. There are no CLI port, headless, output-directory or timeout flags. Chrome itself may create/use a browser profile; the writes column lists command data outputs. ## Crawl flags | Flag | Default | Behavior | | --- | --- | --- | | `--value V` | Unset | Passed to a recipe query or site plugin in single-URL crawl. Not forwarded in follow mode. | | `--selector CSS` | Unset | Forces browser selector extraction to `{ value: ... }`. A missing selector becomes empty when the result would otherwise be ok and has no solved metadata. | | `--recipe NAME` | Host-matched recipe | Picks an exact recipe name; an unmatched name leaves the recipe undefined. | | `--json` | False | Prints each record as compact JSON. Summary and follow messages are still printed to stdout. | | `--follow REGEXP` | Unset | Breadth-first follow of extracted `data.links` on the starting host; regexp applies to pathname + search. Takes precedence over selector. | | `--depth N` | `1` | Maximum follow depth; start URL is depth 0. Only used with follow. | | `--limit N` | `25` with follow, otherwise `1` | Follow page limit, including start URL. Only used with follow. | Follow mode requires a top-level `links` array in extracted data. It de-duplicates URLs and waits 200 ms between processed pages in addition to crawler pacing. Flags for numeric values use `Number(value)` with no range validation. ## Batch flags | Flag | Behavior | | --- | --- | | `--input FILE` | Alternative to the positional file, which takes precedence. | Batch always prints human output. It does not consume crawl-only flags such as `--json`, `--value`, `--recipe`, `--selector`, `--follow`, `--depth` or `--limit`. ## Shared flags and plugin loading | Flag | Commands using it | Behavior | | --- | --- | --- | | `--proxy SPEC` | crawl, batch, probe, init, doctor | Repeatable; replaces all proxy environment input. | | `--solver ./p.ts` | crawl, batch, probe, init, plugins | Loaded before all other plugins; first registered solver becomes active. | | `--plugin ./p.ts` | crawl, batch, probe, init, plugins | Repeatable plugin module paths. | `sites` reads no flags. `doctor` reads proxy flags but does not import plugins. Module paths resolve from the process working directory. Each module must default export a plugin object or a zero-argument factory (which may be async). Loading order is `--solver`, `KITSUNE_SOLVER`, comma-separated `KITSUNE_PLUGINS`, then repeatable `--plugin` entries. `--solver` does not suppress `KITSUNE_SOLVER`; both load if supplied. Only the first solver is active in a launched host; duplicate names fail registration. The inventory command lists the loaded array without constructing a host, so its display follows loading order, not enforce ordering or duplicate validation. Proxy strings support `scheme://user:pass@host:port`, `user:pass@host:port`, `host:port@user:pass`, `host:port:user:pass`, `user:pass:host:port`, `host:port` and `scheme://host:port`. Schemes are http, https, socks4 and socks5; an omitted scheme is http. Lists may use newline, comma or semicolon separators, or a JSON array. Parsed duplicates are removed. One proxy is picked when the browser launches; this does not rotate the browser's identity per URL. ## Environment | Variable | Actual behavior | | --- | --- | | `PROXY_URL`, `PROXIES`, `PROXY_LIST` | First variable in this order that yields a nonempty parsed list wins when no `--proxy` is supplied. | | `KITSUNE_SOLVER` | One plugin module path, loaded after the flag solver. | | `KITSUNE_PLUGINS` | Comma-separated plugin module paths. | | `HEADLESS` | Exactly `1` enables headless Chrome; otherwise headed. | | `JITTER_MIN_MS` | Parsed as a number, default `2500`, when constructing CLI pacing helpers. | | `JITTER_MAX_MS` | Advertised in CLI help/comments but not read by the implementation. | | `CAPMONSTER_API_KEY` | Used by loaded CapMonster solver; checked by doctor. | | `CAPSOLVER_API_KEY` | Used by loaded Capsolver solver; checked by doctor. | | `TWOCAPTCHA_API_KEY` | Used by loaded 2Captcha solver; checked by doctor. | The CLI constructs pacing helpers from `JITTER_MIN_MS` (and recipe pace on crawl), then calls `kit.pace.merge`. Currently merge copies learned domain state, not base/max settings; a fresh helper has none, so these settings do not replace the kit's default 800 ms base. No plugins or paid solvers load merely because an API key is present. ## Output shapes Human crawl/batch result lines are: ```ts // mark is 'OK ' for ok, otherwise verdict.toUpperCase().padEnd(4) `${mark} [${r.tier}] ${r.url} ${r.ms}ms ${r.reason}` ``` Crawl `--json` emits `JSON.stringify(record)` per result. Both commands end with: ```ts // Values shown here are placeholders for the actual summary values. '===== SUMMARY =====' 'verdicts: { ... }' 'tiers: { ... }' 'attempts: avg ms rejection rate %' ' : / ok' 'results: ' ``` Despite the `attempts` label, total counts stored final URL records, not internal browser attempts. Results are flushed per JSONL line. Paths are relative to the working directory; root `bun run kitsune` therefore writes results beneath `packages/kitsune/kitsune-results`. See [Result records](/docs/reference/records). ### Plugins inventory Name is `name@version` if version exists, padded to 24 characters. Each line then shows `site` when present and `SOLVER*` for the first solver, `solver` for other solvers, followed by the description. Trailing whitespace is trimmed. ```ts // Exact line formatter (p is a loaded plugin, active is the first solver): const name = p.version ? `${p.name}@${p.version}` : p.name const flags = [p.site ? 'site' : ' ', p.solver ? (p === active ? 'SOLVER*' : 'solver ') : ' '].join(' ') `${name.padEnd(24)} ${flags} ${p.description ?? ''}`.trimEnd() // With multiple solvers, a preceding line: 'note: 2 solvers registered, only capmonster is active' // With none: 'no plugins loaded — pass --plugin ./plugin.ts or set KITSUNE_PLUGINS' ``` ### Doctor Doctor checks the hardcoded Chrome path `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`, parsed proxies, three key presences, and direct `https://ipinfo.io/json` egress. With a pool it also requests egress for up to five proxies. Missing checks print crosses; they do not themselves cause a nonzero exit. ```ts // Each initial check: `${ok ? '✓' : '✗'} ${name.padEnd(14)} ${detail}` // Check names, in order: ['chrome', 'proxies', 'capmonster key', 'capsolver key', '2captcha key', 'egress'] // Proxy checks and final line: '✓ proxy egress -> ' '✗ proxy egress ' 'parsed form: ' ``` Chrome detail is the path. Proxies detail is `none (direct)` or ` parsed ( …)` (ellipsis only for multiple proxies). Key detail is `configured` or `missing (plugin will skip)`. Direct egress detail is ` ` or `unreachable`. Most proxy displays redact credentials, but the final parsed form uses `proxyLine` and includes credentials for the first configured proxy. --- ## Kit API URL: /docs/reference/kit-api The Kitsune browser session, interaction methods, extraction and crawl options. # Kit API Import `Kitsune` from `kitsune`. The tables show public TypeScript call signatures, including inferred return types; optional arguments list their defaults in the notes. Methods returning `Promise` resolve to the session after the action. ```ts import { Kitsune } from 'kitsune' const kit = await Kitsune.launch({ headless: true }) try { await kit.goto('https://example.com') console.log(await kit.extract()) } finally { await kit.close() } ``` ## Launch options ```ts type LaunchOptions = { proxy?: string | string[] | ProxyConfig | ProxyConfig[] proxyPool?: ProxyPool headless?: boolean port?: number profile?: string paceMs?: number plugins?: KitsunePlugin[] solver?: KitsunePlugin } type ClickOptions = { timeoutMs?: number; force?: boolean } type TypeOptions = { timeoutMs?: number; human?: boolean; clear?: boolean } ``` | Option | Behavior | | --- | --- | | `proxy` | One proxy or list, as provider strings or parsed configs. | | `proxyPool` | Prebuilt pool; takes precedence over `proxy`. One proxy is picked at launch. | | `headless` | Defaults to `HEADLESS === '1'`; otherwise headed Chrome. | | `port` | CDP port, default `9500`. | | `profile` | Passed to the CDP launcher's Chrome profile option. | | `paceMs` | Session pacing base, default `800` ms. | | `plugins` | Session plugins; launch hooks run before Chrome starts, setup after launch. | | `solver` | Added first to the temporary launch-hook host. The live session host is built from `plugins` only: include this plugin there too, or call `useSolver` after launch. | The session exposes `readonly cdp: Cdp`, `readonly pace: Pace`, `readonly plugins: PluginHost` and `readonly proxy?: ProxyConfig`. `poolFrom(input?: LaunchOptions['proxy']): ProxyPool | undefined` is exported from `src/kit.ts` (not the package entrypoint). ## Navigation | Signature | Notes | | --- | --- | | `goto(url: string, opts?: { settleMs?: number }): Promise` | Settle defaults to `2000` ms; runs the navigate hook after navigation with status `200`. | | `back(): Promise` | Calls `history.back()`, then sleeps `500` ms. | | `reload(settleMs?: number): Promise` | Navigates to the current URL; default `1500` ms. | | `url(): Promise` | Current `location.href`. | | `title(): Promise` | Document title. | | `readyState(): Promise` | Document readiness string. | ## Waiting | Signature | Notes | | --- | --- | | `waitFor(selector: string, timeoutMs?: number): Promise` | CSS selector existence; default `15000` ms. | | `waitForText(needle: string, timeoutMs?: number): Promise` | Body substring; default `15000` ms, polls every `250` ms. | | `waitForExpression(expression: string, timeoutMs?: number): Promise` | In-page predicate; default `15000` ms. | | `waitForNetworkIdle(quietMs?: number, timeoutMs?: number): Promise` | Defaults `800`, `15000` ms; polls the resource timing entry count, not active network requests. | | `waitForActionable(selector: string, opts?: ActionableOptions): Promise` | Reports the failing gate rather than throwing an action timeout. | The boolean waits return `false` on timeout. Evaluation errors can still reject. Actionability types are defined in `src/interact/actionable.ts`: ```ts type Gate = 'attached' | 'visible' | 'stable' | 'enabled' | 'editable' | 'unobscured' type RequiredGate = Exclude type ActionableOptions = { timeoutMs?: number; require?: RequiredGate[]; pollMs?: number } type Box = { x: number; y: number; width: number; height: number } type ActionableResult = | { ok: true; box: Box; elapsedMs: number } | { ok: false; reason: string; gate: Gate; elapsedMs: number } ``` `waitForActionable` defaults to `timeoutMs: 30000`, `require: []`, `pollMs: 100`. Attached is always checked. Visible requires a nonempty box and visible styles; stable compares rectangles across animation frames; enabled rejects disabled and aria-disabled controls; editable also checks field/contenteditable and readonly state; unobscured hit-tests the center. ## Interaction | Signature | Notes | | --- | --- | | `click(selector: string, opts?: ClickOptions): Promise` | Default timeout `10000` ms. | | `hover(selector: string, timeoutMs?: number): Promise` | Default `10000` ms. | | `type(selector: string, value: string, opts?: TypeOptions): Promise` | Defaults: timeout `10000` ms, `human: true`, `clear: true`. | | `fill(fields: Record, opts?: TypeOptions): Promise` | Sequentially calls `type` for each selector/value pair. | | `focus(selector: string, timeoutMs?: number): Promise` | Default `10000` ms; clicks the center if available, otherwise calls DOM `focus()`. | | `press(key: keyof typeof KEYS \| string): Promise` | `KEYS` is the internal key map described below. | | `select(selector: string, value: string, opts?: { timeoutMs?: number }): Promise` | Default `10000` ms; waits for enabled and, for native selects, the option value. | | `check(selector: string, checked?: boolean, opts?: { timeoutMs?: number }): Promise` | Defaults `true`, `10000` ms; waits for enabled and the requested checked state. | | `scroll(y: number, settleMs?: number): Promise` | Absolute vertical position; default settle `300` ms. | | `scrollToBottom(step?: number): Promise` | Default step `600`; uses the initial body height and scrolls in increments. | Input uses real CDP mouse/key events. `press` recognizes `Enter`, `Tab`, `Escape`, `Backspace`, `ArrowDown` and `ArrowUp`, and accepts other key strings. `select` sets the value and dispatches input/change events. `check` uses a trusted click for a visible, stable, unobscured input, with DOM `click()` as a fallback for custom or hidden controls. `click`, `type`, `hover`, `fill`, `upload`, `select` and `check` poll actionability and re-resolve stale nodes during hydration, within the action's timeout: | Action | Gates beyond attached | | --- | --- | | `click` | visible, stable, enabled, unobscured | | `hover` | visible, stable, unobscured | | `type`, `fill` | visible, stable, editable (includes enabled), unobscured | | `upload`, `select`, `check` | enabled; hidden native controls are allowed | `click({ force: true })` skips stable/enabled/unobscured gates and the dispatch hit test, but still requires attached and visible, verifies position, and silently returns on failure. Other interaction options do not accept `force`. Typing focuses the verified node before sending keys, then re-queries the live input/textarea to verify its value. If the value differs, it uses the native value setter and dispatches input/change events. This fallback writes exactly `value`, even if `clear: false` initially allowed keys to append. `select` retries until its option exists; `check` polls after clicking and retries until the desired state holds or the action times out. ## Primitives | Signature | Notes | | --- | --- | | `drag(fromSel: string, toSel: string): Promise` | CDP mouse drag over 16 steps. | | `upload(selector: string, paths: string[], opts?: { timeoutMs?: number }): Promise` | Default `10000` ms; resolves file paths from the process working directory. | | `enableDownloads(dir: string): Promise` | Creates/resolves the directory and enables Chrome download events. | | `waitForDownload(timeoutMs?: number): Promise` | Default `30000` ms; rejects unless downloads were enabled, on cancellation, timeout or close. | | `cookies(url?: string): Promise` | Optional URL filter. | | `setCookie(cookie: Cookie): Promise` | Throws if Chrome rejects the cookie. | | `clearCookies(): Promise` | Deletes all cookies, including other origins/paths. | | `frame(urlPart: string): Promise` | First frame whose URL contains the substring. | | `withFrame(urlPart: string, fn: (frame: Frame) => T \| Promise): Promise` | Runs the callback in the matching frame. | | `inFrame(selector: string): Promise` | Finds a document containing the selector, including cross-origin frames. | | `route(pattern: string, handler: RouteHandler): Promise` | CDP URL pattern with `*`, `?` and backslash escaping. Last matching registration wins. | | `unroute(pattern: string): Promise` | Removes a pattern. | | `evaluate(expression: string): Promise` | Arbitrary expression in the page. | | `box(selector: string, timeoutMs?: number): Promise<{ x: number; y: number } \| null>` | Default `10000` ms; scrolls to the element and returns its center, or null. | Upload delivers through `DOM.setFileInputFiles` to the verified node handle's `nodeId`, then checks that the node remained attached. It retries replacement races instead of re-querying a selector at delivery time. The following support types live in `src/interact` and are not re-exported from the package entrypoint: ```ts type Download = { guid: string; state: 'completed'; totalBytes: number receivedBytes: number; filePath?: string } type Cookie = { name: string; value: string; url?: string; domain?: string; path?: string secure?: boolean; httpOnly?: boolean; sameSite?: 'Strict' | 'Lax' | 'None' expires?: number; priority?: 'Low' | 'Medium' | 'High'; sameParty?: boolean sourceScheme?: 'Unset' | 'NonSecure' | 'Secure'; sourcePort?: number partitionKey?: { topLevelSite: string; hasCrossSiteAncestor: boolean } } type StoredCookie = Cookie & { domain: string; path: string; expires: number; size: number; session: boolean } type FulfilOptions = { status?: number; body?: string; headers?: Record } type Route = { request: { url: string; method: string; headers: Record; postData?: string } resourceType: string continue(overrides?: { url?: string; method?: string; postData?: string headers?: { name: string; value: string }[] }): Promise fulfil(options: FulfilOptions): Promise abort(reason?: string): Promise fail(reason?: string): Promise } type RouteHandler = (route: Route) => void | Promise ``` Routes continue automatically if the handler does not handle them. Fulfil defaults to status `200`, empty body and headers; abort defaults to `Aborted`, fail to `Failed`. Interception covers the page, not attached frame sessions. `Frame` exposes readonly `id`, `url`, `sessionId` strings, `evaluate(expression: string): Promise` and `click(selector: string): Promise`; its click does not use the kit's actionability loop. ## Reading | Signature | Notes | | --- | --- | | `html(): Promise` | Document outer HTML. | | `bodyText(): Promise` | Body inner text, or empty string. | | `text(selector: string): Promise` | Normalized text. Declared/inferred as string, but the page expression returns null when absent. | | `texts(selector: string, limit?: number): Promise` | Normalized text list; default limit `200`. | | `attr(selector: string, name: string): Promise` | Attribute or null. | | `href(selector: string): Promise` | Element's `href` property or null when absent. | | `exists(selector: string): Promise` | Selector exists. | | `query(spec: SelectorSpec): Promise` | Field map; object or rows when `each` is set. | | `extract(): Promise` | Automatic structured extraction. | | `screenshot(file?: string): Promise` | Writes PNG and returns the path; default `${Bun.cwd}/kitsune-${Date.now()}.png`. Does not create parent directories. | ```ts type SelectorSpec = { fields: Record each?: string attr?: Record } type AutoExtract = { title: string lang: string | null canonical: string | null description: string | null og: Record headings: { tag: string; text: string }[] text: string links: { href: string; text: string }[] tables: string[][][] jsonLd: any[] appState: Record forms: any[] readyState: string } ``` Selector reads default to text; missing elements return null. `:scope` addresses the repeating row itself. Auto extraction includes up to 200000 text characters, 2000 links, 20 tables (200 rows each), 60 headings and 10 forms. ## Records | Signature | Notes | | --- | --- | | `crawl(url: string, opts?: Partial): Promise` | HTTP → browser → extraction fallback, or site plugin takeover. Does not persist the result. | | `verdict(): Promise` | Extracts and classifies the current page with status `200`. | ```ts type CrawlInput = { url: string value?: string recipe?: Recipe pace: Pace allowHttp?: boolean maxAttempts?: number settleMs?: number timeoutMs?: number proxy?: string plugins?: PluginHost kit?: PluginApi } type Detection = { verdict: Verdict; reason: string; matched?: string } ``` `crawl` supplies the session's URL, pace, proxy URL, host and plugin API before spreading `opts`, so explicit options can override those defaults. Defaults are HTTP allowed, 3 browser attempts, and `2500` ms settle plus `2000` ms per retry; `timeoutMs` is passed to HTTP. Recipes can force browser use, fill/submit a query, and select auto/selectors/js/json extraction. Empty selectors fall back to auto. See [Result records](/docs/reference/records) for the record schema and tiers. ## Lifecycle | Signature | Notes | | --- | --- | | `Kitsune.launch(opts?: LaunchOptions): Promise` | Starts Chrome and prepares plugins. | | `context(): PluginContext` | Live plugin context, including the launch proxy and logger. | | `use(plugin: KitsunePlugin): Promise` | Registers a plugin and immediately runs its setup. Launch hooks cannot affect an already running browser. | | `useSolver(plugin: KitsunePlugin): Promise` | Selects a solver and immediately runs its setup. | | `close(): Promise` | Reverse plugin teardown, interception/download/frame/DOM cleanup, then CDP close. | --- ## Plugin API URL: /docs/reference/plugin-api Plugin metadata, lifecycle hooks, solver selection, contexts and challenge helpers. # Plugin API A plugin is `PluginMeta & PluginHooks`. Missing hooks are no-ops. The package entrypoint exports the types and helpers below, along with `PLUGIN_API_VERSION = 1`. ```ts import type { KitsunePlugin } from 'kitsune' declare function definePlugin(plugin: KitsunePlugin): KitsunePlugin ``` `definePlugin` returns the same object and throws if `name` is missing. ## Metadata | Field | Type | Meaning | | --- | --- | --- | | `name` | `string` | Required stable identity; duplicate names are rejected by the host. | | `version` | `string` (optional) | Displayed by `kitsune plugins`. | | `enforce` | `'pre' \| 'post'` (optional) | Pre hooks first, omitted normal hooks next, post hooks last. | | `description` | `string` (optional) | Human description in the plugin listing. | | `site` | `PluginSite` (optional) | URL ownership; bypasses the generic crawl ladder. | | `solver` | `boolean` (optional) | Marks a solver eligible to become the single active solver. | ```ts type PluginSite = { match: (url: URL) => boolean crawl: (ctx: { kit: PluginApi; cdp: Cdp; url: string; value?: string }) => Promise<{ verdict: Verdict reason: string tier?: string data: unknown }> } ``` The first matching site plugin in host order takes over. Its default record tier is `plugin:${plugin.name}`; a returned tier overrides it. The shipped `repuve` plugin returns `ui`. ## Hooks | Hook signature | When it runs | Returns | | --- | --- | --- | | `launch(args: string[], opts: { headless: boolean })` | Before Chrome starts. May mutate args or replace the array. | `string[] \| void` | | `setup(ctx: PluginContext)` | During prepare after launch; also immediately for `kit.use` / `kit.useSolver`. | `void \| Promise` | | `navigate(info: NavigateInfo, ctx: PluginContext)` | After `kit.goto` (including reload); the generic crawler's direct CDP navigations do not call it. | `void \| Promise` | | `response(info: ResponseInfo, ctx: PluginContext)` | Browser attempt after classification and any solver re-extraction. Not called for HTTP or site takeover. | `void \| Promise` | | `challenge(info: ChallengeInfo, ctx: PluginContext)` | Only the active solver; generic crawl calls it for a challenge with a known kind. | `Promise \| SolveResult` | | `record(record: Record_, ctx: PluginContext)` | Finished site/browser record, in host order. Successful HTTP returns bypass this hook. | `Record_ \| void` | | `close(ctx: PluginContext)` | Session close, reverse host order. Errors are logged and teardown continues. | `void \| Promise` | All hooks are optional. Record hooks can mutate the record, return a replacement, or return nothing to keep the current record. They are typed as synchronous; the crawler awaits their result. Other non-close hook errors propagate from the host; the generic browser crawl catches attempt errors and can retry or return an error record. ```ts type NavigateInfo = { url: string; status: number; settleMs: number } type ResponseInfo = { url: string status: number verdict: Verdict reason: string text: string } ``` `kit.goto` reports status `200`. Browser response info also uses `200` and limits text to 4000 characters. ## PluginContext and PluginApi | Context field | Type | Meaning | | --- | --- | --- | | `kit` | `PluginApi` | Stable subset of the live kit, listed below. | | `cdp` | `Cdp` | Live protocol driver. | | `proxy` | `ProxyConfig` (optional) | Session proxy when supplied by the caller. `kit.context()` includes it; the generic crawl currently builds its context without it. | | `challenge` | `ChallengeInfo` (optional) | Filled by `PluginHost.challenge` for the active solver. | | `log` | `(message: string, data?: unknown) => void` | Kit/crawler logger writes `[plugin]` messages to stderr. | ```ts type PluginApi = { goto(url: string, opts?: { settleMs?: number }): Promise evaluate(expression: string): Promise click(selector: string, opts?: { timeoutMs?: number; force?: boolean }): Promise type(selector: string, value: string, opts?: { timeoutMs?: number }): Promise waitFor(selector: string, timeoutMs?: number): Promise box(selector: string, timeoutMs?: number): Promise<{ x: number; y: number } | null> text(selector: string): Promise exists(selector: string): Promise url(): Promise screenshot(file?: string): Promise cdp: Cdp } type ProxyScheme = 'http' | 'https' | 'socks4' | 'socks5' type ProxyConfig = { scheme: ProxyScheme host: string port: number username?: string password?: string raw: string } ``` Plugins should use the passed kit/context. Token providers that need the same IP can accept an explicit proxy; the shipped solvers otherwise use `ctx.proxy`. ## PluginHost `new PluginHost(plugins?: KitsunePlugin[])` defaults to an empty list. Ordering is stable within each `enforce` group. Registration chooses the first solver before ordering, so `enforce: 'pre'` on a later solver does not activate it. Only the active solver receives challenge calls, with no fallback to dormant vendors. `prepare` skips dormant solver setup; launch, ordinary `run` and close iterate their applicable hooks across registered plugins. | Signature | Behavior | | --- | --- | | `add(plugin: KitsunePlugin): this` | Rejects missing/duplicate names, registers and sorts. | | `get all(): readonly KitsunePlugin[]` | Ordered registry. | | `get solver(): KitsunePlugin \| undefined` | Active solver. | | `get solvers(): readonly KitsunePlugin[]` | Registered solvers, active first. | | `useSolver(plugin: KitsunePlugin): this` | Requires `solver: true`, registers if needed, selects it. Does not itself run setup. | | `siteFor(url: string): { plugin: KitsunePlugin; site: PluginSite } \| undefined` | First URL match; invalid URLs return undefined. | | `run(hook: K, ctx: PluginContext, ...args: any[]): Promise` | `HookName = keyof PluginHooks`; invokes hooks with args followed by context, stops at first failure; ignores returns. | | `challenge(info: ChallengeInfo, ctx: PluginContext): Promise` | Calls only active solver; undefined if it has no challenge hook. | | `launchArgs(args: string[], headless: boolean): string[]` | Applies launch hooks in order. | | `prepare(ctx: PluginContext): Promise` | Runs setup once, except dormant solvers. | | `close(ctx: PluginContext): Promise` | Reverse-order close, logs errors. | A solved result gets `via: plugin.name` if it omitted `via`. A failed result with a detail is logged. Switching through `kit.useSolver` runs setup immediately. The `Kitsune.launch` `solver` option only inserts that plugin into the temporary launch-hook host; the live host uses `plugins`. Include it in `plugins` and place it first for first-registration activation, or use `kit.useSolver` afterward. ## Challenges and results ```ts type ChallengeKind = | 'recaptcha-v2' | 'recaptcha-v3' | 'hcaptcha' | 'turnstile' | 'datadome' | 'cloudflare' | 'unknown' type ChallengeInfo = { kind: ChallengeKind url: string status: number verdict: Verdict reason: string sitekey?: string action?: string matched?: string } type SolveStatus = 'solved' | 'skipped' | 'failed' type SolveResult = { status: SolveStatus via?: string detail?: string costUsd?: number ms?: number token?: string } ``` `sitekey`, `action` and `matched` hold widget metadata and the classification marker when available. The DOM reader is heuristic: it stores the first captured `grecaptcha.execute/render` argument in `action`; do not assume it is a verified reCAPTCHA action. Solvers report solved, skipped or failed; the host does not inject a returned `token` automatically. The current crawler re-extracts after any returned SolveResult, including skipped/failed, and records `via` (or `solver`) as `meta.solved` if the resulting classification is accepted. That metadata alone is not proof of a solve. ## Challenge helpers ```ts declare function readChallenge( cdp: Cdp, base: { url: string; status: number; verdict: Verdict; reason: string; matched?: string }, ): Promise declare function findTokenField(cdp: Cdp, kind: ChallengeKind): Promise declare function injectToken(cdp: Cdp, selector: string, token: string): Promise ``` | Helper | Behavior | | --- | --- | | `readChallenge` | Inspects widgets, markup and iframe URLs; returns `unknown` when no kind is found or evaluation fails. | | `findTokenField` | Returns the first existing hCaptcha, reCAPTCHA or Turnstile response-field selector; null for unsupported kinds or absent fields. | | `injectToken` | Uses the native input/textarea setter when applicable and fires input/change. Returns false if absent or evaluation fails; does not submit or verify server acceptance. | The shipped `capmonster`, `capsolver` and `twocaptcha` factories mark themselves as solvers, read their respective API-key environment variables, request tokens, inject and verify the field, and optionally click a configured submit selector. No solver is loaded by default. `repuve` is a site plugin rather than a solver. ## Example: tag a record ```ts import { definePlugin } from 'kitsune' export default definePlugin({ name: 'acme:tag', record: (record) => ({ ...record, meta: { ...record.meta, team: 'acme' }, }), }) ``` This tags records that pass through record hooks (site/browser paths). ## Example: add a launch flag ```ts import { definePlugin } from 'kitsune' export default definePlugin({ name: 'acme:locale', enforce: 'pre', launch: (args) => [...args, '--lang=es-MX'], }) ``` --- ## Records URL: /docs/reference/records Crawl record fields, verdicts, tiers, metadata and JSONL persistence. # Records `kit.crawl` and `crawlOne` return one final record per URL invocation, after any internal browser retries. The CLI persists those results for `crawl` and `batch`. ## Record_ shape ```ts type Record_ = { ts: string url: string finalUrl?: string tier: string verdict: string reason: string ms: number attempt?: number status?: number data?: any error?: string meta?: Record } ``` | Field | Meaning | | --- | --- | | `ts` | ISO timestamp when the record is constructed. | | `url` | Requested URL. | | `finalUrl` | HTTP final URL or accepted browser location when available; some paths use the requested URL. | | `tier` | Execution/extraction path, a string rather than a closed union. | | `verdict` | Classification; typed as string in Record_, although the classifier uses Verdict below. | | `reason` | Human-readable classification detail. | | `ms` | Elapsed invocation time including pacing, retries and solver work. | | `attempt`, `status` | Optional top-level fields supported by the type. The generic crawler writes these inside meta instead. | | `data` | Auto extraction, selector object/rows, JavaScript/JSON result, site-plugin data, or null. HTTP JSON is wrapped as `{ json: parsedValue }`. | | `error` | Final browser exception message, truncated to 300 characters. | | `meta` | Free-form diagnostics and plugin additions. | ## Verdicts ```ts type Verdict = 'ok' | 'empty' | 'blocked' | 'challenge' | 'tarpit' | 'unknown' type Detection = { verdict: Verdict; reason: string; matched?: string } ``` | Verdict | Meaning in the implementation | | --- | --- | | `ok` | Structured content, a short rendered page, or acceptable substantial HTTP content. Counted as success. | | `empty` | Blank/thin body or recipe emptyPattern; may be a shell that never mounted. The CLI also uses it for a missed ad-hoc selector. Not counted as blocked. | | `blocked` | HTTP 401/403/407/429, recognized block text, or recipe/site override. | | `challenge` | Challenge-page marker, or a known captcha widget with sitekey and no filled response token. | | `tarpit` | Reserved verdict accepted as terminal by the ladder; the current generic detect function never emits it. Plugins can return it. | | `unknown` | No classification rule, HTTP 5xx, missing recipe expectation, exceptions or exhausted attempts without a terminal result. Not success. | `detect` checks status and challenge/strong block markers before accepting `hasData`. Ambiguous block markers apply to bodies under 4000 characters. Without structured data, visible text under 80 characters is empty unless the caller marks the page rendered. `shouldEscalate` returns true for blocked, challenge and empty; `isTerminal` accepts ok and tarpit. The crawl loop also retries unknown results. ## Tiers | Tier | Produced by | | --- | --- | | `http` | Accepted plain HTTP HTML or JSON. | | `browser` | Accepted auto extraction, exhausted nonterminal attempts or a final exception. | | `browser:auto` | Empty final attempt with auto extraction. | | `browser:selectors` | Selector extraction. | | `browser:js` | Recipe JavaScript expression. | | `browser:json` | Parsed browser body JSON. | | `browser:auto-fallback` | Empty selectors degraded to automatic extraction. | | `plugin:` | Default tier for a site plugin that does not supply one. | | `ui` | The shipped REPUVE site plugin. | | Any site/plugin-supplied string | PluginSite permits an arbitrary tier; record hooks can replace records. | There is no separate `interaction` tier emitted by the generic crawler: recipe fill/submit still uses a browser tier. The final nonterminal return uses `browser`, even if extraction used another mode. ## Metadata | Key | Generic crawler value | | --- | --- | | `status` | HTTP response status, on accepted HTTP records. | | `attempt` | Browser attempt number on accepted, final empty or exception records. Not present on every exhausted-attempt result. | | `matched` | Classifier marker when supplied by Detection. | | `plugin` | Site plugin name on a takeover result. | | `solved` | Solver result's `via`, or `solver`, on accepted browser records after a returned solver result. | The current crawler sets `solved` and re-extracts for any returned SolveResult, even skipped/failed. Read the verdict and reason as well; `meta.solved` alone does not verify a successful solve. No solver cost, token or duration is copied into generic record metadata. Plugins may add arbitrary fields through record hooks; successful HTTP returns bypass those hooks. ## JSONL output and Store The CLI creates a new file under the process working directory: `kitsune-results/crawl--.jsonl` or `kitsune-results/batch--.jsonl`. Stamp is an ISO timestamp with colons and periods replaced by hyphens. Root `bun run kitsune` delegates with `--cwd packages/kitsune`, so its output is under `packages/kitsune/kitsune-results`. Direct `bun packages/kitsune/src/cli.ts ...` from the root writes under the root. Each final URL result is appended as one JSON line and flushed immediately. Internal retries do not each produce a line. Each run opens a unique file; `kit.crawl` alone does not write JSONL. `probe`, `sites`, `plugins` and `doctor` print diagnostics; `init` writes a recipe instead. ```ts import { Store, type Record_ } from 'kitsune' async function save(record: Record_) { const store = await Store.open('kitsune-results', 'custom') try { await store.write(record) } finally { await store.close() } console.log(await store.summary()) } ``` | Signature | Behavior | | --- | --- | | `Store.open(dir: string, label?: string): Promise` | Default label `run`; creates an empty unique JSONL file, then opens a writer. | | `write(r: Record_): Promise` | Appends and flushes one JSON line. | | `close(): Promise` | Ends the writer. | | `summary()` | Async recomputation from `readonly file: string`, with the shape below. | ```ts // Return type of summary(): type SummaryResult = Promise<{ total: number byVerdict: Record byTier: Record byHost: Record avgMs: number rejectionRate: number }> ``` Summary ignores malformed JSON when accumulating values, but `total` counts all nonempty lines. Rejection rate is `(blocked + challenge) / total * 100`, rounded to one decimal; average milliseconds is rounded to an integer. Only `ok` counts in each host's success total. --- ## Use Kitsune in TypeScript URL: /docs/typescript Import Kitsune and run a crawl from a Bun script. # Use Kitsune in TypeScript Use `Kitsune` when your application needs to read a crawl result or drive the browser directly. Complete the [CLI setup](/docs/getting-started#1-set-up-kitsune) first. ## Run a crawl from code Save this as `crawl.ts` at the repository root. Bun resolves `kitsune` from the installed workspace. ```ts import { Kitsune } from 'kitsune' const kit = await Kitsune.launch() try { const record = await kit.crawl('https://example.com') console.log(record.verdict, record.data) } finally { await kit.close() } ``` ```bash bun run crawl.ts ``` Expect `ok` and an object with the title `Example Domain`. The library returns the [record](/docs/reference/records) to your script. Use `Store` if you want to persist those records as JSONL. ## Import from another Bun project Register the local package from the Kitsune checkout: ```bash cd packages/kitsune bun link ``` Then run `bun link kitsune` in your other project and use the same import. ## Next steps - [Automate browser actions](/docs/guides/browser-control) for forms and multi-step flows. - [Kitsune API](/docs/reference/kit-api) for session options and method signatures. ---