跳到正文
FunCoding

browser4-coding

Create and validate Browser4 plugins, skills, JS scripts, and shell scripts; and develop Browser4 ITSELF (self-development): build modules, extract live skeletons, analyze impact, plan dev tasks, and check CDP pitfalls. Use when the user asks to write a Browser4 plugin or skill, write browser JS or build scripts, modify Browser4's own Kotlin/Rust code, or validate repo consistency.

Star
1,192
许可证
Apache-2.0
最近提交
2026年12月1日

skills/browser4-coding/SKILL.md

在 GitHub 上查看

browser4-coding

Quick Start

Create and validate a plugin, or a skill:

coding.scaffold(type="plugin", pluginName="My Plugin", domain="media",
                basePackage="ai.platon.pulsar.myplugin",
                toolMethod="detectMedia", toolDescription="Detect media on the page")
coding.validate(type="plugin", path="browser4-plugins/browser4-myplugin")

coding.scaffold(type="skill", name="my-skill", description="What it does")
coding.validate(type="skill", path="skills/my-skill/SKILL.md")

For self-development work (modifying Browser4 itself), start with coding.scaffoldFlow — see Workflows below.

The programming-agent kernel for Browser4: sandboxed shell + filesystem, artifact scaffolding/validation (plugins, skills, browser JS, scripts), and a full self-development toolset for modifying Browser4's own code (live module graph, impact analysis, Maven builds with structured diagnostics, CDP pitfall awareness, high-level dev-task planning).

When to Use

  • User wants to create a new Browser4 plugin, skill (SKILL.md), browser JS script, or build/deploy/run script
  • User wants to validate any of the above
  • User wants to modify Browser4's own code (Kotlin modules, Rust CLI, poms) — use the self-development tools below
  • User wants to check repo governance (versions, module registration) or the CDP pitfalls before editing the browser driver

How It Works

The coding tools fall into three layers: artifact tools generate and validate plugins, skills, JS, and scripts (templates from real code so they never go stale); self-development tools inspect and modify Browser4 itself (live module graph, impact analysis, Maven builds, CDP trap checks); and shell/filesystem tools provide a sandboxed environment for anything else.

Patterns

1. Create and validate a new plugin

coding.scaffold(type="plugin", pluginName="...", domain="...", basePackage="...", toolMethod="...", toolDescription="...")
coding.validate(type="plugin", path="browser4-plugins/browser4-xxx")
coding.mvnBuild(module="browser4-plugins/browser4-xxx")

2. Copy an existing plugin's structure

coding.scaffoldFromExample(path="browser4-plugins/browser4-seo")
coding.validate(type="plugin", path="browser4-plugins/browser4-xxx")

3. Repo governance check before merging

coding.validate(type="repo-consistency")

Flags

coding is a tool set, not a CLI — there are no command-line flags. Tool parameters are documented per tool in the sections below.

Errors & Recovery

SymptomCauseFix
coding.validate failsMissing/incorrect required parametersRead the validation output and fix the named field
coding.mvnBuild failsCompile errors in generated codeRead the structured diagnostics and fix the faulty file
scaffoldFromExample renames wrong classesAmbiguous class stemPass explicit per-class keys (e.g. SeoService=CustomService)

Artifact Tools (plugins / skills / js / scripts)

coding.scaffold

Generate a template for any of the four artifact types.

TypeRequired ParametersOptional Parameters
pluginpluginName, domain, basePackage, toolMethod, toolDescriptionpdkVersion (defaults to the repo VERSION file)
skillname (must equal directory name), description (1-1024 chars)triggers (comma-separated), tools (comma-separated → allowed-tools)
jsnamepurpose (extract, inject, interact)
scriptnamescriptType (build, deploy, run), shell (ps1, bash)

coding.validate

Validate an artifact — or the whole repo (type="repo-consistency", no path).

TypePath MeaningWhat It Checks
pluginPlugin base directorypom.xml (parent browser4-pdk, literal version, required deps), plugin.json (PluginManifest schema), AutoConfiguration implements ToolMount, ToolExecutor structure, manifest.name == artifactId
skillSKILL.md file pathYAML frontmatter name + description (1-1024), name == directory name, allowed-tools, tool-reference cross-check
js.js file pathBracket balance, return statement, use strict, anti-patterns
script.ps1/.sh file pathparam block, shebang, error handling
repo-consistency(none)VERSION format; VERSION == root pom == BOM version; every default <module> dir exists; on-disk module dirs registered in the root pom

coding.scaffoldFromExample — anti-staleness live templates

Generate a skeleton from EXISTING real code instead of hand-written templates (which go stale):

  • Single file: parameterizes basePackage/className/domain/toolMethod into {placeholders}; omit rename args to see discovered parameters.
  • Directory (plugin/module): extracts a MULTI-FILE skeleton set with cross-file-consistent renames — basePackage = common package prefix (per-file .tools/.config suffixes preserved), artifactId from pom.xml (parent BOM excluded), pluginName from plugin.json. Renaming className (or passing stem=<NewStem>) derives sibling classes sharing the detected class stem (Seo → Weather renames SeoToolExecutor and SeoAutoConfiguration/SeoService/SeoConfig). Explicit per-class keys (SeoService=CustomService) always win.

coding.scaffoldFlow — multi-file dev-flow skeletons

type: b4-cli-command (commands.rs CommandDef + MCPToolController alias + backend + test), agent-tool (ToolExecutor + ToolMount auto-config), rest-endpoint (Controller + Service + test), test-class, skill. All identifiers derive from one name; verify=true runs the type-appropriate build check.

Self-Development Tools (modifying Browser4 itself)

coding.moduleGraph — live module graph

Scans the repo's real pom.xml files (module path, artifactId, parent, internal deps) and reports the graph; warns when it drifted from the static snapshot (e.g. browser4-pdk, plugins, test modules). module=<path> reports transitive dependents + suggested test commands. This is the anti-staleness answer to a hand-maintained module map.

coding.impact(path=...)

Which module owns a file, which modules are affected transitively (from the LIVE pom graph), and suggested test commands. Run before modifying Browser4's own code.

coding.verify(module=..., checks=..., runTests=..., files=..., json=...) — the completion authority

Runs the deterministic verification gate and returns a structured verdict: {passed, checks:[{name, ran, ok, exitCode, durationMs, evidence, diagnostics}]}. Checks: compile (mvn -pl <module> -am compile, or cargo check for browser4-cli), test (mvn test, scoped by testClasses), repo-consistency (coding.validate internals), trapCheck (files=). Default checks: compile + repo-consistency (+ trapCheck when files are given). A check that did not RUN is never green — an unresolved module or a skipped required check fails the verdict. The human summary ends with a machine-readable VERDICT_JSON: {...} line; json=true returns pure JSON. Use this (not your own narrative) when claiming a task is done: the finish gate rejects a success claim whose gates were not actually run. From the CLI: browser4-cli code verify --module <module> [--checks ...] [--run-tests] [--json], which exits non-zero when the verdict fails. The whole browser4-cli code … family is deliberately hidden (it does not appear in browser4-cli help and is absent from the browser4-cli skill) — this file is its documentation, and a CLI unit test (code_family_stays_hidden) locks the hidden state in.

coding.mvnBuild(module=..., goals=...)

mvn -pl <module> -am <goals> with structured Kotlin/Java compiler diagnostics instead of raw logs — the fast, dependency-free alternative to a Kotlin LSP server. Use to check code after edits (goals default compile, skipTests=true). Diagnostics keep the workspace-relative path plus line/column. json=true returns {module, goals, exitCode, success, timedOut, diagnostics} instead of the human summary.

coding.ktSymbols / coding.ktReferences / coding.ktInheritance

Zero-dependency Kotlin analysis: symbols (classes/functions/properties), references (scope='file' default, or scope='module' for a cross-file scan that excludes the declaring file), and the inheritance chain (ktInheritance(path, className?) walks the primary supertype across the module's files). Use before refactoring to assess impact without starting a JDTLS server.

coding.devTask(task=..., verify=..., runTests=...)

High-level entry: parse a natural-language dev task into an executable plan following the AGENTS.md flow — locate files → impact → implement (agent contract) → mvnBuild compile → smallest-scope tests → trapCheck (driver code) → repo-consistency → coding.verify. The plan ends with an Acceptance: [...] checklist; the coding.implement step is a contract for an agent (it is printed, never dispatched), and coding.verify is the deterministic gate that decides completion. Bare filenames (Browser4WebDriver.kt) resolve against the workspace to their owning module; module mentions resolve against the LIVE pom graph when available; aggregator modules are not counted as signals. verify=true runs the gate (compile + repo-consistency + trapCheck + tests when runTests=true, scoped to -Dtest=<FooTest> when the task names a test class). module= overrides the inferred module. The test binding (DevPlan.testTarget) is the module that owns the named class — one value feeds the test step, the Acceptance: line and the verify(testModule=…) call, so editing a driver file while adding the test elsewhere cannot point -Dtest= at the wrong module; a filter that matches no test is a failing verdict (ran=true, ok=false), never a green one.

coding.trapCheck(path=...)

Scan a file for the three known Browser4 CDP pitfalls (AGENTS.md): mouseWheel race (crbug.com/444929150), cursor positioning after focus+click, Input.insertText racing. Run before editing browser-driver code (PulsarWebDriver.kt and friends).

coding.protect(path=..., on=...)

Session-level dynamic file protection: coding.protect(path="src/Foo.kt", on=true) blocks delete/replace/editLines/insertAfter on that exact file; on=false removes it; coding.protect() lists dynamic protections. Repo-governance defaults (VERSION/AGENTS.md/CLAUDE.md/root pom/BOM/CI) are always protected and cannot be unprotected.

Permissions (access presets)

A run's coding.* surface is decided by one access preset — the single source of truth consumed by the file system, the shell, the tool registry and the MCP direct-call path:

PresetReadWrite filesmvnBuild/verify/validateshell* / runCode
full (default)✓✓✓✓
write✓✓✓✗
read-build✓✗✓✗
read✓✗✗✗
  • Server default: -Dbrowser4.agent.access=<preset> (unknown values log and fall back to full).
  • Per task: browser4-cli agent run "<task>" --coding --access <preset>; the preset is applied inside the task's lock and reset when the task ends, so tasks never inherit each other's grants.
  • Operator approval: a refused effect is not a dead end. coding.requestAccess(effect="fs.write", target="src/Foo.kt", reason="…") returns immediately with a pending request (it never blocks the task), the task keeps working with what the preset grants, and an operator approves it through POST /api/agent/<taskId>/access/<requestId>/approve. The same effect + target is deduplicated; a grant is effect-level at the method gate and target-scoped where the target is known (the file system refuses a sibling path, the shell an unapproved program, runCode an uncovered interpreter), and it lazily expires. denyTools, protected directories/files, credential paths, the workspace boundary and the shell whitelist are never approved — they are rails, not capabilities. Each step is audited REQUESTED/APPROVED/DENIED/EXPIRED with its source.
  • Strategy file: an unattended job can pre-approve grants with <workspace>/.browser4/access-policy.json — {"grants": [{"effect": "fs.write", "target": "src/generated", "ttlSeconds": 3600, "reason": "…"}]}. It is loaded once when the task starts; target is a command line for fs.exec/proc.spawn, a host for net.connect, otherwise a workspace-relative path. Each entry goes through the same rails and audit as an operator approval (source file), so a protected or out-of-workspace entry is denied, never silently honored. .browser4 is a protected directory, so the job cannot rewrite the file itself.
  • Unattended default: a job nobody watches (no TTY: scripts, CI, submitted tasks) derives full with outbound network allowed instead of the server-wide preset, audited once as ACCESS_APPROVED(source=default); -Dbrowser4.agent.access.unattended=<preset|deny> narrows it. A watched agent run -i on a TTY keeps browser4.agent.access.
  • coding.permissions() reports the active preset, the workspace, what is allowed, every denied method, the pending requests, the operator grants in force and the current protections. Call it after a refusal instead of retrying the same call with different syntax.
  • A refused call is a failed step, not a failed task, and its text is machine-readable: PERMISSION_DENIED | code=… | tool=… | detail=… | hint=… (TOOL_DENIED, READ_ONLY, EXEC_DISABLED, COMMAND_NOT_ALLOWED, PROTECTED_PATH, SENSITIVE_PATH, PATH_OUTSIDE_WORKSPACE, COMMAND_PATH_DENIED).
  • There is no syntax gate. On Windows a single-line if is parsed — if [not] exist <path> <cmd>, if [/i] [not] <a>==<b> <cmd>, if [not] defined <var> <cmd>, if [not] errorlevel <n> <cmd>, optionally wrapped as (<cmd>) with one else (<cmd>) — and the command behind the condition is validated exactly like a top-level one, so if exist x (del y) is refused as a destructive command, not as a grammar limit. A shape the checker cannot decompose — for loops, else if, nested blocks, &/| inside a block, goto/call payloads — is handed to the platform shell verbatim, in every mode, and the shell reports its own parse error; there is no UNSUPPORTED_SYNTAX refusal and nothing to count. The vetoes that do not need the decomposition still refuse: blocked patterns, the command tier, credential and protected paths, and the runtime vetoes (killing or rebuilding this backend, mklink/ln/mount) — their hint= says no approval lifts this instead of offering a request. Use a script file run by path (.\run.cmd, ./run.sh) when the shell's own parse error gets in the way; a bare filename is read as a program name and refused. Windows builtins supported inline: set (bare or NAME=value), mkdir/md, echo (echo. is normalized).

Relations that hold regardless of preset:

  • read-build/read refuse file mutation at the file-system layer too (write, append, replace, replaceRegex, editLines, insertAfter, revert, delete, mkdir, copy, move) and refuse the mutating coding.protect(path, on) form; the listing form still works.
  • .browser4 (the agent's own snapshots/checkpoints/worktrees) and .github/workflows are protected as whole subtrees; VERSION, AGENTS.md, CLAUDE.md, the root pom.xml, the BOM and .github/workflows/ci.yml are protected files. The file tools refuse to write them and the shell refuses any command that names them — including a redirection target (echo x > .browser4/…) and a protected workingDir — so coding.shell is not a way around the guard. A write through a link inside the workspace is judged by the link's real path.
  • ~/.ssh, ~/.aws, ~/.gnupg, ~/.config/gcloud and ~/.browser4 are never readable: the file tools refuse them (real-path checked, so a link inside the workspace cannot reach them) and the shell refuses command arguments naming them in every spelling we can expand (~, $VAR, ${VAR}, $env:VAR, %VAR%), including inside a quoted command substitution (echo "$(cat ~/.ssh/id_rsa)"). This check is advisory (fast-fail), not a security boundary: the OS sandbox (browser4.agent.sandbox) is what actually enforces writes. The deprecated -Dbrowser4.agent.shell.pathGuard=off disables only the credential argument check — the protected subtrees stay enforced.
  • The presets bound what the model can spell. They are not an OS sandbox: read-build and above run the repository's own build (Maven plugins, npm scripts), which executes project code.

Shell & Filesystem Tools

  • coding.shell(command, timeoutSeconds?, workingDir?) — execute allowed dev commands (git/cargo/mvn/npm/python/...). The WHOLE command line is validated: every segment split on && || ; | &, every $(...)/backtick substitution, and every inline sh -c "..." / pwsh -Command "..." / cmd /c ... script body is checked for the same vetoes (blocked patterns, deny lists, credentials, protected writes, runtime). Windows launcher names normalize first (mvnw.cmd → mvnw), and a version-pinned interpreter folds onto its family (python3.12 → python3, pip3.13 → pip3, python2.7 → python), so the verdict does not depend on which exact version the host happens to expose on PATH. An inline body is a script, not a command line, so the tier spelling does not judge it in any mode: powershell -Command "Get-Content x" runs as written (a shape the checker cannot decompose is handed to the platform shell verbatim in every mode too — there is no syntax gate); under agent run --unrestricted the command allow-list no longer applies to the command line either. workingDir may be the workspace, a mirrored module, the checkout those mirrors come from, or an --add-dir folder — a toolchain cache (%TEMP%, ~/.m2, the JDK) is not a project directory and is refused.
  • File ops: read, readLines, write, append, replace, replaceRegex, editLines, insertAfter, revert, delete, mkdir, copy, move, stat, diff (myers/patience), checksum
  • Optimistic concurrency: coding.checksum(path) returns sha256:…; pass it as coding.write(path, content, expectedChecksum=…) and a concurrent edit fails loudly instead of being overwritten. Write snapshots are persisted under .browser4/coding-snapshots/, so coding.revert still works after a backend restart.
  • Provisioned agent workspace: a coding-mode agent run (browser4-cli agent run "<task>" --coding — the coding mode is always requested explicitly, never auto-detected) gets the checkout mirrored into its scratch workspace before the first tool call — every <module> of the root pom is junctioned/symlinked and pom.xml/mvnw/mvnw.cmd/.mvn/VERSION/ROOT.md are copied (WorkspaceMirror), so Maven resolves modules from the first try and the agent never has to repair workspace topology itself.
  • Resumable execution: coding.devTask(execute=true) records a checkpoint per step under .browser4/devtask-checkpoints/ and prints its id; after a crash/failure resume it with coding.resumeDevTask(taskId="dt-…") (CLI: browser4-cli code resume <id>) — completed steps are skipped and a failed isolated run continues inside the worktree it kept.
  • Transactional workspace (default, -Dbrowser4.agent.workspace.isolation=worktree): coding.devTask(..., execute=true) runs its steps inside a git worktree under .browser4/worktrees/, merges the change back only when every step succeeded, and otherwise discards the worktree — a failed task leaves the developer's working tree untouched. The run holds the checkout lock (.git/b4-coding.lock, the same one agent run --coding takes), so two dev-tasks — or a dev-task and a coding agent run — never merge into one checkout at the same time; a second one fails immediately naming the holder. A dev-task that is itself running inside an isolated worktree takes no second lock (its outer task owns the checkout).
  • Search: glob, grep (skip excluded dirs), languages
  • Repo governance protection: EVERY write path — write/append/replace/replaceRegex/editLines/insertAfter/copy/move/delete/revert — is BLOCKED for VERSION, AGENTS.md, CLAUDE.md, root pom.xml, browser4-dependencies/pom.xml (BOM), .github/workflows/ci.yml — do not try to work around this; ask the user for explicit intent instead. Add session-level protections with coding.protect(path, on). Writes are atomic (temp file + move) and line-range edits preserve the file's CRLF/LF style.
  • coding.runCode(language, code) — sandboxed snippet execution (kotlin/js/python/bash)
  • LSP: diagnostics(path), symbols(pattern?), references(path, symbol), lspServers — per-language servers (ts/js/py/rs), started on demand, requires the server installed; degrade gracefully when missing
  • coding.tokenStats(reset?) — per-method token usage of coding tool calls so far (calls/errors/input/output tokens, avg/max output); use to audit context-window consumption. coding.estimateTokens(text) — heuristic token count of any text before sending it.

Workflows

Creating a Browser4 Plugin

1. coding.scaffold(type="plugin", pluginName="browser4-xxx", domain="xxx",
     basePackage="ai.platon.pulsar.xxx", toolMethod="doXxx",
     toolDescription="Does xxx on the page")

2. coding.write(path=<file>, content=<from scaffold>) ... write each file

3. coding.validate(type="plugin", path="browser4-plugins/browser4-xxx") → fix issues

4. coding.mvnBuild(module="browser4-plugins/browser4-xxx") → compile to verify

5. If compile fails: coding.read the error file → coding.replace → recompile

Cloning an existing plugin (anti-staleness)

1. coding.scaffoldFromExample(path="browser4-plugins/browser4-seo")
   → Discovery mode: shows basePackage/className/domain/toolMethod/artifactId/stem

2. coding.scaffoldFromExample(path="browser4-plugins/browser4-seo",
     className="WeatherToolExecutor", basePackage="ai.platon.pulsar.weather",
     domain="weather", artifactId="browser4-weather")
   → Multi-file skeleton; sibling classes (WeatherAutoConfiguration/WeatherService)
     follow the stem rename automatically

3. coding.write each generated file → coding.mvnBuild → coding.validate(type="plugin")
1. coding.impact(path=<file>)      → owning module + affected modules + test commands
2. coding.read the file            → understand the code
3. coding.trapCheck(path=<file>)   → CDP pitfalls if browser-driver code
4. Make the edit (coding.replace / coding.editLines / coding.write)
5. coding.mvnBuild(module=<module>) → compile check
6. coding.shell(command=<smallest test scope>) → run tests
7. coding.validate(type="repo-consistency") → governance still consistent
8. coding.moduleGraph() → confirm no module-graph drift

Creating a Skill / JS Script / Build Script

# Skill
1. coding.scaffold(type="skill", name="my-skill", description="...", triggers="...", tools="coding.read,tab.eval")
2. coding.write(path="skills/my-skill/SKILL.md", content=<from scaffold>)  # dir name MUST equal name
3. coding.validate(type="skill", path="skills/my-skill/SKILL.md")

# Browser JS
1. coding.scaffold(type="js", name="extract-prices", purpose="extract")
2. coding.write(path="scripts/extract-prices.js", content=<from scaffold>)
3. coding.validate(type="js", path="scripts/extract-prices.js")
4. tab.eval(expression=<read the JS file>) → tab.console() → iterate

# Build script
1. coding.scaffold(type="script", name="build", scriptType="build", shell="ps1")
2. coding.write(path="build.ps1", content=<from scaffold>)
3. coding.validate(type="script", path="build.ps1") → coding.shell(command="powershell -File build.ps1")

Notes

  • The generated plugin AutoConfiguration implements ToolMount, so PluginManager registers the plugin's tools into CustomToolRegistry automatically.
  • plugin.json follows the real PluginManifest schema (name/version/description/dependsOn/autoConfigurationClasses).
  • The coding module is intentionally independent of pulsar-common; heavy backends (kotlin-compiler-embeddable, LSP servers) are probed at runtime and NEVER downloaded/loaded by default — tools degrade gracefully when unavailable.

相似的 Skill

rea-analysis-optimization

MOmorluto/rea485k近 7 天新增 7,690 个 star

codebase-design

MAmattpocock/skills336k近 7 天新增 4,217 个 star

精选

diagnosing-bugs

诊断困难 bug 和性能回归,用测试或脚本构建反馈循环定位问题。

MAmattpocock/skills336k近 7 天新增 4,217 个 star

setup-ts-deep-modules

MAmattpocock/skills336k近 7 天新增 4,217 个 star

code-review

MAmattpocock/skills336k近 7 天新增 4,217 个 star

implement

MAmattpocock/skills336k近 7 天新增 4,217 个 star