Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat(plugin): improve OpenClaw compatibility

Bosch86dc60c3f112
diff --git a/plugin/README.md b/plugin/README.md
index 3871156a..4ca5f0bc 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -11,14 +11,14 @@ openclaw gateway restart
## Quick Start
-The plugin can auto-start a local PinchTab server when needed (`autoStart: true` by default). This only works when `baseUrl` points to a local address (`localhost`, `127.0.0.1`, or `::1`).
+Install the plugin, restart the gateway, then point it at a running PinchTab server.
```bash
openclaw plugins install @pinchtab/pinchtab
openclaw gateway restart
```
-For remote servers or Docker, set `autoStart: false` and configure `baseUrl` manually.
+By default the plugin auto-discovers local PinchTab settings from `~/.pinchtab/config.json`. If discovery succeeds, you usually do not need to set `baseUrl` or `token` manually.
## Configure
@@ -34,13 +34,6 @@ For remote servers or Docker, set `autoStart: false` and configure `baseUrl` man
token: "my-secret",
timeoutMs: 30000,
- // Auto-start (local only — localhost, 127.0.0.1, or ::1)
- // When enabled, spawns a PinchTab server process if baseUrl
- // points to a local address and the server is not running.
- autoStart: true,
- binaryPath: "pinchtab", // absolute path or binary name in PATH
- startupTimeoutMs: 30000, // max wait for server to become ready
-
// Policy
allowEvaluate: false, // block JS evaluate by default
allowedDomains: [], // empty = allow all
@@ -78,7 +71,7 @@ For remote servers or Docker, set `autoStart: false` and configure `baseUrl` man
### Manual Server Setup
-If auto-start is disabled or you're using Docker:
+The plugin does not launch the server for you. Start PinchTab separately:
```bash
# Local
@@ -88,16 +81,20 @@ PINCHTAB_TOKEN=my-secret pinchtab server &
docker run -d -p 9867:9867 ghcr.io/pinchtab/pinchtab:latest
```
-## Two Tools: `browser` and `pinchtab`
+## Two Tools: `pinchtab` first, `browser` as compatibility
The plugin registers two tools:
| Tool | Use Case |
|------|----------|
-| `browser` | OpenClaw-compatible, simplified interface for common flows |
-| `pinchtab` | Advanced control with all actions (mouse, wait, handoff, evaluate) |
+| `pinchtab` | Primary supported OpenClaw integration, full action surface |
+| `browser` | Compatibility alias for OpenClaw-style browser calls |
+
+`pinchtab` is the primary documented integration path.
-Disable the browser tool with `registerBrowserTool: false` if you only want `pinchtab`.
+`browser` is best-effort compatibility. Some OpenClaw surfaces treat `browser` specially, so the alias may not appear everywhere even when the plugin is loaded correctly.
+
+Disable the alias with `registerBrowserTool: false` if you only want `pinchtab`.
## Profiles
@@ -121,7 +118,9 @@ Map browser sessions to OpenClaw profile semantics:
}
```
-Usage: `browser({ action: "navigate", url: "...", profile: "user" })`
+Usage: `pinchtab({ action: "navigate", url: "https://example.com" })`
+
+Compatibility usage: `browser({ action: "navigate", url: "...", profile: "user" })`
## Browser Tool Actions
@@ -236,6 +235,14 @@ pinchtab({ action: "wait", text: "Welcome back", timeout: 120000 })
- Use `PINCHTAB_TOKEN` to gate API access; rotate regularly
- In production, run behind HTTPS reverse proxy (Caddy/nginx)
+## OpenClaw Integration Notes
+
+The most reliable OpenClaw integration path is the `pinchtab` tool.
+
+If you disable the bundled OpenClaw browser plugin and enable this plugin, agent turns that explicitly choose `browser` can resolve to PinchTab. However, OpenClaw may still route some tasks to other tools such as `web_fetch` or `canvas`, and some direct gateway surfaces may treat `browser` as a special compatibility name.
+
+For plugin-level validation in OpenClaw, prefer invoking `pinchtab` directly.
+
## Migrating from OpenClaw Bundled Browser
To replace the bundled `browser` plugin with PinchTab:
@@ -274,13 +281,13 @@ To replace the bundled `browser` plugin with PinchTab:
### 4. Key differences
-- **Auto-start**: PinchTab auto-starts locally by default (disable with `autoStart: false`)
+- **Server lifecycle**: start PinchTab separately; the plugin waits for readiness but does not spawn the server
- **Policy**: `allowEvaluate`, `allowDownloads`, `allowUploads` are `false` by default
-- **Advanced actions**: Use `pinchtab` tool for mouse controls, wait, handoff, evaluate
+- **Advanced actions**: use `pinchtab` for mouse controls, wait, handoff, evaluate, and direct plugin validation
## Requirements
-- PinchTab binary in PATH (or set `binaryPath`)
+- Running PinchTab server
- OpenClaw Gateway
## Disclaimer
diff --git a/plugin/client.ts b/plugin/client.ts
index 8f761838..d367f339 100644
--- a/plugin/client.ts
+++ b/plugin/client.ts
@@ -1,18 +1,20 @@
import type { PluginConfig, ToolResult } from "./types.js";
+import { resolveEffectiveConfig } from "./session.js";
export async function pinchtabFetch(
cfg: PluginConfig,
path: string,
opts: { method?: string; body?: unknown; rawResponse?: boolean } = {},
): Promise<any> {
- const base = cfg.baseUrl || "http://localhost:9867";
+ const effectiveCfg = await resolveEffectiveConfig(cfg);
+ const base = effectiveCfg.baseUrl || "http://localhost:9867";
const url = `${base}${path}`;
const headers: Record<string, string> = {};
- if (cfg.token) headers["Authorization"] = `Bearer ${cfg.token}`;
+ if (effectiveCfg.token) headers["Authorization"] = `Bearer ${effectiveCfg.token}`;
if (opts.body) headers["Content-Type"] = "application/json";
const controller = new AbortController();
- const timeout = cfg.timeoutMs ?? cfg.timeout ?? 30000;
+ const timeout = effectiveCfg.timeoutMs ?? effectiveCfg.timeout ?? 30000;
const timer = setTimeout(() => controller.abort(), timeout);
try {
diff --git a/plugin/index.ts b/plugin/index.ts
index fd2e2295..1ad9aee1 100644
--- a/plugin/index.ts
+++ b/plugin/index.ts
@@ -6,6 +6,7 @@
* - `browser`: OpenClaw-compatible simplified interface
*/
+import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
import type { PluginApi, PluginConfig, PluginTool } from "./types.js";
import { pinchtabToolSchema, pinchtabToolDescription, executePinchtabAction } from "./tools/pinchtab.js";
import { browserToolSchema, browserToolDescription, executeBrowserAction } from "./tools/browser.js";
@@ -14,32 +15,35 @@ function getConfig(api: PluginApi): PluginConfig {
return (api.pluginConfig ?? api.config?.plugins?.entries?.pinchtab?.config ?? {}) as PluginConfig;
}
-export default function register(api: PluginApi) {
- const cfg = getConfig(api);
+export default definePluginEntry({
+ id: "pinchtab",
+ name: "Pinchtab",
+ description: "Browser control for AI agents via Pinchtab.",
+ register(api) {
+ const cfg = getConfig(api);
- // Register the full-featured pinchtab tool
- const pinchtabTool = {
- name: "pinchtab",
- label: "PinchTab",
- description: pinchtabToolDescription,
- parameters: pinchtabToolSchema,
- async execute(_id: string, params: any) {
- return executePinchtabAction(getConfig(api), params);
- },
- } satisfies PluginTool;
- api.registerTool(pinchtabTool, { optional: true });
-
- // Register OpenClaw-compatible browser tool
- if (cfg.registerBrowserTool !== false) {
- const browserTool = {
- name: "browser",
- label: "Browser",
- description: browserToolDescription,
- parameters: browserToolSchema,
+ const pinchtabTool = {
+ name: "pinchtab",
+ label: "PinchTab",
+ description: pinchtabToolDescription,
+ parameters: pinchtabToolSchema,
async execute(_id: string, params: any) {
- return executeBrowserAction(getConfig(api), params);
+ return executePinchtabAction(getConfig(api), params);
},
} satisfies PluginTool;
- api.registerTool(browserTool, { optional: true });
- }
-}
+ api.registerTool(pinchtabTool);
+
+ if (cfg.registerBrowserTool !== false) {
+ const browserTool = {
+ name: "browser",
+ label: "Browser",
+ description: browserToolDescription,
+ parameters: browserToolSchema,
+ async execute(_id: string, params: any) {
+ return executeBrowserAction(getConfig(api), params);
+ },
+ } satisfies PluginTool;
+ api.registerTool(browserTool);
+ }
+ },
+});
diff --git a/plugin/navigation.test.ts b/plugin/navigation.test.ts
new file mode 100644
index 00000000..210e6105
--- /dev/null
+++ b/plugin/navigation.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, beforeEach, describe, it } from "node:test";
+import assert from "node:assert";
+import { executeBrowserAction } from "./tools/browser.ts";
+import { executePinchtabAction } from "./tools/pinchtab.ts";
+import { setLastTabId } from "./session.ts";
+
+type FetchCall = { url: string; method: string; body?: any };
+
+const originalFetch = globalThis.fetch;
+
+function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
+ return new Response(JSON.stringify(body), {
+ status: init.status ?? 200,
+ headers: { "Content-Type": "application/json", ...(init.headers || {}) },
+ });
+}
+
+describe("navigation routing", () => {
+ let calls: FetchCall[] = [];
+
+ beforeEach(() => {
+ calls = [];
+ setLastTabId(undefined);
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
+ const method = init?.method || "GET";
+ const body = typeof init?.body === "string" ? JSON.parse(init.body) : undefined;
+ calls.push({ url, method, body });
+
+ const path = new URL(url).pathname;
+ if (path === "/health") return jsonResponse({ ok: true, version: "test" });
+ if (path === "/instances") return jsonResponse([{ id: "inst_a", status: "running" }]);
+ if (path === "/navigate") return jsonResponse({ tabId: "tab_nav" });
+ if (path === "/tab") return jsonResponse({ tabId: "tab_new" });
+ if (path === "/tabs/tab_existing/navigate") return jsonResponse({ tabId: "tab_existing" });
+ throw new Error(`unexpected fetch: ${path}`);
+ }) as typeof fetch;
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ it("browser navigate reuses top-level /navigate when tabId is absent", async () => {
+ const result = await executeBrowserAction({ baseUrl: "http://localhost:9867" }, { action: "navigate", url: "https://example.com" });
+ assert.match(result.content[0].text, /tab_nav/);
+ assert.ok(calls.some((call) => new URL(call.url).pathname === "/navigate"));
+ assert.ok(!calls.some((call) => new URL(call.url).pathname === "/tab"));
+ });
+
+ it("browser navigate still uses /tab for explicit newTab", async () => {
+ const result = await executeBrowserAction({ baseUrl: "http://localhost:9867" }, { action: "navigate", url: "https://example.com", newTab: true });
+ assert.match(result.content[0].text, /tab_new/);
+ assert.ok(calls.some((call) => new URL(call.url).pathname === "/tab"));
+ });
+
+ it("pinchtab navigate reuses top-level /navigate when tabId is absent", async () => {
+ const result = await executePinchtabAction({ baseUrl: "http://localhost:9867" }, { action: "navigate", url: "https://example.com" });
+ assert.match(result.content[0].text, /tab_nav/);
+ assert.ok(calls.some((call) => new URL(call.url).pathname === "/navigate"));
+ assert.ok(!calls.some((call) => new URL(call.url).pathname === "/tab"));
+ });
+
+ it("pinchtab navigate uses tab-scoped route when tabId is present", async () => {
+ const result = await executePinchtabAction({ baseUrl: "http://localhost:9867", persistSessionTabs: false }, { action: "navigate", url: "https://example.com", tabId: "tab_existing" });
+ assert.match(result.content[0].text, /tab_existing/);
+ assert.ok(calls.some((call) => new URL(call.url).pathname === "/tabs/tab_existing/navigate"));
+ });
+});
diff --git a/plugin/openclaw-api.test.ts b/plugin/openclaw-api.test.ts
index 2b47877c..9c9dd517 100644
--- a/plugin/openclaw-api.test.ts
+++ b/plugin/openclaw-api.test.ts
@@ -1,7 +1,7 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import type { AnyAgentTool, OpenClawPluginApi, PluginLogger, PluginRuntime } from "openclaw/plugin-sdk";
-import register from "./index.ts";
+import pluginEntry from "./index.ts";
type RegisteredToolOptions = Parameters<OpenClawPluginApi["registerTool"]>[1];
type TestPluginApiInput = Partial<OpenClawPluginApi>;
@@ -107,7 +107,7 @@ describe("OpenClaw plugin API contract", () => {
},
});
- register(api);
+ pluginEntry.register(api);
assert.deepStrictEqual(
registered.map(({ tool }) => tool.name).sort(),
@@ -118,7 +118,7 @@ describe("OpenClaw plugin API contract", () => {
assert.strictEqual(typeof tool.description, "string");
assert.strictEqual(typeof tool.execute, "function");
assert.strictEqual((tool.parameters as { type?: string }).type, "object");
- assert.strictEqual(opts?.optional, true);
+ assert.strictEqual(opts, undefined);
}
});
@@ -134,7 +134,7 @@ describe("OpenClaw plugin API contract", () => {
},
});
- register(api);
+ pluginEntry.register(api);
assert.deepStrictEqual(names, ["pinchtab"]);
});
diff --git a/plugin/openclaw.plugin.json b/plugin/openclaw.plugin.json
index ac6d7c75..c6489c32 100644
--- a/plugin/openclaw.plugin.json
+++ b/plugin/openclaw.plugin.json
@@ -3,7 +3,13 @@
"name": "Pinchtab",
"description": "Browser control for AI agents via Pinchtab. Single tool, all actions: navigate, snapshot, click/type/press/fill/hover/scroll/select/focus, mouse-move/mouse-down/mouse-up/mouse-wheel, text, screenshot, evaluate, pdf.",
"version": "0.3.0",
- "skills": ["../skills/pinchtab"],
+ "contracts": {
+ "tools": ["pinchtab", "browser"]
+ },
+ "activation": {
+ "onStartup": true
+ },
+ "skills": ["./skills/pinchtab"],
"configSchema": {
"type": "object",
"additionalProperties": false,
@@ -22,20 +28,6 @@
"description": "Default request timeout in milliseconds",
"default": 30000
},
- "autoStart": {
- "type": "boolean",
- "description": "Auto-start local Pinchtab server if not running",
- "default": true
- },
- "binaryPath": {
- "type": "string",
- "description": "Path to pinchtab binary (default: search PATH)"
- },
- "startupTimeoutMs": {
- "type": "number",
- "description": "Max time to wait for server startup",
- "default": 30000
- },
"allowEvaluate": {
"type": "boolean",
"description": "Allow evaluate action (JS execution)",
@@ -111,9 +103,6 @@
"baseUrl": { "label": "Base URL", "placeholder": "http://localhost:9867" },
"token": { "label": "Auth Token", "sensitive": true },
"timeoutMs": { "label": "Timeout (ms)", "placeholder": "30000" },
- "autoStart": { "label": "Auto-start Server" },
- "binaryPath": { "label": "Binary Path", "placeholder": "pinchtab" },
- "startupTimeoutMs": { "label": "Startup Timeout (ms)", "placeholder": "30000" },
"allowEvaluate": { "label": "Allow JS Evaluate" },
"allowedDomains": { "label": "Allowed Domains" },
"allowDownloads": { "label": "Allow Downloads" },
diff --git a/plugin/session.test.ts b/plugin/session.test.ts
index e6870250..67a789e7 100644
--- a/plugin/session.test.ts
+++ b/plugin/session.test.ts
@@ -1,6 +1,6 @@
import { describe, it, beforeEach } from "node:test";
import assert from "node:assert";
-import { getLastTabId, setLastTabId, resolveProfile, isLocalHost } from "./session.ts";
+import { getLastTabId, setLastTabId, resolveProfile, isLocalHost, formatDiscoveredBaseUrl } from "./session.ts";
describe("tab session state", () => {
beforeEach(() => {
@@ -93,3 +93,15 @@ describe("isLocalHost", () => {
assert.strictEqual(isLocalHost(""), false);
});
});
+
+
+describe("formatDiscoveredBaseUrl", () => {
+ it("brackets IPv6 loopback binds", () => {
+ assert.strictEqual(formatDiscoveredBaseUrl("::1", 9867), "http://[::1]:9867");
+ });
+
+ it("normalizes wildcard binds to local loopback", () => {
+ assert.strictEqual(formatDiscoveredBaseUrl("0.0.0.0", 9867), "http://127.0.0.1:9867");
+ assert.strictEqual(formatDiscoveredBaseUrl("::", 9867), "http://[::1]:9867");
+ });
+});
diff --git a/plugin/session.ts b/plugin/session.ts
index efc3b033..c2b3e79e 100644
--- a/plugin/session.ts
+++ b/plugin/session.ts
@@ -1,9 +1,27 @@
+import { readFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
import type { PluginConfig } from "./types.js";
import { pinchtabFetch } from "./client.js";
-let serverStarted = false;
+const instanceReadyRetryDelayMs = 500;
+const instanceReadyMaxWaitMs = 12000;
+
let lastTabId: string | undefined;
-let startupPromise: Promise<{ ok: boolean; error?: string; autoStarted?: boolean }> | null = null;
+let discoveredConfig: { baseUrl?: string; token?: string } | null | undefined;
+
+export function normalizeDiscoveredHost(bind: string): string {
+ if (bind === "0.0.0.0") return "127.0.0.1";
+ if (bind === "::") return "::1";
+ return bind;
+}
+
+export function formatHostForUrl(host: string): string {
+ if (host.includes(":") && !host.startsWith("[") && !host.endsWith("]")) {
+ return `[${host}]`;
+ }
+ return host;
+}
export function isLocalHost(baseUrl: string): boolean {
try {
@@ -34,21 +52,64 @@ export function resolveProfile(cfg: PluginConfig, profile?: string): { instanceI
return {};
}
+async function discoverPinchtabConfig(): Promise<{ baseUrl?: string; token?: string } | null> {
+ if (discoveredConfig !== undefined) {
+ return discoveredConfig;
+ }
+
+ try {
+ const path = join(homedir(), ".pinchtab", "config.json");
+ const raw = await readFile(path, "utf8");
+ const parsed = JSON.parse(raw);
+ const bind = parsed?.server?.bind || "127.0.0.1";
+ const port = parsed?.server?.port;
+ const token = parsed?.server?.token;
+
+ let baseUrl: string | undefined;
+ if (port) {
+ const host = formatHostForUrl(normalizeDiscoveredHost(bind));
+ baseUrl = `http://${host}:${port}`;
+ }
+
+ discoveredConfig = {
+ baseUrl,
+ token: typeof token === "string" && token ? token : undefined,
+ };
+ return discoveredConfig;
+ } catch {
+ discoveredConfig = null;
+ return discoveredConfig;
+ }
+}
+
+export function formatDiscoveredBaseUrl(bind: string, port: string | number): string {
+ return `http://${formatHostForUrl(normalizeDiscoveredHost(bind))}:${port}`;
+}
+
+export async function resolveEffectiveConfig(cfg: PluginConfig): Promise<PluginConfig> {
+ const discovered = await discoverPinchtabConfig();
+ return {
+ ...cfg,
+ baseUrl: cfg.baseUrl || discovered?.baseUrl || "http://localhost:9867",
+ token: cfg.token || discovered?.token,
+ };
+}
+
export async function getEnhancedHealth(cfg: PluginConfig): Promise<any> {
- const base = cfg.baseUrl || "http://localhost:9867";
- const health = await pinchtabFetch(cfg, "/health");
+ const effectiveCfg = await resolveEffectiveConfig(cfg);
+ const base = effectiveCfg.baseUrl || "http://localhost:9867";
+ const health = await pinchtabFetch(effectiveCfg, "/health");
const serverOk = !health?.error;
const result: any = {
server: serverOk ? "ok" : "unreachable",
baseUrl: base,
- autoStart: cfg.autoStart !== false,
- defaultProfile: cfg.defaultProfile || "openclaw",
+ defaultProfile: effectiveCfg.defaultProfile || "openclaw",
policies: {
- allowEvaluate: cfg.allowEvaluate === true,
- allowDownloads: cfg.allowDownloads === true,
- allowUploads: cfg.allowUploads === true,
- allowedDomains: cfg.allowedDomains?.length ? cfg.allowedDomains : "all",
+ allowEvaluate: effectiveCfg.allowEvaluate === true,
+ allowDownloads: effectiveCfg.allowDownloads === true,
+ allowUploads: effectiveCfg.allowUploads === true,
+ allowedDomains: effectiveCfg.allowedDomains?.length ? effectiveCfg.allowedDomains : "all",
},
};
@@ -57,77 +118,79 @@ export async function getEnhancedHealth(cfg: PluginConfig): Promise<any> {
if (health?.version) result.serverVersion = health.version;
} else {
result.error = health?.error;
+ if (isLocalHost(base)) {
+ result.hint = `Pinchtab is not reachable at ${base}. Start it with: pinchtab server`;
+ }
}
const warnings: string[] = [];
- if (cfg.allowEvaluate) warnings.push("evaluate enabled - JS execution allowed");
- if (!cfg.allowedDomains?.length) warnings.push("no domain restrictions");
+ if (effectiveCfg.allowEvaluate) warnings.push("evaluate enabled - JS execution allowed");
+ if (!effectiveCfg.allowedDomains?.length) warnings.push("no domain restrictions");
if (warnings.length) result.warnings = warnings;
return result;
}
export async function ensureServerRunning(cfg: PluginConfig): Promise<{ ok: boolean; error?: string; autoStarted?: boolean }> {
- const base = cfg.baseUrl || "http://localhost:9867";
-
- const healthCheck = await pinchtabFetch(cfg, "/health");
+ const effectiveCfg = await resolveEffectiveConfig(cfg);
+ const base = effectiveCfg.baseUrl || "http://localhost:9867";
+ const healthCheck = await pinchtabFetch(effectiveCfg, "/health");
if (!healthCheck?.error) {
return { ok: true };
}
- if (!isLocalHost(base) || cfg.autoStart === false || serverStarted) {
- return { ok: false, error: healthCheck.error };
- }
+ const hint = isLocalHost(base)
+ ? ` Pinchtab is not running at ${base}. Start it with: pinchtab server`
+ : "";
+ return { ok: false, error: `${healthCheck.error}${hint}` };
+}
- // Single-flight guard: if startup is in progress, wait for it
- if (startupPromise) {
- return startupPromise;
- }
+export async function waitForInstanceReady(cfg: PluginConfig, instanceId?: string): Promise<{ ok: boolean; error?: string }> {
+ const effectiveCfg = await resolveEffectiveConfig(cfg);
+ const start = Date.now();
+ let lastError = "instance not ready";
+
+ while (Date.now() - start < instanceReadyMaxWaitMs) {
+ const health = await pinchtabFetch(effectiveCfg, "/health");
+ if (!health?.error) {
+ const instances = await pinchtabFetch(effectiveCfg, "/instances");
+ const list = Array.isArray(instances?.value)
+ ? instances.value
+ : Array.isArray(instances)
+ ? instances
+ : [];
+ const running = instanceId
+ ? list.find((instance: any) => instance?.id === instanceId && instance?.status === "running")
+ : list.find((instance: any) => instance?.status === "running" && instance?.id);
+ if (running) {
+ return { ok: true };
+ }
+ if (instanceId && list.some((instance: any) => instance?.id === instanceId)) {
+ lastError = `instance ${instanceId} not ready`;
+ }
+ } else {
+ lastError = health.error || lastError;
+ }
- startupPromise = doStartServer(cfg);
- try {
- return await startupPromise;
- } finally {
- startupPromise = null;
- }
-}
+ if (instanceId) {
+ await new Promise((resolve) => setTimeout(resolve, instanceReadyRetryDelayMs));
+ continue;
+ }
-async function resolveBinaryPath(binary: string): Promise<string> {
- if (binary.startsWith("/") || binary.startsWith("./")) {
- return binary;
- }
- try {
- const { execFileSync } = await import("child_process");
- const resolved = execFileSync("which", [binary], { encoding: "utf8" }).trim();
- return resolved || binary;
- } catch {
- return binary;
- }
-}
+ const tabs = await pinchtabFetch(effectiveCfg, "/tabs");
+ if (!tabs?.error) {
+ return { ok: true };
+ }
-async function doStartServer(cfg: PluginConfig): Promise<{ ok: boolean; error?: string; autoStarted?: boolean }> {
- const binary = await resolveBinaryPath(cfg.binaryPath || "pinchtab");
- const startupTimeout = cfg.startupTimeoutMs ?? 30000;
+ const text = `${tabs?.error || ""} ${tabs?.body || ""}`.toLowerCase();
+ lastError = tabs?.error || lastError;
- try {
- const { spawn } = await import("child_process");
- const proc = spawn(binary, ["server"], {
- detached: true,
- stdio: "ignore",
- });
- proc.unref();
- serverStarted = true;
-
- const startTime = Date.now();
- while (Date.now() - startTime < startupTimeout) {
- await new Promise((r) => setTimeout(r, 500));
- const check = await pinchtabFetch(cfg, "/health");
- if (!check?.error) {
- return { ok: true, autoStarted: true };
- }
+ if (!text.includes("instance not ready") && !text.includes("may be restarting") && !text.includes("503")) {
+ return { ok: false, error: tabs?.error || "unknown readiness error" };
}
- return { ok: false, error: `Server failed to start within ${startupTimeout}ms` };
- } catch (err: any) {
- return { ok: false, error: `Failed to start pinchtab: ${err?.message}` };
+
+ await new Promise((resolve) => setTimeout(resolve, instanceReadyRetryDelayMs));
}
+
+ return { ok: false, error: `Timed out waiting for Pinchtab instance readiness: ${lastError}` };
}
diff --git a/plugin/tools/browser.ts b/plugin/tools/browser.ts
index afaeb353..84ff7310 100644
--- a/plugin/tools/browser.ts
+++ b/plugin/tools/browser.ts
@@ -1,7 +1,7 @@
import type { PluginConfig } from "../types.js";
import { pinchtabFetch, textResult, imageResult, resourceResult } from "../client.js";
import { checkNavigationPolicy, enforcePolicyOrReturn } from "../policy.js";
-import { ensureServerRunning, getEnhancedHealth, resolveProfile, getLastTabId, setLastTabId } from "../session.js";
+import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, resolveProfile, getLastTabId, setLastTabId } from "../session.js";
export const browserToolSchema = {
type: "object",
@@ -55,6 +55,10 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Prom
if (!serverCheck.ok) {
return textResult({ error: serverCheck.error });
}
+ const readyCheck = await waitForInstanceReady(cfg, profileConfig.instanceId);
+ if (!readyCheck.ok) {
+ return textResult({ error: readyCheck.error });
+ }
}
// Session tab persistence
@@ -67,11 +71,20 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Prom
const navPolicy = enforcePolicyOrReturn(checkNavigationPolicy(cfg, params.url));
if (navPolicy) return navPolicy;
- const body: any = { url: params.url };
- if (params.tabId) body.tabId = params.tabId;
- if (params.newTab) body.newTab = true;
- if (profileConfig.instanceId) body.instanceId = profileConfig.instanceId;
- const result = await pinchtabFetch(cfg, "/navigate", { body });
+ let result;
+ if (params.newTab) {
+ const body: any = { action: "new", url: params.url };
+ if (profileConfig.instanceId) body.instanceId = profileConfig.instanceId;
+ result = await pinchtabFetch(cfg, "/tab", { body });
+ } else if (params.tabId) {
+ const body: any = { url: params.url };
+ if (profileConfig.instanceId) body.instanceId = profileConfig.instanceId;
+ result = await pinchtabFetch(cfg, `/tabs/${encodeURIComponent(params.tabId)}/navigate`, { body });
+ } else {
+ const body: any = { url: params.url };
+ if (profileConfig.instanceId) body.instanceId = profileConfig.instanceId;
+ result = await pinchtabFetch(cfg, "/navigate", { body });
+ }
if (result?.tabId) setLastTabId(result.tabId);
return textResult(result);
}
diff --git a/plugin/tools/pinchtab.ts b/plugin/tools/pinchtab.ts
index 7648cdd3..bde90c95 100644
--- a/plugin/tools/pinchtab.ts
+++ b/plugin/tools/pinchtab.ts
@@ -1,7 +1,7 @@
import type { PluginConfig } from "../types.js";
import { pinchtabFetch, textResult, imageResult, resourceResult, normalizeActionParams, looksLikeStaleRef } from "../client.js";
import { checkNavigationPolicy, checkEvaluatePolicy, checkDownloadPolicy, checkUploadPolicy, checkNetworkInterceptPolicy, enforcePolicyOrReturn } from "../policy.js";
-import { ensureServerRunning, getEnhancedHealth, getLastTabId, setLastTabId } from "../session.js";
+import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, getLastTabId, setLastTabId } from "../session.js";
export const pinchtabToolSchema = {
type: "object",
@@ -100,6 +100,10 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (!serverCheck.ok) {
return textResult({ error: serverCheck.error });
}
+ const readyCheck = await waitForInstanceReady(cfg);
+ if (!readyCheck.ok) {
+ return textResult({ error: readyCheck.error });
+ }
}
// Session tab persistence
@@ -118,12 +122,23 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
const navPolicy = enforcePolicyOrReturn(checkNavigationPolicy(cfg, normalized.url));
if (navPolicy) return navPolicy;
- const body: any = { url: normalized.url };
- if (normalized.tabId) body.tabId = normalized.tabId;
- if (normalized.newTab) body.newTab = true;
- if (normalized.blockImages) body.blockImages = true;
- if (normalized.timeout) body.timeout = normalized.timeout;
- const result = await pinchtabFetch(cfg, "/navigate", { body });
+ let result;
+ if (normalized.newTab) {
+ const body: any = { action: "new", url: normalized.url };
+ if (normalized.blockImages) body.blockImages = true;
+ if (normalized.timeout) body.timeout = normalized.timeout;
+ result = await pinchtabFetch(cfg, "/tab", { body });
+ } else if (normalized.tabId) {
+ const body: any = { url: normalized.url };
+ if (normalized.blockImages) body.blockImages = true;
+ if (normalized.timeout) body.timeout = normalized.timeout;
+ result = await pinchtabFetch(cfg, `/tabs/${encodeURIComponent(normalized.tabId)}/navigate`, { body });
+ } else {
+ const body: any = { url: normalized.url };
+ if (normalized.blockImages) body.blockImages = true;
+ if (normalized.timeout) body.timeout = normalized.timeout;
+ result = await pinchtabFetch(cfg, "/navigate", { body });
+ }
if (result?.tabId) setLastTabId(result.tabId);
return textResult(result);
}
diff --git a/plugin/types.ts b/plugin/types.ts
index 4bdb7dba..7e3ac00c 100644
--- a/plugin/types.ts
+++ b/plugin/types.ts
@@ -6,9 +6,6 @@ export interface PluginConfig {
timeoutMs?: number;
/** @deprecated Use timeoutMs instead */
timeout?: number;
- autoStart?: boolean;
- binaryPath?: string;
- startupTimeoutMs?: number;
allowEvaluate?: boolean;
allowedDomains?: string[];
allowDownloads?: boolean;