Build a browser agent
ctx.browser lets an agent drive a real browser one step at a time:
open a page, click, type, wait, read text and extract rows. The browser
runs where the platform puts it: on the customer's
Konstera Companion when the agent is pinned to
one. Your code is the same either way.
pip install "konstera-sdk>=0.7.0"
Declare what the agent needs#
Add browser to the kernel services in your manifest, and ask for a
Website login (browser_login) connection:
{
"connectionRequirements": [
{
"purpose": "supplier_portal",
"acceptableTypes": ["browser_login"],
"grantRequired": true,
"description": "A Website login for the supplier portal account."
}
],
"kernelServices": {
"required": ["log", "connector", "browser"]
}
}
The tenant creates the Website login in the portal (site address, username, password, optional authenticator key and named extra fields) and grants it to your agent. Your code only ever sees its alias and its non-secret settings.
Open a session and sign in#
from konstera_sdk import Agent, AgentContext, AgentFailure, AgentRequest, AgentResponse, run
class SupplierOrders(Agent):
async def handle(self, req: AgentRequest, ctx: AgentContext) -> AgentResponse:
grants = await ctx.connector.list()
logins = [g for g in grants if g.connector_type_key == "browser_login"]
if not logins:
raise AgentFailure(
"No Website login is granted to this agent.",
category=AgentFailure.CREDENTIAL_MISSING,
)
async with await ctx.browser.open_session(logins[0].alias) as page:
site = page.connection["config"]["site_url"]
await page.navigate(f"{site}/orders")
if (await page.exists("#username"))["exists"]:
# Typed by the kernel, by reference: the values never reach this process.
await page.type_secret("#username", "username")
await page.type_secret("#password", "password")
await page.click("button[type=submit]")
await page.wait_for(url_contains="/orders", timeout_seconds=20)
rows = await page.extract(
"table.orders tbody tr",
{
"id": {"selector": "td.order-id"},
"status": {"selector": "td.status"},
"link": {"selector": "a", "attr": "href"},
},
)
return AgentResponse(content=f"{len(rows)} orders", structured={"orders": rows})
if __name__ == "__main__":
run(SupplierOrders())
Leaving the async with block closes the session. The browser profile for
that connection is kept, so the next run usually starts already signed in.
Session methods#
| Method | Does | Returns |
|---|---|---|
navigate(url, wait_until="load") | Go to an absolute http(s) URL. wait_until: load, domcontentloaded, networkidle | {"url", "title"} after redirects |
click(selector, timeout_seconds=15) | Click the first match, waiting for it | None |
type(selector, text, timeout_seconds=15) | Type plain, non-secret text | None |
type_secret(selector, secret_field) | Kernel types a secret of the connection: "username", "password", a named extra field such as "pin", or "totp" for the current authenticator code | None |
wait_for(selector=None, url_contains=None, timeout_seconds=30) | Wait for a visible element and/or a URL substring | {"matched", "url"}; matched is False on timeout, not an error |
exists(selector) | Check now, without waiting | {"exists", "count"} |
text(selector) | Inner text of the first match | str or None |
extract(row_selector, fields) | One dict per row. fields: {name: {"selector", "attr"?, "all"?}}, plain CSS relative to the row; "" means the row itself | list[dict] |
screenshot(label) | PNG of the current page | bytes |
handoff_to_human(reason, until_selector=None, until_url_contains=None, timeout_seconds=300) | Ask a person to act in the window, then wait for the condition (up to 1800 s) | {"resolved", "url"} |
close() | Close the session; safe to call twice | None |
page.session_id is the kernel-issued session id. page.connection is
{"alias", "type", "config"}, where config holds only non-secret fields
such as site_url.
Selectors for click, type, wait_for, exists, text and the
extract row are Playwright selectors (CSS, text=…). Keep every
selector for a site in one module, so a page change is a one-file fix.
Secrets by reference#
type_secretnames a field. The kernel resolves the value and types it. Your code, logs, prompts and results never contain it.- The kernel types a secret only while the page is on the Website login's site (or one of its extra domains) over https. Anywhere else it refuses, so a redirect to a look-alike page can't harvest it.
- A field that isn't set on the connection raises an error that lists
the fields that are. For
"totp", the connection needs an authenticator key; if it has none, hand off instead. - Don't take screenshots while a secret field is filled in or focused.
Hand off to a person#
Use handoff_to_human for every CAPTCHA, SMS or email code, passkey
prompt, "approve on your phone", or page your agent doesn't recognise.
Never try to solve or get around a challenge: the platform does no
CAPTCHA solving, stealth or bot-detection evasion, and your agent
shouldn't either.
if (await page.exists("#captcha"))["exists"]:
result = await page.handoff_to_human(
"The supplier portal is showing a CAPTCHA. Please complete it in the browser window.",
until_url_contains="/orders",
timeout_seconds=600,
)
if not result["resolved"]:
raise AgentFailure(
"Waited 10 minutes for someone to complete the CAPTCHA on the supplier portal.",
category=AgentFailure.ACTION_NEEDED,
)
Write reason for the person at the PC: what the site is asking and
what to do. Give the agent's runtime.timeoutSeconds room for a hand-off
(the reference browser agent uses 900 seconds).
Tell Konstera what kind of failure it was#
An uncaught exception is recorded as agent_bug and retried. When the
cause is outside your code, raise AgentFailure with a category, so run
history, reports and retries reflect what actually happened.
| Category | Constant | Use when | Retried |
|---|---|---|---|
dependency_failure (default) | AgentFailure.DEPENDENCY_FAILURE | An outside system refused or failed: site down, timeout, error page | Yes |
action_needed | AgentFailure.ACTION_NEEDED | A person has a step to do first: fix the connection's password, complete a sign-in check | No |
input_invalid | AgentFailure.INPUT_INVALID | The input or the instance settings are wrong | No |
credential_missing | AgentFailure.CREDENTIAL_MISSING | A required connection or secret isn't set up or granted | No |
if (await page.exists(".login-error"))["exists"]:
raise AgentFailure(
"The supplier portal refused the username or password. Check the Website login.",
category=AgentFailure.ACTION_NEEDED,
)
You can also subclass it and set category on the class:
class SiteUnavailable(AgentFailure):
category = AgentFailure.DEPENDENCY_FAILURE
Only these four categories are accepted from an agent; anything else is ignored and the platform's own rules apply. Write messages a non-developer can act on: they appear in the portal's run list.
Testing#
- Unit tests: keep the flow in a module that takes the session as a
parameter, and test it with a fake session object that records calls.
Assert that sign-in uses
type_secret, nevertype, and that every challenge leads tohandoff_to_human. - Direct-run mode (no kernel): every
ctx.browsercall raisesRuntimeError, like other result-returning services.