Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { build } from "vite";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { z } from "zod/v4";
import { connectRPCClient, type RPCClient } from "../../../sdk-ts/src/rpcClient.js";
import { loadStagehandExtension } from "../../../sdk-ts/src/localBrowserLauncher.js";
import { loadStagehandExtension } from "../../../sdk-ts/src/runtime/node/localBrowserLauncher.js";
import { StagehandMethods } from "../../schema-registry.js";
import type { StagehandRpcNotification } from "../../types.js";

Expand Down
28 changes: 25 additions & 3 deletions packages/sdk-ts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,37 @@
"dist"
],
"type": "module",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.mts",
"import": "./dist/index.mjs"
"workerd": {
"types": "./dist/web/index.d.ts",
"default": "./dist/web/index.js"
},
"deno": {
"types": "./dist/web/index.d.ts",
"default": "./dist/web/index.js"
},
"bun": {
"types": "./dist/web/index.d.ts",
"default": "./dist/web/index.js"
},
"browser": {
"types": "./dist/web/index.d.ts",
"default": "./dist/web/index.js"
},
"node": {
"types": "./dist/node/index.d.ts",
"default": "./dist/node/index.js"
},
"types": "./dist/web/index.d.ts",
"default": "./dist/web/index.js"
}
},
"scripts": {
"build": "pnpm --dir ../server run build && pnpm run build:extension-archive && tsdown",
"build:extension-archive": "node scripts/build-extension-archive.ts",
"build": "tsdown",
"test:package-resolution": "pnpm run build && node scripts/test-package-resolution.mjs",
"test": "vitest run --root ../.. packages/sdk-ts/tests"
},
"dependencies": {
Expand Down
37 changes: 37 additions & 0 deletions packages/sdk-ts/scripts/test-package-resolution.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);
const packageName = "@browserbasehq/stagehand-v4-spike-sdk-ts";
const detectVariant = `
const sdk = await import(${JSON.stringify(packageName)});
try {
new sdk.Stagehand({ browser: { type: "local" } });
process.stdout.write("node");
} catch {
process.stdout.write("web");
}
`;

for (const [condition, expectedVariant] of [
[undefined, "node"],
["workerd", "web"],
["deno", "web"],
["bun", "web"],
["browser", "web"],
]) {
const arguments_ = [
...(condition === undefined ? [] : [`--conditions=${condition}`]),
"--input-type=module",
"--eval",
detectVariant,
];
const { stdout } = await execFileAsync(process.execPath, arguments_, {
cwd: new URL("..", import.meta.url),
});
if (stdout !== expectedVariant) {
throw new Error(
`Expected ${condition ?? "default Node"} to resolve ${expectedVariant}, received ${stdout}`,
);
}
}
67 changes: 67 additions & 0 deletions packages/sdk-ts/src/browserSource.shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { BrowserbaseSessionCreateParamsSchema } from "../../protocol/schemas.js";
import {
createBrowserbaseSessionClient,
type BrowserbaseSessionClient,
type BrowserbaseSessionClientFactory,
} from "./browserbaseSession.js";

export type { BrowserbaseSessionClient, BrowserbaseSessionClientFactory };

export type ResolvedBrowserSource = {
cdpUrl: string;
cdpHeaders?: Record<string, string>;
browserbaseSessionId?: string;
keepAlive: boolean;
close?: () => Promise<void> | void;
};

export type RemoteBrowserSourceResolverDependencies = {
browserbase?: BrowserbaseSessionClient;
createBrowserbaseSessionClient?: BrowserbaseSessionClientFactory;
};

type RemoteBrowserSourceInitParams = {
apiKey?: string;
browser:
| {
type: "browserbase";
keepAlive?: boolean;
[key: string]: unknown;
}
| {
type: "cdp";
cdpUrl: string;
headers?: Record<string, string>;
};
};

export async function resolveRemoteBrowserSource(
initParams: RemoteBrowserSourceInitParams,
dependencies: RemoteBrowserSourceResolverDependencies = {},
): Promise<ResolvedBrowserSource> {
const browser = initParams.browser;

if (browser.type === "browserbase") {
const apiKey = initParams.apiKey;
if (apiKey === undefined) {
throw new Error("A Browserbase API key is required for the Browserbase browser source");
}
const sessionCreateParams = BrowserbaseSessionCreateParamsSchema.strip().parse(browser);
const browserbase =
dependencies.browserbase ??
(dependencies.createBrowserbaseSessionClient ?? createBrowserbaseSessionClient)(apiKey);
const session = await browserbase.createSession(sessionCreateParams);
return {
cdpUrl: session.cdpUrl,
browserbaseSessionId: session.sessionId,
keepAlive: browser.keepAlive ?? false,
close: session.close,
};
}

return {
cdpUrl: browser.cdpUrl,
...(browser.headers === undefined ? {} : { cdpHeaders: browser.headers }),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: CDP connections requiring authentication ignore the supplied browser.headers, so Stagehand.init() cannot connect to protected CDP endpoints. Thread cdpHeaders through Stagehand, RPCClient, and CDP discovery/WebSocket transport, or reject/remove this currently nonfunctional option.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/sdk-ts/src/browserSource.shared.ts, line 64:

<comment>CDP connections requiring authentication ignore the supplied `browser.headers`, so `Stagehand.init()` cannot connect to protected CDP endpoints. Thread `cdpHeaders` through `Stagehand`, `RPCClient`, and CDP discovery/WebSocket transport, or reject/remove this currently nonfunctional option.</comment>

<file context>
@@ -0,0 +1,67 @@
+
+  return {
+    cdpUrl: browser.cdpUrl,
+    ...(browser.headers === undefined ? {} : { cdpHeaders: browser.headers }),
+    keepAlive: true,
+  };
</file context>

keepAlive: true,
};
}
72 changes: 1 addition & 71 deletions packages/sdk-ts/src/browserSource.ts
Original file line number Diff line number Diff line change
@@ -1,71 +1 @@
import { StagehandClientInitParamsSchema } from "./clientSchemas.js";
import { BrowserbaseSessionCreateParamsSchema } from "../../protocol/schemas.js";
import { LocalBrowserLaunchOptionsSchema } from "../../protocol/pending-schemas.js";
import {
createBrowserbaseSessionClient,
type BrowserbaseSessionClient,
type BrowserbaseSessionClientFactory,
} from "./browserbaseSession.js";
import { launchLocalBrowser, type LocalBrowserLaunchOptions } from "./localBrowserLauncher.js";

export type { BrowserbaseSessionClient, BrowserbaseSessionClientFactory };

export type ResolvedBrowserSource = {
cdpUrl: string;
cdpHeaders?: Record<string, string>;
browserbaseSessionId?: string;
keepAlive: boolean;
close?: () => Promise<void> | void;
};

export type LocalBrowserLauncher = (
options: LocalBrowserLaunchOptions,
) => Promise<{ cdpUrl: string; close: () => Promise<void> | void }>;

export type BrowserSourceResolverDependencies = {
launchLocalBrowser?: LocalBrowserLauncher;
browserbase?: BrowserbaseSessionClient;
createBrowserbaseSessionClient?: BrowserbaseSessionClientFactory;
};

export async function resolveBrowserSource(
input: unknown,
dependencies: BrowserSourceResolverDependencies = {},
): Promise<ResolvedBrowserSource> {
const initParams = StagehandClientInitParamsSchema.parse(input);
const browser = initParams.browser;

if (browser.type === "browserbase") {
const apiKey = initParams.apiKey;
if (apiKey === undefined) {
throw new Error("A Browserbase API key is required for the Browserbase browser source");
}
const sessionCreateParams = BrowserbaseSessionCreateParamsSchema.strip().parse(browser);
const browserbase =
dependencies.browserbase ??
(dependencies.createBrowserbaseSessionClient ?? createBrowserbaseSessionClient)(apiKey);
const session = await browserbase.createSession(sessionCreateParams);
return {
cdpUrl: session.cdpUrl,
browserbaseSessionId: session.sessionId,
keepAlive: browser.keepAlive ?? false,
close: session.close,
};
}

if (browser.type === "local") {
const launchOptions = LocalBrowserLaunchOptionsSchema.strip().parse(browser);
const launched = await (dependencies.launchLocalBrowser ?? launchLocalBrowser)(launchOptions);
return {
cdpUrl: launched.cdpUrl,
keepAlive: launchOptions.keepAlive ?? false,
close: launched.close,
};
}

return {
cdpUrl: browser.cdpUrl,
...(browser.headers === undefined ? {} : { cdpHeaders: browser.headers }),
keepAlive: true,
};
}
export * from "./runtime/node/browserSource.js";
152 changes: 152 additions & 0 deletions packages/sdk-ts/src/clientSchemas.shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/**
* TypeScript SDK-owned schemas. They extend protocol schemas with SDK-only values such as local/CDP
* connection options, JavaScript callbacks, and Page instances. Those values are consumed by the
* SDK and never cross the RPC boundary. Other language SDKs should follow the same pattern around
* the shared wire params.
*/

import { z } from "zod/v4";
import {
ActOptionsSchema,
BrowserbaseBrowserSettingsSchema,
BrowserbaseSessionCreateParamsSchema,
ExtractOptionsSchema,
LLMGenerateParamsSchema,
LLMGenerateResultSchema,
ModelConfigSchema,
ObserveOptionsSchema,
StagehandInitParamsSchema,
StagehandLogLevelSchema,
StagehandLogSchema,
} from "../../protocol/schemas.js";
import { LocalBrowserLaunchOptionsSchema } from "../../protocol/pending-schemas.js";
import { Page } from "./page.js";

const BrowserbaseClientBrowserSettingsSchema = BrowserbaseBrowserSettingsSchema.omit({
extensionId: true,
}).strict();

/** Browserbase source fields exposed by the TS SDK. Stagehand provisions its own extension. */
export const BrowserbaseBrowserSourceSchema = BrowserbaseSessionCreateParamsSchema.omit({
browserSettings: true,
extensionId: true,
})
.extend({
type: z.literal("browserbase"),
browserSettings: BrowserbaseClientBrowserSettingsSchema.optional(),
})
.strict()
.meta({ id: "BrowserbaseClientBrowserSource" });

export const LocalBrowserSourceSchema = LocalBrowserLaunchOptionsSchema.extend({
type: z.literal("local"),
})
.strict()
.meta({ id: "LocalBrowserSource" });

export const CdpBrowserSourceSchema = z
.object({
type: z.literal("cdp"),
cdpUrl: z.string().min(1),
headers: z.record(z.string(), z.string()).optional(),
})
.strict()
.meta({ id: "CdpBrowserSource" });

/** An LLM callback implemented locally by the SDK consumer. It never crosses the wire. */
export const ClientLLMSchema = z
.object({
generate: z.function({
input: [LLMGenerateParamsSchema],
output: z.promise(LLMGenerateResultSchema),
}),
})
.strict()
.meta({ id: "ClientLLM" });

export const StagehandClientLogLevelSchema = z
.union([StagehandLogLevelSchema, z.literal("off")])
.meta({ id: "StagehandClientLogLevel" });

export const StagehandClientLogFormatSchema = z
.enum(["pretty", "json"])
.meta({ id: "StagehandClientLogFormat" });

export const StagehandClientOnLogSchema = z
.function({
input: [StagehandLogSchema],
output: z.union([z.void(), z.promise(z.void())]),
})
.meta({ id: "StagehandClientOnLog" });

export const StagehandClientLoggingConfigSchema = z
.strictObject({
level: StagehandClientLogLevelSchema.default("info"),
format: StagehandClientLogFormatSchema.default("pretty"),
onLog: StagehandClientOnLogSchema.optional(),
})
.meta({ id: "StagehandClientLoggingConfig" });

export const StagehandClientActOptionsSchema = ActOptionsSchema.unwrap()
.extend({
page: z.instanceof(Page).optional(),
})
.strict()
.meta({ id: "StagehandClientActOptions" });

export const StagehandClientObserveOptionsSchema = ObserveOptionsSchema.unwrap()
.extend({
page: z.instanceof(Page).optional(),
})
.strict()
.meta({ id: "StagehandClientObserveOptions" });

export const StagehandClientExtractOptionsSchema = ExtractOptionsSchema.unwrap()
.extend({
page: z.instanceof(Page).optional(),
})
.strict()
.meta({ id: "StagehandClientExtractOptions" });

export function createStagehandClientInitParamsSchema<
BrowserSourceSchema extends z.ZodType<
| z.output<typeof BrowserbaseBrowserSourceSchema>
| z.output<typeof LocalBrowserSourceSchema>
| z.output<typeof CdpBrowserSourceSchema>
>,
>(browserSourceSchema: BrowserSourceSchema) {
return StagehandInitParamsSchema.extend({
browser: browserSourceSchema.optional().transform(
(browser) =>
browser ??
browserSourceSchema.parse({
type: "browserbase",
}),
),
model: z.union([ModelConfigSchema, ClientLLMSchema]).optional(),
logging: StagehandClientLoggingConfigSchema.default({
level: "info",
format: "pretty",
}),
})
.strict()
.superRefine((params, context) => {
if (params.browser.type === "browserbase" && params.apiKey === undefined) {
context.addIssue({
code: "custom",
path: ["apiKey"],
message: "A Browserbase API key is required for the Browserbase browser source",
});
}
})
.meta({ id: "StagehandClientInitParams" });
}

export type ClientLLM = z.infer<typeof ClientLLMSchema>;
export type StagehandClientLoggingConfig = z.input<typeof StagehandClientLoggingConfigSchema>;
export type ResolvedStagehandClientLoggingConfig = z.output<
typeof StagehandClientLoggingConfigSchema
>;
export type StagehandClientActOptions = z.input<typeof StagehandClientActOptionsSchema>;
export type StagehandClientObserveOptions = z.input<typeof StagehandClientObserveOptionsSchema>;
export type StagehandClientExtractOptions = z.input<typeof StagehandClientExtractOptionsSchema>;
Loading
Loading