Commit Graph
186 Commits
Author SHA1 Message Date
Karl Seguin 743408125e chore: remove lp.timedWait
This was added because it didn't exist in Zig 0.16. But it does in 0.17.
2026-11-05 09:53:22 +08:00
Adrià Arrufat deb376518f Merge pull request #4287 from lightpanda-io/structured-data-microdata
structured_data: add microdata
2026-11-02 11:31:15 +01:00
Adrià Arrufat 65d79303c8 mcp: run a script file by path
The MCP save tool writes a script on the server, but run only took the
source, so a client had to send it again to replay it. run now also
takes a path, checked with isPathSafe like save's.

The script file helpers move from the agent to lp.script_file, so /save,
/load and the MCP save and run tools read and write scripts the same way.
2026-10-30 16:27:04 +01:00
Adrià Arrufat e4b15c44ec Merge pull request #4041 from jayhemnani9910/feat/mcp-run
mcp: add a run tool for agent scripts
2026-10-30 15:57:48 +01:00
Adrià Arrufat b3a5e8437d Merge remote-tracking branch 'origin/main' into structured-data-microdata
main moved the tool definitions to tools/definitions.zig; the structuredData description and summary now change there.
2026-10-30 15:28:52 +01:00
Adrià Arrufat e119e9496e fetch: no Accept: text/markdown with --inject-script
Injected scripts run against the page's DOM, which a markdown response
doesn't have.
2026-10-30 07:19:36 +01:00
Adrià Arrufat ca814daab6 fetch: ask the server for markdown on markdown dumps
`fetch --dump markdown` sends `Accept: text/markdown` ahead of HTML. A
server that honors it (e.g. Cloudflare's Markdown for Agents) returns
markdown, which is dumped as-is and logged as "markdown served".

Not with --dump-selector, --wait-selector or --wait-script: they need
the page's DOM, which a markdown response doesn't have.
2026-10-29 16:32:22 +01:00
Adrià Arrufat 6437e977d0 structured_data: add microdata
Top-level itemscope items, in the shape of the HTML spec's JSON
conversion: {type, id, properties}, each property value an array of
strings or nested items. Properties follow the spec's crawl (descendants
plus itemref targets, not descending into nested items, tree order), its
per-element value rules (meta content, src/href/data URLs, data/meter
value, time datetime, else textContent, trimmed) and its "ERROR" for an
item that contains itself.

The key is emitted only when the page has items. Product, recipe and
review pages often declare their facts as microdata instead of JSON-LD.
2026-10-29 15:06:48 +01:00
Karl Seguin 7dcf8ef38e dev: groundwork for cross validating our unit tests in chrome
Will rely on an external driver (in demo) to run our page tests in Chrome and
catch unintentional divergence.

Initially this involves:

1 - Flagging every test with a marker (`<meta name=lp-mode content=test>`) so
    that the external runner knows this is a test file to be run, and not
    some support file.

2 - Extracting the TestHTTPServer and TestWSServer so that they can be run from
    a new (very simple) build step (`zig build test-server`) so that the
    test files and test endpoints (e.g. `/redirect_cross_echo_headers`) are
    accessible

3 - Starting to tweak testing.js so that it runs better in Chrome. Namely
    removing some of the attribution (for module scripts) which depend on our
    non-compliant document.currentScript behavior.

4 - Flagging a few tests and fixing them, as proof of concept.
2026-10-23 07:07:02 +08:00
Adrià Arrufat f9ef50ae03 lightpanda: move remainingMs above fetch's doc comment 2026-10-21 09:46:46 +02:00
Adrià Arrufat d9faa42b8e mcp: simplify run's console cap and page cleanup
Cap the console through LimitedWriter instead of a hand-rolled UTF-8 cut,
with its own limit rather than the session's console capture budget.
Share the evict-then-close pair as browser_tools.closePage, used by both
startGoto and the run cleanup. Move the run body into runScript so
allocation failures use plain try.
2026-10-20 16:38:48 +02:00
Adrià Arrufat 02a6f8295b tools: close the page when a goto fails to start
openPage left the page it created in the session when navigate failed
synchronously (e.g. a blob: URL that isn't registered). startGoto, which
the script Runtime uses for concurrent gotos, kept that blank page
around. fetch also gets a remainingMs helper for its three copies of the
remaining wait budget.
2026-10-20 16:16:59 +02:00
Adrià Arrufat 2b924d7962 markdown: share opening the alternate, write a followed alternate directly
fetch and the markdown tool opened the alternate with separate copies of
the same steps; both now call markdown.openAlternate, which also closes the
page when navigating fails. A followed alternate is written by
markdown.dumpAlternate instead of an Opts flag, and the http(s) check moves
to URL.isRemoteScheme, shared with preload.
2026-10-20 15:45:38 +02:00
Jay Hemnani 16fc3852f7 markdown: don't swap a failed page for its alternate, keep text documents byte-faithful 2026-10-20 14:55:21 +05:30
Jay Hemnani f391647241 markdown: follow text/plain alternates, say which source was used 2026-10-20 14:55:21 +05:30
Jay Hemnani 40290f3290 fetch, tools: opt-in follow of a page's text/markdown alternate
A page can link the author's markdown version of itself with
<link rel="alternate" type="text/markdown">. That file is usually
cleaner than converting the DOM, but it can differ from the rendered
page, so following it is opt-in:

- `fetch --dump markdown --markdown-alternate` loads the alternate in a
  page of the same session and dumps it in place of the page. With
  --json, "url" is the alternate's.
- the markdown tool takes `alternate: true` and reads the alternate in a
  separate page, so the current page stays where it is.

Only http(s) links are followed. When there is no such link, or the
link doesn't give a 2xx text/markdown response, the page is converted
as before.
2026-10-20 14:55:21 +05:30
Karl Seguin 8c73fb44a0 zig fmt 2026-10-20 06:25:14 +08:00
Karl Seguin 273a578e2f silence more expected logs 2026-10-20 06:23:24 +08:00
Karl Seguin f875090d44 ops: capture and expose page issue summary
Ultimately, the goal is to provide feedback to operators about any issues which
might have caused the page to struggle to load/render. For example, we want to
expose the # of JS errors, and whether resources weren't loaded (like iframes
because `--load-resource iframe` wasn't specified). We also want to expose
the use of unsupported or partially supported APIs, like webgl and canvas.

This is exposed in CDP via a new lp.getPageStatus. It's included in a `fetch`
with --json and when nav_note == true.
2026-10-20 06:15:24 +08:00
Adrià Arrufat 3ced705715 fetch: add --dump structured_data
Prints the page's JSON-LD, OpenGraph, Twitter card, meta and link tags
as JSON, the same output as the MCP structuredData tool.

Closes #3950
2026-10-16 20:53:27 +02:00
Adrià Arrufat 15523e906f Merge branch 'main' into shell-completion
# Conflicts:
#	src/Config.zig
2026-10-14 16:15:05 +02:00
Adrià Arrufat e5a7d3fab2 docs: generate reference partials with zig build docs
Render MDX partials for the docs site from the registries the runtime
serves, so the browser tools, MCP tools and agent REPL command references
can't drift from the code:

- browser-tools.mdx: every tool, grouped, with its description, an
  argument table from its input schema, and its script/navigation/page
  state traits.
- mcp-tools.mdx: titles and annotation hints per tool, linking to the
  browser tools reference, plus the MCP-only tools and resources.
- agent-commands.mdx: meta, LLM and browser slash commands in the syntax
  the REPL parses.

Tool.group() assigns each tool its docs section as an exhaustive switch,
so a new tool can't ship undocumented. The release workflow attaches the
partials to each release as lightpanda-docs.tar.gz for the docs repo to
pull.
2026-10-12 22:33:17 +02:00
Karl Seguin 35958d5eaf crash: re-implement __clear_cache on linux arm64 to workaround zig bug
Fixes https://github.com/lightpanda-io/browser/issues/3672

Zig's __clear_cache for ARM64 emits incorrect LLVM. It fails to emit a data
synchronization barrier which causes a stale instruction in the cache line that
SIGILL.
2026-10-08 07:53:07 +08:00
Adrià Arrufat 79e0a111ad Merge branch 'main' into shell-completion
# Conflicts:
#	src/Config.zig
#	src/cli.zig
2026-10-05 12:44:23 +02:00
Adrià Arrufat c3083725c5 Replace deprecated std.mem.indexOf* with find* 2026-10-03 16:09:42 +02:00
Adrià Arrufat 10609b025a Upgrade to Zig 0.17
Dependencies:
- v8: zig-v8-fork 0.17 branch (lightpanda-io/zig-v8-fork#218).
- sqlite3: build the amalgamation directly; the allyourcodebase wrapper
  has no 0.17 support yet.
- pcre2: master commit with 0.17 support (no release yet).
- translate_c package (2.0.0) replaces the deprecated addTranslateC.
  default_init is set to keep 0.16's zero-initialized struct fields.

Build:
- b.pathFromRoot/build_root/args/sysroot are gone: resolve paths from
  b.root, use addPassthruArgs, declare configure-time file and directory
  dependencies, and poison the configure cache for the git version.
- Drop curl config values the template never used (now an error).
- Drop the 0.16 zip-fetch workaround from the Makefile and CI.
- -Doptimize=ReleaseFast -> -Doptimize=fast.

Language and std:
- @intFromEnum/@enumFromInt -> @backingInt/@fromBackingInt.
- Struct-of-arrays @typeInfo (field_names, field_types, decl_names,
  param_types, error_names).
- `a ** n` removed: @splat for arrays, string.repeat for strings.
- errdefer captures removed: split WebDriver.run and fulfillRedirect.
- @hasDecl only sees pub decls: make StyleManager's Spec.finish pub,
  otherwise it silently stops running.
- SafeAllocator replaces DebugAllocator; the test runner now has to
  initialize std.testing.allocator_instance itself.
- std.fmt.allocPrint/bufPrint -> Allocator.print/std.mem.print,
  dupeZ -> dupeSentinel, std.builtin -> std.lang, builtin.os ->
  builtin.target.os, zon.parse arena API, BufferFirstAllocator, and the
  remaining renames (getLastOrNull, bit_set, ascii.find*, meta.Int).
2026-10-03 16:09:42 +02:00
Karl Seguin 64dbff13c5 ops: attempt to generate an appropriate error on a bot challenge
If you goto https://www.tortoiseandladygrey.com with --obey-robots, you'll get:

```
ERROR frame : navigate failed . . . . . . . . . . . . . . . .  [+47ms]
      err = RobotsBlocked
      type = root
      url = https://www.tortoiseandladygrey.com/

```

But what's actually happening is that the robots.txt is being protected by a
bot check (cloudflare). This commit doesn't change any behavior. All it does
is try to generate a better error message. The above instead fails with:

```
WARN  http : robots.txt bot challenge . . . . . . . . . . . .  [+41ms]
      url = https://www.tortoiseandladygrey.com/robots.txt
      status = 403
      provider = cloudflare

ERROR app : page failed . . . . . . . . . . . . . . . . . . .  [+41ms]
      url = https://www.tortoiseandladygrey.com
      err = BotChallenge
```
2026-10-01 15:54:07 +08:00
Adrià Arrufat d2296393af Merge branch 'main' into shell-completion
# Conflicts:
#	src/cli.zig
2026-09-28 10:45:10 +02:00
Karl Seguin 4caaa27411 mem: Set M_MMAP_THRESHOLD to 128K on linux builds
Following some experimentation, this sets M_MMAP_THRESHOLD to 128K on linux
builds IF it isn't explicit set, e.g. via the `MALLOC_MMAP_THRESHOLD_` env. This
allows users explicitly set it if they want.

I've been looking at this for a while, but my understanding is still basic. The
simplistic explanation is that glibc's allocator internally uses arenas.
Allocations above THRESHOLD skip these arenas and are allocated directly from
and freed directly to the OS. Allocations under this threshold are released
to the arena where they can be re-used. Everything works OK, EXCEPT for when it
comes time to release the memory from these arenas back to the OS. If free arena
memory is pinned under live memory, it cannot be released.

Various online posts / comments reference glibc as suffering from significant
fragmentation and "holding" onto memory. That's the behavior that we've seen.
Further, calls to malloc_trim reclaim the lost memory, so what we're seeing
aren't leaks.
2026-09-28 14:02:39 +08:00
Adrià Arrufat d26e1e2f55 Add shell completion for bash, fish and zsh
`lightpanda completion <bash | fish | zsh>` prints a completion script
for commands, flags and their values. The scripts are generated from
the command recipe, so a new flag is completed without extra work:
enum options offer their tags, packed-struct options their fields,
and options marked `.path = true` offer files. Descriptions are the
first sentence of each flag's help.zon entry.

To support it, the cli builder gains enum positionals and a per-command
flag list that both completion and the "did you mean" suggestions use.
Deprecated flags are no longer suggested.
2026-09-26 23:02:42 +02:00
Adrià Arrufat a160b8d552 SemanticTree: resolve the owner frame once in init
Every caller resolved node.ownerFrame(frame) before building a
SemanticTree or calling getNodeDetails, and every one made the same
decision on a frameless node. Move that into SemanticTree.init, which
returns error.FramelessNode, and turn getNodeDetails into a method so
it goes through the same constructor.

With init as the only entry point the per-method assertOwns is
redundant, so drop it along with its copy of StyleManager's helper.
2026-09-17 11:59:01 +02:00
Karl Seguin afbc8378b1 Merge pull request #3522 from lightpanda-io/regex-shared
`Regex`: share the PCRE2 wrapper; `findElement` matches names by `/regex/`
2026-09-16 16:55:40 +08:00
Adrià Arrufat d2f72a9fa9 Regex: share the PCRE2 wrapper beyond adblock
Compiled patterns are useful anywhere someone else writes the pattern:
the adblock lists today, agent tool arguments next. The wrapper moves
out of the adblock directory and gains an options struct (case, UTF-8
subjects) and a compile diagnostic the caller can log or show. The App
owns the one context every consumer compiles through, the blocker
included.
2026-09-15 09:33:39 +02:00
Karl Seguin 48dc72cd49 webapi: better frame integrity
Follow up to  https://github.com/lightpanda-io/browser/pull/3510

Moves the element/node lookups, e.g. `element_class_lists` from Frame to Page.
Elements and nodes can outlive a Frame (it's the reason the identity map lives
on the Page, not the frame). These maps are merely properties on Node/Elements
optimized for a specific usage-pattern (i.e. most Node/Elements don't have these
or they are never materialized from JS). So if a Node/Element can outlive the
Frame, than so too can all of their properties. And, even when an frame is alive
the properties belong to the *Node* or *Element*, NOT the Frame...accessing
those properties across frames should yield the same value / identity.

More mechanically, frame._page => frame.page and all of these lookups lose their
_ prefix. Short summary of _ prefix is:

1 - It's used to deal with Zig not allowing shadowing. This is particularly true
    in the WebApis were it happens a bit more often

2 - Early prototype was built as a stand-alone library, and the _ was used to
    signal "private" (again, working around Zig). Frame.page shouldn't be
    "private" and neither should these lookups (if we aren't going to provide
    getter/setters for them).
2026-09-15 11:26:04 +08:00
Karl Seguin e8f6591411 address feedback
remove --strip-mode full   (and all `full` support from cli, because it makes
backwards-compatibility a pain)
2026-09-11 06:36:49 +08:00
Karl Seguin 5bc4f7482c render: add "clutter" option to --strip-mode
Adds a `clutter` option to --strip-mode. This is based on readability.js. It
isn't a direct port (e.g. it doesn't strop bylines). It fallsback to `shell` if
it strips too much (and shell itself can fallback to not stripping anything).
But clutter rarely fallback to shell, only when a page is very small or when
it strips out _a lot_.

Also expanded shell to look at class names and ids.
2026-09-11 06:36:48 +08:00
Karl Seguin cdceca37c3 render: add "shell" option to --strip-mode
Some additional API changes:
- Add strip-mode support to pdf/png generation.
- Add LP.dump which provides greater content gathering capability to CDP,
  exposing most `fetch` dump-related parameters (e.g. format, strip, selector,
  ...)

The new "--strip-mode shell" is designed to try to remove non-content elements
such as the header and footer. The end goal is to use readibility.js test cases
as a baseline, but this isn't a port of readibility.js.

This is just the basic implementation of this, e.g removing a few key tags, e.g.
<header>, <footer> and considering some specific roles.

Even if --strip-mode shell is used, we might decide to stick with a whole dump:
it's better to strip not enough than to strip too much. This currently works by
measuring the ratio of non-link text of the stripped vs unstripped page.
2026-09-11 06:35:26 +08:00
Karl Seguin 2e6999f20b chore: make declarations private if they don't need to be public
This change is 99%  s/pub//   + a handful of dead code removal.
2026-09-10 14:42:09 +08:00
Karl Seguin 3061930153 chore: refactor Execution and GlobalScope
The js.Execution is the API behind the Frame/WGS split, but the split is
actually held by the underlying js.GlobalScope. Most Execution methods are:

```zig
    return switch (self.js.global) {
        inline else => |g| g.isSameOrigin(url),
    };
```

And that works well, except that in some cases, code has a js.Context, not an
js.Execution, and they need to do the same inline switch.

This commit moves GlobalScope from src/browser/js to src/browser (there's
nothing JS/v8 about it), and moves all those inline switches into it. The
js.Execution API stays the same (it forwards the call to js.global)
but all callers that directly inlined switched the js.global no longer do.
2026-09-08 17:46:11 +08:00
Karl Seguin 7c51dfff05 bidi: add skeleton for bidi
1. Abstract "Driver". Non-CDP things that referenced *CDP now reference a Driver
2. Move the NodeRegistry out of CDP. This created an artificial link between
   agent / mcp and CDP
3. Add BiDi driver with enough to navigate to a page
2026-08-31 22:44:59 +08:00
Karl Seguin eded004450 Merge pull request #3312 from lightpanda-io/tool-session
mcp: fold Server.Session onto lp.ToolSession, bracket every isolate use
2026-08-29 07:02:32 +08:00
Adrià Arrufat f1bdd0019f Merge branch 'main' into tool-session 2026-08-28 15:14:56 +02:00
Karl Seguin 67927b9bde Add PDF support
adds --dump screen.pdf and CDP's Page.printToPDF (along with IO.read and
IO.read). Builds ontop of https://github.com/lightpanda-io/browser/pull/3231

This generates a text-based PDF, not just our PNG placed into a PDF. The biggest
change to the existing (isolated) code was adding href information so that links
are actually clickable.

Like 3231 the hard parts are all Claude but isolated. The one place it diverged
from the plan was NOT using the subsetter rust crate for trimming the size of
the embedded font. It felt that the dependencies were too much (e.g. a second
version of skrifa, ...). One subsetter was removed, the pdf rendering, while
still a blackbox, was moved from Rust to Zig (pdf.zig), which is kind of nice.
2026-08-28 12:53:36 +08:00
Adrià Arrufat 071eca1f3f mcp: fold Server.Session onto lp.ToolSession
Extract the Browser+Session+Notification+node Registry quartet, with its
ordering-sensitive init/teardown and isolate enter/exit, into
src/ToolSession.zig. mcp/Server.zig's sessions map now holds
*lp.ToolSession directly; the session id lives only as the map key.

Claude-Session: https://claude.ai/code/session_01M6WGk8wZSE28efFQkYT9SK
2026-08-27 16:27:27 +02:00
Adrià Arrufat 193f15558c tools: declare image support at the call site, not in each consumer
Callers pass CallOpts.inline_image; execScreenshot rejects a path-less
call before navigating or rendering, which removes the per-consumer
guards and covers the model-driven tool path that had none. MCP image
content is a protocol type, the screenshot recording rule joins the
recorder's replayRequires predicate, and the viewport-to-Opts mapping,
node-scope ladder and save-path helpers are shared instead of copied.
2026-08-27 15:03:19 +02:00
Karl Seguin 05627c5368 handle error in json+png error
improve log error message when 1 of multiple URLs fails to fetch
2026-08-27 08:11:15 +08:00
Adrià Arrufat 56241e26b8 dump: take max_bytes in Opts
Review feedback: markdown caps its own output through Opts.max_bytes while
the html dump left it to each caller, so the html tool and fetch each
carried a copy of the LimitedWriter wrapping. root and deep now do it,
with a no-cap fast path so innerHTML/outerHTML are unaffected.
2026-08-26 15:44:48 +02:00
Adrià Arrufat 6811cc8226 fetch: per-page errors, an "error" field in --json, --fail-on-http-error
A wait failure on one URL aborted the whole multi-URL fetch with no
output, the wait_ms budget was computed once before the loop so N pages
could take N times the budget, navigation failures exited 0 with an empty
dump, and HTTP 4xx/5xx were indistinguishable from success by exit code.

Each page now has its own error slot: wait, navigation and dump failures
are recorded there instead of returned, every page is still written (the
JSON envelope carries the name under "error"), then the first failure is
returned so the process exits 1. The remaining budget is recomputed per
page. --fail-on-http-error turns a status >= 400 into exit 22, curl's
code for the same condition; the dump is written first either way.
2026-08-26 15:35:15 +02:00
Adrià Arrufat d3bad960c3 fetch: add --selector and --max-bytes, honor --strip-mode for markdown
--strip-mode was silently ignored for --dump markdown, and fetch had no
way to scope a dump to one element or cap its size although the markdown
and html tools have both.

--selector dumps the first matching element in any dump mode, --max-bytes
caps html and markdown with the tools' truncation marker, and markdown
now honors strip ui (images; scripts, styles and hidden elements are
never rendered, so the other groups don't apply).
2026-08-26 13:23:18 +02:00
Karl Seguin 289502e19a Merge pull request #3231 from lightpanda-io/screenshot
Screenshot
2026-08-25 18:12:00 +08:00