openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
408 lines (407 loc) • 21.9 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { n as stringEnum, t as optionalStringEnum } from "./string-enum-DXKqjXG0.mjs";
import { a as optionalNonNegativeIntegerSchema, i as optionalFiniteNumberSchema, o as optionalPositiveIntegerSchema } from "./typebox-BwU4K8-3.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import { i as resolveBrowserConfig, s as resolveProfile } from "./config-ccOD-Wrr.mjs";
import { n as BROWSER_MODEL_ACT_KINDS, t as BROWSER_ACT_KIND_FACTS } from "./act-kinds-BgVHTlGH.mjs";
import { n as ACT_MAX_VIEWPORT_DIMENSION } from "./act-policy-fWdzY2YP.mjs";
import "./channel-actions-DxuDuzvg.mjs";
import { t as getBrowserProfileCapabilities } from "./profile-capabilities-C9i07NhJ.mjs";
import { Type } from "typebox";
//#region extensions/browser/src/browser-node-commands.ts
const BROWSER_PROXY_COMMAND = "browser.proxy";
const BROWSER_PROXY_UPLOAD_COMMAND = "browser.proxy.upload.v1";
function browserProxyUploadUnavailableMessage(e) {
return e?.includes("browser.proxy.upload.v1") ? "browser node remote upload transfer is pending approval; approve the node's pending command update before retrying" : "browser node does not support remote upload transfer; update the node or approve its pending command update before retrying";
}
//#endregion
//#region extensions/browser/src/browser-tool-binding.ts
/** Validate the plugin-owned run binding before any browser route is resolved. */
function parseBrowserTabToolBinding(e) {
if (!e || typeof e !== "object" || Array.isArray(e)) throw new Error("invalid browser run binding: browser tool binding must be an object");
const t = e;
const n = t.target === "host" || t.target === "node" ? t.target : void 0;
const r = normalizeOptionalString(t.node);
const i = normalizeOptionalString(t.profile);
const a = normalizeOptionalString(t.targetId);
if (t.kind !== "tab") throw new Error("invalid browser run binding: browser tool binding kind must be \"tab\"");
if (!Number.isSafeInteger(t.tabId) || Number(t.tabId) < 0) throw new Error("invalid browser run binding: browser tool binding tabId must be a non-negative integer");
if (!n || !i || !a || n === "node" && !r) throw new Error("invalid browser run binding: browser tool binding requires target, profile, and targetId");
if (n === "host" && r) throw new Error("invalid browser run binding: browser host binding cannot include node");
return {
kind: "tab",
tabId: Number(t.tabId),
target: n,
...r ? { node: r } : {},
profile: i,
targetId: a
};
}
function bindTargetId(e, t) {
const n = normalizeOptionalString(e.targetId);
if (n && n !== t) throw new Error("browser action cannot override its run-bound tab target");
const r = Array.isArray(e.actions) ? e.actions.map((e) => e && typeof e === "object" && !Array.isArray(e) ? bindTargetId(e, t) : e) : e.actions;
return {
...e,
targetId: t,
...r ? { actions: r } : {}
};
}
/** Pin model-supplied browser arguments to the trusted tab route for this run. */
function applyBrowserTabToolBinding(e, t) {
const n = {
target: normalizeOptionalString(e.target),
node: normalizeOptionalString(e.node),
profile: normalizeOptionalString(e.profile)
};
for (const e of [
"target",
"node",
"profile"
]) if (n[e] && n[e] !== t[e]) throw new Error(`browser action cannot override its run-bound ${e}`);
const r = bindTargetId(e, t.targetId);
const i = r.request && typeof r.request === "object" && !Array.isArray(r.request) ? bindTargetId(r.request, t.targetId) : r.request;
return {
...r,
target: t.target,
...t.node ? { node: t.node } : {},
profile: t.profile,
...i ? { request: i } : {}
};
}
//#endregion
//#region extensions/browser/src/browser-tool-action-facts.ts
const definitions = {
doctor: { lifecycle: true },
status: { lifecycle: true },
start: { lifecycle: true },
stop: { lifecycle: true },
profiles: { lifecycle: true },
importprofile: { lifecycle: true },
tabs: { tabBoundOrder: 14 },
open: {},
focus: { tabBoundOrder: 9 },
close: { tabBoundOrder: 1 },
snapshot: { tabBoundOrder: 13 },
screenshot: {
tabBoundOrder: 12,
capability: "supportsScreenshots",
path: true
},
navigate: { tabBoundOrder: 10 },
console: {
tabBoundOrder: 2,
capability: "supportsConsole"
},
requests: {
tabBoundOrder: 3,
capability: "supportsRequests"
},
errors: {
tabBoundOrder: 4,
capability: "supportsErrors"
},
text: {
tabBoundOrder: 5,
capability: "supportsPageText"
},
judge: {
tabBoundOrder: 17,
capability: "supportsPageText"
},
emulate: {
tabBoundOrder: 6,
capability: "supportsEmulation"
},
pdf: {
tabBoundOrder: 11,
capability: "supportsPdf",
path: true
},
download: {
tabBoundOrder: 8,
capability: "supportsDownloads",
path: true
},
waitfordownload: {
tabBoundOrder: 16,
capability: "supportsDownloads",
path: true
},
upload: {
tabBoundOrder: 15,
capability: "supportsUploads"
},
dialog: {
tabBoundOrder: 7,
capability: "supportsDialogs"
},
act: { tabBoundOrder: 0 }
};
const BROWSER_TOOL_ACTION_FACTS = definitions;
const BROWSER_TOOL_ACTIONS = Object.keys(definitions);
const BROWSER_TAB_BOUND_ACTIONS = BROWSER_TOOL_ACTIONS.filter((e) => BROWSER_TOOL_ACTION_FACTS[e].tabBoundOrder !== void 0).toSorted((e, t) => BROWSER_TOOL_ACTION_FACTS[e].tabBoundOrder - BROWSER_TOOL_ACTION_FACTS[t].tabBoundOrder);
function isBrowserLifecycleAction(e) {
return Object.hasOwn(definitions, e) && BROWSER_TOOL_ACTION_FACTS[e].lifecycle === true;
}
//#endregion
//#region extensions/browser/src/browser-tool.schema.ts
const BROWSER_TARGETS = [
"sandbox",
"host",
"node"
];
const BROWSER_SNAPSHOT_FORMATS = ["aria", "ai"];
const BROWSER_SNAPSHOT_MODES = ["efficient"];
const BROWSER_SNAPSHOT_REFS = ["role", "aria"];
const BROWSER_IMAGE_TYPES = ["png", "jpeg"];
const TAB_REFERENCE_DESCRIPTION = "Prefer suggestedTargetId/tabId/label; raw CDP targetId.";
function resolveBrowserToolCapabilities(e) {
const t = e?.evaluateEnabled !== false;
const n = e?.profileCapabilities;
return {
actions: (e?.tabBound ? BROWSER_TAB_BOUND_ACTIONS : BROWSER_TOOL_ACTIONS).filter((t) => {
if (t === "judge" && e?.canJudge !== true) return false;
const r = BROWSER_TOOL_ACTION_FACTS[t].capability;
return !r || n?.[r] !== false;
}),
actKinds: BROWSER_MODEL_ACT_KINDS.filter((e) => {
const r = BROWSER_ACT_KIND_FACTS[e].capability;
return (t || e !== "evaluate") && (!r || n?.[r] !== false);
}),
tabBound: e?.tabBound === true,
supportsNativeSnapshots: n?.supportsNativeSnapshots !== false
};
}
function createBrowserActProperties(e) {
const t = e.actKinds.includes("batch");
return {
targetId: Type.Optional(Type.String({ description: TAB_REFERENCE_DESCRIPTION })),
ref: Type.Optional(Type.String({ description: "snapshot ref." })),
actions: Type.Optional(Type.Array(Type.Object({}, { additionalProperties: true }), t ? { description: "batch actions." } : {})),
stopOnError: Type.Optional(Type.Boolean(t ? { description: "Stop on error; default true." } : {})),
doubleClick: Type.Optional(Type.Boolean({ description: "Double-click/clickCoords." })),
button: Type.Optional(Type.String()),
modifiers: Type.Optional(Type.Array(Type.String())),
...e.actKinds.includes("clickCoords") ? {
x: optionalFiniteNumberSchema(),
y: optionalFiniteNumberSchema()
} : {},
text: Type.Optional(Type.String()),
submit: Type.Optional(Type.Boolean()),
slowly: Type.Optional(Type.Boolean()),
key: Type.Optional(Type.String({ description: "Escape, Enter, Control+Shift+T; aliases Esc, Return, Del, Ctrl, Cmd." })),
delayMs: optionalNonNegativeIntegerSchema(),
...e.actKinds.includes("drag") ? {
startRef: Type.Optional(Type.String()),
endRef: Type.Optional(Type.String())
} : {},
values: Type.Optional(Type.Array(Type.String())),
fields: Type.Optional(Type.Array(Type.Object({}, { additionalProperties: true }))),
...e.actKinds.includes("resize") ? {
width: optionalPositiveIntegerSchema({ maximum: ACT_MAX_VIEWPORT_DIMENSION }),
height: optionalPositiveIntegerSchema({ maximum: ACT_MAX_VIEWPORT_DIMENSION })
} : {},
timeMs: optionalNonNegativeIntegerSchema(),
...e.supportsNativeSnapshots !== false ? { selector: Type.Optional(Type.String()) } : {},
url: Type.Optional(Type.String()),
loadState: Type.Optional(Type.String()),
textGone: Type.Optional(Type.String()),
timeoutMs: optionalPositiveIntegerSchema(),
...e.actKinds.includes("evaluate") ? { fn: Type.Optional(Type.String()) } : {}
};
}
const BROWSER_ACT_REQUEST_KEYS = ["kind", ...Object.keys(createBrowserActProperties(resolveBrowserToolCapabilities()))];
function createBrowserToolSchema(e) {
const t = createBrowserActProperties(e);
const n = e.actKinds.includes("batch") ? "batch uses actions." : "Act kind.";
const r = Type.Object({
kind: stringEnum(e.actKinds, { description: n }),
...t
}, { description: "act" });
return Type.Object({
action: stringEnum(e.actions),
target: optionalStringEnum(BROWSER_TARGETS),
...!e.tabBound ? { dashboard: Type.Optional(Type.String({
pattern: "^[a-z0-9][a-z0-9._-]{0,63}$",
description: "browser:dashboard widget name."
})) } : {},
node: Type.Optional(Type.String()),
profile: Type.Optional(Type.String({ description: e.tabBound ? "Run-bound browser profile." : "default if omitted." })),
browser: Type.Optional(Type.String()),
systemProfile: Type.Optional(Type.String()),
into: Type.Optional(Type.String()),
domains: Type.Optional(Type.Array(Type.String())),
targetUrl: Type.Optional(Type.String()),
label: Type.Optional(Type.String()),
limit: optionalPositiveIntegerSchema(),
maxChars: optionalNonNegativeIntegerSchema(),
mode: optionalStringEnum(BROWSER_SNAPSHOT_MODES),
snapshotFormat: optionalStringEnum(e.supportsNativeSnapshots === false ? ["ai"] : BROWSER_SNAPSHOT_FORMATS),
refs: optionalStringEnum(e.supportsNativeSnapshots === false ? ["aria"] : BROWSER_SNAPSHOT_REFS),
interactive: Type.Optional(Type.Boolean()),
compact: Type.Optional(Type.Boolean()),
depth: optionalNonNegativeIntegerSchema(),
...e.supportsNativeSnapshots !== false ? { frame: Type.Optional(Type.String()) } : {},
...e.actions.includes("screenshot") ? {
labels: Type.Optional(Type.Boolean({ description: "Label snapshot/screenshot." })),
fullPage: Type.Optional(Type.Boolean()),
element: Type.Optional(Type.String()),
type: optionalStringEnum(BROWSER_IMAGE_TYPES)
} : {},
urls: Type.Optional(Type.Boolean()),
...e.actions.some((e) => BROWSER_TOOL_ACTION_FACTS[e].path) ? { path: Type.Optional(Type.String()) } : {},
level: Type.Optional(Type.String()),
filter: Type.Optional(Type.String()),
clear: Type.Optional(Type.Boolean()),
query: Type.Optional(Type.String()),
...e.actions.includes("emulate") ? {
device: Type.Optional(Type.String()),
colorScheme: optionalStringEnum([
"dark",
"light",
"no-preference",
"none"
]),
timezoneId: Type.Optional(Type.String()),
locale: Type.Optional(Type.String())
} : {},
...e.actions.includes("upload") ? {
paths: Type.Optional(Type.Array(Type.String())),
inputRef: Type.Optional(Type.String())
} : {},
...e.actions.includes("dialog") ? {
dialogId: Type.Optional(Type.String()),
accept: Type.Optional(Type.Boolean()),
promptText: Type.Optional(Type.String())
} : {},
kind: Type.Optional(stringEnum(e.actKinds, { description: n })),
...t,
request: Type.Optional(r)
});
}
const BrowserSnapshotStatsSchema = Type.Object({
lines: Type.Number(),
chars: Type.Number(),
refs: Type.Number(),
interactive: Type.Number()
}, { additionalProperties: false });
const BrowserBatchAbortSchema = Type.Object({
reason: stringEnum(["navigation", "closed"]),
afterAction: Type.Number(),
url: Type.String(),
skipped: Type.Number()
}, { additionalProperties: false });
const BrowserToolOutputSchema = Type.Object({
ok: Type.Optional(Type.Boolean()),
targetId: Type.Optional(Type.String()),
url: Type.Optional(Type.String()),
format: Type.Optional(stringEnum(BROWSER_SNAPSHOT_FORMATS)),
snapshot: Type.Optional(Type.String()),
text: Type.Optional(Type.String({ description: "Bounded browser observation wrapped as untrusted content." })),
refs: Type.Optional(Type.Union([Type.Number(), Type.Record(Type.String(), Type.Unknown())])),
stats: Type.Optional(BrowserSnapshotStatsSchema),
truncated: Type.Optional(Type.Boolean()),
observation: Type.Optional(Type.Object({
chars: Type.Number(),
truncated: Type.Boolean()
})),
judgment: Type.Optional(Type.Object({
status: stringEnum(["ok", "unavailable"]),
reason: Type.Optional(Type.String()),
result: Type.Optional(Type.Object({
model: Type.String(),
answers: Type.Record(Type.String(), Type.Unknown())
}, { additionalProperties: true }))
}, {
additionalProperties: true,
description: "Selected Decision provider outcome; missing/error/null answers remain unknown. Not a page-usability verdict."
})),
newElements: Type.Optional(Type.Number()),
tabs: Type.Optional(Type.Array(Type.Object({
suggestedTargetId: Type.Optional(Type.String()),
tabId: Type.Optional(Type.String()),
webExtensionTabId: Type.Optional(Type.Integer({ minimum: 0 })),
label: Type.Optional(Type.String()),
targetId: Type.Optional(Type.String()),
title: Type.Optional(Type.String()),
url: Type.Optional(Type.String()),
urlUnavailableReason: optionalStringEnum(["navigation_blocked", "navigation_check_failed"]),
type: Type.Optional(Type.String())
}, { additionalProperties: true }))),
tabCount: Type.Optional(Type.Number()),
results: Type.Optional(Type.Array(Type.Object({
ok: Type.Boolean(),
error: Type.Optional(Type.String()),
navigated: Type.Optional(Type.Literal(true)),
url: Type.Optional(Type.String())
}, { additionalProperties: false }))),
aborted: Type.Optional(BrowserBatchAbortSchema),
pageState: Type.Optional(Type.Object({}, {
additionalProperties: true,
description: "Inline snapshot details attached when the action changed the page document."
})),
enabled: Type.Optional(Type.Boolean()),
running: Type.Optional(Type.Boolean()),
profile: Type.Optional(Type.String()),
driver: Type.Optional(Type.String()),
transport: Type.Optional(Type.String()),
pid: Type.Optional(Type.Union([Type.Number(), Type.Null()])),
cdpPort: Type.Optional(Type.Union([Type.Number(), Type.Null()])),
cdpUrl: Type.Optional(Type.Union([Type.String(), Type.Null()]))
}, { additionalProperties: true });
//#endregion
//#region extensions/browser/src/browser-tool-description.ts
/** Lazy registration and execution expose exactly the same configured tool. */
function createBrowserToolDefinition(e, t) {
const n = e?.runToolBinding === void 0 ? void 0 : parseBrowserTabToolBinding(e.runToolBinding);
const r = t();
const i = e?.toolCapabilities ?? (() => {
const t = n?.target === "host" ? resolveProfile(resolveBrowserConfig(r?.browser, r), n.profile) : void 0;
return resolveBrowserToolCapabilities({
canJudge: Boolean(e?.decisions && e.agentId),
tabBound: Boolean(n),
evaluateEnabled: r?.browser?.evaluateEnabled !== false,
...t ? { profileCapabilities: getBrowserProfileCapabilities(t) } : {}
});
})();
const a = r?.gateway?.nodes?.browser;
const o = a?.mode !== "off" && Boolean(a?.node?.trim()) && !e?.sandboxBridgeUrl?.trim() && e?.allowHostControl !== false;
const s = new Set(i.actions);
const c = i.actKinds.includes("evaluate");
return {
binding: n,
capabilities: i,
metadata: {
label: "Browser",
name: "browser",
resultContentSource: "network",
description: [
`Control the browser via OpenClaw's browser control server. Available actions: ${i.actions.join(", ")}.`,
...s.has("profiles") ? ["Browser choice: omit profile to use the configured default (normally the isolated OpenClaw-managed `openclaw` browser).", "When existing logins/cookies matter, use action=profiles to inspect available profiles, then select the appropriate profile by name. Do not assume a profile name."] : [],
s.has("importprofile") ? "Use action=importprofile on macOS to copy cookies from an authorized Chrome-family system profile into a fresh managed profile; this may show a Keychain consent prompt." : void 0,
`For Chrome MCP existing-session profiles, omit timeoutMs on act:type, hover, scrollIntoView, drag, select, and fill; that driver rejects per-call timeout overrides for those actions.${c ? " act:evaluate supports timeoutMs." : ""}`,
!i.tabBound ? o ? "Omit target and node to use the configured browser node. If it is unavailable, report the routing error rather than switching to host. Set target=\"host\" only when you intend to use the Gateway host browser; it bypasses configured node routing." : "Prefer the host browser; auto-route to a connected browser node only when the host has no usable browser capability. Select another location with target=\"node\" or node=<id|name>; configured node pins also take precedence." : void 0,
"When using refs from snapshot (e.g. e12), keep the same tab: prefer passing targetId from the snapshot response into subsequent actions (act/click/type/etc). For tab operations, targetId also accepts tabId handles (t1) and labels from action=tabs.",
"For multi-step browser work, login checks, stale refs, duplicate tabs, or Google Meet flows, use the bundled browser-automation skill when it is available.",
!i.tabBound ? "Only create a Browser dashboard when the user asks for a dashboard. Opening the browser sidebar or side panel does not require a widget. For a requested agent-controllable HTTP(S) dashboard, first call tool dashboard with action=\"widget_put\", pluginKind=\"browser:dashboard\", name=<stable widget name>, props={url}, and size=\"full\". Next call tool browser with action=\"open\", dashboard=<that widget name>, and no targetUrl. Then call tool dashboard with action=\"set_presentation\", presentation=\"expanded\". The dashboard tool owns widget authoring and presentation; the browser tool owns page interaction. Use dashboard=<widget name> and omit targetId/profile/route overrides. Administrator dashboards use managed-profile state. Non-admin selectors use an empty isolated context in the configured default local managed profile; supported actions are tabs, focus, navigate, snapshot, screenshot, act, open and close. Session mode is unavailable when a sandbox is required or model selection is locked. Agent and viewer must use the same mode to share page state. Hiding a dashboard preserves its page; resetting a session closes its isolated context. General browser actions retain their configured host/profile access. Call browser with action=\"close\" and dashboard to request stop, or action=\"open\" and dashboard to resume its saved URL. A session:website widget is a lightweight iframe and cannot be controlled through this selector." : void 0,
"For stable, self-resolving refs across calls, use snapshot with refs=\"aria\" (Playwright aria-ref ids). Default refs=\"role\" are role+name-based.",
"Repeated compatible snapshots with stable document identity mark newly appeared ref-bearing elements with [new].",
`navigate returns the loaded page's compact snapshot inline (efficient interactive tier; use action=snapshot for a full snapshot); do not call snapshot after navigate.${i.actKinds.includes("batch") ? " Batch act results that report a cross-document navigation also include fresh page state;" : ""} After a single act that triggers navigation, snapshot before using refs.`,
"Use snapshot+act for UI automation. Avoid act:wait by default; use only in exceptional cases when no reliable UI state exists.",
s.has("text") ? "For page prose, use action=text with optional selector and maxChars; it reads the first selector match, else article, main, or body. Use efficient snapshots for controls; they omit most prose." : `For page text, use snapshot${c ? " or a bounded act:evaluate" : ""}; efficient snapshots omit most prose.`,
s.has("judge") ? "Use action=judge for explicit advisory page-blocker classification with this agent's selected Decision model. Sends up to 6,000 characters of body text to that provider (hosted inference may charge); returns answers, not page text. No automatic fallback or actions. Missing, uncertain or all-low answers do not prove usable content. Requires a text-capable profile; not native Lightpanda judge()." : void 0,
"Use snapshot query to keep lines matching all whitespace-separated tokens, case-insensitively; matching lines retain element refs.",
s.has("requests") ? "Use requests for the recent network log; filter matches URL/type, limit defaults to 50, and clear=true clears the collected log after reading." : void 0,
s.has("errors") ? "Use errors for page errors; limit defaults to 50, clear=true clears after reading." : void 0,
s.has("emulate") ? "Use emulate with device, colorScheme, timezoneId, or locale; at least one setting is required." : void 0,
s.has("upload") ? "For file chooser uploads, pass the trigger ref with paths in the same upload call when available; use paths-only arming only when a later trigger is intentional. Use inputRef or element to set a file input directly." : void 0,
...!i.tabBound ? [`target selects browser location (sandbox|host|node). Default: ${o ? "configured browser node" : e?.sandboxBridgeUrl ? "sandbox" : "host"}.`, e?.allowHostControl === false ? "Host target blocked by policy." : "Host target allowed."] : []
].filter(Boolean).join(" "),
parameters: createBrowserToolSchema(i),
outputSchema: BrowserToolOutputSchema
}
};
}
//#endregion
export { BROWSER_PROXY_COMMAND as a, applyBrowserTabToolBinding as i, BROWSER_ACT_REQUEST_KEYS as n, BROWSER_PROXY_UPLOAD_COMMAND as o, isBrowserLifecycleAction as r, browserProxyUploadUnavailableMessage as s, createBrowserToolDefinition as t };