Skip to content
Konstera
Docs · Konstera Companion
Konstera documentation.

Getting started, SDK quickstart, manifest reference, kernel MCP services, deploy guide and FAQ — everything you need to build and run agents on Konstera.

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.

What you'll have at the end
An agent that signs in to a site through a Website login without ever seeing the password, hands challenges to a person, and reports failures with the right category.
Level
Intermediate
You need
konstera-sdk 0.7.0 or later (Python)The SDK quickstartA Website login connection to test with
Terminal
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:

JSON
{
  "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#

Python
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#

MethodDoesReturns
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 itNone
type(selector, text, timeout_seconds=15)Type plain, non-secret textNone
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 codeNone
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 matchstr or None
extract(row_selector, fields)One dict per row. fields: {name: {"selector", "attr"?, "all"?}}, plain CSS relative to the row; "" means the row itselflist[dict]
screenshot(label)PNG of the current pagebytes
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 twiceNone

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_secret names 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.

Python
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.

CategoryConstantUse whenRetried
dependency_failure (default)AgentFailure.DEPENDENCY_FAILUREAn outside system refused or failed: site down, timeout, error pageYes
action_neededAgentFailure.ACTION_NEEDEDA person has a step to do first: fix the connection's password, complete a sign-in checkNo
input_invalidAgentFailure.INPUT_INVALIDThe input or the instance settings are wrongNo
credential_missingAgentFailure.CREDENTIAL_MISSINGA required connection or secret isn't set up or grantedNo
Python
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:

Python
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, never type, and that every challenge leads to handoff_to_human.
  • Direct-run mode (no kernel): every ctx.browser call raises RuntimeError, like other result-returning services.