Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
c762fc9
feat(integrations): add Playwright-facade tool surface (run/snapshot/…
miguelg719 Aug 9, 2026
7d76a0e
docs(integrations): explain the wire-vs-runtime schema split in facad…
miguelg719 Aug 9, 2026
e82efce
fix(integrations): drop top-level oneOf from run wire schema
miguelg719 Aug 9, 2026
08c8340
feat(integrations): expose facade library surface via ./facade export
miguelg719 Aug 10, 2026
1b0acf8
fix(integrations): address facade review comments
miguelg719 Aug 10, 2026
cb12c6c
chore(integrations): update facade model default
miguelg719 Aug 10, 2026
fc74fbd
feat(protocol): support Gemini 3.6 Flash
miguelg719 Aug 10, 2026
fffe64f
chore(protocol): regenerate v4 schema
miguelg719 Aug 10, 2026
8945629
feat(integrations): export canonical facade agent instructions
miguelg719 Aug 10, 2026
9ef260e
refactor(integrations): move the package into core/, siblings for exa…
miguelg719 Aug 10, 2026
6ab64c8
style: format facade tools
miguelg719 Aug 10, 2026
4b2bba9
feat(integrations): CrewAI example (MCP over stdio) for the facade to…
miguelg719 Aug 10, 2026
aa3cd38
style: format crewai example files
miguelg719 Aug 10, 2026
dba26a8
chore(sdk-python): regenerate models for Gemini 3.6 Flash
miguelg719 Aug 10, 2026
6340d66
merge facade-core codegen fix
miguelg719 Aug 10, 2026
ff8eeb0
fix(ci): regenerate Go embedded extension; bound docs parity test at 30s
miguelg719 Aug 10, 2026
d58c4ce
test(integrations): pin crewai instructions to the canonical TS constant
miguelg719 Aug 10, 2026
aa86e46
chore(integrations): standardize crewai default model to openai/gpt-5…
miguelg719 Aug 10, 2026
6f0d074
docs(integrations): crewai README commands run from the repo root
miguelg719 Aug 10, 2026
dbb0a7b
fix(integrations): default local facade browser to headed
miguelg719 Aug 10, 2026
6c95f4f
Merge branch 'miguel/facade-core' into miguel/facade-crewai-example
miguelg719 Aug 10, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ jobs:
packages/extension/dist/**
packages/extension/artifacts/**
packages/sdk-ts/dist/**
packages/integrations/dist/**
packages/integrations/core/dist/**
packages/evals/dist/**
retention-days: 1

Expand Down
2 changes: 1 addition & 1 deletion packages/docs/tests/sdk-reference.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ describe("SDK reference surface", () => {
`${language} method headings must match the public SDK surface`,
).toStrictEqual(expected);
}
});
}, 30_000);

it("has exactly one reference page for every documented SDK object", async () => {
const pageSlugs = (await readReferencePages()).map(({ classSlug }) => classSlug).sort();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,34 @@
"version": "4.0.0",
"private": true,
"description": "Shared integration surfaces for Stagehand V4",
"bin": {
"stagehand-facade": "./dist/facade/stdio-server.mjs"
},
"files": [
"dist"
],
"type": "module",
"exports": {
"./codemode/stdio-server": {
"import": "./dist/codemode/stdio-server.mjs"
},
"./facade": {
"import": "./dist/facade/index.mjs"
},
"./facade/stdio-server": {
"import": "./dist/facade/stdio-server.mjs"
}
},
"scripts": {
"build": "tsdown",
"test": "pnpm run build && vitest run --root ../.. packages/integrations/tests",
"test:unit": "vitest run --root ../.. packages/integrations/tests",
"test": "pnpm run build && vitest run --root ../../.. packages/integrations/core/tests",
"test:unit": "vitest run --root ../../.. packages/integrations/core/tests",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
"@modelcontextprotocol/sdk": "catalog:"
"@browserbasehq/stagehand": "workspace:*",
"@modelcontextprotocol/sdk": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
Expand Down
115 changes: 115 additions & 0 deletions packages/integrations/core/src/facade/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import {
StagehandClientCreateConfigSchema,
type BrowserbaseLaunchOptions,
type LocalBrowserLaunchOptions,
type StagehandClientCreateConfig,
} from "@browserbasehq/stagehand";

export class StagehandFacadeConfigError extends Error {
override readonly name = "StagehandFacadeConfigError";
}

export type StagehandFacadeConfig = {
browser:
| { type: "local"; launchOptions: LocalBrowserLaunchOptions }
| { type: "browserbase"; launchOptions: BrowserbaseLaunchOptions };
stagehand: StagehandClientCreateConfig;
};

export function stagehandFacadeConfigFromEnv(
env: NodeJS.ProcessEnv = process.env,
): StagehandFacadeConfig {
const browserbaseApiKey = nonEmpty(env.BROWSERBASE_API_KEY);
const browserbaseProjectId = nonEmpty(env.BROWSERBASE_PROJECT_ID);
const requestedBrowser = nonEmpty(env.STAGEHAND_BROWSER);
if (requestedBrowser && requestedBrowser !== "local" && requestedBrowser !== "browserbase") {
throw new StagehandFacadeConfigError(
'STAGEHAND_BROWSER must be either "local" or "browserbase".',
);
}

const browserType = requestedBrowser ?? (browserbaseApiKey ? "browserbase" : "local");
if (browserType === "browserbase" && !browserbaseApiKey) {
throw new StagehandFacadeConfigError(
'BROWSERBASE_API_KEY is required when STAGEHAND_BROWSER="browserbase".',
);
}

const explicitModelName = nonEmpty(env.STAGEHAND_MODEL_NAME);
const explicitModelApiKey = nonEmpty(env.STAGEHAND_MODEL_API_KEY);
if (explicitModelApiKey && !explicitModelName) {
throw new StagehandFacadeConfigError(
"STAGEHAND_MODEL_NAME is required when STAGEHAND_MODEL_API_KEY is set.",
);
}

const inferredGoogleKey = providerApiKey("google", env);
const modelName =
explicitModelName ?? (inferredGoogleKey ? "google/gemini-3.6-flash" : undefined);
const modelProvider = modelName ? providerName(modelName) : undefined;
const modelApiKey = explicitModelApiKey ?? providerApiKey(modelProvider, env);
const parsed = StagehandClientCreateConfigSchema.safeParse({
logging: { level: "off" },
...(modelName
? {
model: {
modelName,
...(modelApiKey ? { apiKey: modelApiKey } : {}),
...(modelProvider === "anthropic"
? { headers: { "anthropic-dangerous-direct-browser-access": "true" } }
: {}),
},
}
: {}),
});
if (!parsed.success) {
throw new StagehandFacadeConfigError(
`Unsupported STAGEHAND_MODEL_NAME "${modelName}": ${parsed.error.issues[0]?.message ?? "invalid model configuration"}`,
);
}
const stagehand = parsed.data;

return {
browser:
browserType === "browserbase"
? {
type: "browserbase",
launchOptions: {
apiKey: browserbaseApiKey!,
...(browserbaseProjectId ? { projectId: browserbaseProjectId } : {}),
},
}
: { type: "local", launchOptions: { headless: false } },
stagehand,
};
}

function nonEmpty(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}

function providerName(modelName: string): string {
return modelName.split("/", 1)[0] ?? "";
}

function providerApiKey(provider: string | undefined, env: NodeJS.ProcessEnv): string | undefined {
switch (provider) {
case "google":
return (
nonEmpty(env.GOOGLE_GENERATIVE_AI_API_KEY) ??
nonEmpty(env.GEMINI_API_KEY) ??
nonEmpty(env.GOOGLE_API_KEY)
);
case "openai":
return nonEmpty(env.OPENAI_API_KEY);
case "anthropic":
return nonEmpty(env.ANTHROPIC_API_KEY);
case "groq":
return nonEmpty(env.GROQ_API_KEY);
case "cerebras":
return nonEmpty(env.CEREBRAS_API_KEY);
default:
return undefined;
}
}
180 changes: 180 additions & 0 deletions packages/integrations/core/src/facade/contract.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { z } from "zod/v4";

/**
* This file intentionally carries the same contract twice:
*
* - The JSON-schema literals below are the WIRE contract — the exact bytes
* advertised to MCP clients via tools/list. They are hand-written because
* they cannot be generated from the zod schemas: the `const`-typed `op`
* discriminators and the per-property guidance descriptions do not survive
* zod-to-JSON-schema conversion, and `.refine()` emits nothing at all.
* Their wording is pinned string-exact to the reference contract (models
* are prompted against these descriptions) — see
* tests/facade-contract.test.ts. One deliberate deviation is documented on
* RUN_INPUT_SCHEMA below.
*
* - The zod schemas at the bottom are the RUNTIME validators: they parse
* tools/call arguments into typed values and enforce what the wire schema
* states (e.g. the code/actions exclusivity via `.refine`).
*
* If you change one half, change the other; the contract test exists to
* catch drift between them.
*/
const actionSchema = (op: string, extra: Record<string, Record<string, unknown>> = {}) => ({
type: "object",
properties: {
op: {
const: op,
description: `Action operation. Use "op": "${op}"; never use a "kind" field.`,
},
id: {
type: "string",
description:
'Bracketed ID copied from the latest snapshot, as a string. Use "id"; never use "ref".',
},
...extra,
},
required: ["op", "id", ...Object.keys(extra).filter((key) => key !== "delay")],
additionalProperties: false,
});

export const RUN_TOOL_DESCRIPTION =
'Execute either a JavaScript workflow against the Stagehand Playwright facade or a batch of actions using IDs from the latest snapshot. Provide exactly one of code or actions. Each action must use "op" (never "kind") and "id" (never "ref"). Copy the bracketed snapshot ID as a string. Examples: {"actions":[{"op":"click","id":"1-42"}]}, {"actions":[{"op":"fill","id":"2-14","value":"Miami"}]}, {"actions":[{"op":"select","id":"3-9","values":"Lowest price"}]}.';

export const SNAPSHOT_TOOL_DESCRIPTION =
"Capture the active page's Stagehand accessibility tree and hydrate its displayed IDs for subsequent run actions. Every call replaces the active page's ID map.";

export const SCREENSHOT_TOOL_DESCRIPTION = "Capture a screenshot of the active page.";

export const RUN_INPUT_SCHEMA = {
type: "object",
properties: {
code: { type: "string", minLength: 1 },
actions: {
type: "array",
description:
'Snapshot actions with the exact fields "op" and "id". Do not use "kind" or "ref".',
items: {
oneOf: [
actionSchema("click"),
actionSchema("hover"),
actionSchema("fill", { value: { type: "string" } }),
actionSchema("type", {
text: { type: "string" },
delay: { type: "number", minimum: 0 },
}),
actionSchema("press", { key: { type: "string" } }),
actionSchema("select", {
values: {
oneOf: [
{ type: "string" },
{ type: "array", items: { type: "string" }, minItems: 1 },
],
},
}),
],
},
minItems: 1,
},
},
// Deliberate deviation from the reference contract: no top-level
// `oneOf: [{required:["code"]},{required:["actions"]}]` here. AI-SDK-based
// MCP clients (Eve, Vercel AI SDK) reject tool input schemas with a
// top-level oneOf, failing every `run` call client-side before it reaches
// the server. The code/actions exclusivity is stated in the description
// and enforced at runtime by CodeModeRunInputSchema's `.refine`.
additionalProperties: false,
} as const;

export const SNAPSHOT_INPUT_SCHEMA = {
type: "object",
properties: { includeIframes: { type: "boolean", default: true } },
additionalProperties: false,
} as const;

export const SCREENSHOT_INPUT_SCHEMA = {
type: "object",
properties: {
fullPage: { type: "boolean" },
type: { type: "string", enum: ["png", "jpeg"] },
quality: { type: "number", minimum: 0, maximum: 100 },
},
additionalProperties: false,
} as const;

export const FACADE_TOOLS = [
{ name: "run", description: RUN_TOOL_DESCRIPTION, inputSchema: RUN_INPUT_SCHEMA },
{
name: "snapshot",
description: SNAPSHOT_TOOL_DESCRIPTION,
inputSchema: SNAPSHOT_INPUT_SCHEMA,
},
{
name: "screenshot",
description: SCREENSHOT_TOOL_DESCRIPTION,
inputSchema: SCREENSHOT_INPUT_SCHEMA,
},
] as const;

/**
* Canonical agent system prompt for the facade tool surface. Host examples
* (Eve, Vercel AI SDK, deepagents) should use this text rather than authoring
* their own so agent guidance stays identical across frameworks.
*/
export const FACADE_AGENT_INSTRUCTIONS = `You control one persistent browser through exactly three tools:
- snapshot: inspect the active page and hydrate bracketed element IDs.
- run: provide either snapshot actions or JavaScript using the Playwright-shaped page API.
- screenshot: inspect the rendered page visually.

Use snapshot actions for simple interactions and run code for multi-step workflows. Pass run exactly one of code or actions; every action uses "op" and "id", never "kind" or "ref". Snapshot IDs are valid only for the latest snapshot of the active page; snapshot again after navigation or stale IDs. Do not launch another browser.`;

export const NO_HYDRATED_SNAPSHOT_ERROR =
"No hydrated snapshot exists for the active page; call snapshot first.";
export const NAVIGATED_SNAPSHOT_ERROR =
"The active page navigated after its snapshot; call snapshot again.";
export const STALE_SNAPSHOT_ID_ERROR =
'Snapshot ID "${id}" is stale or not actionable; call snapshot again.';

export function staleSnapshotIdError(id: string): string {
return STALE_SNAPSHOT_ID_ERROR.replace("${id}", id);
}

export const RefActionSchema = z.discriminatedUnion("op", [
z.strictObject({ op: z.literal("click"), id: z.string().min(1) }),
z.strictObject({ op: z.literal("hover"), id: z.string().min(1) }),
z.strictObject({ op: z.literal("fill"), id: z.string().min(1), value: z.string() }),
z.strictObject({
op: z.literal("type"),
id: z.string().min(1),
text: z.string(),
delay: z.number().nonnegative().optional(),
}),
z.strictObject({ op: z.literal("press"), id: z.string().min(1), key: z.string().min(1) }),
z.strictObject({
op: z.literal("select"),
id: z.string().min(1),
values: z.union([z.string(), z.array(z.string()).min(1)]),
}),
]);

export const CodeModeRunInputSchema = z
.strictObject({
code: z.string().min(1).optional(),
actions: z.array(RefActionSchema).min(1).optional(),
})
.refine((input) => (input.code === undefined) !== (input.actions === undefined), {
message: "run requires exactly one of code or actions",
});

export const SnapshotInputSchema = z.strictObject({
includeIframes: z.boolean().optional(),
});

export const ScreenshotInputSchema = z.strictObject({
fullPage: z.boolean().optional(),
type: z.enum(["png", "jpeg"]).optional(),
quality: z.number().min(0).max(100).optional(),
});

export type RefAction = z.infer<typeof RefActionSchema>;
export type CodeModeRunInput = z.infer<typeof CodeModeRunInputSchema>;
26 changes: 26 additions & 0 deletions packages/integrations/core/src/facade/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export {
FACADE_TOOLS,
FACADE_AGENT_INSTRUCTIONS,
RUN_TOOL_DESCRIPTION,
SNAPSHOT_TOOL_DESCRIPTION,
SCREENSHOT_TOOL_DESCRIPTION,
RUN_INPUT_SCHEMA,
SNAPSHOT_INPUT_SCHEMA,
SCREENSHOT_INPUT_SCHEMA,
NO_HYDRATED_SNAPSHOT_ERROR,
NAVIGATED_SNAPSHOT_ERROR,
STALE_SNAPSHOT_ID_ERROR,
staleSnapshotIdError,
RefActionSchema,
CodeModeRunInputSchema,
SnapshotInputSchema,
ScreenshotInputSchema,
type RefAction,
type CodeModeRunInput,
} from "./contract.js";
export { StagehandFacadeTools } from "./tools.js";
export {
StagehandFacadeConfigError,
stagehandFacadeConfigFromEnv,
type StagehandFacadeConfig,
} from "./config.js";
Loading
Loading