@vibecontrols/vibe-plugin-desk-browser 0.0.0-stage → 2026.1125.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Burdenoff Consultancy Services Private Limited,
4
+ Algoshred Technologies Private Limited,
5
+ and all its sister companies.
6
+
7
+ Maintainer: Vignesh T.V <https://github.com/tvvignesh>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is furnished
14
+ to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,93 @@
1
- # Temporary Holding Version
1
+ # @vibecontrols/vibe-plugin-desk-browser
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The browser provider for BotManor Stewards desks. It gives a Steward a dedicated Chromium profile and drives it with Playwright behind the common desk API of [`@vibecontrols/vibe-plugin-desk`](https://github.com/Algoshred/vibe-plugin-desk).
4
+
5
+ Install it next to the desk meta plugin. The meta routes actions here and enforces fencing, idempotency, timeouts, local consent and the kill switch. This plugin does the browsing.
6
+
7
+ ## Actions
8
+
9
+ | Action | What it does |
10
+ | ------------- | --------------------------------------------------------------------------------------------------------------------------- |
11
+ | `screenshot` | PNG of the page. Password fields are masked. |
12
+ | `snapshot` | The actionable elements of the page, each with a ref (`e1`, `e2`, ...), plus the page text. Password values are never read. |
13
+ | `click` | Clicks a ref or a point. Takes `button` and a double-click `count`. |
14
+ | `type` | Types text, after focusing a ref or point if one is given. |
15
+ | `secret_fill` | Fills a field from the secret store, only when the page origin equals `expectedOrigin`. The value is never returned. |
16
+ | `key` | Presses keys in Playwright syntax, for example `Enter` or `Control+A`. |
17
+ | `scroll` | Scrolls by `dx`/`dy`, over a ref or point if one is given. |
18
+ | `navigate` | Opens an http(s) URL that passes the URL guard (below). |
19
+
20
+ Window, shell and file actions are not browser actions. The meta refuses them for this provider.
21
+
22
+ Refs come from the last `snapshot` and are written into the page under an attribute name that is random per snapshot, so a page cannot forge them. A ref that no longer matches exactly one visible element returns `TARGET_NOT_FOUND`: take a new snapshot.
23
+
24
+ ## Where the browser may go
25
+
26
+ The URL guard is the same as the FluidGrids remote browser node's:
27
+
28
+ - **Allowed:** http and https only, with no user name or password in the URL.
29
+ - **Refused:**
30
+ - `localhost`, `*.local`, `*.internal` and single-label names;
31
+ - every address that is not globally routable: private, loopback, CGNAT, link-local (which includes the cloud metadata address), multicast and reserved, plus IPv4-mapped and NAT64 forms of them.
32
+ - **When the guard runs:**
33
+ - before every navigation;
34
+ - on the final URL after redirects; a blocked final URL clears the page and returns `URL_BLOCKED`;
35
+ - on every request the page makes, without a DNS lookup.
36
+ - **Always off:** service workers and downloads.
37
+
38
+ **Limits:**
39
+
40
+ - Chrome resolves names itself, so DNS rebinding is not caught here. A redirect is followed before its target is checked.
41
+ - On a **cloud desk**, the egress proxy covers both cases: it checks the address it actually connects to.
42
+ - On a **user's own machine**, there is no proxy. That machine's network is the user's, and the consent screen says so.
43
+
44
+ ## Configuration
45
+
46
+ Set with `vibe config set <key> <value>`:
47
+
48
+ | Key | Default | Meaning |
49
+ | ------------------------------ | ------------------------- | ---------------------------------------------------------------------------------- |
50
+ | `desk-browser.executable-path` | Playwright's Chromium | Chrome or Chromium binary |
51
+ | `desk-browser.channel` | none | `chrome`, `msedge`, ... instead of a path |
52
+ | `desk-browser.headless` | off when a display exists | `on` or `off` |
53
+ | `desk-browser.proxy` | none | http(s) proxy URL without credentials. Cloud desks use `http://172.20.0.200:3128`. |
54
+ | `desk-browser.allowed-hosts` | any public host | Comma-separated allow-list. `*.example.com` matches subdomains. |
55
+
56
+ The browser starts on the first action and closes when the agent stops. The profile lives in `<dataDir>/desk-browser-profile` with mode 0700.
57
+
58
+ On a cloud desk, that folder is part of the home snapshot taken at hibernation. Sign-ins that use persistent cookies survive a restore; session-only cookies do not, just as when a browser is closed.
59
+
60
+ ## Secret fill
61
+
62
+ `secret_fill` needs a secret store that registers a resolver under the `desk-secret` provider type:
63
+
64
+ ```ts
65
+ import type { DeskSecretResolver } from "@vibecontrols/vibe-plugin-desk-browser";
66
+
67
+ const store: DeskSecretResolver = {
68
+ async resolve(secretRef, { origin, deskId }) {
69
+ // Return the value only if this secret may be used on `origin`, else null.
70
+ return null;
71
+ },
72
+ };
73
+ host.serviceRegistry?.registerProvider?.(
74
+ "desk-secret",
75
+ store,
76
+ "my-secret-store",
77
+ );
78
+ ```
79
+
80
+ Without a store, `secret_fill` is refused and every other action works.
81
+
82
+ ## Development
83
+
84
+ ```bash
85
+ bun install
86
+ bun run sanity # format, lint, type check, build, tests
87
+ ```
88
+
89
+ The browser tests need Chrome or Chromium: `/usr/bin/google-chrome`, or set `DESK_BROWSER_TEST_EXECUTABLE`. Without one they are skipped, and the test run says so.
90
+
91
+ ## License
92
+
93
+ MIT
@@ -0,0 +1,61 @@
1
+ import type { DeskAction, DeskActionType, DeskBackend, DeskBackendResult } from "@vibecontrols/plugin-sdk/desk";
2
+ import { type BrowserContext } from "playwright-core";
3
+ import { type GuardOptions } from "./url-guard.js";
4
+ /** Provider type a secret store registers under to serve `secret_fill`. */
5
+ export declare const DESK_SECRET_PROVIDER_TYPE = "desk-secret";
6
+ /**
7
+ * Resolves a `secretRef` to the value to type. Returning null refuses the
8
+ * fill. Implementations decide whether `origin` may receive that secret.
9
+ */
10
+ export interface DeskSecretResolver {
11
+ resolve(secretRef: string, request: {
12
+ origin: string;
13
+ deskId: string;
14
+ }): Promise<string | null>;
15
+ }
16
+ export declare const BROWSER_ACTIONS: readonly ["screenshot", "snapshot", "click", "type", "secret_fill", "key", "scroll", "navigate"];
17
+ export declare const BROWSER_LIMITS: {
18
+ readonly viewport: {
19
+ readonly width: 1280;
20
+ readonly height: 800;
21
+ };
22
+ readonly navigationTimeoutMs: 30000;
23
+ readonly actionTimeoutMs: 10000;
24
+ };
25
+ export interface LaunchOptions {
26
+ headless: boolean;
27
+ executablePath?: string;
28
+ channel?: string;
29
+ proxy?: string;
30
+ }
31
+ export type Launcher = (profileFolder: string, options: LaunchOptions) => Promise<BrowserContext>;
32
+ export declare const defaultLauncher: Launcher;
33
+ export interface BrowserDeskOptions extends LaunchOptions {
34
+ /** Persistent profile folder (cookies, storage). Created with mode 0700. */
35
+ profileFolder: string;
36
+ guard?: GuardOptions;
37
+ /** Looked up on every `secret_fill`, so a store installed later is used. */
38
+ secrets?: () => DeskSecretResolver | undefined;
39
+ launch?: Launcher;
40
+ }
41
+ export declare class BrowserDeskBackend implements DeskBackend {
42
+ private readonly options;
43
+ readonly kind = "browser";
44
+ readonly actions: readonly DeskActionType[];
45
+ private contextPromise;
46
+ private readonly desks;
47
+ private closed;
48
+ constructor(options: BrowserDeskOptions);
49
+ act(action: DeskAction, context: {
50
+ deskId: string;
51
+ signal: AbortSignal;
52
+ }): Promise<DeskBackendResult>;
53
+ /** Close the browser. Safe to call twice; later actions are refused. */
54
+ close(): Promise<void>;
55
+ private context;
56
+ private launchContext;
57
+ private deskPage;
58
+ private resolve;
59
+ private afterNavigationCheck;
60
+ private run;
61
+ }
@@ -0,0 +1,24 @@
1
+ import type { VibePluginFactory } from "@vibecontrols/plugin-sdk/contract";
2
+ import { type Launcher } from "./backend.js";
3
+ /** The provider type the `vibe-plugin-desk` meta routes to. */
4
+ export declare const DESK_PROVIDER_TYPE = "desk";
5
+ export declare const DESK_BROWSER_CONFIG: {
6
+ readonly executablePath: "desk-browser.executable-path";
7
+ readonly channel: "desk-browser.channel";
8
+ readonly headless: "desk-browser.headless";
9
+ readonly proxy: "desk-browser.proxy";
10
+ readonly allowedHosts: "desk-browser.allowed-hosts";
11
+ };
12
+ /** Default headless: on Linux without a display there is nothing to show. */
13
+ export declare function defaultHeadless(platform?: string, env?: NodeJS.ProcessEnv): boolean;
14
+ /** Only http(s) proxies without credentials are accepted from config. */
15
+ export declare function parseProxy(value: string | undefined): string | undefined;
16
+ export interface DeskBrowserPluginOptions {
17
+ /** Replaces Playwright's launcher. Tests only. */
18
+ launch?: Launcher;
19
+ }
20
+ export declare function createDeskBrowserPlugin(options?: DeskBrowserPluginOptions): VibePluginFactory;
21
+ export declare const createPlugin: VibePluginFactory;
22
+ export default createPlugin;
23
+ export { BROWSER_ACTIONS, BROWSER_LIMITS, BrowserDeskBackend, DESK_SECRET_PROVIDER_TYPE, type DeskSecretResolver, } from "./backend.js";
24
+ export { checkNavigation, isBlockedAddress, quickBlockReason, } from "./url-guard.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{existsSync,readFileSync}from"fs";import{dirname,join as joinPath}from"path";import{fileURLToPath}from"url";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
3
+ `);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(context)=>{if(onShutdown)await onShutdown(context)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var BoundLogger=class{logger;source;constructor(logger,source){this.logger=logger,this.source=source}info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};import{mkdir}from"fs/promises";import{chromium}from"playwright-core";var SNAPSHOT_LIMITS={maxElements:500,maxName:120,maxValue:200,maxText:20000};function collectInPage(args){let{attr,previousAttr,maxElements,maxName,maxValue}=args;if(previousAttr)for(let el of Array.from(document.querySelectorAll(`[${previousAttr}]`)))el.removeAttribute(previousAttr);let clip=(s,n)=>{let t=s.replace(/\s+/g," ").trim();return t.length>n?`${t.slice(0,n-1)}\u2026`:t},visible=(el)=>{let h=el,withCheck=h;if(typeof withCheck.checkVisibility==="function"&&!withCheck.checkVisibility())return!1;let r=h.getBoundingClientRect();return r.width>0&&r.height>0},textOf=(el)=>el?el.innerText??el.textContent??"":"",roleOf=(el)=>{let explicit=el.getAttribute("role");if(explicit)return explicit.split(/\s+/)[0]??null;let tag=el.tagName.toLowerCase();if(tag==="a"&&el.hasAttribute("href"))return"link";if(tag==="button"||tag==="summary")return"button";if(tag==="select")return"combobox";if(tag==="textarea")return"textbox";if(/^h[1-6]$/.test(tag))return"heading";if(tag==="img"&&el.getAttribute("alt"))return"img";if(tag==="input"){let type=(el.getAttribute("type")??"text").toLowerCase();if(type==="hidden")return null;if(["button","submit","reset","image"].includes(type))return"button";if(type==="checkbox")return"checkbox";if(type==="radio")return"radio";if(type==="range")return"slider";if(type==="search")return"searchbox";return"textbox"}if(el.isContentEditable)return"textbox";let tabindex=el.getAttribute("tabindex");if(tabindex!==null&&Number(tabindex)>=0)return"generic";return null},nameOf=(el)=>{let label=el.getAttribute("aria-label");if(label)return label;let labelledBy=el.getAttribute("aria-labelledby");if(labelledBy){let parts=labelledBy.split(/\s+/).map((id)=>textOf(document.getElementById(id))).filter(Boolean);if(parts.length)return parts.join(" ")}let field=el;if(field.labels&&field.labels.length)return Array.from(field.labels).map((l)=>textOf(l)).join(" ");for(let a of["placeholder","alt","title","value"]){let v=el.getAttribute(a);if(v&&!(a==="value"&&el.tagName.toLowerCase()==="input"&&field.type!=="submit"&&field.type!=="button"))return v}return textOf(el)},elements=[],truncated=!1,n=0;for(let el of Array.from(document.querySelectorAll("body *"))){let role=roleOf(el);if(!role||!visible(el))continue;if(elements.length>=maxElements){truncated=!0;break}let ref=`e${++n}`;el.setAttribute(attr,ref);let item={ref,role,name:clip(nameOf(el),maxName)},tag=el.tagName.toLowerCase();if(tag==="input"||tag==="textarea"||tag==="select"){let f=el;if(f.type==="password"){if(f.value)item.value="(hidden)"}else if(f.type==="checkbox"||f.type==="radio")item.checked=f.checked;else if(f.value)item.value=clip(f.value,maxValue);if(f.disabled)item.disabled=!0}if(role==="heading"){let m=/^h([1-6])$/.exec(tag);item.level=m?Number(m[1]):Number(el.getAttribute("aria-level")??2)}elements.push(item)}return{url:location.href,title:document.title,elements,truncated}}function newRefAttribute(random=()=>crypto.randomUUID()){return`data-vc-${random().replace(/[^a-z0-9]/gi,"").slice(0,16).toLowerCase()}`}function refSelector(attr,ref){if(!/^e\d{1,6}$/.test(ref))return null;return`[${attr}="${ref}"]`}import{lookup}from"dns/promises";import{isIP}from"net";var systemResolver=async(host)=>(await lookup(host,{all:!0,verbatim:!0})).map((r)=>r.address),WEB_SCHEMES=new Set(["http:","https:"]),LOCAL_SCHEMES=new Set(["data:","blob:","about:"]),BLOCKED_NAMES=new Set(["localhost","localhost.localdomain","metadata","instance-data","metadata.google.internal"]),BLOCKED_SUFFIXES=[".localhost",".local",".internal",".home.arpa",".lan",".intranet",".corp"];class GuardError extends Error{name="GuardError"}function ipv4ToInt(ip){let parts=ip.split(".");if(parts.length!==4)return null;let n=0;for(let p of parts){if(!/^\d{1,3}$/.test(p))return null;let v=Number(p);if(v>255)return null;n=n*256+v}return n}var V4_BLOCKS=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function v4Blocked(ip){let n=ipv4ToInt(ip);if(n===null)return!0;return V4_BLOCKS.some(([base,bits])=>{let b=ipv4ToInt(base),size=2**(32-bits);return n>=b&&n<b+size})}function expandV6(input){let ip=input.toLowerCase(),zone=ip.indexOf("%");if(zone>=0)ip=ip.slice(0,zone);let lastColon=ip.lastIndexOf(":"),tail=ip.slice(lastColon+1);if(tail.includes(".")){let n=ipv4ToInt(tail);if(n===null)return null;ip=`${ip.slice(0,lastColon+1)}${(n>>>16).toString(16)}:${(n&65535).toString(16)}`}let halves=ip.split("::");if(halves.length>2)return null;let head=halves[0]?halves[0].split(":"):[],rest=halves.length===2&&halves[1]?halves[1].split(":"):[],missing=8-head.length-rest.length;if(halves.length===1&&missing!==0)return null;if(halves.length===2&&missing<1)return null;let groups=[...head,...Array(Math.max(missing,0)).fill("0"),...rest],out=[];for(let g of groups){if(!/^[0-9a-f]{1,4}$/.test(g))return null;out.push(parseInt(g,16))}return out.length===8?out:null}function v6Blocked(ip){let h=expandV6(ip);if(!h)return!0;let[a,b,c,d,e,f,g,last]=h;if(a===0&&b===0&&c===0&&d===0&&e===0&&(f===65535||f===0)){if(f===0&&g===0&&(last===0||last===1))return!0;return v4Blocked(`${g>>8}.${g&255}.${last>>8}.${last&255}`)}if(a===100&&b===65435&&c===0&&d===0&&e===0&&f===0)return v4Blocked(`${g>>8}.${g&255}.${last>>8}.${last&255}`);if((a&65024)===64512)return!0;if((a&65472)===65152)return!0;if((a&65472)===65216)return!0;if((a&65280)===65280)return!0;if(a===8193&&b===3512)return!0;if(a===8194)return v4Blocked(`${b>>8}.${b&255}.${c>>8}.${c&255}`);if(a===256&&b===0&&c===0&&d===0)return!0;return!1}function isBlockedAddress(ip){let family=isIP(ip);if(family===4)return v4Blocked(ip);if(family===6)return v6Blocked(ip);return!0}function bareHost(hostname){let h=hostname.toLowerCase().replace(/\.$/,"");return h.startsWith("[")&&h.endsWith("]")?h.slice(1,-1):h}function blockedByName(host){if(BLOCKED_NAMES.has(host))return`${host} is a local name`;if(BLOCKED_SUFFIXES.some((s)=>host.endsWith(s)))return`${host} is a local name`;if(isIP(host)===0&&!host.includes("."))return`${host} is a single-label name`;return null}function hostAllowed(host,allowed){if(allowed.length===0)return!0;return allowed.some((entry)=>{let rule=entry.trim().toLowerCase();if(!rule)return!1;if(rule.startsWith("*."))return host.endsWith(rule.slice(1));return host===rule})}function parseAllowedHosts(value){if(!value)return[];return value.split(/[\s,]+/).map((s)=>s.trim().toLowerCase()).filter((s)=>/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(s))}function parseWebUrl(raw){let url;try{url=new URL(raw)}catch{throw new GuardError("not a valid URL")}if(!WEB_SCHEMES.has(url.protocol))throw new GuardError(`scheme ${url.protocol} is not allowed`);if(url.username||url.password)throw new GuardError("URLs with a user name or password are not allowed");if(!url.hostname)throw new GuardError("URL has no host");return url}async function checkNavigation(raw,options={}){let url=parseWebUrl(raw),host=bareHost(url.hostname);if(!hostAllowed(host,options.allowedHosts??[]))throw new GuardError(`${host} is not on this desk's allow-list`);if(options.allowPrivateNetwork)return url;let byName=blockedByName(host);if(byName)throw new GuardError(byName);if(isIP(host)!==0){if(isBlockedAddress(host))throw new GuardError(`${host} is not a public address`);return url}let addresses;try{addresses=await(options.resolver??systemResolver)(host)}catch{throw new GuardError(`${host} does not resolve`)}if(addresses.length===0)throw new GuardError(`${host} does not resolve`);if(addresses.find(isBlockedAddress))throw new GuardError(`${host} resolves to a non-public address`);return url}function quickBlockReason(raw,options={}){let url;try{url=new URL(raw)}catch{return"not a valid URL"}if(LOCAL_SCHEMES.has(url.protocol))return null;if(!WEB_SCHEMES.has(url.protocol))return`scheme ${url.protocol} is not allowed`;let host=bareHost(url.hostname);if(options.allowPrivateNetwork)return null;let byName=blockedByName(host);if(byName)return byName;if(isIP(host)!==0&&isBlockedAddress(host))return`${host} is not a public address`;return null}var DESK_SECRET_PROVIDER_TYPE="desk-secret",BROWSER_ACTIONS=["screenshot","snapshot","click","type","secret_fill","key","scroll","navigate"],BROWSER_LIMITS={viewport:{width:1280,height:800},navigationTimeoutMs:30000,actionTimeoutMs:1e4},defaultLauncher=(profileFolder,options)=>chromium.launchPersistentContext(profileFolder,{headless:options.headless,...options.executablePath?{executablePath:options.executablePath}:{},...options.channel?{channel:options.channel}:{},...options.proxy?{proxy:{server:options.proxy}}:{},viewport:BROWSER_LIMITS.viewport,acceptDownloads:!1,serviceWorkers:"block"}),fail=(code,message)=>({ok:!1,error:{code,message}});class ActionError extends Error{code;constructor(code,message){super(message);this.code=code}}function shortMessage(err){return((err instanceof Error?err.message:String(err)).split(`
4
+ `)[0]??"browser action failed").slice(0,200)}function isTimeout(err){return err instanceof Error&&err.name==="TimeoutError"}class BrowserDeskBackend{options;kind="browser";actions=BROWSER_ACTIONS;contextPromise=null;desks=new Map;closed=!1;constructor(options){this.options=options}async act(action,context){if(this.closed)return fail("DESK_OFFLINE","the browser desk is stopped");try{let desk=await this.deskPage(context.deskId);return await this.run(desk,action,context.deskId)}catch(err){if(err instanceof ActionError)return fail(err.code,err.message);if(isTimeout(err))return fail("TIMEOUT",shortMessage(err));if(action.type==="secret_fill")return fail("DESK_OFFLINE","secret fill failed");return fail("DESK_OFFLINE",shortMessage(err))}}async close(){this.closed=!0;let pending=this.contextPromise;if(this.contextPromise=null,this.desks.clear(),!pending)return;try{await(await pending).close()}catch{}}context(){if(!this.contextPromise)this.contextPromise=this.launchContext().catch((err)=>{throw this.contextPromise=null,err});return this.contextPromise}async launchContext(){await mkdir(this.options.profileFolder,{recursive:!0,mode:448});let context=await(this.options.launch??defaultLauncher)(this.options.profileFolder,{headless:this.options.headless,executablePath:this.options.executablePath,channel:this.options.channel,proxy:this.options.proxy});return context.setDefaultTimeout(BROWSER_LIMITS.actionTimeoutMs),context.setDefaultNavigationTimeout(BROWSER_LIMITS.navigationTimeoutMs),await context.route("**/*",async(route)=>{if(quickBlockReason(route.request().url(),this.options.guard))await route.abort("blockedbyclient");else await route.continue()}),context.on("close",()=>{this.contextPromise=null,this.desks.clear()}),context}async deskPage(deskId){let existing=this.desks.get(deskId);if(existing&&!existing.page.isClosed())return existing;let context=await this.context(),taken=new Set([...this.desks.values()].map((d)=>d.page)),page=context.pages().find((p)=>!p.isClosed()&&!taken.has(p))??await context.newPage(),desk={page,refAttr:null};return this.desks.set(deskId,desk),page.on("close",()=>{if(this.desks.get(deskId)?.page===page)this.desks.delete(deskId)}),desk}async resolve(desk,target){if(target.by==="point"){let{width,height}=BROWSER_LIMITS.viewport;if(target.x<0||target.y<0||target.x>=width||target.y>=height)throw new ActionError("TARGET_NOT_FOUND",`point ${target.x},${target.y} is outside the ${width}x${height} page`);return{kind:"point",x:target.x,y:target.y}}if(target.by==="window")throw new ActionError("TARGET_NOT_FOUND","a browser desk has no windows; use a ref or a point");let selector=desk.refAttr?refSelector(desk.refAttr,target.ref):null;if(!selector)throw new ActionError("TARGET_NOT_FOUND",`ref ${target.ref} is unknown; take a snapshot first`);let locator=desk.page.locator(selector);if(await locator.count()!==1||!await locator.isVisible())throw new ActionError("TARGET_NOT_FOUND",`ref ${target.ref} is no longer on the page; take a new snapshot`);return{kind:"locator",locator}}async afterNavigationCheck(page){let current=page.url();if(current==="about:blank")return;try{await checkNavigation(current,this.options.guard)}catch(err){throw await page.goto("about:blank").catch(()=>{return}),new ActionError("URL_BLOCKED",err instanceof Error?`redirected to a blocked URL: ${err.message}`:"redirected to a blocked URL")}}async run(desk,action,deskId){let{page}=desk;switch(action.type){case"screenshot":{let png=await page.screenshot({type:"png",animations:"disabled",caret:"hide",mask:[page.locator('input[type="password"]')]});return{ok:!0,screenshotPng:new Uint8Array(png)}}case"snapshot":{let attr=newRefAttribute(),snapshot=await page.evaluate(collectInPage,{attr,previousAttr:desk.refAttr,maxElements:SNAPSHOT_LIMITS.maxElements,maxName:SNAPSHOT_LIMITS.maxName,maxValue:SNAPSHOT_LIMITS.maxValue});desk.refAttr=attr;let text=await page.evaluate(()=>document.body?.innerText??"").catch(()=>"");return{ok:!0,snapshot,text:text.slice(0,SNAPSHOT_LIMITS.maxText)}}case"click":{let target=await this.resolve(desk,action.target),button=action.button??"left",clickCount=action.count??1;if(target.kind==="point")await page.mouse.click(target.x,target.y,{button,clickCount});else await target.locator.click({button,clickCount});return await page.waitForLoadState("domcontentloaded").catch(()=>{return}),await this.afterNavigationCheck(page),{ok:!0,text:page.url()}}case"type":{if(action.target){let target=await this.resolve(desk,action.target);if(target.kind==="point")await page.mouse.click(target.x,target.y);else await target.locator.focus()}return await page.keyboard.type(action.text),{ok:!0}}case"secret_fill":{let expected;try{expected=new URL(action.expectedOrigin).origin}catch{return fail("ORIGIN_MISMATCH","expectedOrigin is not a valid origin")}let actual=(()=>{try{return new URL(page.url()).origin}catch{return"null"}})();if(actual!==expected)return fail("ORIGIN_MISMATCH",`the page is on ${actual}, not ${expected}`);let target=await this.resolve(desk,action.target);if(target.kind!=="locator")return fail("TARGET_NOT_FOUND","secret_fill needs a ref target, not a point");let resolver=this.options.secrets?.();if(!resolver)return fail("DESK_OFFLINE","no secret store is installed on this desk");let value=await resolver.resolve(action.secretRef,{origin:expected,deskId});if(value===null)return fail("DESK_OFFLINE","the secret is not available for this origin");if(new URL(page.url()).origin!==expected)return fail("ORIGIN_MISMATCH","the page left the expected origin");return await target.locator.fill(value),{ok:!0}}case"key":{for(let key of action.keys)try{await page.keyboard.press(key)}catch(err){if(isTimeout(err))throw err;throw new ActionError("TARGET_NOT_FOUND",`unknown key ${JSON.stringify(key).slice(0,40)}`)}return await this.afterNavigationCheck(page),{ok:!0}}case"scroll":{if(action.target){let target=await this.resolve(desk,action.target);if(target.kind==="point")await page.mouse.move(target.x,target.y);else await target.locator.hover()}return await page.mouse.wheel(action.dx,action.dy),{ok:!0}}case"navigate":{try{await checkNavigation(action.url,this.options.guard)}catch(err){if(err instanceof GuardError)return fail("URL_BLOCKED",err.message);throw err}return await page.goto(action.url,{waitUntil:"domcontentloaded"}),await this.afterNavigationCheck(page),desk.refAttr=null,{ok:!0,text:`${page.url()}
5
+ ${await page.title()}`}}default:return fail("DESK_OFFLINE",`a browser desk cannot ${action.type}`)}}}var PLUGIN_NAME="desk-browser",PLUGIN_PACKAGE_NAME="@vibecontrols/vibe-plugin-desk-browser",PLUGIN_VERSION=getPluginVersion(),DESK_PROVIDER_TYPE="desk",DESK_BROWSER_CONFIG={executablePath:"desk-browser.executable-path",channel:"desk-browser.channel",headless:"desk-browser.headless",proxy:"desk-browser.proxy",allowedHosts:"desk-browser.allowed-hosts"};function getPluginVersion(){try{let dir=dirname(fileURLToPath(import.meta.url));for(let i=0;i<10&&dir&&dir!==dirname(dir);i++){let pkgPath=joinPath(dir,"package.json");if(existsSync(pkgPath))try{let pkg=JSON.parse(readFileSync(pkgPath,"utf8"));if(pkg.name===PLUGIN_PACKAGE_NAME&&typeof pkg.version==="string")return pkg.version}catch{}dir=dirname(dir)}}catch{}return"0.0.0"}function defaultHeadless(platform=process.platform,env=process.env){if(platform!=="linux")return!1;return!env.DISPLAY&&!env.WAYLAND_DISPLAY}function parseProxy(value){if(!value)return;try{let url=new URL(value);if(url.protocol!=="http:"&&url.protocol!=="https:")return;if(url.username||url.password)return;return`${url.protocol}//${url.host}`}catch{return}}function createDeskBrowserPlugin(options={}){return(ctx)=>{let log=new BoundLogger(ctx.logger,PLUGIN_NAME),backend=null,lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"desk-browser.ready",onInit:async(host)=>{let read=async(key)=>(await host.getConfig?.(key))?.trim()||void 0,headlessSetting=await read(DESK_BROWSER_CONFIG.headless),proxySetting=await read(DESK_BROWSER_CONFIG.proxy),proxy=parseProxy(proxySetting);if(proxySetting&&!proxy)log.warn(`${DESK_BROWSER_CONFIG.proxy} is not an http(s) URL without credentials; ignored`);backend=new BrowserDeskBackend({profileFolder:joinPath(ctx.dataDir,"desk-browser-profile"),headless:headlessSetting?headlessSetting==="on":defaultHeadless(),executablePath:await read(DESK_BROWSER_CONFIG.executablePath),channel:await read(DESK_BROWSER_CONFIG.channel),proxy,guard:{allowedHosts:parseAllowedHosts(await read(DESK_BROWSER_CONFIG.allowedHosts))},secrets:()=>host.serviceRegistry?.getProvider?.(DESK_SECRET_PROVIDER_TYPE),launch:options.launch}),host.serviceRegistry?.registerProvider?.(DESK_PROVIDER_TYPE,backend,PLUGIN_NAME),log.info("browser desk registered")},onShutdown:async(context)=>{let current=backend;backend=null,await current?.close(),log.info(`browser desk stopped (${context?.reason??"shutdown"})`)}});return{name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Steward desk provider: a dedicated browser driven through the desk API",tags:["backend","provider"],capabilities:{telemetry:!0},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}}}var createPlugin=createDeskBrowserPlugin(),src_default=createPlugin;export{BROWSER_ACTIONS,BROWSER_LIMITS,BrowserDeskBackend,DESK_BROWSER_CONFIG,DESK_PROVIDER_TYPE,DESK_SECRET_PROVIDER_TYPE,checkNavigation,createDeskBrowserPlugin,createPlugin,src_default as default,defaultHeadless,isBlockedAddress,parseProxy,quickBlockReason};
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The desk browser's `snapshot`: a compact list of what a model can act on,
3
+ * each with a stable ref (spec §7: "accessibility-tree ref from the last
4
+ * snapshot (preferred)").
5
+ *
6
+ * Refs are written into the page as an attribute whose NAME is random per
7
+ * snapshot (`data-vc-<nonce>`). A page cannot predict it, so it cannot plant
8
+ * elements that answer to a ref the model will use later. Each new snapshot
9
+ * removes the previous attribute first. Before every action the backend
10
+ * re-resolves the ref and requires exactly one visible match
11
+ * (TARGET_NOT_FOUND otherwise).
12
+ *
13
+ * The main frame only; content inside iframes is not listed. Password field
14
+ * values are never read: they appear as `"value": "(hidden)"` when non-empty.
15
+ */
16
+ export interface SnapshotElement {
17
+ ref: string;
18
+ role: string;
19
+ name: string;
20
+ value?: string;
21
+ checked?: boolean;
22
+ disabled?: boolean;
23
+ level?: number;
24
+ }
25
+ export interface PageSnapshot {
26
+ url: string;
27
+ title: string;
28
+ elements: SnapshotElement[];
29
+ /** True when the element cap cut the list short. */
30
+ truncated: boolean;
31
+ }
32
+ export declare const SNAPSHOT_LIMITS: {
33
+ readonly maxElements: 500;
34
+ readonly maxName: 120;
35
+ readonly maxValue: 200;
36
+ readonly maxText: 20000;
37
+ };
38
+ export interface SnapshotArgs {
39
+ attr: string;
40
+ previousAttr: string | null;
41
+ maxElements: number;
42
+ maxName: number;
43
+ maxValue: number;
44
+ }
45
+ /**
46
+ * Runs INSIDE the page (passed to `page.evaluate`). It must stay
47
+ * self-contained: no imports, no closures over module scope.
48
+ */
49
+ export declare function collectInPage(args: SnapshotArgs): {
50
+ url: string;
51
+ title: string;
52
+ elements: SnapshotElement[];
53
+ truncated: boolean;
54
+ };
55
+ /** A fresh, unguessable attribute name for one snapshot. */
56
+ export declare function newRefAttribute(random?: () => string): string;
57
+ /** CSS selector for a ref under a given attribute; null when the ref is malformed. */
58
+ export declare function refSelector(attr: string, ref: string): string | null;
@@ -0,0 +1,33 @@
1
+ export type Resolver = (host: string) => Promise<string[]>;
2
+ export declare const systemResolver: Resolver;
3
+ export interface GuardOptions {
4
+ /** Hosts the desk may visit; empty means any public host. `*.example.com` matches subdomains. */
5
+ allowedHosts?: readonly string[];
6
+ /** Name resolution, injectable for tests. */
7
+ resolver?: Resolver;
8
+ /**
9
+ * Allow private, loopback and link-local destinations. Tests only: the
10
+ * plugin never sets it from configuration.
11
+ */
12
+ allowPrivateNetwork?: boolean;
13
+ }
14
+ export declare class GuardError extends Error {
15
+ name: string;
16
+ }
17
+ /** True when `ip` is not a globally routable unicast address. */
18
+ export declare function isBlockedAddress(ip: string): boolean;
19
+ /**
20
+ * Parse an allow-list from configuration: comma or whitespace separated
21
+ * host names, `*.` prefix for subdomains. Anything else is dropped.
22
+ */
23
+ export declare function parseAllowedHosts(value: string | undefined): string[];
24
+ /**
25
+ * Check a navigation target. Resolves the host and refuses it when any
26
+ * address is not public. Returns the parsed URL.
27
+ */
28
+ export declare function checkNavigation(raw: string, options?: GuardOptions): Promise<URL>;
29
+ /**
30
+ * Cheap per-request check (no DNS). Returns why the request must be refused,
31
+ * or null to let it through.
32
+ */
33
+ export declare function quickBlockReason(raw: string, options?: GuardOptions): string | null;
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@vibecontrols/vibe-plugin-desk-browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2026.1125.1",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "description": "Browser desk provider for BotManor Stewards: a dedicated Chromium profile driven with Playwright behind the common desk API (screenshot, snapshot refs, click, type, keys, scroll, guarded navigation, origin-bound secret fill).",
8
+ "engines": {
9
+ "bun": ">=1.4.4"
10
+ },
11
+ "author": {
12
+ "name": "Vignesh T.V",
13
+ "url": "https://github.com/tvvignesh"
14
+ },
15
+ "license": "MIT",
16
+ "scripts": {
17
+ "build": "bun build ./src/index.ts --outdir ./dist --target bun --minify-syntax --minify-whitespace --external playwright-core && tsc -p tsconfig.build.json",
18
+ "dev": "tsc -p tsconfig.build.json --watch",
19
+ "lint": "eslint .",
20
+ "format": "bun fmt",
21
+ "format:check": "bun fmt --check",
22
+ "type:check": "boff gate -- bun check --no-pretty",
23
+ "clean": "rimraf dist",
24
+ "prebuild": "bun run clean",
25
+ "prepublishOnly": "bun run build",
26
+ "sanity": "boff sanity",
27
+ "test": "bun test",
28
+ "sanity:force": "boff sanity --force",
29
+ "audit": "bun audit --audit-level=high"
30
+ },
31
+ "dependencies": {
32
+ "@vibecontrols/plugin-sdk": "2026.1125.1",
33
+ "playwright-core": "1.65.1"
34
+ },
35
+ "devDependencies": {
36
+ "@burdenoff/toolchain": "2026.1107.14",
37
+ "@types/bun": "^1.4.4",
38
+ "eslint": "^9.39.5",
39
+ "happy-dom": "21.0.4",
40
+ "knip": "^6.44.1",
41
+ "rimraf": "^6.1.4",
42
+ "typescript": "6.0.3"
43
+ },
44
+ "peerDependencies": {
45
+ "@vibecontrols/agent": ">=2026.1125.1"
46
+ },
47
+ "peerDependenciesMeta": {
48
+ "@vibecontrols/agent": {
49
+ "optional": true
50
+ }
51
+ },
52
+ "keywords": [
53
+ "vibecontrols",
54
+ "vibe",
55
+ "vibe-plugin",
56
+ "desk",
57
+ "stewards",
58
+ "computer-use",
59
+ "browser",
60
+ "playwright",
61
+ "bun"
62
+ ],
63
+ "repository": {
64
+ "type": "git",
65
+ "url": "git+https://github.com/Algoshred/vibe-plugin-desk-browser.git"
66
+ },
67
+ "bugs": {
68
+ "url": "https://github.com/Algoshred/vibe-plugin-desk-browser/issues"
69
+ },
70
+ "homepage": "https://github.com/Algoshred/vibe-plugin-desk-browser#readme",
71
+ "publishConfig": {
72
+ "access": "public",
73
+ "registry": "https://registry.npmjs.org/"
74
+ },
75
+ "files": [
76
+ "dist/**/*",
77
+ "!dist/**/*.map",
78
+ "README.md",
79
+ "LICENSE"
80
+ ]
81
+ }