@gaiventures/pilotfish-mcp 0.1.19 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +134 -89
  2. package/cli.js +1 -1
  3. package/package.json +5 -2
package/README.md CHANGED
@@ -1,149 +1,194 @@
1
1
  # pilotfish MCP
2
2
 
3
- A real Chromium on your own machine for any [MCP](https://modelcontextprotocol.io) agent: Claude Code, OpenAI
4
- Codex CLI, Cursor, Claude Desktop, VS Code, or your own client. **No account and no API key.** Your agent's own
5
- model reads each page and decides every step; pilotfish carries out the action, checks it, and reports what
6
- changed.
7
-
8
- - **Ref-based tools that prove each action.** `browser_click {ref: "e12"}` refuses (obscured, stale, not
9
- visible) rather than clicking the wrong thing, and every action returns evidence of what changed.
10
- - **Cheap to read.** Compact snapshots of the visible screen, only the lines that changed when the agent has
11
- seen the page a moment ago, and `browser_query` for just the values it needs (read-only JavaScript).
12
- - **People stay in the loop.** A sign-in, a one-time code or a CAPTCHA comes back as `NEEDS A PERSON`: you do
13
- it in the browser window, the agent calls `browser_resume` and carries on. Nothing tries to get past it.
14
- - **Secrets never reach the model.** Values in `PILOTFISH_SECRETS` are typed as `{{name}}` placeholders and
15
- masked in every result.
16
- - **Local.** A fresh browser on your machine and your own IP; nothing is kept when it closes. Cookie banners
17
- are rejected and ads and trackers blocked before the agent sees the page.
3
+ [![npm](https://img.shields.io/npm/v/@gaiventures/pilotfish-mcp)](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp)
4
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](#license)
5
+
6
+ Give your AI agent a real Chrome browser on your own computer. It works with Claude Code, Codex CLI, Cursor,
7
+ Claude Desktop, VS Code and any other [MCP](https://modelcontextprotocol.io) client.
8
+
9
+ Free, MIT licensed. No account, no API key, no pilotfish servers: your agent's own model reads each page and
10
+ picks each step, and pilotfish carries it out, checks it and tells the agent what changed.
11
+
12
+ ```sh
13
+ claude mcp add pilotfish -- npx -y @gaiventures/pilotfish-mcp
14
+ ```
15
+
16
+ > **Want pilotfish to do the whole task for you?** [pilotfish managed](#local-or-managed) runs it in our cloud
17
+ > browser, signed in with your saved logins, and hands your agent the answer.
18
+
19
+ ## Why pilotfish
20
+
21
+ - **It clicks what it means to.** Tools act on refs from the page (`browser_click {ref: "e12"}`). If the element
22
+ is covered, gone or off screen, the click is refused instead of landing on the wrong thing, and every action
23
+ reports what changed.
24
+ - **It reads pages cheaply.** The agent sees a compact outline of the visible screen. After the first look it
25
+ gets only the lines that changed, and `browser_query` pulls out just the values it needs.
26
+ - **You stay in charge.** Sign-ins, one-time codes and CAPTCHAs are handed to you in the browser window. Payments,
27
+ orders, messages and deletions wait for your yes.
28
+ - **Your passwords stay out of the model.** Secrets you configure are typed as `{{name}}` placeholders and masked
29
+ in every result.
30
+ - **It runs locally.** A fresh browser on your machine and your own internet connection, closed when your agent
31
+ disconnects. Cookie banners are declined and ads and trackers blocked before the agent sees the page.
32
+
33
+ ## Local or managed?
34
+
35
+ This package is the local version. **pilotfish managed** is the same browser engine run for you in the cloud, as
36
+ a paid service on your pilotfish account.
37
+
38
+ | | **Local** (this package) | **Managed** |
39
+ | --- | --- | --- |
40
+ | Who does the work | Your agent's model, one step at a time | pilotfish runs the whole task and returns the result |
41
+ | Your agent's tokens | Every page it reads | A call or two per task |
42
+ | Browser | Chrome on your computer, your IP | pilotfish's cloud browser, on even when your computer is off |
43
+ | Sign-ins | You sign in each time; nothing is kept | Saved logins and sessions, two-factor codes, phone sign-in by code |
44
+ | Sites that block bots | You clear each check yourself | Residential IPs, stealth browsing and CAPTCHA solving, with you as the last resort |
45
+ | Watching and history | The browser window | Live view, take control, replays, per-task cost |
46
+ | Price | Free | Pay as you go, from $10 of credit |
47
+
48
+ Use local when you are at your desk and want your agent to drive. Use managed when you want a task done, need
49
+ to stay signed in to sites between runs, or keep running into bot checks.
50
+
51
+ **Get started with managed:** [sign up](https://pilotfish.gai.ventures/signup), add credits, and connect your
52
+ agent with [`@gaiventures/pilotfish-mcp-managed`](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp-managed)
53
+ or the URL `https://pilotfish-be.gai.ventures/mcp`.
18
54
 
19
55
  ## Requirements
20
56
 
21
57
  - Node.js 22 or newer
22
- - Google Chrome (or another Chromium browser such as Microsoft Edge or Chromium). Set `PILOTFISH_CHROME` to use
23
- a specific one.
58
+ - Google Chrome, Microsoft Edge or Chromium. Set `PILOTFISH_CHROME` to choose one.
24
59
 
25
60
  ## Setup
26
61
 
27
- **Claude Code**
62
+ ### Claude Code
28
63
 
29
64
  ```sh
30
65
  claude mcp add pilotfish -- npx -y @gaiventures/pilotfish-mcp
31
66
  ```
32
67
 
33
- On native Windows (not WSL): `claude mcp add pilotfish -- cmd /c npx -y @gaiventures/pilotfish-mcp`.
34
- Settings go before the `--` as `-e NAME=value`, e.g. `-e PILOTFISH_HEADLESS=1`.
68
+ On native Windows (not WSL), use `claude mcp add pilotfish -- cmd /c npx -y @gaiventures/pilotfish-mcp`.
69
+ Settings go before the `--` as `-e NAME=value`, for example `-e PILOTFISH_HEADLESS=1`.
35
70
 
36
- **OpenAI Codex CLI** (`~/.codex/config.toml`)
71
+ ### Codex CLI
72
+
73
+ In `~/.codex/config.toml`:
37
74
 
38
75
  ```toml
39
76
  [mcp_servers.pilotfish]
40
77
  command = "npx"
41
78
  args = ["-y", "@gaiventures/pilotfish-mcp"]
42
- # browser_resume waits up to 300 s for you; Codex's default per-call limit is 60 s.
79
+ # browser_resume waits up to 300 s for you; Codex stops a call after 60 s by default.
43
80
  tool_timeout_sec = 330
44
- # Optional settings:
81
+ # Optional:
45
82
  # env = { PILOTFISH_HEADLESS = "1", PILOTFISH_ALLOWED_HOSTS = "example.com,*.example.com" }
46
83
  ```
47
84
 
48
- **Cursor, Claude Desktop, Windsurf and other MCP clients** (Cursor: `~/.cursor/mcp.json` or `.cursor/mcp.json`;
49
- Claude Desktop: `claude_desktop_config.json`)
85
+ ### Cursor, Claude Desktop, Windsurf and others
86
+
87
+ In Cursor's `~/.cursor/mcp.json` (or `.cursor/mcp.json` in a project), Claude Desktop's
88
+ `claude_desktop_config.json`, or your client's equivalent:
50
89
 
51
90
  ```json
52
91
  {
53
92
  "mcpServers": {
54
93
  "pilotfish": {
55
94
  "command": "npx",
56
- "args": ["-y", "@gaiventures/pilotfish-mcp"],
57
- "env": {
58
- "PILOTFISH_SECRETS": "{\"shop_password\": {\"value\": \"...\", \"allowedHosts\": [\"shop.example.com\"]}}"
59
- }
95
+ "args": ["-y", "@gaiventures/pilotfish-mcp"]
60
96
  }
61
97
  }
62
98
  }
63
99
  ```
64
100
 
65
- `env` is optional; leave it out when you set nothing. To pin a version, use `@gaiventures/pilotfish-mcp@0.1.0`.
101
+ Settings go in an `env` object next to `args`. To pin a version, use `@gaiventures/pilotfish-mcp@0.1.0`.
102
+
103
+ The browser opens in its own window, where you sign in or solve a CAPTCHA when a page needs a person.
104
+ `PILOTFISH_HEADLESS=1` hides it; on a Linux machine without a display it is hidden already.
66
105
 
67
- The browser opens in a window of its own on your desktop, where you sign in or solve a CAPTCHA when a page
68
- needs a person (`PILOTFISH_HEADLESS=1` hides it; on a Linux machine with no display it is hidden already).
106
+ ### Over HTTP
69
107
 
70
- **Streamable HTTP** (one browser shared by every client that connects; binds to 127.0.0.1):
108
+ One browser shared by every client that connects, on 127.0.0.1:
71
109
 
72
110
  ```sh
73
- npx -y @gaiventures/pilotfish-mcp --http --port 8931 # http://127.0.0.1:8931/mcp
111
+ npx -y @gaiventures/pilotfish-mcp --http --port 8931
74
112
  claude mcp add --transport http pilotfish http://127.0.0.1:8931/mcp
75
113
  ```
76
114
 
77
- Clients that take a URL instead of a command (`"url": "http://127.0.0.1:8931/mcp"`) connect the same way. A
78
- loopback server answers only loopback `Host` headers (DNS rebinding). Set `PILOTFISH_MCP_TOKEN` to require
79
- `Authorization: Bearer <token>`; serving on any other address needs it.
115
+ Clients that take a URL use `"url": "http://127.0.0.1:8931/mcp"`. The server only answers requests addressed to
116
+ localhost. Set `PILOTFISH_MCP_TOKEN` to require `Authorization: Bearer <token>`; it is required to serve on any
117
+ other address.
80
118
 
81
119
  ## Tools
82
120
 
83
121
  | Tool | What it does |
84
122
  | --- | --- |
85
- | `browser_navigate` `{url, snapshot?}` | Open an http(s) URL. Returns evidence and the visible screen as a snapshot, with counts of what is above and below. `snapshot: false` leaves the screen out (what happened and the counts only): only for a page the same reply reads with `browser_query` and the agent will not act on. |
86
- | `browser_snapshot` `{whole_page?}` | The page as a compact tree with refs (`[e12]<button>Search`): three screens around the viewport, or everything with `whole_page`. Each word once: no closing tags, an element's text not repeated on the lines under it, link targets as paths, no generated ids; every word and ref is kept. |
87
- | `browser_click` `{ref}` | Click by ref; refuses (obscured, stale, not visible) rather than clicking the wrong thing. |
88
- | `browser_type` `{ref, text, submit?}` | Replace a field's text; `{{name}}` placeholders type configured secrets. |
89
- | `browser_select` `{ref, values}` | Pick `<select>` option(s) by label or value. |
90
- | `browser_press` `{key}` | A key or shortcut (`Enter`, `Escape`, `Control+a`). |
91
- | `browser_scroll` `{direction}` | Scroll about one screen; returns the screen it shows. |
92
- | `browser_actions` `{actions}` | Up to 10 steps in one call, each `{action, …}`: `click`, `select` and `type` take a `ref`; `type` takes `text` (and `submit`), `select` `values`, `press` `key`, `scroll` `direction`, `wait` `seconds`. E.g. a form's fields then submit; each goes through the same checks as its own tool, and a step missing a field, or with another action's, is refused before any step runs. Stops at the first that fails or after one that moves the page to another address. |
93
- | `browser_query` `{expression}` | Read just the values you need with a read-only JavaScript expression (JSON, at most 4,000 characters): a results list, prices, counts. It runs in a world of its own where clicks, typing, submits and network writes are refused. The cheapest way to read. |
94
- | `browser_find` `{query}` | Refs of the elements on the whole page that match the words, best first; partial matches are marked. Several targets can be separated by commas. |
95
- | `browser_get_text` `{max_chars?, selector?}` | Readable text of the whole page (PDFs too), or of the first element matching `selector` (`main`, `#results`), secrets masked, up to `max_chars` (default 20,000). |
96
- | `browser_screenshot` `{}` | JPEG of the viewport (off when secrets are configured: the image could show them). |
97
- | `browser_wait` `{seconds}` | Wait 0.5–10 s, then return what changed. Actions already wait for the requests they start. |
98
- | `browser_resume` `{timeout_s?}` | After a result said NEEDS A PERSON and you were asked: waits (default 300 s) until the page has moved on, then returns it. |
99
- | `browser_tabs` `{switch_to?}` | List open tabs; `switch_to: "t2"` makes another tab current. |
100
- | `browser_close` `{}` | Close the browser; the next call starts a fresh one. Not needed at the end of a task: the browser closes when the client disconnects. |
101
-
102
- **Each screen once.** The agent's model keeps every result in its context, and a new token costs it far more than
103
- one it re-reads (a prompt-cache write against a read). So an action on a page the agent was shown a few results back
104
- (at most 8) returns only the lines that changed (`CHANGES ONLY since the page snapshot N browser results back`), each
105
- under its unchanged parent line marked `~ `, with what is gone listed by ref. Refs are stable across snapshots, so the
106
- lines not repeated still work; a change of more than half of the screen gets the whole screen, and
107
- `browser_snapshot` always does. The same goes for what the agent reads before any page: each tool's use is said once,
108
- in its own description, with the rules in the description of the tool they are used with (a "cheapest", "latest" or
109
- "most" is the site's own sort: `browser_navigate`; what to do on `NEEDS A PERSON`: `browser_resume`). Server
110
- instructions are sent only for the settings that need them (secrets, allowed hosts).
111
-
112
- **Pages only a person can pass.** After every acting tool the page is classified. A sign-in with no credentials, a
113
- one-time code or 2FA prompt, a device approval, a sign-in link, a passkey, 3-D Secure or a CAPTCHA adds a
114
- `NEEDS A PERSON (…)` block to the result: what the page needs, and that you should do it in the pilotfish browser
115
- window; the agent then calls `browser_resume`. Nothing tries to get past it (no passwords or codes it was not given,
116
- no CAPTCHA solving). A client that supports elicitation asks you itself and the call goes on when you are done. A
117
- browser check that clears by itself is waited out first (up to 12 s). `BLOCKED:` (the site refused this browser) and
118
- `STOP:` (a never-automate site's bot check) mean nobody can fix it from the window.
119
-
120
- **Confirmations.** Irreversible-looking actions (pay, place an order, send, delete) need your yes. A client with
121
- elicitation asks you; without it such actions are refused with that reason, never read as a "no".
123
+ | `browser_navigate` `{url, snapshot?}` | Open an http(s) URL and return what happened plus the visible screen, with counts of what is above and below. `snapshot: false` returns only what happened and the counts, for a page you will read with `browser_query` and not act on. |
124
+ | `browser_snapshot` `{whole_page?}` | The page as a compact outline with refs (`[e12]<button>Search`): about three screens around the viewport, or all of it with `whole_page`. Every word and ref is kept; repeated text, closing tags and generated ids are left out. |
125
+ | `browser_click` `{ref}` | Click an element. Refused if it is covered, stale or not visible. |
126
+ | `browser_type` `{ref, text, submit?}` | Replace a field's text. `{{name}}` types a configured secret. |
127
+ | `browser_select` `{ref, values}` | Pick `<select>` options by label or value. |
128
+ | `browser_press` `{key}` | Press a key or shortcut (`Enter`, `Escape`, `Control+a`). |
129
+ | `browser_scroll` `{direction}` | Scroll about one screen and return it. |
130
+ | `browser_actions` `{actions}` | Up to 10 steps in one call, such as a form's fields and its submit button. Each step is `{action, …}`: `click`, `type`, `select`, `press`, `scroll` or `wait`, with the same fields as its own tool. A malformed step stops the batch before anything runs; otherwise it stops at the first step that fails or moves to another page. |
131
+ | `browser_query` `{expression}` | Read values with a JavaScript expression that returns JSON (up to 4,000 characters): a list of results, prices, counts. It cannot click, type, submit or send data. The cheapest way to read a page. |
132
+ | `browser_find` `{query}` | Find elements anywhere on the page by their words, best match first. Separate several targets with commas. |
133
+ | `browser_get_text` `{max_chars?, selector?}` | The readable text of the page (PDFs too), or of one element (`main`, `#results`), with secrets masked. Up to `max_chars` (default 20,000). |
134
+ | `browser_screenshot` `{}` | A JPEG of the viewport. Off when secrets are configured, since the image could show them. |
135
+ | `browser_wait` `{seconds}` | Wait 0.5 to 10 seconds, then return what changed. Actions already wait for the requests they start. |
136
+ | `browser_resume` `{timeout_s?}` | After a result said `NEEDS A PERSON`: wait (default 300 s) until you have dealt with the page, then return it. |
137
+ | `browser_tabs` `{switch_to?}` | List open tabs, or switch with `switch_to: "t2"`. |
138
+ | `browser_close` `{}` | Close the browser; the next call opens a fresh one. Not needed at the end: it closes when the client disconnects. |
139
+
140
+ ## How it behaves
141
+
142
+ **Each screen once.** Your agent pays for every token it reads, and new tokens cost far more than ones it has
143
+ already seen. So when the agent acts on a page it saw in one of its last 8 results, it gets only the lines that
144
+ changed, each under its unchanged parent line marked `~ `, with removed elements listed by ref. Refs stay the
145
+ same between snapshots, so lines it was not sent again still work. If more than half the screen changed it gets
146
+ the whole screen, and `browser_snapshot` always returns everything.
147
+
148
+ **Pages that need a person.** After each action the page is checked. A sign-in it has no credentials for, a
149
+ one-time code or two-factor prompt, a device approval, a sign-in link, a passkey, 3-D Secure or a CAPTCHA adds a
150
+ `NEEDS A PERSON` note to the result. You handle it in the browser window and the agent calls `browser_resume`.
151
+ pilotfish never tries to get past these pages itself: no guessed passwords or codes, no CAPTCHA solving. A client
152
+ that supports elicitation asks you directly. A bot check that clears on its own is waited out first, for up to
153
+ 12 seconds. `BLOCKED:` means the site refused this browser, and `STOP:` marks a site that must not be automated.
154
+
155
+ **Confirmations.** Actions that look irreversible (pay, place an order, send, delete) need your yes. A client with
156
+ elicitation asks you; any other client gets the action refused, with the reason.
122
157
 
123
158
  ## Settings
124
159
 
125
- All optional. No API key is read: the server works the same with none set.
160
+ All optional.
126
161
 
127
162
  | Variable | Default | Meaning |
128
163
  | --- | --- | --- |
129
- | `PILOTFISH_HEADLESS` | `0` where a window can be shown (Windows, macOS, Linux with a display), else `1` | `1` hides the browser window; sign-ins and CAPTCHAs then cannot be done by hand. |
130
- | `PILOTFISH_ALLOWED_HOSTS` | any public host | Comma-separated hostname globs (`example.com,*.example.com`) the browser may visit and act on. |
131
- | `PILOTFISH_ALLOW_PRIVATE` | `0` | `1` allows localhost and private networks (development). |
132
- | `PILOTFISH_SECRETS` | | JSON: `{"name": "value"}` or `{"name": {"value"?, "totp"?, "allowedHosts"?}}`, typed as `{{name}}`; a `totp` seed (base32) types the current 2FA code. Values never reach a model, a result or an error message. |
164
+ | `PILOTFISH_HEADLESS` | `0` where a window can open, else `1` | `1` hides the browser window. You then cannot sign in or solve CAPTCHAs by hand. |
165
+ | `PILOTFISH_ALLOWED_HOSTS` | any public site | Comma-separated hostnames the browser may visit, with `*` wildcards (`example.com,*.example.com`). |
166
+ | `PILOTFISH_ALLOW_PRIVATE` | `0` | `1` allows localhost and private networks, for testing your own apps. |
167
+ | `PILOTFISH_SECRETS` | | JSON, either `{"name": "value"}` or `{"name": {"value"?, "totp"?, "allowedHosts"?}}`. Typed as `{{name}}`; a base32 `totp` seed types the current two-factor code. Values never reach the model, a result or an error. |
133
168
  | `PILOTFISH_INTERVENTION_TIMEOUT_MS` | `180000` | How long a call waits for your answer to a question asked in the client. |
134
- | `PILOTFISH_ALLOW_SCREENSHOTS` | on without secrets | `1` allows screenshots even with secrets configured. |
135
- | `PILOTFISH_CHROME` | auto-detect | The browser executable. |
136
- | `PILOTFISH_MCP_TOKEN` | | HTTP mode: the required bearer token. |
169
+ | `PILOTFISH_ALLOW_SCREENSHOTS` | on unless secrets are set | `1` allows screenshots even with secrets configured. |
170
+ | `PILOTFISH_CHROME` | found automatically | Path to the browser executable. |
171
+ | `PILOTFISH_MCP_TOKEN` | | HTTP mode: the bearer token clients must send. |
172
+
173
+ Example with a secret:
174
+
175
+ ```json
176
+ "env": {
177
+ "PILOTFISH_SECRETS": "{\"shop_password\": {\"value\": \"...\", \"allowedHosts\": [\"shop.example.com\"]}}"
178
+ }
179
+ ```
180
+
181
+ ## Privacy
137
182
 
138
- ## What it connects to
183
+ pilotfish connects only to the sites your agent opens, plus the public ad-block lists (EasyList, EasyPrivacy and
184
+ uBlock Origin's filters), downloaded about once a week and cached in `~/.pilotfish/adblock`. No telemetry, no
185
+ pilotfish servers, no model providers.
139
186
 
140
- Only the sites your agent opens, and the public ad-block lists (EasyList, EasyPrivacy, uBlock Origin filters),
141
- fetched about once a week and cached in `~/.pilotfish/adblock`. No telemetry, no pilotfish servers, no model
142
- providers.
187
+ ## More from pilotfish
143
188
 
144
- For saved logins, sessions you can come back to, a cloud browser and whole tasks run for you, see the hosted
145
- pilotfish app: https://pilotfish.gai.ventures (and its MCP,
146
- [`@gaiventures/pilotfish-mcp-managed`](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp-managed)).
189
+ - [pilotfish managed](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp-managed): whole tasks in the cloud,
190
+ signed in as you.
191
+ - [The pilotfish app](https://pilotfish.gai.ventures): run tasks from the web, save logins, watch live, see replays.
147
192
 
148
193
  ## License
149
194
 
package/cli.js CHANGED
@@ -411,7 +411,7 @@ return __pfClassify("Accept all") === "accept" && __pfClassify("Reject all") ===
411
411
  return click.call(this);
412
412
  };
413
413
  })();
414
- ${ns(mr(wr,"autoconsent.playwright.js"),"utf8")}`,$u=3,Tu=2500,Iu=6500,Eu=6e3,Cu=3e3,Au=1500,Mu=3e3,Ou=4e3;function Ru(n,e){if(n.doneAt)return"opted_out";if(n.optOut===!1)return"failed";if(n.optOut===!0)return e-n.optOutAt>Cu?"opted_out":"pending";if(n.popupAt)return"pending";if(n.detectedAt)return e-n.detectedAt<Iu?"pending":"no_cmp";let t=n.topLifecycle!=="nothingDetected",s=l((o,i)=>e-o>=Tu&&i!==void 0&&n.topAttempts>=i+$u,"quiet");return n.cmpRequestAt&&e-n.cmpRequestAt<Eu&&t&&!s(n.cmpRequestAt,n.roundAtCmpRequest)||!n.topInitAt&&/^https?:/.test(n.url)&&e-n.navAt<Au||n.topInitAt&&n.topAttempts<2&&e-n.topInitAt<Mu||n.patternsAt&&e-n.patternsAt<Ou&&t&&!s(n.patternsAt,n.roundAtPatterns)?"pending":"no_cmp"}l(Ru,"outcomeOf");var ss=class{static{l(this,"ConsentEngine")}opts;emitter=new wu;pages=new WeakMap;disposers=new Set;armed=new WeakSet;retried=new WeakSet;retryTimers=new Set;disposed=!1;config;constructor(e={}){if(this.opts=e,this.config=xu(e),this.config.autoAction!=="optOut"||!["off","reject"].includes(this.config.heuristicMode))throw new Error("ConsentEngine only ever opts out")}on(e,t){return this.emitter.on(e,t),()=>this.emitter.off(e,t)}consentStatus(e){let t=this.state(e),s=Date.now(),o=Ru(t,s),i=o==="opted_out"?t.doneAt??t.optOutAt:s;return{cmp:t.cmp,outcome:o,ms:Math.max(0,i-t.navAt),url:t.url,...t.cosmetic!==void 0?{cosmetic:t.cosmetic}:{},...t.selfTest!==void 0?{selfTest:t.selfTest}:{},refusedClicks:t.refused,frames:t.frames.size}}async waitForConsent(e,t=1e4){let s=Date.now()+t;for(;;){let o=this.consentStatus(e);if(o.outcome!=="pending"||Date.now()>=s||e.closed)return o;await new Promise(i=>setTimeout(i,Math.min(100,Math.max(1,s-Date.now()))))}}dispose(){this.disposed=!0;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear();for(let e of this.disposers)e();this.disposers.clear()}initSession=l(async e=>{let t=e.session,s=e.page;if(!e.isMain&&ke(e.url)||this.armed.has(t))return;this.armed.add(t);let o=new Map,i=[()=>this.armed.delete(t)],r;try{[,r]=await Promise.all([t.send("Runtime.addBinding",{name:Je,executionContextName:gn},{timeoutMs:5e3}),t.send("Page.addScriptToEvaluateOnNewDocument",{source:Su,worldName:gn,runImmediately:!0},{timeoutMs:5e3})])}catch(p){if(this.armed.delete(t),e.isMain&&!this.retried.has(t)&&!this.disposed){this.retried.add(t);let f=setTimeout(()=>{this.retryTimers.delete(f),this.disposed||this.initSession(e).catch(()=>{})},2e3);f.unref?.(),this.retryTimers.add(f)}throw p}let a=l(()=>{for(let p of i)p();t.send("Page.removeScriptToEvaluateOnNewDocument",{identifier:r.identifier}).catch(()=>{}),t.send("Runtime.removeBinding",{name:Je}).catch(()=>{})},"dispose");this.disposers.add(a),i.push(()=>this.disposers.delete(a));let c=l(async(p,f,y)=>{if(!/^https?:/.test(f)||!y&&ke(f))return;let{executionContextId:b}=await t.send("Page.createIsolatedWorld",{frameId:p,worldName:gn,grantUniveralAccess:!1},{timeoutMs:5e3});o.set(b,{frameId:p,mainFrame:y}),await t.send("Runtime.addBinding",{name:Je,executionContextId:b},{timeoutMs:5e3}),await t.send("Runtime.evaluate",{contextId:b,expression:"globalThis.__pfAcFlush && __pfAcFlush()",returnByValue:!0},{timeoutMs:5e3})},"arm"),d=l((p,f,y)=>{c(p,f,y).catch(b=>{/not found|Cannot find|No frame|detached|closed|destroyed|navigated/i.test(String(b))||this.emit("error",{page:s,frameId:p,url:f,error:`arm: ${String(b)}`})})},"armSafe");i.push(t.on("Page.frameNavigated",p=>{let f=e.isMain&&!p.frame.parentId;f&&this.reset(s,p.frame.url),d(p.frame.id,p.frame.url,f)}),t.on("Runtime.bindingCalled",p=>{if(p.name!==Je)return;let f=o.get(p.executionContextId);f&&this.onMessage(t,s,p.executionContextId,f,p.payload).catch(()=>{})}),t.on("Network.requestWillBeSent",p=>{if(!Qi(p.request.url))return;let f=this.state(s);f.cmpRequestAt===void 0&&(f.cmpRequestAt=Date.now(),f.roundAtCmpRequest=f.topAttempts)}));let{frameTree:u}=await t.send("Page.getFrameTree"),h=l((p,f)=>{d(p.frame.id,p.frame.url,f);for(let y of p.childFrames??[])h(y,!1)},"walk");h(u,e.isMain)},"initSession");async onMessage(e,t,s,o,i){let r;try{r=JSON.parse(i)}catch{return}let a=this.state(t),c=typeof r.url=="string"?r.url:"",d={page:t,frameId:o.frameId,url:c},u=typeof r.cmp=="string"?r.cmp:"";switch(r.type){case"init":{a.frames.add(o.frameId),o.mainFrame&&(a.topInitAt??=Date.now());let h={autoconsent:[],compact:ku(yr,{url:c,mainFrame:o.mainFrame})};await this.reply(e,s,{type:"initResp",config:this.config,rules:h});return}case"eval":await this.reply(e,s,{type:"evalResp",id:r.id,result:await this.runSnippet(e,t,s,o,r.snippetId)});return;case"cmpDetected":a.cmp??=u,a.detectedAt??=Date.now(),this.emit("cmpDetected",{...d,cmp:u});return;case"popupFound":a.cmp=u,a.popupAt??=Date.now(),this.emit("popupFound",{...d,cmp:u});return;case"optOutResult":a.cmp=u||a.cmp,a.optOut=r.result===!0,a.optOutAt=Date.now(),r.result===!0&&r.scheduleSelfTest===!0&&(a.selfTestTarget={s:e,contextId:s}),this.emit("optOutResult",{...d,cmp:u,result:r.result===!0});return;case"autoconsentDone":{a.cmp=u||a.cmp,a.doneAt=Date.now(),a.cosmetic=r.isCosmetic===!0,this.emit("autoconsentDone",{...d,cmp:u,cosmetic:a.cosmetic,durationMs:Number(r.duration)||0,clicks:Number(r.totalClicks)||0});let h=a.selfTestTarget;a.selfTestTarget=void 0,this.opts.selfTest!==!1&&h&&await this.reply(h.s,h.contextId,{type:"selfTest"});return}case"selfTestResult":a.selfTest=r.result===!0,this.emit("selfTestResult",{...d,cmp:u,result:a.selfTest});return;case"optInResult":this.emit("error",{...d,error:"unexpected optInResult",details:r});return;case"autoconsentError":this.emit("error",{...d,error:"autoconsent",details:r.details});return;case"pfRefusedClick":a.refused++,this.emit("error",{...d,error:`refused to click an accept button: "${String(r.text)}"`});return;case"report":{let h=r.state??{};if(!o.mainFrame||r.mainFrame!==!0)return;a.topLifecycle=h.lifecycle,a.topAttempts=Math.max(a.topAttempts,Number(h.findCmpAttempts)||0),h.heuristicPatterns?.length&&a.patternsAt===void 0&&(a.patternsAt=Date.now(),a.roundAtPatterns=a.topAttempts);return}default:return}}reply(e,t,s){return e.send("Runtime.evaluate",{contextId:t,expression:`autoconsentReceiveMessage(${JSON.stringify(s)})`,returnByValue:!0}).catch(()=>{})}async runSnippet(e,t,s,o,i){let r=typeof i=="string"?gr[i]:void 0;if(!r||vu.has(i))return this.emit("error",{page:t,frameId:o.frameId,error:`refused eval snippet ${String(i)}`}),!1;let a=await e.send("Runtime.evaluate",{contextId:s,expression:"document",returnByValue:!1});if(!a.result.objectId)return!1;try{let{node:c}=await e.send("DOM.describeNode",{objectId:a.result.objectId}),{object:d}=await e.send("DOM.resolveNode",{backendNodeId:c.backendNodeId});if(!d.objectId)return!1;try{return(await e.send("Runtime.callFunctionOn",{objectId:d.objectId,functionDeclaration:`async function () { try { return !!(await (${r.toString()}).call(window)); } catch (e) { return false; } }`,returnByValue:!0,awaitPromise:!0})).result.value===!0}finally{e.send("Runtime.releaseObject",{objectId:d.objectId}).catch(()=>{})}}catch{return!1}finally{e.send("Runtime.releaseObject",{objectId:a.result.objectId}).catch(()=>{})}}state(e){let t=this.pages.get(e);return t||(t={navAt:Date.now(),url:e.url,cmp:null,refused:0,frames:new Set,topAttempts:0},this.pages.set(e,t)),t}reset(e,t){this.pages.set(e,{navAt:Date.now(),url:t,cmp:null,refused:0,frames:new Set,topAttempts:0})}emit(e,t){e==="error"&&this.emitter.listenerCount("error")===0||this.emitter.emit(e,t)}};var Pu=["cmpDetected","popupFound","optOutResult","autoconsentDone","selfTestResult","error"],Nu=["blocked","error"];async function yn(n,e={}){let t=e.consent===!1?null:new ss(typeof e.consent=="object"?e.consent:{}),s=e.adblock===!1?null:await ts.create(typeof e.adblock=="object"?e.adblock:{}),o=[];if(e.onEvent){let r=e.onEvent;if(t)for(let a of Pu)o.push(t.on(a,(c=>r({source:"consent",type:a,data:c}))));if(s)for(let a of Nu)o.push(s.on(a,(c=>r({source:"adblock",type:a,data:c}))))}let i=l(async r=>{await Promise.all([t?.initSession(r),s?.initSession(r)])},"init");return o.push(n.addSessionInitializer(i)),{consent:t,adblock:s,detach(){for(let r of o)r();t?.dispose(),s?.dispose()}}}l(yn,"attachInterrupts");var Du="pilotfish's open MCP makes no model calls: the MCP client's own model reads the page and decides the next step",Lu=l(()=>{let n=l(async()=>{throw new Error(Du)},"refuse");return{messages:{create:n},beta:{messages:{create:n}}}},"noModelClient"),bn=class{static{l(this,"ConfirmThrough")}inner;canAsk;constructor(e,t){this.inner=e,this.canAsk=t}async check(e){let t=await this.inner.check(e);return t.kind!=="confirm"||this.canAsk()?t:{kind:"deny",reason:`${t.reason}. This needs a person's confirmation, and this MCP client cannot ask for one (no elicitation support)`}}},Xe=class{static{l(this,"BrowserSession")}config;opts;browser=null;launching=null;interrupts=null;tabs=null;agent=null;queue=Promise.resolve();policy;asker;constructor(e,t={}){this.config=e,this.opts=t,this.policy=new Pe({allowedHosts:e.allowedHosts,allowPrivateNetwork:e.allowPrivateNetwork})}get launched(){return!!this.browser&&!this.browser.closed}async page(){return await this.ensure(),this.tabs.current}get tabTable(){return this.tabs}async ensure(){return this.browser&&!this.browser.closed?this.browser:(this.launching??=this.start().finally(()=>{this.launching=null}),this.launching)}async start(){let e=await ks({...this.opts.launch,headless:this.config.headless});this.interrupts=await yn(e,{consent:!0,adblock:!0}).catch(()=>null);let t=e.allPages()[0]??await e.newPage();return this.tabs=new Ne(t),this.browser=e,e.on("disconnected",()=>{this.browser===e&&this.reset()}),e}reset(){this.agent?.dispose(),this.agent=null,this.tabs?.dispose(),this.tabs=null,this.interrupts?.detach(),this.interrupts=null,this.browser=null}executor(){return this.agent??=new wt(this.tabs.current,{tabs:this.tabs,client:Lu(),secrets:this.config.secrets,policy:new bn(this.policy,()=>!!this.asker),consent:this.interrupts?.consent??void 0,allowScreenshots:this.config.allowScreenshots,askUser:l(e=>this.asker?.(e)??Promise.resolve(null),"askUser"),fastSettle:!0,enableQuery:!0,compactSnapshots:!0,autoDismiss:!0,awaitLoading:!0,actionSnapshotBand:0,snapshotMoreHint:"browser_scroll for the next screen, browser_get_text for the page's text, or browser_snapshot (whole_page) for every element"}),this.agent}async act(e,t,s={}){let o=this.queue.then(async()=>(await this.ensure(),this.executor().act(e,t,"",s)));return this.queue=o.catch(()=>{}),o}async obstacle(e={}){if(!this.launched)return null;let t=this.queue.then(()=>this.executor().obstacle(e));return this.queue=t.catch(()=>{}),t.catch(()=>null)}async close(){let e=this.browser??(this.launching?await this.launching.catch(()=>null):null);return e?(this.reset(),await e.close().catch(()=>{}),!0):!1}};import{McpServer as Fu}from"@modelcontextprotocol/sdk/server/mcp.js";import{ListToolsRequestSchema as Hu}from"@modelcontextprotocol/sdk/types.js";import{z as q}from"zod";var os="0.1.19";var is=Oe.click.shape.ref.describe('From the latest snapshot, e.g. "e12" or "f1e3"'),br=q.enum(["down","up","left","right"]),Uu={click:["ref"],type:["ref","text","submit"],select:["ref","values"],press:["key"],scroll:["direction"],wait:["seconds"]},ju={click:1,type:2,select:2,press:1,scroll:1,wait:1},Bu=q.object({action:q.enum(["click","type","select","press","scroll","wait"]).describe("click, select, type take ref; type: text (submit: Enter after); select: values; press: key; scroll: direction; wait: seconds"),ref:is.optional(),text:q.string().max(2e4).optional(),submit:q.boolean().optional(),values:q.array(q.string()).min(1).max(50).optional(),key:q.string().min(1).max(40).optional(),direction:br.optional(),seconds:q.number().min(.5).max(10).optional()}).strict().superRefine((n,e)=>{let t=Uu[n.action];for(let s of t.slice(0,ju[n.action]))n[s]===void 0&&e.addIssue({code:"custom",path:[s],message:`${n.action} needs ${s}`});for(let s of Object.keys(n))s!=="action"&&!t.includes(s)&&e.addIssue({code:"custom",path:[s],message:`${s} is not a field of ${n.action} (it takes ${t.join(", ")})`})}),re={browser_navigate:q.object({url:q.url({protocol:/^https?$/}).describe("Absolute http(s) URL"),snapshot:q.boolean().optional().describe("Default true. false: no page snapshot, only what happened (title, counts). Only when this same reply also reads the page with browser_query and you will not act on it; keep it for a page you have not seen or whose tabs, sorts, filters or forms you may use.")}).strict(),browser_snapshot:q.object({whole_page:q.boolean().optional()}).strict(),browser_click:q.object({ref:is}).strict(),browser_type:q.object({ref:is,text:q.string().max(2e4),submit:q.boolean().optional().describe("Press Enter afterwards")}).strict(),browser_select:q.object({ref:is,values:q.array(q.string()).min(1).max(50)}).strict(),browser_press:q.object({key:q.string().min(1).max(40).describe('e.g. "Enter", "Escape", "Tab", "ArrowDown", "Control+a"')}).strict(),browser_scroll:q.object({direction:br}).strict(),browser_screenshot:q.object({}).strict(),browser_get_text:q.object({max_chars:q.number().int().min(500).max(6e4).optional().describe("Default 20000. Ask for less when the start of the page is enough."),selector:q.string().min(1).max(300).optional().describe(`CSS selector: only the first match's text, e.g. "main" or "#results"`)}).strict(),browser_query:q.object({expression:q.string().min(1).max(4e3).describe("e.g. [...document.querySelectorAll('.result')].slice(0,10).map(e => e.innerText)")}).strict(),browser_find:q.object({query:q.string().min(1).max(300).describe('Words naming the element(s), e.g. "Sort by" or "price max input, Go button"')}).strict(),browser_wait:q.object({seconds:q.number().min(.5).max(10)}).strict(),browser_resume:q.object({timeout_s:q.number().int().min(5).max(900).optional().describe("Default 300")}).strict(),browser_actions:q.object({actions:q.array(Bu).min(1).max(10)}).strict(),browser_tabs:q.object({switch_to:q.string().min(1).max(10).optional().describe('Tab id to work in from now on, e.g. "t2"')}).strict(),browser_close:q.object({}).strict()};function Te(n,e=!1){return{content:[{type:"text",text:n}],...e?{isError:!0}:{}}}l(Te,"text");function qu(n){let e=Object.keys(n.secrets),t=[e.length?`Secrets are typed as placeholders and never shown: ${e.map(s=>`{{${s}}}`).join(", ")}.`:"",n.allowedHosts.length?`Navigation is limited to: ${n.allowedHosts.join(", ")}.`:""].filter(Boolean);return t.length?t.join(`
414
+ ${ns(mr(wr,"autoconsent.playwright.js"),"utf8")}`,$u=3,Tu=2500,Iu=6500,Eu=6e3,Cu=3e3,Au=1500,Mu=3e3,Ou=4e3;function Ru(n,e){if(n.doneAt)return"opted_out";if(n.optOut===!1)return"failed";if(n.optOut===!0)return e-n.optOutAt>Cu?"opted_out":"pending";if(n.popupAt)return"pending";if(n.detectedAt)return e-n.detectedAt<Iu?"pending":"no_cmp";let t=n.topLifecycle!=="nothingDetected",s=l((o,i)=>e-o>=Tu&&i!==void 0&&n.topAttempts>=i+$u,"quiet");return n.cmpRequestAt&&e-n.cmpRequestAt<Eu&&t&&!s(n.cmpRequestAt,n.roundAtCmpRequest)||!n.topInitAt&&/^https?:/.test(n.url)&&e-n.navAt<Au||n.topInitAt&&n.topAttempts<2&&e-n.topInitAt<Mu||n.patternsAt&&e-n.patternsAt<Ou&&t&&!s(n.patternsAt,n.roundAtPatterns)?"pending":"no_cmp"}l(Ru,"outcomeOf");var ss=class{static{l(this,"ConsentEngine")}opts;emitter=new wu;pages=new WeakMap;disposers=new Set;armed=new WeakSet;retried=new WeakSet;retryTimers=new Set;disposed=!1;config;constructor(e={}){if(this.opts=e,this.config=xu(e),this.config.autoAction!=="optOut"||!["off","reject"].includes(this.config.heuristicMode))throw new Error("ConsentEngine only ever opts out")}on(e,t){return this.emitter.on(e,t),()=>this.emitter.off(e,t)}consentStatus(e){let t=this.state(e),s=Date.now(),o=Ru(t,s),i=o==="opted_out"?t.doneAt??t.optOutAt:s;return{cmp:t.cmp,outcome:o,ms:Math.max(0,i-t.navAt),url:t.url,...t.cosmetic!==void 0?{cosmetic:t.cosmetic}:{},...t.selfTest!==void 0?{selfTest:t.selfTest}:{},refusedClicks:t.refused,frames:t.frames.size}}async waitForConsent(e,t=1e4){let s=Date.now()+t;for(;;){let o=this.consentStatus(e);if(o.outcome!=="pending"||Date.now()>=s||e.closed)return o;await new Promise(i=>setTimeout(i,Math.min(100,Math.max(1,s-Date.now()))))}}dispose(){this.disposed=!0;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear();for(let e of this.disposers)e();this.disposers.clear()}initSession=l(async e=>{let t=e.session,s=e.page;if(!e.isMain&&ke(e.url)||this.armed.has(t))return;this.armed.add(t);let o=new Map,i=[()=>this.armed.delete(t)],r;try{[,r]=await Promise.all([t.send("Runtime.addBinding",{name:Je,executionContextName:gn},{timeoutMs:5e3}),t.send("Page.addScriptToEvaluateOnNewDocument",{source:Su,worldName:gn,runImmediately:!0},{timeoutMs:5e3})])}catch(p){if(this.armed.delete(t),e.isMain&&!this.retried.has(t)&&!this.disposed){this.retried.add(t);let f=setTimeout(()=>{this.retryTimers.delete(f),this.disposed||this.initSession(e).catch(()=>{})},2e3);f.unref?.(),this.retryTimers.add(f)}throw p}let a=l(()=>{for(let p of i)p();t.send("Page.removeScriptToEvaluateOnNewDocument",{identifier:r.identifier}).catch(()=>{}),t.send("Runtime.removeBinding",{name:Je}).catch(()=>{})},"dispose");this.disposers.add(a),i.push(()=>this.disposers.delete(a));let c=l(async(p,f,y)=>{if(!/^https?:/.test(f)||!y&&ke(f))return;let{executionContextId:b}=await t.send("Page.createIsolatedWorld",{frameId:p,worldName:gn,grantUniveralAccess:!1},{timeoutMs:5e3});o.set(b,{frameId:p,mainFrame:y}),await t.send("Runtime.addBinding",{name:Je,executionContextId:b},{timeoutMs:5e3}),await t.send("Runtime.evaluate",{contextId:b,expression:"globalThis.__pfAcFlush && __pfAcFlush()",returnByValue:!0},{timeoutMs:5e3})},"arm"),d=l((p,f,y)=>{c(p,f,y).catch(b=>{/not found|Cannot find|No frame|detached|closed|destroyed|navigated/i.test(String(b))||this.emit("error",{page:s,frameId:p,url:f,error:`arm: ${String(b)}`})})},"armSafe");i.push(t.on("Page.frameNavigated",p=>{let f=e.isMain&&!p.frame.parentId;f&&this.reset(s,p.frame.url),d(p.frame.id,p.frame.url,f)}),t.on("Runtime.bindingCalled",p=>{if(p.name!==Je)return;let f=o.get(p.executionContextId);f&&this.onMessage(t,s,p.executionContextId,f,p.payload).catch(()=>{})}),t.on("Network.requestWillBeSent",p=>{if(!Qi(p.request.url))return;let f=this.state(s);f.cmpRequestAt===void 0&&(f.cmpRequestAt=Date.now(),f.roundAtCmpRequest=f.topAttempts)}));let{frameTree:u}=await t.send("Page.getFrameTree"),h=l((p,f)=>{d(p.frame.id,p.frame.url,f);for(let y of p.childFrames??[])h(y,!1)},"walk");h(u,e.isMain)},"initSession");async onMessage(e,t,s,o,i){let r;try{r=JSON.parse(i)}catch{return}let a=this.state(t),c=typeof r.url=="string"?r.url:"",d={page:t,frameId:o.frameId,url:c},u=typeof r.cmp=="string"?r.cmp:"";switch(r.type){case"init":{a.frames.add(o.frameId),o.mainFrame&&(a.topInitAt??=Date.now());let h={autoconsent:[],compact:ku(yr,{url:c,mainFrame:o.mainFrame})};await this.reply(e,s,{type:"initResp",config:this.config,rules:h});return}case"eval":await this.reply(e,s,{type:"evalResp",id:r.id,result:await this.runSnippet(e,t,s,o,r.snippetId)});return;case"cmpDetected":a.cmp??=u,a.detectedAt??=Date.now(),this.emit("cmpDetected",{...d,cmp:u});return;case"popupFound":a.cmp=u,a.popupAt??=Date.now(),this.emit("popupFound",{...d,cmp:u});return;case"optOutResult":a.cmp=u||a.cmp,a.optOut=r.result===!0,a.optOutAt=Date.now(),r.result===!0&&r.scheduleSelfTest===!0&&(a.selfTestTarget={s:e,contextId:s}),this.emit("optOutResult",{...d,cmp:u,result:r.result===!0});return;case"autoconsentDone":{a.cmp=u||a.cmp,a.doneAt=Date.now(),a.cosmetic=r.isCosmetic===!0,this.emit("autoconsentDone",{...d,cmp:u,cosmetic:a.cosmetic,durationMs:Number(r.duration)||0,clicks:Number(r.totalClicks)||0});let h=a.selfTestTarget;a.selfTestTarget=void 0,this.opts.selfTest!==!1&&h&&await this.reply(h.s,h.contextId,{type:"selfTest"});return}case"selfTestResult":a.selfTest=r.result===!0,this.emit("selfTestResult",{...d,cmp:u,result:a.selfTest});return;case"optInResult":this.emit("error",{...d,error:"unexpected optInResult",details:r});return;case"autoconsentError":this.emit("error",{...d,error:"autoconsent",details:r.details});return;case"pfRefusedClick":a.refused++,this.emit("error",{...d,error:`refused to click an accept button: "${String(r.text)}"`});return;case"report":{let h=r.state??{};if(!o.mainFrame||r.mainFrame!==!0)return;a.topLifecycle=h.lifecycle,a.topAttempts=Math.max(a.topAttempts,Number(h.findCmpAttempts)||0),h.heuristicPatterns?.length&&a.patternsAt===void 0&&(a.patternsAt=Date.now(),a.roundAtPatterns=a.topAttempts);return}default:return}}reply(e,t,s){return e.send("Runtime.evaluate",{contextId:t,expression:`autoconsentReceiveMessage(${JSON.stringify(s)})`,returnByValue:!0}).catch(()=>{})}async runSnippet(e,t,s,o,i){let r=typeof i=="string"?gr[i]:void 0;if(!r||vu.has(i))return this.emit("error",{page:t,frameId:o.frameId,error:`refused eval snippet ${String(i)}`}),!1;let a=await e.send("Runtime.evaluate",{contextId:s,expression:"document",returnByValue:!1});if(!a.result.objectId)return!1;try{let{node:c}=await e.send("DOM.describeNode",{objectId:a.result.objectId}),{object:d}=await e.send("DOM.resolveNode",{backendNodeId:c.backendNodeId});if(!d.objectId)return!1;try{return(await e.send("Runtime.callFunctionOn",{objectId:d.objectId,functionDeclaration:`async function () { try { return !!(await (${r.toString()}).call(window)); } catch (e) { return false; } }`,returnByValue:!0,awaitPromise:!0})).result.value===!0}finally{e.send("Runtime.releaseObject",{objectId:d.objectId}).catch(()=>{})}}catch{return!1}finally{e.send("Runtime.releaseObject",{objectId:a.result.objectId}).catch(()=>{})}}state(e){let t=this.pages.get(e);return t||(t={navAt:Date.now(),url:e.url,cmp:null,refused:0,frames:new Set,topAttempts:0},this.pages.set(e,t)),t}reset(e,t){this.pages.set(e,{navAt:Date.now(),url:t,cmp:null,refused:0,frames:new Set,topAttempts:0})}emit(e,t){e==="error"&&this.emitter.listenerCount("error")===0||this.emitter.emit(e,t)}};var Pu=["cmpDetected","popupFound","optOutResult","autoconsentDone","selfTestResult","error"],Nu=["blocked","error"];async function yn(n,e={}){let t=e.consent===!1?null:new ss(typeof e.consent=="object"?e.consent:{}),s=e.adblock===!1?null:await ts.create(typeof e.adblock=="object"?e.adblock:{}),o=[];if(e.onEvent){let r=e.onEvent;if(t)for(let a of Pu)o.push(t.on(a,(c=>r({source:"consent",type:a,data:c}))));if(s)for(let a of Nu)o.push(s.on(a,(c=>r({source:"adblock",type:a,data:c}))))}let i=l(async r=>{await Promise.all([t?.initSession(r),s?.initSession(r)])},"init");return o.push(n.addSessionInitializer(i)),{consent:t,adblock:s,detach(){for(let r of o)r();t?.dispose(),s?.dispose()}}}l(yn,"attachInterrupts");var Du="pilotfish's open MCP makes no model calls: the MCP client's own model reads the page and decides the next step",Lu=l(()=>{let n=l(async()=>{throw new Error(Du)},"refuse");return{messages:{create:n},beta:{messages:{create:n}}}},"noModelClient"),bn=class{static{l(this,"ConfirmThrough")}inner;canAsk;constructor(e,t){this.inner=e,this.canAsk=t}async check(e){let t=await this.inner.check(e);return t.kind!=="confirm"||this.canAsk()?t:{kind:"deny",reason:`${t.reason}. This needs a person's confirmation, and this MCP client cannot ask for one (no elicitation support)`}}},Xe=class{static{l(this,"BrowserSession")}config;opts;browser=null;launching=null;interrupts=null;tabs=null;agent=null;queue=Promise.resolve();policy;asker;constructor(e,t={}){this.config=e,this.opts=t,this.policy=new Pe({allowedHosts:e.allowedHosts,allowPrivateNetwork:e.allowPrivateNetwork})}get launched(){return!!this.browser&&!this.browser.closed}async page(){return await this.ensure(),this.tabs.current}get tabTable(){return this.tabs}async ensure(){return this.browser&&!this.browser.closed?this.browser:(this.launching??=this.start().finally(()=>{this.launching=null}),this.launching)}async start(){let e=await ks({...this.opts.launch,headless:this.config.headless});this.interrupts=await yn(e,{consent:!0,adblock:!0}).catch(()=>null);let t=e.allPages()[0]??await e.newPage();return this.tabs=new Ne(t),this.browser=e,e.on("disconnected",()=>{this.browser===e&&this.reset()}),e}reset(){this.agent?.dispose(),this.agent=null,this.tabs?.dispose(),this.tabs=null,this.interrupts?.detach(),this.interrupts=null,this.browser=null}executor(){return this.agent??=new wt(this.tabs.current,{tabs:this.tabs,client:Lu(),secrets:this.config.secrets,policy:new bn(this.policy,()=>!!this.asker),consent:this.interrupts?.consent??void 0,allowScreenshots:this.config.allowScreenshots,askUser:l(e=>this.asker?.(e)??Promise.resolve(null),"askUser"),fastSettle:!0,enableQuery:!0,compactSnapshots:!0,autoDismiss:!0,awaitLoading:!0,actionSnapshotBand:0,snapshotMoreHint:"browser_scroll for the next screen, browser_get_text for the page's text, or browser_snapshot (whole_page) for every element"}),this.agent}async act(e,t,s={}){let o=this.queue.then(async()=>(await this.ensure(),this.executor().act(e,t,"",s)));return this.queue=o.catch(()=>{}),o}async obstacle(e={}){if(!this.launched)return null;let t=this.queue.then(()=>this.executor().obstacle(e));return this.queue=t.catch(()=>{}),t.catch(()=>null)}async close(){let e=this.browser??(this.launching?await this.launching.catch(()=>null):null);return e?(this.reset(),await e.close().catch(()=>{}),!0):!1}};import{McpServer as Fu}from"@modelcontextprotocol/sdk/server/mcp.js";import{ListToolsRequestSchema as Hu}from"@modelcontextprotocol/sdk/types.js";import{z as q}from"zod";var os="0.1.20";var is=Oe.click.shape.ref.describe('From the latest snapshot, e.g. "e12" or "f1e3"'),br=q.enum(["down","up","left","right"]),Uu={click:["ref"],type:["ref","text","submit"],select:["ref","values"],press:["key"],scroll:["direction"],wait:["seconds"]},ju={click:1,type:2,select:2,press:1,scroll:1,wait:1},Bu=q.object({action:q.enum(["click","type","select","press","scroll","wait"]).describe("click, select, type take ref; type: text (submit: Enter after); select: values; press: key; scroll: direction; wait: seconds"),ref:is.optional(),text:q.string().max(2e4).optional(),submit:q.boolean().optional(),values:q.array(q.string()).min(1).max(50).optional(),key:q.string().min(1).max(40).optional(),direction:br.optional(),seconds:q.number().min(.5).max(10).optional()}).strict().superRefine((n,e)=>{let t=Uu[n.action];for(let s of t.slice(0,ju[n.action]))n[s]===void 0&&e.addIssue({code:"custom",path:[s],message:`${n.action} needs ${s}`});for(let s of Object.keys(n))s!=="action"&&!t.includes(s)&&e.addIssue({code:"custom",path:[s],message:`${s} is not a field of ${n.action} (it takes ${t.join(", ")})`})}),re={browser_navigate:q.object({url:q.url({protocol:/^https?$/}).describe("Absolute http(s) URL"),snapshot:q.boolean().optional().describe("Default true. false: no page snapshot, only what happened (title, counts). Only when this same reply also reads the page with browser_query and you will not act on it; keep it for a page you have not seen or whose tabs, sorts, filters or forms you may use.")}).strict(),browser_snapshot:q.object({whole_page:q.boolean().optional()}).strict(),browser_click:q.object({ref:is}).strict(),browser_type:q.object({ref:is,text:q.string().max(2e4),submit:q.boolean().optional().describe("Press Enter afterwards")}).strict(),browser_select:q.object({ref:is,values:q.array(q.string()).min(1).max(50)}).strict(),browser_press:q.object({key:q.string().min(1).max(40).describe('e.g. "Enter", "Escape", "Tab", "ArrowDown", "Control+a"')}).strict(),browser_scroll:q.object({direction:br}).strict(),browser_screenshot:q.object({}).strict(),browser_get_text:q.object({max_chars:q.number().int().min(500).max(6e4).optional().describe("Default 20000. Ask for less when the start of the page is enough."),selector:q.string().min(1).max(300).optional().describe(`CSS selector: only the first match's text, e.g. "main" or "#results"`)}).strict(),browser_query:q.object({expression:q.string().min(1).max(4e3).describe("e.g. [...document.querySelectorAll('.result')].slice(0,10).map(e => e.innerText)")}).strict(),browser_find:q.object({query:q.string().min(1).max(300).describe('Words naming the element(s), e.g. "Sort by" or "price max input, Go button"')}).strict(),browser_wait:q.object({seconds:q.number().min(.5).max(10)}).strict(),browser_resume:q.object({timeout_s:q.number().int().min(5).max(900).optional().describe("Default 300")}).strict(),browser_actions:q.object({actions:q.array(Bu).min(1).max(10)}).strict(),browser_tabs:q.object({switch_to:q.string().min(1).max(10).optional().describe('Tab id to work in from now on, e.g. "t2"')}).strict(),browser_close:q.object({}).strict()};function Te(n,e=!1){return{content:[{type:"text",text:n}],...e?{isError:!0}:{}}}l(Te,"text");function qu(n){let e=Object.keys(n.secrets),t=[e.length?`Secrets are typed as placeholders and never shown: ${e.map(s=>`{{${s}}}`).join(", ")}.`:"",n.allowedHosts.length?`Navigation is limited to: ${n.allowedHosts.join(", ")}.`:""].filter(Boolean);return t.length?t.join(`
415
415
  `):void 0}l(qu,"serverInstructions");function kn(n={}){let e=n.config??n.session?.config??vt(),t=!n.session,s=n.session??new Xe(e,n),o=new Fu({name:"pilotfish",version:n.version??os},{capabilities:{logging:{}},instructions:qu(e)}),i=Object.keys(e.secrets),r=i.length?` Secrets: ${i.map(g=>`{{${g}}}`).join(", ")}.`:"",a=l(()=>!!o.server.getClientCapabilities()?.elicitation?.form,"canElicit"),c=l(g=>a()?async S=>{let E=await o.server.elicitInput({message:S,requestedSchema:{type:"object",properties:{answer:{type:"string",title:"Answer",description:'Reply "yes" to allow an action'}},required:["answer"]}},{relatedRequestId:g.requestId,timeout:e.interventionTimeoutMs}).catch(()=>null);return E?.action==="accept"&&typeof E.content?.answer=="string"?E.content.answer:null}:void 0,"askerFor"),d=l(g=>g.replace(/in the live view/g,"in the pilotfish browser window").replace(/Please send the code, or type it/,"Please type the code"),"forWindow"),u=l(g=>g.needs==="solve_in_live_view"||g.needs==="login_in_live_view"||g.needs==="code"||g.needs==="credentials","byHand"),h=l((g,S="")=>[`NEEDS A PERSON (${g.category}${g.vendor?`, ${g.vendor}`:""}): ${d(g.message)}`,S,u(g)&&e.headless?"This browser is headless, so it cannot be done by hand here: tell the user, and that the pilotfish server needs PILOTFISH_HEADLESS=0 (a visible window) for steps like this one.":`Tell the user now, in your reply: what the page needs, and that the pilotfish browser window is open on it (${g.url}). Ask them to do it there and to tell you when it is done. Then call browser_resume: it waits for the page to move on and returns it.`,"Do not try to get past it yourself: pilotfish does not type passwords or codes it was not given, and does not solve CAPTCHAs."].filter(Boolean).join(`
416
416
  `),"needsPerson"),p=l(async()=>{let g=await s.act("read_page",{}).catch(()=>null);return g?g.text||g.summary:""},"pageNow"),f=l(async(g,S=1e3)=>{let E=Date.now()+g,A=await s.obstacle({fresh:!0});for(;A&&Date.now()<E;)await new Promise(k=>setTimeout(k,S)),A=await s.obstacle({fresh:!0});return A},"untilClear"),y=l((g,S)=>({...g,content:[...g.content,{type:"text",text:S}]}),"withNote"),b=l(async(g,S)=>{let E=await s.obstacle();if(!E)return S;if(E.autoResolvable&&!E.neverAutomate&&(E=await f(12e3),!E))return y(S,`A browser check was showing and cleared by itself. The page now:
417
417
  ${await p()}`);if(E.neverAutomate)return y(S,`STOP: ${E.host} shows a bot check, and this site is never automated past one (ticket sellers: the US BOTS Act; UIDAI: the Aadhaar Act). Do not continue on it; tell the user.`);if(E.category==="hard_block"||E.needs==="none_possible")return y(S,`BLOCKED: ${d(E.message)} A person cannot fix this from the browser window: try another way (another page or site), or tell the user.`);if(a()&&!(u(E)&&e.headless)){let A=await o.server.elicitInput({message:`${d(E.message)} (${E.url})`,requestedSchema:{type:"object",properties:{done:{type:"boolean",title:"I have done it in the pilotfish browser window"}},required:["done"]}},{relatedRequestId:g.requestId,timeout:e.interventionTimeoutMs}).catch(()=>null);if(A?.action==="accept"&&A.content?.done!==!1){let k=await f(15e3);return k?y(S,h(k,"The person said it is done, but the page still shows it.")):y(S,`The person handled it. The page now:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gaiventures/pilotfish-mcp",
3
- "version": "0.1.19",
4
- "description": "A real Chromium on your machine for any MCP agent: ref-based tools, evidence per action, no API key.",
3
+ "version": "0.1.20",
4
+ "description": "Give any MCP agent a real Chrome on your own computer. Free, no account, no API key.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
@@ -37,8 +37,11 @@
37
37
  "mcp",
38
38
  "mcp-server",
39
39
  "model-context-protocol",
40
+ "pilotfish",
40
41
  "browser",
41
42
  "browser-automation",
43
+ "browser-agent",
44
+ "ai-agent",
42
45
  "chromium",
43
46
  "chrome-devtools-protocol",
44
47
  "claude-code",