pilotfish-ai 0.1.0__tar.gz

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.
@@ -0,0 +1,5 @@
1
+ dist/
2
+ build/
3
+ *.egg-info/
4
+ __pycache__/
5
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gAI Ventures
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,317 @@
1
+ Metadata-Version: 2.5
2
+ Name: pilotfish-ai
3
+ Version: 0.1.0
4
+ Summary: Run browser tasks in pilotfish's cloud from Python, or drive Chrome on your own machine.
5
+ Project-URL: Homepage, https://pilotfish.gai.ventures/docs/sdk
6
+ Project-URL: Documentation, https://pilotfish.gai.ventures/docs/sdk
7
+ Project-URL: Source, https://github.com/gAI-ventures/pilotfish-ai/tree/main/sdks/python
8
+ Project-URL: Issues, https://github.com/gAI-ventures/pilotfish-ai/issues
9
+ Author: gAI Ventures
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: ai agent,browser agent,browser automation,mcp,web automation
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.9
26
+ Requires-Dist: httpx<1,>=0.25
27
+ Provides-Extra: test
28
+ Requires-Dist: pytest>=7; extra == 'test'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # pilotfish for Python
32
+
33
+ Run browser tasks in [pilotfish](https://pilotfish.gai.ventures)'s cloud from Python, or drive Chrome on your own
34
+ machine.
35
+
36
+ pilotfish's agent and its open MCP send a page to the model as a compact outline with refs (`[e12]<button>Search`),
37
+ and after each step only what changed, never the whole page again. That means far fewer tokens per step and faster
38
+ steps than screenshots or raw HTML.
39
+
40
+ Two clients in one package:
41
+
42
+ - **`Pilotfish`** (and **`AsyncPilotfish`**): the hosted client. Describe a task in words; pilotfish's agent runs it in
43
+ a cloud browser (signed in with saved logins, bot checks handled, a person asked only when needed) and returns the answer, as text or as JSON matching your schema. Paid from your org's credits.
44
+ - **`LocalBrowser`**: Chrome on your own machine and IP, driven step by step from your code through the open MCP's
45
+ browser tools. No account, no API key, no model calls.
46
+
47
+ ```bash
48
+ pip install pilotfish-ai
49
+ ```
50
+
51
+ Installed as `pilotfish-ai`, imported as `pilotfish`. Python 3.9 or newer. The only dependency is
52
+ [httpx](https://www.python-httpx.org/).
53
+
54
+ ## Hosted quickstart
55
+
56
+ Make an API key in the app at <https://pilotfish.gai.ventures> (Org settings → API keys) and set it as
57
+ `PILOTFISH_API_KEY`.
58
+
59
+ ```python
60
+ from pilotfish import Pilotfish
61
+
62
+ pf = Pilotfish() # reads PILOTFISH_API_KEY; or Pilotfish(api_key="pf_...")
63
+
64
+ task = pf.tasks.run("Find the cheapest blue desk lamp on ikea.com and give its name and price")
65
+ print(task["status"]) # done, failed, cancelled, or needs_input
66
+ print(task["result"]["result"]) # the answer, in words
67
+ ```
68
+
69
+ Responses are the API's own JSON as plain dicts, with the API's field names (`startUrl`, `threadId`, `costUsd`...).
70
+ Request bodies take the API's names too, as a dict or as keyword arguments; query options are snake_case keyword
71
+ arguments:
72
+
73
+ ```python
74
+ pf.tasks.create("Read my loyalty points", startUrl="https://shop.example/account", maxSteps=30, region="us")
75
+ pf.tasks.create({"task": "Read my loyalty points", "startUrl": "https://shop.example/account"})
76
+ pf.tasks.list(status="done", limit=20)
77
+ ```
78
+
79
+ `Pilotfish(...)` takes `api_key`, `base_url` (default `PILOTFISH_BASE_URL`, else `https://pilotfish-be.gai.ventures`),
80
+ `max_retries` (2), `timeout` (60 s per request) and `http_client` (your own `httpx.Client`). Use it as a
81
+ context manager to close its connections: `with Pilotfish() as pf: ...`.
82
+
83
+ ## Tasks
84
+
85
+ ```python
86
+ t = pf.tasks.create("How many loyalty points do I have?", startUrl="https://shop.example/account")
87
+ print(t["id"], t["appUrl"]) # watch it live in the app
88
+
89
+ for event in pf.tasks.stream(t["id"]): # each new event (steps, questions, files) until it ends
90
+ print(event["type"])
91
+
92
+ done = pf.tasks.wait(t["id"]) # until it ends, or waits on a question
93
+ ```
94
+
95
+ - `tasks.run(task, **fields)` starts a task and waits; `tasks.wait(id, timeout=1800, poll_interval=2)` returns when
96
+ the task ends or asks a question (`return_on_question=False` waits for the end). A wait that times out raises
97
+ `WaitTimeoutError`; the task carries on.
98
+ - `tasks.get(id)`, `tasks.list(status=, limit=, cursor=, project=, identity=)` (one page: `.items`, `.next_cursor`),
99
+ `tasks.iterate(...)` (every task, page after page), `tasks.events(id, after=None)`.
100
+ - `tasks.follow_up(id, "now add the chair")` gives the next instruction in the same session: the same browser while
101
+ it is kept, the same sign-ins, what earlier turns found.
102
+ - `tasks.continue_(id)` carries a paused task on (`paused: True`, `next: "continue"`), as the app's Continue does.
103
+ (The trailing underscore is because `continue` is a Python keyword.)
104
+ - `tasks.answer(id, question_id, answer)` answers the open question (`task["question"]["id"]`): `"yes"`, `"no"`,
105
+ `"done"`, `"cancel"`, any other text, or an answer dict. Codes and passwords go on the task's `answerUrl`, never
106
+ through the API.
107
+ - `tasks.message(id, "use the cheaper one")` tells a running task something; it reads it before its next step.
108
+ - `tasks.cancel(id)`, `tasks.pause(id)` / `tasks.resume(id)` (take the browser over and hand it back),
109
+ `tasks.rerun(id)`, `tasks.thread(id)`, `tasks.delete_session(id)`.
110
+ - Files and replays: `tasks.files(id)`, `tasks.download_file(id, file_id)` and `tasks.replay_mp4(id)` return
111
+ `(data, content_type, filename)`, and `tasks.frames(id)` the screenshots after each step that changed the page.
112
+
113
+ ```python
114
+ t = pf.tasks.wait(t["id"])
115
+ if t["status"] == "needs_input":
116
+ q = t["question"]
117
+ print(q.get("text") or q.get("question"))
118
+ pf.tasks.answer(t["id"], q["id"], "yes")
119
+ ```
120
+
121
+ ## Structured output
122
+
123
+ Give a JSON Schema (root `type: "object"`) and the result's `data` validates against it:
124
+
125
+ ```python
126
+ t = pf.tasks.run(
127
+ "List the first three laptops on the page with their prices",
128
+ startUrl="https://shop.example/laptops",
129
+ outputSchema={
130
+ "type": "object",
131
+ "properties": {"laptops": {"type": "array", "items": {
132
+ "type": "object",
133
+ "properties": {"name": {"type": "string"}, "price": {"type": "number"}},
134
+ "required": ["name", "price"],
135
+ }}},
136
+ "required": ["laptops"],
137
+ },
138
+ )
139
+ print(t["result"].get("data") or t["result"].get("dataError"))
140
+ ```
141
+
142
+ ## Batches
143
+
144
+ Many tasks in one request, run one after another, their results collected together (up to 100). Each task is
145
+ charged when it runs; if credits run out, the rest are skipped.
146
+
147
+ ```python
148
+ batch = pf.batches.run(
149
+ ["What is on the front page of example.com?", {"task": "Read the points", "startUrl": "https://shop.example/a"}],
150
+ name="nightly",
151
+ webhookUrl="https://you.example/pilotfish", # batch.finished, signed
152
+ )
153
+ for item in batch["items"]:
154
+ print(item["status"], (item["result"] or {}).get("result"))
155
+ ```
156
+
157
+ `batches.create`, `batches.get`, `batches.wait(id, timeout=7200)`, `batches.list(status=, limit=, cursor=)` and
158
+ `batches.cancel` (the running task is cancelled, the rest skipped and never charged).
159
+
160
+ ## Identities and login links
161
+
162
+ For a product with its own end users: in a shared project (an org key's project), each identity keeps its own logins,
163
+ sessions, IP address and device.
164
+
165
+ ```python
166
+ org = Pilotfish(api_key="pf_org_key")
167
+ ada = org.identities.create(externalUserId="user-42", label="Ada") # existed: True if you had it already
168
+ link = org.identities.login_link(ada["id"], ["example.com"]) # a one-time page where Ada types her own login
169
+ print(link["url"])
170
+ org.identities.add_credential(ada["id"], site="example.com", username="ada@example.com", password="...")
171
+ org.tasks.run("Download my latest invoice", identity=ada["id"], startUrl="https://example.com/billing")
172
+ ```
173
+
174
+ Also `identities.get`, `list(external_user_id=, q=, limit=, cursor=)` (with `.total`), `update` (PATCH), `delete`
175
+ (wipes its logins, sessions and device; its tasks and cost are kept), `usage(id, since=<ms since the epoch>)`, `credentials` (masked: never the
176
+ password), `set_default_credential` and `delete_credential`.
177
+
178
+ ## Saved tasks and schedules
179
+
180
+ ```python
181
+ saved = pf.saved_tasks.create(name="points", task="How many loyalty points do I have?",
182
+ options={"startUrl": "https://shop.example/account"})
183
+ run = pf.saved_tasks.run(saved["id"], extraInstructions="also the expiry date")
184
+ pf.schedules.create(savedTaskId=saved["id"], rule={"repeat": "weekdays", "time": "09:00", "tz": "Europe/London"})
185
+ ```
186
+
187
+ Saved tasks and schedules live in your Personal project (an org key's shared project has none: `ConflictError` with
188
+ code `shared_project`). What would stop a scheduled run with nobody there is settled before it is saved
189
+ (`ConflictError` with code `not_ready`).
190
+
191
+ ## Usage
192
+
193
+ ```python
194
+ pf.usage.get(days=7) # spending by kind, day, model and task, and what is left of an allowance
195
+ pf.usage.get(from_="2026-11-01", to="2026-11-30")
196
+ ```
197
+
198
+ ## Errors and retries
199
+
200
+ Every API error is raised as its class, with the API's `code`, `hint`, `docs`, `fields` (the invalid parts of a 400),
201
+ `retry_after_s` and the whole `body`:
202
+
203
+ | Class | Status | For example |
204
+ | --- | --- | --- |
205
+ | `BadRequestError` | 400, 422 | `invalid_request` with `fields`, `invalid_schema` |
206
+ | `AuthenticationError` | 401 | no key, a wrong or revoked one |
207
+ | `PaymentRequiredError` | 402 | `no_credits`, `allocation_used`, `org_limit` |
208
+ | `PermissionDeniedError` | 403 | `admins_only` |
209
+ | `NotFoundError` | 404, 410 | no such task, batch or identity |
210
+ | `ConflictError` | 409 | `one_session`, `identity_busy`, `shared_project` |
211
+ | `RateLimitError` | 429 | `rate_limited`, `queue_full`, `start_rate` |
212
+ | `ServerError` | 5xx | |
213
+ | `ConnectionError` | (0) | no answer: the network, or the client's timeout |
214
+ | `WaitTimeoutError` | (0) | `wait()` gave up; the task carries on |
215
+
216
+ All are `PilotfishError`s.
217
+
218
+ ```python
219
+ from pilotfish import PaymentRequiredError, PilotfishError
220
+
221
+ try:
222
+ pf.tasks.create("...")
223
+ except PaymentRequiredError as e:
224
+ print(e.code, e.hint) # no_credits, who to ask
225
+ except PilotfishError as e:
226
+ print(e.status, e.code, e)
227
+ ```
228
+
229
+ The client retries by itself: a 429 for any request, after its `retryAfterS` (or `Retry-After`, at most 60 s), since
230
+ nothing was made; a 5xx or a network failure only for reads (GET), so a task is never started twice. `max_retries`
231
+ (default 2) sets how many tries follow the first.
232
+
233
+ ## Webhooks
234
+
235
+ A task's `webhookUrl` gets `job.needs_input` and `job.finished`, a batch's `batch.finished`, an identity's login link
236
+ `identity.login_saved`. Each delivery carries `Pilotfish-Signature: t=<unix>,v1=<hex>`, the HMAC-SHA256 of
237
+ `"<t>.<raw body>"` with your org's webhook secret (Org settings, or `GET /org/webhook-secret`). Check it on the raw
238
+ body, exactly as received:
239
+
240
+ ```python
241
+ from pilotfish import parse_webhook, verify_webhook
242
+
243
+ ok = verify_webhook(secret, request.headers.get("Pilotfish-Signature"), raw_body) # True or False; 5 minutes' tolerance
244
+ event = parse_webhook(secret, request.headers.get("Pilotfish-Signature"), raw_body) # or raises (code bad_signature)
245
+ print(event["type"], event.get("jobId") or event.get("batchId"), event["data"])
246
+ ```
247
+
248
+ `sign_webhook(secret, body, t=None)` makes a header, for tests of your own endpoint.
249
+
250
+ ## Async
251
+
252
+ `AsyncPilotfish` has the same surface, every call awaited; `tasks.iterate` and `tasks.stream` are async iterators.
253
+
254
+ ```python
255
+ import asyncio
256
+ from pilotfish import AsyncPilotfish
257
+
258
+ async def main():
259
+ async with AsyncPilotfish() as pf:
260
+ t = await pf.tasks.run("What is on the front page of example.com?")
261
+ print(t["result"]["result"])
262
+ async for event in pf.tasks.stream(t["id"]):
263
+ print(event["type"])
264
+
265
+ asyncio.run(main())
266
+ ```
267
+
268
+ ## Local quickstart
269
+
270
+ `LocalBrowser` drives Chrome on your own machine with the open MCP's tools
271
+ ([@gaiventures/pilotfish-mcp](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp), MIT). It needs Node.js 22+
272
+ and Chrome; it starts `npx -y @gaiventures/pilotfish-mcp` (or `node $PILOTFISH_MCP_CLI`, or the `command=` you
273
+ give) and speaks MCP to it over stdio. No key and no model calls: your code decides each step.
274
+
275
+ ```python
276
+ import re
277
+ from pilotfish import LocalBrowser
278
+
279
+ with LocalBrowser.start() as b:
280
+ page = b.navigate("https://en.wikipedia.org")
281
+ print(page.text) # the visible screen as an outline with refs
282
+ box = re.search(r"\[(e\d+)\]", b.find("Search Wikipedia").text).group(1)
283
+ b.type(box, "Pilot fish", submit=True)
284
+ headings = b.query("[...document.querySelectorAll('h2')].map((h) => h.textContent.trim())")
285
+ print(headings.value) # parsed JSON
286
+ open("page.jpg", "wb").write(b.screenshot())
287
+ ```
288
+
289
+ Tools: `navigate(url, snapshot=, expect=, escalate=)`, `snapshot(whole_page=False)`, `click(ref)`,
290
+ `type(ref, text, submit=)`, `select(ref, values)`, `press(key)`, `scroll(direction)`, `actions(steps)` (up to 10 in
291
+ one call), `query(expression, schema=)` (`.value`), `find(query)`, `get_text(max_chars=, selector=)`,
292
+ `screenshot()` (JPEG bytes), `wait(seconds, until=, gone=, in_=)`, `resume(timeout_s=)`, `tabs(switch_to=)`,
293
+ `page_tool(tool, arguments)`, `tools()`, and `call(name, args)` for any tool by name. Each returns a `ToolResult`
294
+ (`text`, `images`, `structured`, `is_error`); a tool's error raises `LocalToolError` (with `.tool` and `.result`)
295
+ unless `throw_on_error=False`.
296
+
297
+ `LocalBrowser.start(...)` takes `headless`, `allowed_hosts`, `allow_private` (localhost and private networks, for
298
+ testing your own app), `secrets` (typed as `{{name}}`, never in any result), `chrome`, `env` (further
299
+ [settings](https://pilotfish.gai.ventures/docs/open-settings)), `command`, `timeout` (per call, 300 s) and
300
+ `on_question`. Without `on_question` an irreversible step (pay, send, delete) is refused and a page that needs a
301
+ person says so in the result. With it, you decide:
302
+
303
+ ```python
304
+ def on_question(q): # q.kind is "confirm" (an irreversible step) or "handoff" (a sign-in, code or CAPTCHA)
305
+ print(q.message)
306
+ return input("Allow? [y/N] ").lower() == "y" # True allows (or, for a handoff, says it is done); None or False declines
307
+
308
+ b = LocalBrowser.start(on_question=on_question)
309
+ ```
310
+
311
+ ## Links
312
+
313
+ - SDK documentation: <https://pilotfish.gai.ventures/docs/sdk>
314
+ - REST API reference: <https://pilotfish.gai.ventures/docs/api>
315
+ - Source: <https://github.com/gAI-ventures/pilotfish-ai/tree/main/sdks/python>
316
+
317
+ MIT licensed.
@@ -0,0 +1,287 @@
1
+ # pilotfish for Python
2
+
3
+ Run browser tasks in [pilotfish](https://pilotfish.gai.ventures)'s cloud from Python, or drive Chrome on your own
4
+ machine.
5
+
6
+ pilotfish's agent and its open MCP send a page to the model as a compact outline with refs (`[e12]<button>Search`),
7
+ and after each step only what changed, never the whole page again. That means far fewer tokens per step and faster
8
+ steps than screenshots or raw HTML.
9
+
10
+ Two clients in one package:
11
+
12
+ - **`Pilotfish`** (and **`AsyncPilotfish`**): the hosted client. Describe a task in words; pilotfish's agent runs it in
13
+ a cloud browser (signed in with saved logins, bot checks handled, a person asked only when needed) and returns the answer, as text or as JSON matching your schema. Paid from your org's credits.
14
+ - **`LocalBrowser`**: Chrome on your own machine and IP, driven step by step from your code through the open MCP's
15
+ browser tools. No account, no API key, no model calls.
16
+
17
+ ```bash
18
+ pip install pilotfish-ai
19
+ ```
20
+
21
+ Installed as `pilotfish-ai`, imported as `pilotfish`. Python 3.9 or newer. The only dependency is
22
+ [httpx](https://www.python-httpx.org/).
23
+
24
+ ## Hosted quickstart
25
+
26
+ Make an API key in the app at <https://pilotfish.gai.ventures> (Org settings → API keys) and set it as
27
+ `PILOTFISH_API_KEY`.
28
+
29
+ ```python
30
+ from pilotfish import Pilotfish
31
+
32
+ pf = Pilotfish() # reads PILOTFISH_API_KEY; or Pilotfish(api_key="pf_...")
33
+
34
+ task = pf.tasks.run("Find the cheapest blue desk lamp on ikea.com and give its name and price")
35
+ print(task["status"]) # done, failed, cancelled, or needs_input
36
+ print(task["result"]["result"]) # the answer, in words
37
+ ```
38
+
39
+ Responses are the API's own JSON as plain dicts, with the API's field names (`startUrl`, `threadId`, `costUsd`...).
40
+ Request bodies take the API's names too, as a dict or as keyword arguments; query options are snake_case keyword
41
+ arguments:
42
+
43
+ ```python
44
+ pf.tasks.create("Read my loyalty points", startUrl="https://shop.example/account", maxSteps=30, region="us")
45
+ pf.tasks.create({"task": "Read my loyalty points", "startUrl": "https://shop.example/account"})
46
+ pf.tasks.list(status="done", limit=20)
47
+ ```
48
+
49
+ `Pilotfish(...)` takes `api_key`, `base_url` (default `PILOTFISH_BASE_URL`, else `https://pilotfish-be.gai.ventures`),
50
+ `max_retries` (2), `timeout` (60 s per request) and `http_client` (your own `httpx.Client`). Use it as a
51
+ context manager to close its connections: `with Pilotfish() as pf: ...`.
52
+
53
+ ## Tasks
54
+
55
+ ```python
56
+ t = pf.tasks.create("How many loyalty points do I have?", startUrl="https://shop.example/account")
57
+ print(t["id"], t["appUrl"]) # watch it live in the app
58
+
59
+ for event in pf.tasks.stream(t["id"]): # each new event (steps, questions, files) until it ends
60
+ print(event["type"])
61
+
62
+ done = pf.tasks.wait(t["id"]) # until it ends, or waits on a question
63
+ ```
64
+
65
+ - `tasks.run(task, **fields)` starts a task and waits; `tasks.wait(id, timeout=1800, poll_interval=2)` returns when
66
+ the task ends or asks a question (`return_on_question=False` waits for the end). A wait that times out raises
67
+ `WaitTimeoutError`; the task carries on.
68
+ - `tasks.get(id)`, `tasks.list(status=, limit=, cursor=, project=, identity=)` (one page: `.items`, `.next_cursor`),
69
+ `tasks.iterate(...)` (every task, page after page), `tasks.events(id, after=None)`.
70
+ - `tasks.follow_up(id, "now add the chair")` gives the next instruction in the same session: the same browser while
71
+ it is kept, the same sign-ins, what earlier turns found.
72
+ - `tasks.continue_(id)` carries a paused task on (`paused: True`, `next: "continue"`), as the app's Continue does.
73
+ (The trailing underscore is because `continue` is a Python keyword.)
74
+ - `tasks.answer(id, question_id, answer)` answers the open question (`task["question"]["id"]`): `"yes"`, `"no"`,
75
+ `"done"`, `"cancel"`, any other text, or an answer dict. Codes and passwords go on the task's `answerUrl`, never
76
+ through the API.
77
+ - `tasks.message(id, "use the cheaper one")` tells a running task something; it reads it before its next step.
78
+ - `tasks.cancel(id)`, `tasks.pause(id)` / `tasks.resume(id)` (take the browser over and hand it back),
79
+ `tasks.rerun(id)`, `tasks.thread(id)`, `tasks.delete_session(id)`.
80
+ - Files and replays: `tasks.files(id)`, `tasks.download_file(id, file_id)` and `tasks.replay_mp4(id)` return
81
+ `(data, content_type, filename)`, and `tasks.frames(id)` the screenshots after each step that changed the page.
82
+
83
+ ```python
84
+ t = pf.tasks.wait(t["id"])
85
+ if t["status"] == "needs_input":
86
+ q = t["question"]
87
+ print(q.get("text") or q.get("question"))
88
+ pf.tasks.answer(t["id"], q["id"], "yes")
89
+ ```
90
+
91
+ ## Structured output
92
+
93
+ Give a JSON Schema (root `type: "object"`) and the result's `data` validates against it:
94
+
95
+ ```python
96
+ t = pf.tasks.run(
97
+ "List the first three laptops on the page with their prices",
98
+ startUrl="https://shop.example/laptops",
99
+ outputSchema={
100
+ "type": "object",
101
+ "properties": {"laptops": {"type": "array", "items": {
102
+ "type": "object",
103
+ "properties": {"name": {"type": "string"}, "price": {"type": "number"}},
104
+ "required": ["name", "price"],
105
+ }}},
106
+ "required": ["laptops"],
107
+ },
108
+ )
109
+ print(t["result"].get("data") or t["result"].get("dataError"))
110
+ ```
111
+
112
+ ## Batches
113
+
114
+ Many tasks in one request, run one after another, their results collected together (up to 100). Each task is
115
+ charged when it runs; if credits run out, the rest are skipped.
116
+
117
+ ```python
118
+ batch = pf.batches.run(
119
+ ["What is on the front page of example.com?", {"task": "Read the points", "startUrl": "https://shop.example/a"}],
120
+ name="nightly",
121
+ webhookUrl="https://you.example/pilotfish", # batch.finished, signed
122
+ )
123
+ for item in batch["items"]:
124
+ print(item["status"], (item["result"] or {}).get("result"))
125
+ ```
126
+
127
+ `batches.create`, `batches.get`, `batches.wait(id, timeout=7200)`, `batches.list(status=, limit=, cursor=)` and
128
+ `batches.cancel` (the running task is cancelled, the rest skipped and never charged).
129
+
130
+ ## Identities and login links
131
+
132
+ For a product with its own end users: in a shared project (an org key's project), each identity keeps its own logins,
133
+ sessions, IP address and device.
134
+
135
+ ```python
136
+ org = Pilotfish(api_key="pf_org_key")
137
+ ada = org.identities.create(externalUserId="user-42", label="Ada") # existed: True if you had it already
138
+ link = org.identities.login_link(ada["id"], ["example.com"]) # a one-time page where Ada types her own login
139
+ print(link["url"])
140
+ org.identities.add_credential(ada["id"], site="example.com", username="ada@example.com", password="...")
141
+ org.tasks.run("Download my latest invoice", identity=ada["id"], startUrl="https://example.com/billing")
142
+ ```
143
+
144
+ Also `identities.get`, `list(external_user_id=, q=, limit=, cursor=)` (with `.total`), `update` (PATCH), `delete`
145
+ (wipes its logins, sessions and device; its tasks and cost are kept), `usage(id, since=<ms since the epoch>)`, `credentials` (masked: never the
146
+ password), `set_default_credential` and `delete_credential`.
147
+
148
+ ## Saved tasks and schedules
149
+
150
+ ```python
151
+ saved = pf.saved_tasks.create(name="points", task="How many loyalty points do I have?",
152
+ options={"startUrl": "https://shop.example/account"})
153
+ run = pf.saved_tasks.run(saved["id"], extraInstructions="also the expiry date")
154
+ pf.schedules.create(savedTaskId=saved["id"], rule={"repeat": "weekdays", "time": "09:00", "tz": "Europe/London"})
155
+ ```
156
+
157
+ Saved tasks and schedules live in your Personal project (an org key's shared project has none: `ConflictError` with
158
+ code `shared_project`). What would stop a scheduled run with nobody there is settled before it is saved
159
+ (`ConflictError` with code `not_ready`).
160
+
161
+ ## Usage
162
+
163
+ ```python
164
+ pf.usage.get(days=7) # spending by kind, day, model and task, and what is left of an allowance
165
+ pf.usage.get(from_="2026-11-01", to="2026-11-30")
166
+ ```
167
+
168
+ ## Errors and retries
169
+
170
+ Every API error is raised as its class, with the API's `code`, `hint`, `docs`, `fields` (the invalid parts of a 400),
171
+ `retry_after_s` and the whole `body`:
172
+
173
+ | Class | Status | For example |
174
+ | --- | --- | --- |
175
+ | `BadRequestError` | 400, 422 | `invalid_request` with `fields`, `invalid_schema` |
176
+ | `AuthenticationError` | 401 | no key, a wrong or revoked one |
177
+ | `PaymentRequiredError` | 402 | `no_credits`, `allocation_used`, `org_limit` |
178
+ | `PermissionDeniedError` | 403 | `admins_only` |
179
+ | `NotFoundError` | 404, 410 | no such task, batch or identity |
180
+ | `ConflictError` | 409 | `one_session`, `identity_busy`, `shared_project` |
181
+ | `RateLimitError` | 429 | `rate_limited`, `queue_full`, `start_rate` |
182
+ | `ServerError` | 5xx | |
183
+ | `ConnectionError` | (0) | no answer: the network, or the client's timeout |
184
+ | `WaitTimeoutError` | (0) | `wait()` gave up; the task carries on |
185
+
186
+ All are `PilotfishError`s.
187
+
188
+ ```python
189
+ from pilotfish import PaymentRequiredError, PilotfishError
190
+
191
+ try:
192
+ pf.tasks.create("...")
193
+ except PaymentRequiredError as e:
194
+ print(e.code, e.hint) # no_credits, who to ask
195
+ except PilotfishError as e:
196
+ print(e.status, e.code, e)
197
+ ```
198
+
199
+ The client retries by itself: a 429 for any request, after its `retryAfterS` (or `Retry-After`, at most 60 s), since
200
+ nothing was made; a 5xx or a network failure only for reads (GET), so a task is never started twice. `max_retries`
201
+ (default 2) sets how many tries follow the first.
202
+
203
+ ## Webhooks
204
+
205
+ A task's `webhookUrl` gets `job.needs_input` and `job.finished`, a batch's `batch.finished`, an identity's login link
206
+ `identity.login_saved`. Each delivery carries `Pilotfish-Signature: t=<unix>,v1=<hex>`, the HMAC-SHA256 of
207
+ `"<t>.<raw body>"` with your org's webhook secret (Org settings, or `GET /org/webhook-secret`). Check it on the raw
208
+ body, exactly as received:
209
+
210
+ ```python
211
+ from pilotfish import parse_webhook, verify_webhook
212
+
213
+ ok = verify_webhook(secret, request.headers.get("Pilotfish-Signature"), raw_body) # True or False; 5 minutes' tolerance
214
+ event = parse_webhook(secret, request.headers.get("Pilotfish-Signature"), raw_body) # or raises (code bad_signature)
215
+ print(event["type"], event.get("jobId") or event.get("batchId"), event["data"])
216
+ ```
217
+
218
+ `sign_webhook(secret, body, t=None)` makes a header, for tests of your own endpoint.
219
+
220
+ ## Async
221
+
222
+ `AsyncPilotfish` has the same surface, every call awaited; `tasks.iterate` and `tasks.stream` are async iterators.
223
+
224
+ ```python
225
+ import asyncio
226
+ from pilotfish import AsyncPilotfish
227
+
228
+ async def main():
229
+ async with AsyncPilotfish() as pf:
230
+ t = await pf.tasks.run("What is on the front page of example.com?")
231
+ print(t["result"]["result"])
232
+ async for event in pf.tasks.stream(t["id"]):
233
+ print(event["type"])
234
+
235
+ asyncio.run(main())
236
+ ```
237
+
238
+ ## Local quickstart
239
+
240
+ `LocalBrowser` drives Chrome on your own machine with the open MCP's tools
241
+ ([@gaiventures/pilotfish-mcp](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp), MIT). It needs Node.js 22+
242
+ and Chrome; it starts `npx -y @gaiventures/pilotfish-mcp` (or `node $PILOTFISH_MCP_CLI`, or the `command=` you
243
+ give) and speaks MCP to it over stdio. No key and no model calls: your code decides each step.
244
+
245
+ ```python
246
+ import re
247
+ from pilotfish import LocalBrowser
248
+
249
+ with LocalBrowser.start() as b:
250
+ page = b.navigate("https://en.wikipedia.org")
251
+ print(page.text) # the visible screen as an outline with refs
252
+ box = re.search(r"\[(e\d+)\]", b.find("Search Wikipedia").text).group(1)
253
+ b.type(box, "Pilot fish", submit=True)
254
+ headings = b.query("[...document.querySelectorAll('h2')].map((h) => h.textContent.trim())")
255
+ print(headings.value) # parsed JSON
256
+ open("page.jpg", "wb").write(b.screenshot())
257
+ ```
258
+
259
+ Tools: `navigate(url, snapshot=, expect=, escalate=)`, `snapshot(whole_page=False)`, `click(ref)`,
260
+ `type(ref, text, submit=)`, `select(ref, values)`, `press(key)`, `scroll(direction)`, `actions(steps)` (up to 10 in
261
+ one call), `query(expression, schema=)` (`.value`), `find(query)`, `get_text(max_chars=, selector=)`,
262
+ `screenshot()` (JPEG bytes), `wait(seconds, until=, gone=, in_=)`, `resume(timeout_s=)`, `tabs(switch_to=)`,
263
+ `page_tool(tool, arguments)`, `tools()`, and `call(name, args)` for any tool by name. Each returns a `ToolResult`
264
+ (`text`, `images`, `structured`, `is_error`); a tool's error raises `LocalToolError` (with `.tool` and `.result`)
265
+ unless `throw_on_error=False`.
266
+
267
+ `LocalBrowser.start(...)` takes `headless`, `allowed_hosts`, `allow_private` (localhost and private networks, for
268
+ testing your own app), `secrets` (typed as `{{name}}`, never in any result), `chrome`, `env` (further
269
+ [settings](https://pilotfish.gai.ventures/docs/open-settings)), `command`, `timeout` (per call, 300 s) and
270
+ `on_question`. Without `on_question` an irreversible step (pay, send, delete) is refused and a page that needs a
271
+ person says so in the result. With it, you decide:
272
+
273
+ ```python
274
+ def on_question(q): # q.kind is "confirm" (an irreversible step) or "handoff" (a sign-in, code or CAPTCHA)
275
+ print(q.message)
276
+ return input("Allow? [y/N] ").lower() == "y" # True allows (or, for a handoff, says it is done); None or False declines
277
+
278
+ b = LocalBrowser.start(on_question=on_question)
279
+ ```
280
+
281
+ ## Links
282
+
283
+ - SDK documentation: <https://pilotfish.gai.ventures/docs/sdk>
284
+ - REST API reference: <https://pilotfish.gai.ventures/docs/api>
285
+ - Source: <https://github.com/gAI-ventures/pilotfish-ai/tree/main/sdks/python>
286
+
287
+ MIT licensed.