Skip to content

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

feat(plugin): reuse Pinchtab state per OpenClaw agent

Bosch7f668ada268f
diff --git a/plugin/client.test.ts b/plugin/client.test.ts
index 11a2adad..adf7c318 100644
--- a/plugin/client.test.ts
+++ b/plugin/client.test.ts
@@ -1,6 +1,6 @@
-import { describe, it } from "node:test";
+import { afterEach, beforeEach, describe, it } from "node:test";
import assert from "node:assert";
-import { isRefToken, normalizeActionParams, looksLikeStaleRef, textResult, imageResult, resourceResult } from "./client.ts";
+import { isRefToken, normalizeActionParams, looksLikeStaleRef, pinchtabFetch, textResult, imageResult, resourceResult } from "./client.ts";
describe("isRefToken", () => {
it("returns true for valid ref tokens", () => {
@@ -83,6 +83,38 @@ describe("looksLikeStaleRef", () => {
});
});
+describe("pinchtabFetch", () => {
+ const originalFetch = globalThis.fetch;
+
+ beforeEach(() => {
+ globalThis.fetch = (async (_input: string | URL | Request, init?: RequestInit) => {
+ return new Response(JSON.stringify({ headers: init?.headers ?? {} }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }) as typeof fetch;
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ it("forwards OpenClaw agent and session headers", async () => {
+ const result = await pinchtabFetch(
+ { baseUrl: "http://localhost:9867", token: "secret" },
+ "/health",
+ {},
+ { agentId: "writer", sessionId: "session-123", sessionKey: "chat:writer" },
+ );
+ assert.deepStrictEqual(result.headers, {
+ Authorization: "Bearer secret",
+ "X-OpenClaw-Agent-Id": "writer",
+ "X-OpenClaw-Session-Id": "session-123",
+ "X-OpenClaw-Session-Key": "chat:writer",
+ });
+ });
+});
+
describe("textResult", () => {
it("wraps string as text content", () => {
const result = textResult("hello");
diff --git a/plugin/client.ts b/plugin/client.ts
index d367f339..4f173cde 100644
--- a/plugin/client.ts
+++ b/plugin/client.ts
@@ -1,16 +1,26 @@
-import type { PluginConfig, ToolResult } from "./types.js";
+import type { PluginConfig, PluginRuntimeContext, ToolResult } from "./types.js";
import { resolveEffectiveConfig } from "./session.js";
+function buildRequestHeaders(cfg: PluginConfig, context?: PluginRuntimeContext): Record<string, string> {
+ const headers: Record<string, string> = {};
+ if (cfg.token) headers["Authorization"] = `Bearer ${cfg.token}`;
+ if (context?.agentId) headers["X-OpenClaw-Agent-Id"] = context.agentId;
+ if (context?.agentName) headers["X-OpenClaw-Agent-Name"] = context.agentName;
+ if (context?.sessionId) headers["X-OpenClaw-Session-Id"] = context.sessionId;
+ if (context?.sessionKey) headers["X-OpenClaw-Session-Key"] = context.sessionKey;
+ return headers;
+}
+
export async function pinchtabFetch(
cfg: PluginConfig,
path: string,
opts: { method?: string; body?: unknown; rawResponse?: boolean } = {},
+ context?: PluginRuntimeContext,
): Promise<any> {
const effectiveCfg = await resolveEffectiveConfig(cfg);
const base = effectiveCfg.baseUrl || "http://localhost:9867";
const url = `${base}${path}`;
- const headers: Record<string, string> = {};
- if (effectiveCfg.token) headers["Authorization"] = `Bearer ${effectiveCfg.token}`;
+ const headers = buildRequestHeaders(effectiveCfg, context);
if (opts.body) headers["Content-Type"] = "application/json";
const controller = new AbortController();
diff --git a/plugin/index.ts b/plugin/index.ts
index 1ad9aee1..8b8c11f4 100644
--- a/plugin/index.ts
+++ b/plugin/index.ts
@@ -7,7 +7,7 @@
*/
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
-import type { PluginApi, PluginConfig, PluginTool } from "./types.js";
+import type { PluginApi, PluginConfig, PluginRuntimeContext, PluginTool, PluginToolContext } from "./types.js";
import { pinchtabToolSchema, pinchtabToolDescription, executePinchtabAction } from "./tools/pinchtab.js";
import { browserToolSchema, browserToolDescription, executeBrowserAction } from "./tools/browser.js";
@@ -15,6 +15,14 @@ function getConfig(api: PluginApi): PluginConfig {
return (api.pluginConfig ?? api.config?.plugins?.entries?.pinchtab?.config ?? {}) as PluginConfig;
}
+function toRuntimeContext(ctx: PluginToolContext): PluginRuntimeContext {
+ return {
+ agentId: ctx.agentId,
+ sessionId: ctx.sessionId,
+ sessionKey: ctx.sessionKey,
+ };
+}
+
export default definePluginEntry({
id: "pinchtab",
name: "Pinchtab",
@@ -22,28 +30,34 @@ export default definePluginEntry({
register(api) {
const cfg = getConfig(api);
- 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);
-
- if (cfg.registerBrowserTool !== false) {
- const browserTool = {
- name: "browser",
- label: "Browser",
- description: browserToolDescription,
- parameters: browserToolSchema,
+ api.registerTool((ctx) => {
+ const runtimeContext = toRuntimeContext(ctx);
+ 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, runtimeContext);
},
} satisfies PluginTool;
- api.registerTool(browserTool);
+ return pinchtabTool;
+ });
+
+ if (cfg.registerBrowserTool !== false) {
+ api.registerTool((ctx) => {
+ const runtimeContext = toRuntimeContext(ctx);
+ const browserTool = {
+ name: "browser",
+ label: "Browser",
+ description: browserToolDescription,
+ parameters: browserToolSchema,
+ async execute(_id: string, params: any) {
+ return executeBrowserAction(getConfig(api), params, runtimeContext);
+ },
+ } satisfies PluginTool;
+ return browserTool;
+ });
}
},
});
diff --git a/plugin/openclaw-api.test.ts b/plugin/openclaw-api.test.ts
index 9c9dd517..f592465e 100644
--- a/plugin/openclaw-api.test.ts
+++ b/plugin/openclaw-api.test.ts
@@ -1,6 +1,6 @@
import { describe, it } from "node:test";
import assert from "node:assert";
-import type { AnyAgentTool, OpenClawPluginApi, PluginLogger, PluginRuntime } from "openclaw/plugin-sdk";
+import type { AnyAgentTool, OpenClawPluginApi, OpenClawPluginToolContext, PluginLogger, PluginRuntime } from "openclaw/plugin-sdk";
import pluginEntry from "./index.ts";
type RegisteredToolOptions = Parameters<OpenClawPluginApi["registerTool"]>[1];
@@ -87,6 +87,12 @@ function createTestPluginApi(api: TestPluginApiInput): OpenClawPluginApi {
};
}
+const testToolContext: OpenClawPluginToolContext = {
+ agentId: "main",
+ sessionId: "session-1",
+ sessionKey: "chat:main",
+};
+
describe("OpenClaw plugin API contract", () => {
it("registers tools through the official OpenClaw plugin API", () => {
const registered: Array<{ tool: AnyAgentTool; opts?: RegisteredToolOptions }> = [];
@@ -102,8 +108,9 @@ describe("OpenClaw plugin API contract", () => {
},
},
registerTool(tool, opts) {
- assert.strictEqual(typeof tool, "object");
- registered.push({ tool: tool as AnyAgentTool, opts });
+ const resolved = typeof tool === "function" ? tool(testToolContext) : tool;
+ assert.ok(resolved);
+ registered.push({ tool: resolved as AnyAgentTool, opts });
},
});
@@ -129,8 +136,9 @@ describe("OpenClaw plugin API contract", () => {
name: "Pinchtab",
pluginConfig: { registerBrowserTool: false },
registerTool(tool) {
- assert.strictEqual(typeof tool, "object");
- names.push((tool as AnyAgentTool).name);
+ const resolved = typeof tool === "function" ? tool(testToolContext) : tool;
+ assert.ok(resolved);
+ names.push((resolved as AnyAgentTool).name);
},
});
diff --git a/plugin/session.test.ts b/plugin/session.test.ts
index 67a789e7..6b794794 100644
--- a/plugin/session.test.ts
+++ b/plugin/session.test.ts
@@ -5,6 +5,8 @@ import { getLastTabId, setLastTabId, resolveProfile, isLocalHost, formatDiscover
describe("tab session state", () => {
beforeEach(() => {
setLastTabId(undefined);
+ setLastTabId(undefined, { agentId: "main" });
+ setLastTabId(undefined, { agentId: "writer" });
});
it("starts with undefined tabId", () => {
@@ -16,6 +18,14 @@ describe("tab session state", () => {
assert.strictEqual(getLastTabId(), "tab123");
});
+ it("keeps tab state isolated per agent", () => {
+ setLastTabId("main-tab", { agentId: "main", sessionId: "s1" });
+ setLastTabId("writer-tab", { agentId: "writer", sessionId: "s2" });
+ assert.strictEqual(getLastTabId({ agentId: "main" }), "main-tab");
+ assert.strictEqual(getLastTabId({ agentId: "writer" }), "writer-tab");
+ assert.strictEqual(getLastTabId(), undefined);
+ });
+
it("can clear tabId", () => {
setLastTabId("tab123");
setLastTabId(undefined);
diff --git a/plugin/session.ts b/plugin/session.ts
index c2b3e79e..d0d0970f 100644
--- a/plugin/session.ts
+++ b/plugin/session.ts
@@ -1,15 +1,39 @@
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
-import type { PluginConfig } from "./types.js";
+import type { AgentSessionState, PluginConfig, PluginRuntimeContext } from "./types.js";
import { pinchtabFetch } from "./client.js";
const instanceReadyRetryDelayMs = 500;
const instanceReadyMaxWaitMs = 12000;
-let lastTabId: string | undefined;
+const agentSessions = new Map<string, AgentSessionState>();
let discoveredConfig: { baseUrl?: string; token?: string } | null | undefined;
+function resolveSessionStateKey(context?: PluginRuntimeContext): string {
+ return context?.agentId || context?.sessionId || "global";
+}
+
+export function rememberRuntimeContext(context?: PluginRuntimeContext): AgentSessionState {
+ const key = resolveSessionStateKey(context);
+ const existing = agentSessions.get(key);
+ const next: AgentSessionState = {
+ key,
+ agentId: context?.agentId ?? existing?.agentId,
+ agentName: context?.agentName ?? existing?.agentName,
+ sessionId: context?.sessionId ?? existing?.sessionId,
+ sessionKey: context?.sessionKey ?? existing?.sessionKey,
+ lastTabId: existing?.lastTabId,
+ updatedAt: Date.now(),
+ };
+ agentSessions.set(key, next);
+ return next;
+}
+
+export function getAgentSessionState(context?: PluginRuntimeContext): AgentSessionState | undefined {
+ return agentSessions.get(resolveSessionStateKey(context));
+}
+
export function normalizeDiscoveredHost(bind: string): string {
if (bind === "0.0.0.0") return "127.0.0.1";
if (bind === "::") return "::1";
@@ -33,15 +57,23 @@ export function isLocalHost(baseUrl: string): boolean {
}
}
-export function getLastTabId(): string | undefined {
- return lastTabId;
+export function getLastTabId(context?: PluginRuntimeContext): string | undefined {
+ return getAgentSessionState(context)?.lastTabId;
}
-export function setLastTabId(tabId: string | undefined): void {
- lastTabId = tabId;
+export function setLastTabId(tabId: string | undefined, context?: PluginRuntimeContext): void {
+ const state = rememberRuntimeContext(context);
+ state.lastTabId = tabId;
+ state.updatedAt = Date.now();
+ agentSessions.set(state.key, state);
}
-export function resolveProfile(cfg: PluginConfig, profile?: string): { instanceId?: string; attach?: boolean } {
+export function resolveProfile(
+ cfg: PluginConfig,
+ profile?: string,
+ context?: PluginRuntimeContext,
+): { instanceId?: string; attach?: boolean } {
+ rememberRuntimeContext(context);
const name = profile || cfg.defaultProfile || "openclaw";
if (cfg.profiles?.[name]) {
return cfg.profiles[name];
@@ -95,11 +127,12 @@ export async function resolveEffectiveConfig(cfg: PluginConfig): Promise<PluginC
};
}
-export async function getEnhancedHealth(cfg: PluginConfig): Promise<any> {
+export async function getEnhancedHealth(cfg: PluginConfig, context?: PluginRuntimeContext): Promise<any> {
const effectiveCfg = await resolveEffectiveConfig(cfg);
const base = effectiveCfg.baseUrl || "http://localhost:9867";
- const health = await pinchtabFetch(effectiveCfg, "/health");
+ const health = await pinchtabFetch(effectiveCfg, "/health", {}, context);
const serverOk = !health?.error;
+ const agentSession = getAgentSessionState(context);
const result: any = {
server: serverOk ? "ok" : "unreachable",
@@ -113,6 +146,16 @@ export async function getEnhancedHealth(cfg: PluginConfig): Promise<any> {
},
};
+ if (agentSession) {
+ result.agentSession = {
+ agentId: agentSession.agentId,
+ agentName: agentSession.agentName,
+ sessionId: agentSession.sessionId,
+ sessionKey: agentSession.sessionKey,
+ lastTabId: agentSession.lastTabId,
+ };
+ }
+
if (serverOk) {
result.serverHealth = health;
if (health?.version) result.serverVersion = health.version;
@@ -131,10 +174,13 @@ export async function getEnhancedHealth(cfg: PluginConfig): Promise<any> {
return result;
}
-export async function ensureServerRunning(cfg: PluginConfig): Promise<{ ok: boolean; error?: string; autoStarted?: boolean }> {
+export async function ensureServerRunning(
+ cfg: PluginConfig,
+ context?: PluginRuntimeContext,
+): Promise<{ ok: boolean; error?: string; autoStarted?: boolean }> {
const effectiveCfg = await resolveEffectiveConfig(cfg);
const base = effectiveCfg.baseUrl || "http://localhost:9867";
- const healthCheck = await pinchtabFetch(effectiveCfg, "/health");
+ const healthCheck = await pinchtabFetch(effectiveCfg, "/health", {}, context);
if (!healthCheck?.error) {
return { ok: true };
}
@@ -145,15 +191,19 @@ export async function ensureServerRunning(cfg: PluginConfig): Promise<{ ok: bool
return { ok: false, error: `${healthCheck.error}${hint}` };
}
-export async function waitForInstanceReady(cfg: PluginConfig, instanceId?: string): Promise<{ ok: boolean; error?: string }> {
+export async function waitForInstanceReady(
+ cfg: PluginConfig,
+ instanceId?: string,
+ context?: PluginRuntimeContext,
+): 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");
+ const health = await pinchtabFetch(effectiveCfg, "/health", {}, context);
if (!health?.error) {
- const instances = await pinchtabFetch(effectiveCfg, "/instances");
+ const instances = await pinchtabFetch(effectiveCfg, "/instances", {}, context);
const list = Array.isArray(instances?.value)
? instances.value
: Array.isArray(instances)
@@ -177,7 +227,7 @@ export async function waitForInstanceReady(cfg: PluginConfig, instanceId?: strin
continue;
}
- const tabs = await pinchtabFetch(effectiveCfg, "/tabs");
+ const tabs = await pinchtabFetch(effectiveCfg, "/tabs", {}, context);
if (!tabs?.error) {
return { ok: true };
}
diff --git a/plugin/tools/browser.ts b/plugin/tools/browser.ts
index 84ff7310..8e83d35b 100644
--- a/plugin/tools/browser.ts
+++ b/plugin/tools/browser.ts
@@ -1,7 +1,7 @@
-import type { PluginConfig } from "../types.js";
+import type { PluginConfig, PluginRuntimeContext } from "../types.js";
import { pinchtabFetch, textResult, imageResult, resourceResult } from "../client.js";
import { checkNavigationPolicy, enforcePolicyOrReturn } from "../policy.js";
-import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, resolveProfile, getLastTabId, setLastTabId } from "../session.js";
+import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, resolveProfile, getLastTabId, rememberRuntimeContext, setLastTabId } from "../session.js";
export const browserToolSchema = {
type: "object",
@@ -43,27 +43,28 @@ Actions:
Profiles: "openclaw" (default isolated), "user" (attach to existing session)`;
-export async function executeBrowserAction(cfg: PluginConfig, params: any): Promise<any> {
+export async function executeBrowserAction(cfg: PluginConfig, params: any, context?: PluginRuntimeContext): Promise<any> {
+ rememberRuntimeContext(context);
const { action, profile } = params;
// Resolve profile to instance
- const profileConfig = resolveProfile(cfg, profile);
+ const profileConfig = resolveProfile(cfg, profile, context);
// Auto-start server if needed
if (action !== "status") {
- const serverCheck = await ensureServerRunning(cfg);
+ const serverCheck = await ensureServerRunning(cfg, context);
if (!serverCheck.ok) {
return textResult({ error: serverCheck.error });
}
- const readyCheck = await waitForInstanceReady(cfg, profileConfig.instanceId);
+ const readyCheck = await waitForInstanceReady(cfg, profileConfig.instanceId, context);
if (!readyCheck.ok) {
return textResult({ error: readyCheck.error });
}
}
// Session tab persistence
- if (cfg.persistSessionTabs !== false && !params.tabId && getLastTabId()) {
- params.tabId = getLastTabId();
+ if (cfg.persistSessionTabs !== false && !params.tabId && getLastTabId(context)) {
+ params.tabId = getLastTabId(context);
}
// --- navigate ---
@@ -75,17 +76,17 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Prom
if (params.newTab) {
const body: any = { action: "new", url: params.url };
if (profileConfig.instanceId) body.instanceId = profileConfig.instanceId;
- result = await pinchtabFetch(cfg, "/tab", { body });
+ result = await pinchtabFetch(cfg, "/tab", { body }, context);
} 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 });
+ result = await pinchtabFetch(cfg, `/tabs/${encodeURIComponent(params.tabId)}/navigate`, { body }, context);
} else {
const body: any = { url: params.url };
if (profileConfig.instanceId) body.instanceId = profileConfig.instanceId;
- result = await pinchtabFetch(cfg, "/navigate", { body });
+ result = await pinchtabFetch(cfg, "/navigate", { body }, context);
}
- if (result?.tabId) setLastTabId(result.tabId);
+ if (result?.tabId) setLastTabId(result.tabId, context);
return textResult(result);
}
@@ -97,7 +98,7 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Prom
query.set("format", params.format || cfg.defaultSnapshotFormat || "compact");
if (params.selector) query.set("selector", params.selector);
if (params.maxTokens) query.set("maxTokens", String(params.maxTokens));
- return textResult(await pinchtabFetch(cfg, `/snapshot?${query.toString()}`));
+ return textResult(await pinchtabFetch(cfg, `/snapshot?${query.toString()}`, {}, context));
}
// --- screenshot ---
@@ -108,7 +109,7 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Prom
if (fmt === "png") query.set("format", "png");
query.set("quality", String(params.quality || cfg.screenshotQuality || 80));
try {
- const res = await pinchtabFetch(cfg, `/screenshot?${query.toString()}`, { rawResponse: true });
+ const res = await pinchtabFetch(cfg, `/screenshot?${query.toString()}`, { rawResponse: true }, context);
if (res instanceof Response) {
if (!res.ok) return textResult({ error: `Screenshot failed: ${res.status}` });
const buf = await res.arrayBuffer();
@@ -129,27 +130,27 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Prom
if (params.key) body.key = params.key;
if (params.value) body.value = params.value;
if (params.tabId) body.tabId = params.tabId;
- return textResult(await pinchtabFetch(cfg, "/action", { body }));
+ return textResult(await pinchtabFetch(cfg, "/action", { body }, context));
}
// --- tabs ---
if (action === "tabs") {
const tabAction = params.tabAction || "list";
if (tabAction === "list") {
- return textResult(await pinchtabFetch(cfg, "/tabs"));
+ return textResult(await pinchtabFetch(cfg, "/tabs", {}, context));
}
if (tabAction === "close") {
const body: any = {};
if (params.tabId) body.tabId = params.tabId;
- const result = await pinchtabFetch(cfg, "/close", { body });
- if (params.tabId && params.tabId === getLastTabId()) setLastTabId(undefined);
+ const result = await pinchtabFetch(cfg, "/close", { body }, context);
+ if (params.tabId && params.tabId === getLastTabId(context)) setLastTabId(undefined, context);
return textResult(result);
}
const body: any = { action: tabAction };
if (params.url) body.url = params.url;
if (params.tabId) body.tabId = params.tabId;
- const result = await pinchtabFetch(cfg, "/tab", { body });
- if (tabAction === "new" && result?.tabId) setLastTabId(result.tabId);
+ const result = await pinchtabFetch(cfg, "/tab", { body }, context);
+ if (tabAction === "new" && result?.tabId) setLastTabId(result.tabId, context);
return textResult(result);
}
@@ -161,7 +162,7 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Prom
if (params.landscape) query.set("landscape", "true");
if (params.scale) query.set("scale", String(params.scale));
try {
- const res = await pinchtabFetch(cfg, `/pdf?${query.toString()}`, { rawResponse: true });
+ const res = await pinchtabFetch(cfg, `/pdf?${query.toString()}`, { rawResponse: true }, context);
if (res instanceof Response) {
if (!res.ok) return textResult({ error: `PDF failed: ${res.status}` });
const buf = await res.arrayBuffer();
@@ -176,7 +177,7 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Prom
// --- status ---
if (action === "status") {
- return textResult(await getEnhancedHealth(cfg));
+ return textResult(await getEnhancedHealth(cfg, context));
}
return textResult({ error: `Unknown browser action: ${action}` });
diff --git a/plugin/tools/pinchtab.ts b/plugin/tools/pinchtab.ts
index bde90c95..1116315b 100644
--- a/plugin/tools/pinchtab.ts
+++ b/plugin/tools/pinchtab.ts
@@ -1,7 +1,7 @@
-import type { PluginConfig } from "../types.js";
+import type { PluginConfig, PluginRuntimeContext } 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, waitForInstanceReady, getEnhancedHealth, getLastTabId, setLastTabId } from "../session.js";
+import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, getLastTabId, rememberRuntimeContext, setLastTabId } from "../session.js";
export const pinchtabToolSchema = {
type: "object",
@@ -90,25 +90,26 @@ export const pinchtabToolDescription = `Browser control via Pinchtab. Actions:
Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=interactive&format=compact for interactions (~3,600), diff=true on subsequent snapshots.`;
-export async function executePinchtabAction(cfg: PluginConfig, params: any): Promise<any> {
+export async function executePinchtabAction(cfg: PluginConfig, params: any, context?: PluginRuntimeContext): Promise<any> {
+ rememberRuntimeContext(context);
const normalized = normalizeActionParams(params);
const { action } = normalized;
// Auto-start server if needed
if (action !== "health") {
- const serverCheck = await ensureServerRunning(cfg);
+ const serverCheck = await ensureServerRunning(cfg, context);
if (!serverCheck.ok) {
return textResult({ error: serverCheck.error });
}
- const readyCheck = await waitForInstanceReady(cfg);
+ const readyCheck = await waitForInstanceReady(cfg, undefined, context);
if (!readyCheck.ok) {
return textResult({ error: readyCheck.error });
}
}
// Session tab persistence
- if (cfg.persistSessionTabs !== false && !normalized.tabId && getLastTabId()) {
- normalized.tabId = getLastTabId();
+ if (cfg.persistSessionTabs !== false && !normalized.tabId && getLastTabId(context)) {
+ normalized.tabId = getLastTabId(context);
}
// Policy: block evaluate if not allowed
@@ -127,19 +128,19 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
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 });
+ result = await pinchtabFetch(cfg, "/tab", { body }, context);
} 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 });
+ result = await pinchtabFetch(cfg, `/tabs/${encodeURIComponent(normalized.tabId)}/navigate`, { body }, context);
} 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 });
+ result = await pinchtabFetch(cfg, "/navigate", { body }, context);
}
- if (result?.tabId) setLastTabId(result.tabId);
+ if (result?.tabId) setLastTabId(result.tabId, context);
return textResult(result);
}
@@ -155,7 +156,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (normalized.maxTokens) query.set("maxTokens", String(normalized.maxTokens));
if (normalized.depth) query.set("depth", String(normalized.depth));
if (normalized.diff) query.set("diff", "true");
- return textResult(await pinchtabFetch(cfg, `/snapshot?${query.toString()}`));
+ return textResult(await pinchtabFetch(cfg, `/snapshot?${query.toString()}`, {}, context));
}
// --- element actions ---
@@ -169,7 +170,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (normalized[k] !== undefined) body[k] = normalized[k];
}
- let result = await pinchtabFetch(cfg, "/action", { body });
+ let result = await pinchtabFetch(cfg, "/action", { body }, context);
// Stale ref recovery
if (body.ref && looksLikeStaleRef(result)) {
@@ -177,8 +178,8 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
q.set("filter", "interactive");
q.set("format", "compact");
if (body.tabId) q.set("tabId", body.tabId);
- await pinchtabFetch(cfg, `/snapshot?${q.toString()}`);
- const retried = await pinchtabFetch(cfg, "/action", { body });
+ await pinchtabFetch(cfg, `/snapshot?${q.toString()}`, {}, context);
+ const retried = await pinchtabFetch(cfg, "/action", { body }, context);
result = retried?.error
? { ...retried, warning: "Action retried once after snapshot refresh but still failed." }
: { ...retried, warning: "Action succeeded after automatic snapshot refresh (stale ref recovery)." };
@@ -191,7 +192,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
typeBody.text = typeBody.value;
}
delete typeBody.value;
- const typed = await pinchtabFetch(cfg, "/action", { body: typeBody });
+ const typed = await pinchtabFetch(cfg, "/action", { body: typeBody }, context);
if (!typed?.error) {
result = { ...typed, warning: "Fill failed; type fallback succeeded." };
}
@@ -205,7 +206,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
const query = new URLSearchParams();
if (normalized.tabId) query.set("tabId", normalized.tabId);
if (normalized.mode) query.set("mode", normalized.mode);
- return textResult(await pinchtabFetch(cfg, `/text?${query.toString()}`));
+ return textResult(await pinchtabFetch(cfg, `/text?${query.toString()}`, {}, context));
}
// --- wait ---
@@ -214,7 +215,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
for (const k of ["selector", "text", "url", "load", "fn", "ms", "tabId", "timeout", "state"]) {
if (normalized[k] !== undefined) body[k] = normalized[k];
}
- return textResult(await pinchtabFetch(cfg, "/wait", { body }));
+ return textResult(await pinchtabFetch(cfg, "/wait", { body }, context));
}
// --- handoff ---
@@ -234,7 +235,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
for (const k of ["selector", "text", "url", "load", "fn", "ms", "tabId", "timeout", "state"]) {
if (normalized[k] !== undefined) waitBody[k] = normalized[k];
}
- const waitResult = await pinchtabFetch(cfg, "/wait", { body: waitBody });
+ const waitResult = await pinchtabFetch(cfg, "/wait", { body: waitBody }, context);
return textResult({ ...handoffMeta, resumed: !waitResult?.error, waitResult });
}
@@ -242,31 +243,31 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (action === "tabs") {
const tabAction = normalized.tabAction || "list";
if (tabAction === "list") {
- const listed = await pinchtabFetch(cfg, "/tabs");
+ const listed = await pinchtabFetch(cfg, "/tabs", {}, context);
const tabs = Array.isArray(listed?.tabs) ? listed.tabs : Array.isArray(listed) ? listed : [];
if (tabs.length > 0) return textResult(listed);
- const instances = await pinchtabFetch(cfg, "/instances");
+ const instances = await pinchtabFetch(cfg, "/instances", {}, context);
const list = Array.isArray(instances?.value) ? instances.value : Array.isArray(instances) ? instances : [];
const running = list.find((i: any) => i?.status === "running" && i?.id);
if (!running) {
return textResult({ ...listed, warning: "No tabs returned and no running instance found." });
}
- const instanceTabs = await pinchtabFetch(cfg, `/instances/${running.id}/tabs`);
+ const instanceTabs = await pinchtabFetch(cfg, `/instances/${running.id}/tabs`, {}, context);
return textResult({ source: "instance-fallback", instanceId: running.id, tabs: instanceTabs?.tabs ?? instanceTabs });
}
if (tabAction === "close") {
const body: any = {};
if (normalized.tabId) body.tabId = normalized.tabId;
- const result = await pinchtabFetch(cfg, "/close", { body });
- if (normalized.tabId && normalized.tabId === getLastTabId()) setLastTabId(undefined);
+ const result = await pinchtabFetch(cfg, "/close", { body }, context);
+ if (normalized.tabId && normalized.tabId === getLastTabId(context)) setLastTabId(undefined, context);
return textResult(result);
}
const body: any = { action: tabAction };
if (normalized.url) body.url = normalized.url;
if (normalized.tabId) body.tabId = normalized.tabId;
- const result = await pinchtabFetch(cfg, "/tab", { body });
- if (tabAction === "new" && result?.tabId) setLastTabId(result.tabId);
+ const result = await pinchtabFetch(cfg, "/tab", { body }, context);
+ if (tabAction === "new" && result?.tabId) setLastTabId(result.tabId, context);
return textResult(result);
}
@@ -279,7 +280,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (format === "png") query.set("format", "png");
query.set("quality", String(quality));
try {
- const res = await pinchtabFetch(cfg, `/screenshot?${query.toString()}`, { rawResponse: true });
+ const res = await pinchtabFetch(cfg, `/screenshot?${query.toString()}`, { rawResponse: true }, context);
if (res instanceof Response) {
if (!res.ok) return textResult({ error: `Screenshot failed: ${res.status} ${await res.text()}` });
const buf = await res.arrayBuffer();
@@ -296,7 +297,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (action === "evaluate") {
const body: any = { expression: normalized.expression };
if (normalized.tabId) body.tabId = normalized.tabId;
- return textResult(await pinchtabFetch(cfg, "/evaluate", { body }));
+ return textResult(await pinchtabFetch(cfg, "/evaluate", { body }, context));
}
// --- pdf ---
@@ -307,7 +308,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (normalized.landscape) query.set("landscape", "true");
if (normalized.scale) query.set("scale", String(normalized.scale));
try {
- const res = await pinchtabFetch(cfg, `/pdf?${query.toString()}`, { rawResponse: true });
+ const res = await pinchtabFetch(cfg, `/pdf?${query.toString()}`, { rawResponse: true }, context);
if (res instanceof Response) {
if (!res.ok) return textResult({ error: `PDF failed: ${res.status} ${await res.text()}` });
const buf = await res.arrayBuffer();
@@ -327,18 +328,18 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (networkAction === "clear") {
const query = new URLSearchParams();
if (normalized.tabId) query.set("tabId", normalized.tabId);
- return textResult(await pinchtabFetch(cfg, `/network/clear?${query.toString()}`, { method: "POST" }));
+ return textResult(await pinchtabFetch(cfg, `/network/clear?${query.toString()}`, { method: "POST" }, context));
}
if (networkAction === "get" && normalized.requestId) {
- return textResult(await pinchtabFetch(cfg, `/network/${normalized.requestId}`));
+ return textResult(await pinchtabFetch(cfg, `/network/${normalized.requestId}`, {}, context));
}
if (networkAction === "export") {
const query = new URLSearchParams();
if (normalized.tabId) query.set("tabId", normalized.tabId);
if (normalized.exportFormat === "json") query.set("format", "json");
- const result = await pinchtabFetch(cfg, `/network/export?${query.toString()}`);
+ const result = await pinchtabFetch(cfg, `/network/export?${query.toString()}`, {}, context);
if (normalized.exportFormat === "har" || !normalized.exportFormat) {
return resourceResult("har://export", "application/json", Buffer.from(JSON.stringify(result)).toString("base64"));
}
@@ -362,7 +363,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
return textResult(await pinchtabFetch(cfg, `/tabs/${encodeURIComponent(normalized.tabId)}/network/route`, {
method: "POST",
body: payload,
- }));
+ }, context));
}
if (networkAction === "unroute") {
@@ -373,7 +374,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (normalized.pattern) query.set("pattern", normalized.pattern);
const qs = query.toString();
const path = `/tabs/${encodeURIComponent(normalized.tabId)}/network/route${qs ? `?${qs}` : ""}`;
- return textResult(await pinchtabFetch(cfg, path, { method: "DELETE" }));
+ return textResult(await pinchtabFetch(cfg, path, { method: "DELETE" }, context));
}
// list
@@ -383,7 +384,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (normalized.status) query.set("status", normalized.status);
if (normalized.resourceType) query.set("type", normalized.resourceType);
if (normalized.limit) query.set("limit", String(normalized.limit));
- return textResult(await pinchtabFetch(cfg, `/network?${query.toString()}`));
+ return textResult(await pinchtabFetch(cfg, `/network?${query.toString()}`, {}, context));
}
// --- download ---
@@ -397,11 +398,11 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (normalized.savePath) {
query.set("output", "file");
query.set("path", normalized.savePath);
- return textResult(await pinchtabFetch(cfg, `/download?${query.toString()}`));
+ return textResult(await pinchtabFetch(cfg, `/download?${query.toString()}`, {}, context));
}
query.set("raw", "true");
try {
- const res = await pinchtabFetch(cfg, `/download?${query.toString()}`, { rawResponse: true });
+ const res = await pinchtabFetch(cfg, `/download?${query.toString()}`, { rawResponse: true }, context);
if (res instanceof Response) {
if (!res.ok) return textResult({ error: `download failed: ${res.status} ${await res.text()}` });
const buf = await res.arrayBuffer();
@@ -425,12 +426,12 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Pro
if (normalized.selector) body.selector = normalized.selector;
if (normalized.files) body.files = normalized.files;
if (normalized.paths) body.paths = normalized.paths;
- return textResult(await pinchtabFetch(cfg, "/upload", { body }));
+ return textResult(await pinchtabFetch(cfg, "/upload", { body }, context));
}
// --- health ---
if (action === "health") {
- return textResult(await getEnhancedHealth(cfg));
+ return textResult(await getEnhancedHealth(cfg, context));
}
return textResult({ error: `Unknown action: ${action}` });
diff --git a/plugin/types.ts b/plugin/types.ts
index 7e3ac00c..70e334dc 100644
--- a/plugin/types.ts
+++ b/plugin/types.ts
@@ -1,4 +1,4 @@
-import type { AnyAgentTool, OpenClawPluginApi } from "openclaw/plugin-sdk";
+import type { AnyAgentTool, OpenClawPluginApi, OpenClawPluginToolContext } from "openclaw/plugin-sdk";
export interface PluginConfig {
baseUrl?: string;
@@ -21,8 +21,22 @@ export interface PluginConfig {
profiles?: Record<string, { instanceId?: string; attach?: boolean }>;
}
+export interface PluginRuntimeContext {
+ agentId?: string;
+ agentName?: string;
+ sessionId?: string;
+ sessionKey?: string;
+}
+
+export interface AgentSessionState extends PluginRuntimeContext {
+ key: string;
+ lastTabId?: string;
+ updatedAt?: number;
+}
+
export type PluginApi = OpenClawPluginApi;
export type PluginTool = AnyAgentTool;
+export type PluginToolContext = OpenClawPluginToolContext;
export interface ToolResult {
content: Array<