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.
`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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
`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.
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.
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.
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).
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.
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.
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.
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
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.
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
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.
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.
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.
--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).