tinyfish 0.6.1__tar.gz → 0.8.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.
Files changed (54) hide show
  1. {tinyfish-0.6.1 → tinyfish-0.8.0}/CHANGELOG.md +20 -0
  2. {tinyfish-0.6.1 → tinyfish-0.8.0}/CLAUDE.md +3 -4
  3. {tinyfish-0.6.1 → tinyfish-0.8.0}/PKG-INFO +80 -4
  4. {tinyfish-0.6.1 → tinyfish-0.8.0}/README.md +78 -2
  5. {tinyfish-0.6.1 → tinyfish-0.8.0}/pyproject.toml +1 -1
  6. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/__init__.py +12 -0
  7. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/agent/__init__.py +65 -0
  8. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/agent/types.py +43 -0
  9. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/fetch/__init__.py +39 -3
  10. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/fetch/types.py +23 -1
  11. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/runs/types.py +2 -0
  12. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_agent.py +47 -4
  13. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_fetch.py +99 -1
  14. {tinyfish-0.6.1 → tinyfish-0.8.0}/uv.lock +1 -1
  15. {tinyfish-0.6.1 → tinyfish-0.8.0}/.gitignore +0 -0
  16. {tinyfish-0.6.1 → tinyfish-0.8.0}/.pre-commit-config.yaml +0 -0
  17. {tinyfish-0.6.1 → tinyfish-0.8.0}/AGENTS.md +0 -0
  18. {tinyfish-0.6.1 → tinyfish-0.8.0}/RELEASE.md +0 -0
  19. {tinyfish-0.6.1 → tinyfish-0.8.0}/docs/exceptions-and-errors-guide.md +0 -0
  20. {tinyfish-0.6.1 → tinyfish-0.8.0}/docs/internal/api-integration-header.md +0 -0
  21. {tinyfish-0.6.1 → tinyfish-0.8.0}/docs/internal/exceptions-and-errors-guide.md +0 -0
  22. {tinyfish-0.6.1 → tinyfish-0.8.0}/docs/internal/publishing-private-guide.md +0 -0
  23. {tinyfish-0.6.1 → tinyfish-0.8.0}/docs/pagination-guide.md +0 -0
  24. {tinyfish-0.6.1 → tinyfish-0.8.0}/docs/proxy-and-browser-profiles.md +0 -0
  25. {tinyfish-0.6.1 → tinyfish-0.8.0}/docs/streaming-guide.md +0 -0
  26. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/_utils/__init__.py +0 -0
  27. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/_utils/client/__init__.py +0 -0
  28. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/_utils/client/_base.py +0 -0
  29. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/_utils/client/async_.py +0 -0
  30. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/_utils/client/sync.py +0 -0
  31. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/_utils/exceptions.py +0 -0
  32. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/_utils/resource.py +0 -0
  33. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/_utils/sse_parser.py +0 -0
  34. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/browser/__init__.py +0 -0
  35. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/browser/types.py +0 -0
  36. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/client.py +0 -0
  37. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/py.typed +0 -0
  38. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/runs/__init__.py +0 -0
  39. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/search/__init__.py +0 -0
  40. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/search/types.py +0 -0
  41. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/vault/__init__.py +0 -0
  42. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/vault/types.py +0 -0
  43. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/wallet/__init__.py +0 -0
  44. {tinyfish-0.6.1 → tinyfish-0.8.0}/src/tinyfish/wallet/types.py +0 -0
  45. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/__init__.py +0 -0
  46. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/conftest.py +0 -0
  47. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_browser.py +0 -0
  48. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_client.py +0 -0
  49. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_errors.py +0 -0
  50. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_runs.py +0 -0
  51. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_search.py +0 -0
  52. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_vault.py +0 -0
  53. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/test_wallet.py +0 -0
  54. {tinyfish-0.6.1 → tinyfish-0.8.0}/tests/testing_guide.md +0 -0
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.8.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.7.0...sdk-py/v0.8.0) (2026-09-02)
4
+
5
+
6
+ ### Features
7
+
8
+ * **sdk-python:** add fetch highlights ([#4785](https://github.com/tinyfish-io/ux-labs/issues/4785)) ([29d6400](https://github.com/tinyfish-io/ux-labs/commit/29d6400ba410b5c0a80f57c82f7183be3683cb97))
9
+
10
+ ## [0.7.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.6.1...sdk-py/v0.7.0) (2026-08-18)
11
+
12
+
13
+ ### Features
14
+
15
+ * **sdk-cli:** add agent run parity fields ([#3260](https://github.com/tinyfish-io/ux-labs/issues/3260)) ([1ec839e](https://github.com/tinyfish-io/ux-labs/commit/1ec839ed578811d6fea859a8240bd1a9c89086e0))
16
+
17
+
18
+ ### Documentation
19
+
20
+ * compress agent-facing docs, cap code comments at 11 words ([#4364](https://github.com/tinyfish-io/ux-labs/issues/4364)) ([4ea055c](https://github.com/tinyfish-io/ux-labs/commit/4ea055c515e1af78da8b5f6049b84a8433c64221))
21
+ * **wallet:** wallet surfaces on docs.tinyfish.ai, dual-mode billing copy (PF-3480) ([#4316](https://github.com/tinyfish-io/ux-labs/issues/4316)) ([267db96](https://github.com/tinyfish-io/ux-labs/commit/267db967c8eeba73ae8de33b800812f95b65fa19))
22
+
3
23
  ## [0.6.1](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.6.0...sdk-py/v0.6.1) (2026-08-12)
4
24
 
5
25
 
@@ -1,9 +1,8 @@
1
1
  # TinyFish Python SDK (`tinyfish`)
2
2
 
3
- Official Python SDK for TinyFish. Provides sync (`TinyFish`) and async (`AsyncTinyFish`) clients for running
4
- automations, streaming events, and managing runs.
3
+ Official Python SDK. Sync (`TinyFish`) and async (`AsyncTinyFish`) clients for running automations, streaming events, managing runs.
5
4
 
6
- For full method reference and examples: see `README.md`.
5
+ Full method reference and examples: `README.md`.
7
6
 
8
7
  ---
9
8
 
@@ -57,4 +56,4 @@ cd sdk/sdk-python && uv run ruff check . && uv run ruff format .
57
56
 
58
57
  ## Further Reading
59
58
 
60
- See `README.md` for full usage examples, authentication patterns, and SDK changelog.
59
+ `README.md` — usage examples, authentication patterns, SDK changelog.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: tinyfish
3
- Version: 0.6.1
3
+ Version: 0.8.0
4
4
  Summary: Official Python SDK for the TinyFish API
5
5
  Requires-Python: >=3.11
6
6
  Requires-Dist: httpx>=0.27.0
@@ -57,7 +57,7 @@ Every method below is available on both `TinyFish` (sync) and `AsyncTinyFish` (a
57
57
  | [`runs.get()`](#runsget--retrieve-a-single-run) | Retrieve a single run by ID | `Run` | — |
58
58
  | [`runs.list()`](#runslist--list-and-filter-runs) | List runs with filtering, sorting, pagination | `RunListResponse` | — |
59
59
  | [`search.query()`](#searchquery--search-the-web) | Search the web for ranked results | `SearchQueryResponse` | Yes |
60
- | `wallet.get()` | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
60
+ | [`wallet.get()`](#walletget--get-your-balance) | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
61
61
 
62
62
  ---
63
63
 
@@ -212,6 +212,8 @@ print(response.errors)
212
212
 
213
213
  `fetch.get_contents()` accepts 1 to 10 URLs. Set `per_url_timeout_ms` to apply an independent timeout budget to each URL in the batch; slow URLs return in `errors` with `timeout` while siblings can still complete.
214
214
 
215
+ Pass `highlights={"query": "pricing tiers"}` (beta, markdown format only) to get query-ranked `HighlightSnippet` lists on each result instead of the full `text`; set `include_full_page_text=True` to keep both. Accounts not enrolled in the beta get `PermissionDeniedError`.
216
+
215
217
  **Returns `FetchResponse`:**
216
218
 
217
219
  | Field | Type | Description |
@@ -354,6 +356,55 @@ Filter validation rules:
354
356
 
355
357
  ---
356
358
 
359
+ ### `wallet.get()` — get your balance
360
+
361
+ Returns the caller's current balance, auto-reload configuration, per-product rates, and any in-flight top-up.
362
+
363
+ ```python
364
+ from tinyfish import TinyFish, WalletAutoReloadState
365
+
366
+ client = TinyFish()
367
+
368
+ wallet = client.wallet.get()
369
+
370
+ print(f"{wallet.available_balance} {wallet.currency}")
371
+
372
+ if wallet.auto_reload and wallet.auto_reload.state == WalletAutoReloadState.ON:
373
+ print(f"Auto-reload at {wallet.auto_reload.threshold}, tops up to {wallet.auto_reload.recharge_to}")
374
+
375
+ if wallet.pending_top_up:
376
+ print(f"Pending top-up: {wallet.pending_top_up.amount}")
377
+ ```
378
+
379
+ **Returns `WalletResponse`:**
380
+
381
+ | Field | Type | Description |
382
+ |-------|------|-------------|
383
+ | `available_balance` | `str` | Current spendable balance. Negative means the wallet is overdrawn. |
384
+ | `currency` | `str` | ISO 4217 currency code, e.g. `USD` |
385
+ | `as_of` | `str` | ISO timestamp the wallet was read |
386
+ | `auto_reload` | `WalletAutoReload \| None` | `None` means the auto-reload read failed — not the same as `state == "unconfigured"`, which means the read succeeded and nothing is set |
387
+ | `pending_top_up` | `WalletPendingTopUp \| None` | `None` means no in-flight top-up, or the ledger read failed |
388
+ | `rates` | `WalletRates \| None` | `None` means the rates read failed, or the wallet has no rate contract yet |
389
+
390
+ `auto_reload.state` is one of `WalletAutoReloadState.UNCONFIGURED`, `ON`, `OFF`, `PAUSED_PAYMENT_FAILED`, or `NEEDS_PAYMENT_METHOD`. `threshold` and `recharge_to` are only present for the four configured states.
391
+
392
+ Accounts are on either wallet billing or a legacy subscription/credits plan. `wallet.get()` raises `NotFoundError` (404) with `.code` of `"FEATURE_NOT_AVAILABLE"` when the account is on the legacy plan. A wallet account that hasn't added money yet is not an error — it returns normally with an `available_balance` of `"0"`.
393
+
394
+ ```python
395
+ from tinyfish import NotFoundError
396
+
397
+ try:
398
+ wallet = client.wallet.get()
399
+ except NotFoundError as e:
400
+ if e.code == "FEATURE_NOT_AVAILABLE":
401
+ print("Account is on the legacy subscription/credits plan, not a wallet.")
402
+ else:
403
+ raise
404
+ ```
405
+
406
+ ---
407
+
357
408
  ## Sync vs Async
358
409
 
359
410
  Use `AsyncTinyFish` when you're in an async context (FastAPI, aiohttp, etc.):
@@ -376,7 +427,7 @@ client = AsyncTinyFish()
376
427
  response = await client.agent.run(goal="...", url="...")
377
428
  ```
378
429
 
379
- All seven methods (`agent.run()`, `agent.queue()`, `agent.stream()`, `fetch.get_contents()`, `runs.get()`, `runs.list()`, `search.query()`) work the same way — same parameters, just `await`-ed.
430
+ All eight methods (`agent.run()`, `agent.queue()`, `agent.stream()`, `fetch.get_contents()`, `runs.get()`, `runs.list()`, `search.query()`, `wallet.get()`) work the same way — same parameters, just `await`-ed.
380
431
 
381
432
  ## Configuration
382
433
 
@@ -414,6 +465,31 @@ response = client.agent.run(
414
465
  )
415
466
  ```
416
467
 
468
+ ### Agent controls and capture
469
+
470
+ `agent.run()`, `agent.queue()`, and `agent.stream()` also accept `agent_config`, `capture_config`, `webhook_url`, `use_profile`, and `profile_id`:
471
+
472
+ ```python
473
+ from tinyfish import AgentConfig, CaptureConfig
474
+
475
+ response = client.agent.run(
476
+ goal="...",
477
+ url="...",
478
+ agent_config=AgentConfig(mode="strict", cursor_style="standard", max_duration_seconds=300),
479
+ capture_config=CaptureConfig(screenshots=True, html=True),
480
+ webhook_url="https://example.com/tinyfish-webhook",
481
+ use_profile=True,
482
+ profile_id="prof_abc123def4567890",
483
+ )
484
+ ```
485
+
486
+ - `agent_config` (`AgentConfig`) — `mode`, `cursor_style`, `max_steps`, `max_duration_seconds`
487
+ - `capture_config` (`CaptureConfig`) — `elements`, `snapshots`, `screenshots`, `recording`, `html`
488
+ - `webhook_url` — HTTPS URL notified on run lifecycle events
489
+ - `profile_id` — a specific Browser Context Profile; requires `use_profile=True`
490
+
491
+ `elements` and `recording` are gated capabilities: an account without them enabled gets a 403 saying the capability is not enabled.
492
+
417
493
  ### Browser Context Profiles
418
494
 
419
495
  Use Browser Context Profiles when a run should start from saved logged-in state. Pass `use_profile=True` for your default profile, or add `profile_id` for a specific profile. Pair with `use_vault=True` when TinyFish should repair stale sessions with saved credentials.
@@ -47,7 +47,7 @@ Every method below is available on both `TinyFish` (sync) and `AsyncTinyFish` (a
47
47
  | [`runs.get()`](#runsget--retrieve-a-single-run) | Retrieve a single run by ID | `Run` | — |
48
48
  | [`runs.list()`](#runslist--list-and-filter-runs) | List runs with filtering, sorting, pagination | `RunListResponse` | — |
49
49
  | [`search.query()`](#searchquery--search-the-web) | Search the web for ranked results | `SearchQueryResponse` | Yes |
50
- | `wallet.get()` | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
50
+ | [`wallet.get()`](#walletget--get-your-balance) | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
51
51
 
52
52
  ---
53
53
 
@@ -202,6 +202,8 @@ print(response.errors)
202
202
 
203
203
  `fetch.get_contents()` accepts 1 to 10 URLs. Set `per_url_timeout_ms` to apply an independent timeout budget to each URL in the batch; slow URLs return in `errors` with `timeout` while siblings can still complete.
204
204
 
205
+ Pass `highlights={"query": "pricing tiers"}` (beta, markdown format only) to get query-ranked `HighlightSnippet` lists on each result instead of the full `text`; set `include_full_page_text=True` to keep both. Accounts not enrolled in the beta get `PermissionDeniedError`.
206
+
205
207
  **Returns `FetchResponse`:**
206
208
 
207
209
  | Field | Type | Description |
@@ -344,6 +346,55 @@ Filter validation rules:
344
346
 
345
347
  ---
346
348
 
349
+ ### `wallet.get()` — get your balance
350
+
351
+ Returns the caller's current balance, auto-reload configuration, per-product rates, and any in-flight top-up.
352
+
353
+ ```python
354
+ from tinyfish import TinyFish, WalletAutoReloadState
355
+
356
+ client = TinyFish()
357
+
358
+ wallet = client.wallet.get()
359
+
360
+ print(f"{wallet.available_balance} {wallet.currency}")
361
+
362
+ if wallet.auto_reload and wallet.auto_reload.state == WalletAutoReloadState.ON:
363
+ print(f"Auto-reload at {wallet.auto_reload.threshold}, tops up to {wallet.auto_reload.recharge_to}")
364
+
365
+ if wallet.pending_top_up:
366
+ print(f"Pending top-up: {wallet.pending_top_up.amount}")
367
+ ```
368
+
369
+ **Returns `WalletResponse`:**
370
+
371
+ | Field | Type | Description |
372
+ |-------|------|-------------|
373
+ | `available_balance` | `str` | Current spendable balance. Negative means the wallet is overdrawn. |
374
+ | `currency` | `str` | ISO 4217 currency code, e.g. `USD` |
375
+ | `as_of` | `str` | ISO timestamp the wallet was read |
376
+ | `auto_reload` | `WalletAutoReload \| None` | `None` means the auto-reload read failed — not the same as `state == "unconfigured"`, which means the read succeeded and nothing is set |
377
+ | `pending_top_up` | `WalletPendingTopUp \| None` | `None` means no in-flight top-up, or the ledger read failed |
378
+ | `rates` | `WalletRates \| None` | `None` means the rates read failed, or the wallet has no rate contract yet |
379
+
380
+ `auto_reload.state` is one of `WalletAutoReloadState.UNCONFIGURED`, `ON`, `OFF`, `PAUSED_PAYMENT_FAILED`, or `NEEDS_PAYMENT_METHOD`. `threshold` and `recharge_to` are only present for the four configured states.
381
+
382
+ Accounts are on either wallet billing or a legacy subscription/credits plan. `wallet.get()` raises `NotFoundError` (404) with `.code` of `"FEATURE_NOT_AVAILABLE"` when the account is on the legacy plan. A wallet account that hasn't added money yet is not an error — it returns normally with an `available_balance` of `"0"`.
383
+
384
+ ```python
385
+ from tinyfish import NotFoundError
386
+
387
+ try:
388
+ wallet = client.wallet.get()
389
+ except NotFoundError as e:
390
+ if e.code == "FEATURE_NOT_AVAILABLE":
391
+ print("Account is on the legacy subscription/credits plan, not a wallet.")
392
+ else:
393
+ raise
394
+ ```
395
+
396
+ ---
397
+
347
398
  ## Sync vs Async
348
399
 
349
400
  Use `AsyncTinyFish` when you're in an async context (FastAPI, aiohttp, etc.):
@@ -366,7 +417,7 @@ client = AsyncTinyFish()
366
417
  response = await client.agent.run(goal="...", url="...")
367
418
  ```
368
419
 
369
- All seven methods (`agent.run()`, `agent.queue()`, `agent.stream()`, `fetch.get_contents()`, `runs.get()`, `runs.list()`, `search.query()`) work the same way — same parameters, just `await`-ed.
420
+ All eight methods (`agent.run()`, `agent.queue()`, `agent.stream()`, `fetch.get_contents()`, `runs.get()`, `runs.list()`, `search.query()`, `wallet.get()`) work the same way — same parameters, just `await`-ed.
370
421
 
371
422
  ## Configuration
372
423
 
@@ -404,6 +455,31 @@ response = client.agent.run(
404
455
  )
405
456
  ```
406
457
 
458
+ ### Agent controls and capture
459
+
460
+ `agent.run()`, `agent.queue()`, and `agent.stream()` also accept `agent_config`, `capture_config`, `webhook_url`, `use_profile`, and `profile_id`:
461
+
462
+ ```python
463
+ from tinyfish import AgentConfig, CaptureConfig
464
+
465
+ response = client.agent.run(
466
+ goal="...",
467
+ url="...",
468
+ agent_config=AgentConfig(mode="strict", cursor_style="standard", max_duration_seconds=300),
469
+ capture_config=CaptureConfig(screenshots=True, html=True),
470
+ webhook_url="https://example.com/tinyfish-webhook",
471
+ use_profile=True,
472
+ profile_id="prof_abc123def4567890",
473
+ )
474
+ ```
475
+
476
+ - `agent_config` (`AgentConfig`) — `mode`, `cursor_style`, `max_steps`, `max_duration_seconds`
477
+ - `capture_config` (`CaptureConfig`) — `elements`, `snapshots`, `screenshots`, `recording`, `html`
478
+ - `webhook_url` — HTTPS URL notified on run lifecycle events
479
+ - `profile_id` — a specific Browser Context Profile; requires `use_profile=True`
480
+
481
+ `elements` and `recording` are gated capabilities: an account without them enabled gets a 403 saying the capability is not enabled.
482
+
407
483
  ### Browser Context Profiles
408
484
 
409
485
  Use Browser Context Profiles when a run should start from saved logged-in state. Pass `use_profile=True` for your default profile, or add `profile_id` for a specific profile. Pair with `use_vault=True` when TinyFish should repair stale sessions with saved credentials.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "tinyfish"
3
- version = "0.6.1"
3
+ version = "0.8.0"
4
4
  description = "Official Python SDK for the TinyFish API"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -27,11 +27,15 @@ from ._utils.exceptions import (
27
27
  # Agent resource
28
28
  from .agent import AgentStream, AsyncAgentStream
29
29
  from .agent.types import (
30
+ AgentConfig,
31
+ AgentMode,
30
32
  AgentRunAsyncResponse,
31
33
  AgentRunResponse,
32
34
  AgentRunWithStreamingResponse,
33
35
  BrowserProfile,
36
+ CaptureConfig,
34
37
  CompleteEvent,
38
+ CursorStyle,
35
39
  EventType,
36
40
  HeartbeatEvent,
37
41
  ProgressEvent,
@@ -47,8 +51,10 @@ from .client import AsyncTinyFish, TinyFish
47
51
  from .fetch.types import (
48
52
  FetchError,
49
53
  FetchFormat,
54
+ FetchHighlights,
50
55
  FetchResponse,
51
56
  FetchResult,
57
+ HighlightSnippet,
52
58
  )
53
59
 
54
60
  # Runs types
@@ -120,7 +126,11 @@ __all__ = [
120
126
  "BrowserSessionCreateParams",
121
127
  # Agent types
122
128
  "EventType",
129
+ "AgentConfig",
130
+ "AgentMode",
123
131
  "BrowserProfile",
132
+ "CaptureConfig",
133
+ "CursorStyle",
124
134
  "ProxyCountryCode",
125
135
  "ProxyConfig",
126
136
  "AgentRunResponse",
@@ -136,6 +146,8 @@ __all__ = [
136
146
  "FetchResult",
137
147
  "FetchError",
138
148
  "FetchResponse",
149
+ "FetchHighlights",
150
+ "HighlightSnippet",
139
151
  # Search types
140
152
  "SearchResult",
141
153
  "SearchQueryResponse",
@@ -9,10 +9,12 @@ from tinyfish._utils.resource import BaseAsyncAPIResource, BaseSyncAPIResource
9
9
  from tinyfish._utils.sse_parser import async_parse_sse_line_stream, parse_sse_line_stream
10
10
 
11
11
  from .types import (
12
+ AgentConfig,
12
13
  AgentRunAsyncResponse,
13
14
  AgentRunResponse,
14
15
  AgentRunWithStreamingResponse,
15
16
  BrowserProfile,
17
+ CaptureConfig,
16
18
  CompleteEvent,
17
19
  HeartbeatEvent,
18
20
  ProgressEvent,
@@ -27,6 +29,9 @@ def _build_run_body(
27
29
  url: str,
28
30
  browser_profile: BrowserProfile | None,
29
31
  proxy_config: ProxyConfig | None,
32
+ agent_config: AgentConfig | None,
33
+ capture_config: CaptureConfig | None,
34
+ webhook_url: str | None,
30
35
  output_schema: dict[str, Any] | None,
31
36
  use_profile: bool | None = None,
32
37
  profile_id: str | None = None,
@@ -38,6 +43,12 @@ def _build_run_body(
38
43
  body["browser_profile"] = browser_profile
39
44
  if proxy_config is not None:
40
45
  body["proxy_config"] = proxy_config.model_dump(exclude_none=True)
46
+ if agent_config is not None:
47
+ body["agent_config"] = agent_config.model_dump(exclude_none=True, mode="json")
48
+ if capture_config is not None:
49
+ body["capture_config"] = capture_config.model_dump(exclude_none=True)
50
+ if webhook_url is not None:
51
+ body["webhook_url"] = webhook_url
41
52
  if output_schema is not None:
42
53
  body["output_schema"] = output_schema
43
54
  if use_profile is not None:
@@ -126,6 +137,9 @@ class AgentResource(BaseSyncAPIResource):
126
137
  url: str,
127
138
  browser_profile: BrowserProfile | None = None,
128
139
  proxy_config: ProxyConfig | None = None,
140
+ agent_config: AgentConfig | None = None,
141
+ capture_config: CaptureConfig | None = None,
142
+ webhook_url: str | None = None,
129
143
  output_schema: dict[str, Any] | None = None,
130
144
  use_profile: bool | None = None,
131
145
  profile_id: str | None = None,
@@ -142,6 +156,9 @@ class AgentResource(BaseSyncAPIResource):
142
156
  url: The URL to open the browser on.
143
157
  browser_profile: "lite" (default) or "stealth" (anti-detection).
144
158
  proxy_config: Optional proxy settings (enabled, country_code).
159
+ agent_config: Optional agent behavior settings.
160
+ capture_config: Optional artifact capture settings.
161
+ webhook_url: Optional HTTPS URL for run lifecycle webhooks.
145
162
  output_schema: Optional JSON Schema object describing the expected final result.
146
163
  use_profile: Whether to start from a saved Browser Context Profile.
147
164
  profile_id: Specific Browser Context Profile ID. Requires use_profile=True.
@@ -161,6 +178,9 @@ class AgentResource(BaseSyncAPIResource):
161
178
  url,
162
179
  browser_profile,
163
180
  proxy_config,
181
+ agent_config,
182
+ capture_config,
183
+ webhook_url,
164
184
  output_schema,
165
185
  use_profile,
166
186
  profile_id,
@@ -176,6 +196,9 @@ class AgentResource(BaseSyncAPIResource):
176
196
  url: str,
177
197
  browser_profile: BrowserProfile | None = None,
178
198
  proxy_config: ProxyConfig | None = None,
199
+ agent_config: AgentConfig | None = None,
200
+ capture_config: CaptureConfig | None = None,
201
+ webhook_url: str | None = None,
179
202
  output_schema: dict[str, Any] | None = None,
180
203
  use_profile: bool | None = None,
181
204
  profile_id: str | None = None,
@@ -192,6 +215,9 @@ class AgentResource(BaseSyncAPIResource):
192
215
  url: The URL to open the browser on.
193
216
  browser_profile: "lite" (default) or "stealth" (anti-detection).
194
217
  proxy_config: Optional proxy settings (enabled, country_code).
218
+ agent_config: Optional agent behavior settings.
219
+ capture_config: Optional artifact capture settings.
220
+ webhook_url: Optional HTTPS URL for run lifecycle webhooks.
195
221
  output_schema: Optional JSON Schema object describing the expected final result.
196
222
  use_profile: Whether to start from a saved Browser Context Profile.
197
223
  profile_id: Specific Browser Context Profile ID. Requires use_profile=True.
@@ -211,6 +237,9 @@ class AgentResource(BaseSyncAPIResource):
211
237
  url,
212
238
  browser_profile,
213
239
  proxy_config,
240
+ agent_config,
241
+ capture_config,
242
+ webhook_url,
214
243
  output_schema,
215
244
  use_profile,
216
245
  profile_id,
@@ -226,6 +255,9 @@ class AgentResource(BaseSyncAPIResource):
226
255
  url: str,
227
256
  browser_profile: BrowserProfile | None = None,
228
257
  proxy_config: ProxyConfig | None = None,
258
+ agent_config: AgentConfig | None = None,
259
+ capture_config: CaptureConfig | None = None,
260
+ webhook_url: str | None = None,
229
261
  output_schema: dict[str, Any] | None = None,
230
262
  use_profile: bool | None = None,
231
263
  profile_id: str | None = None,
@@ -267,6 +299,9 @@ class AgentResource(BaseSyncAPIResource):
267
299
  url: The URL to open the browser on.
268
300
  browser_profile: "lite" (default) or "stealth" (anti-detection).
269
301
  proxy_config: Optional proxy settings (enabled, country_code).
302
+ agent_config: Optional agent behavior settings.
303
+ capture_config: Optional artifact capture settings.
304
+ webhook_url: Optional HTTPS URL for run lifecycle webhooks.
270
305
  output_schema: Optional JSON Schema object describing the expected final result.
271
306
  use_profile: Whether to start from a saved Browser Context Profile.
272
307
  profile_id: Specific Browser Context Profile ID. Requires use_profile=True.
@@ -291,6 +326,9 @@ class AgentResource(BaseSyncAPIResource):
291
326
  url,
292
327
  browser_profile,
293
328
  proxy_config,
329
+ agent_config,
330
+ capture_config,
331
+ webhook_url,
294
332
  output_schema,
295
333
  use_profile,
296
334
  profile_id,
@@ -341,6 +379,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
341
379
  url: str,
342
380
  browser_profile: BrowserProfile | None = None,
343
381
  proxy_config: ProxyConfig | None = None,
382
+ agent_config: AgentConfig | None = None,
383
+ capture_config: CaptureConfig | None = None,
384
+ webhook_url: str | None = None,
344
385
  output_schema: dict[str, Any] | None = None,
345
386
  use_profile: bool | None = None,
346
387
  profile_id: str | None = None,
@@ -357,6 +398,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
357
398
  url: The URL to open the browser on.
358
399
  browser_profile: "lite" (default) or "stealth" (anti-detection).
359
400
  proxy_config: Optional proxy settings (enabled, country_code).
401
+ agent_config: Optional agent behavior settings.
402
+ capture_config: Optional artifact capture settings.
403
+ webhook_url: Optional HTTPS URL for run lifecycle webhooks.
360
404
  output_schema: Optional JSON Schema object describing the expected final result.
361
405
  use_profile: Whether to start from a saved Browser Context Profile.
362
406
  profile_id: Specific Browser Context Profile ID. Requires use_profile=True.
@@ -376,6 +420,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
376
420
  url,
377
421
  browser_profile,
378
422
  proxy_config,
423
+ agent_config,
424
+ capture_config,
425
+ webhook_url,
379
426
  output_schema,
380
427
  use_profile,
381
428
  profile_id,
@@ -391,6 +438,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
391
438
  url: str,
392
439
  browser_profile: BrowserProfile | None = None,
393
440
  proxy_config: ProxyConfig | None = None,
441
+ agent_config: AgentConfig | None = None,
442
+ capture_config: CaptureConfig | None = None,
443
+ webhook_url: str | None = None,
394
444
  output_schema: dict[str, Any] | None = None,
395
445
  use_profile: bool | None = None,
396
446
  profile_id: str | None = None,
@@ -407,6 +457,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
407
457
  url: The URL to open the browser on.
408
458
  browser_profile: "lite" (default) or "stealth" (anti-detection).
409
459
  proxy_config: Optional proxy settings (enabled, country_code).
460
+ agent_config: Optional agent behavior settings.
461
+ capture_config: Optional artifact capture settings.
462
+ webhook_url: Optional HTTPS URL for run lifecycle webhooks.
410
463
  output_schema: Optional JSON Schema object describing the expected final result.
411
464
  use_profile: Whether to start from a saved Browser Context Profile.
412
465
  profile_id: Specific Browser Context Profile ID. Requires use_profile=True.
@@ -426,6 +479,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
426
479
  url,
427
480
  browser_profile,
428
481
  proxy_config,
482
+ agent_config,
483
+ capture_config,
484
+ webhook_url,
429
485
  output_schema,
430
486
  use_profile,
431
487
  profile_id,
@@ -441,6 +497,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
441
497
  url: str,
442
498
  browser_profile: BrowserProfile | None = None,
443
499
  proxy_config: ProxyConfig | None = None,
500
+ agent_config: AgentConfig | None = None,
501
+ capture_config: CaptureConfig | None = None,
502
+ webhook_url: str | None = None,
444
503
  output_schema: dict[str, Any] | None = None,
445
504
  use_profile: bool | None = None,
446
505
  profile_id: str | None = None,
@@ -482,6 +541,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
482
541
  url: The URL to open the browser on.
483
542
  browser_profile: "lite" (default) or "stealth" (anti-detection).
484
543
  proxy_config: Optional proxy settings (enabled, country_code).
544
+ agent_config: Optional agent behavior settings.
545
+ capture_config: Optional artifact capture settings.
546
+ webhook_url: Optional HTTPS URL for run lifecycle webhooks.
485
547
  output_schema: Optional JSON Schema object describing the expected final result.
486
548
  use_profile: Whether to start from a saved Browser Context Profile.
487
549
  profile_id: Specific Browser Context Profile ID. Requires use_profile=True.
@@ -506,6 +568,9 @@ class AsyncAgentResource(BaseAsyncAPIResource):
506
568
  url,
507
569
  browser_profile,
508
570
  proxy_config,
571
+ agent_config,
572
+ capture_config,
573
+ webhook_url,
509
574
  output_schema,
510
575
  use_profile,
511
576
  profile_id,
@@ -40,6 +40,49 @@ class ProxyConfig(BaseModel):
40
40
  """ISO 3166-1 alpha-2 country code for proxy location."""
41
41
 
42
42
 
43
+ class AgentMode(StrEnum):
44
+ """Agent behavior mode."""
45
+
46
+ DEFAULT = "default"
47
+ STRICT = "strict"
48
+
49
+
50
+ class CursorStyle(StrEnum):
51
+ """Cursor style rendered in the browser recording."""
52
+
53
+ FISH = "fish"
54
+ STANDARD = "standard"
55
+ GREEN_POINTER = "green-pointer"
56
+
57
+
58
+ class AgentConfig(BaseModel):
59
+ """Agent behavior settings."""
60
+
61
+ mode: AgentMode | None = None
62
+ """"strict" enforces the goal more literally; defaults to "default"."""
63
+ cursor_style: CursorStyle | None = None
64
+ """Cursor style rendered in the browser recording."""
65
+ max_steps: int | None = Field(default=None, ge=1, le=500)
66
+ """Maximum tool-call steps before stopping."""
67
+ max_duration_seconds: int | None = Field(default=None, ge=1)
68
+ """Maximum wall-clock seconds before stopping."""
69
+
70
+
71
+ class CaptureConfig(BaseModel):
72
+ """Artifact capture settings."""
73
+
74
+ elements: bool | None = None
75
+ """Capture page element metadata. Gated capability; 403 if not enabled."""
76
+ snapshots: bool | None = None
77
+ """Capture page snapshots."""
78
+ screenshots: bool | None = None
79
+ """Capture screenshots."""
80
+ recording: bool | None = None
81
+ """Capture a browser recording. Gated capability; 403 if not enabled."""
82
+ html: bool | None = None
83
+ """Capture HTML snapshots."""
84
+
85
+
43
86
  class EventType(StrEnum):
44
87
  """SSE event type discriminator."""
45
88
 
@@ -2,10 +2,12 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from pydantic import ValidationError
6
+
5
7
  from tinyfish._utils.exceptions import SDKError
6
8
  from tinyfish._utils.resource import BaseAsyncAPIResource, BaseSyncAPIResource
7
9
 
8
- from .types import FetchFormat, FetchResponse
10
+ from .types import FetchFormat, FetchHighlights, FetchResponse
9
11
 
10
12
  MIN_URLS = 1
11
13
  MAX_URLS = 10
@@ -31,6 +33,7 @@ class FetchResource(BaseSyncAPIResource):
31
33
  if_none_match: str | None = None,
32
34
  if_modified_since: str | None = None,
33
35
  include_etag_and_last_modified: bool | None = None,
36
+ highlights: FetchHighlights | dict[str, object] | None = None,
34
37
  ) -> FetchResponse:
35
38
  """Fetch and extract content from one or more URLs.
36
39
 
@@ -69,6 +72,11 @@ class FetchResource(BaseSyncAPIResource):
69
72
  ``last_modified`` validators (and ``not_modified`` detection)
70
73
  on each result. Defaults to false — those fields come back
71
74
  only when this is set. Works with a single URL or a batch.
75
+ highlights: Query-ranked snippets per page (beta). ``FetchHighlights``
76
+ or a dict with ``query`` (required), ``max_snippets`` (1..20,
77
+ default 5), ``max_characters`` (>= 1 or None) and
78
+ ``include_full_page_text`` (default False, leaving ``text``
79
+ None). Markdown format only.
72
80
 
73
81
  Returns:
74
82
  FetchResponse with results and errors lists.
@@ -76,14 +84,17 @@ class FetchResource(BaseSyncAPIResource):
76
84
  Raises:
77
85
  SDKError: urls is empty or has more than 10 items, purpose is
78
86
  empty or over 2000 characters, ttl is negative or not an
79
- integer, or per_url_timeout_ms is outside 1..110000.
87
+ integer, per_url_timeout_ms is outside 1..110000, or
88
+ highlights is malformed or paired with a non-markdown format.
80
89
  AuthenticationError: Invalid API key.
90
+ PermissionDeniedError: highlights sent from an account not in the beta.
81
91
  """
82
92
  _validate_urls(urls)
83
93
  _validate_purpose(purpose)
84
94
  _validate_ttl(ttl)
85
95
  _validate_per_url_timeout_ms(per_url_timeout_ms)
86
96
  _validate_conditional_headers(urls, if_none_match, if_modified_since)
97
+ highlights = _validate_highlights(format, highlights)
87
98
  body = _build_body(
88
99
  urls,
89
100
  purpose=purpose,
@@ -96,6 +107,7 @@ class FetchResource(BaseSyncAPIResource):
96
107
  if_none_match=if_none_match,
97
108
  if_modified_since=if_modified_since,
98
109
  include_etag_and_last_modified=include_etag_and_last_modified,
110
+ highlights=highlights,
99
111
  )
100
112
  return self._post(self._client.product_url("fetch"), json=body, cast_to=FetchResponse)
101
113
 
@@ -117,6 +129,7 @@ class AsyncFetchResource(BaseAsyncAPIResource):
117
129
  if_none_match: str | None = None,
118
130
  if_modified_since: str | None = None,
119
131
  include_etag_and_last_modified: bool | None = None,
132
+ highlights: FetchHighlights | dict[str, object] | None = None,
120
133
  ) -> FetchResponse:
121
134
  """Fetch and extract content from one or more URLs.
122
135
 
@@ -149,6 +162,8 @@ class AsyncFetchResource(BaseAsyncAPIResource):
149
162
  ``last_modified`` validators (and ``not_modified`` detection)
150
163
  on each result. Defaults to false. Works with a single URL or
151
164
  a batch.
165
+ highlights: Query-ranked snippets per page (beta). See
166
+ FetchResource.get_contents for the accepted shape.
152
167
 
153
168
  Returns:
154
169
  FetchResponse with results and errors lists.
@@ -156,14 +171,17 @@ class AsyncFetchResource(BaseAsyncAPIResource):
156
171
  Raises:
157
172
  SDKError: urls is empty or has more than 10 items, purpose is
158
173
  empty or over 2000 characters, ttl is negative or not an
159
- integer, or per_url_timeout_ms is outside 1..110000.
174
+ integer, per_url_timeout_ms is outside 1..110000, or
175
+ highlights is malformed or paired with a non-markdown format.
160
176
  AuthenticationError: Invalid API key.
177
+ PermissionDeniedError: highlights sent from an account not in the beta.
161
178
  """
162
179
  _validate_urls(urls)
163
180
  _validate_purpose(purpose)
164
181
  _validate_ttl(ttl)
165
182
  _validate_per_url_timeout_ms(per_url_timeout_ms)
166
183
  _validate_conditional_headers(urls, if_none_match, if_modified_since)
184
+ highlights = _validate_highlights(format, highlights)
167
185
  body = _build_body(
168
186
  urls,
169
187
  purpose=purpose,
@@ -176,6 +194,7 @@ class AsyncFetchResource(BaseAsyncAPIResource):
176
194
  if_none_match=if_none_match,
177
195
  if_modified_since=if_modified_since,
178
196
  include_etag_and_last_modified=include_etag_and_last_modified,
197
+ highlights=highlights,
179
198
  )
180
199
  return await self._post(self._client.product_url("fetch"), json=body, cast_to=FetchResponse)
181
200
 
@@ -235,6 +254,20 @@ def _validate_conditional_headers(urls: list[str], if_none_match: str | None, if
235
254
  raise SDKError("if_modified_since can only be used with a single URL, not a batch")
236
255
 
237
256
 
257
+ def _validate_highlights(
258
+ format: FetchFormat | None,
259
+ highlights: FetchHighlights | dict[str, object] | None,
260
+ ) -> FetchHighlights | None:
261
+ if highlights is None:
262
+ return None
263
+ if format is not None and format != "markdown":
264
+ raise SDKError("highlights is only valid when format is 'markdown'")
265
+ try:
266
+ return FetchHighlights.model_validate(highlights)
267
+ except ValidationError as exc:
268
+ raise SDKError(f"highlights is invalid: {exc}") from exc
269
+
270
+
238
271
  def _build_body(
239
272
  urls: list[str],
240
273
  *,
@@ -248,6 +281,7 @@ def _build_body(
248
281
  if_none_match: str | None,
249
282
  if_modified_since: str | None,
250
283
  include_etag_and_last_modified: bool | None,
284
+ highlights: FetchHighlights | None,
251
285
  ) -> dict[str, object]:
252
286
  body: dict[str, object] = {"urls": urls}
253
287
  if purpose is not None:
@@ -270,4 +304,6 @@ def _build_body(
270
304
  body["if_modified_since"] = if_modified_since
271
305
  if include_etag_and_last_modified is not None:
272
306
  body["include_etag_and_last_modified"] = include_etag_and_last_modified
307
+ if highlights is not None:
308
+ body["highlights"] = highlights.model_dump()
273
309
  return body
@@ -4,11 +4,30 @@ from __future__ import annotations
4
4
 
5
5
  from typing import Literal
6
6
 
7
- from pydantic import BaseModel, Field
7
+ from pydantic import BaseModel, ConfigDict, Field
8
8
 
9
9
  FetchFormat = Literal["markdown", "html", "json"]
10
10
 
11
11
 
12
+ class FetchHighlights(BaseModel):
13
+ """Request query-ranked snippets from each page; markdown format only."""
14
+
15
+ # strict: no coercion; forbid: a typo'd key must not silently fall to a default.
16
+ model_config = ConfigDict(strict=True, extra="forbid")
17
+
18
+ query: str = Field(..., min_length=1, description="Query used to rank and select snippets")
19
+ max_snippets: int = Field(5, ge=1, le=20, description="Maximum snippets per URL")
20
+ max_characters: int | None = Field(None, ge=1, description="Total character cap across snippets")
21
+ include_full_page_text: bool = Field(False, description="Also populate text; otherwise text is None")
22
+
23
+
24
+ class HighlightSnippet(BaseModel):
25
+ """A single highlighted snippet extracted from a page."""
26
+
27
+ text: str = Field(..., description="Verbatim snippet text")
28
+ rank: int = Field(..., description="1-based relevance rank, 1 = most relevant")
29
+
30
+
12
31
  class FetchResult(BaseModel):
13
32
  """A single successfully fetched URL result."""
14
33
 
@@ -38,6 +57,9 @@ class FetchResult(BaseModel):
38
57
  None,
39
58
  description="Origin Last-Modified validator; omitted when not applicable",
40
59
  )
60
+ highlights: list[HighlightSnippet] | None = Field(
61
+ None, description="Query-ranked snippets; present only when highlights was requested"
62
+ )
41
63
 
42
64
 
43
65
  class FetchError(BaseModel):
@@ -50,12 +50,14 @@ class ErrorCategory(StrEnum):
50
50
 
51
51
  SYSTEM_FAILURE = "SYSTEM_FAILURE"
52
52
  AGENT_FAILURE = "AGENT_FAILURE"
53
+ BILLING_FAILURE = "BILLING_FAILURE"
53
54
  UNKNOWN = "UNKNOWN"
54
55
 
55
56
 
56
57
  class RunError(BaseModel):
57
58
  """Error details for failed runs."""
58
59
 
60
+ code: str | None = Field(None, description="Machine-readable error code")
59
61
  message: str = Field(..., description="Error message describing why the run failed")
60
62
  category: ErrorCategory = Field(..., description="Error category indicating the source of failure")
61
63
  retry_after: int | None = Field(None, description="Suggested retry delay in seconds")
@@ -11,9 +11,11 @@ from respx import MockRouter
11
11
 
12
12
  from tests.conftest import API_KEY, BASE_URL
13
13
  from tinyfish import (
14
+ AgentConfig,
14
15
  AsyncTinyFish,
15
16
  AuthenticationError,
16
17
  BrowserProfile,
18
+ CaptureConfig,
17
19
  InternalServerError,
18
20
  ProxyConfig,
19
21
  ProxyCountryCode,
@@ -243,6 +245,45 @@ def test_run_all_params(client: TinyFish, respx_mock: MockRouter):
243
245
  assert body["proxy_config"]["country_code"] == "GB"
244
246
 
245
247
 
248
+ @pytest.mark.respx(base_url=BASE_URL)
249
+ def test_run_advanced_agent_params(client: TinyFish, respx_mock: MockRouter):
250
+ route = respx_mock.post(_RUN_PATH).mock(return_value=httpx.Response(200, json=_RUN_OK))
251
+ client.agent.run(
252
+ **_BODY,
253
+ agent_config=AgentConfig(
254
+ mode="strict",
255
+ cursor_style="standard",
256
+ max_steps=75,
257
+ max_duration_seconds=300,
258
+ ),
259
+ capture_config=CaptureConfig(
260
+ elements=True,
261
+ snapshots=True,
262
+ screenshots=False,
263
+ recording=True,
264
+ html=True,
265
+ ),
266
+ webhook_url="https://example.com/webhook",
267
+ use_profile=True,
268
+ )
269
+ body = json.loads(route.calls[0].request.content)
270
+ assert body["agent_config"] == {
271
+ "mode": "strict",
272
+ "cursor_style": "standard",
273
+ "max_steps": 75,
274
+ "max_duration_seconds": 300,
275
+ }
276
+ assert body["capture_config"] == {
277
+ "elements": True,
278
+ "snapshots": True,
279
+ "screenshots": False,
280
+ "recording": True,
281
+ "html": True,
282
+ }
283
+ assert body["webhook_url"] == "https://example.com/webhook"
284
+ assert body["use_profile"] is True
285
+
286
+
246
287
  # Sync run() sends output_schema in request body
247
288
  @pytest.mark.respx(base_url=BASE_URL)
248
289
  def test_run_output_schema_in_body(client: TinyFish, respx_mock: MockRouter):
@@ -319,14 +360,15 @@ def test_run_error_has_category(client: TinyFish, respx_mock: MockRouter):
319
360
 
320
361
 
321
362
  # Sync run() correctly maps each error category string
322
- @pytest.mark.parametrize("category", ["SYSTEM_FAILURE", "AGENT_FAILURE", "UNKNOWN"])
363
+ @pytest.mark.parametrize("category", ["SYSTEM_FAILURE", "AGENT_FAILURE", "BILLING_FAILURE", "UNKNOWN"])
323
364
  @pytest.mark.respx(base_url=BASE_URL)
324
365
  def test_run_error_category_values(category: str, client: TinyFish, respx_mock: MockRouter):
325
- data = {**_RUN_FAIL, "error": {"message": "err", "category": category}}
366
+ data = {**_RUN_FAIL, "error": {"code": "err_code", "message": "err", "category": category}}
326
367
  respx_mock.post(_RUN_PATH).mock(return_value=httpx.Response(200, json=data))
327
368
  result = client.agent.run(**_BODY)
328
369
  assert result.error is not None
329
370
  assert result.error.category == category
371
+ assert result.error.code == "err_code"
330
372
 
331
373
 
332
374
  # Sync run() raises AuthenticationError on 401 response
@@ -409,15 +451,16 @@ async def test_async_run_error_has_category(async_client: AsyncTinyFish, respx_m
409
451
 
410
452
 
411
453
  # Async run() correctly maps each error category string
412
- @pytest.mark.parametrize("category", ["SYSTEM_FAILURE", "AGENT_FAILURE", "UNKNOWN"])
454
+ @pytest.mark.parametrize("category", ["SYSTEM_FAILURE", "AGENT_FAILURE", "BILLING_FAILURE", "UNKNOWN"])
413
455
  @pytest.mark.respx(base_url=BASE_URL)
414
456
  async def test_async_run_error_category_values(category: str, async_client: AsyncTinyFish, respx_mock: MockRouter):
415
- data = {**_RUN_FAIL, "error": {"message": "err", "category": category}}
457
+ data = {**_RUN_FAIL, "error": {"code": "err_code", "message": "err", "category": category}}
416
458
  respx_mock.post(_RUN_PATH).mock(return_value=httpx.Response(200, json=data))
417
459
  async with async_client as c:
418
460
  result = await c.agent.run(**_BODY)
419
461
  assert result.error is not None
420
462
  assert result.error.category == category
463
+ assert result.error.code == "err_code"
421
464
 
422
465
 
423
466
  # Async run() sends all params (browser_profile, proxy_config) in body
@@ -11,7 +11,7 @@ from respx import MockRouter
11
11
 
12
12
  from tests.conftest import BASE_URL
13
13
  from tinyfish import AsyncTinyFish, AuthenticationError, SDKError, TinyFish
14
- from tinyfish.fetch.types import FetchResponse
14
+ from tinyfish.fetch.types import FetchHighlights, FetchResponse, HighlightSnippet
15
15
 
16
16
  # ─── Paths ────────────────────────────────────────────────────────────────────
17
17
 
@@ -335,6 +335,90 @@ def test_get_contents_conditional_headers_allowed_single_url(client: TinyFish, r
335
335
  assert body["if_modified_since"] == "Wed, 21 Oct 2015 07:28:00 GMT"
336
336
 
337
337
 
338
+ @pytest.mark.respx(base_url=BASE_URL)
339
+ def test_get_contents_sends_highlights_with_defaults(client: TinyFish, respx_mock: MockRouter):
340
+ route = respx_mock.post(_FETCH_PATH).mock(return_value=httpx.Response(200, json=_response(results=[_result()])))
341
+ client.fetch.get_contents(["https://example.com"], highlights={"query": "pricing tiers"})
342
+ body = json.loads(route.calls[0].request.content)
343
+ assert body["highlights"] == {
344
+ "query": "pricing tiers",
345
+ "max_snippets": 5,
346
+ "max_characters": None,
347
+ "include_full_page_text": False,
348
+ }
349
+
350
+
351
+ @pytest.mark.respx(base_url=BASE_URL)
352
+ def test_get_contents_accepts_highlights_model(client: TinyFish, respx_mock: MockRouter):
353
+ route = respx_mock.post(_FETCH_PATH).mock(return_value=httpx.Response(200, json=_response(results=[_result()])))
354
+ client.fetch.get_contents(
355
+ ["https://example.com"],
356
+ format="markdown",
357
+ highlights=FetchHighlights(query="pricing", max_snippets=3, max_characters=800, include_full_page_text=True),
358
+ )
359
+ body = json.loads(route.calls[0].request.content)
360
+ assert body["highlights"] == {
361
+ "query": "pricing",
362
+ "max_snippets": 3,
363
+ "max_characters": 800,
364
+ "include_full_page_text": True,
365
+ }
366
+
367
+
368
+ @pytest.mark.parametrize("format", ["html", "json"], ids=["html", "json"])
369
+ def test_get_contents_highlights_rejects_non_markdown(format: str, client: TinyFish):
370
+ with pytest.raises(SDKError, match="highlights is only valid when format is 'markdown'"):
371
+ client.fetch.get_contents(["https://example.com"], format=format, highlights={"query": "q"}) # type: ignore[arg-type]
372
+
373
+
374
+ @pytest.mark.parametrize(
375
+ "highlights",
376
+ [
377
+ {},
378
+ {"query": ""},
379
+ {"query": "q", "max_snippets": 0},
380
+ {"query": "q", "max_snippets": 21},
381
+ {"query": "q", "max_characters": 0},
382
+ {"query": "q", "include_full_page_text": "yes"},
383
+ {"query": "q", "max_snippet": 3},
384
+ ],
385
+ ids=[
386
+ "missing_query",
387
+ "empty_query",
388
+ "snippets_zero",
389
+ "snippets_too_many",
390
+ "characters_zero",
391
+ "text_not_bool",
392
+ "unknown_key",
393
+ ],
394
+ )
395
+ def test_get_contents_invalid_highlights(highlights: dict[str, Any], client: TinyFish):
396
+ with pytest.raises(SDKError, match="highlights"):
397
+ client.fetch.get_contents(["https://example.com"], highlights=highlights)
398
+
399
+
400
+ @pytest.mark.respx(base_url=BASE_URL)
401
+ def test_get_contents_parses_highlights(client: TinyFish, respx_mock: MockRouter):
402
+ snippets = [{"text": "Pro plan is $20/mo", "rank": 1}, {"text": "Free tier available", "rank": 2}]
403
+ respx_mock.post(_FETCH_PATH).mock(
404
+ return_value=httpx.Response(200, json=_response(results=[_result(text=None, highlights=snippets)]))
405
+ )
406
+ result = client.fetch.get_contents(["https://example.com"], highlights={"query": "pricing"})
407
+ assert result.results[0].text is None
408
+ assert result.results[0].highlights == [
409
+ HighlightSnippet(text="Pro plan is $20/mo", rank=1),
410
+ HighlightSnippet(text="Free tier available", rank=2),
411
+ ]
412
+
413
+
414
+ @pytest.mark.respx(base_url=BASE_URL)
415
+ def test_get_contents_highlights_absent_when_not_requested(client: TinyFish, respx_mock: MockRouter):
416
+ route = respx_mock.post(_FETCH_PATH).mock(return_value=httpx.Response(200, json=_response(results=[_result()])))
417
+ result = client.fetch.get_contents(["https://example.com"])
418
+ assert "highlights" not in json.loads(route.calls[0].request.content)
419
+ assert result.results[0].highlights is None
420
+
421
+
338
422
  @pytest.mark.respx(base_url=BASE_URL)
339
423
  def test_get_contents_401(client: TinyFish, respx_mock: MockRouter):
340
424
  respx_mock.post(_FETCH_PATH).mock(return_value=httpx.Response(401, json={"error": {"message": "unauthorized"}}))
@@ -475,6 +559,20 @@ async def test_async_get_contents_conditional_headers_allowed_single_url(
475
559
  assert body["if_modified_since"] == "Wed, 21 Oct 2015 07:28:00 GMT"
476
560
 
477
561
 
562
+ @pytest.mark.respx(base_url=BASE_URL)
563
+ async def test_async_get_contents_sends_highlights(async_client: AsyncTinyFish, respx_mock: MockRouter):
564
+ route = respx_mock.post(_FETCH_PATH).mock(return_value=httpx.Response(200, json=_response(results=[_result()])))
565
+ await async_client.fetch.get_contents(["https://example.com"], highlights={"query": "pricing", "max_snippets": 2})
566
+ body = json.loads(route.calls[0].request.content)
567
+ assert body["highlights"]["query"] == "pricing"
568
+ assert body["highlights"]["max_snippets"] == 2
569
+
570
+
571
+ async def test_async_get_contents_highlights_rejects_non_markdown(async_client: AsyncTinyFish):
572
+ with pytest.raises(SDKError, match="highlights is only valid when format is 'markdown'"):
573
+ await async_client.fetch.get_contents(["https://example.com"], format="html", highlights={"query": "q"})
574
+
575
+
478
576
  @pytest.mark.respx(base_url=BASE_URL)
479
577
  async def test_async_get_contents_401(async_client: AsyncTinyFish, respx_mock: MockRouter):
480
578
  respx_mock.post(_FETCH_PATH).mock(return_value=httpx.Response(401, json={"error": {"message": "unauthorized"}}))
@@ -329,7 +329,7 @@ wheels = [
329
329
 
330
330
  [[package]]
331
331
  name = "tinyfish"
332
- version = "0.4.0"
332
+ version = "0.6.1"
333
333
  source = { editable = "." }
334
334
  dependencies = [
335
335
  { name = "httpx" },
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes