Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a257ad2c1 | ||
|
|
d97e2016f5 | ||
|
|
6aea316c82 | ||
|
|
c7fa10cb1b | ||
|
|
44c0361fcd | ||
|
|
907ca8c808 | ||
|
|
b304a4188c | ||
|
|
e912f541f2 | ||
|
|
7238b7da4c | ||
|
|
79d8dfe34c | ||
|
|
14ec5b5ffa | ||
|
|
74fda70b67 | ||
|
|
2a397de59f | ||
|
|
bf672ee7f9 | ||
|
|
74910cfef1 | ||
|
|
41830dff71 | ||
|
|
79b05877a8 | ||
|
|
7bd8ce937b | ||
|
|
b455a58aa2 | ||
|
|
b59dc4c82c | ||
|
|
2e38882664 | ||
|
|
bc1e917e87 |
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,356 +0,0 @@
|
||||
---
|
||||
name: skill-creator
|
||||
description: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Skill Creator
|
||||
|
||||
This skill provides guidance for creating effective skills.
|
||||
|
||||
## About Skills
|
||||
|
||||
Skills are modular, self-contained packages that extend Claude's capabilities by providing
|
||||
specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
|
||||
domains or tasks—they transform Claude from a general-purpose agent into a specialized agent
|
||||
equipped with procedural knowledge that no model can fully possess.
|
||||
|
||||
### What Skills Provide
|
||||
|
||||
1. Specialized workflows - Multi-step procedures for specific domains
|
||||
2. Tool integrations - Instructions for working with specific file formats or APIs
|
||||
3. Domain expertise - Company-specific knowledge, schemas, business logic
|
||||
4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
|
||||
|
||||
## Core Principles
|
||||
|
||||
### Concise is Key
|
||||
|
||||
The context window is a public good. Skills share the context window with everything else Claude needs: system prompt, conversation history, other Skills' metadata, and the actual user request.
|
||||
|
||||
**Default assumption: Claude is already very smart.** Only add context Claude doesn't already have. Challenge each piece of information: "Does Claude really need this explanation?" and "Does this paragraph justify its token cost?"
|
||||
|
||||
Prefer concise examples over verbose explanations.
|
||||
|
||||
### Set Appropriate Degrees of Freedom
|
||||
|
||||
Match the level of specificity to the task's fragility and variability:
|
||||
|
||||
**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.
|
||||
|
||||
**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
|
||||
|
||||
**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
|
||||
|
||||
Think of Claude as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
|
||||
|
||||
### Anatomy of a Skill
|
||||
|
||||
Every skill consists of a required SKILL.md file and optional bundled resources:
|
||||
|
||||
```
|
||||
skill-name/
|
||||
├── SKILL.md (required)
|
||||
│ ├── YAML frontmatter metadata (required)
|
||||
│ │ ├── name: (required)
|
||||
│ │ └── description: (required)
|
||||
│ └── Markdown instructions (required)
|
||||
└── Bundled Resources (optional)
|
||||
├── scripts/ - Executable code (Python/Bash/etc.)
|
||||
├── references/ - Documentation intended to be loaded into context as needed
|
||||
└── assets/ - Files used in output (templates, icons, fonts, etc.)
|
||||
```
|
||||
|
||||
#### SKILL.md (required)
|
||||
|
||||
Every SKILL.md consists of:
|
||||
|
||||
- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that Claude reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.
|
||||
- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
|
||||
|
||||
#### Bundled Resources (optional)
|
||||
|
||||
##### Scripts (`scripts/`)
|
||||
|
||||
Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
|
||||
|
||||
- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
|
||||
- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
|
||||
- **Benefits**: Token efficient, deterministic, may be executed without loading into context
|
||||
- **Note**: Scripts may still need to be read by Claude for patching or environment-specific adjustments
|
||||
|
||||
##### References (`references/`)
|
||||
|
||||
Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.
|
||||
|
||||
- **When to include**: For documentation that Claude should reference while working
|
||||
- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
|
||||
- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
|
||||
- **Benefits**: Keeps SKILL.md lean, loaded only when Claude determines it's needed
|
||||
- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
|
||||
- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
|
||||
|
||||
##### Assets (`assets/`)
|
||||
|
||||
Files not intended to be loaded into context, but rather used within the output Claude produces.
|
||||
|
||||
- **When to include**: When the skill needs files that will be used in the final output
|
||||
- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
|
||||
- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
|
||||
- **Benefits**: Separates output resources from documentation, enables Claude to use files without loading them into context
|
||||
|
||||
#### What to Not Include in a Skill
|
||||
|
||||
A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
|
||||
|
||||
- README.md
|
||||
- INSTALLATION_GUIDE.md
|
||||
- QUICK_REFERENCE.md
|
||||
- CHANGELOG.md
|
||||
- etc.
|
||||
|
||||
The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxilary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
|
||||
|
||||
### Progressive Disclosure Design Principle
|
||||
|
||||
Skills use a three-level loading system to manage context efficiently:
|
||||
|
||||
1. **Metadata (name + description)** - Always in context (~100 words)
|
||||
2. **SKILL.md body** - When skill triggers (<5k words)
|
||||
3. **Bundled resources** - As needed by Claude (Unlimited because scripts can be executed without reading into context window)
|
||||
|
||||
#### Progressive Disclosure Patterns
|
||||
|
||||
Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
|
||||
|
||||
**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
|
||||
|
||||
**Pattern 1: High-level guide with references**
|
||||
|
||||
```markdown
|
||||
# PDF Processing
|
||||
|
||||
## Quick start
|
||||
|
||||
Extract text with pdfplumber:
|
||||
[code example]
|
||||
|
||||
## Advanced features
|
||||
|
||||
- **Form filling**: See [FORMS.md](FORMS.md) for complete guide
|
||||
- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
|
||||
- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
|
||||
```
|
||||
|
||||
Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
|
||||
|
||||
**Pattern 2: Domain-specific organization**
|
||||
|
||||
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
|
||||
|
||||
```
|
||||
bigquery-skill/
|
||||
├── SKILL.md (overview and navigation)
|
||||
└── reference/
|
||||
├── finance.md (revenue, billing metrics)
|
||||
├── sales.md (opportunities, pipeline)
|
||||
├── product.md (API usage, features)
|
||||
└── marketing.md (campaigns, attribution)
|
||||
```
|
||||
|
||||
When a user asks about sales metrics, Claude only reads sales.md.
|
||||
|
||||
Similarly, for skills supporting multiple frameworks or variants, organize by variant:
|
||||
|
||||
```
|
||||
cloud-deploy/
|
||||
├── SKILL.md (workflow + provider selection)
|
||||
└── references/
|
||||
├── aws.md (AWS deployment patterns)
|
||||
├── gcp.md (GCP deployment patterns)
|
||||
└── azure.md (Azure deployment patterns)
|
||||
```
|
||||
|
||||
When the user chooses AWS, Claude only reads aws.md.
|
||||
|
||||
**Pattern 3: Conditional details**
|
||||
|
||||
Show basic content, link to advanced content:
|
||||
|
||||
```markdown
|
||||
# DOCX Processing
|
||||
|
||||
## Creating documents
|
||||
|
||||
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
|
||||
|
||||
## Editing documents
|
||||
|
||||
For simple edits, modify the XML directly.
|
||||
|
||||
**For tracked changes**: See [REDLINING.md](REDLINING.md)
|
||||
**For OOXML details**: See [OOXML.md](OOXML.md)
|
||||
```
|
||||
|
||||
Claude reads REDLINING.md or OOXML.md only when the user needs those features.
|
||||
|
||||
**Important guidelines:**
|
||||
|
||||
- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
|
||||
- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so Claude can see the full scope when previewing.
|
||||
|
||||
## Skill Creation Process
|
||||
|
||||
Skill creation involves these steps:
|
||||
|
||||
1. Understand the skill with concrete examples
|
||||
2. Plan reusable skill contents (scripts, references, assets)
|
||||
3. Initialize the skill (run init_skill.py)
|
||||
4. Edit the skill (implement resources and write SKILL.md)
|
||||
5. Package the skill (run package_skill.py)
|
||||
6. Iterate based on real usage
|
||||
|
||||
Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
|
||||
|
||||
### Step 1: Understanding the Skill with Concrete Examples
|
||||
|
||||
Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
|
||||
|
||||
To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
|
||||
|
||||
For example, when building an image-editor skill, relevant questions include:
|
||||
|
||||
- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
|
||||
- "Can you give some examples of how this skill would be used?"
|
||||
- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
|
||||
- "What would a user say that should trigger this skill?"
|
||||
|
||||
To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
|
||||
|
||||
Conclude this step when there is a clear sense of the functionality the skill should support.
|
||||
|
||||
### Step 2: Planning the Reusable Skill Contents
|
||||
|
||||
To turn concrete examples into an effective skill, analyze each example by:
|
||||
|
||||
1. Considering how to execute on the example from scratch
|
||||
2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
|
||||
|
||||
Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
|
||||
|
||||
1. Rotating a PDF requires re-writing the same code each time
|
||||
2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
|
||||
|
||||
Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
|
||||
|
||||
1. Writing a frontend webapp requires the same boilerplate HTML/React each time
|
||||
2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
|
||||
|
||||
Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
|
||||
|
||||
1. Querying BigQuery requires re-discovering the table schemas and relationships each time
|
||||
2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
|
||||
|
||||
To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
|
||||
|
||||
### Step 3: Initializing the Skill
|
||||
|
||||
At this point, it is time to actually create the skill.
|
||||
|
||||
Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
|
||||
|
||||
When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
scripts/init_skill.py <skill-name> --path <output-directory>
|
||||
```
|
||||
|
||||
The script:
|
||||
|
||||
- Creates the skill directory at the specified path
|
||||
- Generates a SKILL.md template with proper frontmatter and TODO placeholders
|
||||
- Creates example resource directories: `scripts/`, `references/`, and `assets/`
|
||||
- Adds example files in each directory that can be customized or deleted
|
||||
|
||||
After initialization, customize or remove the generated SKILL.md and example files as needed.
|
||||
|
||||
### Step 4: Edit the Skill
|
||||
|
||||
When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Claude to use. Include information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.
|
||||
|
||||
#### Learn Proven Design Patterns
|
||||
|
||||
Consult these helpful guides based on your skill's needs:
|
||||
|
||||
- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic
|
||||
- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns
|
||||
|
||||
These files contain established best practices for effective skill design.
|
||||
|
||||
#### Start with Reusable Skill Contents
|
||||
|
||||
To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
|
||||
|
||||
Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
|
||||
|
||||
Any example files and directories not needed for the skill should be deleted. The initialization script creates example files in `scripts/`, `references/`, and `assets/` to demonstrate structure, but most skills won't need all of them.
|
||||
|
||||
#### Update SKILL.md
|
||||
|
||||
**Writing Guidelines:** Always use imperative/infinitive form.
|
||||
|
||||
##### Frontmatter
|
||||
|
||||
Write the YAML frontmatter with `name` and `description`:
|
||||
|
||||
- `name`: The skill name
|
||||
- `description`: This is the primary triggering mechanism for your skill, and helps Claude understand when to use the skill.
|
||||
- Include both what the Skill does and specific triggers/contexts for when to use it.
|
||||
- Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to Claude.
|
||||
- Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
|
||||
|
||||
Do not include any other fields in YAML frontmatter.
|
||||
|
||||
##### Body
|
||||
|
||||
Write instructions for using the skill and its bundled resources.
|
||||
|
||||
### Step 5: Packaging a Skill
|
||||
|
||||
Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
|
||||
|
||||
```bash
|
||||
scripts/package_skill.py <path/to/skill-folder>
|
||||
```
|
||||
|
||||
Optional output directory specification:
|
||||
|
||||
```bash
|
||||
scripts/package_skill.py <path/to/skill-folder> ./dist
|
||||
```
|
||||
|
||||
The packaging script will:
|
||||
|
||||
1. **Validate** the skill automatically, checking:
|
||||
|
||||
- YAML frontmatter format and required fields
|
||||
- Skill naming conventions and directory structure
|
||||
- Description completeness and quality
|
||||
- File organization and resource references
|
||||
|
||||
2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
|
||||
|
||||
If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
|
||||
|
||||
### Step 6: Iterate
|
||||
|
||||
After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
|
||||
|
||||
**Iteration workflow:**
|
||||
|
||||
1. Use the skill on real tasks
|
||||
2. Notice struggles or inefficiencies
|
||||
3. Identify how SKILL.md or bundled resources should be updated
|
||||
4. Implement changes and test again
|
||||
@@ -1,82 +0,0 @@
|
||||
# Output Patterns
|
||||
|
||||
Use these patterns when skills need to produce consistent, high-quality output.
|
||||
|
||||
## Template Pattern
|
||||
|
||||
Provide templates for output format. Match the level of strictness to your needs.
|
||||
|
||||
**For strict requirements (like API responses or data formats):**
|
||||
|
||||
```markdown
|
||||
## Report structure
|
||||
|
||||
ALWAYS use this exact template structure:
|
||||
|
||||
# [Analysis Title]
|
||||
|
||||
## Executive summary
|
||||
[One-paragraph overview of key findings]
|
||||
|
||||
## Key findings
|
||||
- Finding 1 with supporting data
|
||||
- Finding 2 with supporting data
|
||||
- Finding 3 with supporting data
|
||||
|
||||
## Recommendations
|
||||
1. Specific actionable recommendation
|
||||
2. Specific actionable recommendation
|
||||
```
|
||||
|
||||
**For flexible guidance (when adaptation is useful):**
|
||||
|
||||
```markdown
|
||||
## Report structure
|
||||
|
||||
Here is a sensible default format, but use your best judgment:
|
||||
|
||||
# [Analysis Title]
|
||||
|
||||
## Executive summary
|
||||
[Overview]
|
||||
|
||||
## Key findings
|
||||
[Adapt sections based on what you discover]
|
||||
|
||||
## Recommendations
|
||||
[Tailor to the specific context]
|
||||
|
||||
Adjust sections as needed for the specific analysis type.
|
||||
```
|
||||
|
||||
## Examples Pattern
|
||||
|
||||
For skills where output quality depends on seeing examples, provide input/output pairs:
|
||||
|
||||
```markdown
|
||||
## Commit message format
|
||||
|
||||
Generate commit messages following these examples:
|
||||
|
||||
**Example 1:**
|
||||
Input: Added user authentication with JWT tokens
|
||||
Output:
|
||||
```
|
||||
feat(auth): implement JWT-based authentication
|
||||
|
||||
Add login endpoint and token validation middleware
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
Input: Fixed bug where dates displayed incorrectly in reports
|
||||
Output:
|
||||
```
|
||||
fix(reports): correct date formatting in timezone conversion
|
||||
|
||||
Use UTC timestamps consistently across report generation
|
||||
```
|
||||
|
||||
Follow this style: type(scope): brief description, then detailed explanation.
|
||||
```
|
||||
|
||||
Examples help Claude understand the desired style and level of detail more clearly than descriptions alone.
|
||||
@@ -1,28 +0,0 @@
|
||||
# Workflow Patterns
|
||||
|
||||
## Sequential Workflows
|
||||
|
||||
For complex tasks, break operations into clear, sequential steps. It is often helpful to give Claude an overview of the process towards the beginning of SKILL.md:
|
||||
|
||||
```markdown
|
||||
Filling a PDF form involves these steps:
|
||||
|
||||
1. Analyze the form (run analyze_form.py)
|
||||
2. Create field mapping (edit fields.json)
|
||||
3. Validate mapping (run validate_fields.py)
|
||||
4. Fill the form (run fill_form.py)
|
||||
5. Verify output (run verify_output.py)
|
||||
```
|
||||
|
||||
## Conditional Workflows
|
||||
|
||||
For tasks with branching logic, guide Claude through decision points:
|
||||
|
||||
```markdown
|
||||
1. Determine the modification type:
|
||||
**Creating new content?** → Follow "Creation workflow" below
|
||||
**Editing existing content?** → Follow "Editing workflow" below
|
||||
|
||||
2. Creation workflow: [steps]
|
||||
3. Editing workflow: [steps]
|
||||
```
|
||||
@@ -1,303 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Skill Initializer - Creates a new skill from template
|
||||
|
||||
Usage:
|
||||
init_skill.py <skill-name> --path <path>
|
||||
|
||||
Examples:
|
||||
init_skill.py my-new-skill --path skills/public
|
||||
init_skill.py my-api-helper --path skills/private
|
||||
init_skill.py custom-skill --path /custom/location
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SKILL_TEMPLATE = """---
|
||||
name: {skill_name}
|
||||
description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
|
||||
---
|
||||
|
||||
# {skill_title}
|
||||
|
||||
## Overview
|
||||
|
||||
[TODO: 1-2 sentences explaining what this skill enables]
|
||||
|
||||
## Structuring This Skill
|
||||
|
||||
[TODO: Choose the structure that best fits this skill's purpose. Common patterns:
|
||||
|
||||
**1. Workflow-Based** (best for sequential processes)
|
||||
- Works well when there are clear step-by-step procedures
|
||||
- Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing"
|
||||
- Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2...
|
||||
|
||||
**2. Task-Based** (best for tool collections)
|
||||
- Works well when the skill offers different operations/capabilities
|
||||
- Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text"
|
||||
- Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2...
|
||||
|
||||
**3. Reference/Guidelines** (best for standards or specifications)
|
||||
- Works well for brand guidelines, coding standards, or requirements
|
||||
- Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features"
|
||||
- Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage...
|
||||
|
||||
**4. Capabilities-Based** (best for integrated systems)
|
||||
- Works well when the skill provides multiple interrelated features
|
||||
- Example: Product Management with "Core Capabilities" → numbered capability list
|
||||
- Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature...
|
||||
|
||||
Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).
|
||||
|
||||
Delete this entire "Structuring This Skill" section when done - it's just guidance.]
|
||||
|
||||
## [TODO: Replace with the first main section based on chosen structure]
|
||||
|
||||
[TODO: Add content here. See examples in existing skills:
|
||||
- Code samples for technical skills
|
||||
- Decision trees for complex workflows
|
||||
- Concrete examples with realistic user requests
|
||||
- References to scripts/templates/references as needed]
|
||||
|
||||
## Resources
|
||||
|
||||
This skill includes example resource directories that demonstrate how to organize different types of bundled resources:
|
||||
|
||||
### scripts/
|
||||
Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.
|
||||
|
||||
**Examples from other skills:**
|
||||
- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation
|
||||
- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing
|
||||
|
||||
**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.
|
||||
|
||||
**Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments.
|
||||
|
||||
### references/
|
||||
Documentation and reference material intended to be loaded into context to inform Claude's process and thinking.
|
||||
|
||||
**Examples from other skills:**
|
||||
- Product management: `communication.md`, `context_building.md` - detailed workflow guides
|
||||
- BigQuery: API reference documentation and query examples
|
||||
- Finance: Schema documentation, company policies
|
||||
|
||||
**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working.
|
||||
|
||||
### assets/
|
||||
Files not intended to be loaded into context, but rather used within the output Claude produces.
|
||||
|
||||
**Examples from other skills:**
|
||||
- Brand styling: PowerPoint template files (.pptx), logo files
|
||||
- Frontend builder: HTML/React boilerplate project directories
|
||||
- Typography: Font files (.ttf, .woff2)
|
||||
|
||||
**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.
|
||||
|
||||
---
|
||||
|
||||
**Any unneeded directories can be deleted.** Not every skill requires all three types of resources.
|
||||
"""
|
||||
|
||||
EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
|
||||
"""
|
||||
Example helper script for {skill_name}
|
||||
|
||||
This is a placeholder script that can be executed directly.
|
||||
Replace with actual implementation or delete if not needed.
|
||||
|
||||
Example real scripts from other skills:
|
||||
- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
|
||||
- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
|
||||
"""
|
||||
|
||||
def main():
|
||||
print("This is an example script for {skill_name}")
|
||||
# TODO: Add actual script logic here
|
||||
# This could be data processing, file conversion, API calls, etc.
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
'''
|
||||
|
||||
EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}
|
||||
|
||||
This is a placeholder for detailed reference documentation.
|
||||
Replace with actual reference content or delete if not needed.
|
||||
|
||||
Example real reference docs from other skills:
|
||||
- product-management/references/communication.md - Comprehensive guide for status updates
|
||||
- product-management/references/context_building.md - Deep-dive on gathering context
|
||||
- bigquery/references/ - API references and query examples
|
||||
|
||||
## When Reference Docs Are Useful
|
||||
|
||||
Reference docs are ideal for:
|
||||
- Comprehensive API documentation
|
||||
- Detailed workflow guides
|
||||
- Complex multi-step processes
|
||||
- Information too lengthy for main SKILL.md
|
||||
- Content that's only needed for specific use cases
|
||||
|
||||
## Structure Suggestions
|
||||
|
||||
### API Reference Example
|
||||
- Overview
|
||||
- Authentication
|
||||
- Endpoints with examples
|
||||
- Error codes
|
||||
- Rate limits
|
||||
|
||||
### Workflow Guide Example
|
||||
- Prerequisites
|
||||
- Step-by-step instructions
|
||||
- Common patterns
|
||||
- Troubleshooting
|
||||
- Best practices
|
||||
"""
|
||||
|
||||
EXAMPLE_ASSET = """# Example Asset File
|
||||
|
||||
This placeholder represents where asset files would be stored.
|
||||
Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
|
||||
|
||||
Asset files are NOT intended to be loaded into context, but rather used within
|
||||
the output Claude produces.
|
||||
|
||||
Example asset files from other skills:
|
||||
- Brand guidelines: logo.png, slides_template.pptx
|
||||
- Frontend builder: hello-world/ directory with HTML/React boilerplate
|
||||
- Typography: custom-font.ttf, font-family.woff2
|
||||
- Data: sample_data.csv, test_dataset.json
|
||||
|
||||
## Common Asset Types
|
||||
|
||||
- Templates: .pptx, .docx, boilerplate directories
|
||||
- Images: .png, .jpg, .svg, .gif
|
||||
- Fonts: .ttf, .otf, .woff, .woff2
|
||||
- Boilerplate code: Project directories, starter files
|
||||
- Icons: .ico, .svg
|
||||
- Data files: .csv, .json, .xml, .yaml
|
||||
|
||||
Note: This is a text placeholder. Actual assets can be any file type.
|
||||
"""
|
||||
|
||||
|
||||
def title_case_skill_name(skill_name):
|
||||
"""Convert hyphenated skill name to Title Case for display."""
|
||||
return ' '.join(word.capitalize() for word in skill_name.split('-'))
|
||||
|
||||
|
||||
def init_skill(skill_name, path):
|
||||
"""
|
||||
Initialize a new skill directory with template SKILL.md.
|
||||
|
||||
Args:
|
||||
skill_name: Name of the skill
|
||||
path: Path where the skill directory should be created
|
||||
|
||||
Returns:
|
||||
Path to created skill directory, or None if error
|
||||
"""
|
||||
# Determine skill directory path
|
||||
skill_dir = Path(path).resolve() / skill_name
|
||||
|
||||
# Check if directory already exists
|
||||
if skill_dir.exists():
|
||||
print(f"[x] Error: Skill directory already exists: {skill_dir}")
|
||||
return None
|
||||
|
||||
# Create skill directory
|
||||
try:
|
||||
skill_dir.mkdir(parents=True, exist_ok=False)
|
||||
print(f"[OK] Created skill directory: {skill_dir}")
|
||||
except Exception as e:
|
||||
print(f"[x] Error creating directory: {e}")
|
||||
return None
|
||||
|
||||
# Create SKILL.md from template
|
||||
skill_title = title_case_skill_name(skill_name)
|
||||
skill_content = SKILL_TEMPLATE.format(
|
||||
skill_name=skill_name,
|
||||
skill_title=skill_title
|
||||
)
|
||||
|
||||
skill_md_path = skill_dir / 'SKILL.md'
|
||||
try:
|
||||
skill_md_path.write_text(skill_content)
|
||||
print("[OK] Created SKILL.md")
|
||||
except Exception as e:
|
||||
print(f"[x] Error creating SKILL.md: {e}")
|
||||
return None
|
||||
|
||||
# Create resource directories with example files
|
||||
try:
|
||||
# Create scripts/ directory with example script
|
||||
scripts_dir = skill_dir / 'scripts'
|
||||
scripts_dir.mkdir(exist_ok=True)
|
||||
example_script = scripts_dir / 'example.py'
|
||||
example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
|
||||
example_script.chmod(0o755)
|
||||
print("[OK] Created scripts/example.py")
|
||||
|
||||
# Create references/ directory with example reference doc
|
||||
references_dir = skill_dir / 'references'
|
||||
references_dir.mkdir(exist_ok=True)
|
||||
example_reference = references_dir / 'api_reference.md'
|
||||
example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
|
||||
print("[OK] Created references/api_reference.md")
|
||||
|
||||
# Create assets/ directory with example asset placeholder
|
||||
assets_dir = skill_dir / 'assets'
|
||||
assets_dir.mkdir(exist_ok=True)
|
||||
example_asset = assets_dir / 'example_asset.txt'
|
||||
example_asset.write_text(EXAMPLE_ASSET)
|
||||
print("[OK] Created assets/example_asset.txt")
|
||||
except Exception as e:
|
||||
print(f"[x] Error creating resource directories: {e}")
|
||||
return None
|
||||
|
||||
# Print next steps
|
||||
print(f"\n[OK] Skill '{skill_name}' initialized successfully at {skill_dir}")
|
||||
print("\nNext steps:")
|
||||
print("1. Edit SKILL.md to complete the TODO items and update the description")
|
||||
print("2. Customize or delete the example files in scripts/, references/, and assets/")
|
||||
print("3. Run the validator when ready to check the skill structure")
|
||||
|
||||
return skill_dir
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 4 or sys.argv[2] != '--path':
|
||||
print("Usage: init_skill.py <skill-name> --path <path>")
|
||||
print("\nSkill name requirements:")
|
||||
print(" - Hyphen-case identifier (e.g., 'data-analyzer')")
|
||||
print(" - Lowercase letters, digits, and hyphens only")
|
||||
print(" - Max 40 characters")
|
||||
print(" - Must match directory name exactly")
|
||||
print("\nExamples:")
|
||||
print(" init_skill.py my-new-skill --path skills/public")
|
||||
print(" init_skill.py my-api-helper --path skills/private")
|
||||
print(" init_skill.py custom-skill --path /custom/location")
|
||||
sys.exit(1)
|
||||
|
||||
skill_name = sys.argv[1]
|
||||
path = sys.argv[3]
|
||||
|
||||
print(f"Initializing skill: {skill_name}")
|
||||
print(f" Location: {path}")
|
||||
print()
|
||||
|
||||
result = init_skill(skill_name, path)
|
||||
|
||||
if result:
|
||||
sys.exit(0)
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,113 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Skill Packager - Creates a distributable .skill file of a skill folder
|
||||
|
||||
Usage:
|
||||
python utils/package_skill.py <path/to/skill-folder> [output-directory]
|
||||
|
||||
Example:
|
||||
python utils/package_skill.py skills/public/my-skill
|
||||
python utils/package_skill.py skills/public/my-skill ./dist
|
||||
"""
|
||||
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
# Add script directory to path for sibling imports
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from quick_validate import validate_skill
|
||||
|
||||
|
||||
def package_skill(skill_path, output_dir=None):
|
||||
"""
|
||||
Package a skill folder into a .skill file.
|
||||
|
||||
Args:
|
||||
skill_path: Path to the skill folder
|
||||
output_dir: Optional output directory for the .skill file (defaults to current directory)
|
||||
|
||||
Returns:
|
||||
Path to the created .skill file, or None if error
|
||||
"""
|
||||
skill_path = Path(skill_path).resolve()
|
||||
|
||||
# Validate skill folder exists
|
||||
if not skill_path.exists():
|
||||
print(f"[x] Error: Skill folder not found: {skill_path}")
|
||||
return None
|
||||
|
||||
if not skill_path.is_dir():
|
||||
print(f"[x] Error: Path is not a directory: {skill_path}")
|
||||
return None
|
||||
|
||||
# Validate SKILL.md exists
|
||||
skill_md = skill_path / "SKILL.md"
|
||||
if not skill_md.exists():
|
||||
print(f"[x] Error: SKILL.md not found in {skill_path}")
|
||||
return None
|
||||
|
||||
# Run validation before packaging
|
||||
print("Validating skill...")
|
||||
valid, message = validate_skill(skill_path)
|
||||
if not valid:
|
||||
print(f"[x] Validation failed: {message}")
|
||||
print(" Please fix the validation errors before packaging.")
|
||||
return None
|
||||
print(f"[OK] {message}\n")
|
||||
|
||||
# Determine output location
|
||||
skill_name = skill_path.name
|
||||
if output_dir:
|
||||
output_path = Path(output_dir).resolve()
|
||||
output_path.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
output_path = Path.cwd()
|
||||
|
||||
skill_filename = output_path / f"{skill_name}.skill"
|
||||
|
||||
# Create the .skill file (zip format)
|
||||
try:
|
||||
with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
||||
# Walk through the skill directory
|
||||
for file_path in skill_path.rglob('*'):
|
||||
if file_path.is_file():
|
||||
# Calculate the relative path within the zip
|
||||
arcname = file_path.relative_to(skill_path.parent)
|
||||
zipf.write(file_path, arcname)
|
||||
print(f" Added: {arcname}")
|
||||
|
||||
print(f"\n[OK] Successfully packaged skill to: {skill_filename}")
|
||||
return skill_filename
|
||||
|
||||
except Exception as e:
|
||||
print(f"[x] Error creating .skill file: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]")
|
||||
print("\nExample:")
|
||||
print(" python utils/package_skill.py skills/public/my-skill")
|
||||
print(" python utils/package_skill.py skills/public/my-skill ./dist")
|
||||
sys.exit(1)
|
||||
|
||||
skill_path = sys.argv[1]
|
||||
output_dir = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
|
||||
print(f"Packaging skill: {skill_path}")
|
||||
if output_dir:
|
||||
print(f" Output directory: {output_dir}")
|
||||
print()
|
||||
|
||||
result = package_skill(skill_path, output_dir)
|
||||
|
||||
if result:
|
||||
sys.exit(0)
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,95 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick validation script for skills - minimal version
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
def validate_skill(skill_path):
|
||||
"""Basic validation of a skill"""
|
||||
skill_path = Path(skill_path)
|
||||
|
||||
# Check SKILL.md exists
|
||||
skill_md = skill_path / 'SKILL.md'
|
||||
if not skill_md.exists():
|
||||
return False, "SKILL.md not found"
|
||||
|
||||
# Read and validate frontmatter
|
||||
content = skill_md.read_text()
|
||||
if not content.startswith('---'):
|
||||
return False, "No YAML frontmatter found"
|
||||
|
||||
# Extract frontmatter
|
||||
match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
|
||||
if not match:
|
||||
return False, "Invalid frontmatter format"
|
||||
|
||||
frontmatter_text = match.group(1)
|
||||
|
||||
# Parse YAML frontmatter
|
||||
try:
|
||||
frontmatter = yaml.safe_load(frontmatter_text)
|
||||
if not isinstance(frontmatter, dict):
|
||||
return False, "Frontmatter must be a YAML dictionary"
|
||||
except yaml.YAMLError as e:
|
||||
return False, f"Invalid YAML in frontmatter: {e}"
|
||||
|
||||
# Define allowed properties
|
||||
ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata'}
|
||||
|
||||
# Check for unexpected properties (excluding nested keys under metadata)
|
||||
unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES
|
||||
if unexpected_keys:
|
||||
return False, (
|
||||
f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. "
|
||||
f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}"
|
||||
)
|
||||
|
||||
# Check required fields
|
||||
if 'name' not in frontmatter:
|
||||
return False, "Missing 'name' in frontmatter"
|
||||
if 'description' not in frontmatter:
|
||||
return False, "Missing 'description' in frontmatter"
|
||||
|
||||
# Extract name for validation
|
||||
name = frontmatter.get('name', '')
|
||||
if not isinstance(name, str):
|
||||
return False, f"Name must be a string, got {type(name).__name__}"
|
||||
name = name.strip()
|
||||
if name:
|
||||
# Check naming convention (hyphen-case: lowercase with hyphens)
|
||||
if not re.match(r'^[a-z0-9-]+$', name):
|
||||
return False, f"Name '{name}' should be hyphen-case (lowercase letters, digits, and hyphens only)"
|
||||
if name.startswith('-') or name.endswith('-') or '--' in name:
|
||||
return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens"
|
||||
# Check name length (max 64 characters per spec)
|
||||
if len(name) > 64:
|
||||
return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters."
|
||||
|
||||
# Extract and validate description
|
||||
description = frontmatter.get('description', '')
|
||||
if not isinstance(description, str):
|
||||
return False, f"Description must be a string, got {type(description).__name__}"
|
||||
description = description.strip()
|
||||
if description:
|
||||
# Check for angle brackets
|
||||
if '<' in description or '>' in description:
|
||||
return False, "Description cannot contain angle brackets (< or >)"
|
||||
# Check description length (max 1024 characters per spec)
|
||||
if len(description) > 1024:
|
||||
return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters."
|
||||
|
||||
return True, "Skill is valid!"
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python quick_validate.py <skill_directory>")
|
||||
sys.exit(1)
|
||||
|
||||
valid, message = validate_skill(sys.argv[1])
|
||||
print(message)
|
||||
sys.exit(0 if valid else 1)
|
||||
+20
-1
@@ -1,6 +1,25 @@
|
||||
# agent-browser
|
||||
|
||||
## 0.14.0-fork.3
|
||||
## 0.15.2-fork.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Merge upstream `v0.15.2` updates, including fixes for cookies clear/tab close output, daemon EPERM liveness checks, unnamed element reference matching, and docs/skills refresh.
|
||||
|
||||
## 0.15.1-fork.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Auto-attach existing browser more reliably by trying CDP localhost:9333 first, then falling back to auto-discovery before failing.
|
||||
Align daemon behavior and user-facing docs/skill guidance with the same attachment policy.
|
||||
|
||||
## 0.15.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 7bd8ce9: Added support for chrome:// and chrome-extension:// URLs in navigation and recording commands. These special browser URLs are now preserved as-is instead of having https:// incorrectly prepended.
|
||||
|
||||
## 0.15.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
|
||||
@@ -15,6 +15,24 @@ This README focuses on stealth architecture and principles. For full command cov
|
||||
- Region signals are auto-aligned (locale/timezone/Accept-Language) to reduce mismatch risk.
|
||||
- Verification/captcha handling is policy-driven (`--risk-mode off|warn|block`).
|
||||
|
||||
## FAQ: `agent-browser` vs `agent-browser-stealth`
|
||||
|
||||
People often ask this: "What's the anti-detection approach compared to `agent-browser-stealth` on npm?"
|
||||
|
||||
- `agent-browser-stealth` on npm is the package name for this fork.
|
||||
- The CLI keeps upstream-compatible command names (`agent-browser` is still the main executable, with `agent-browser-stealth` as an alias).
|
||||
- The practical difference vs upstream `agent-browser` is not one single "stealth switch"; it is a defense-in-depth stack designed for anti-bot pressure.
|
||||
|
||||
The core idea is layered hardening across the full automation lifecycle:
|
||||
|
||||
1. Connection-aware policy: choose the best available stealth capability by mode (local launch/CDP/cloud provider).
|
||||
2. Fingerprint hardening: patch launch args, CDP metadata, and init-script surfaces before page code runs.
|
||||
3. Behavioral humanization: non-uniform typing/mouse/wait patterns instead of perfectly mechanical actions.
|
||||
4. Region coherence: auto-align locale/timezone/language signals to target geography.
|
||||
5. Risk-aware control loop: detect verification/captcha signals and handle them with explicit `risk-mode` policy.
|
||||
|
||||
Goal: reduce detection probability and improve stability in production automation. Non-goal: "guaranteed bypass" on every target.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Install
|
||||
@@ -50,12 +68,12 @@ flowchart TD
|
||||
|
||||
### Policy by Connection Mode
|
||||
|
||||
| Mode | Stealth Capabilities | Notes |
|
||||
|---|---|---|
|
||||
| Local Chromium launch | Chromium launch args + CDP UA override + context init scripts | Most complete stack |
|
||||
| Existing browser via CDP | CDP UA override + context init scripts | No local Chromium arg injection |
|
||||
| Cloud provider (browserbase/browseruse) | Context init scripts | Remote browser runtime controls launch layer |
|
||||
| Kernel provider | Context init scripts + provider-managed stealth | Provider-side stealth may also apply |
|
||||
| Mode | Stealth Capabilities | Notes |
|
||||
| --------------------------------------- | ------------------------------------------------------------- | -------------------------------------------- |
|
||||
| Local Chromium launch | Chromium launch args + CDP UA override + context init scripts | Most complete stack |
|
||||
| Existing browser via CDP | CDP UA override + context init scripts | No local Chromium arg injection |
|
||||
| Cloud provider (browserbase/browseruse) | Context init scripts | Remote browser runtime controls launch layer |
|
||||
| Kernel provider | Context init scripts + provider-managed stealth | Provider-side stealth may also apply |
|
||||
|
||||
## Principle 1: Always-On Stealth with Explicit Boundaries
|
||||
|
||||
@@ -63,7 +81,7 @@ flowchart TD
|
||||
- Project policy forbids:
|
||||
- `--profile` / `AGENT_BROWSER_PROFILE`
|
||||
- `--channel` / `AGENT_BROWSER_CHANNEL`
|
||||
- Default CLI policy expects an existing browser on CDP `localhost:9333` unless explicit connection options are provided.
|
||||
- Default CLI policy auto-attaches an existing browser: try CDP `localhost:9333` first, then auto-discovery unless explicit connection options are provided.
|
||||
|
||||
## Principle 2: Multi-Layer Fingerprint Hardening
|
||||
|
||||
@@ -181,6 +199,8 @@ flowchart TD
|
||||
- Reuse session state with `--session-name` for continuity.
|
||||
- Keep locale/timezone consistent with target market.
|
||||
- Use `--risk-mode block` in strict pipelines that require explicit operator intervention on verification pages.
|
||||
- For `cookies set`, use either `--url <url>`, or `--domain <domain> --path <path>` together.
|
||||
- If `--url`, `--domain`, and `--path` are all omitted, the cookie is scoped from the current page URL.
|
||||
|
||||
## Validation Scripts
|
||||
|
||||
|
||||
Generated
+2
-1
@@ -4,10 +4,11 @@ version = 4
|
||||
|
||||
[[package]]
|
||||
name = "agent-browser-stealth"
|
||||
version = "0.14.0-fork.5"
|
||||
version = "0.15.2-fork.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"dirs",
|
||||
"getrandom",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "agent-browser-stealth"
|
||||
version = "0.14.0-fork.5"
|
||||
version = "0.15.2-fork.0"
|
||||
edition = "2021"
|
||||
description = "Stealth browser automation CLI for AI agents with anti-bot evasions"
|
||||
license = "Apache-2.0"
|
||||
@@ -18,6 +18,7 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
dirs = "5.0"
|
||||
base64 = "0.22"
|
||||
getrandom = "0.2"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
+71
-18
@@ -159,6 +159,8 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
|| url_lower.starts_with("about:")
|
||||
|| url_lower.starts_with("data:")
|
||||
|| url_lower.starts_with("file:")
|
||||
|| url_lower.starts_with("chrome-extension://")
|
||||
|| url_lower.starts_with("chrome://")
|
||||
{
|
||||
url.to_string()
|
||||
} else {
|
||||
@@ -828,6 +830,17 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
}
|
||||
}
|
||||
|
||||
// Playwright requires either `url` or a complete `domain`+`path` pair.
|
||||
let has_url = cookie.get("url").is_some();
|
||||
let has_domain = cookie.get("domain").is_some();
|
||||
let has_path = cookie.get("path").is_some();
|
||||
if !has_url && (has_domain != has_path) {
|
||||
return Err(ParseError::MissingArguments {
|
||||
context: "cookies set".to_string(),
|
||||
usage: "When not using --url, you must provide both --domain <domain> and --path <path>",
|
||||
});
|
||||
}
|
||||
|
||||
Ok(json!({ "id": id, "action": "cookies_set", "cookies": [cookie] }))
|
||||
}
|
||||
"clear" => Ok(json!({ "id": id, "action": "cookies_clear" })),
|
||||
@@ -983,8 +996,8 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
let url = rest.get(2);
|
||||
let mut cmd = json!({ "id": id, "action": "recording_start", "path": path });
|
||||
if let Some(u) = url {
|
||||
// Add https:// prefix if needed
|
||||
let url_str = if u.starts_with("http") {
|
||||
// Add https:// prefix if needed (preserve special schemes)
|
||||
let url_str = if u.starts_with("http") || u.contains("://") {
|
||||
u.to_string()
|
||||
} else {
|
||||
format!("https://{}", u)
|
||||
@@ -1003,8 +1016,8 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
let url = rest.get(2);
|
||||
let mut cmd = json!({ "id": id, "action": "recording_restart", "path": path });
|
||||
if let Some(u) = url {
|
||||
// Add https:// prefix if needed
|
||||
let url_str = if u.starts_with("http") {
|
||||
// Add https:// prefix if needed (preserve special schemes)
|
||||
let url_str = if u.starts_with("http") || u.contains("://") {
|
||||
u.to_string()
|
||||
} else {
|
||||
format!("https://{}", u)
|
||||
@@ -2097,28 +2110,34 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cookies_set_with_domain() {
|
||||
let cmd = parse_command(
|
||||
fn test_cookies_set_with_domain_requires_path() {
|
||||
let result = parse_command(
|
||||
&args("cookies set mycookie myvalue --domain example.com"),
|
||||
&default_flags(),
|
||||
);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cookies_set_with_path_requires_domain() {
|
||||
let result = parse_command(
|
||||
&args("cookies set mycookie myvalue --path /api"),
|
||||
&default_flags(),
|
||||
);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cookies_set_with_domain_and_path() {
|
||||
let cmd = parse_command(
|
||||
&args("cookies set mycookie myvalue --domain example.com --path /api"),
|
||||
&default_flags(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd["action"], "cookies_set");
|
||||
assert_eq!(cmd["cookies"][0]["name"], "mycookie");
|
||||
assert_eq!(cmd["cookies"][0]["value"], "myvalue");
|
||||
assert_eq!(cmd["cookies"][0]["domain"], "example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cookies_set_with_path() {
|
||||
let cmd = parse_command(
|
||||
&args("cookies set mycookie myvalue --path /api"),
|
||||
&default_flags(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd["action"], "cookies_set");
|
||||
assert_eq!(cmd["cookies"][0]["name"], "mycookie");
|
||||
assert_eq!(cmd["cookies"][0]["value"], "myvalue");
|
||||
assert_eq!(cmd["cookies"][0]["path"], "/api");
|
||||
}
|
||||
|
||||
@@ -2345,6 +2364,28 @@ mod tests {
|
||||
assert!(msg.contains("Invalid JSON for --headers"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_navigate_chrome_extension_url() {
|
||||
let cmd = parse_command(
|
||||
&args("open chrome-extension://abcdefghijklmnop/popup.html"),
|
||||
&default_flags(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd["action"], "navigate");
|
||||
assert_eq!(
|
||||
cmd["url"],
|
||||
"chrome-extension://abcdefghijklmnop/popup.html"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_navigate_chrome_url() {
|
||||
let cmd =
|
||||
parse_command(&args("open chrome://extensions"), &default_flags()).unwrap();
|
||||
assert_eq!(cmd["action"], "navigate");
|
||||
assert_eq!(cmd["url"], "chrome://extensions");
|
||||
}
|
||||
|
||||
// === Set Headers Tests ===
|
||||
|
||||
#[test]
|
||||
@@ -2723,6 +2764,18 @@ mod tests {
|
||||
assert_eq!(cmd["url"], "https://example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_record_start_with_chrome_extension_url() {
|
||||
let cmd = parse_command(
|
||||
&args("record start demo.webm chrome-extension://abcdef/popup.html"),
|
||||
&default_flags(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd["action"], "recording_start");
|
||||
assert_eq!(cmd["path"], "demo.webm");
|
||||
assert_eq!(cmd["url"], "chrome-extension://abcdef/popup.html");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_record_start_missing_path() {
|
||||
let result = parse_command(&args("record start"), &default_flags());
|
||||
|
||||
@@ -159,7 +159,13 @@ fn is_daemon_running(session: &str) -> bool {
|
||||
if let Ok(pid_str) = fs::read_to_string(&pid_path) {
|
||||
if let Ok(pid) = pid_str.trim().parse::<i32>() {
|
||||
unsafe {
|
||||
return libc::kill(pid, 0) == 0;
|
||||
if libc::kill(pid, 0) == 0 {
|
||||
return true;
|
||||
}
|
||||
// EPERM means the process exists but we lack permission to
|
||||
// signal it (e.g. inside a macOS sandbox). Only ESRCH means
|
||||
// the process is genuinely gone.
|
||||
return std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+33
-8
@@ -72,7 +72,11 @@ fn run_session(args: &[String], session: &str, json_mode: bool) {
|
||||
if let Ok(pid_str) = fs::read_to_string(&pid_path) {
|
||||
if let Ok(pid) = pid_str.trim().parse::<u32>() {
|
||||
#[cfg(unix)]
|
||||
let running = unsafe { libc::kill(pid as i32, 0) == 0 };
|
||||
let running = unsafe {
|
||||
libc::kill(pid as i32, 0) == 0
|
||||
|| std::io::Error::last_os_error().raw_os_error()
|
||||
!= Some(libc::ESRCH)
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let running = unsafe {
|
||||
let handle =
|
||||
@@ -399,6 +403,8 @@ fn main() {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
let mut attached_to_existing_browser = false;
|
||||
|
||||
// Auto-connect to existing browser
|
||||
if flags.auto_connect {
|
||||
let mut launch_cmd = json!({
|
||||
@@ -436,6 +442,8 @@ fn main() {
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
attached_to_existing_browser = true;
|
||||
}
|
||||
|
||||
// Connect via CDP if --cdp flag is set
|
||||
@@ -526,6 +534,8 @@ fn main() {
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
attached_to_existing_browser = true;
|
||||
}
|
||||
|
||||
// Launch with cloud provider if -p flag is set
|
||||
@@ -567,8 +577,8 @@ fn main() {
|
||||
}
|
||||
|
||||
// Project policy: when no explicit connection mode is provided,
|
||||
// commands must attach to an existing browser on CDP :9333.
|
||||
// If unavailable, fail fast instead of launching a managed browser.
|
||||
// commands should attach to an existing browser.
|
||||
// Try CDP :9333 first, then fall back to auto-connect discovery.
|
||||
let can_try_default_cdp = flags.cdp.is_none()
|
||||
&& !flags.auto_connect
|
||||
&& flags.provider.is_none()
|
||||
@@ -581,7 +591,6 @@ fn main() {
|
||||
&& !flags.allow_file_access
|
||||
&& flags.extensions.is_empty();
|
||||
|
||||
let mut launched_via_default_cdp = false;
|
||||
if can_try_default_cdp {
|
||||
let mut launch_cmd = json!({
|
||||
"id": gen_id(),
|
||||
@@ -594,11 +603,27 @@ fn main() {
|
||||
}
|
||||
|
||||
if let Ok(resp) = send_command(launch_cmd, &flags.session) {
|
||||
launched_via_default_cdp = resp.success;
|
||||
attached_to_existing_browser = resp.success;
|
||||
}
|
||||
|
||||
if !attached_to_existing_browser {
|
||||
let mut auto_connect_cmd = json!({
|
||||
"id": gen_id(),
|
||||
"action": "launch",
|
||||
"autoConnect": true
|
||||
});
|
||||
|
||||
if let Some(ref cs) = flags.color_scheme {
|
||||
auto_connect_cmd["colorScheme"] = json!(cs);
|
||||
}
|
||||
|
||||
if let Ok(resp) = send_command(auto_connect_cmd, &flags.session) {
|
||||
attached_to_existing_browser = resp.success;
|
||||
}
|
||||
}
|
||||
}
|
||||
if can_try_default_cdp && !launched_via_default_cdp {
|
||||
let msg = "Project policy requires using your existing browser. Could not connect to CDP at localhost:9333. Start your browser with remote debugging on port 9333, or pass --cdp <port|url>.";
|
||||
if can_try_default_cdp && !attached_to_existing_browser {
|
||||
let msg = "Project policy requires using your existing browser. Could not connect to CDP at localhost:9333 and auto-discovery also failed. Start Chrome with remote debugging (for example, --remote-debugging-port=9333), or pass --cdp <port|url>.";
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
@@ -621,7 +646,7 @@ fn main() {
|
||||
|| flags.download_path.is_some())
|
||||
&& flags.cdp.is_none()
|
||||
&& flags.provider.is_none()
|
||||
&& !launched_via_default_cdp
|
||||
&& !attached_to_existing_browser
|
||||
{
|
||||
let mut launch_cmd = json!({
|
||||
"id": gen_id(),
|
||||
|
||||
+288
-22
@@ -1,9 +1,83 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::color;
|
||||
use crate::connection::Response;
|
||||
|
||||
pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
if json_mode {
|
||||
println!("{}", serde_json::to_string(resp).unwrap_or_default());
|
||||
static BOUNDARY_NONCE: OnceLock<String> = OnceLock::new();
|
||||
|
||||
/// Per-process nonce for content boundary markers. Uses a CSPRNG (getrandom) so
|
||||
/// that untrusted page content cannot predict or spoof the boundary delimiter.
|
||||
/// Process ID or timestamps would be insufficient since pages can read those.
|
||||
fn get_boundary_nonce() -> &'static str {
|
||||
BOUNDARY_NONCE.get_or_init(|| {
|
||||
let mut buf = [0u8; 16];
|
||||
getrandom::getrandom(&mut buf).expect("failed to generate random nonce");
|
||||
buf.iter().map(|b| format!("{:02x}", b)).collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct OutputOptions {
|
||||
pub json: bool,
|
||||
pub content_boundaries: bool,
|
||||
pub max_output: Option<usize>,
|
||||
}
|
||||
|
||||
fn truncate_if_needed(content: &str, max: Option<usize>) -> String {
|
||||
let Some(limit) = max else {
|
||||
return content.to_string();
|
||||
};
|
||||
// Fast path: byte length is a lower bound on char count, so if the
|
||||
// byte length is within the limit the char count must be too.
|
||||
if content.len() <= limit {
|
||||
return content.to_string();
|
||||
}
|
||||
// Find the byte offset of the limit-th character.
|
||||
match content.char_indices().nth(limit).map(|(i, _)| i) {
|
||||
Some(byte_offset) => {
|
||||
let total_chars = content.chars().count();
|
||||
format!(
|
||||
"{}\n[truncated: showing {} of {} chars. Use --max-output to adjust]",
|
||||
&content[..byte_offset], limit, total_chars
|
||||
)
|
||||
}
|
||||
// Content has fewer than `limit` chars despite more bytes
|
||||
None => content.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_with_boundaries(content: &str, origin: Option<&str>, opts: &OutputOptions) {
|
||||
let content = truncate_if_needed(content, opts.max_output);
|
||||
if opts.content_boundaries {
|
||||
let origin_str = origin.unwrap_or("unknown");
|
||||
let nonce = get_boundary_nonce();
|
||||
println!("--- AGENT_BROWSER_PAGE_CONTENT nonce={} origin={} ---", nonce, origin_str);
|
||||
println!("{}", content);
|
||||
println!("--- END_AGENT_BROWSER_PAGE_CONTENT nonce={} ---", nonce);
|
||||
} else {
|
||||
println!("{}", content);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &OutputOptions) {
|
||||
if opts.json {
|
||||
if opts.content_boundaries {
|
||||
let mut json_val = serde_json::to_value(resp).unwrap_or_default();
|
||||
if let Some(obj) = json_val.as_object_mut() {
|
||||
let nonce = get_boundary_nonce();
|
||||
let origin = obj.get("data")
|
||||
.and_then(|d| d.get("origin"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown");
|
||||
obj.insert("_boundary".to_string(), serde_json::json!({
|
||||
"nonce": nonce,
|
||||
"origin": origin,
|
||||
}));
|
||||
}
|
||||
println!("{}", serde_json::to_string(&json_val).unwrap_or_default());
|
||||
} else {
|
||||
println!("{}", serde_json::to_string(resp).unwrap_or_default());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -82,9 +156,10 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let origin = data.get("origin").and_then(|v| v.as_str());
|
||||
// Snapshot
|
||||
if let Some(snapshot) = data.get("snapshot").and_then(|v| v.as_str()) {
|
||||
println!("{}", snapshot);
|
||||
print_with_boundaries(snapshot, origin, opts);
|
||||
return;
|
||||
}
|
||||
// Title
|
||||
@@ -94,12 +169,12 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
}
|
||||
// Text
|
||||
if let Some(text) = data.get("text").and_then(|v| v.as_str()) {
|
||||
println!("{}", text);
|
||||
print_with_boundaries(text, origin, opts);
|
||||
return;
|
||||
}
|
||||
// HTML
|
||||
if let Some(html) = data.get("html").and_then(|v| v.as_str()) {
|
||||
println!("{}", html);
|
||||
print_with_boundaries(html, origin, opts);
|
||||
return;
|
||||
}
|
||||
// Value
|
||||
@@ -127,10 +202,8 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
}
|
||||
// Eval result
|
||||
if let Some(result) = data.get("result") {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(result).unwrap_or_default()
|
||||
);
|
||||
let formatted = serde_json::to_string_pretty(result).unwrap_or_default();
|
||||
print_with_boundaries(&formatted, origin, opts);
|
||||
return;
|
||||
}
|
||||
// iOS Devices
|
||||
@@ -217,10 +290,23 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
}
|
||||
// Console logs
|
||||
if let Some(logs) = data.get("messages").and_then(|v| v.as_array()) {
|
||||
for log in logs {
|
||||
let level = log.get("type").and_then(|v| v.as_str()).unwrap_or("log");
|
||||
let text = log.get("text").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!("{} {}", color::console_level_prefix(level), text);
|
||||
if opts.content_boundaries {
|
||||
let mut console_output = String::new();
|
||||
for log in logs {
|
||||
let level = log.get("type").and_then(|v| v.as_str()).unwrap_or("log");
|
||||
let text = log.get("text").and_then(|v| v.as_str()).unwrap_or("");
|
||||
console_output.push_str(&format!("{} {}\n", color::console_level_prefix(level), text));
|
||||
}
|
||||
if console_output.ends_with('\n') {
|
||||
console_output.pop();
|
||||
}
|
||||
print_with_boundaries(&console_output, origin, opts);
|
||||
} else {
|
||||
for log in logs {
|
||||
let level = log.get("type").and_then(|v| v.as_str()).unwrap_or("log");
|
||||
let text = log.get("text").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!("{} {}", color::console_level_prefix(level), text);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -258,10 +344,14 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Cleared requests
|
||||
// Cleared (cookies or request log)
|
||||
if let Some(cleared) = data.get("cleared").and_then(|v| v.as_bool()) {
|
||||
if cleared {
|
||||
println!("{} Request log cleared", color::success_indicator());
|
||||
let label = match action {
|
||||
Some("cookies_clear") => "Cookies cleared",
|
||||
_ => "Request log cleared",
|
||||
};
|
||||
println!("{} {}", color::success_indicator(), label);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -322,9 +412,13 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Closed
|
||||
// Closed (browser or tab)
|
||||
if data.get("closed").is_some() {
|
||||
println!("{} Browser closed", color::success_indicator());
|
||||
let label = match action {
|
||||
Some("tab_close") => "Tab closed",
|
||||
_ => "Browser closed",
|
||||
};
|
||||
println!("{} {}", color::success_indicator(), label);
|
||||
return;
|
||||
}
|
||||
// Recording start (has "started" field)
|
||||
@@ -593,6 +687,87 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
println!("{}", note);
|
||||
return;
|
||||
}
|
||||
// Auth list
|
||||
if let Some(profiles) = data.get("profiles").and_then(|v| v.as_array()) {
|
||||
if profiles.is_empty() {
|
||||
println!("{}", color::dim("No auth profiles saved"));
|
||||
} else {
|
||||
println!("{}", color::bold("Auth profiles:"));
|
||||
for p in profiles {
|
||||
let name = p.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let url = p.get("url").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let user = p.get("username").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!(" {} {} {}", color::green(name), color::dim(user), color::dim(url));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Auth show
|
||||
if let Some(profile) = data.get("profile").and_then(|v| v.as_object()) {
|
||||
let name = profile.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let url = profile.get("url").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let user = profile.get("username").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let created = profile.get("createdAt").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let last_login = profile.get("lastLoginAt").and_then(|v| v.as_str());
|
||||
println!("Name: {}", name);
|
||||
println!("URL: {}", url);
|
||||
println!("Username: {}", user);
|
||||
println!("Created: {}", created);
|
||||
if let Some(ll) = last_login {
|
||||
println!("Last login: {}", ll);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Auth save/update/login/delete
|
||||
if data.get("saved").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
let name = data.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!("{} Auth profile '{}' saved", color::success_indicator(), name);
|
||||
return;
|
||||
}
|
||||
if data.get("updated").and_then(|v| v.as_bool()).unwrap_or(false)
|
||||
&& !data.get("saved").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
let name = data.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!("{} Auth profile '{}' updated", color::success_indicator(), name);
|
||||
return;
|
||||
}
|
||||
if data.get("loggedIn").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
let name = data.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if let Some(title) = data.get("title").and_then(|v| v.as_str()) {
|
||||
println!("{} Logged in as '{}' - {}", color::success_indicator(), name, title);
|
||||
} else {
|
||||
println!("{} Logged in as '{}'", color::success_indicator(), name);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if data.get("deleted").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
if let Some(name) = data.get("name").and_then(|v| v.as_str()) {
|
||||
println!("{} Auth profile '{}' deleted", color::success_indicator(), name);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Confirmation required (for orchestrator use)
|
||||
if data.get("confirmation_required").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
let category = data.get("category").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let description = data.get("description").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let cid = data.get("confirmation_id").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!("Confirmation required:");
|
||||
println!(" {}: {}", category, description);
|
||||
println!(" Run: agent-browser confirm {}", cid);
|
||||
println!(" Or: agent-browser deny {}", cid);
|
||||
return;
|
||||
}
|
||||
if data.get("confirmed").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
println!("{} Action confirmed", color::success_indicator());
|
||||
return;
|
||||
}
|
||||
if data.get("denied").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
println!("{} Action denied", color::success_indicator());
|
||||
return;
|
||||
}
|
||||
|
||||
// Default success
|
||||
println!("{} Done", color::success_indicator());
|
||||
}
|
||||
@@ -1486,8 +1661,8 @@ Operations:
|
||||
|
||||
Cookie Set Options:
|
||||
--url <url> URL for the cookie (allows setting before page load)
|
||||
--domain <domain> Cookie domain (e.g., ".example.com")
|
||||
--path <path> Cookie path (e.g., "/api")
|
||||
--domain <domain> Cookie domain (use with --path, e.g., ".example.com")
|
||||
--path <path> Cookie path (use with --domain, e.g., "/api")
|
||||
--httpOnly Set HttpOnly flag (prevents JavaScript access)
|
||||
--secure Set Secure flag (HTTPS only)
|
||||
--sameSite <Strict|Lax|None> SameSite policy
|
||||
@@ -1495,6 +1670,7 @@ Cookie Set Options:
|
||||
|
||||
Note: If --url, --domain, and --path are all omitted, the cookie will be set
|
||||
for the current page URL.
|
||||
When --url is omitted, --domain and --path must be provided together.
|
||||
|
||||
Global Options:
|
||||
--json Output as JSON
|
||||
@@ -1599,6 +1775,64 @@ Examples:
|
||||
"##
|
||||
}
|
||||
|
||||
// === Auth ===
|
||||
"auth" => {
|
||||
r##"
|
||||
agent-browser auth - Manage authentication profiles
|
||||
|
||||
Usage: agent-browser auth <subcommand> [args]
|
||||
|
||||
Subcommands:
|
||||
save <name> Save credentials for a login profile
|
||||
login <name> Login using saved credentials
|
||||
list List saved profiles (names and URLs only)
|
||||
show <name> Show profile metadata (no passwords)
|
||||
delete <name> Delete a saved profile
|
||||
|
||||
Save Options:
|
||||
--url <url> Login page URL (required)
|
||||
--username <user> Username (required)
|
||||
--password <pass> Password (required unless --password-stdin)
|
||||
--password-stdin Read password from stdin (recommended)
|
||||
--username-selector <s> Custom CSS selector for username field
|
||||
--password-selector <s> Custom CSS selector for password field
|
||||
--submit-selector <s> Custom CSS selector for submit button
|
||||
|
||||
Global Options:
|
||||
--json Output as JSON
|
||||
--session <name> Use specific session
|
||||
|
||||
Examples:
|
||||
echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin
|
||||
agent-browser auth save github --url https://github.com/login --username user --password pass
|
||||
agent-browser auth login github
|
||||
agent-browser auth list
|
||||
agent-browser auth show github
|
||||
agent-browser auth delete github
|
||||
"##
|
||||
}
|
||||
|
||||
// === Confirm/Deny ===
|
||||
"confirm" | "deny" => {
|
||||
r##"
|
||||
agent-browser confirm/deny - Approve or deny pending actions
|
||||
|
||||
Usage:
|
||||
agent-browser confirm <confirmation-id>
|
||||
agent-browser deny <confirmation-id>
|
||||
|
||||
When --confirm-actions is set, certain action categories return a
|
||||
confirmation_required response with a confirmation ID. Use confirm/deny
|
||||
to approve or reject the action.
|
||||
|
||||
Pending confirmations auto-deny after 60 seconds.
|
||||
|
||||
Examples:
|
||||
agent-browser confirm c_8f3a1234
|
||||
agent-browser deny c_8f3a1234
|
||||
"##
|
||||
}
|
||||
|
||||
// === Dialog ===
|
||||
"dialog" => {
|
||||
r##"
|
||||
@@ -2124,6 +2358,17 @@ Debug:
|
||||
errors [--clear] View page errors
|
||||
highlight <sel> Highlight element
|
||||
|
||||
Auth Vault:
|
||||
auth save <name> [opts] Save auth profile (--url, --username, --password/--password-stdin)
|
||||
auth login <name> Login using saved credentials
|
||||
auth list List saved auth profiles
|
||||
auth show <name> Show auth profile metadata
|
||||
auth delete <name> Delete auth profile
|
||||
|
||||
Confirmation:
|
||||
confirm <id> Approve a pending action
|
||||
deny <id> Deny a pending action
|
||||
|
||||
Sessions:
|
||||
session Show current session name
|
||||
session list List active sessions
|
||||
@@ -2161,11 +2406,17 @@ Options:
|
||||
--headed Show browser window (not headless)
|
||||
--cdp <port> Connect via CDP (Chrome DevTools Protocol)
|
||||
--auto-connect Auto-discover and connect to running Chrome
|
||||
Project default: require existing browser at localhost:9333 (no auto local fallback)
|
||||
Project default: try localhost:9333 first, then auto-discovery (no managed local-launch fallback)
|
||||
--color-scheme <scheme> Color scheme: dark, light, no-preference (or AGENT_BROWSER_COLOR_SCHEME)
|
||||
--download-path <path> Default download directory (or AGENT_BROWSER_DOWNLOAD_PATH)
|
||||
--risk-mode <mode> Verify/captcha handling: off, warn, block (or AGENT_BROWSER_RISK_MODE)
|
||||
--session-name <name> Auto-save/restore session state (cookies, localStorage)
|
||||
--content-boundaries Wrap page output in boundary markers (or AGENT_BROWSER_CONTENT_BOUNDARIES)
|
||||
--max-output <chars> Truncate page output to N chars (or AGENT_BROWSER_MAX_OUTPUT)
|
||||
--allowed-domains <list> Restrict navigation domains (or AGENT_BROWSER_ALLOWED_DOMAINS)
|
||||
--action-policy <path> Action policy JSON file (or AGENT_BROWSER_ACTION_POLICY)
|
||||
--confirm-actions <list> Categories requiring confirmation (or AGENT_BROWSER_CONFIRM_ACTIONS)
|
||||
--confirm-interactive Interactive confirmation prompts; auto-denies if stdin is not a TTY (or AGENT_BROWSER_CONFIRM_INTERACTIVE)
|
||||
--config <path> Use a custom config file (or AGENT_BROWSER_CONFIG env)
|
||||
--debug Debug output
|
||||
--version, -V Show version (fork builds include upstream/fork info)
|
||||
@@ -2173,7 +2424,7 @@ Options:
|
||||
Policy:
|
||||
--profile / AGENT_BROWSER_PROFILE are forbidden
|
||||
--channel / AGENT_BROWSER_CHANNEL are forbidden
|
||||
Use existing browser session (CDP localhost:9333) or pass --cdp explicitly
|
||||
Auto-attach existing browser (prefer CDP localhost:9333, then auto-discovery), or pass --cdp explicitly
|
||||
|
||||
Configuration:
|
||||
agent-browser looks for agent-browser.json in these locations (lowest to highest priority):
|
||||
@@ -2224,6 +2475,12 @@ Environment:
|
||||
AGENT_BROWSER_STREAM_PORT Enable WebSocket streaming on port (e.g., 9223)
|
||||
AGENT_BROWSER_IOS_DEVICE Default iOS device name
|
||||
AGENT_BROWSER_IOS_UDID Default iOS device UDID
|
||||
AGENT_BROWSER_CONTENT_BOUNDARIES Wrap page output in boundary markers
|
||||
AGENT_BROWSER_MAX_OUTPUT Max characters for page output
|
||||
AGENT_BROWSER_ALLOWED_DOMAINS Comma-separated allowed domain patterns
|
||||
AGENT_BROWSER_ACTION_POLICY Path to action policy JSON file
|
||||
AGENT_BROWSER_CONFIRM_ACTIONS Action categories requiring confirmation
|
||||
AGENT_BROWSER_CONFIRM_INTERACTIVE Enable interactive confirmation prompts
|
||||
|
||||
Install (recommended, fastest - native Rust CLI):
|
||||
npm install -g agent-browser-stealth
|
||||
@@ -2265,6 +2522,15 @@ iOS Simulator (requires Xcode and Appium):
|
||||
);
|
||||
}
|
||||
|
||||
pub fn print_response(resp: &Response, json: bool, action: Option<&str>) {
|
||||
let opts = OutputOptions {
|
||||
json,
|
||||
content_boundaries: false,
|
||||
max_output: None,
|
||||
};
|
||||
print_response_with_opts(resp, action, &opts);
|
||||
}
|
||||
|
||||
fn print_snapshot_diff(data: &serde_json::Map<String, serde_json::Value>) {
|
||||
let changed = data
|
||||
.get("changed")
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.1.1",
|
||||
"tailwindcss": "^4",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+12
-8
@@ -102,9 +102,9 @@ importers:
|
||||
tailwindcss:
|
||||
specifier: ^4
|
||||
version: 4.1.18
|
||||
tw-animate-css:
|
||||
specifier: ^1.4.0
|
||||
version: 1.4.0
|
||||
tailwindcss-animate:
|
||||
specifier: ^1.0.7
|
||||
version: 1.0.7(tailwindcss@4.1.18)
|
||||
typescript:
|
||||
specifier: ^5
|
||||
version: 5.9.3
|
||||
@@ -3467,6 +3467,11 @@ packages:
|
||||
tailwind-merge@3.4.0:
|
||||
resolution: {integrity: sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==}
|
||||
|
||||
tailwindcss-animate@1.0.7:
|
||||
resolution: {integrity: sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==}
|
||||
peerDependencies:
|
||||
tailwindcss: '>=3.0.0 || insiders'
|
||||
|
||||
tailwindcss@4.1.18:
|
||||
resolution: {integrity: sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==}
|
||||
|
||||
@@ -3521,9 +3526,6 @@ packages:
|
||||
turndown@7.2.2:
|
||||
resolution: {integrity: sha512-1F7db8BiExOKxjSMU2b7if62D/XOyQyZbPKq/nUwopfgnHlqXHqQ0lvfUTeUIr1lZJzOPFn43dODyMSIfvWRKQ==}
|
||||
|
||||
tw-animate-css@1.4.0:
|
||||
resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==}
|
||||
|
||||
type-check@0.4.0:
|
||||
resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
@@ -7827,6 +7829,10 @@ snapshots:
|
||||
|
||||
tailwind-merge@3.4.0: {}
|
||||
|
||||
tailwindcss-animate@1.0.7(tailwindcss@4.1.18):
|
||||
dependencies:
|
||||
tailwindcss: 4.1.18
|
||||
|
||||
tailwindcss@4.1.18: {}
|
||||
|
||||
tapable@2.3.0: {}
|
||||
@@ -7891,8 +7897,6 @@ snapshots:
|
||||
dependencies:
|
||||
'@mixmark-io/domino': 2.2.0
|
||||
|
||||
tw-animate-css@1.4.0: {}
|
||||
|
||||
type-check@0.4.0:
|
||||
dependencies:
|
||||
prelude-ls: 1.2.1
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { readFile } from "fs/promises";
|
||||
import { join } from "path";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { mdxToCleanMarkdown } from "@/lib/mdx-to-markdown";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const docPath = searchParams.get("path");
|
||||
|
||||
if (!docPath) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing ?path= parameter" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const normalized = docPath
|
||||
.replace(/^\//, "")
|
||||
.replace(/\.\./g, "")
|
||||
.replace(/[^a-zA-Z0-9/_-]/g, "");
|
||||
|
||||
const slug = normalized;
|
||||
const filePath = slug
|
||||
? join(process.cwd(), "src", "app", ...slug.split("/"), "page.mdx")
|
||||
: join(process.cwd(), "src", "app", "page.mdx");
|
||||
|
||||
try {
|
||||
const raw = await readFile(filePath, "utf-8");
|
||||
const markdown = mdxToCleanMarkdown(raw);
|
||||
|
||||
return new NextResponse(markdown, {
|
||||
headers: {
|
||||
"Content-Type": "text/markdown; charset=utf-8",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Page not found" }, { status: 404 });
|
||||
}
|
||||
}
|
||||
+130
-25
@@ -1,12 +1,12 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
import { pageMetadata } from '@/lib/page-metadata';
|
||||
|
||||
export const metadata = pageMetadata("cdp-mode")
|
||||
export const metadata = pageMetadata('cdp-mode');
|
||||
|
||||
# CDP Mode
|
||||
|
||||
Connect to an existing browser via Chrome DevTools Protocol:
|
||||
|
||||
Default behavior in this fork: when `--cdp` is omitted, agent-browser requires an existing browser at `localhost:9333`. If CDP is unavailable, the command fails fast (no local-launch fallback).
|
||||
Default behavior in this fork: when `--cdp` is omitted, agent-browser auto-attaches to an existing browser by trying `localhost:9333` first, then auto-discovery. If both fail, the command exits (no managed local-launch fallback).
|
||||
|
||||
Project policy:
|
||||
|
||||
@@ -88,12 +88,24 @@ AGENT_BROWSER_COLOR_SCHEME=dark agent-browser --cdp 9222 open https://example.co
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Connection type</th><th>Stealth capabilities</th></tr>
|
||||
<tr>
|
||||
<th>Connection type</th>
|
||||
<th>Stealth capabilities</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td>Local launch</td><td>Chromium launch args + context init scripts</td></tr>
|
||||
<tr><td>CDP / auto-connect</td><td>Context init scripts</td></tr>
|
||||
<tr><td>Cloud providers</td><td>Context init scripts (Kernel may also apply provider-managed stealth)</td></tr>
|
||||
<tr>
|
||||
<td>Local launch</td>
|
||||
<td>Chromium launch args + context init scripts</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>CDP / auto-connect</td>
|
||||
<td>Context init scripts</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Cloud providers</td>
|
||||
<td>Context init scripts (Kernel may also apply provider-managed stealth)</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -113,26 +125,119 @@ This enables control of:
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Option</th><th>Description</th></tr>
|
||||
<tr>
|
||||
<th>Option</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><code>--session <name></code></td><td>Use isolated session</td></tr>
|
||||
<tr><td><code>-p <provider></code></td><td>Cloud browser provider (<code>browserbase</code>, <code>browseruse</code>, <code>kernel</code>)</td></tr>
|
||||
<tr><td><code>--headers <json></code></td><td>HTTP headers scoped to origin</td></tr>
|
||||
<tr><td><code>--executable-path</code></td><td>Custom browser executable</td></tr>
|
||||
<tr><td><code>--args <args></code></td><td>Browser launch args (comma-separated)</td></tr>
|
||||
<tr><td><code>--user-agent <ua></code></td><td>Custom User-Agent string</td></tr>
|
||||
<tr><td><code>--proxy <url></code></td><td>Proxy server URL</td></tr>
|
||||
<tr><td><code>--proxy-bypass <hosts></code></td><td>Hosts to bypass proxy</td></tr>
|
||||
<tr><td><code>--json</code></td><td>JSON output for scripts</td></tr>
|
||||
<tr><td><code>--full, -f</code></td><td>Full page screenshot</td></tr>
|
||||
<tr><td><code>--name, -n</code></td><td>Locator name filter</td></tr>
|
||||
<tr><td><code>--exact</code></td><td>Exact text match</td></tr>
|
||||
<tr><td><code>--headed</code></td><td>Show browser window</td></tr>
|
||||
<tr><td><code>{"--cdp <port|url>"}</code></td><td>CDP connection (port or WebSocket URL)</td></tr>
|
||||
<tr><td><code>--auto-connect</code></td><td>Auto-discover and connect to running Chrome</td></tr>
|
||||
<tr><td><code>--color-scheme <scheme></code></td><td>Persistent color scheme (<code>dark</code>, <code>light</code>, <code>no-preference</code>)</td></tr>
|
||||
<tr><td><code>--debug</code></td><td>Debug output</td></tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--session <name></code>
|
||||
</td>
|
||||
<td>Use isolated session</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>-p <provider></code>
|
||||
</td>
|
||||
<td>
|
||||
Cloud browser provider (<code>browserbase</code>, <code>browseruse</code>,{' '}
|
||||
<code>kernel</code>)
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--headers <json></code>
|
||||
</td>
|
||||
<td>HTTP headers scoped to origin</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--executable-path</code>
|
||||
</td>
|
||||
<td>Custom browser executable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--args <args></code>
|
||||
</td>
|
||||
<td>Browser launch args (comma-separated)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--user-agent <ua></code>
|
||||
</td>
|
||||
<td>Custom User-Agent string</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--proxy <url></code>
|
||||
</td>
|
||||
<td>Proxy server URL</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--proxy-bypass <hosts></code>
|
||||
</td>
|
||||
<td>Hosts to bypass proxy</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--json</code>
|
||||
</td>
|
||||
<td>JSON output for scripts</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--full, -f</code>
|
||||
</td>
|
||||
<td>Full page screenshot</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--name, -n</code>
|
||||
</td>
|
||||
<td>Locator name filter</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--exact</code>
|
||||
</td>
|
||||
<td>Exact text match</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--headed</code>
|
||||
</td>
|
||||
<td>Show browser window</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>{'--cdp <port|url>'}</code>
|
||||
</td>
|
||||
<td>CDP connection (port or WebSocket URL)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--auto-connect</code>
|
||||
</td>
|
||||
<td>Auto-discover and connect to running Chrome</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--color-scheme <scheme></code>
|
||||
</td>
|
||||
<td>
|
||||
Persistent color scheme (<code>dark</code>, <code>light</code>, <code>no-preference</code>)
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>--debug</code>
|
||||
</td>
|
||||
<td>Debug output</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
@@ -4,6 +4,123 @@ export const metadata = pageMetadata("changelog")
|
||||
|
||||
# Changelog
|
||||
|
||||
## v0.15.0
|
||||
|
||||
<p className="text-[#888] text-sm">February 2026</p>
|
||||
|
||||
### New Features
|
||||
|
||||
- **Authentication vault** -- Store credentials locally (always AES-256-GCM encrypted) and reference them by name. The LLM never sees passwords. Commands: `auth save`, `auth login`, `auth list`, `auth show`, `auth delete`. Passwords can be piped via stdin (`--password-stdin`) to avoid shell history exposure.
|
||||
- **Content boundary markers** -- `--content-boundaries` wraps page-sourced output in structural delimiters with a per-process CSPRNG nonce, so LLMs can distinguish trusted tool output from untrusted page content. In `--json` mode, a `_boundary` object is injected with `nonce` and `origin` fields.
|
||||
- **Domain allowlist** -- `--allowed-domains` restricts navigation, sub-resource requests, WebSocket connections, and EventSource streams to trusted domains. Supports exact match and wildcard prefix patterns (e.g., `*.example.com`).
|
||||
- **Action policy** -- `--action-policy` gates actions using a static JSON policy file with `allow`/`deny` lists across 13 action categories. Auth vault operations bypass policy enforcement.
|
||||
- **Action confirmation** -- `--confirm-actions` requires explicit approval for sensitive action categories. New `confirm` and `deny` commands for orchestrator use. `--confirm-interactive` enables human-in-the-loop terminal prompts (auto-denies if stdin is not a TTY). Pending confirmations auto-deny after 60 seconds.
|
||||
- **Output length limits** -- `--max-output` truncates large page outputs to prevent LLM context flooding.
|
||||
- **`--download-path` option** -- Set a default download directory via flag, `AGENT_BROWSER_DOWNLOAD_PATH` env var, or `downloadPath` config key. Without it, downloads go to a temporary directory deleted when the browser closes.
|
||||
- **`--selector` flag for scroll** -- Scroll within a specific container element instead of the page: `agent-browser scroll down 500 --selector "div.scroll-container"`
|
||||
|
||||
```bash
|
||||
# Auth vault
|
||||
echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin
|
||||
agent-browser auth login github
|
||||
|
||||
# Security flags
|
||||
agent-browser --content-boundaries --allowed-domains "example.com,*.example.com" --max-output 50000 open https://example.com
|
||||
|
||||
# Download path
|
||||
agent-browser --download-path ./downloads open https://example.com
|
||||
|
||||
# Scroll within container
|
||||
agent-browser scroll down 500 --selector "div.content"
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Six new environment variables for security configuration: `AGENT_BROWSER_CONTENT_BOUNDARIES`, `AGENT_BROWSER_MAX_OUTPUT`, `AGENT_BROWSER_ALLOWED_DOMAINS`, `AGENT_BROWSER_ACTION_POLICY`, `AGENT_BROWSER_CONFIRM_ACTIONS`, `AGENT_BROWSER_CONFIRM_INTERACTIVE`.
|
||||
|
||||
---
|
||||
|
||||
## v0.14.0
|
||||
|
||||
<p className="text-[#888] text-sm">February 2026</p>
|
||||
|
||||
### New Features
|
||||
|
||||
- **`keyboard` command** -- Type with real keystrokes, insert text, and press shortcuts at the currently focused element without needing a selector (`keyboard type`, `keyboard inserttext`).
|
||||
- **`--color-scheme` flag** -- Persistent dark/light mode preference across browser sessions via flag or `AGENT_BROWSER_COLOR_SCHEME` env var.
|
||||
|
||||
```bash
|
||||
agent-browser keyboard type "Hello world"
|
||||
agent-browser keyboard inserttext "pasted text"
|
||||
agent-browser --color-scheme dark open https://example.com
|
||||
```
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Fixed IPC EAGAIN errors (os error 35/11) with backpressure-aware socket writes, command serialization, and lowered default Playwright timeout to 25s (configurable via `AGENT_BROWSER_DEFAULT_TIMEOUT`).
|
||||
- Fixed remote debugging (CDP) reconnection.
|
||||
- Fixed state load failing when no browser is running.
|
||||
- Fixed `--annotate` flag warning appearing when not explicitly passed via CLI.
|
||||
|
||||
---
|
||||
|
||||
## v0.13.0
|
||||
|
||||
<p className="text-[#888] text-sm">February 2026</p>
|
||||
|
||||
### New Features
|
||||
|
||||
- **Diff commands** -- Compare snapshots, screenshots, and URLs between page states. Run visual pixel diffs against baseline images, compare accessibility tree snapshots with customizable depth and selectors, and diff two URLs side-by-side with optional screenshot comparison.
|
||||
|
||||
```bash
|
||||
agent-browser diff snapshot
|
||||
agent-browser diff screenshot --baseline before.png
|
||||
agent-browser diff url https://staging.example.com https://prod.example.com
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## v0.12.0
|
||||
|
||||
<p className="text-[#888] text-sm">February 2026</p>
|
||||
|
||||
### New Features
|
||||
|
||||
- **Annotated screenshots** -- `--annotate` flag overlays numbered labels on interactive elements and prints a legend mapping each label to its element ref. Enables multimodal AI models to reason about visual layout while using the same `@eN` refs for subsequent interactions. Also settable via `AGENT_BROWSER_ANNOTATE` env var.
|
||||
|
||||
```bash
|
||||
agent-browser screenshot --annotate
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## v0.11.1
|
||||
|
||||
<p className="text-[#888] text-sm">February 2026</p>
|
||||
|
||||
### Documentation
|
||||
|
||||
- Added documentation for command chaining with `&&` across README, CLI help output, docs, and skill files.
|
||||
|
||||
---
|
||||
|
||||
## v0.11.0
|
||||
|
||||
<p className="text-[#888] text-sm">February 2026</p>
|
||||
|
||||
### New Features
|
||||
|
||||
- **Configuration file support** -- Automatic loading from user (`~/.agent-browser/config.json`) and project (`./agent-browser.json`) directories with priority-based merging.
|
||||
- **Profiler commands** -- Chrome DevTools profiling with `profiler start` and `profiler stop`.
|
||||
- **Browser extension loading** -- `--extension` flag to load browser extensions.
|
||||
- **Storage state management** -- `state save` and `state load` commands for auth state persistence.
|
||||
- **iOS device emulation** -- `--device` flag for device emulation.
|
||||
- **Enhanced click** -- `--new-tab` option for click commands.
|
||||
- **Enhanced find** -- Additional actions and filtering options.
|
||||
- **CDP WebSocket URLs** -- `--cdp` now accepts WebSocket URLs in addition to ports.
|
||||
|
||||
---
|
||||
|
||||
## v0.10.0
|
||||
|
||||
<p className="text-[#888] text-sm">February 2026</p>
|
||||
|
||||
@@ -172,6 +172,14 @@ agent-browser storage local clear # Clear all
|
||||
agent-browser storage session # Same for sessionStorage
|
||||
```
|
||||
|
||||
For `cookies set`, use one of these patterns:
|
||||
|
||||
- `--url <url>`
|
||||
- `--domain <domain> --path <path>`
|
||||
- omit all three to scope from the current page URL
|
||||
|
||||
When `--url` is omitted, `--domain` and `--path` must be provided together.
|
||||
|
||||
## Network
|
||||
|
||||
```bash
|
||||
|
||||
@@ -6,7 +6,7 @@ export const metadata = pageMetadata('configuration');
|
||||
|
||||
Create an `agent-browser.json` file to set persistent defaults instead of repeating flags on every command.
|
||||
|
||||
In this fork, default launch behavior requires a resident browser at `localhost:9333` (CDP). If unavailable, commands fail fast instead of launching a managed browser.
|
||||
In this fork, default launch behavior auto-attaches to an existing browser by trying `localhost:9333` (CDP) first, then auto-discovery. If both fail, commands exit instead of launching a managed browser.
|
||||
|
||||
## Config File Locations
|
||||
|
||||
|
||||
+158
-115
@@ -1,117 +1,112 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@plugin "tailwindcss-animate";
|
||||
|
||||
@source "../../node_modules/streamdown/dist/index.js";
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@theme {
|
||||
--font-sans: "Inter", ui-sans-serif, system-ui, -apple-system, sans-serif;
|
||||
--font-mono: var(--font-geist-mono), ui-monospace, "SF Mono", "Cascadia Mono", "Segoe UI Mono", Menlo, Consolas, monospace;
|
||||
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-border: var(--border);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.5rem;
|
||||
--background: oklch(1.0 0 0);
|
||||
--foreground: oklch(0.1 0 0);
|
||||
--card: oklch(0.98 0 0);
|
||||
--card-foreground: oklch(0.1 0 0);
|
||||
--popover: oklch(0.98 0 0);
|
||||
--popover-foreground: oklch(0.1 0 0);
|
||||
--primary: oklch(0.1 0 0);
|
||||
--primary-foreground: oklch(1.0 0 0);
|
||||
--secondary: oklch(0.92 0 0);
|
||||
--secondary-foreground: oklch(0.1 0 0);
|
||||
--muted: oklch(0.92 0 0);
|
||||
--muted-foreground: oklch(0.45 0 0);
|
||||
--accent: oklch(0.92 0 0);
|
||||
--accent-foreground: oklch(0.1 0 0);
|
||||
--destructive: oklch(0.55 0.2 25);
|
||||
--destructive-foreground: oklch(1.0 0 0);
|
||||
--border: oklch(0.85 0 0);
|
||||
--input: oklch(0.85 0 0);
|
||||
--ring: oklch(0.6 0 0);
|
||||
--chat-bg: oklch(0.95 0 0);
|
||||
--background: #fff;
|
||||
--foreground: #171717;
|
||||
--border: #e5e5e5;
|
||||
--muted: #f5f5f5;
|
||||
--muted-foreground: #737373;
|
||||
--primary: #171717;
|
||||
--primary-foreground: #fff;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.0 0 0);
|
||||
--foreground: oklch(0.98 0 0);
|
||||
--card: oklch(0.08 0 0);
|
||||
--card-foreground: oklch(0.98 0 0);
|
||||
--popover: oklch(0.08 0 0);
|
||||
--popover-foreground: oklch(0.98 0 0);
|
||||
--primary: oklch(0.98 0 0);
|
||||
--primary-foreground: oklch(0.0 0 0);
|
||||
--secondary: oklch(0.15 0 0);
|
||||
--secondary-foreground: oklch(0.98 0 0);
|
||||
--muted: oklch(0.15 0 0);
|
||||
--muted-foreground: oklch(0.6 0 0);
|
||||
--accent: oklch(0.15 0 0);
|
||||
--accent-foreground: oklch(0.1 0 0);
|
||||
--destructive: oklch(0.65 0.2 25);
|
||||
--destructive-foreground: oklch(0.98 0 0);
|
||||
--border: oklch(0.25 0 0);
|
||||
--input: oklch(0.25 0 0);
|
||||
--ring: oklch(0.4 0 0);
|
||||
--chat-bg: oklch(0.25 0 0);
|
||||
--background: #0a0a0a;
|
||||
--foreground: #f5f5f5;
|
||||
--border: #262626;
|
||||
--muted: #262626;
|
||||
--muted-foreground: #a3a3a3;
|
||||
--primary: #f5f5f5;
|
||||
--primary-foreground: #0a0a0a;
|
||||
}
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--font-sans: var(--font-geist);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
* {
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-geist), system-ui, sans-serif;
|
||||
}
|
||||
|
||||
/* Hide page scrollbar */
|
||||
html {
|
||||
scrollbar-width: none;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
html::-webkit-scrollbar {
|
||||
display: none;
|
||||
::selection {
|
||||
background-color: #000;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
::selection {
|
||||
background-color: #fff;
|
||||
color: #000;
|
||||
}
|
||||
}
|
||||
|
||||
/* Article tables */
|
||||
article table {
|
||||
width: 100%;
|
||||
font-size: 0.875rem;
|
||||
margin-bottom: 1rem;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
article th {
|
||||
border-bottom: 1px solid #e5e5e5;
|
||||
padding: 0.5rem 0.75rem;
|
||||
text-align: left;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: #737373;
|
||||
}
|
||||
|
||||
article td {
|
||||
border-bottom: 1px solid #f5f5f5;
|
||||
padding: 0.5rem 0.75rem;
|
||||
color: #525252;
|
||||
}
|
||||
|
||||
:is(.dark) article th {
|
||||
border-bottom-color: #262626;
|
||||
color: #a3a3a3;
|
||||
}
|
||||
|
||||
:is(.dark) article td {
|
||||
border-bottom-color: rgba(38, 38, 38, 0.5);
|
||||
color: #a3a3a3;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Code blocks */
|
||||
pre {
|
||||
background: var(--card) !important;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
padding: 0.875rem;
|
||||
overflow-x: auto;
|
||||
font-family: var(--font-geist-mono), monospace;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
pre:not(.shiki) {
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.code-block pre {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -127,17 +122,26 @@ pre {
|
||||
}
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--font-geist-mono), monospace;
|
||||
}
|
||||
|
||||
:not(pre) > code {
|
||||
background: var(--card);
|
||||
background: var(--muted);
|
||||
padding: 0.125rem 0.375rem;
|
||||
border-radius: 3px;
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
/* Shiki dual theme support */
|
||||
.shiki,
|
||||
.shiki span {
|
||||
color: var(--shiki-light) !important;
|
||||
background-color: var(--shiki-light-bg) !important;
|
||||
}
|
||||
|
||||
.dark .shiki,
|
||||
.dark .shiki span {
|
||||
color: var(--shiki-dark) !important;
|
||||
background-color: var(--shiki-dark-bg) !important;
|
||||
}
|
||||
|
||||
/* Prose */
|
||||
.prose {
|
||||
max-width: 100%;
|
||||
@@ -145,9 +149,9 @@ code {
|
||||
|
||||
.prose h1 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 500;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.02em;
|
||||
margin-bottom: 0.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
@@ -158,59 +162,102 @@ code {
|
||||
}
|
||||
|
||||
.prose h2 {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
margin-top: 3rem;
|
||||
margin-bottom: 1rem;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.prose h2:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.prose h3 {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin-top: 2rem;
|
||||
margin-bottom: 0.75rem;
|
||||
color: var(--foreground);
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.prose p {
|
||||
margin-bottom: 1.25rem;
|
||||
line-height: 1.7;
|
||||
color: var(--muted-foreground);
|
||||
margin-bottom: 1rem;
|
||||
line-height: 1.65;
|
||||
color: #525252;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
:is(.dark) .prose p {
|
||||
color: #a3a3a3;
|
||||
}
|
||||
|
||||
.prose ul, .prose ol {
|
||||
margin-bottom: 1.25rem;
|
||||
margin-bottom: 1rem;
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
.prose ul {
|
||||
list-style-type: disc;
|
||||
}
|
||||
|
||||
.prose ol {
|
||||
list-style-type: decimal;
|
||||
}
|
||||
|
||||
.prose li {
|
||||
margin-bottom: 0.5rem;
|
||||
color: var(--muted-foreground);
|
||||
margin-bottom: 0.25rem;
|
||||
color: #525252;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
:is(.dark) .prose li {
|
||||
color: #a3a3a3;
|
||||
}
|
||||
|
||||
.prose li strong {
|
||||
color: var(--foreground);
|
||||
opacity: 0.85;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.prose a {
|
||||
color: var(--foreground);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: #d4d4d4;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.prose a:hover {
|
||||
text-decoration-color: var(--foreground);
|
||||
}
|
||||
|
||||
:is(.dark) .prose a {
|
||||
text-decoration-color: #525252;
|
||||
}
|
||||
|
||||
:is(.dark) .prose a:hover {
|
||||
text-decoration-color: var(--foreground);
|
||||
}
|
||||
|
||||
.prose strong {
|
||||
font-weight: 500;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.prose blockquote {
|
||||
margin-bottom: 1rem;
|
||||
border-left: 2px solid #e5e5e5;
|
||||
padding-left: 1rem;
|
||||
font-size: 0.875rem;
|
||||
color: #737373;
|
||||
}
|
||||
|
||||
:is(.dark) .prose blockquote {
|
||||
border-left-color: #525252;
|
||||
color: #a3a3a3;
|
||||
}
|
||||
|
||||
.prose table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
@@ -284,7 +331,3 @@ code {
|
||||
margin-top: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
+20
-19
@@ -1,18 +1,19 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import { Inter, Geist_Mono } from "next/font/google";
|
||||
import { GeistPixelSquare } from "geist/font/pixel";
|
||||
import "./globals.css";
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
import { MobileNavProvider } from "@/components/mobile-nav-context";
|
||||
import { Header } from "@/components/header";
|
||||
import { Sidebar } from "@/components/sidebar";
|
||||
import { DocsSidebar } from "@/components/docs-sidebar";
|
||||
import { DocsMobileNav } from "@/components/docs-mobile-nav";
|
||||
import { CopyPageButton } from "@/components/copy-page-button";
|
||||
import { DocsChat } from "@/components/docs-chat";
|
||||
import { cookies } from "next/headers";
|
||||
import { SpeedInsights } from "@vercel/speed-insights/next";
|
||||
import { Analytics } from "@vercel/analytics/next";
|
||||
|
||||
const geist = Geist({
|
||||
variable: "--font-geist",
|
||||
const inter = Inter({
|
||||
variable: "--font-inter",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
@@ -66,23 +67,23 @@ export default async function RootLayout({
|
||||
)}
|
||||
</head>
|
||||
<body
|
||||
className={`${geist.variable} ${geistMono.variable} ${GeistPixelSquare.variable} antialiased bg-background text-foreground`}
|
||||
className={`${inter.variable} ${geistMono.variable} ${GeistPixelSquare.variable} bg-white text-neutral-900 antialiased dark:bg-neutral-950 dark:text-neutral-100`}
|
||||
>
|
||||
<ThemeProvider>
|
||||
<MobileNavProvider>
|
||||
<Header />
|
||||
<div className="flex min-h-[calc(100vh-3.5rem)]">
|
||||
<Sidebar />
|
||||
<main className="flex-1 overflow-auto">
|
||||
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
|
||||
<div className="prose">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<Header />
|
||||
<DocsMobileNav />
|
||||
<div className="max-w-5xl mx-auto px-6 py-8 lg:py-12 flex gap-16">
|
||||
<aside className="w-48 shrink-0 hidden lg:block sticky top-28 h-[calc(100vh-7rem)] overflow-y-auto">
|
||||
<DocsSidebar />
|
||||
</aside>
|
||||
<div className="flex-1 min-w-0 max-w-2xl pb-20">
|
||||
<div className="flex justify-end mb-4">
|
||||
<CopyPageButton />
|
||||
</div>
|
||||
<article className="prose">{children}</article>
|
||||
</div>
|
||||
<DocsChat defaultOpen={chatOpen} defaultWidth={chatWidth} />
|
||||
</MobileNavProvider>
|
||||
</div>
|
||||
<DocsChat defaultOpen={chatOpen} defaultWidth={chatWidth} />
|
||||
</ThemeProvider>
|
||||
<SpeedInsights />
|
||||
<Analytics />
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("security")
|
||||
|
||||
# Security
|
||||
|
||||
agent-browser includes security features to protect against credential exposure, prompt injection via untrusted page content, and unauthorized browser actions.
|
||||
|
||||
All security features are opt-in. By default, agent-browser imposes no restrictions on navigation, actions, or output. Enable these features as needed for your deployment -- existing workflows are unaffected until you explicitly activate a feature.
|
||||
|
||||
## Threat Model
|
||||
|
||||
These features are designed to mitigate the following threats when an LLM-based agent drives a browser:
|
||||
|
||||
- **Credential exposure** -- Passwords stored in the auth vault are never included in LLM context. The CLI handles vault operations locally; credentials do not pass through the daemon's IPC channel.
|
||||
- **Prompt injection via page content** -- Malicious pages can embed text that looks like tool output or system instructions. Content boundary markers (`--content-boundaries`) let the orchestrator distinguish trusted tool output from untrusted page content.
|
||||
- **Unauthorized navigation / data exfiltration** -- A compromised or manipulated agent could navigate to attacker-controlled domains to exfiltrate data. The domain allowlist (`--allowed-domains`) blocks navigations, sub-resource requests, WebSocket connections, EventSource streams, and `sendBeacon` calls to non-allowed domains.
|
||||
- **Unauthorized destructive actions** -- Action policy (`--action-policy`) and confirmation gating (`--confirm-actions`) prevent the agent from performing dangerous operations (eval, downloads, uploads) without explicit approval.
|
||||
- **Context flooding** -- Large page outputs can overwhelm an LLM's context window. Output truncation (`--max-output`) caps the size of page-sourced content.
|
||||
|
||||
### Known limitations
|
||||
|
||||
- **WebSocket/EventSource blocking is best-effort.** It works by overriding browser constructors via an init script. If the `eval` action category is allowed, page scripts could theoretically restore the original constructors. Deny `eval` via `--action-policy` for maximum protection.
|
||||
- **Domain filter timing on remote connections.** When connecting to a pre-existing browser via CDP or a cloud provider, pages may have already loaded content before the domain filter is installed. agent-browser navigates disallowed pages to `about:blank` after the filter is active, but resources loaded before that point are not retroactively blocked.
|
||||
- **Content boundaries are defense-in-depth.** They rely on the LLM and orchestrator respecting the structural markers. A sufficiently capable adversarial page could attempt to mimic the boundary format, though the per-process CSPRNG nonce makes this impractical to predict.
|
||||
- **Confirmation timeout.** Pending confirmations auto-deny after 60 seconds. Orchestrators must respond within that window.
|
||||
- **Non-TTY auto-deny.** When `--confirm-interactive` is set but stdin is not a terminal (e.g., piped input), actions are automatically denied to prevent accidental approval in non-interactive contexts.
|
||||
|
||||
## Authentication Vault
|
||||
|
||||
Store credentials locally and reference them by name. The LLM never sees passwords.
|
||||
|
||||
```bash
|
||||
# Save credentials (encrypted if AGENT_BROWSER_ENCRYPTION_KEY is set)
|
||||
# Recommended: pipe password via stdin to avoid shell history / process listing exposure
|
||||
echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin
|
||||
|
||||
# Or pass directly (a warning will be shown)
|
||||
agent-browser auth save github --url https://github.com/login --username user --password pass
|
||||
|
||||
# Login using saved credentials
|
||||
agent-browser auth login github
|
||||
|
||||
# List saved profiles (names and URLs only, no secrets)
|
||||
agent-browser auth list
|
||||
|
||||
# Show profile metadata
|
||||
agent-browser auth show github
|
||||
|
||||
# Delete a profile
|
||||
agent-browser auth delete github
|
||||
```
|
||||
|
||||
Custom selectors can be specified if auto-detection fails:
|
||||
|
||||
```bash
|
||||
agent-browser auth save myapp \
|
||||
--url https://app.example.com/login \
|
||||
--username user --password pass \
|
||||
--username-selector "#email" \
|
||||
--password-selector "#password" \
|
||||
--submit-selector "button.login"
|
||||
```
|
||||
|
||||
Profiles are stored in `~/.agent-browser/auth/` and always encrypted with AES-256-GCM. If `AGENT_BROWSER_ENCRYPTION_KEY` is not set, a key is auto-generated at `~/.agent-browser/.encryption-key` on first use. Back up this file or set the environment variable explicitly for portability.
|
||||
|
||||
File permissions are enforced on both Unix (`chmod 600`/`700`) and Windows (`icacls` restricted to the current user) to prevent other users from reading encryption keys or auth profiles.
|
||||
|
||||
## Content Boundary Markers
|
||||
|
||||
When `--content-boundaries` is enabled, all page-sourced output is wrapped in structural markers so LLMs can distinguish tool output from untrusted page content:
|
||||
|
||||
```
|
||||
--- AGENT_BROWSER_PAGE_CONTENT nonce=a1b2c3d4 origin=https://example.com ---
|
||||
[snapshot / text / html / eval output here]
|
||||
--- END_AGENT_BROWSER_PAGE_CONTENT nonce=a1b2c3d4 ---
|
||||
```
|
||||
|
||||
The nonce is a random value generated per CLI process invocation, making it unpredictable to page content that might attempt to spoof the boundary.
|
||||
|
||||
Enable via flag or environment variable:
|
||||
|
||||
```bash
|
||||
agent-browser --content-boundaries snapshot
|
||||
# or
|
||||
export AGENT_BROWSER_CONTENT_BOUNDARIES=1
|
||||
```
|
||||
|
||||
Affected output types: `snapshot`, `get text`, `get html`, `eval`, `console`.
|
||||
|
||||
In `--json` mode, boundary metadata is injected into the JSON response as a `_boundary` object containing `nonce` and `origin` fields, allowing orchestrators to verify provenance programmatically:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": { "snapshot": "...", "origin": "https://example.com" },
|
||||
"_boundary": { "nonce": "a1b2c3d4e5f6...", "origin": "https://example.com" }
|
||||
}
|
||||
```
|
||||
|
||||
## Domain Allowlist
|
||||
|
||||
Restrict which domains the browser can interact with, preventing redirect-based attacks and data exfiltration:
|
||||
|
||||
```bash
|
||||
agent-browser --allowed-domains "example.com,*.example.com,github.com" open https://example.com
|
||||
# or
|
||||
export AGENT_BROWSER_ALLOWED_DOMAINS="example.com,*.example.com"
|
||||
```
|
||||
|
||||
Supports exact match (`github.com`) and wildcard prefix (`*.example.com`, which also matches the bare domain `example.com`). Both page navigations and sub-resource requests (scripts, images, fetch, XHR, etc.) to non-allowed domains are blocked, preventing data exfiltration. WebSocket and EventSource connections are also blocked via constructor-level patching. Non-http(s) sub-resources (data URIs, blobs) are still allowed. When a request is blocked, the command returns an error.
|
||||
|
||||
> **Note:** The WebSocket/EventSource blocking is best-effort -- it works by overriding the browser constructors via an init script. If the `eval` action category is allowed, page scripts could theoretically restore the original constructors. For maximum protection, deny the `eval` category via `--action-policy` when using `--allowed-domains`.
|
||||
|
||||
Config file:
|
||||
|
||||
```json
|
||||
{
|
||||
"allowedDomains": ["example.com", "*.example.com", "github.com"]
|
||||
}
|
||||
```
|
||||
|
||||
> **CDN and third-party resources:** The domain filter blocks all sub-resource requests (scripts, stylesheets, images, fonts, fetch/XHR) to non-allowed domains. Most websites load assets from CDN domains. Include these in your allowlist or pages will break. For example:
|
||||
>
|
||||
> ```bash
|
||||
> --allowed-domains "myapp.com,*.myapp.com,cdn.jsdelivr.net,fonts.googleapis.com,fonts.gstatic.com"
|
||||
> ```
|
||||
|
||||
## Action Policy
|
||||
|
||||
Gate actions using a static policy file. The policy is enforced by the daemon -- denied actions fail immediately.
|
||||
|
||||
```bash
|
||||
agent-browser --action-policy ./policy.json open https://example.com
|
||||
# or
|
||||
export AGENT_BROWSER_ACTION_POLICY=./policy.json
|
||||
```
|
||||
|
||||
Example policy (permissive with specific denials):
|
||||
|
||||
```json
|
||||
{
|
||||
"default": "allow",
|
||||
"deny": ["eval", "download", "upload"]
|
||||
}
|
||||
```
|
||||
|
||||
Example policy (restrictive):
|
||||
|
||||
```json
|
||||
{
|
||||
"default": "deny",
|
||||
"allow": ["navigate", "snapshot", "click", "scroll", "wait", "get"]
|
||||
}
|
||||
```
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Category</th><th>Actions</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><code>navigate</code></td><td>open, back, forward, reload, tab new</td></tr>
|
||||
<tr><td><code>click</code></td><td>click, dblclick, tap</td></tr>
|
||||
<tr><td><code>fill</code></td><td>fill, type, keyboard type/inserttext, select, check, uncheck</td></tr>
|
||||
<tr><td><code>eval</code></td><td>eval, evalhandle, addscript, addinitscript, addstyle, expose, setcontent</td></tr>
|
||||
<tr><td><code>download</code></td><td>download, waitfordownload</td></tr>
|
||||
<tr><td><code>upload</code></td><td>upload</td></tr>
|
||||
<tr><td><code>snapshot</code></td><td>snapshot, screenshot, pdf, diff</td></tr>
|
||||
<tr><td><code>scroll</code></td><td>scroll, scrollintoview</td></tr>
|
||||
<tr><td><code>wait</code></td><td>wait, waitforurl, waitforloadstate, waitforfunction</td></tr>
|
||||
<tr><td><code>get</code></td><td>get text/html/url/title, count, isvisible, getbyrole, getbytext, getbylabel, etc.</td></tr>
|
||||
<tr><td><code>interact</code></td><td>hover, focus, drag, press, keydown, keyup, mousemove, dispatch</td></tr>
|
||||
<tr><td><code>network</code></td><td>network route/unroute, requests</td></tr>
|
||||
<tr><td><code>state</code></td><td>state save/load, cookies set, storage set</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
Auth vault operations (`auth save`, `auth login`, `auth list`, `auth show`, `auth delete`) and other internal/meta operations bypass action policy enforcement since they are trusted local operations. Domain allowlist restrictions still apply to `auth login` navigations.
|
||||
|
||||
## Action Confirmation
|
||||
|
||||
For actions that require explicit approval, use `--confirm-actions` to specify categories that require confirmation:
|
||||
|
||||
```bash
|
||||
# Orchestrator mode: returns confirmation_required response
|
||||
agent-browser --confirm-actions eval,download eval "document.title"
|
||||
|
||||
# Then approve or deny:
|
||||
agent-browser confirm c_8f3a1234
|
||||
agent-browser deny c_8f3a1234
|
||||
```
|
||||
|
||||
For interactive (human-in-the-loop) confirmation:
|
||||
|
||||
```bash
|
||||
agent-browser --confirm-actions eval,download --confirm-interactive eval "document.title"
|
||||
# Prompts: Allow? [y/N]
|
||||
```
|
||||
|
||||
Pending confirmations auto-deny after 60 seconds.
|
||||
|
||||
> **Non-TTY behavior:** When `--confirm-interactive` is set but stdin is not a TTY (e.g., piped input or running inside an automated pipeline), actions are automatically denied. This prevents accidental approval in non-interactive contexts.
|
||||
|
||||
## Output Length Limits
|
||||
|
||||
Prevent context flooding by truncating large page outputs:
|
||||
|
||||
```bash
|
||||
agent-browser --max-output 50000 get text body
|
||||
# or
|
||||
export AGENT_BROWSER_MAX_OUTPUT=50000
|
||||
```
|
||||
|
||||
Affected output types: `snapshot`, `get text`, `get html`, `eval`, `console`.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Variable</th><th>Description</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><code>AGENT_BROWSER_CONTENT_BOUNDARIES</code></td><td>Wrap page output in boundary markers</td></tr>
|
||||
<tr><td><code>AGENT_BROWSER_MAX_OUTPUT</code></td><td>Max characters for page output</td></tr>
|
||||
<tr><td><code>AGENT_BROWSER_ALLOWED_DOMAINS</code></td><td>Comma-separated allowed domain patterns</td></tr>
|
||||
<tr><td><code>AGENT_BROWSER_ACTION_POLICY</code></td><td>Path to action policy JSON file</td></tr>
|
||||
<tr><td><code>AGENT_BROWSER_CONFIRM_ACTIONS</code></td><td>Comma-separated action categories requiring confirmation</td></tr>
|
||||
<tr><td><code>AGENT_BROWSER_CONFIRM_INTERACTIVE</code></td><td>Enable interactive confirmation prompts</td></tr>
|
||||
<tr><td><code>AGENT_BROWSER_ENCRYPTION_KEY</code></td><td>64-char hex key for AES-256-GCM encryption (auth vault + sessions)</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
## Recommended Configuration
|
||||
|
||||
For production AI agent deployments:
|
||||
|
||||
```json
|
||||
{
|
||||
"contentBoundaries": true,
|
||||
"maxOutput": 50000,
|
||||
"allowedDomains": ["your-app.com", "*.your-app.com"],
|
||||
"actionPolicy": "./policy.json"
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,60 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
|
||||
export const metadata = pageMetadata("skills")
|
||||
|
||||
# Skills
|
||||
|
||||
agent-browser ships with skills that teach AI coding agents how to use it for specific workflows. Install a skill and your agent in Cursor, Claude Code, or Codex can automate browser tasks without manual guidance.
|
||||
|
||||
## Available Skills
|
||||
|
||||
- **agent-browser** — General browser automation: navigation, snapshots, forms, screenshots, data extraction, sessions, authentication, diffing, and the full command reference.
|
||||
- **dogfood** — Systematic exploratory testing. Navigates an app like a real user, finds bugs and UX issues, and produces a structured report with screenshots and repro videos.
|
||||
- **electron** — Automate any Electron app (VS Code, Slack, Discord, Figma, etc.) by connecting to its built-in Chrome DevTools Protocol port. This is how agent-browser drives native desktop apps like the Slack macOS app.
|
||||
- **slack** — Browser-based Slack automation. Check unreads, navigate channels, search conversations, send messages, and extract data — no API tokens needed.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npx skills add vercel-labs/agent-browser --skill agent-browser
|
||||
npx skills add vercel-labs/agent-browser --skill dogfood
|
||||
npx skills add vercel-labs/agent-browser --skill electron
|
||||
npx skills add vercel-labs/agent-browser --skill slack
|
||||
```
|
||||
|
||||
After installing, your AI agent will automatically activate the right skill when it encounters a matching request.
|
||||
|
||||
## agent-browser
|
||||
|
||||
The core skill. Teaches agents the full agent-browser API: the navigate-snapshot-interact-re-snapshot workflow, all commands, command chaining, authentication (auth vault and state persistence), sessions, diffing, JavaScript evaluation, annotated screenshots, semantic locators, and configuration.
|
||||
|
||||
Example agent interactions:
|
||||
|
||||
- "Open example.com and fill out the contact form"
|
||||
- "Take a screenshot of the dashboard after logging in"
|
||||
- "Compare staging and production versions of the homepage"
|
||||
|
||||
## dogfood
|
||||
|
||||
A structured workflow for exploratory testing. The agent opens a target URL, systematically explores the app (navigating pages, testing forms, clicking buttons, checking console errors), and documents every issue it finds with:
|
||||
|
||||
- Numbered repro steps
|
||||
- Step-by-step screenshots
|
||||
- Repro videos for interactive bugs
|
||||
- Severity classification
|
||||
|
||||
The output is a markdown report in an output directory, ready to hand to the responsible team. Run it with a single prompt like "dogfood vercel.com" or "QA http://localhost:3000 — focus on the billing page".
|
||||
|
||||
## electron
|
||||
|
||||
Electron apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) are built on Chromium and expose a Chrome DevTools Protocol (CDP) port that agent-browser can connect to. This skill teaches agents how to launch or connect to any Electron app, then use the standard snapshot-interact workflow to automate it.
|
||||
|
||||
Electron apps are built on Chromium, so they expose a Chrome DevTools Protocol (CDP) port that agent-browser can connect to. Launch the app with `--remote-debugging-port`, connect, and use the standard snapshot-interact workflow. This is the foundation that the **slack** skill builds on.
|
||||
|
||||
## slack
|
||||
|
||||
Browser-based Slack automation. Connects to an existing Slack session (via `agent-browser connect 9222`) or opens Slack in a new browser, then uses snapshots and element refs to navigate the UI. Covers checking unreads, navigating channels and DMs, searching conversations, extracting message data, and taking screenshots — all without needing Slack API tokens or bot setup.
|
||||
|
||||
## Source
|
||||
|
||||
All skill files are in the [`skills/`](https://github.com/vercel-labs/agent-browser/tree/main/skills) directory of the repository.
|
||||
@@ -10,7 +10,10 @@ export async function CodeBlock({ code, lang = "bash" }: CodeBlockProps) {
|
||||
const trimmedCode = code.trim();
|
||||
const html = await codeToHtml(trimmedCode, {
|
||||
lang,
|
||||
theme: "github-dark-default",
|
||||
themes: {
|
||||
light: "github-light-default",
|
||||
dark: "github-dark-default",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
export function CopyPageButton() {
|
||||
const pathname = usePathname();
|
||||
const [state, setState] = useState<"idle" | "loading" | "copied">("idle");
|
||||
|
||||
const handleCopy = async () => {
|
||||
setState("loading");
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/docs-markdown?path=${encodeURIComponent(pathname)}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch markdown");
|
||||
}
|
||||
const markdown = await response.text();
|
||||
await navigator.clipboard.writeText(markdown);
|
||||
setState("copied");
|
||||
setTimeout(() => setState("idle"), 2000);
|
||||
} catch {
|
||||
setState("idle");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
disabled={state === "loading"}
|
||||
className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs text-muted-foreground hover:text-foreground border border-border rounded-md hover:bg-muted transition-colors disabled:opacity-50"
|
||||
aria-label="Copy page as Markdown"
|
||||
>
|
||||
{state === "copied" ? (
|
||||
<>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<polyline points="20 6 9 17 4 12" />
|
||||
</svg>
|
||||
Copied
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
|
||||
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
|
||||
</svg>
|
||||
Copy Page
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -494,7 +494,7 @@ export function DocsChat({
|
||||
{!open && (
|
||||
<button
|
||||
onClick={() => setOpen(true)}
|
||||
className="fixed z-50 bottom-4 left-1/2 -translate-x-1/2 sm:left-auto sm:translate-x-0 sm:right-4 flex items-center gap-2 px-4 py-2 rounded-lg border bg-background text-primary shadow-lg hover:bg-primary hover:text-primary-foreground transition-colors text-sm font-medium"
|
||||
className="fixed z-50 bottom-4 left-1/2 -translate-x-1/2 sm:left-auto sm:translate-x-0 sm:right-4 flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground shadow-lg hover:opacity-90 transition-opacity text-sm font-medium"
|
||||
aria-label="Ask AI"
|
||||
>
|
||||
Ask AI
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useMemo } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetContent,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { navigation, allDocsPages } from "@/lib/docs-navigation";
|
||||
|
||||
export function DocsMobileNav() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const pathname = usePathname();
|
||||
|
||||
const currentPage = useMemo(() => {
|
||||
const page = allDocsPages.find((p) => p.href === pathname);
|
||||
return page ?? allDocsPages[0];
|
||||
}, [pathname]);
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger className="lg:hidden sticky top-14 z-40 w-full px-6 py-3 bg-background/80 backdrop-blur-sm border-b border-border flex items-center justify-between focus:outline-none">
|
||||
<div className="text-sm font-medium">{currentPage?.name}</div>
|
||||
<div className="w-8 h-8 flex items-center justify-center">
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="text-muted-foreground"
|
||||
>
|
||||
<line x1="8" y1="6" x2="21" y2="6" />
|
||||
<line x1="8" y1="12" x2="21" y2="12" />
|
||||
<line x1="8" y1="18" x2="21" y2="18" />
|
||||
<line x1="3" y1="6" x2="3.01" y2="6" />
|
||||
<line x1="3" y1="12" x2="3.01" y2="12" />
|
||||
<line x1="3" y1="18" x2="3.01" y2="18" />
|
||||
</svg>
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="left" showCloseButton={false} className="overflow-y-auto p-6">
|
||||
<SheetTitle className="mb-6">Table of Contents</SheetTitle>
|
||||
<nav className="space-y-6">
|
||||
{navigation.map((section, sectionIndex) => (
|
||||
<div key={section.title ?? sectionIndex}>
|
||||
{section.title && (
|
||||
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">
|
||||
{section.title}
|
||||
</h4>
|
||||
)}
|
||||
<ul className="space-y-1">
|
||||
{section.items.map((item) => (
|
||||
<li key={item.href}>
|
||||
<Link
|
||||
href={item.href}
|
||||
onClick={() => setOpen(false)}
|
||||
className={`text-sm block py-2 transition-colors ${
|
||||
pathname === item.href
|
||||
? "text-primary font-medium"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { navigation } from "@/lib/docs-navigation";
|
||||
|
||||
export function DocsSidebar() {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<nav className="space-y-6 pb-8">
|
||||
{navigation.map((section, sectionIndex) => (
|
||||
<div key={section.title ?? sectionIndex}>
|
||||
{section.title && (
|
||||
<h4 className="text-xs font-normal text-muted-foreground/50 uppercase tracking-wider mb-2">
|
||||
{section.title}
|
||||
</h4>
|
||||
)}
|
||||
<ul className="space-y-1">
|
||||
{section.items.map((item) => {
|
||||
const isActive = pathname === item.href;
|
||||
return (
|
||||
<li key={item.href}>
|
||||
<Link
|
||||
href={item.href}
|
||||
className={cn(
|
||||
"text-sm transition-colors block py-1",
|
||||
isActive
|
||||
? "text-primary font-medium"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useMobileNav } from "./mobile-nav-context";
|
||||
import { ThemeToggle } from "./theme-toggle";
|
||||
|
||||
export function Header() {
|
||||
const { isOpen, toggle } = useMobileNav();
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-50 bg-background/90 backdrop-blur-sm">
|
||||
<header className="sticky top-0 z-50 bg-white/90 backdrop-blur-sm dark:bg-neutral-950/90">
|
||||
<div className="flex h-14 items-center justify-between px-4 gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href="https://vercel.com" title="Made with love by Vercel">
|
||||
@@ -25,10 +22,10 @@ export function Header() {
|
||||
clipRule="evenodd"
|
||||
d="M8 1L16 15H0L8 1Z"
|
||||
fill="currentColor"
|
||||
></path>
|
||||
/>
|
||||
</svg>
|
||||
</Link>
|
||||
<span className="text-border">
|
||||
<span className="text-neutral-300 dark:text-neutral-700">
|
||||
<svg
|
||||
data-testid="geist-icon"
|
||||
height="16"
|
||||
@@ -42,11 +39,14 @@ export function Header() {
|
||||
clipRule="evenodd"
|
||||
d="M4.01526 15.3939L4.3107 14.7046L10.3107 0.704556L10.6061 0.0151978L11.9849 0.606077L11.6894 1.29544L5.68942 15.2954L5.39398 15.9848L4.01526 15.3939Z"
|
||||
fill="currentColor"
|
||||
></path>
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<Link href="/">
|
||||
<span className="font-medium tracking-tight text-lg" style={{ fontFamily: "var(--font-geist-pixel-square)" }}>
|
||||
<span
|
||||
className="font-medium tracking-tight text-lg"
|
||||
style={{ fontFamily: "var(--font-geist-pixel-square)" }}
|
||||
>
|
||||
agent-browser
|
||||
</span>
|
||||
</Link>
|
||||
@@ -56,7 +56,7 @@ export function Header() {
|
||||
href="https://github.com/leeguooooo/agent-browser"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="hidden sm:flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
className="flex items-center gap-1.5 text-sm text-neutral-500 hover:text-neutral-900 transition-colors dark:text-neutral-400 dark:hover:text-neutral-100"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 16 16"
|
||||
@@ -66,32 +66,17 @@ export function Header() {
|
||||
>
|
||||
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />
|
||||
</svg>
|
||||
<span>14k</span>
|
||||
<span>16k</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://www.npmjs.com/package/agent-browser-stealth"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="hidden sm:block text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
className="text-sm text-neutral-500 hover:text-neutral-900 transition-colors dark:text-neutral-400 dark:hover:text-neutral-100"
|
||||
>
|
||||
npm
|
||||
</a>
|
||||
<ThemeToggle />
|
||||
<button
|
||||
onClick={toggle}
|
||||
className="lg:hidden p-2 -mr-2 text-muted-foreground hover:text-foreground transition-colors"
|
||||
aria-label="Toggle menu"
|
||||
>
|
||||
{isOpen ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 6h16M4 12h16M4 18h16" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useState, useEffect } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
type MobileNavContextType = {
|
||||
isOpen: boolean;
|
||||
setIsOpen: (open: boolean) => void;
|
||||
toggle: () => void;
|
||||
};
|
||||
|
||||
const MobileNavContext = createContext<MobileNavContextType | null>(null);
|
||||
|
||||
export function MobileNavProvider({ children }: { children: React.ReactNode }) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const pathname = usePathname();
|
||||
|
||||
useEffect(() => {
|
||||
setIsOpen(false);
|
||||
}, [pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setIsOpen(false);
|
||||
};
|
||||
document.addEventListener("keydown", handleEscape);
|
||||
return () => document.removeEventListener("keydown", handleEscape);
|
||||
}, []);
|
||||
|
||||
const toggle = () => setIsOpen(!isOpen);
|
||||
|
||||
return (
|
||||
<MobileNavContext.Provider value={{ isOpen, setIsOpen, toggle }}>
|
||||
{children}
|
||||
</MobileNavContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useMobileNav() {
|
||||
const context = useContext(MobileNavContext);
|
||||
if (!context) {
|
||||
throw new Error("useMobileNav must be used within a MobileNavProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useMobileNav } from "./mobile-nav-context";
|
||||
import { navigation } from "@/lib/docs-navigation";
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const { isOpen, setIsOpen } = useMobileNav();
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile overlay */}
|
||||
{isOpen && (
|
||||
<div
|
||||
className="lg:hidden fixed inset-0 z-40 bg-background/80"
|
||||
onClick={() => setIsOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Sidebar */}
|
||||
<aside
|
||||
className={`
|
||||
fixed lg:sticky top-14 left-0 z-50 lg:z-auto
|
||||
w-56 lg:w-48 h-[calc(100vh-3.5rem)]
|
||||
bg-background
|
||||
transform transition-transform duration-150 ease-out
|
||||
${isOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"}
|
||||
`}
|
||||
>
|
||||
<div className="h-full overflow-y-auto py-5 pl-3 pr-5">
|
||||
<nav className="space-y-4">
|
||||
{navigation.map((section, sectionIndex) => (
|
||||
<div key={section.title ?? sectionIndex}>
|
||||
{section.title && (
|
||||
<div className="px-2 pb-1 text-xs font-medium text-muted-foreground/60 uppercase tracking-wider">
|
||||
{section.title}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-0.5">
|
||||
{section.items.map((item) => {
|
||||
const isActive = pathname === item.href;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={`block px-2 py-1.5 text-sm transition-colors ${
|
||||
isActive
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -18,7 +18,7 @@ export function ThemeToggle() {
|
||||
return (
|
||||
<button
|
||||
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
|
||||
className="w-8 h-8 flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
|
||||
className="w-8 h-8 flex items-center justify-center rounded-md text-neutral-500 hover:text-neutral-900 hover:bg-neutral-100 transition-colors dark:text-neutral-400 dark:hover:text-neutral-100 dark:hover:bg-neutral-800"
|
||||
aria-label="Toggle theme"
|
||||
>
|
||||
{theme === "dark" ? (
|
||||
|
||||
@@ -15,6 +15,7 @@ export const navigation: NavSection[] = [
|
||||
{ name: "Introduction", href: "/" },
|
||||
{ name: "Installation", href: "/installation" },
|
||||
{ name: "Quick Start", href: "/quick-start" },
|
||||
{ name: "Skills", href: "/skills" },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -35,6 +36,7 @@ export const navigation: NavSection[] = [
|
||||
{ name: "Streaming", href: "/streaming" },
|
||||
{ name: "Profiler", href: "/profiler" },
|
||||
{ name: "iOS Simulator", href: "/ios" },
|
||||
{ name: "Security", href: "/security" },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
/**
|
||||
* Converts raw MDX content to clean Markdown suitable for AI agents.
|
||||
*
|
||||
* Transformations:
|
||||
* - Remove `export` statements (metadata, etc.)
|
||||
* - Remove `import` statements
|
||||
* - Strip standalone JSX divs with className attributes
|
||||
* - Pass everything else through as-is (already valid Markdown)
|
||||
* Strips export/import statements and standalone JSX divs with className
|
||||
* attributes, passing everything else through as valid Markdown.
|
||||
*/
|
||||
export function mdxToCleanMarkdown(raw: string): string {
|
||||
const lines = raw.split("\n");
|
||||
@@ -16,12 +13,10 @@ export function mdxToCleanMarkdown(raw: string): string {
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
|
||||
// Skip export and import statements
|
||||
if (trimmed.startsWith("export ") || trimmed.startsWith("import ")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Track JSX blocks (like callout divs) and skip them
|
||||
if (
|
||||
!inJsxBlock &&
|
||||
trimmed.startsWith("<div ") &&
|
||||
@@ -33,7 +28,6 @@ export function mdxToCleanMarkdown(raw: string): string {
|
||||
}
|
||||
|
||||
if (inJsxBlock) {
|
||||
// Count opening/closing div tags to handle nesting
|
||||
const opens = (line.match(/<div[\s>]/g) || []).length;
|
||||
const closes = (line.match(/<\/div>/g) || []).length;
|
||||
jsxDepth += opens - closes;
|
||||
@@ -47,7 +41,6 @@ export function mdxToCleanMarkdown(raw: string): string {
|
||||
out.push(line);
|
||||
}
|
||||
|
||||
// Clean up leading blank lines
|
||||
let result = out.join("\n");
|
||||
result = result.replace(/^\n+/, "\n").trim();
|
||||
return result;
|
||||
|
||||
@@ -2,6 +2,7 @@ export const PAGE_TITLES: Record<string, string> = {
|
||||
"": "Headless Browser\nAutomation for AI",
|
||||
installation: "Installation",
|
||||
"quick-start": "Quick Start",
|
||||
skills: "Skills",
|
||||
commands: "Commands",
|
||||
configuration: "Configuration",
|
||||
selectors: "Selectors",
|
||||
@@ -12,6 +13,7 @@ export const PAGE_TITLES: Record<string, string> = {
|
||||
streaming: "Streaming",
|
||||
profiler: "Profiler",
|
||||
ios: "iOS Simulator",
|
||||
security: "Security",
|
||||
changelog: "Changelog",
|
||||
};
|
||||
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agent-browser-stealth",
|
||||
"version": "0.14.0-fork.5",
|
||||
"version": "0.15.2-fork.0",
|
||||
"description": "Stealth browser automation CLI for AI agents with anti-bot evasions",
|
||||
"type": "module",
|
||||
"main": "dist/daemon.js",
|
||||
@@ -35,12 +35,13 @@
|
||||
"test:watch": "vitest",
|
||||
"test:e2e:dogfood": "vitest run test/e2e/dogfood.eval.ts",
|
||||
"postinstall": "node scripts/postinstall.js",
|
||||
"verify:native-version": "node scripts/verify-native-version.js",
|
||||
"clawhub:sync": "bash scripts/clawhub-sync.sh",
|
||||
"sync:upstream": "bash scripts/sync-upstream.sh",
|
||||
"sync:upstream:push": "bash scripts/sync-upstream.sh --push",
|
||||
"changeset": "changeset",
|
||||
"ci:version": "changeset version && pnpm run version:sync && pnpm install --no-frozen-lockfile",
|
||||
"ci:publish": "pnpm run version:sync && pnpm run build && changeset publish"
|
||||
"ci:publish": "pnpm run version:sync && pnpm run build && pnpm run build:native && pnpm run verify:native-version && changeset publish"
|
||||
},
|
||||
"keywords": [
|
||||
"browser",
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Verifies that the bundled native binary version matches package.json version.
|
||||
* This prevents publishing npm tarballs where package version and native binary
|
||||
* version drift (e.g. package is fork.8 but binary still reports fork.7).
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { arch, platform } from 'os';
|
||||
import { execFileSync } from 'child_process';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const projectRoot = join(__dirname, '..');
|
||||
|
||||
const pkg = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
|
||||
const expectedVersion = pkg.version;
|
||||
|
||||
const ext = platform() === 'win32' ? '.exe' : '';
|
||||
const platformBinary = join(projectRoot, 'bin', `agent-browser-${platform()}-${arch()}${ext}`);
|
||||
|
||||
if (!existsSync(platformBinary)) {
|
||||
console.error(`Error: native binary not found for current platform: ${platformBinary}`);
|
||||
console.error('Run `pnpm run build:native` before publishing.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let versionOutput = '';
|
||||
try {
|
||||
versionOutput = execFileSync(platformBinary, ['--version'], {
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
}).trim();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(`Error: failed to execute native binary --version: ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!versionOutput.includes(expectedVersion)) {
|
||||
console.error(`Version mismatch: package.json=${expectedVersion}, native='${versionOutput}'.`);
|
||||
console.error('Run `pnpm run build:native` and retry publishing.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`✓ Native binary version matches package.json (${expectedVersion})`);
|
||||
@@ -18,12 +18,12 @@ Use this skill when the task needs web automation and anti-bot stability.
|
||||
## Install and baseline
|
||||
|
||||
```bash
|
||||
npm install -g agent-browser-stealth
|
||||
pnpm add -g agent-browser-stealth
|
||||
agent-browser install
|
||||
agent-browser --version
|
||||
```
|
||||
|
||||
If default CDP mode is used in your environment, ensure a browser is available at `localhost:9333`, or pass `--cdp` / `--auto-connect` explicitly.
|
||||
If default CDP mode is used in your environment, the CLI first tries `localhost:9333` and then auto-discovery. You can still pass `--cdp` / `--auto-connect` explicitly when needed.
|
||||
|
||||
## Standard execution workflow
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ allowed-tools: Bash(npx agent-browser-stealth:*), Bash(npx agent-browser:*), Bas
|
||||
|
||||
# Browser Automation with agent-browser
|
||||
|
||||
Install package: `npm install -g agent-browser-stealth` (CLI command remains `agent-browser` for compatibility).
|
||||
Install package: `pnpm add -g agent-browser-stealth` (CLI command remains `agent-browser` for compatibility). If global install is unavailable in your environment, use `pnpm dlx agent-browser-stealth <command>` for one-off runs.
|
||||
|
||||
## Core Workflow
|
||||
|
||||
@@ -120,6 +120,22 @@ agent-browser click @e5
|
||||
agent-browser wait --load networkidle
|
||||
```
|
||||
|
||||
### Authentication with Auth Vault (Recommended)
|
||||
|
||||
```bash
|
||||
# Save credentials once (encrypted with AGENT_BROWSER_ENCRYPTION_KEY)
|
||||
# Recommended: pipe password via stdin to avoid shell history exposure
|
||||
echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin
|
||||
|
||||
# Login using saved profile (LLM never sees password)
|
||||
agent-browser auth login github
|
||||
|
||||
# List/show/delete profiles
|
||||
agent-browser auth list
|
||||
agent-browser auth show github
|
||||
agent-browser auth delete github
|
||||
```
|
||||
|
||||
### Authentication with State Persistence
|
||||
|
||||
```bash
|
||||
@@ -137,6 +153,20 @@ agent-browser state load auth.json
|
||||
agent-browser open https://app.example.com/dashboard
|
||||
```
|
||||
|
||||
### Cookie Injection for Auth Callbacks
|
||||
|
||||
```bash
|
||||
# Before navigation: set by URL
|
||||
agent-browser cookies set session_id "abc123" --url https://app.example.com/api/auth/sso/callback
|
||||
|
||||
# Explicit domain/path pair (must be provided together)
|
||||
agent-browser cookies set auth_token "xyz789" --domain .example.com --path /api
|
||||
|
||||
# Or navigate first and rely on current URL
|
||||
agent-browser open https://app.example.com/api/auth/sso/callback
|
||||
agent-browser cookies set callback_token "token123"
|
||||
```
|
||||
|
||||
### Session Persistence
|
||||
|
||||
```bash
|
||||
@@ -186,7 +216,11 @@ agent-browser session list
|
||||
|
||||
### Connect to Existing Chrome
|
||||
|
||||
By default in this fork, commands without `--cdp` require an existing browser at `localhost:9333`. If CDP is unavailable, the command fails fast (no automatic local browser launch).
|
||||
By default in this fork, commands without `--cdp` auto-attach to your existing browser with this order:
|
||||
|
||||
1. Try CDP at `localhost:9333`
|
||||
2. If unavailable, fall back to `--auto-connect`-style discovery
|
||||
3. If both fail, exit with guidance (no automatic managed local browser launch on this path)
|
||||
|
||||
```bash
|
||||
# Auto-discover running Chrome with remote debugging enabled
|
||||
@@ -195,6 +229,9 @@ agent-browser --auto-connect snapshot
|
||||
|
||||
# Or with explicit CDP port
|
||||
agent-browser --cdp 9222 snapshot
|
||||
|
||||
# Debug auto-attach behavior
|
||||
agent-browser --debug snapshot
|
||||
```
|
||||
|
||||
### Color Scheme (Dark Mode)
|
||||
@@ -233,7 +270,7 @@ agent-browser screenshot output.png
|
||||
|
||||
- `--profile` / `AGENT_BROWSER_PROFILE` are forbidden
|
||||
- `--channel` / `AGENT_BROWSER_CHANNEL` are forbidden
|
||||
- Use existing browser sessions (default CDP `localhost:9333`) or pass `--cdp` explicitly
|
||||
- Use existing browser sessions (default attach path: CDP `localhost:9333` then auto-discovery) or pass `--cdp` explicitly
|
||||
|
||||
### Stealth Mode (Always On)
|
||||
|
||||
@@ -291,6 +328,57 @@ agent-browser -p ios close
|
||||
|
||||
**Real devices:** Works with physical iOS devices if pre-configured. Use `--device "<UDID>"` where UDID is from `xcrun xctrace list devices`.
|
||||
|
||||
## Security
|
||||
|
||||
All security features are opt-in. By default, agent-browser imposes no restrictions on navigation, actions, or output.
|
||||
|
||||
### Content Boundaries (Recommended for AI Agents)
|
||||
|
||||
Enable `--content-boundaries` to wrap page-sourced output in markers that help LLMs distinguish tool output from untrusted page content:
|
||||
|
||||
```bash
|
||||
export AGENT_BROWSER_CONTENT_BOUNDARIES=1
|
||||
agent-browser snapshot
|
||||
# Output:
|
||||
# --- AGENT_BROWSER_PAGE_CONTENT nonce=<hex> origin=https://example.com ---
|
||||
# [accessibility tree]
|
||||
# --- END_AGENT_BROWSER_PAGE_CONTENT nonce=<hex> ---
|
||||
```
|
||||
|
||||
### Domain Allowlist
|
||||
|
||||
Restrict navigation to trusted domains. Wildcards like `*.example.com` also match the bare domain `example.com`. Sub-resource requests, WebSocket, and EventSource connections to non-allowed domains are also blocked. Include CDN domains your target pages depend on:
|
||||
|
||||
```bash
|
||||
export AGENT_BROWSER_ALLOWED_DOMAINS="example.com,*.example.com"
|
||||
agent-browser open https://example.com # OK
|
||||
agent-browser open https://malicious.com # Blocked
|
||||
```
|
||||
|
||||
### Action Policy
|
||||
|
||||
Use a policy file to gate destructive actions:
|
||||
|
||||
```bash
|
||||
export AGENT_BROWSER_ACTION_POLICY=./policy.json
|
||||
```
|
||||
|
||||
Example `policy.json`:
|
||||
|
||||
```json
|
||||
{ "default": "deny", "allow": ["navigate", "snapshot", "click", "scroll", "wait", "get"] }
|
||||
```
|
||||
|
||||
Auth vault operations (`auth login`, etc.) bypass action policy but domain allowlist still applies.
|
||||
|
||||
### Output Limits
|
||||
|
||||
Prevent context flooding from large pages:
|
||||
|
||||
```bash
|
||||
export AGENT_BROWSER_MAX_OUTPUT=50000
|
||||
```
|
||||
|
||||
## Diffing (Verifying Changes)
|
||||
|
||||
Use `diff snapshot` after performing an action to verify it had the intended effect. This compares the current accessibility tree against the last snapshot taken in the session.
|
||||
|
||||
@@ -3,6 +3,11 @@
|
||||
# Purpose: Login once, save state, reuse for subsequent runs
|
||||
# Usage: ./authenticated-session.sh <login-url> [state-file]
|
||||
#
|
||||
# RECOMMENDED: Use the auth vault instead of this template:
|
||||
# echo "<pass>" | agent-browser auth save myapp --url <login-url> --username <user> --password-stdin
|
||||
# agent-browser auth login myapp
|
||||
# The auth vault stores credentials securely and the LLM never sees passwords.
|
||||
#
|
||||
# Environment variables:
|
||||
# APP_USERNAME - Login username/email
|
||||
# APP_PASSWORD - Login password
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
---
|
||||
name: electron
|
||||
description: Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include "automate Slack app", "control VS Code", "interact with Discord app", "test this Electron app", "connect to desktop app", or any task requiring automation of a native Electron application.
|
||||
allowed-tools: Bash(agent-browser:*), Bash(npx agent-browser:*)
|
||||
---
|
||||
|
||||
# Electron App Automation
|
||||
|
||||
Automate any Electron desktop app using agent-browser. Electron apps are built on Chromium and expose a Chrome DevTools Protocol (CDP) port that agent-browser can connect to, enabling the same snapshot-interact workflow used for web pages.
|
||||
|
||||
## Core Workflow
|
||||
|
||||
1. **Launch** the Electron app with remote debugging enabled
|
||||
2. **Connect** agent-browser to the CDP port
|
||||
3. **Snapshot** to discover interactive elements
|
||||
4. **Interact** using element refs
|
||||
5. **Re-snapshot** after navigation or state changes
|
||||
|
||||
```bash
|
||||
# Launch an Electron app with remote debugging
|
||||
open -a "Slack" --args --remote-debugging-port=9222
|
||||
|
||||
# Connect agent-browser to the app
|
||||
agent-browser connect 9222
|
||||
|
||||
# Standard workflow from here
|
||||
agent-browser snapshot -i
|
||||
agent-browser click @e5
|
||||
agent-browser screenshot slack-desktop.png
|
||||
```
|
||||
|
||||
## Launching Electron Apps with CDP
|
||||
|
||||
Every Electron app supports the `--remote-debugging-port` flag since it's built into Chromium.
|
||||
|
||||
### macOS
|
||||
|
||||
```bash
|
||||
# Slack
|
||||
open -a "Slack" --args --remote-debugging-port=9222
|
||||
|
||||
# VS Code
|
||||
open -a "Visual Studio Code" --args --remote-debugging-port=9223
|
||||
|
||||
# Discord
|
||||
open -a "Discord" --args --remote-debugging-port=9224
|
||||
|
||||
# Figma
|
||||
open -a "Figma" --args --remote-debugging-port=9225
|
||||
|
||||
# Notion
|
||||
open -a "Notion" --args --remote-debugging-port=9226
|
||||
|
||||
# Spotify
|
||||
open -a "Spotify" --args --remote-debugging-port=9227
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
```bash
|
||||
slack --remote-debugging-port=9222
|
||||
code --remote-debugging-port=9223
|
||||
discord --remote-debugging-port=9224
|
||||
```
|
||||
|
||||
### Windows
|
||||
|
||||
```bash
|
||||
"C:\Users\%USERNAME%\AppData\Local\slack\slack.exe" --remote-debugging-port=9222
|
||||
"C:\Users\%USERNAME%\AppData\Local\Programs\Microsoft VS Code\Code.exe" --remote-debugging-port=9223
|
||||
```
|
||||
|
||||
**Important:** If the app is already running, quit it first, then relaunch with the flag. The `--remote-debugging-port` flag must be present at launch time.
|
||||
|
||||
## Connecting
|
||||
|
||||
```bash
|
||||
# Connect to a specific port
|
||||
agent-browser connect 9222
|
||||
|
||||
# Or use --cdp on each command
|
||||
agent-browser --cdp 9222 snapshot -i
|
||||
|
||||
# Auto-discover a running Chromium-based app
|
||||
agent-browser --auto-connect snapshot -i
|
||||
```
|
||||
|
||||
After `connect`, all subsequent commands target the connected app without needing `--cdp`.
|
||||
|
||||
## Tab Management
|
||||
|
||||
Electron apps often have multiple windows or webviews. Use tab commands to list and switch between them:
|
||||
|
||||
```bash
|
||||
# List all available targets (windows, webviews, etc.)
|
||||
agent-browser tab
|
||||
|
||||
# Switch to a specific tab by index
|
||||
agent-browser tab 2
|
||||
|
||||
# Switch by URL pattern
|
||||
agent-browser tab --url "*settings*"
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Inspect and Navigate an App
|
||||
|
||||
```bash
|
||||
open -a "Slack" --args --remote-debugging-port=9222
|
||||
sleep 3 # Wait for app to start
|
||||
agent-browser connect 9222
|
||||
agent-browser snapshot -i
|
||||
# Read the snapshot output to identify UI elements
|
||||
agent-browser click @e10 # Navigate to a section
|
||||
agent-browser snapshot -i # Re-snapshot after navigation
|
||||
```
|
||||
|
||||
### Take Screenshots of Desktop Apps
|
||||
|
||||
```bash
|
||||
agent-browser connect 9222
|
||||
agent-browser screenshot app-state.png
|
||||
agent-browser screenshot --full full-app.png
|
||||
agent-browser screenshot --annotate annotated-app.png
|
||||
```
|
||||
|
||||
### Extract Data from a Desktop App
|
||||
|
||||
```bash
|
||||
agent-browser connect 9222
|
||||
agent-browser snapshot -i
|
||||
agent-browser get text @e5
|
||||
agent-browser snapshot --json > app-state.json
|
||||
```
|
||||
|
||||
### Fill Forms in Desktop Apps
|
||||
|
||||
```bash
|
||||
agent-browser connect 9222
|
||||
agent-browser snapshot -i
|
||||
agent-browser fill @e3 "search query"
|
||||
agent-browser press Enter
|
||||
agent-browser wait 1000
|
||||
agent-browser snapshot -i
|
||||
```
|
||||
|
||||
### Run Multiple Apps Simultaneously
|
||||
|
||||
Use named sessions to control multiple Electron apps at the same time:
|
||||
|
||||
```bash
|
||||
# Connect to Slack
|
||||
agent-browser --session slack connect 9222
|
||||
|
||||
# Connect to VS Code
|
||||
agent-browser --session vscode connect 9223
|
||||
|
||||
# Interact with each independently
|
||||
agent-browser --session slack snapshot -i
|
||||
agent-browser --session vscode snapshot -i
|
||||
```
|
||||
|
||||
## Color Scheme
|
||||
|
||||
Playwright overrides the color scheme to `light` by default when connecting via CDP. To preserve dark mode:
|
||||
|
||||
```bash
|
||||
agent-browser connect 9222
|
||||
agent-browser --color-scheme dark snapshot -i
|
||||
```
|
||||
|
||||
Or set it globally:
|
||||
|
||||
```bash
|
||||
AGENT_BROWSER_COLOR_SCHEME=dark agent-browser connect 9222
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Connection refused" or "Cannot connect"
|
||||
|
||||
- Make sure the app was launched with `--remote-debugging-port=NNNN`
|
||||
- If the app was already running, quit and relaunch with the flag
|
||||
- Check that the port isn't in use by another process: `lsof -i :9222`
|
||||
|
||||
### App launches but connect fails
|
||||
|
||||
- Wait a few seconds after launch before connecting (`sleep 3`)
|
||||
- Some apps take time to initialize their webview
|
||||
|
||||
### Elements not appearing in snapshot
|
||||
|
||||
- The app may use multiple webviews. Use `agent-browser tab` to list targets and switch to the right one
|
||||
- Use `agent-browser snapshot -i -C` to include cursor-interactive elements (divs with onclick handlers)
|
||||
|
||||
### Cannot type in input fields
|
||||
|
||||
- Try `agent-browser keyboard type "text"` to type at the current focus without a selector
|
||||
- Some Electron apps use custom input components; use `agent-browser keyboard inserttext "text"` to bypass key events
|
||||
|
||||
## Supported Apps
|
||||
|
||||
Any app built on Electron works, including:
|
||||
|
||||
- **Communication:** Slack, Discord, Microsoft Teams, Signal, Telegram Desktop
|
||||
- **Development:** VS Code, GitHub Desktop, Postman, Insomnia
|
||||
- **Design:** Figma, Notion, Obsidian
|
||||
- **Media:** Spotify, Tidal
|
||||
- **Productivity:** Todoist, Linear, 1Password
|
||||
|
||||
If an app is built with Electron, it supports `--remote-debugging-port` and can be automated with agent-browser.
|
||||
@@ -0,0 +1,294 @@
|
||||
---
|
||||
name: slack
|
||||
description: Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include "check my Slack", "what channels have unreads", "send a message to", "search Slack for", "extract from Slack", "find who said", or any task requiring programmatic Slack interaction.
|
||||
allowed-tools: Bash(agent-browser:*), Bash(npx agent-browser:*)
|
||||
---
|
||||
|
||||
# Slack Automation
|
||||
|
||||
Interact with Slack workspaces to check messages, extract data, and automate common tasks.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Connect to an existing Slack browser session or open Slack:
|
||||
|
||||
```bash
|
||||
# Connect to existing session on port 9222 (typical for already-open Slack)
|
||||
agent-browser connect 9222
|
||||
|
||||
# Or open Slack if not already running
|
||||
agent-browser open https://app.slack.com
|
||||
```
|
||||
|
||||
Then take a snapshot to see what's available:
|
||||
|
||||
```bash
|
||||
agent-browser snapshot -i
|
||||
```
|
||||
|
||||
## Core Workflow
|
||||
|
||||
1. **Connect/Navigate**: Open or connect to Slack
|
||||
2. **Snapshot**: Get interactive elements with refs (`@e1`, `@e2`, etc.)
|
||||
3. **Navigate**: Click tabs, expand sections, or navigate to specific channels
|
||||
4. **Extract/Interact**: Read data or perform actions
|
||||
5. **Screenshot**: Capture evidence of findings
|
||||
|
||||
```bash
|
||||
# Example: Check unread channels
|
||||
agent-browser connect 9222
|
||||
agent-browser snapshot -i
|
||||
# Look for "More unreads" button
|
||||
agent-browser click @e21 # Ref for "More unreads" button
|
||||
agent-browser screenshot slack-unreads.png
|
||||
```
|
||||
|
||||
## Common Tasks
|
||||
|
||||
### Checking Unread Messages
|
||||
|
||||
```bash
|
||||
# Connect to Slack
|
||||
agent-browser connect 9222
|
||||
|
||||
# Take snapshot to locate unreads button
|
||||
agent-browser snapshot -i
|
||||
|
||||
# Look for:
|
||||
# - "More unreads" button (usually near top of sidebar)
|
||||
# - "Unreads" toggle in Activity tab (shows unread count)
|
||||
# - Channel names with badges/bold text indicating unreads
|
||||
|
||||
# Navigate to Activity tab to see all unreads in one view
|
||||
agent-browser click @e14 # Activity tab (ref may vary)
|
||||
agent-browser wait 1000
|
||||
agent-browser screenshot activity-unreads.png
|
||||
|
||||
# Or check DMs tab
|
||||
agent-browser click @e13 # DMs tab
|
||||
agent-browser screenshot dms.png
|
||||
|
||||
# Or expand "More unreads" in sidebar
|
||||
agent-browser click @e21 # More unreads button
|
||||
agent-browser wait 500
|
||||
agent-browser screenshot expanded-unreads.png
|
||||
```
|
||||
|
||||
### Navigating to a Channel
|
||||
|
||||
```bash
|
||||
# Search for channel in sidebar or by name
|
||||
agent-browser snapshot -i
|
||||
|
||||
# Look for channel name in the list (e.g., "engineering", "product-design")
|
||||
# Click on the channel treeitem ref
|
||||
agent-browser click @e94 # Example: engineering channel ref
|
||||
agent-browser wait --load networkidle
|
||||
agent-browser screenshot channel.png
|
||||
```
|
||||
|
||||
### Finding Messages/Threads
|
||||
|
||||
```bash
|
||||
# Use Slack search
|
||||
agent-browser snapshot -i
|
||||
agent-browser click @e5 # Search button (typical ref)
|
||||
agent-browser fill @e_search "keyword"
|
||||
agent-browser press Enter
|
||||
agent-browser wait --load networkidle
|
||||
agent-browser screenshot search-results.png
|
||||
```
|
||||
|
||||
### Extracting Channel Information
|
||||
|
||||
```bash
|
||||
# Get list of all visible channels
|
||||
agent-browser snapshot --json > slack-snapshot.json
|
||||
|
||||
# Parse for channel names and metadata
|
||||
# Look for treeitem elements with level=2 (sub-channels under sections)
|
||||
```
|
||||
|
||||
### Checking Channel Details
|
||||
|
||||
```bash
|
||||
# Open a channel
|
||||
agent-browser click @e_channel_ref
|
||||
agent-browser wait 1000
|
||||
|
||||
# Get channel info (members, description, etc.)
|
||||
agent-browser snapshot -i
|
||||
agent-browser screenshot channel-details.png
|
||||
|
||||
# Scroll through messages
|
||||
agent-browser scroll down 500
|
||||
agent-browser screenshot channel-messages.png
|
||||
```
|
||||
|
||||
### Taking Notes/Capturing State
|
||||
|
||||
When you need to document findings from Slack:
|
||||
|
||||
```bash
|
||||
# Take annotated screenshot (shows element numbers)
|
||||
agent-browser screenshot --annotate slack-state.png
|
||||
|
||||
# Take full-page screenshot
|
||||
agent-browser screenshot --full slack-full.png
|
||||
|
||||
# Get current URL for reference
|
||||
agent-browser get url
|
||||
|
||||
# Get page title
|
||||
agent-browser get title
|
||||
```
|
||||
|
||||
## Sidebar Structure
|
||||
|
||||
Understanding Slack's sidebar helps you navigate efficiently:
|
||||
|
||||
```
|
||||
- Threads
|
||||
- Huddles
|
||||
- Drafts & sent
|
||||
- Directories
|
||||
- [Section Headers - External connections, Starred, Channels, etc.]
|
||||
- [Channels listed as treeitems]
|
||||
- Direct Messages
|
||||
- [DMs listed]
|
||||
- Apps
|
||||
- [App shortcuts]
|
||||
- [More unreads] button (toggles unread channels list)
|
||||
```
|
||||
|
||||
Key refs to look for:
|
||||
- `@e12` - Home tab (usually)
|
||||
- `@e13` - DMs tab
|
||||
- `@e14` - Activity tab
|
||||
- `@e5` - Search button
|
||||
- `@e21` - More unreads button (varies by session)
|
||||
|
||||
## Tabs in Slack
|
||||
|
||||
After clicking on a channel, you'll see tabs:
|
||||
- **Messages** - Channel conversation
|
||||
- **Files** - Shared files
|
||||
- **Pins** - Pinned messages
|
||||
- **Add canvas** - Collaborative canvas
|
||||
- Other tabs depending on workspace setup
|
||||
|
||||
Click tab refs to switch views and get different information.
|
||||
|
||||
## Extracting Data from Slack
|
||||
|
||||
### Get Text Content
|
||||
|
||||
```bash
|
||||
# Get a message or element's text
|
||||
agent-browser get text @e_message_ref
|
||||
```
|
||||
|
||||
### Parse Accessibility Tree
|
||||
|
||||
```bash
|
||||
# Full snapshot as JSON for programmatic parsing
|
||||
agent-browser snapshot --json > output.json
|
||||
|
||||
# Look for:
|
||||
# - Channel names (name field in treeitem)
|
||||
# - Message content (in listitem/document elements)
|
||||
# - User names (button elements with user info)
|
||||
# - Timestamps (link elements with time info)
|
||||
```
|
||||
|
||||
### Count Unreads
|
||||
|
||||
```bash
|
||||
# After expanding unreads section:
|
||||
agent-browser snapshot -i | grep -c "treeitem"
|
||||
# Each treeitem with a channel name in the unreads section is one unread
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Connect to existing sessions**: Use `agent-browser connect 9222` if Slack is already open. This is faster than opening a new browser.
|
||||
- **Take snapshots before clicking**: Always `snapshot -i` to identify refs before clicking buttons.
|
||||
- **Re-snapshot after navigation**: After navigating to a new channel or section, take a fresh snapshot to find new refs.
|
||||
- **Use JSON snapshots for parsing**: When you need to extract structured data, use `snapshot --json` for machine-readable output.
|
||||
- **Pace interactions**: Add `sleep 1` between rapid interactions to let the UI update.
|
||||
- **Check accessibility tree**: The accessibility tree shows what screen readers (and your automation) can see. If an element isn't in the snapshot, it may be hidden or require scrolling.
|
||||
- **Scroll in sidebar**: Use `agent-browser scroll down 300 --selector ".p-sidebar"` to scroll within the Slack sidebar if channel list is long.
|
||||
|
||||
## Limitations
|
||||
|
||||
- **Cannot access Slack API**: This uses browser automation, not the Slack API. No OAuth, webhooks, or bot tokens needed.
|
||||
- **Session-specific**: Screenshots and snapshots are tied to the current browser session.
|
||||
- **Rate limiting**: Slack may rate-limit rapid interactions. Add delays between commands if needed.
|
||||
- **Workspace-specific**: You interact with your own workspace -- no cross-workspace automation.
|
||||
|
||||
## Debugging
|
||||
|
||||
### Check console for errors
|
||||
|
||||
```bash
|
||||
agent-browser console
|
||||
agent-browser errors
|
||||
```
|
||||
|
||||
### View raw HTML of an element
|
||||
|
||||
```bash
|
||||
# Snapshot shows the accessibility tree. If an element isn't there,
|
||||
# it may not be interactive (e.g., div instead of button)
|
||||
# Use snapshot -i -C to include cursor-interactive divs
|
||||
agent-browser snapshot -i -C
|
||||
```
|
||||
|
||||
### Get current page state
|
||||
|
||||
```bash
|
||||
agent-browser get url
|
||||
agent-browser get title
|
||||
agent-browser screenshot page-state.png
|
||||
```
|
||||
|
||||
## Example: Full Unread Check
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
# Connect to Slack
|
||||
agent-browser connect 9222
|
||||
|
||||
# Take initial snapshot
|
||||
echo "=== Checking Slack unreads ==="
|
||||
agent-browser snapshot -i > snapshot.txt
|
||||
|
||||
# Check Activity tab for unreads
|
||||
agent-browser click @e14 # Activity tab
|
||||
agent-browser wait 1000
|
||||
agent-browser screenshot activity.png
|
||||
ACTIVITY_RESULT=$(agent-browser get text @e_main_area)
|
||||
echo "Activity: $ACTIVITY_RESULT"
|
||||
|
||||
# Check DMs
|
||||
agent-browser click @e13 # DMs tab
|
||||
agent-browser wait 1000
|
||||
agent-browser screenshot dms.png
|
||||
|
||||
# Check unread channels in sidebar
|
||||
agent-browser click @e21 # More unreads button
|
||||
agent-browser wait 500
|
||||
agent-browser snapshot -i > unreads-expanded.txt
|
||||
agent-browser screenshot unreads.png
|
||||
|
||||
# Summary
|
||||
echo "=== Summary ==="
|
||||
echo "See activity.png, dms.png, and unreads.png for full details"
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- **Slack docs**: https://slack.com/help
|
||||
- **Web experience**: https://app.slack.com
|
||||
- **Keyboard shortcuts**: Type `?` in Slack for shortcut list
|
||||
@@ -0,0 +1,354 @@
|
||||
# Common Slack Tasks & Patterns
|
||||
|
||||
Reference guide for common automations and data extraction patterns when interacting with Slack.
|
||||
|
||||
## Task: Check All Unread Messages
|
||||
|
||||
### Goal
|
||||
Determine which channels and DMs have unread messages.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Connect to Slack**
|
||||
```bash
|
||||
agent-browser connect 9222
|
||||
```
|
||||
|
||||
2. **Check Activity Tab**
|
||||
- Take snapshot: `agent-browser snapshot -i`
|
||||
- Look for Activity tab ref (usually `@e14`)
|
||||
- Click: `agent-browser click @e14`
|
||||
- Wait: `agent-browser wait 1000`
|
||||
- If you see "You've read all the unreads", you have no unread messages
|
||||
- Screenshot: `agent-browser screenshot activity.png`
|
||||
|
||||
3. **Check DMs**
|
||||
- Click DMs tab ref (usually `@e13`)
|
||||
- Look for "Unreads" toggle/badge
|
||||
- Count visible conversations with indicators
|
||||
|
||||
4. **Check Channels**
|
||||
- Look for "More unreads" button (usually in sidebar)
|
||||
- Click it to expand list of channels with unreads
|
||||
- Screenshot the expanded view
|
||||
- Parse channel names from snapshot
|
||||
|
||||
5. **Summary**
|
||||
- Activity + DMs + Channels = complete unread picture
|
||||
|
||||
### Evidence Capture
|
||||
- Screenshot of Activity tab
|
||||
- Screenshot of DMs
|
||||
- Screenshot of expanded unreads sidebar
|
||||
|
||||
---
|
||||
|
||||
## Task: Find All Channels in Workspace
|
||||
|
||||
### Goal
|
||||
Get a complete list of all channels you have access to.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Navigate to Channels section**
|
||||
```bash
|
||||
agent-browser connect 9222
|
||||
agent-browser snapshot -i
|
||||
```
|
||||
|
||||
2. **Look for "Channels" treeitem**
|
||||
- This is usually a collapsed section header
|
||||
- Click to expand if collapsed
|
||||
- Screenshot: `agent-browser screenshot all-channels.png`
|
||||
|
||||
3. **Scroll through sidebar**
|
||||
```bash
|
||||
# If the list is long, scroll within the sidebar
|
||||
agent-browser scroll down 500 --selector ".p-sidebar"
|
||||
agent-browser screenshot channels-page-2.png
|
||||
```
|
||||
|
||||
4. **Parse snapshot for channel list**
|
||||
```bash
|
||||
agent-browser snapshot --json > channels.json
|
||||
# Search JSON for treeitem elements with level=2 under "Channels" section
|
||||
```
|
||||
|
||||
### Evidence
|
||||
- JSON snapshot with all channel refs
|
||||
- Screenshots of channel list
|
||||
- Count of total channels
|
||||
|
||||
---
|
||||
|
||||
## Task: Search for Messages Containing Keywords
|
||||
|
||||
### Goal
|
||||
Find all messages/threads mentioning specific terms.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Open search**
|
||||
```bash
|
||||
agent-browser snapshot -i
|
||||
# Find Search button ref (usually @e5)
|
||||
agent-browser click @e5
|
||||
agent-browser wait 500
|
||||
```
|
||||
|
||||
2. **Enter search term**
|
||||
```bash
|
||||
# Identify search input ref from snapshot
|
||||
agent-browser fill @e_search_input "your keyword"
|
||||
agent-browser press Enter
|
||||
agent-browser wait --load networkidle
|
||||
```
|
||||
|
||||
3. **Capture results**
|
||||
```bash
|
||||
agent-browser screenshot search-results.png
|
||||
agent-browser snapshot -i > search-snapshot.txt
|
||||
```
|
||||
|
||||
4. **Parse results**
|
||||
- Look for result items in snapshot
|
||||
- Extract message content, sender, channel, timestamp
|
||||
- Follow links to view full context
|
||||
|
||||
### Filters
|
||||
Slack search supports filters:
|
||||
- `in:channel-name` - Search in specific channel
|
||||
- `from:@user` - Messages from specific user
|
||||
- `before:2026-02-25` - Messages before date
|
||||
- `after:2026-02-20` - Messages after date
|
||||
- `has:file` - Messages with files
|
||||
- `has:emoji` - Messages with reactions
|
||||
|
||||
Example search: `"bug report" in:engineering from:@alice after:2026-02-20`
|
||||
|
||||
---
|
||||
|
||||
## Task: Monitor a Specific Channel for Activity
|
||||
|
||||
### Goal
|
||||
Watch a channel and capture new messages/engagement.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Navigate to channel**
|
||||
```bash
|
||||
agent-browser connect 9222
|
||||
agent-browser snapshot -i
|
||||
# Find channel ref from sidebar
|
||||
agent-browser click @e_channel_ref
|
||||
agent-browser wait --load networkidle
|
||||
```
|
||||
|
||||
2. **Check channel info**
|
||||
- Screenshot channel details: `agent-browser screenshot channel-header.png`
|
||||
- Look for member count, description, topic
|
||||
|
||||
3. **View messages**
|
||||
```bash
|
||||
# Jump to recent/unread
|
||||
agent-browser press j # Jump to unread in Slack
|
||||
agent-browser wait 500
|
||||
agent-browser screenshot recent-messages.png
|
||||
```
|
||||
|
||||
4. **Scroll to see more**
|
||||
```bash
|
||||
agent-browser scroll down 500
|
||||
agent-browser screenshot more-messages.png
|
||||
```
|
||||
|
||||
5. **Check threads**
|
||||
- Click on messages with thread indicators
|
||||
- View replies in thread view
|
||||
- Screenshot: `agent-browser screenshot thread.png`
|
||||
|
||||
### Evidence
|
||||
- Channel info screenshot
|
||||
- Message history screenshots
|
||||
- Thread examples
|
||||
|
||||
---
|
||||
|
||||
## Task: Extract User Information from a Conversation
|
||||
|
||||
### Goal
|
||||
Find who said what, when, and in what context.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Navigate to relevant channel or DM**
|
||||
```bash
|
||||
agent-browser click @e_conversation_ref
|
||||
agent-browser wait 1000
|
||||
```
|
||||
|
||||
2. **Take snapshot with context**
|
||||
```bash
|
||||
agent-browser snapshot --json > conversation.json
|
||||
```
|
||||
|
||||
3. **Find message blocks**
|
||||
- In JSON, look for document/listitem elements
|
||||
- These contain: user name (button), timestamp (link), message text, reactions
|
||||
|
||||
4. **Extract structured data**
|
||||
- User: Found in button element with username
|
||||
- Time: Found in link with timestamp
|
||||
- Content: Text content of message
|
||||
- Reactions: Buttons showing emoji counts
|
||||
|
||||
5. **Screenshot key messages**
|
||||
```bash
|
||||
agent-browser screenshot important-message.png
|
||||
agent-browser screenshot --annotate annotated-message.png
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task: Track Reactions to a Message
|
||||
|
||||
### Goal
|
||||
See who reacted to a message and with what emoji.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Find message with reactions**
|
||||
```bash
|
||||
agent-browser snapshot -i
|
||||
# Look for "N reaction(s)" buttons in messages
|
||||
```
|
||||
|
||||
2. **Click reaction button to expand**
|
||||
```bash
|
||||
agent-browser click @e_reaction_button
|
||||
agent-browser wait 500
|
||||
```
|
||||
|
||||
3. **Capture reaction details**
|
||||
```bash
|
||||
agent-browser screenshot reactions.png
|
||||
# You'll see emoji, count, and list of users who reacted
|
||||
```
|
||||
|
||||
4. **Extract data**
|
||||
- Emoji used
|
||||
- Number of people who reacted
|
||||
- User names (if visible in popup)
|
||||
|
||||
---
|
||||
|
||||
## Task: Find and Review Pinned Messages
|
||||
|
||||
### Goal
|
||||
See messages that have been pinned in a channel.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Open a channel**
|
||||
```bash
|
||||
agent-browser click @e_channel_ref
|
||||
agent-browser wait 1000
|
||||
agent-browser snapshot -i
|
||||
```
|
||||
|
||||
2. **Click Pins tab**
|
||||
- In channel view, look for "Pins" tab ref (usually near Messages, Files tabs)
|
||||
- Click it: `agent-browser click @e_pins_tab`
|
||||
- Wait: `agent-browser wait 500`
|
||||
|
||||
3. **View pinned messages**
|
||||
```bash
|
||||
agent-browser screenshot pins.png
|
||||
agent-browser snapshot -i > pins-snapshot.txt
|
||||
```
|
||||
|
||||
4. **Review each pin**
|
||||
- Click pin to see context
|
||||
- Note who pinned it, when, and why
|
||||
- Screenshot: `agent-browser screenshot pin-detail.png`
|
||||
|
||||
---
|
||||
|
||||
## Pattern: Extract Timestamp from Link
|
||||
|
||||
In Slack snapshot, message timestamps appear as links. Example:
|
||||
```
|
||||
- link "Feb 25th at 10:26:22 AM" [ref=e151]
|
||||
- /url: https://vercel.slack.com/archives/C0A5RTN0856/p1772036782543189
|
||||
```
|
||||
|
||||
The URL contains the timestamp in the fragment (`p1772036782543189`). This is a Slack message ID that uniquely identifies the message.
|
||||
|
||||
---
|
||||
|
||||
## Pattern: Understanding Channel/Thread Structure
|
||||
|
||||
```
|
||||
- treeitem "channel-name" [ref=e94] [level=2]
|
||||
- group: (contains channel metadata or sub-items)
|
||||
```
|
||||
|
||||
- **level=1**: Section headers (External connections, Starred, Channels, etc.)
|
||||
- **level=2**: Individual channels/items within sections
|
||||
- **level=3+**: Nested sub-items (rare in sidebar)
|
||||
|
||||
---
|
||||
|
||||
## Common Ref Patterns (Session-Dependent)
|
||||
|
||||
These refs vary per session, but follow patterns:
|
||||
|
||||
| Element | Typical Ref Range | How to Find |
|
||||
|---------|------------------|------------|
|
||||
| Home tab | e10-e20 | `snapshot -i \| grep "Home"` |
|
||||
| DMs tab | e10-e20 | `snapshot -i \| grep "DMs"` |
|
||||
| Activity tab | e10-e20 | `snapshot -i \| grep "Activity"` |
|
||||
| Search | e5-e10 | `snapshot -i \| grep "Search"` |
|
||||
| More unreads | e20-e30 | `snapshot -i \| grep "More unreads"` |
|
||||
| Channel refs | e30+ | `snapshot -i \| grep "treeitem"` |
|
||||
|
||||
**Always take a fresh snapshot** to find current refs for the current session.
|
||||
|
||||
---
|
||||
|
||||
## Debugging: Element Not Found
|
||||
|
||||
If you can't find an element:
|
||||
|
||||
1. **Check it's visible**
|
||||
```bash
|
||||
# Is the element on screen or off-screen?
|
||||
agent-browser screenshot current-state.png
|
||||
# Compare screenshot to what you expected
|
||||
```
|
||||
|
||||
2. **Try expanding/scrolling**
|
||||
```bash
|
||||
# Sidebar might need scrolling
|
||||
agent-browser scroll down 300 --selector ".p-sidebar"
|
||||
agent-browser snapshot -i
|
||||
```
|
||||
|
||||
3. **Try snapshot with extended range**
|
||||
```bash
|
||||
# Include cursor-interactive elements (divs with onclick handlers)
|
||||
agent-browser snapshot -i -C
|
||||
```
|
||||
|
||||
4. **Check current URL**
|
||||
```bash
|
||||
agent-browser get url
|
||||
# Verify you're in the right section
|
||||
```
|
||||
|
||||
5. **Wait for page to load**
|
||||
```bash
|
||||
agent-browser wait --load networkidle
|
||||
agent-browser wait 1000
|
||||
agent-browser snapshot -i
|
||||
```
|
||||
@@ -0,0 +1,163 @@
|
||||
# Slack Analysis Report
|
||||
|
||||
**Date**: [DATE]
|
||||
**Workspace**: [WORKSPACE_NAME]
|
||||
**Analyst**: [YOUR_NAME]
|
||||
**Scope**: [WHAT_YOU_ANALYZED]
|
||||
|
||||
## Summary
|
||||
|
||||
### Unread Counts
|
||||
- **Activity**: [NUMBER] unreads
|
||||
- **Direct Messages**: [NUMBER] unreads
|
||||
- **Channels**: [NUMBER] channels with unreads
|
||||
|
||||
### Key Findings
|
||||
- [FINDING 1]
|
||||
- [FINDING 2]
|
||||
- [FINDING 3]
|
||||
|
||||
---
|
||||
|
||||
## Unread Channels
|
||||
|
||||
List of channels with unread messages:
|
||||
|
||||
| Channel | Unread Count | Last Activity | Notes |
|
||||
|---------|-------------|---------------|-------|
|
||||
| #engineering | 12 | Today 2:45 PM | Active discussion thread |
|
||||
| #announcements | 3 | Yesterday 5:30 PM | Team updates |
|
||||
| #random | 5 | Today 11:20 AM | Various topics |
|
||||
|
||||
---
|
||||
|
||||
## Unread Direct Messages
|
||||
|
||||
| User/Group | Message Count | Last Message | Preview |
|
||||
|------------|--------------|--------------|---------|
|
||||
| @alice | 2 | Today 3:15 PM | "Are you free to..." |
|
||||
| @product-team | 5 | Today 2:00 PM | Sync scheduled for... |
|
||||
|
||||
---
|
||||
|
||||
## Channel Snapshot
|
||||
|
||||
### Total Channels Accessible
|
||||
- **Public Channels**: [NUMBER]
|
||||
- **Private Channels**: [NUMBER]
|
||||
- **Group DMs**: [NUMBER]
|
||||
|
||||
### Channel Categories
|
||||
- **External Connections**: [COUNT] channels
|
||||
- **Starred**: [COUNT] channels
|
||||
- **Main Channels**: [COUNT] channels
|
||||
|
||||
---
|
||||
|
||||
## Most Active Channels (by recent activity)
|
||||
|
||||
| Rank | Channel | Activity | Participants |
|
||||
|------|---------|----------|--------------|
|
||||
| 1 | #engineering | High | 15+ active |
|
||||
| 2 | #general | High | 10+ active |
|
||||
| 3 | #product-design | Medium | 8+ active |
|
||||
|
||||
---
|
||||
|
||||
## Key Conversations
|
||||
|
||||
### [TOPIC 1]: Channel #engineering
|
||||
- **Status**: Ongoing discussion
|
||||
- **Participants**: @alice, @bob, @charlie
|
||||
- **Latest Update**: [TIME]
|
||||
- **Thread Count**: 5 threads
|
||||
- **Files Shared**: 2 documents
|
||||
- **Screenshots**: See `engineering-thread.png`
|
||||
|
||||
**Notes**: [Additional context about the conversation]
|
||||
|
||||
### [TOPIC 2]: DM with @alice
|
||||
- **Unread Messages**: 2
|
||||
- **Last Message**: [TIME]
|
||||
- **Summary**: [Brief summary of conversation]
|
||||
- **Action Items**: [Any TODOs mentioned]
|
||||
|
||||
---
|
||||
|
||||
## Search Results
|
||||
|
||||
### Query: "[SEARCH_TERM]"
|
||||
- **Results**: [NUMBER] messages
|
||||
- **Date Range**: [FROM] to [TO]
|
||||
- **Top Channels**: [LIST]
|
||||
- **Key Themes**: [PATTERNS OBSERVED]
|
||||
|
||||
#### Sample Results
|
||||
1. **[Date/Time]** in #[channel]: [Message snippet]
|
||||
2. **[Date/Time]** in #[channel]: [Message snippet]
|
||||
3. **[Date/Time]** in #[channel]: [Message snippet]
|
||||
|
||||
---
|
||||
|
||||
## Reactions & Engagement
|
||||
|
||||
### Most Reacted-To Messages
|
||||
| Message | Emoji | Count | Channel |
|
||||
|---------|-------|-------|---------|
|
||||
| "Shipped to production" | 🎉 | 8 | #engineering |
|
||||
| "FYI the site is down" | 🚨 | 12 | #incidents |
|
||||
|
||||
---
|
||||
|
||||
## Team Insights
|
||||
|
||||
### Most Active Users (by message volume)
|
||||
1. @alice - [COUNT] messages
|
||||
2. @bob - [COUNT] messages
|
||||
3. @charlie - [COUNT] messages
|
||||
|
||||
### Most Active Times
|
||||
- Peak hour: [TIME]
|
||||
- Peak day: [DAY]
|
||||
- Average messages per hour: [NUMBER]
|
||||
|
||||
---
|
||||
|
||||
## Issues / Observations
|
||||
|
||||
### [ISSUE 1]: [Title]
|
||||
**Severity**: [Critical/High/Medium/Low]
|
||||
**Description**: [What was observed]
|
||||
**Evidence**: See `issue-1-screenshot.png`
|
||||
**Recommendation**: [Suggested action]
|
||||
|
||||
---
|
||||
|
||||
## Screenshots
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `activity-tab.png` | Activity tab showing unreads |
|
||||
| `dms-overview.png` | DM list with unread indicators |
|
||||
| `channels-full-list.png` | Complete channel list |
|
||||
| `engineering-thread.png` | Active engineering thread |
|
||||
|
||||
---
|
||||
|
||||
## Appendix: Raw Data
|
||||
|
||||
### Snapshot Output
|
||||
```
|
||||
[Paste snapshot -i output here]
|
||||
```
|
||||
|
||||
### JSON Snapshot (for parsing)
|
||||
```json
|
||||
[Paste snapshot --json output here]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Report Generated**: [DATE/TIME]
|
||||
**Analysis Duration**: [TIME]
|
||||
**Next Steps**: [TODO]
|
||||
@@ -0,0 +1,213 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import {
|
||||
getActionCategory,
|
||||
checkPolicy,
|
||||
loadPolicyFile,
|
||||
describeAction,
|
||||
KNOWN_CATEGORIES,
|
||||
type ActionPolicy,
|
||||
} from './action-policy.js';
|
||||
|
||||
describe('action-policy', () => {
|
||||
describe('getActionCategory', () => {
|
||||
it('should return correct category for known actions', () => {
|
||||
expect(getActionCategory('navigate')).toBe('navigate');
|
||||
expect(getActionCategory('click')).toBe('click');
|
||||
expect(getActionCategory('fill')).toBe('fill');
|
||||
expect(getActionCategory('evaluate')).toBe('eval');
|
||||
expect(getActionCategory('download')).toBe('download');
|
||||
expect(getActionCategory('upload')).toBe('upload');
|
||||
expect(getActionCategory('snapshot')).toBe('snapshot');
|
||||
expect(getActionCategory('scroll')).toBe('scroll');
|
||||
expect(getActionCategory('wait')).toBe('wait');
|
||||
expect(getActionCategory('gettext')).toBe('get');
|
||||
expect(getActionCategory('route')).toBe('network');
|
||||
expect(getActionCategory('state_save')).toBe('state');
|
||||
expect(getActionCategory('hover')).toBe('interact');
|
||||
});
|
||||
|
||||
it('should return _internal for internal actions', () => {
|
||||
expect(getActionCategory('launch')).toBe('_internal');
|
||||
expect(getActionCategory('close')).toBe('_internal');
|
||||
expect(getActionCategory('session')).toBe('_internal');
|
||||
expect(getActionCategory('auth_save')).toBe('_internal');
|
||||
expect(getActionCategory('confirm')).toBe('_internal');
|
||||
});
|
||||
|
||||
it('should return eval for security-sensitive actions', () => {
|
||||
expect(getActionCategory('setcontent')).toBe('eval');
|
||||
expect(getActionCategory('expose')).toBe('eval');
|
||||
expect(getActionCategory('addstyle')).toBe('eval');
|
||||
});
|
||||
|
||||
it('should return unknown for unrecognized actions', () => {
|
||||
expect(getActionCategory('nonexistent')).toBe('unknown');
|
||||
expect(getActionCategory('')).toBe('unknown');
|
||||
});
|
||||
|
||||
it('should return get for semantic locator actions', () => {
|
||||
expect(getActionCategory('getbyrole')).toBe('get');
|
||||
expect(getActionCategory('getbytext')).toBe('get');
|
||||
expect(getActionCategory('getbylabel')).toBe('get');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkPolicy', () => {
|
||||
it('should always allow internal actions regardless of policy', () => {
|
||||
const denyAll: ActionPolicy = { default: 'deny' };
|
||||
expect(checkPolicy('launch', denyAll, new Set())).toBe('allow');
|
||||
expect(checkPolicy('close', denyAll, new Set())).toBe('allow');
|
||||
expect(checkPolicy('session', denyAll, new Set())).toBe('allow');
|
||||
});
|
||||
|
||||
it('should allow all when no policy and no confirm categories', () => {
|
||||
expect(checkPolicy('navigate', null, new Set())).toBe('allow');
|
||||
expect(checkPolicy('click', null, new Set())).toBe('allow');
|
||||
expect(checkPolicy('evaluate', null, new Set())).toBe('allow');
|
||||
});
|
||||
|
||||
it('should deny actions in explicit deny list', () => {
|
||||
const policy: ActionPolicy = { default: 'allow', deny: ['eval', 'download'] };
|
||||
expect(checkPolicy('evaluate', policy, new Set())).toBe('deny');
|
||||
expect(checkPolicy('download', policy, new Set())).toBe('deny');
|
||||
expect(checkPolicy('click', policy, new Set())).toBe('allow');
|
||||
});
|
||||
|
||||
it('should allow actions in explicit allow list with deny default', () => {
|
||||
const policy: ActionPolicy = { default: 'deny', allow: ['navigate', 'snapshot'] };
|
||||
expect(checkPolicy('navigate', policy, new Set())).toBe('allow');
|
||||
expect(checkPolicy('snapshot', policy, new Set())).toBe('allow');
|
||||
expect(checkPolicy('click', policy, new Set())).toBe('deny');
|
||||
});
|
||||
|
||||
it('should return confirm for actions in confirm categories', () => {
|
||||
expect(checkPolicy('evaluate', null, new Set(['eval']))).toBe('confirm');
|
||||
expect(checkPolicy('download', null, new Set(['download']))).toBe('confirm');
|
||||
});
|
||||
|
||||
it('should deny over confirm when action is in deny list', () => {
|
||||
const policy: ActionPolicy = { default: 'allow', deny: ['eval'] };
|
||||
expect(checkPolicy('evaluate', policy, new Set(['eval']))).toBe('deny');
|
||||
});
|
||||
|
||||
it('should use default policy for unknown categories', () => {
|
||||
const denyPolicy: ActionPolicy = { default: 'deny' };
|
||||
const allowPolicy: ActionPolicy = { default: 'allow' };
|
||||
expect(checkPolicy('nonexistent', denyPolicy, new Set())).toBe('deny');
|
||||
expect(checkPolicy('nonexistent', allowPolicy, new Set())).toBe('allow');
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadPolicyFile', () => {
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'action-policy-test-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should load a valid allow-default policy', () => {
|
||||
const policyPath = path.join(tempDir, 'policy.json');
|
||||
fs.writeFileSync(policyPath, JSON.stringify({ default: 'allow', deny: ['eval'] }));
|
||||
const policy = loadPolicyFile(policyPath);
|
||||
expect(policy.default).toBe('allow');
|
||||
expect(policy.deny).toEqual(['eval']);
|
||||
});
|
||||
|
||||
it('should load a valid deny-default policy', () => {
|
||||
const policyPath = path.join(tempDir, 'policy.json');
|
||||
fs.writeFileSync(
|
||||
policyPath,
|
||||
JSON.stringify({ default: 'deny', allow: ['navigate', 'snapshot'] })
|
||||
);
|
||||
const policy = loadPolicyFile(policyPath);
|
||||
expect(policy.default).toBe('deny');
|
||||
expect(policy.allow).toEqual(['navigate', 'snapshot']);
|
||||
});
|
||||
|
||||
it('should throw on invalid default value', () => {
|
||||
const policyPath = path.join(tempDir, 'policy.json');
|
||||
fs.writeFileSync(policyPath, JSON.stringify({ default: 'maybe' }));
|
||||
expect(() => loadPolicyFile(policyPath)).toThrow('must be "allow" or "deny"');
|
||||
});
|
||||
|
||||
it('should throw on missing file', () => {
|
||||
expect(() => loadPolicyFile(path.join(tempDir, 'missing.json'))).toThrow();
|
||||
});
|
||||
|
||||
it('should throw on invalid JSON', () => {
|
||||
const policyPath = path.join(tempDir, 'policy.json');
|
||||
fs.writeFileSync(policyPath, 'not json');
|
||||
expect(() => loadPolicyFile(policyPath)).toThrow();
|
||||
});
|
||||
|
||||
it('should warn on unrecognized category names', () => {
|
||||
const policyPath = path.join(tempDir, 'policy.json');
|
||||
fs.writeFileSync(
|
||||
policyPath,
|
||||
JSON.stringify({ default: 'allow', deny: ['eval', 'typo_category'] })
|
||||
);
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const policy = loadPolicyFile(policyPath);
|
||||
expect(policy.default).toBe('allow');
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('unrecognized action category "typo_category"')
|
||||
);
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not warn on valid category names', () => {
|
||||
const policyPath = path.join(tempDir, 'policy.json');
|
||||
fs.writeFileSync(
|
||||
policyPath,
|
||||
JSON.stringify({ default: 'deny', allow: ['navigate', 'snapshot', 'get'] })
|
||||
);
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
loadPolicyFile(policyPath);
|
||||
expect(warnSpy).not.toHaveBeenCalled();
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('describeAction', () => {
|
||||
it('should describe navigate actions', () => {
|
||||
expect(describeAction('navigate', { url: 'https://example.com' })).toBe(
|
||||
'Navigate to https://example.com'
|
||||
);
|
||||
});
|
||||
|
||||
it('should describe eval actions with truncation', () => {
|
||||
const longScript = 'a'.repeat(200);
|
||||
const desc = describeAction('evaluate', { script: longScript });
|
||||
expect(desc).toContain('Evaluate JavaScript:');
|
||||
expect(desc.length).toBeLessThan(200);
|
||||
});
|
||||
|
||||
it('should describe click actions', () => {
|
||||
expect(describeAction('click', { selector: '#btn' })).toBe('Click #btn');
|
||||
});
|
||||
|
||||
it('should describe dblclick actions', () => {
|
||||
expect(describeAction('dblclick', { selector: '#btn' })).toBe('Double-click #btn');
|
||||
});
|
||||
|
||||
it('should describe tap actions', () => {
|
||||
expect(describeAction('tap', { selector: '#btn' })).toBe('Tap #btn');
|
||||
});
|
||||
|
||||
it('should describe fill actions', () => {
|
||||
expect(describeAction('fill', { selector: '#input' })).toBe('Fill #input');
|
||||
});
|
||||
|
||||
it('should use fallback for unknown actions', () => {
|
||||
const desc = describeAction('scroll', {});
|
||||
expect(desc).toContain('scroll');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import { readFileSync, statSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
export interface ActionPolicy {
|
||||
default: 'allow' | 'deny';
|
||||
allow?: string[];
|
||||
deny?: string[];
|
||||
}
|
||||
|
||||
export type PolicyDecision = 'allow' | 'deny' | 'confirm';
|
||||
|
||||
const ACTION_CATEGORIES: Record<string, string> = {
|
||||
navigate: 'navigate',
|
||||
back: 'navigate',
|
||||
forward: 'navigate',
|
||||
reload: 'navigate',
|
||||
tab_new: 'navigate',
|
||||
|
||||
click: 'click',
|
||||
dblclick: 'click',
|
||||
tap: 'click',
|
||||
|
||||
fill: 'fill',
|
||||
type: 'fill',
|
||||
// The `keyboard` action is a compound command that dispatches to sub-actions
|
||||
// (type, inserttext, press, down, up). Its primary use is text input, so it
|
||||
// maps to 'fill'. The interact-like sub-actions (press, down, up) are less
|
||||
// common and don't have separate top-level action names in the protocol.
|
||||
keyboard: 'fill',
|
||||
inserttext: 'fill',
|
||||
select: 'fill',
|
||||
multiselect: 'fill',
|
||||
check: 'fill',
|
||||
uncheck: 'fill',
|
||||
clear: 'fill',
|
||||
selectall: 'fill',
|
||||
setvalue: 'fill',
|
||||
|
||||
download: 'download',
|
||||
waitfordownload: 'download',
|
||||
|
||||
upload: 'upload',
|
||||
|
||||
evaluate: 'eval',
|
||||
evalhandle: 'eval',
|
||||
addscript: 'eval',
|
||||
addinitscript: 'eval',
|
||||
|
||||
snapshot: 'snapshot',
|
||||
screenshot: 'snapshot',
|
||||
pdf: 'snapshot',
|
||||
diff_snapshot: 'snapshot',
|
||||
diff_screenshot: 'snapshot',
|
||||
diff_url: 'snapshot',
|
||||
|
||||
scroll: 'scroll',
|
||||
scrollintoview: 'scroll',
|
||||
|
||||
wait: 'wait',
|
||||
waitforurl: 'wait',
|
||||
waitforloadstate: 'wait',
|
||||
waitforfunction: 'wait',
|
||||
|
||||
gettext: 'get',
|
||||
content: 'get',
|
||||
innerhtml: 'get',
|
||||
innertext: 'get',
|
||||
inputvalue: 'get',
|
||||
url: 'get',
|
||||
title: 'get',
|
||||
getattribute: 'get',
|
||||
count: 'get',
|
||||
boundingbox: 'get',
|
||||
styles: 'get',
|
||||
isvisible: 'get',
|
||||
isenabled: 'get',
|
||||
ischecked: 'get',
|
||||
responsebody: 'get',
|
||||
|
||||
route: 'network',
|
||||
unroute: 'network',
|
||||
requests: 'network',
|
||||
|
||||
state_save: 'state',
|
||||
state_load: 'state',
|
||||
cookies_set: 'state',
|
||||
storage_set: 'state',
|
||||
credentials: 'state',
|
||||
|
||||
hover: 'interact',
|
||||
focus: 'interact',
|
||||
drag: 'interact',
|
||||
press: 'interact',
|
||||
keydown: 'interact',
|
||||
keyup: 'interact',
|
||||
mousemove: 'interact',
|
||||
mousedown: 'interact',
|
||||
mouseup: 'interact',
|
||||
wheel: 'interact',
|
||||
dispatch: 'interact',
|
||||
|
||||
// These are always allowed (internal/meta operations)
|
||||
launch: '_internal',
|
||||
close: '_internal',
|
||||
tab_list: '_internal',
|
||||
tab_switch: '_internal',
|
||||
tab_close: '_internal',
|
||||
window_new: '_internal',
|
||||
frame: '_internal',
|
||||
mainframe: '_internal',
|
||||
dialog: '_internal',
|
||||
session: '_internal',
|
||||
console: '_internal',
|
||||
errors: '_internal',
|
||||
cookies_get: '_internal',
|
||||
cookies_clear: '_internal',
|
||||
storage_get: '_internal',
|
||||
storage_clear: '_internal',
|
||||
state_list: '_internal',
|
||||
state_show: '_internal',
|
||||
state_clear: '_internal',
|
||||
state_clean: '_internal',
|
||||
state_rename: '_internal',
|
||||
highlight: '_internal',
|
||||
bringtofront: '_internal',
|
||||
trace_start: '_internal',
|
||||
trace_stop: '_internal',
|
||||
har_start: '_internal',
|
||||
har_stop: '_internal',
|
||||
video_start: '_internal',
|
||||
video_stop: '_internal',
|
||||
recording_start: '_internal',
|
||||
recording_stop: '_internal',
|
||||
recording_restart: '_internal',
|
||||
profiler_start: '_internal',
|
||||
profiler_stop: '_internal',
|
||||
clipboard: '_internal',
|
||||
viewport: '_internal',
|
||||
useragent: '_internal',
|
||||
device: '_internal',
|
||||
geolocation: '_internal',
|
||||
permissions: '_internal',
|
||||
emulatemedia: '_internal',
|
||||
offline: '_internal',
|
||||
headers: '_internal',
|
||||
addstyle: 'eval',
|
||||
expose: 'eval',
|
||||
timezone: '_internal',
|
||||
locale: '_internal',
|
||||
pause: '_internal',
|
||||
setcontent: 'eval',
|
||||
screencast_start: '_internal',
|
||||
screencast_stop: '_internal',
|
||||
input_mouse: '_internal',
|
||||
input_keyboard: '_internal',
|
||||
input_touch: '_internal',
|
||||
|
||||
auth_save: '_internal',
|
||||
auth_login: '_internal',
|
||||
auth_list: '_internal',
|
||||
auth_delete: '_internal',
|
||||
auth_show: '_internal',
|
||||
confirm: '_internal',
|
||||
deny: '_internal',
|
||||
|
||||
// Find/semantic locator actions (read-only element resolution)
|
||||
getbyrole: 'get',
|
||||
getbytext: 'get',
|
||||
getbylabel: 'get',
|
||||
getbyplaceholder: 'get',
|
||||
getbyalttext: 'get',
|
||||
getbytitle: 'get',
|
||||
getbytestid: 'get',
|
||||
nth: 'get',
|
||||
};
|
||||
|
||||
// User-facing categories used in policy files. '_internal' is excluded because
|
||||
// internal actions always bypass policy. 'unknown' is intentionally not a value
|
||||
// in ACTION_CATEGORIES -- it is only the fallback return of getActionCategory()
|
||||
// for unrecognized actions. If a user puts "unknown" in a policy file,
|
||||
// loadPolicyFile will warn about it as unrecognized, which is correct.
|
||||
export const KNOWN_CATEGORIES = new Set(
|
||||
Object.values(ACTION_CATEGORIES).filter((c) => c !== '_internal')
|
||||
);
|
||||
|
||||
export function getActionCategory(action: string): string {
|
||||
return ACTION_CATEGORIES[action] ?? 'unknown';
|
||||
}
|
||||
|
||||
export function loadPolicyFile(policyPath: string): ActionPolicy {
|
||||
const resolved = resolve(policyPath);
|
||||
const content = readFileSync(resolved, 'utf-8');
|
||||
const policy = JSON.parse(content) as ActionPolicy;
|
||||
|
||||
if (policy.default !== 'allow' && policy.default !== 'deny') {
|
||||
throw new Error(
|
||||
`Invalid action policy: "default" must be "allow" or "deny", got "${policy.default}"`
|
||||
);
|
||||
}
|
||||
|
||||
for (const list of [policy.allow, policy.deny]) {
|
||||
if (!list) continue;
|
||||
for (const category of list) {
|
||||
if (!KNOWN_CATEGORIES.has(category)) {
|
||||
console.warn(
|
||||
`[agent-browser] Warning: unrecognized action category "${category}" in policy file. ` +
|
||||
`Known categories: ${[...KNOWN_CATEGORIES].sort().join(', ')}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return policy;
|
||||
}
|
||||
|
||||
let cachedPolicyPath: string | null = null;
|
||||
let cachedPolicyMtimeMs = 0;
|
||||
let cachedPolicy: ActionPolicy | null = null;
|
||||
const RELOAD_CHECK_INTERVAL_MS = 5_000;
|
||||
let lastCheckMs = 0;
|
||||
|
||||
export function initPolicyReloader(policyPath: string, policy: ActionPolicy): void {
|
||||
cachedPolicyPath = resolve(policyPath);
|
||||
cachedPolicyMtimeMs = statSync(cachedPolicyPath).mtimeMs;
|
||||
cachedPolicy = policy;
|
||||
}
|
||||
|
||||
export function reloadPolicyIfChanged(): ActionPolicy | null {
|
||||
if (!cachedPolicyPath) return cachedPolicy;
|
||||
|
||||
const now = Date.now();
|
||||
if (now - lastCheckMs < RELOAD_CHECK_INTERVAL_MS) return cachedPolicy;
|
||||
lastCheckMs = now;
|
||||
|
||||
try {
|
||||
const currentMtime = statSync(cachedPolicyPath).mtimeMs;
|
||||
if (currentMtime !== cachedPolicyMtimeMs) {
|
||||
cachedPolicy = loadPolicyFile(cachedPolicyPath);
|
||||
cachedPolicyMtimeMs = currentMtime;
|
||||
}
|
||||
} catch {
|
||||
// File may have been removed; keep using cached policy
|
||||
}
|
||||
|
||||
return cachedPolicy;
|
||||
}
|
||||
|
||||
export function checkPolicy(
|
||||
action: string,
|
||||
policy: ActionPolicy | null,
|
||||
confirmCategories: Set<string>
|
||||
): PolicyDecision {
|
||||
const category = getActionCategory(action);
|
||||
|
||||
// Internal actions are always allowed
|
||||
if (category === '_internal') return 'allow';
|
||||
|
||||
// Explicit deny takes precedence over confirmation
|
||||
if (policy?.deny?.includes(category)) return 'deny';
|
||||
|
||||
// Check if this category requires confirmation
|
||||
if (confirmCategories.has(category)) return 'confirm';
|
||||
|
||||
if (!policy) return 'allow';
|
||||
|
||||
// Explicit allow list
|
||||
if (policy.allow?.includes(category)) return 'allow';
|
||||
|
||||
return policy.default;
|
||||
}
|
||||
|
||||
export function describeAction(action: string, command: Record<string, unknown>): string {
|
||||
const category = getActionCategory(action);
|
||||
switch (action) {
|
||||
case 'navigate':
|
||||
return `Navigate to ${command.url}`;
|
||||
case 'evaluate':
|
||||
case 'evalhandle':
|
||||
return `Evaluate JavaScript: ${String(command.script ?? '').slice(0, 80)}`;
|
||||
case 'fill':
|
||||
return `Fill ${command.selector}`;
|
||||
case 'type':
|
||||
return `Type into ${command.selector}`;
|
||||
case 'click':
|
||||
return `Click ${command.selector}`;
|
||||
case 'dblclick':
|
||||
return `Double-click ${command.selector}`;
|
||||
case 'tap':
|
||||
return `Tap ${command.selector}`;
|
||||
case 'download':
|
||||
return `Download via ${command.selector} to ${command.path}`;
|
||||
case 'upload':
|
||||
return `Upload files to ${command.selector}`;
|
||||
default:
|
||||
return `${category}: ${action}`;
|
||||
}
|
||||
}
|
||||
+13
-2
@@ -1005,7 +1005,7 @@ async function handleSnapshot(
|
||||
});
|
||||
|
||||
// Simplify refs for output (just role and name)
|
||||
const simpleRefs: Record<string, { role: string; name?: string }> = {};
|
||||
const simpleRefs: Record<string, { role: string; name: string }> = {};
|
||||
for (const [ref, data] of Object.entries(refs)) {
|
||||
simpleRefs[ref] = { role: data.role, name: data.name };
|
||||
}
|
||||
@@ -1378,9 +1378,20 @@ async function handleCookiesSet(
|
||||
): Promise<Response> {
|
||||
const page = browser.getPage();
|
||||
const context = page.context();
|
||||
// Auto-fill URL for cookies that don't have domain/path/url set
|
||||
// Playwright requires either `url` or a complete `domain` + `path` pair.
|
||||
// If none are provided, we default to the current page URL.
|
||||
const pageUrl = page.url();
|
||||
const cookies = command.cookies.map((cookie) => {
|
||||
const hasUrl = Boolean(cookie.url);
|
||||
const hasDomain = Boolean(cookie.domain);
|
||||
const hasPath = Boolean(cookie.path);
|
||||
|
||||
if (!hasUrl && hasDomain !== hasPath) {
|
||||
throw new Error(
|
||||
`Invalid cookie "${cookie.name}": provide either url, or both domain and path`
|
||||
);
|
||||
}
|
||||
|
||||
if (!cookie.url && !cookie.domain && !cookie.path) {
|
||||
return { ...cookie, url: pageUrl };
|
||||
}
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Standalone CLI entry point for auth vault operations that don't need a browser.
|
||||
* Invoked directly by the Rust CLI to avoid sending passwords through the daemon channel.
|
||||
*
|
||||
* Usage: node auth-cli.js <json-command>
|
||||
* Prints a JSON response to stdout and exits.
|
||||
*/
|
||||
import {
|
||||
saveAuthProfile,
|
||||
getAuthProfileMeta,
|
||||
listAuthProfiles,
|
||||
deleteAuthProfile,
|
||||
} from './auth-vault.js';
|
||||
|
||||
interface AuthCommand {
|
||||
id: string;
|
||||
action: string;
|
||||
name?: string;
|
||||
url?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
usernameSelector?: string;
|
||||
passwordSelector?: string;
|
||||
submitSelector?: string;
|
||||
}
|
||||
|
||||
function success(id: string, data: Record<string, unknown>): string {
|
||||
return JSON.stringify({ success: true, id, data });
|
||||
}
|
||||
|
||||
function error(id: string, message: string): string {
|
||||
return JSON.stringify({ success: false, id, error: message });
|
||||
}
|
||||
|
||||
function run(): void {
|
||||
const input = process.argv[2];
|
||||
if (!input) {
|
||||
process.stderr.write('Usage: node auth-cli.js <json-command>\n');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let cmd: AuthCommand;
|
||||
try {
|
||||
cmd = JSON.parse(input);
|
||||
} catch {
|
||||
console.log(error('', 'Invalid JSON input'));
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const id = cmd.id || '';
|
||||
|
||||
try {
|
||||
switch (cmd.action) {
|
||||
case 'auth_save': {
|
||||
if (!cmd.name || !cmd.url || !cmd.username || !cmd.password) {
|
||||
console.log(error(id, 'Missing required fields: name, url, username, password'));
|
||||
return;
|
||||
}
|
||||
const meta = saveAuthProfile({
|
||||
name: cmd.name,
|
||||
url: cmd.url,
|
||||
username: cmd.username,
|
||||
password: cmd.password,
|
||||
usernameSelector: cmd.usernameSelector,
|
||||
passwordSelector: cmd.passwordSelector,
|
||||
submitSelector: cmd.submitSelector,
|
||||
});
|
||||
console.log(
|
||||
success(id, {
|
||||
saved: !meta.updated,
|
||||
updated: meta.updated,
|
||||
name: meta.name,
|
||||
url: meta.url,
|
||||
username: meta.username,
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
case 'auth_list': {
|
||||
const profiles = listAuthProfiles();
|
||||
console.log(success(id, { profiles }));
|
||||
return;
|
||||
}
|
||||
case 'auth_show': {
|
||||
if (!cmd.name) {
|
||||
console.log(error(id, 'Missing required field: name'));
|
||||
return;
|
||||
}
|
||||
const meta = getAuthProfileMeta(cmd.name);
|
||||
if (!meta) {
|
||||
console.log(error(id, `Auth profile '${cmd.name}' not found`));
|
||||
return;
|
||||
}
|
||||
console.log(success(id, { profile: meta }));
|
||||
return;
|
||||
}
|
||||
case 'auth_delete': {
|
||||
if (!cmd.name) {
|
||||
console.log(error(id, 'Missing required field: name'));
|
||||
return;
|
||||
}
|
||||
const deleted = deleteAuthProfile(cmd.name);
|
||||
if (!deleted) {
|
||||
console.log(error(id, `Auth profile '${cmd.name}' not found`));
|
||||
return;
|
||||
}
|
||||
console.log(success(id, { deleted: true, name: cmd.name }));
|
||||
return;
|
||||
}
|
||||
default:
|
||||
console.log(error(id, `Unknown auth action: ${cmd.action}`));
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'Operation failed';
|
||||
console.log(error(id, msg));
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
|
||||
let tempHome: string;
|
||||
|
||||
vi.mock('node:os', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('os')>();
|
||||
return {
|
||||
...actual,
|
||||
default: {
|
||||
...actual,
|
||||
homedir: () => tempHome,
|
||||
},
|
||||
homedir: () => tempHome,
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
saveAuthProfile,
|
||||
getAuthProfile,
|
||||
getAuthProfileMeta,
|
||||
listAuthProfiles,
|
||||
deleteAuthProfile,
|
||||
updateLastLogin,
|
||||
} from './auth-vault.js';
|
||||
|
||||
describe('auth-vault', () => {
|
||||
beforeEach(() => {
|
||||
tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-browser-auth-test-'));
|
||||
delete process.env.AGENT_BROWSER_ENCRYPTION_KEY;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
try {
|
||||
fs.rmSync(tempHome, { recursive: true, force: true });
|
||||
} catch {
|
||||
// ignore cleanup errors
|
||||
}
|
||||
});
|
||||
|
||||
function cleanAuthDir() {
|
||||
const authDir = path.join(tempHome, '.agent-browser', 'auth');
|
||||
if (fs.existsSync(authDir)) {
|
||||
for (const f of fs.readdirSync(authDir)) {
|
||||
fs.unlinkSync(path.join(authDir, f));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('saveAuthProfile', () => {
|
||||
it('should save a new profile', () => {
|
||||
const result = saveAuthProfile({
|
||||
name: 'github',
|
||||
url: 'https://github.com/login',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
});
|
||||
|
||||
expect(result.name).toBe('github');
|
||||
expect(result.url).toBe('https://github.com/login');
|
||||
expect(result.username).toBe('user');
|
||||
expect(result.updated).toBe(false);
|
||||
expect(result.createdAt).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should mark as updated when overwriting', () => {
|
||||
saveAuthProfile({
|
||||
name: 'github',
|
||||
url: 'https://github.com/login',
|
||||
username: 'user1',
|
||||
password: 'pass1',
|
||||
});
|
||||
|
||||
const result = saveAuthProfile({
|
||||
name: 'github',
|
||||
url: 'https://github.com/login',
|
||||
username: 'user2',
|
||||
password: 'pass2',
|
||||
});
|
||||
|
||||
expect(result.updated).toBe(true);
|
||||
expect(result.username).toBe('user2');
|
||||
});
|
||||
|
||||
it('should preserve createdAt on update', () => {
|
||||
const first = saveAuthProfile({
|
||||
name: 'github',
|
||||
url: 'https://github.com/login',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
});
|
||||
|
||||
const second = saveAuthProfile({
|
||||
name: 'github',
|
||||
url: 'https://github.com/login',
|
||||
username: 'user2',
|
||||
password: 'pass2',
|
||||
});
|
||||
|
||||
expect(second.createdAt).toBe(first.createdAt);
|
||||
});
|
||||
|
||||
it('should save with custom selectors', () => {
|
||||
saveAuthProfile({
|
||||
name: 'myapp',
|
||||
url: 'https://example.com/login',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
usernameSelector: '#email',
|
||||
passwordSelector: '#password',
|
||||
submitSelector: 'button.login',
|
||||
});
|
||||
|
||||
const profile = getAuthProfile('myapp');
|
||||
expect(profile).not.toBeNull();
|
||||
expect(profile!.usernameSelector).toBe('#email');
|
||||
expect(profile!.passwordSelector).toBe('#password');
|
||||
expect(profile!.submitSelector).toBe('button.login');
|
||||
});
|
||||
|
||||
it('should reject invalid profile names', () => {
|
||||
expect(() =>
|
||||
saveAuthProfile({
|
||||
name: '../escape',
|
||||
url: 'https://example.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
})
|
||||
).toThrow('only alphanumeric');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAuthProfile', () => {
|
||||
it('should return null for non-existent profile', () => {
|
||||
expect(getAuthProfile('nonexistent')).toBeNull();
|
||||
});
|
||||
|
||||
it('should return full profile with password', () => {
|
||||
saveAuthProfile({
|
||||
name: 'test',
|
||||
url: 'https://example.com',
|
||||
username: 'user',
|
||||
password: 'secret',
|
||||
});
|
||||
|
||||
const profile = getAuthProfile('test');
|
||||
expect(profile).not.toBeNull();
|
||||
expect(profile!.password).toBe('secret');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAuthProfileMeta', () => {
|
||||
it('should return metadata without password', () => {
|
||||
saveAuthProfile({
|
||||
name: 'test',
|
||||
url: 'https://example.com',
|
||||
username: 'user',
|
||||
password: 'secret',
|
||||
});
|
||||
|
||||
const meta = getAuthProfileMeta('test');
|
||||
expect(meta).not.toBeNull();
|
||||
expect(meta!.name).toBe('test');
|
||||
expect(meta!.username).toBe('user');
|
||||
expect((meta as Record<string, unknown>).password).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return null for non-existent profile', () => {
|
||||
expect(getAuthProfileMeta('nonexistent')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listAuthProfiles', () => {
|
||||
it('should return empty array when no profiles', () => {
|
||||
cleanAuthDir();
|
||||
expect(listAuthProfiles()).toEqual([]);
|
||||
});
|
||||
|
||||
it('should list all saved profiles', () => {
|
||||
cleanAuthDir();
|
||||
saveAuthProfile({
|
||||
name: 'github',
|
||||
url: 'https://github.com/login',
|
||||
username: 'user1',
|
||||
password: 'pass1',
|
||||
});
|
||||
saveAuthProfile({
|
||||
name: 'gitlab',
|
||||
url: 'https://gitlab.com/login',
|
||||
username: 'user2',
|
||||
password: 'pass2',
|
||||
});
|
||||
|
||||
const profiles = listAuthProfiles();
|
||||
expect(profiles).toHaveLength(2);
|
||||
const names = profiles.map((p) => p.name).sort();
|
||||
expect(names).toEqual(['github', 'gitlab']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteAuthProfile', () => {
|
||||
it('should delete an existing profile', () => {
|
||||
saveAuthProfile({
|
||||
name: 'test',
|
||||
url: 'https://example.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
});
|
||||
|
||||
expect(deleteAuthProfile('test')).toBe(true);
|
||||
expect(getAuthProfile('test')).toBeNull();
|
||||
});
|
||||
|
||||
it('should return false for non-existent profile', () => {
|
||||
expect(deleteAuthProfile('nonexistent')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateLastLogin', () => {
|
||||
it('should update lastLoginAt timestamp', () => {
|
||||
saveAuthProfile({
|
||||
name: 'test',
|
||||
url: 'https://example.com',
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
});
|
||||
|
||||
const metaBefore = getAuthProfileMeta('test');
|
||||
expect(metaBefore!.lastLoginAt).toBeUndefined();
|
||||
|
||||
updateLastLogin('test');
|
||||
|
||||
const metaAfter = getAuthProfileMeta('test');
|
||||
expect(metaAfter!.lastLoginAt).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('auto-generated encryption key', () => {
|
||||
it('should auto-create key file and encrypt profile when no env var is set', () => {
|
||||
delete process.env.AGENT_BROWSER_ENCRYPTION_KEY;
|
||||
|
||||
saveAuthProfile({
|
||||
name: 'autokey',
|
||||
url: 'https://example.com',
|
||||
username: 'user',
|
||||
password: 'secret',
|
||||
});
|
||||
|
||||
const keyFilePath = path.join(tempHome, '.agent-browser', '.encryption-key');
|
||||
expect(fs.existsSync(keyFilePath)).toBe(true);
|
||||
|
||||
const keyHex = fs.readFileSync(keyFilePath, 'utf-8').trim();
|
||||
expect(keyHex).toMatch(/^[a-f0-9]{64}$/);
|
||||
|
||||
const profilePath = path.join(tempHome, '.agent-browser', 'auth', 'autokey.json');
|
||||
const raw = JSON.parse(fs.readFileSync(profilePath, 'utf-8'));
|
||||
expect(raw.encrypted).toBe(true);
|
||||
expect(raw.iv).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should read back profile using auto-generated key', () => {
|
||||
delete process.env.AGENT_BROWSER_ENCRYPTION_KEY;
|
||||
|
||||
saveAuthProfile({
|
||||
name: 'readback',
|
||||
url: 'https://example.com',
|
||||
username: 'user',
|
||||
password: 'secret123',
|
||||
});
|
||||
|
||||
const profile = getAuthProfile('readback');
|
||||
expect(profile).not.toBeNull();
|
||||
expect(profile!.password).toBe('secret123');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
readdirSync,
|
||||
unlinkSync,
|
||||
} from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import {
|
||||
getEncryptionKey,
|
||||
ensureEncryptionKey,
|
||||
encryptData,
|
||||
decryptData,
|
||||
isEncryptedPayload,
|
||||
getKeyFilePath,
|
||||
restrictFilePermissions,
|
||||
restrictDirPermissions,
|
||||
type EncryptedPayload,
|
||||
} from './encryption.js';
|
||||
|
||||
const AUTH_DIR = 'auth';
|
||||
|
||||
interface AuthProfile {
|
||||
name: string;
|
||||
url: string;
|
||||
username: string;
|
||||
password: string;
|
||||
usernameSelector?: string;
|
||||
passwordSelector?: string;
|
||||
submitSelector?: string;
|
||||
createdAt: string;
|
||||
lastLoginAt?: string;
|
||||
}
|
||||
|
||||
export interface AuthProfileMeta {
|
||||
name: string;
|
||||
url: string;
|
||||
username: string;
|
||||
createdAt: string;
|
||||
lastLoginAt?: string;
|
||||
}
|
||||
|
||||
function getAuthDir(): string {
|
||||
const dir = path.join(os.homedir(), '.agent-browser', AUTH_DIR);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
restrictDirPermissions(dir);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
const SAFE_NAME_RE = /^[a-zA-Z0-9_-]+$/;
|
||||
|
||||
function validateProfileName(name: string): void {
|
||||
if (!SAFE_NAME_RE.test(name)) {
|
||||
throw new Error(
|
||||
`Invalid auth profile name '${name}': only alphanumeric characters, hyphens, and underscores are allowed`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function profilePath(name: string): string {
|
||||
validateProfileName(name);
|
||||
return path.join(getAuthDir(), `${name}.json`);
|
||||
}
|
||||
|
||||
function readProfile(name: string): AuthProfile | null {
|
||||
const p = profilePath(name);
|
||||
if (!existsSync(p)) return null;
|
||||
|
||||
const raw = readFileSync(p, 'utf-8');
|
||||
const parsed = JSON.parse(raw);
|
||||
|
||||
if (isEncryptedPayload(parsed)) {
|
||||
const key = getEncryptionKey();
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`Encryption key required to read encrypted auth profiles. ` +
|
||||
`Set AGENT_BROWSER_ENCRYPTION_KEY or ensure ${getKeyFilePath()} exists.`
|
||||
);
|
||||
}
|
||||
const decrypted = decryptData(parsed as EncryptedPayload, key);
|
||||
return JSON.parse(decrypted) as AuthProfile;
|
||||
}
|
||||
|
||||
return parsed as AuthProfile;
|
||||
}
|
||||
|
||||
function writeProfile(profile: AuthProfile): void {
|
||||
const key = ensureEncryptionKey();
|
||||
const serialized = JSON.stringify(profile, null, 2);
|
||||
const encrypted = encryptData(serialized, key);
|
||||
const filePath = profilePath(profile.name);
|
||||
writeFileSync(filePath, JSON.stringify(encrypted, null, 2), {
|
||||
mode: 0o600,
|
||||
});
|
||||
restrictFilePermissions(filePath);
|
||||
}
|
||||
|
||||
export function saveAuthProfile(opts: {
|
||||
name: string;
|
||||
url: string;
|
||||
username: string;
|
||||
password: string;
|
||||
usernameSelector?: string;
|
||||
passwordSelector?: string;
|
||||
submitSelector?: string;
|
||||
}): AuthProfileMeta & { updated: boolean } {
|
||||
const existing = readProfile(opts.name);
|
||||
|
||||
const profile: AuthProfile = {
|
||||
name: opts.name,
|
||||
url: opts.url,
|
||||
username: opts.username,
|
||||
password: opts.password,
|
||||
usernameSelector: opts.usernameSelector,
|
||||
passwordSelector: opts.passwordSelector,
|
||||
submitSelector: opts.submitSelector,
|
||||
createdAt: existing?.createdAt ?? new Date().toISOString(),
|
||||
lastLoginAt: existing?.lastLoginAt,
|
||||
};
|
||||
|
||||
writeProfile(profile);
|
||||
|
||||
return {
|
||||
name: profile.name,
|
||||
url: profile.url,
|
||||
username: profile.username,
|
||||
createdAt: profile.createdAt,
|
||||
lastLoginAt: profile.lastLoginAt,
|
||||
updated: existing !== null,
|
||||
};
|
||||
}
|
||||
|
||||
export function getAuthProfile(name: string): AuthProfile | null {
|
||||
return readProfile(name);
|
||||
}
|
||||
|
||||
export function getAuthProfileMeta(name: string): AuthProfileMeta | null {
|
||||
const profile = readProfile(name);
|
||||
if (!profile) return null;
|
||||
return {
|
||||
name: profile.name,
|
||||
url: profile.url,
|
||||
username: profile.username,
|
||||
createdAt: profile.createdAt,
|
||||
lastLoginAt: profile.lastLoginAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function listAuthProfiles(): AuthProfileMeta[] {
|
||||
const dir = getAuthDir();
|
||||
const files = readdirSync(dir).filter((f) => f.endsWith('.json'));
|
||||
const profiles: AuthProfileMeta[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
const name = file.replace(/\.json$/, '');
|
||||
try {
|
||||
const meta = getAuthProfileMeta(name);
|
||||
if (meta) profiles.push(meta);
|
||||
} catch {
|
||||
profiles.push({
|
||||
name,
|
||||
url: '(encrypted)',
|
||||
username: '(encrypted)',
|
||||
createdAt: '(unknown)',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return profiles;
|
||||
}
|
||||
|
||||
export function deleteAuthProfile(name: string): boolean {
|
||||
const p = profilePath(name);
|
||||
if (!existsSync(p)) return false;
|
||||
unlinkSync(p);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function updateLastLogin(name: string): void {
|
||||
const profile = readProfile(name);
|
||||
if (profile) {
|
||||
profile.lastLoginAt = new Date().toISOString();
|
||||
writeProfile(profile);
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,56 @@ describe('BrowserManager', () => {
|
||||
await newBrowser.close();
|
||||
});
|
||||
|
||||
it('should switch from local session when auto-connect is explicitly requested', async () => {
|
||||
const testBrowser = new BrowserManager();
|
||||
await testBrowser.launch({ id: 'test', action: 'launch', headless: true });
|
||||
|
||||
const closeSpy = vi.spyOn(testBrowser, 'close');
|
||||
const autoConnectSpy = vi
|
||||
.spyOn(testBrowser as any, 'autoConnectViaCDP')
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
await testBrowser.launch({ id: 'test', action: 'launch', autoConnect: true });
|
||||
|
||||
expect(closeSpy).toHaveBeenCalledTimes(1);
|
||||
expect(autoConnectSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
autoConnectSpy.mockRestore();
|
||||
closeSpy.mockRestore();
|
||||
await testBrowser.close();
|
||||
});
|
||||
|
||||
it('should not relaunch when already connected via healthy CDP and auto-connect is requested', async () => {
|
||||
const addInitScript = vi.fn().mockResolvedValue(undefined);
|
||||
const mockPage = { url: () => 'http://example.com', on: vi.fn(), isClosed: () => false };
|
||||
const mockContext = {
|
||||
pages: () => [mockPage],
|
||||
on: vi.fn(),
|
||||
setDefaultTimeout: vi.fn(),
|
||||
addInitScript,
|
||||
};
|
||||
const mockBrowser = {
|
||||
contexts: () => [mockContext],
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
isConnected: vi.fn(() => true),
|
||||
};
|
||||
const connectSpy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
|
||||
|
||||
const cdpBrowser = new BrowserManager();
|
||||
await cdpBrowser.launch({ id: 'test', action: 'launch', cdpPort: 9222 });
|
||||
expect(connectSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
const closeSpy = vi.spyOn(cdpBrowser, 'close');
|
||||
await cdpBrowser.launch({ id: 'test', action: 'launch', autoConnect: true });
|
||||
|
||||
expect(closeSpy).not.toHaveBeenCalled();
|
||||
expect(connectSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
closeSpy.mockRestore();
|
||||
await cdpBrowser.close();
|
||||
connectSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should report local stealth policy capabilities', async () => {
|
||||
const testBrowser = new BrowserManager();
|
||||
await testBrowser.launch({ headless: true });
|
||||
@@ -97,6 +147,90 @@ describe('BrowserManager', () => {
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should reject CDP endpoints with only blank pages when meaningful tabs are required', async () => {
|
||||
const mockPage = { url: () => 'about:blank', on: vi.fn(), isClosed: () => false };
|
||||
const mockContext = {
|
||||
pages: () => [mockPage],
|
||||
on: vi.fn(),
|
||||
setDefaultTimeout: vi.fn(),
|
||||
addInitScript: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const mockBrowser = {
|
||||
contexts: () => [mockContext],
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
isConnected: vi.fn(() => true),
|
||||
};
|
||||
const connectSpy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
|
||||
|
||||
const cdpBrowser = new BrowserManager();
|
||||
await expect(
|
||||
(cdpBrowser as any).connectViaCDP('9222', {
|
||||
allowCreatePageFallback: false,
|
||||
requireMeaningfulPage: true,
|
||||
})
|
||||
).rejects.toThrow('No existing user tabs found on this CDP endpoint.');
|
||||
|
||||
expect(mockBrowser.close).toHaveBeenCalledTimes(1);
|
||||
connectSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should skip auto-connect candidates without user tabs and continue discovery', async () => {
|
||||
const cdpBrowser = new BrowserManager();
|
||||
const dirsSpy = vi
|
||||
.spyOn(cdpBrowser as any, 'getChromeUserDataDirs')
|
||||
.mockReturnValue(['/tmp/chrome-a', '/tmp/chrome-b']);
|
||||
const activePortSpy = vi.spyOn(cdpBrowser as any, 'readDevToolsActivePort');
|
||||
activePortSpy
|
||||
.mockReturnValueOnce({ port: 9222, wsPath: '/devtools/browser/a' })
|
||||
.mockReturnValueOnce({ port: 9333, wsPath: '/devtools/browser/b' });
|
||||
const probeSpy = vi.spyOn(cdpBrowser as any, 'probeDebugPort');
|
||||
probeSpy
|
||||
.mockResolvedValueOnce('ws://127.0.0.1:9222/devtools/browser/a')
|
||||
.mockResolvedValueOnce('ws://127.0.0.1:9333/devtools/browser/b');
|
||||
const connectViaCDPSpy = vi.spyOn(cdpBrowser as any, 'connectViaCDP');
|
||||
connectViaCDPSpy
|
||||
.mockRejectedValueOnce(new Error('No existing user tabs found on this CDP endpoint.'))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
|
||||
await (cdpBrowser as any).autoConnectViaCDP();
|
||||
|
||||
expect(connectViaCDPSpy).toHaveBeenCalledTimes(2);
|
||||
expect(connectViaCDPSpy.mock.calls[0][1]).toMatchObject({
|
||||
allowCreatePageFallback: false,
|
||||
requireMeaningfulPage: true,
|
||||
});
|
||||
expect(connectViaCDPSpy.mock.calls[1][1]).toMatchObject({
|
||||
allowCreatePageFallback: false,
|
||||
requireMeaningfulPage: true,
|
||||
});
|
||||
|
||||
dirsSpy.mockRestore();
|
||||
activePortSpy.mockRestore();
|
||||
probeSpy.mockRestore();
|
||||
connectViaCDPSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should prefer port 9333 before DevToolsActivePort discovery in auto-connect', async () => {
|
||||
const cdpBrowser = new BrowserManager();
|
||||
const probeSpy = vi.spyOn(cdpBrowser as any, 'probeDebugPort');
|
||||
probeSpy.mockResolvedValueOnce('ws://127.0.0.1:9333/devtools/browser/preferred');
|
||||
const connectViaCDPSpy = vi
|
||||
.spyOn(cdpBrowser as any, 'connectViaCDP')
|
||||
.mockResolvedValue(undefined);
|
||||
const dirsSpy = vi.spyOn(cdpBrowser as any, 'getChromeUserDataDirs');
|
||||
|
||||
await (cdpBrowser as any).autoConnectViaCDP();
|
||||
|
||||
expect(probeSpy).toHaveBeenCalledWith(9333);
|
||||
expect(connectViaCDPSpy).toHaveBeenCalledTimes(1);
|
||||
expect(connectViaCDPSpy.mock.calls[0][0]).toContain('9333');
|
||||
expect(dirsSpy).not.toHaveBeenCalled();
|
||||
|
||||
probeSpy.mockRestore();
|
||||
connectViaCDPSpy.mockRestore();
|
||||
dirsSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should ignore legacy stealth=false and keep CDP stealth capabilities enabled', async () => {
|
||||
const addInitScript = vi.fn().mockResolvedValue(undefined);
|
||||
const mockPage = { url: () => 'http://example.com', on: vi.fn(), isClosed: () => false };
|
||||
@@ -227,6 +361,30 @@ describe('BrowserManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('unnamed-button ref uniqueness', () => {
|
||||
it('should click the correct unnamed button among named buttons', async () => {
|
||||
const page = browser.getPage();
|
||||
// 1 unnamed button among 2 named buttons
|
||||
await page.setContent(`
|
||||
<html><body>
|
||||
<button>OK</button>
|
||||
<button onclick="document.title='unnamed'"></button>
|
||||
<button>Cancel</button>
|
||||
</body></html>
|
||||
`);
|
||||
|
||||
const snapshot = await browser.getSnapshot();
|
||||
const refs = snapshot.refs;
|
||||
const unnamedRefs = Object.entries(refs).filter(([, v]) => v.role === 'button' && !v.name);
|
||||
expect(unnamedRefs.length).toBe(1);
|
||||
|
||||
const [refId] = unnamedRefs[0];
|
||||
await executeCommand({ id: 'test', action: 'click', selector: `@${refId}` }, browser);
|
||||
const title = await page.title();
|
||||
expect(title).toBe('unnamed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cursor-ref selector uniqueness', () => {
|
||||
it('should produce unique selectors for repeated DOM structures', async () => {
|
||||
const page = browser.getPage();
|
||||
|
||||
+209
-16
@@ -21,6 +21,7 @@ import { writeFile, mkdir } from 'node:fs/promises';
|
||||
import type { LaunchCommand, TraceEvent } from './types.js';
|
||||
import { type RefMap, type EnhancedSnapshot, getEnhancedSnapshot, parseRef } from './snapshot.js';
|
||||
import { safeHeaderMerge } from './state-utils.js';
|
||||
import { isDomainAllowed, installDomainFilter, parseDomainList } from './domain-filter.js';
|
||||
import {
|
||||
getEncryptionKey,
|
||||
isEncryptedPayload,
|
||||
@@ -161,6 +162,7 @@ export class BrowserManager {
|
||||
private contextHeaders: Record<string, string> | undefined = undefined;
|
||||
private contextUserAgent: string | undefined = undefined;
|
||||
private downloadPath: string | null = null;
|
||||
private allowedDomains: string[] = [];
|
||||
|
||||
/**
|
||||
* Set the persistent color scheme preference.
|
||||
@@ -551,12 +553,10 @@ export class BrowserManager {
|
||||
}
|
||||
|
||||
// Build locator with exact: true to avoid substring matches
|
||||
let locator: Locator;
|
||||
if (refData.name) {
|
||||
locator = page.getByRole(refData.role as any, { name: refData.name, exact: true });
|
||||
} else {
|
||||
locator = page.getByRole(refData.role as any);
|
||||
}
|
||||
let locator: Locator = page.getByRole(refData.role as any, {
|
||||
name: refData.name,
|
||||
exact: true,
|
||||
});
|
||||
|
||||
// If an nth index is stored (for disambiguation), use it
|
||||
if (refData.nth !== undefined) {
|
||||
@@ -573,6 +573,61 @@ export class BrowserManager {
|
||||
return parseRef(selector) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the domain filter on a context if an allowlist is configured.
|
||||
* Should be called before any pages navigate on the context.
|
||||
*/
|
||||
private async ensureDomainFilter(context: BrowserContext): Promise<void> {
|
||||
if (this.allowedDomains.length > 0) {
|
||||
await installDomainFilter(context, this.allowedDomains);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After installing the domain filter, verify existing pages are on allowed
|
||||
* domains. Pages that pre-date the filter (e.g. CDP/cloud connect) may have
|
||||
* already navigated to disallowed domains. Navigate them to about:blank.
|
||||
*/
|
||||
private async sanitizeExistingPages(pages: Page[]): Promise<void> {
|
||||
if (this.allowedDomains.length === 0) return;
|
||||
for (const page of pages) {
|
||||
const url = page.url();
|
||||
if (!url || url === 'about:blank') continue;
|
||||
try {
|
||||
const hostname = new URL(url).hostname.toLowerCase();
|
||||
if (!isDomainAllowed(hostname, this.allowedDomains)) {
|
||||
await page.goto('about:blank');
|
||||
}
|
||||
} catch {
|
||||
await page.goto('about:blank').catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a URL is allowed by the domain allowlist.
|
||||
* Throws if the URL's domain is blocked. No-op if no allowlist is set.
|
||||
* Blocks non-http(s) schemes and unparseable URLs by default.
|
||||
*/
|
||||
checkDomainAllowed(url: string): void {
|
||||
if (this.allowedDomains.length === 0) return;
|
||||
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
throw new Error(`Navigation blocked: non-http(s) scheme in URL "${url}"`);
|
||||
}
|
||||
|
||||
let hostname: string;
|
||||
try {
|
||||
hostname = new URL(url).hostname.toLowerCase();
|
||||
} catch {
|
||||
throw new Error(`Navigation blocked: unable to parse URL "${url}"`);
|
||||
}
|
||||
|
||||
if (!isDomainAllowed(hostname, this.allowedDomains)) {
|
||||
throw new Error(`Navigation blocked: ${hostname} is not in the allowed domains list`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get locator - supports both refs and regular selectors
|
||||
*/
|
||||
@@ -614,6 +669,16 @@ export class BrowserManager {
|
||||
return !this.isIgnoredCDPPageUrl(url);
|
||||
}
|
||||
|
||||
private isMeaningfulCDPPage(page: Page): boolean {
|
||||
if (page.isClosed()) return false;
|
||||
const url = this.getSafePageUrl(page).trim().toLowerCase();
|
||||
if (!url) return false;
|
||||
if (url === 'about:blank' || url.startsWith('about:blank#')) return false;
|
||||
if (url === 'chrome://newtab/' || url.startsWith('chrome://newtab')) return false;
|
||||
if (url === 'chrome://new-tab-page/' || url.startsWith('chrome://new-tab-page')) return false;
|
||||
return !this.isIgnoredCDPPageUrl(url);
|
||||
}
|
||||
|
||||
private collectUsableCDPPages(contexts: BrowserContext[]): Page[] {
|
||||
return contexts
|
||||
.flatMap((context) => context.pages())
|
||||
@@ -645,6 +710,7 @@ export class BrowserManager {
|
||||
context.setDefaultTimeout(getDefaultTimeout());
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
await this.ensureDomainFilter(context);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
@@ -1278,6 +1344,8 @@ export class BrowserManager {
|
||||
context.setDefaultTimeout(10000);
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
await this.ensureDomainFilter(context);
|
||||
await this.sanitizeExistingPages([page]);
|
||||
this.pages.push(page);
|
||||
this.activePageIndex = 0;
|
||||
this.setupPageTracking(page);
|
||||
@@ -1421,10 +1489,12 @@ export class BrowserManager {
|
||||
this.browser = browser;
|
||||
context.setDefaultTimeout(getDefaultTimeout());
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
await this.ensureDomainFilter(context);
|
||||
await this.sanitizeExistingPages([page]);
|
||||
this.pages.push(page);
|
||||
this.activePageIndex = 0;
|
||||
this.setupPageTracking(page);
|
||||
this.setupContextTracking(context);
|
||||
} catch (error) {
|
||||
await this.closeKernelSession(session.session_id, kernelApiKey).catch((sessionError) => {
|
||||
console.error('Failed to close Kernel session during cleanup:', sessionError);
|
||||
@@ -1497,10 +1567,12 @@ export class BrowserManager {
|
||||
this.browser = browser;
|
||||
context.setDefaultTimeout(getDefaultTimeout());
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
await this.ensureDomainFilter(context);
|
||||
await this.sanitizeExistingPages([page]);
|
||||
this.pages.push(page);
|
||||
this.activePageIndex = 0;
|
||||
this.setupPageTracking(page);
|
||||
this.setupContextTracking(context);
|
||||
} catch (error) {
|
||||
await this.closeBrowserUseSession(session.id, browserUseApiKey).catch((sessionError) => {
|
||||
console.error('Failed to close Browser Use session during cleanup:', sessionError);
|
||||
@@ -1530,7 +1602,13 @@ export class BrowserManager {
|
||||
}
|
||||
|
||||
if (this.isLaunched()) {
|
||||
// Explicit --auto-connect should switch away from managed/local/provider sessions
|
||||
// so commands always target a discovered user browser.
|
||||
const shouldSwitchToAutoConnect =
|
||||
!!options.autoConnect &&
|
||||
(this.cdpEndpoint === null || this.stealthConnectionKind !== 'cdp');
|
||||
const needsRelaunch =
|
||||
shouldSwitchToAutoConnect ||
|
||||
(!cdpEndpoint && !options.autoConnect && this.cdpEndpoint !== null) ||
|
||||
(!!cdpEndpoint && this.needsCdpReconnect(cdpEndpoint)) ||
|
||||
(!!options.autoConnect && !this.isCdpConnectionAlive());
|
||||
@@ -1572,6 +1650,15 @@ export class BrowserManager {
|
||||
this.downloadPath = options.downloadPath;
|
||||
}
|
||||
|
||||
if (options.allowedDomains && options.allowedDomains.length > 0) {
|
||||
this.allowedDomains = options.allowedDomains.map((d: string) => d.toLowerCase());
|
||||
} else {
|
||||
const envDomains = process.env.AGENT_BROWSER_ALLOWED_DOMAINS;
|
||||
if (envDomains) {
|
||||
this.allowedDomains = parseDomainList(envDomains);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.downloadPath && (cdpEndpoint || options.autoConnect)) {
|
||||
const warning =
|
||||
"--download-path is ignored when connecting via CDP or auto-connect (downloads use the remote browser's configuration)";
|
||||
@@ -1832,8 +1919,10 @@ export class BrowserManager {
|
||||
context.setDefaultTimeout(getDefaultTimeout());
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
await this.ensureDomainFilter(context);
|
||||
|
||||
const page = context.pages()[0] ?? (await context.newPage());
|
||||
await this.sanitizeExistingPages([page]);
|
||||
// Only add if not already tracked (setupContextTracking may have already added it via 'page' event)
|
||||
if (!this.pages.includes(page)) {
|
||||
this.pages.push(page);
|
||||
@@ -1848,7 +1937,11 @@ export class BrowserManager {
|
||||
*/
|
||||
private async connectViaCDP(
|
||||
cdpEndpoint: string | undefined,
|
||||
options?: { timeout?: number }
|
||||
options?: {
|
||||
timeout?: number;
|
||||
allowCreatePageFallback?: boolean;
|
||||
requireMeaningfulPage?: boolean;
|
||||
}
|
||||
): Promise<void> {
|
||||
this.stealthConnectionKind = 'cdp';
|
||||
if (!cdpEndpoint) {
|
||||
@@ -1894,8 +1987,12 @@ export class BrowserManager {
|
||||
}
|
||||
|
||||
let allPages = this.collectUsableCDPPages(contexts);
|
||||
const allowCreatePageFallback = options?.allowCreatePageFallback ?? true;
|
||||
|
||||
if (allPages.length === 0) {
|
||||
if (!allowCreatePageFallback) {
|
||||
throw new Error('No existing user tabs found on this CDP endpoint.');
|
||||
}
|
||||
// Some Chrome instances (especially with custom UI pages) expose only internal/transient
|
||||
// pages over CDP. Create a fresh page so commands always have a stable target.
|
||||
let fallbackPage: Page | null = null;
|
||||
@@ -1921,6 +2018,14 @@ export class BrowserManager {
|
||||
allPages = [fallbackPage];
|
||||
}
|
||||
|
||||
if (options?.requireMeaningfulPage) {
|
||||
const meaningfulPages = allPages.filter((page) => this.isMeaningfulCDPPage(page));
|
||||
if (meaningfulPages.length === 0) {
|
||||
throw new Error('No existing user tabs found on this CDP endpoint.');
|
||||
}
|
||||
allPages = meaningfulPages;
|
||||
}
|
||||
|
||||
// All validation passed - commit state
|
||||
this.browser = browser;
|
||||
this.cdpEndpoint = cdpEndpoint;
|
||||
@@ -1930,8 +2035,11 @@ export class BrowserManager {
|
||||
context.setDefaultTimeout(10000);
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
await this.ensureDomainFilter(context);
|
||||
}
|
||||
|
||||
await this.sanitizeExistingPages(allPages);
|
||||
|
||||
for (const page of allPages) {
|
||||
this.pages.push(page);
|
||||
this.setupPageTracking(page);
|
||||
@@ -2027,6 +2135,35 @@ export class BrowserManager {
|
||||
* 4. If a port responds, connect via CDP
|
||||
*/
|
||||
private async autoConnectViaCDP(): Promise<void> {
|
||||
let sawEndpointWithoutUserTabs = false;
|
||||
|
||||
// Strategy 0: Prefer project-default resident CDP port first.
|
||||
// This keeps user + agent on the same browser session when 9333 is available.
|
||||
{
|
||||
const wsUrl = await this.probeDebugPort(9333);
|
||||
if (wsUrl) {
|
||||
try {
|
||||
await this.connectViaCDP(wsUrl, {
|
||||
allowCreatePageFallback: false,
|
||||
requireMeaningfulPage: true,
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message.includes('No existing user tabs found on this CDP endpoint')) {
|
||||
sawEndpointWithoutUserTabs = true;
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error(
|
||||
`[DEBUG] Skipping preferred CDP endpoint without user tabs (${wsUrl}): ${message}`
|
||||
);
|
||||
}
|
||||
} else if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error(`[DEBUG] Failed preferred CDP candidate (${wsUrl}): ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Strategy 1: Check DevToolsActivePort files
|
||||
const userDataDirs = this.getChromeUserDataDirs();
|
||||
for (const dir of userDataDirs) {
|
||||
@@ -2035,8 +2172,25 @@ export class BrowserManager {
|
||||
// Try HTTP discovery first (works with --remote-debugging-port mode)
|
||||
const wsUrl = await this.probeDebugPort(activePort.port);
|
||||
if (wsUrl) {
|
||||
await this.connectViaCDP(wsUrl);
|
||||
return;
|
||||
try {
|
||||
await this.connectViaCDP(wsUrl, {
|
||||
allowCreatePageFallback: false,
|
||||
requireMeaningfulPage: true,
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message.includes('No existing user tabs found on this CDP endpoint')) {
|
||||
sawEndpointWithoutUserTabs = true;
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error(
|
||||
`[DEBUG] Skipping CDP endpoint without user tabs (${wsUrl}): ${message}`
|
||||
);
|
||||
}
|
||||
} else if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error(`[DEBUG] Failed CDP candidate (${wsUrl}): ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
// HTTP probe failed -- Chrome M144+ chrome://inspect remote debugging uses a
|
||||
// WebSocket-only server with no HTTP endpoints. Connect using the WebSocket
|
||||
@@ -2049,24 +2203,62 @@ export class BrowserManager {
|
||||
`attempting direct WebSocket connection to ${directWsUrl}`
|
||||
);
|
||||
}
|
||||
await this.connectViaCDP(directWsUrl, { timeout: 60_000 });
|
||||
await this.connectViaCDP(directWsUrl, {
|
||||
timeout: 60_000,
|
||||
allowCreatePageFallback: false,
|
||||
requireMeaningfulPage: true,
|
||||
});
|
||||
return;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message.includes('No existing user tabs found on this CDP endpoint')) {
|
||||
sawEndpointWithoutUserTabs = true;
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error(
|
||||
`[DEBUG] Skipping CDP endpoint without user tabs (${directWsUrl}): ${message}`
|
||||
);
|
||||
}
|
||||
} else if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error(`[DEBUG] Failed CDP candidate (${directWsUrl}): ${message}`);
|
||||
}
|
||||
// Direct WebSocket also failed, try next directory
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Strategy 2: Probe common debugging ports
|
||||
const commonPorts = [9222, 9229, 9333];
|
||||
const commonPorts = [9222, 9229];
|
||||
for (const port of commonPorts) {
|
||||
const wsUrl = await this.probeDebugPort(port);
|
||||
if (wsUrl) {
|
||||
await this.connectViaCDP(wsUrl);
|
||||
return;
|
||||
try {
|
||||
await this.connectViaCDP(wsUrl, {
|
||||
allowCreatePageFallback: false,
|
||||
requireMeaningfulPage: true,
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message.includes('No existing user tabs found on this CDP endpoint')) {
|
||||
sawEndpointWithoutUserTabs = true;
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error(
|
||||
`[DEBUG] Skipping CDP endpoint without user tabs (${wsUrl}): ${message}`
|
||||
);
|
||||
}
|
||||
} else if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error(`[DEBUG] Failed CDP candidate (${wsUrl}): ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sawEndpointWithoutUserTabs) {
|
||||
throw new Error(
|
||||
'Found CDP endpoints, but none exposed existing user tabs. Ensure you are attaching to the same Chrome instance/profile you are using manually.'
|
||||
);
|
||||
}
|
||||
|
||||
// Nothing found
|
||||
const platform = os.platform();
|
||||
let hint: string;
|
||||
@@ -2200,6 +2392,7 @@ export class BrowserManager {
|
||||
context.setDefaultTimeout(getDefaultTimeout());
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
await this.ensureDomainFilter(context);
|
||||
|
||||
const page = await context.newPage();
|
||||
// Only add if not already tracked (setupContextTracking may have already added it via 'page' event)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { requestConfirmation, getAndRemovePending } from './confirmation.js';
|
||||
|
||||
describe('confirmation', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('requestConfirmation', () => {
|
||||
it('should return a confirmation ID', () => {
|
||||
const result = requestConfirmation('evaluate', 'eval', 'Evaluate JS', { script: 'test' });
|
||||
expect(result.confirmationId).toBeTruthy();
|
||||
expect(result.confirmationId).toMatch(/^c_[0-9a-f]{16}$/);
|
||||
});
|
||||
|
||||
it('should generate unique IDs', () => {
|
||||
const r1 = requestConfirmation('evaluate', 'eval', 'desc', {});
|
||||
const r2 = requestConfirmation('click', 'click', 'desc', {});
|
||||
expect(r1.confirmationId).not.toBe(r2.confirmationId);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAndRemovePending', () => {
|
||||
it('should retrieve and remove a pending confirmation', () => {
|
||||
const { confirmationId } = requestConfirmation('evaluate', 'eval', 'desc', {
|
||||
action: 'evaluate',
|
||||
script: 'test',
|
||||
});
|
||||
|
||||
const entry = getAndRemovePending(confirmationId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry!.action).toBe('evaluate');
|
||||
expect(entry!.command).toEqual({ action: 'evaluate', script: 'test' });
|
||||
});
|
||||
|
||||
it('should return null on second retrieval (already removed)', () => {
|
||||
const { confirmationId } = requestConfirmation('evaluate', 'eval', 'desc', {});
|
||||
getAndRemovePending(confirmationId);
|
||||
expect(getAndRemovePending(confirmationId)).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for non-existent ID', () => {
|
||||
expect(getAndRemovePending('c_nonexistent')).toBeNull();
|
||||
});
|
||||
|
||||
it('should auto-deny after 60 seconds', () => {
|
||||
const { confirmationId } = requestConfirmation('evaluate', 'eval', 'desc', {});
|
||||
|
||||
vi.advanceTimersByTime(60_000);
|
||||
|
||||
expect(getAndRemovePending(confirmationId)).toBeNull();
|
||||
});
|
||||
|
||||
it('should still be retrievable before 60 second timeout', () => {
|
||||
const { confirmationId } = requestConfirmation('evaluate', 'eval', 'desc', {});
|
||||
|
||||
vi.advanceTimersByTime(59_999);
|
||||
|
||||
const entry = getAndRemovePending(confirmationId);
|
||||
expect(entry).not.toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
|
||||
interface PendingConfirmation {
|
||||
id: string;
|
||||
action: string;
|
||||
category: string;
|
||||
description: string;
|
||||
command: Record<string, unknown>;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const AUTO_DENY_TIMEOUT_MS = 60_000;
|
||||
|
||||
const pending = new Map<string, PendingConfirmation>();
|
||||
|
||||
function generateId(): string {
|
||||
return `c_${randomBytes(8).toString('hex')}`;
|
||||
}
|
||||
|
||||
export function requestConfirmation(
|
||||
action: string,
|
||||
category: string,
|
||||
description: string,
|
||||
command: Record<string, unknown>
|
||||
): { confirmationId: string } {
|
||||
const id = generateId();
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
}, AUTO_DENY_TIMEOUT_MS);
|
||||
|
||||
pending.set(id, {
|
||||
id,
|
||||
action,
|
||||
category,
|
||||
description,
|
||||
command,
|
||||
timer,
|
||||
});
|
||||
|
||||
return { confirmationId: id };
|
||||
}
|
||||
|
||||
export function getAndRemovePending(
|
||||
id: string
|
||||
): { command: Record<string, unknown>; action: string } | null {
|
||||
const entry = pending.get(id);
|
||||
if (!entry) return null;
|
||||
|
||||
clearTimeout(entry.timer);
|
||||
pending.delete(id);
|
||||
return { command: entry.command, action: entry.action };
|
||||
}
|
||||
+43
-11
@@ -262,7 +262,12 @@ export function isDaemonRunning(session?: string): boolean {
|
||||
// Check if process exists (works on both Unix and Windows)
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
} catch (err: unknown) {
|
||||
// EPERM means the process exists but we lack permission to signal it
|
||||
// (e.g. caller is inside a macOS sandbox). Only ESRCH means it's gone.
|
||||
if (err instanceof Error && (err as NodeJS.ErrnoException).code === 'EPERM') {
|
||||
return true;
|
||||
}
|
||||
// Process doesn't exist, clean up stale files
|
||||
cleanupSocket(session);
|
||||
return false;
|
||||
@@ -406,8 +411,7 @@ export async function startDaemon(options?: {
|
||||
}
|
||||
|
||||
// Auto-launch if not already launched and this isn't a launch/close/state_load command.
|
||||
// Default behavior for this fork: first try attaching to a resident Chrome on CDP :9333,
|
||||
// then fall back to launching a local Playwright browser if CDP is unavailable.
|
||||
// Default behavior for this fork: attach to an existing browser only.
|
||||
if (
|
||||
!manager.isLaunched() &&
|
||||
parseResult.command.action !== 'launch' &&
|
||||
@@ -477,10 +481,10 @@ export async function startDaemon(options?: {
|
||||
autoStateFilePath: getSessionAutoStatePath(),
|
||||
};
|
||||
|
||||
let launchedViaDefaultCdp = false;
|
||||
let attachedToExistingBrowser = false;
|
||||
try {
|
||||
// Keep default CDP attempt minimal. Launch-only options like extensions
|
||||
// are incompatible with CDP and can cause a false-negative fallback.
|
||||
// are incompatible with CDP and can cause false-negative attach failures.
|
||||
const cdpLaunchOptions = {
|
||||
id: launchOptions.id,
|
||||
action: launchOptions.action,
|
||||
@@ -492,7 +496,7 @@ export async function startDaemon(options?: {
|
||||
await manager.launch({
|
||||
...cdpLaunchOptions,
|
||||
});
|
||||
launchedViaDefaultCdp = true;
|
||||
attachedToExistingBrowser = true;
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error('[DEBUG] Auto-launch connected via default CDP port 9333');
|
||||
}
|
||||
@@ -500,13 +504,37 @@ export async function startDaemon(options?: {
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(
|
||||
`[DEBUG] Default CDP port 9333 unavailable, falling back to local launch: ${message}`
|
||||
`[DEBUG] Default CDP port 9333 unavailable, trying auto-connect discovery: ${message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!launchedViaDefaultCdp) {
|
||||
await manager.launch(launchOptions);
|
||||
if (!attachedToExistingBrowser) {
|
||||
try {
|
||||
await manager.launch({
|
||||
id: launchOptions.id,
|
||||
action: launchOptions.action,
|
||||
autoConnect: true,
|
||||
ignoreHTTPSErrors: launchOptions.ignoreHTTPSErrors,
|
||||
colorScheme: launchOptions.colorScheme,
|
||||
userAgent: launchOptions.userAgent,
|
||||
});
|
||||
attachedToExistingBrowser = true;
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error('[DEBUG] Auto-launch connected via auto-connect discovery');
|
||||
}
|
||||
} catch (error) {
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(`[DEBUG] Auto-connect discovery failed: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!attachedToExistingBrowser) {
|
||||
throw new Error(
|
||||
'Project policy requires using your existing browser. Could not connect to CDP at localhost:9333 and auto-discovery also failed.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -630,9 +658,13 @@ export async function startDaemon(options?: {
|
||||
processQueue().catch((err) => {
|
||||
// Socket write failures during queue processing are non-fatal;
|
||||
// the client has likely disconnected.
|
||||
console.warn('[warn] processQueue error:', err?.message ?? err);
|
||||
// Only log err.message to avoid leaking sensitive fields (e.g. passwords) from command objects.
|
||||
console.warn('[warn] processQueue error:', err?.message ?? String(err));
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error('[DEBUG] processQueue error (full):', err);
|
||||
console.error(
|
||||
'[DEBUG] processQueue error stack:',
|
||||
err?.stack ?? err?.message ?? String(err)
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { isDomainAllowed, parseDomainList, buildWebSocketFilterScript } from './domain-filter.js';
|
||||
|
||||
describe('domain-filter', () => {
|
||||
describe('isDomainAllowed', () => {
|
||||
it('should match exact domains', () => {
|
||||
expect(isDomainAllowed('example.com', ['example.com'])).toBe(true);
|
||||
expect(isDomainAllowed('github.com', ['github.com'])).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject non-matching domains', () => {
|
||||
expect(isDomainAllowed('evil.com', ['example.com'])).toBe(false);
|
||||
expect(isDomainAllowed('notexample.com', ['example.com'])).toBe(false);
|
||||
});
|
||||
|
||||
it('should match wildcard patterns', () => {
|
||||
expect(isDomainAllowed('sub.example.com', ['*.example.com'])).toBe(true);
|
||||
expect(isDomainAllowed('deep.sub.example.com', ['*.example.com'])).toBe(true);
|
||||
});
|
||||
|
||||
it('should match bare domain against wildcard pattern', () => {
|
||||
expect(isDomainAllowed('example.com', ['*.example.com'])).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject non-matching wildcard patterns', () => {
|
||||
expect(isDomainAllowed('example.org', ['*.example.com'])).toBe(false);
|
||||
expect(isDomainAllowed('evil.com', ['*.example.com'])).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for empty allowlist', () => {
|
||||
expect(isDomainAllowed('example.com', [])).toBe(false);
|
||||
});
|
||||
|
||||
it('should match against multiple patterns', () => {
|
||||
const patterns = ['example.com', '*.github.com', 'vercel.app'];
|
||||
expect(isDomainAllowed('example.com', patterns)).toBe(true);
|
||||
expect(isDomainAllowed('api.github.com', patterns)).toBe(true);
|
||||
expect(isDomainAllowed('vercel.app', patterns)).toBe(true);
|
||||
expect(isDomainAllowed('evil.com', patterns)).toBe(false);
|
||||
});
|
||||
|
||||
it('should not partially match domain suffixes without wildcard', () => {
|
||||
expect(isDomainAllowed('sub.example.com', ['example.com'])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseDomainList', () => {
|
||||
it('should split comma-separated domains', () => {
|
||||
expect(parseDomainList('a.com,b.com')).toEqual(['a.com', 'b.com']);
|
||||
});
|
||||
|
||||
it('should trim whitespace', () => {
|
||||
expect(parseDomainList(' a.com , b.com ')).toEqual(['a.com', 'b.com']);
|
||||
});
|
||||
|
||||
it('should lowercase domains', () => {
|
||||
expect(parseDomainList('Example.COM,GitHub.Com')).toEqual(['example.com', 'github.com']);
|
||||
});
|
||||
|
||||
it('should filter empty entries', () => {
|
||||
expect(parseDomainList('a.com,,b.com,')).toEqual(['a.com', 'b.com']);
|
||||
});
|
||||
|
||||
it('should handle empty string', () => {
|
||||
expect(parseDomainList('')).toEqual([]);
|
||||
});
|
||||
|
||||
it('should preserve wildcard prefixes', () => {
|
||||
expect(parseDomainList('*.example.com')).toEqual(['*.example.com']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildWebSocketFilterScript', () => {
|
||||
it('should produce a valid JavaScript IIFE', () => {
|
||||
const script = buildWebSocketFilterScript(['example.com', '*.github.com']);
|
||||
expect(script).toContain('_allowedDomains');
|
||||
expect(script).toContain('"example.com"');
|
||||
expect(script).toContain('"*.github.com"');
|
||||
});
|
||||
|
||||
it('should embed the domain list as JSON', () => {
|
||||
const script = buildWebSocketFilterScript(['a.com']);
|
||||
expect(script).toContain('["a.com"]');
|
||||
});
|
||||
|
||||
it('should include WebSocket, EventSource, and sendBeacon patches', () => {
|
||||
const script = buildWebSocketFilterScript(['a.com']);
|
||||
expect(script).toContain('WebSocket');
|
||||
expect(script).toContain('EventSource');
|
||||
expect(script).toContain('SecurityError');
|
||||
expect(script).toContain('sendBeacon');
|
||||
});
|
||||
|
||||
it('should handle empty allowlist', () => {
|
||||
const script = buildWebSocketFilterScript([]);
|
||||
expect(script).toContain('[]');
|
||||
});
|
||||
|
||||
it('should include domain matching logic consistent with isDomainAllowed', () => {
|
||||
const script = buildWebSocketFilterScript(['*.example.com']);
|
||||
expect(script).toContain('_isDomainAllowed');
|
||||
expect(script).toContain('slice(1)');
|
||||
expect(script).toContain('slice(2)');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import type { BrowserContext, Route } from 'playwright-core';
|
||||
|
||||
/**
|
||||
* Checks whether a hostname matches one of the allowed domain patterns.
|
||||
* Patterns support exact match ("example.com") and wildcard prefix ("*.example.com").
|
||||
*/
|
||||
export function isDomainAllowed(hostname: string, allowedDomains: string[]): boolean {
|
||||
for (const pattern of allowedDomains) {
|
||||
if (pattern.startsWith('*.')) {
|
||||
const suffix = pattern.slice(1); // ".example.com"
|
||||
if (hostname === pattern.slice(2) || hostname.endsWith(suffix)) {
|
||||
return true;
|
||||
}
|
||||
} else if (hostname === pattern) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function parseDomainList(raw: string): string[] {
|
||||
return raw
|
||||
.split(',')
|
||||
.map((d) => d.trim().toLowerCase())
|
||||
.filter((d) => d.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the init script source that monkey-patches WebSocket, EventSource,
|
||||
* and navigator.sendBeacon to block connections to non-allowed domains.
|
||||
* Exported for testing.
|
||||
*/
|
||||
export function buildWebSocketFilterScript(allowedDomains: string[]): string {
|
||||
const serialized = JSON.stringify(allowedDomains);
|
||||
return `(function() {
|
||||
var _allowedDomains = ${serialized};
|
||||
function _isDomainAllowed(hostname) {
|
||||
hostname = hostname.toLowerCase();
|
||||
for (var i = 0; i < _allowedDomains.length; i++) {
|
||||
var pattern = _allowedDomains[i];
|
||||
if (pattern.indexOf('*.') === 0) {
|
||||
var suffix = pattern.slice(1);
|
||||
if (hostname === pattern.slice(2) || hostname.slice(-suffix.length) === suffix) {
|
||||
return true;
|
||||
}
|
||||
} else if (hostname === pattern) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function _checkUrl(url) {
|
||||
try {
|
||||
var parsed = new URL(url);
|
||||
return _isDomainAllowed(parsed.hostname);
|
||||
} catch(e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (typeof WebSocket !== 'undefined') {
|
||||
var _OrigWS = WebSocket;
|
||||
WebSocket = function(url, protocols) {
|
||||
if (!_checkUrl(url)) {
|
||||
throw new DOMException(
|
||||
'WebSocket connection to ' + url + ' blocked by domain allowlist',
|
||||
'SecurityError'
|
||||
);
|
||||
}
|
||||
if (protocols !== undefined) {
|
||||
return new _OrigWS(url, protocols);
|
||||
}
|
||||
return new _OrigWS(url);
|
||||
};
|
||||
WebSocket.prototype = _OrigWS.prototype;
|
||||
WebSocket.CONNECTING = _OrigWS.CONNECTING;
|
||||
WebSocket.OPEN = _OrigWS.OPEN;
|
||||
WebSocket.CLOSING = _OrigWS.CLOSING;
|
||||
WebSocket.CLOSED = _OrigWS.CLOSED;
|
||||
}
|
||||
if (typeof EventSource !== 'undefined') {
|
||||
var _OrigES = EventSource;
|
||||
EventSource = function(url, opts) {
|
||||
if (!_checkUrl(url)) {
|
||||
throw new DOMException(
|
||||
'EventSource connection to ' + url + ' blocked by domain allowlist',
|
||||
'SecurityError'
|
||||
);
|
||||
}
|
||||
return new _OrigES(url, opts);
|
||||
};
|
||||
EventSource.prototype = _OrigES.prototype;
|
||||
EventSource.CONNECTING = _OrigES.CONNECTING;
|
||||
EventSource.OPEN = _OrigES.OPEN;
|
||||
EventSource.CLOSED = _OrigES.CLOSED;
|
||||
}
|
||||
if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
|
||||
var _origSendBeacon = navigator.sendBeacon.bind(navigator);
|
||||
navigator.sendBeacon = function(url, data) {
|
||||
if (!_checkUrl(url)) {
|
||||
return false;
|
||||
}
|
||||
return _origSendBeacon(url, data);
|
||||
};
|
||||
}
|
||||
})();`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs a context-level route that enforces the domain allowlist.
|
||||
* Both document navigations and sub-resource requests (scripts, images, fetch, etc.)
|
||||
* to non-allowed domains are blocked, preventing data exfiltration.
|
||||
* Non-http(s) schemes (data:, blob:, etc.) are allowed for sub-resources
|
||||
* but blocked for document navigations.
|
||||
*
|
||||
* Also installs an init script that patches WebSocket, EventSource, and
|
||||
* navigator.sendBeacon to block connections to non-allowed domains. This is
|
||||
* a best-effort defense: if eval is permitted by action policy, page scripts
|
||||
* could theoretically restore the originals. Denying the eval action
|
||||
* category closes that loophole.
|
||||
*/
|
||||
export async function installDomainFilter(
|
||||
context: BrowserContext,
|
||||
allowedDomains: string[]
|
||||
): Promise<void> {
|
||||
if (allowedDomains.length === 0) return;
|
||||
|
||||
await context.addInitScript(buildWebSocketFilterScript(allowedDomains));
|
||||
|
||||
await context.route('**/*', async (route: Route) => {
|
||||
const request = route.request();
|
||||
const urlStr = request.url();
|
||||
|
||||
if (!urlStr.startsWith('http://') && !urlStr.startsWith('https://')) {
|
||||
if (request.resourceType() === 'document') {
|
||||
await route.abort('blockedbyclient');
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let hostname: string;
|
||||
try {
|
||||
hostname = new URL(urlStr).hostname.toLowerCase();
|
||||
} catch {
|
||||
await route.abort('blockedbyclient');
|
||||
return;
|
||||
}
|
||||
|
||||
if (isDomainAllowed(hostname, allowedDomains)) {
|
||||
await route.continue();
|
||||
} else {
|
||||
await route.abort('blockedbyclient');
|
||||
}
|
||||
});
|
||||
}
|
||||
+104
-12
@@ -3,6 +3,10 @@
|
||||
*/
|
||||
|
||||
import * as crypto from 'crypto';
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import os from 'node:os';
|
||||
|
||||
// ============================================
|
||||
// Constants
|
||||
@@ -10,6 +14,7 @@ import * as crypto from 'crypto';
|
||||
export const ENCRYPTION_ALGORITHM = 'aes-256-gcm';
|
||||
export const ENCRYPTION_KEY_ENV = 'AGENT_BROWSER_ENCRYPTION_KEY';
|
||||
export const IV_LENGTH = 12; // 96 bits for GCM
|
||||
const KEY_FILE_NAME = '.encryption-key';
|
||||
|
||||
/**
|
||||
* Encrypted payload structure.
|
||||
@@ -22,27 +27,114 @@ export interface EncryptedPayload {
|
||||
data: string; // Base64 encoded ciphertext
|
||||
}
|
||||
|
||||
export function getKeyFilePath(): string {
|
||||
return join(os.homedir(), '.agent-browser', KEY_FILE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get encryption key from environment variable.
|
||||
* Restrict file permissions to the current user only.
|
||||
* On Unix, the caller should use `mode: 0o600` when writing. This function
|
||||
* handles Windows where Node's mode parameter is ignored.
|
||||
*/
|
||||
export function restrictFilePermissions(filePath: string): void {
|
||||
if (os.platform() !== 'win32') return;
|
||||
try {
|
||||
execSync(`icacls "${filePath}" /inheritance:r /grant:r "%USERNAME%:F"`, {
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
});
|
||||
} catch {
|
||||
// Best-effort; may fail in some environments (containers, restricted shells)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restrict directory permissions to the current user only.
|
||||
* On Unix, the caller should use `mode: 0o700` when creating. This function
|
||||
* handles Windows where Node's mode parameter is ignored.
|
||||
*/
|
||||
export function restrictDirPermissions(dirPath: string): void {
|
||||
if (os.platform() !== 'win32') return;
|
||||
try {
|
||||
execSync(`icacls "${dirPath}" /inheritance:r /grant:r "%USERNAME%:(OI)(CI)F"`, {
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
});
|
||||
} catch {
|
||||
// Best-effort
|
||||
}
|
||||
}
|
||||
|
||||
function parseKeyHex(keyHex: string): Buffer | null {
|
||||
if (!/^[a-fA-F0-9]{64}$/.test(keyHex.trim())) return null;
|
||||
return Buffer.from(keyHex.trim(), 'hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get encryption key from environment variable or key file.
|
||||
* The key should be a 32-byte (256-bit) hex-encoded string (64 characters).
|
||||
* Generate with: openssl rand -hex 32
|
||||
*
|
||||
* @returns Buffer containing the key, or null if not set/invalid
|
||||
* Checks (in order):
|
||||
* 1. AGENT_BROWSER_ENCRYPTION_KEY env var
|
||||
* 2. ~/.agent-browser/.encryption-key file
|
||||
*
|
||||
* @returns Buffer containing the key, or null if not available
|
||||
*/
|
||||
export function getEncryptionKey(): Buffer | null {
|
||||
const keyHex = process.env[ENCRYPTION_KEY_ENV];
|
||||
if (!keyHex) return null;
|
||||
|
||||
// Key should be 64 hex chars = 32 bytes = 256 bits
|
||||
if (!/^[a-fA-F0-9]{64}$/.test(keyHex)) {
|
||||
console.warn(
|
||||
`Warning: ${ENCRYPTION_KEY_ENV} should be a 64-character hex string (256 bits). ` +
|
||||
`Generate one with: openssl rand -hex 32`
|
||||
);
|
||||
return null;
|
||||
if (keyHex) {
|
||||
const key = parseKeyHex(keyHex);
|
||||
if (!key) {
|
||||
console.warn(
|
||||
`Warning: ${ENCRYPTION_KEY_ENV} should be a 64-character hex string (256 bits). ` +
|
||||
`Generate one with: openssl rand -hex 32`
|
||||
);
|
||||
return null;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
return Buffer.from(keyHex, 'hex');
|
||||
const keyFilePath = getKeyFilePath();
|
||||
if (existsSync(keyFilePath)) {
|
||||
try {
|
||||
const fileHex = readFileSync(keyFilePath, 'utf-8');
|
||||
return parseKeyHex(fileHex);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure an encryption key is available, auto-generating one if needed.
|
||||
* On first call without an existing key, generates a random 256-bit key
|
||||
* and writes it to ~/.agent-browser/.encryption-key (mode 0600).
|
||||
*/
|
||||
export function ensureEncryptionKey(): Buffer {
|
||||
const existing = getEncryptionKey();
|
||||
if (existing) return existing;
|
||||
|
||||
const key = crypto.randomBytes(32);
|
||||
const keyHex = key.toString('hex');
|
||||
|
||||
const dir = join(os.homedir(), '.agent-browser');
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
restrictDirPermissions(dir);
|
||||
}
|
||||
|
||||
const keyFilePath = getKeyFilePath();
|
||||
writeFileSync(keyFilePath, keyHex + '\n', { mode: 0o600 });
|
||||
restrictFilePermissions(keyFilePath);
|
||||
|
||||
console.error(
|
||||
`[agent-browser] Auto-generated encryption key at ${keyFilePath} -- back up this file or set ${ENCRYPTION_KEY_ENV}`
|
||||
);
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -52,6 +52,9 @@ const launchSchema = baseCommandSchema.extend({
|
||||
colorScheme: z.enum(['light', 'dark', 'no-preference']).optional(),
|
||||
downloadPath: z.string().optional(),
|
||||
storageState: z.string().optional(),
|
||||
allowedDomains: z.array(z.string()).optional(),
|
||||
actionPolicy: z.string().optional(),
|
||||
confirmActions: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
const navigateSchema = baseCommandSchema.extend({
|
||||
@@ -874,6 +877,53 @@ const windowNewSchema = baseCommandSchema.extend({
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const authProfileName = z
|
||||
.string()
|
||||
.min(1)
|
||||
.regex(/^[a-zA-Z0-9_-]+$/, {
|
||||
message: 'Profile name must contain only alphanumeric characters, hyphens, and underscores',
|
||||
});
|
||||
|
||||
const authSaveSchema = baseCommandSchema.extend({
|
||||
action: z.literal('auth_save'),
|
||||
name: authProfileName,
|
||||
url: z.string().min(1),
|
||||
username: z.string().min(1),
|
||||
password: z.string().min(1),
|
||||
usernameSelector: z.string().optional(),
|
||||
passwordSelector: z.string().optional(),
|
||||
submitSelector: z.string().optional(),
|
||||
});
|
||||
|
||||
const authLoginSchema = baseCommandSchema.extend({
|
||||
action: z.literal('auth_login'),
|
||||
name: authProfileName,
|
||||
});
|
||||
|
||||
const authListSchema = baseCommandSchema.extend({
|
||||
action: z.literal('auth_list'),
|
||||
});
|
||||
|
||||
const authDeleteSchema = baseCommandSchema.extend({
|
||||
action: z.literal('auth_delete'),
|
||||
name: authProfileName,
|
||||
});
|
||||
|
||||
const authShowSchema = baseCommandSchema.extend({
|
||||
action: z.literal('auth_show'),
|
||||
name: authProfileName,
|
||||
});
|
||||
|
||||
const confirmSchema = baseCommandSchema.extend({
|
||||
action: z.literal('confirm'),
|
||||
confirmationId: z.string().min(1),
|
||||
});
|
||||
|
||||
const denySchema = baseCommandSchema.extend({
|
||||
action: z.literal('deny'),
|
||||
confirmationId: z.string().min(1),
|
||||
});
|
||||
|
||||
// Union schema for all commands
|
||||
const commandSchema = z.discriminatedUnion('action', [
|
||||
launchSchema,
|
||||
@@ -1011,6 +1061,13 @@ const commandSchema = z.discriminatedUnion('action', [
|
||||
diffSnapshotSchema,
|
||||
diffScreenshotSchema,
|
||||
diffUrlSchema,
|
||||
confirmSchema,
|
||||
denySchema,
|
||||
authSaveSchema,
|
||||
authLoginSchema,
|
||||
authListSchema,
|
||||
authDeleteSchema,
|
||||
authShowSchema,
|
||||
]);
|
||||
|
||||
// Parse result type
|
||||
|
||||
+16
-16
@@ -23,7 +23,7 @@ export interface RefMap {
|
||||
[ref: string]: {
|
||||
selector: string;
|
||||
role: string;
|
||||
name?: string;
|
||||
name: string;
|
||||
/** Index for disambiguation when multiple elements have same role+name */
|
||||
nth?: number;
|
||||
};
|
||||
@@ -130,12 +130,9 @@ const STRUCTURAL_ROLES = new Set([
|
||||
/**
|
||||
* Build a selector string for storing in ref map
|
||||
*/
|
||||
function buildSelector(role: string, name?: string): string {
|
||||
if (name) {
|
||||
const escapedName = JSON.stringify(name);
|
||||
return `getByRole('${role}', { name: ${escapedName}, exact: true })`;
|
||||
}
|
||||
return `getByRole('${role}')`;
|
||||
function buildSelector(role: string, name: string): string {
|
||||
const escapedName = JSON.stringify(name);
|
||||
return `getByRole('${role}', { name: ${escapedName}, exact: true })`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -293,7 +290,7 @@ export async function getEnhancedSnapshot(
|
||||
const cursorElements = await findCursorInteractiveElements(page, options.selector);
|
||||
|
||||
// Filter out elements whose text is already captured in the snapshot
|
||||
const existingTexts = new Set(Object.values(refs).map((r) => r.name?.toLowerCase()));
|
||||
const existingTexts = new Set(Object.values(refs).map((r) => r.name.toLowerCase()));
|
||||
// Also extract quoted strings from the ARIA tree for broader dedup
|
||||
for (const m of enhancedTree.matchAll(/"([^"]+)"/g)) {
|
||||
existingTexts.add(m[1].toLowerCase());
|
||||
@@ -404,12 +401,13 @@ function processAriaTree(ariaTree: string, refs: RefMap, options: SnapshotOption
|
||||
|
||||
if (INTERACTIVE_ROLES.has(roleLower)) {
|
||||
const ref = nextRef();
|
||||
const nth = tracker.getNextIndex(roleLower, name);
|
||||
tracker.trackRef(roleLower, name, ref);
|
||||
const resolvedName = name ?? '';
|
||||
const nth = tracker.getNextIndex(roleLower, resolvedName);
|
||||
tracker.trackRef(roleLower, resolvedName, ref);
|
||||
refs[ref] = {
|
||||
selector: buildSelector(roleLower, name),
|
||||
selector: buildSelector(roleLower, resolvedName),
|
||||
role: roleLower,
|
||||
name,
|
||||
name: resolvedName,
|
||||
nth, // Always store nth, we'll use it for duplicates
|
||||
};
|
||||
|
||||
@@ -531,13 +529,15 @@ function processLine(
|
||||
|
||||
if (shouldHaveRef) {
|
||||
const ref = nextRef();
|
||||
const nth = tracker.getNextIndex(roleLower, name);
|
||||
tracker.trackRef(roleLower, name, ref);
|
||||
// Normalize to "" so unnamed elements get exact-match selectors
|
||||
const resolvedName = isInteractive ? (name ?? '') : name!;
|
||||
const nth = tracker.getNextIndex(roleLower, resolvedName);
|
||||
tracker.trackRef(roleLower, resolvedName, ref);
|
||||
|
||||
refs[ref] = {
|
||||
selector: buildSelector(roleLower, name),
|
||||
selector: buildSelector(roleLower, resolvedName),
|
||||
role: roleLower,
|
||||
name,
|
||||
name: resolvedName,
|
||||
nth, // Always store nth, we'll clean up non-duplicates later
|
||||
};
|
||||
|
||||
|
||||
@@ -127,12 +127,24 @@ describe('Stealth mode', () => {
|
||||
activeTextColor,
|
||||
prefersLight: matchMedia('(prefers-color-scheme: light)').matches,
|
||||
prefersDark: matchMedia('(prefers-color-scheme: dark)').matches,
|
||||
lightListenerCalls: (() => {
|
||||
try {
|
||||
const mql = matchMedia('(prefers-color-scheme: light)');
|
||||
const handler = () => {};
|
||||
mql.addEventListener('change', handler);
|
||||
mql.removeEventListener('change', handler);
|
||||
return 'ok';
|
||||
} catch (error) {
|
||||
return String(error);
|
||||
}
|
||||
})(),
|
||||
};
|
||||
});
|
||||
|
||||
expect(signals.activeTextColor).not.toBe('rgb(255, 0, 0)');
|
||||
expect(signals.prefersLight).toBe(false);
|
||||
expect(typeof signals.prefersDark).toBe('boolean');
|
||||
expect(signals.lightListenerCalls).toBe('ok');
|
||||
});
|
||||
|
||||
it('exposes realistic mimeTypes/pdf/share signals', async () => {
|
||||
|
||||
+6
-2
@@ -856,9 +856,13 @@ function patchPrefersColorSchemeHeuristic(): string {
|
||||
const patchMediaQueryList = (mql) => {
|
||||
if (!mql || typeof mql !== 'object') return mql;
|
||||
return new Proxy(mql, {
|
||||
get(target, prop, receiver) {
|
||||
get(target, prop) {
|
||||
if (prop === 'matches') return false;
|
||||
return Reflect.get(target, prop, receiver);
|
||||
const value = Reflect.get(target, prop, target);
|
||||
if (typeof value === 'function') {
|
||||
return value.bind(target);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
+76
-1
@@ -41,6 +41,9 @@ export interface LaunchCommand extends BaseCommand {
|
||||
allowFileAccess?: boolean; // Enable file:// URL access and cross-origin file requests
|
||||
colorScheme?: 'light' | 'dark' | 'no-preference'; // Persistent color scheme override
|
||||
downloadPath?: string; // Directory for browser downloads (Playwright's downloadsPath)
|
||||
allowedDomains?: string[];
|
||||
actionPolicy?: string;
|
||||
confirmActions?: string[];
|
||||
// Auto-load state file for session persistence
|
||||
autoStateFilePath?: string;
|
||||
}
|
||||
@@ -1033,7 +1036,54 @@ export type Command =
|
||||
| DeviceListCommand
|
||||
| DiffSnapshotCommand
|
||||
| DiffScreenshotCommand
|
||||
| DiffUrlCommand;
|
||||
| DiffUrlCommand
|
||||
| AuthSaveCommand
|
||||
| AuthLoginCommand
|
||||
| AuthListCommand
|
||||
| AuthDeleteCommand
|
||||
| AuthShowCommand
|
||||
| ConfirmCommand
|
||||
| DenyCommand;
|
||||
|
||||
export interface AuthSaveCommand extends BaseCommand {
|
||||
action: 'auth_save';
|
||||
name: string;
|
||||
url: string;
|
||||
username: string;
|
||||
password: string;
|
||||
usernameSelector?: string;
|
||||
passwordSelector?: string;
|
||||
submitSelector?: string;
|
||||
}
|
||||
|
||||
export interface AuthLoginCommand extends BaseCommand {
|
||||
action: 'auth_login';
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AuthListCommand extends BaseCommand {
|
||||
action: 'auth_list';
|
||||
}
|
||||
|
||||
export interface AuthDeleteCommand extends BaseCommand {
|
||||
action: 'auth_delete';
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AuthShowCommand extends BaseCommand {
|
||||
action: 'auth_show';
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ConfirmCommand extends BaseCommand {
|
||||
action: 'confirm';
|
||||
confirmationId: string;
|
||||
}
|
||||
|
||||
export interface DenyCommand extends BaseCommand {
|
||||
action: 'deny';
|
||||
confirmationId: string;
|
||||
}
|
||||
|
||||
// Diff commands
|
||||
export interface DiffSnapshotCommand extends BaseCommand {
|
||||
@@ -1105,14 +1155,39 @@ export interface ScreenshotData {
|
||||
|
||||
export interface SnapshotData {
|
||||
snapshot: string;
|
||||
refs?: Record<string, { role: string; name?: string }>;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
export interface EvaluateData {
|
||||
result: unknown;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
export interface ContentData {
|
||||
html: string;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
export interface TextData {
|
||||
text: string | null;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
export interface AttributeData {
|
||||
attribute: string;
|
||||
value: string | null;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
export interface ValueData {
|
||||
value: string;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
export interface ConsoleData {
|
||||
messages: Array<{ type: string; text: string }>;
|
||||
origin?: string;
|
||||
}
|
||||
|
||||
export interface TabInfo {
|
||||
|
||||
Reference in New Issue
Block a user