@edlsh/browse-core 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/dist/broker-client.d.ts +4 -2
- package/dist/broker-client.js +10 -5
- package/dist/broker-protocol.d.ts +3 -2
- package/dist/broker-protocol.js +11 -7
- package/dist/broker.js +12 -12
- package/dist/config.d.ts +101 -0
- package/dist/config.js +78 -0
- package/dist/contexts.d.ts +10 -0
- package/dist/contexts.js +27 -0
- package/dist/errors.d.ts +29 -0
- package/dist/errors.js +83 -0
- package/dist/host-model.d.ts +24 -0
- package/dist/host-model.js +35 -0
- package/dist/index.d.ts +10 -13
- package/dist/index.js +11 -15
- package/dist/jev.js +9 -3
- package/dist/page-operations.d.ts +11 -1
- package/dist/page-operations.js +62 -11
- package/dist/real-browser-ai.d.ts +1 -1
- package/dist/real-browser-ai.js +1 -1
- package/dist/real-browser-client.js +1 -1
- package/dist/real-browser-session.d.ts +1 -1
- package/dist/real-browser-session.js +24 -5
- package/dist/schema.d.ts +32 -0
- package/dist/schema.js +22 -6
- package/dist/session-runtime.d.ts +42 -0
- package/dist/session-runtime.js +144 -0
- package/dist/session.d.ts +27 -118
- package/dist/session.js +134 -350
- package/dist/settings.js +47 -6
- package/dist/tool-results.d.ts +28 -0
- package/dist/tool-results.js +40 -0
- package/extensions/http-auth/README.md +27 -0
- package/extensions/http-auth/background.js +85 -0
- package/extensions/http-auth/manifest.json +27 -0
- package/extensions/http-auth/native/README.md +31 -0
- package/extensions/http-auth/native/host.py +97 -0
- package/extensions/http-auth/native/install.py +62 -0
- package/extensions/http-auth/options.html +25 -0
- package/extensions/http-auth/options.js +36 -0
- package/extensions/http-auth/origin.js +16 -0
- package/package.json +13 -2
package/README.md
CHANGED
|
@@ -18,12 +18,16 @@ const output = await browser.run(browserParameters.parse({ action: "start", back
|
|
|
18
18
|
- A persistent profile's cached extension service workers are dropped before a launch whenever the bundled Stagehand extension changed, because Chrome otherwise keeps running the worker of the SDK that first launched the profile. Logins and extension data are kept.
|
|
19
19
|
- `BrowseSessionOptions.cookies` takes a `CookieProvider` (`list`, `find`, `read`) that `cookie_profiles` and `cookie_import` read through; the default, `localCookieProvider`, reads this Mac's installed browsers. A host whose user's browsers are on another machine supplies its own (hermes-browse reads the MacBook's Helium through a cookie service). Imports with a custom provider go into Browserbase or private launches only, since shared browsers run in a broker that reads its own machine's browsers.
|
|
20
20
|
- A hosted start uploads the Stagehand extension to the Browserbase project once and remembers its ID in `$XDG_CACHE_HOME/browse-core/browserbase-extensions.json` (`~/.cache` without `XDG_CACHE_HOME`), keyed by a hash of the API key and project; later conversations and processes reuse it, and an SDK upgrade replaces it. The extension stays in the project. A remembered extension the project no longer has is uploaded again.
|
|
21
|
-
- `browserBatchParameters` is `browserParameters` plus the `batch` action: 1 to 20 known steps (`open`, `back`, `forward`, `reload`, `snapshot`, `click`, `fill`, `select`, `press`, `scroll`, `wait`, `evaluate`) run in order on one tab
|
|
22
|
-
- `ClientInference`
|
|
21
|
+
- `browserBatchParameters` is `browserParameters` plus the `batch` action: 1 to 20 known steps (`open`, `back`, `forward`, `reload`, `snapshot`, `click`, `fill`, `select`, `press`, `scroll`, `wait`, `evaluate`) run in order on one tab under one deadline. Stagehand normally executes them in one browser request. A shifted printable key uses tab-scoped DevTools input because Stagehand 4.4 drops its keydown metadata; that batch and real-browser batches can take several round trips. The first failure stops the rest; the result's `batch` reports `total`, `completed`, `failedIndex`, and `outcomeUnknown`, and a failed call's `BrowseToolError` carries the same. A batch whose first step is `open` starts a browser when none is running. A host opts in by registering this schema, because it owns the prompts and approval rules one call that navigates, acts, and runs page script needs; `browserParameters` stays without batch.
|
|
22
|
+
- `ClientInference.describe` names the host model for status. Supply `ClientInference.generate` for a session-wide provider, or pass a provider factory to `browser.run(params, context, signal, providerFactory)` for each AI call. The factory receives that call’s abort signal. Hosted sessions without a host model use Browserbase Model Gateway.
|
|
23
23
|
- `settings.ts` holds the per-profile `/browse` settings file (`browserbase-ai.json`): `readSettings`, `writeSetting`, and the model-role helpers.
|
|
24
24
|
|
|
25
25
|
Stagehand is pinned to 4.4.0 and used unmodified. zod is pinned to 4.6.6, the exact version Stagehand pins, so one copy is installed; a second copy fails the typecheck on the schema passed to `stagehand.extract`. An attached browser needs Chrome 137 or newer and the Stagehand extension shipped with 4.4.0. Run both real-browser suites before upgrading Stagehand.
|
|
26
26
|
|
|
27
|
+
**Saved context ownership:** a hosted context must match the remote project and profile prefix and have a local creation record for this integration, profile and project. The registry is the configured history file or a private file under the user state directory. Older untagged records are not proof of origin: create a new context. A context returned with `historySaved: false` cannot be reused until the registry is writable and a new context is created.
|
|
28
|
+
|
|
29
|
+
**Tool results:** hosts call `encodeResult` or `encodeError` before rendering. For a large reply, use `result_read(resultId, offset)` to retrieve redacted JSON in chunks without replaying an action. Only the latest large reply is held in memory, and close or shutdown discards it.
|
|
30
|
+
|
|
27
31
|
## HTTP sign-in in a managed browser
|
|
28
32
|
|
|
29
33
|
Start an isolated browser for a site that uses a browser-native username and password prompt.
|
|
@@ -32,6 +36,8 @@ Start an isolated browser for a site that uses a browser-native username and pas
|
|
|
32
36
|
{ action: "start", backend: "local", httpAuth: true, url: "https://example.com/" }
|
|
33
37
|
```
|
|
34
38
|
|
|
39
|
+
The package includes the companion and native helper under `extensions/http-auth/`. To install the resolver explicitly, run `python3 node_modules/@edlsh/browse-core/extensions/http-auth/native/install.py managed`; installing the npm package does not register or run it. See the companion README there for desktop registration.
|
|
40
|
+
|
|
35
41
|
Enable the installed browser credential helper with `BROWSE_HTTP_AUTH_USE_STORE=true`. The helper looks up the starting URL's exact origin in the user's private credential mapping. Set `BROWSE_HTTP_AUTH_ORIGIN` to restrict this profile's lookups to one origin. Alternatively, supply `BROWSE_HTTP_AUTH_ORIGIN`, `BROWSE_HTTP_AUTH_USERNAME` and `BROWSE_HTTP_AUTH_PASSWORD` through the host's configured secrets manager. Keep these values out of tool arguments. Custom host resolvers receive `scope.httpAuth === true` at this start and may return profile-specific `httpAuthStore: {}` or `httpAuth: {origin, username, password}`.
|
|
36
42
|
|
|
37
43
|
The browser answers a server's HTTP Basic challenge at that scheme, host and port. Authentication requires HTTPS or loopback HTTP. Closing the browser discards its auth cache. An authenticated start uses a fresh profile even where the host normally shares a persistent profile. HAR capture is unavailable during this session.
|
package/dist/broker-client.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type RunContext } from "./broker-protocol.ts";
|
|
2
2
|
import type { HostClassify } from "./classifier.ts";
|
|
3
|
-
import
|
|
3
|
+
import type { ConfigResolver } from "./config.ts";
|
|
4
|
+
import type { BrowserOutput, ClientGenerate, HostIdentity } from "./session.ts";
|
|
4
5
|
import type { AIParams, BrowserParams } from "./schema.ts";
|
|
5
6
|
/** What a conversation in this process lends the broker. */
|
|
6
7
|
export interface BrokerHandlers {
|
|
@@ -11,6 +12,7 @@ export interface BrokerHandlers {
|
|
|
11
12
|
export declare class BrokerConnection {
|
|
12
13
|
private readonly socket;
|
|
13
14
|
private readonly socketPath;
|
|
15
|
+
private readonly inferenceRuns;
|
|
14
16
|
private readonly runs;
|
|
15
17
|
private readonly conversations;
|
|
16
18
|
private hello;
|
|
@@ -35,7 +37,7 @@ export declare class BrokerConnection {
|
|
|
35
37
|
/** Opens a conversation in the broker; its calls then run on the shared browser. */
|
|
36
38
|
openConversation(conv: string, identity: HostIdentity, handlers: BrokerHandlers): void;
|
|
37
39
|
/** Runs one call in the broker. A cancel is passed on, and the broker's own account of the outcome awaited briefly. */
|
|
38
|
-
run(conv: string, params: BrowserParams | AIParams, context: RunContext, ai: boolean, defaultBackend: "browserbase" | "local", signal: AbortSignal): Promise<BrowserOutput>;
|
|
40
|
+
run(conv: string, params: BrowserParams | AIParams, context: RunContext, ai: boolean, defaultBackend: "browserbase" | "local", signal: AbortSignal, generate?: ClientGenerate): Promise<BrowserOutput>;
|
|
39
41
|
/** Ends a conversation in the broker: its tabs close, and the browser goes with the last conversation. */
|
|
40
42
|
closeConversation(conv: string): Promise<void>;
|
|
41
43
|
}
|
package/dist/broker-client.js
CHANGED
|
@@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url";
|
|
|
8
8
|
import { setTimeout as delay } from "node:timers/promises";
|
|
9
9
|
import { z } from "zod";
|
|
10
10
|
import { BROKER_PROTOCOL, brokerMessage, brokerSocketPath, classifyRequest, errorBodyOf, } from "./broker-protocol.js";
|
|
11
|
-
import { BrowseToolError } from "./
|
|
11
|
+
import { BrowseToolError } from "./errors.js";
|
|
12
12
|
const CONNECT_TIMEOUT_MS = 15_000;
|
|
13
13
|
/** After a cancel, how long a call still waits for the broker's own account of what happened. */
|
|
14
14
|
const CANCEL_GRACE_MS = 15_000;
|
|
@@ -58,6 +58,7 @@ const connections = new Map();
|
|
|
58
58
|
export class BrokerConnection {
|
|
59
59
|
socket;
|
|
60
60
|
socketPath;
|
|
61
|
+
inferenceRuns = new Map();
|
|
61
62
|
runs = new Map();
|
|
62
63
|
conversations = new Map();
|
|
63
64
|
hello = Promise.withResolvers();
|
|
@@ -178,10 +179,11 @@ export class BrokerConnection {
|
|
|
178
179
|
value = sharedConfig;
|
|
179
180
|
}
|
|
180
181
|
else if (request.kind === "generate") {
|
|
181
|
-
|
|
182
|
-
|
|
182
|
+
const run = this.inferenceRuns.get(request.runId);
|
|
183
|
+
if (!run || run.conv !== conv)
|
|
184
|
+
throw new Error("This browser model call has ended.");
|
|
183
185
|
// SAFETY: the broker forwards Stagehand's own generate() parameters, unchanged apart from the JSON round trip.
|
|
184
|
-
value = await
|
|
186
|
+
value = await run.generate(request.params);
|
|
185
187
|
}
|
|
186
188
|
else {
|
|
187
189
|
if (!handlers.classify)
|
|
@@ -215,7 +217,7 @@ export class BrokerConnection {
|
|
|
215
217
|
this.send({ t: "open", conv, identity, inference: Boolean(handlers.generate), classify: Boolean(handlers.classify) });
|
|
216
218
|
}
|
|
217
219
|
/** Runs one call in the broker. A cancel is passed on, and the broker's own account of the outcome awaited briefly. */
|
|
218
|
-
async run(conv, params, context, ai, defaultBackend, signal) {
|
|
220
|
+
async run(conv, params, context, ai, defaultBackend, signal, generate) {
|
|
219
221
|
if (this.ended)
|
|
220
222
|
throw new BrowseToolError("session_lost", "The shared browser service stopped. Start again.");
|
|
221
223
|
if (params.action === "batch" && !this.features.includes("batch")) {
|
|
@@ -224,6 +226,8 @@ export class BrokerConnection {
|
|
|
224
226
|
const id = this.nextId++;
|
|
225
227
|
const waiter = Promise.withResolvers();
|
|
226
228
|
this.runs.set(id, waiter);
|
|
229
|
+
if (generate)
|
|
230
|
+
this.inferenceRuns.set(id, { conv, generate });
|
|
227
231
|
this.hold();
|
|
228
232
|
const onAbort = () => {
|
|
229
233
|
this.send({ t: "cancel", id });
|
|
@@ -236,6 +240,7 @@ export class BrokerConnection {
|
|
|
236
240
|
}
|
|
237
241
|
finally {
|
|
238
242
|
signal.removeEventListener("abort", onAbort);
|
|
243
|
+
this.inferenceRuns.delete(id);
|
|
239
244
|
this.runs.delete(id);
|
|
240
245
|
this.release();
|
|
241
246
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
/** Bumped on any incompatible message change; a client never talks to a broker of another protocol. */
|
|
3
|
-
export declare const BROKER_PROTOCOL =
|
|
3
|
+
export declare const BROKER_PROTOCOL = 2;
|
|
4
4
|
declare const json: z.ZodJSONSchema;
|
|
5
5
|
/** A JSON value as it crosses the socket. */
|
|
6
6
|
export type Json = z.infer<typeof json>;
|
|
@@ -154,6 +154,7 @@ export declare const brokerMessage: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
154
154
|
}, z.core.$strip>;
|
|
155
155
|
}, z.core.$strip>, z.ZodObject<{
|
|
156
156
|
kind: z.ZodLiteral<"generate">;
|
|
157
|
+
runId: z.ZodNumber;
|
|
157
158
|
params: z.ZodJSONSchema;
|
|
158
159
|
}, z.core.$strip>, z.ZodObject<{
|
|
159
160
|
kind: z.ZodLiteral<"classify">;
|
|
@@ -218,7 +219,7 @@ export declare const classifyAnswers: z.ZodRecord<z.ZodString, z.ZodDiscriminate
|
|
|
218
219
|
probability: z.ZodNumber;
|
|
219
220
|
}, z.core.$strip>], "type">>;
|
|
220
221
|
/** An error as it crosses the socket: a tool error keeps its code, an abort its name. */
|
|
221
|
-
export declare function errorBodyOf(cause: unknown): ErrorBody;
|
|
222
|
+
export declare function errorBodyOf(cause: unknown, redact?: (value: string) => string): ErrorBody;
|
|
222
223
|
/**
|
|
223
224
|
* The broker's socket for one shared browser key. In the user's runtime or temp directory (0700), named by a hash of the
|
|
224
225
|
* key, since a profile path can exceed the 104-byte socket path limit.
|
package/dist/broker-protocol.js
CHANGED
|
@@ -5,7 +5,8 @@ import { tmpdir } from "node:os";
|
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
/** Bumped on any incompatible message change; a client never talks to a broker of another protocol. */
|
|
8
|
-
|
|
8
|
+
// Older brokers return unredacted results. Do not silently share their browser.
|
|
9
|
+
export const BROKER_PROTOCOL = 2;
|
|
9
10
|
const json = z.json();
|
|
10
11
|
/** A failed batch's progress, as BatchProgress in session.ts. */
|
|
11
12
|
const batchProgress = z.object({
|
|
@@ -42,7 +43,7 @@ export const brokerMessage = z.union([
|
|
|
42
43
|
t: z.literal("ask"), cb: z.number().int(), conv: z.string(),
|
|
43
44
|
request: z.discriminatedUnion("kind", [
|
|
44
45
|
z.object({ kind: z.literal("config"), context: runContext.extend({ purpose: z.enum(["browser", "ai", "jev", "ask"]) }) }),
|
|
45
|
-
z.object({ kind: z.literal("generate"), params: json }),
|
|
46
|
+
z.object({ kind: z.literal("generate"), runId: z.number().int(), params: json }),
|
|
46
47
|
z.object({ kind: z.literal("classify"), model: z.string(), request: json }),
|
|
47
48
|
]),
|
|
48
49
|
}),
|
|
@@ -72,16 +73,19 @@ export const classifyAnswers = z.record(z.string(), z.discriminatedUnion("type",
|
|
|
72
73
|
z.object({ type: z.literal("bool"), probability: z.number() }),
|
|
73
74
|
]));
|
|
74
75
|
/** An error as it crosses the socket: a tool error keeps its code, an abort its name. */
|
|
75
|
-
export function errorBodyOf(cause) {
|
|
76
|
+
export function errorBodyOf(cause, redact = (value) => value) {
|
|
76
77
|
if (!(cause instanceof Error))
|
|
77
|
-
return { name: "Error", message: String(cause) };
|
|
78
|
+
return { name: "Error", message: redact(String(cause)) };
|
|
78
79
|
const code = "code" in cause && cause.name !== "AbortError" ? z.string().safeParse(cause.code) : undefined;
|
|
79
|
-
const body = { name: cause.name, message: cause.message };
|
|
80
|
+
const body = { name: redact(cause.name), message: redact(cause.message) };
|
|
80
81
|
if (code?.success)
|
|
81
|
-
body.code = code.data;
|
|
82
|
+
body.code = redact(code.data);
|
|
82
83
|
const batch = "batch" in cause ? batchProgress.safeParse(cause.batch) : undefined;
|
|
83
|
-
if (batch?.success)
|
|
84
|
+
if (batch?.success) {
|
|
84
85
|
body.batch = batch.data;
|
|
86
|
+
if (body.batch.error)
|
|
87
|
+
body.batch.error = { code: redact(body.batch.error.code), message: redact(body.batch.error.message) };
|
|
88
|
+
}
|
|
85
89
|
return body;
|
|
86
90
|
}
|
|
87
91
|
/**
|
package/dist/broker.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { chmodSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { createServer } from "node:net";
|
|
7
7
|
import { BROKER_FEATURES, BROKER_PROTOCOL, browseConfig, classifyAnswers, clientMessage, errorBodyOf, } from "./broker-protocol.js";
|
|
8
|
+
import { redactMetadata } from "./tool-results.js";
|
|
8
9
|
import { aiParameters, browserBatchParameters } from "./schema.js";
|
|
9
10
|
import { BrowseSession } from "./session.js";
|
|
10
11
|
const IDLE_EXIT_MS = 30_000;
|
|
@@ -22,10 +23,10 @@ function armIdle() {
|
|
|
22
23
|
idle = setTimeout(() => void stop(), IDLE_EXIT_MS);
|
|
23
24
|
}
|
|
24
25
|
/** A BrowserOutput as JSON: the image as base64, BigInt (cookie timestamps) as strings. */
|
|
25
|
-
function encodeOutput(output) {
|
|
26
|
+
function encodeOutput(output, redact) {
|
|
26
27
|
const { image, ...rest } = output;
|
|
27
|
-
|
|
28
|
-
|
|
28
|
+
return { ...redactMetadata(rest, redact),
|
|
29
|
+
...(image ? { image: Buffer.from(image).toString("base64") } : {}) };
|
|
29
30
|
}
|
|
30
31
|
class Connection {
|
|
31
32
|
socket;
|
|
@@ -76,12 +77,7 @@ class Connection {
|
|
|
76
77
|
}
|
|
77
78
|
open(message) {
|
|
78
79
|
const { conv } = message;
|
|
79
|
-
|
|
80
|
-
const value = await this.ask(conv, { kind: "generate", params: JSON.parse(JSON.stringify(params)) });
|
|
81
|
-
// SAFETY: the client returns its own Stagehand generate() result, unchanged apart from the JSON round trip.
|
|
82
|
-
return value;
|
|
83
|
-
};
|
|
84
|
-
return new BrowseSession(async ({ signal: _signal, ...context }) => browseConfig.parse(await this.ask(conv, { kind: "config", context })), message.inference ? { generate, describe: async () => "host model" } : undefined, message.classify ? async (model, request) => classifyAnswers.parse(await this.ask(conv, { kind: "classify", model, request: JSON.parse(JSON.stringify(request)) })) : undefined, message.identity, { profileBroker: false });
|
|
80
|
+
return new BrowseSession(async ({ signal: _signal, ...context }) => browseConfig.parse(await this.ask(conv, { kind: "config", context })), message.inference ? { describe: async () => "host model" } : undefined, message.classify ? async (model, request) => classifyAnswers.parse(await this.ask(conv, { kind: "classify", model, request: JSON.parse(JSON.stringify(request)) })) : undefined, message.identity, { profileBroker: false });
|
|
85
81
|
}
|
|
86
82
|
async handle(message) {
|
|
87
83
|
switch (message.t) {
|
|
@@ -103,11 +99,15 @@ class Connection {
|
|
|
103
99
|
try {
|
|
104
100
|
session.defaultBackend = message.defaultBackend;
|
|
105
101
|
const params = message.ai ? aiParameters.parse(message.params) : browserBatchParameters.parse(message.params);
|
|
106
|
-
const output = await session.run(params, message.context, controller.signal, message.ai)
|
|
107
|
-
|
|
102
|
+
const output = await session.run(params, message.context, controller.signal, message.ai && (() => async (args) => {
|
|
103
|
+
// Correlate callbacks to the originating run, not the conversation's latest model.
|
|
104
|
+
const value = await this.ask(message.conv, { kind: "generate", runId: message.id, params: JSON.parse(JSON.stringify(args)) });
|
|
105
|
+
return value;
|
|
106
|
+
}));
|
|
107
|
+
this.send({ t: "result", id: message.id, ok: true, output: encodeOutput(output, text => session.redact(text)) });
|
|
108
108
|
}
|
|
109
109
|
catch (error) {
|
|
110
|
-
this.send({ t: "result", id: message.id, ok: false, error: errorBodyOf(error) });
|
|
110
|
+
this.send({ t: "result", id: message.id, ok: false, error: errorBodyOf(error, text => session.redact(text)) });
|
|
111
111
|
}
|
|
112
112
|
finally {
|
|
113
113
|
this.controllers.delete(message.id);
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { BrowserParams } from "./schema.ts";
|
|
2
|
+
import type { HttpAuth } from "./http-auth.ts";
|
|
3
|
+
export interface BrowseConfig {
|
|
4
|
+
/** One exact origin and its credentials, resolved for an explicit isolated HTTP-auth start. */
|
|
5
|
+
httpAuth?: HttpAuth;
|
|
6
|
+
/** Allow this profile to read the initial URL's exact origin from the locally installed native helper. */
|
|
7
|
+
httpAuthStore?: {
|
|
8
|
+
hosted?: boolean;
|
|
9
|
+
origin?: string;
|
|
10
|
+
};
|
|
11
|
+
apiKey?: string;
|
|
12
|
+
projectId?: string;
|
|
13
|
+
model?: string;
|
|
14
|
+
modelApiKey?: string;
|
|
15
|
+
/** Vercel AI Gateway key for JEV's default classifier; resolvers should load it only for purpose "jev". */
|
|
16
|
+
jevApiKey?: string;
|
|
17
|
+
/**
|
|
18
|
+
* Classifier for JEV targeting: absent or `vercel` (Jev on Vercel AI Gateway), `workers-ai` (Jev 1.14 on Workers AI)
|
|
19
|
+
* or `workers-ai/<model>`, or a host classifier as `<provider>/<id>`.
|
|
20
|
+
*/
|
|
21
|
+
jevModel?: string;
|
|
22
|
+
/** Classifier for ask's bool and choice fields: absent is Clef on Workers AI; takes the same values as jevModel. */
|
|
23
|
+
askModel?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Cloudflare account and Workers AI token for ask, and for JEV on Workers AI; resolvers should load the token only for
|
|
26
|
+
* purposes "ask" and "jev".
|
|
27
|
+
*/
|
|
28
|
+
cloudflareAccountId?: string;
|
|
29
|
+
cloudflareApiKey?: string;
|
|
30
|
+
/** Optional profile-specific file containing only saved-context identifiers. */
|
|
31
|
+
contextHistoryPath?: string;
|
|
32
|
+
/** Browserbase region for new sessions; validated against the SDK's regions. Absent uses Browserbase's default (us-west-2). */
|
|
33
|
+
region?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Chrome user data directory for local launches, so logins and installed extensions persist across launches. Absent
|
|
36
|
+
* launches a temporary profile that close deletes. Only one browser can use the directory at a time.
|
|
37
|
+
*/
|
|
38
|
+
localUserDataDir?: string;
|
|
39
|
+
/** Chrome or Chromium executable for local launches; absent uses CHROME_PATH or Stagehand's discovery of an installed Chrome. */
|
|
40
|
+
localExecutablePath?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Bare domains, each with its subdomains, that this profile's browsers may reach; every other http(s) request fails,
|
|
43
|
+
* page resources included. A start can narrow the list, never widen it.
|
|
44
|
+
*/
|
|
45
|
+
allowedDomains?: string[];
|
|
46
|
+
/** Bare domains, each with its subdomains, that this profile's browsers never reach; a start can add more. */
|
|
47
|
+
blockedDomains?: string[];
|
|
48
|
+
/** Browserbase navigation policy for hosted sessions (browserSettings.riskPolicyId); the project must enforce policies. */
|
|
49
|
+
navigationPolicyId?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Browsers start can attach to by name (endpoint): a DevTools URL, headers for an authenticated gateway (secrets that
|
|
52
|
+
* never reach results), and the URL Stagehand's in-browser extension uses when the browser runs on another machine.
|
|
53
|
+
*/
|
|
54
|
+
remoteBrowsers?: Record<string, RemoteBrowser>;
|
|
55
|
+
/**
|
|
56
|
+
* The user's own browser, through OpenCode Browse: `command` is the argv that runs `browse mcp`, on this machine or
|
|
57
|
+
* over SSH on the machine with the browser. When set, a local start that names no cdpUrl, endpoint, or headless works
|
|
58
|
+
* in that browser instead of launching one.
|
|
59
|
+
*/
|
|
60
|
+
realBrowser?: {
|
|
61
|
+
command: string[];
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** A browser to attach to. extensionCdpUrl is the browser-level DevTools URL the browser itself reaches without headers. */
|
|
65
|
+
export interface RemoteBrowser {
|
|
66
|
+
cdpUrl: string;
|
|
67
|
+
headers?: Record<string, string>;
|
|
68
|
+
extensionCdpUrl?: string;
|
|
69
|
+
}
|
|
70
|
+
/** A browser's domain fence as bare domains, each covering its subdomains. */
|
|
71
|
+
export interface DomainLists {
|
|
72
|
+
allowedDomains?: string[];
|
|
73
|
+
blockedDomains?: string[];
|
|
74
|
+
}
|
|
75
|
+
/** The profile's domain lists, narrowed by start: start's allowed domains must fall inside the profile's, and blocked ones add up. */
|
|
76
|
+
export declare function domainLists(config: BrowseConfig, start: Pick<BrowserParams, "allowedDomains" | "blockedDomains">): DomainLists | undefined;
|
|
77
|
+
/** Why the fence refuses a URL's host, or undefined when it lets the URL through. */
|
|
78
|
+
export declare function fenced(url: string, lists: DomainLists | undefined): string | undefined;
|
|
79
|
+
/** Stagehand matches exact hosts and `*.` subdomains, so each bare domain becomes both. */
|
|
80
|
+
export declare function stagehandPolicy(lists: DomainLists): {
|
|
81
|
+
allowedDomains?: string[] | undefined;
|
|
82
|
+
blockedDomains?: string[] | undefined;
|
|
83
|
+
};
|
|
84
|
+
export interface ConfigurationContext {
|
|
85
|
+
/** Resolve origin credentials for an explicitly requested isolated launch. */
|
|
86
|
+
httpAuth?: true;
|
|
87
|
+
sessionId: string;
|
|
88
|
+
profile: string;
|
|
89
|
+
cwd: string;
|
|
90
|
+
signal: AbortSignal;
|
|
91
|
+
purpose: "browser" | "ai" | "jev" | "ask";
|
|
92
|
+
/** Selected browser backend; local controls do not need Browserbase credentials. */
|
|
93
|
+
backend?: "browserbase" | "local";
|
|
94
|
+
/**
|
|
95
|
+
* For purposes "jev" and "ask", the classifier chosen with /browse jev-model or ask-model. It replaces the returned jevModel or askModel,
|
|
96
|
+
* so load the credentials it needs.
|
|
97
|
+
*/
|
|
98
|
+
classifier?: string;
|
|
99
|
+
}
|
|
100
|
+
export type ConfigResolver = (context: ConfigurationContext) => BrowseConfig | Promise<BrowseConfig>;
|
|
101
|
+
export declare function environmentConfig(scope?: Pick<ConfigurationContext, "httpAuth">): BrowseConfig;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { normalizeCookieDomains } from "./browser-cookies.js";
|
|
2
|
+
import { BrowseToolError, messageOf } from "./errors.js";
|
|
3
|
+
/** Whether `domain` is `parent` or one of its subdomains. */
|
|
4
|
+
function within(domain, parent) {
|
|
5
|
+
return domain === parent || domain.endsWith(`.${parent}`);
|
|
6
|
+
}
|
|
7
|
+
/** The profile's domain lists, narrowed by start: start's allowed domains must fall inside the profile's, and blocked ones add up. */
|
|
8
|
+
export function domainLists(config, start) {
|
|
9
|
+
const normalize = (domains, setting) => {
|
|
10
|
+
if (!domains?.length)
|
|
11
|
+
return undefined;
|
|
12
|
+
try {
|
|
13
|
+
return normalizeCookieDomains(domains);
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
throw new BrowseToolError("configuration", `${setting}: ${messageOf(error)}`);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const profileAllowed = normalize(config.allowedDomains, "the profile's allowedDomains");
|
|
20
|
+
const startAllowed = normalize(start.allowedDomains, "allowedDomains");
|
|
21
|
+
if (profileAllowed && startAllowed) {
|
|
22
|
+
const outside = startAllowed.filter(domain => !profileAllowed.some(parent => within(domain, parent)));
|
|
23
|
+
if (outside.length)
|
|
24
|
+
throw new BrowseToolError("domain_policy_widened", `allowedDomains can only narrow this profile's allowed domains (${profileAllowed.join(", ")}); ${outside.join(", ")} is outside them.`);
|
|
25
|
+
}
|
|
26
|
+
const allowedDomains = startAllowed ?? profileAllowed;
|
|
27
|
+
const blockedDomains = [...new Set([...normalize(config.blockedDomains, "the profile's blockedDomains") ?? [], ...normalize(start.blockedDomains, "blockedDomains") ?? []])];
|
|
28
|
+
if (!allowedDomains && !blockedDomains.length)
|
|
29
|
+
return undefined;
|
|
30
|
+
return { ...(allowedDomains ? { allowedDomains } : {}), ...(blockedDomains.length ? { blockedDomains } : {}) };
|
|
31
|
+
}
|
|
32
|
+
/** Why the fence refuses a URL's host, or undefined when it lets the URL through. */
|
|
33
|
+
export function fenced(url, lists) {
|
|
34
|
+
if (!lists || !URL.canParse(url))
|
|
35
|
+
return undefined;
|
|
36
|
+
const host = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
|
|
37
|
+
if (lists.blockedDomains?.some(domain => within(host, domain)))
|
|
38
|
+
return `${host} is in this browser's blocked domains (${lists.blockedDomains.join(", ")})`;
|
|
39
|
+
if (lists.allowedDomains && !lists.allowedDomains.some(domain => within(host, domain)))
|
|
40
|
+
return `${host} is outside this browser's allowed domains (${lists.allowedDomains.join(", ")})`;
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
/** Stagehand matches exact hosts and `*.` subdomains, so each bare domain becomes both. */
|
|
44
|
+
export function stagehandPolicy(lists) {
|
|
45
|
+
const patterns = (domains) => domains.flatMap(domain => [domain, `*.${domain}`]);
|
|
46
|
+
return {
|
|
47
|
+
...(lists.allowedDomains ? { allowedDomains: patterns(lists.allowedDomains) } : {}),
|
|
48
|
+
...(lists.blockedDomains ? { blockedDomains: patterns(lists.blockedDomains) } : {}),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** A comma- or space-separated domain list from the environment; empty counts as unset. */
|
|
52
|
+
function domainList(value) {
|
|
53
|
+
const domains = value?.split(/[\s,]+/).filter(Boolean);
|
|
54
|
+
return domains?.length ? domains : undefined;
|
|
55
|
+
}
|
|
56
|
+
export function environmentConfig(scope) {
|
|
57
|
+
return {
|
|
58
|
+
...(scope?.httpAuth && (process.env.BROWSE_HTTP_AUTH_USERNAME || process.env.BROWSE_HTTP_AUTH_PASSWORD) ? { httpAuth: {
|
|
59
|
+
origin: process.env.BROWSE_HTTP_AUTH_ORIGIN ?? "", username: process.env.BROWSE_HTTP_AUTH_USERNAME ?? "",
|
|
60
|
+
password: process.env.BROWSE_HTTP_AUTH_PASSWORD ?? "", hosted: process.env.BROWSE_HTTP_AUTH_HOSTED === "true",
|
|
61
|
+
} } : {}),
|
|
62
|
+
...(scope?.httpAuth && process.env.BROWSE_HTTP_AUTH_USE_STORE === "true"
|
|
63
|
+
? { httpAuthStore: { hosted: process.env.BROWSE_HTTP_AUTH_HOSTED === "true", origin: process.env.BROWSE_HTTP_AUTH_ORIGIN } } : {}),
|
|
64
|
+
apiKey: process.env.BROWSERBASE_API_KEY ?? "",
|
|
65
|
+
projectId: process.env.BROWSERBASE_PROJECT_ID ?? "",
|
|
66
|
+
model: process.env.STAGEHAND_MODEL,
|
|
67
|
+
modelApiKey: process.env.STAGEHAND_MODEL_API_KEY,
|
|
68
|
+
jevApiKey: process.env.AI_GATEWAY_API_KEY,
|
|
69
|
+
cloudflareAccountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
|
70
|
+
cloudflareApiKey: process.env.CLOUDFLARE_API_KEY,
|
|
71
|
+
region: process.env.BROWSERBASE_REGION,
|
|
72
|
+
allowedDomains: domainList(process.env.BROWSE_ALLOWED_DOMAINS),
|
|
73
|
+
blockedDomains: domainList(process.env.BROWSE_BLOCKED_DOMAINS),
|
|
74
|
+
navigationPolicyId: process.env.BROWSERBASE_NAVIGATION_POLICY_ID,
|
|
75
|
+
jevModel: process.env.BROWSE_JEV_MODEL,
|
|
76
|
+
askModel: process.env.BROWSE_ASK_MODEL,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
interface ContextRecord {
|
|
2
|
+
contextId: string;
|
|
3
|
+
integration: string;
|
|
4
|
+
projectId: string;
|
|
5
|
+
profile: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function contextRegistry(path: string | undefined, integration: string): string;
|
|
8
|
+
export declare function rememberContext(path: string, record: ContextRecord): Promise<void>;
|
|
9
|
+
export declare function knownContext(path: string, expected: ContextRecord): Promise<boolean>;
|
|
10
|
+
export {};
|
package/dist/contexts.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { appendFile, mkdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
export function contextRegistry(path, integration) {
|
|
6
|
+
return path ?? join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "browse-core", createHash("sha256").update(integration).digest("hex"), "contexts.jsonl");
|
|
7
|
+
}
|
|
8
|
+
export async function rememberContext(path, record) {
|
|
9
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
10
|
+
await appendFile(path, JSON.stringify(record) + "\n", { mode: 0o600 });
|
|
11
|
+
}
|
|
12
|
+
export async function knownContext(path, expected) {
|
|
13
|
+
try {
|
|
14
|
+
return (await readFile(path, "utf8")).split("\n").some(line => {
|
|
15
|
+
try {
|
|
16
|
+
const record = JSON.parse(line);
|
|
17
|
+
return Object.entries(expected).every(([k, value]) => record[k] === value);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** How far a batch got. */
|
|
2
|
+
export interface BatchProgress {
|
|
3
|
+
total: number;
|
|
4
|
+
/** Steps confirmed to have completed; absent when a lost reply, deadline, or cancellation leaves that unknown. */
|
|
5
|
+
completed?: number;
|
|
6
|
+
/** Zero-based index of the step that stopped the batch. */
|
|
7
|
+
failedIndex?: number;
|
|
8
|
+
/** True when steps may have run without being confirmed: inspect the page before repeating anything. */
|
|
9
|
+
outcomeUnknown: boolean;
|
|
10
|
+
error?: {
|
|
11
|
+
code: string;
|
|
12
|
+
message: string;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export declare class BrowseToolError extends Error {
|
|
16
|
+
readonly code: string;
|
|
17
|
+
readonly batch?: BatchProgress | undefined;
|
|
18
|
+
/** `batch` is set on a failed batch call. */
|
|
19
|
+
constructor(code: string, message: string, batch?: BatchProgress | undefined);
|
|
20
|
+
}
|
|
21
|
+
/** Stagehand reports an exception a page script threw as "Uncaught ..."; anything else is not a script error. */
|
|
22
|
+
export declare function scriptError(message: string): BrowseToolError | undefined;
|
|
23
|
+
export declare function messageOf(error: unknown): string;
|
|
24
|
+
/** Gives recurring Stagehand failures a code and a next step; anything else passes through unchanged. */
|
|
25
|
+
export declare function translate(error: unknown): unknown;
|
|
26
|
+
export declare function abortError(message?: string): BrowseToolError;
|
|
27
|
+
/** Stops waiting immediately; the caller is responsible for closing the remote browser. */
|
|
28
|
+
export declare function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
|
|
29
|
+
export declare function deadline<T>(promise: Promise<T>, ms: number): Promise<T>;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export class BrowseToolError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
batch;
|
|
4
|
+
/** `batch` is set on a failed batch call. */
|
|
5
|
+
constructor(code, message, batch) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.batch = batch;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** Stagehand reports an exception a page script threw as "Uncaught ..."; anything else is not a script error. */
|
|
12
|
+
export function scriptError(message) {
|
|
13
|
+
if (!/^Uncaught\b/.test(message))
|
|
14
|
+
return undefined;
|
|
15
|
+
const detail = message.replace(/^Uncaught\s*(?:\(in promise\)\s*)?/, "").slice(0, 500);
|
|
16
|
+
return new BrowseToolError("script_error", (detail
|
|
17
|
+
? `The script threw: ${detail}.`
|
|
18
|
+
: "The script threw; Stagehand hides the exception message. To see it, wrap the script: (() => { try { ... } catch (e) { return String(e) } })().")
|
|
19
|
+
+ " Side effects before the throw may have happened.");
|
|
20
|
+
}
|
|
21
|
+
export function messageOf(error) {
|
|
22
|
+
return error instanceof Error ? error.message : String(error);
|
|
23
|
+
}
|
|
24
|
+
/** Gives recurring Stagehand failures a code and a next step; anything else passes through unchanged. */
|
|
25
|
+
export function translate(error) {
|
|
26
|
+
if (error instanceof BrowseToolError)
|
|
27
|
+
return error;
|
|
28
|
+
const message = messageOf(error);
|
|
29
|
+
if (/^Request timed out\.?$/i.test(message))
|
|
30
|
+
return new BrowseToolError("timeout", "The browser service timed out; the action may have completed. Inspect status and the page before retrying.");
|
|
31
|
+
if (/Node does not have a layout object/.test(message))
|
|
32
|
+
return new BrowseToolError("not_actionable", "The target has no rendered box. Use select on a native dropdown, or choose a visible element from a fresh snapshot.");
|
|
33
|
+
if (/ERR_BLOCKED_BY_CLIENT/.test(message))
|
|
34
|
+
return new BrowseToolError("domain_blocked", "The browser's domain policy blocked this request. status lists the allowed and blocked domains; close and start again to change them, or ask the user to change the profile's.");
|
|
35
|
+
if (/^No Page found|^Stagehand callback batch page was not found:|^Stagehand has no active page\.|^Stagehand page ".+" was not found;/.test(message))
|
|
36
|
+
return new BrowseToolError("tab_missing", "The tab closed or navigated away during the action. List tabs, select one, and take a snapshot.");
|
|
37
|
+
if (/^Connection error\.?$/.test(message))
|
|
38
|
+
return new BrowseToolError("network_error", "Could not reach Browserbase. Retry once; if it persists, check this machine's network.");
|
|
39
|
+
// Stagehand admits one client per browser and refuses a second while the first is connected.
|
|
40
|
+
if (/A Stagehand client is already connected/.test(message))
|
|
41
|
+
return new BrowseToolError("browser_in_use", "Another Stagehand client is connected to this browser, and a browser takes one at a time: a conversation on another machine, or another tool. Close the browser there, then start again.");
|
|
42
|
+
if (/does not support the client watchdog|requires Chrome 137 or later/.test(message))
|
|
43
|
+
return new BrowseToolError("attach_failed", "This browser cannot take this version of Stagehand: it needs Chrome 137 or newer and the Stagehand extension this tool ships. Update the browser and reinstall the extension in it, then start again.");
|
|
44
|
+
// Stagehand's own per-request limit: the tab stopped answering, typically a busy script.
|
|
45
|
+
const rpc = /^RPC response timed out: (\S+)/.exec(message);
|
|
46
|
+
if (rpc)
|
|
47
|
+
return new BrowseToolError("timeout", `Stagehand got no reply for ${rpc[1]} in time; the action may have completed. The tab may be busy: check status, and if it reports tab_unresponsive, call tab_new and tab_close that tab.`);
|
|
48
|
+
// Page-level waits and navigations that ran out of time, in Stagehand's wording, sometimes wrapped as a page exception.
|
|
49
|
+
const pageTimeout = /^(?:Uncaught (?:\(in promise\) )?(?:Error: )?)?(.*(?:timed out after \d+ ?ms|Timeout \d+ ?ms exceeded).*)$/s.exec(message);
|
|
50
|
+
if (pageTimeout)
|
|
51
|
+
return new BrowseToolError("timeout", `${pageTimeout[1].slice(0, 300)}. The browser was kept; take a snapshot to check the page, or raise timeoutMs.`);
|
|
52
|
+
// Strict structured output (OpenAI models on Model Gateway) rejects schemas with optional properties.
|
|
53
|
+
if (/^Invalid schema for response_format/.test(message)) {
|
|
54
|
+
return new BrowseToolError("invalid_arguments", `The model rejected the extract schema: ${message.slice(0, 300)} List every property in required, and allow null for values that may be missing.`);
|
|
55
|
+
}
|
|
56
|
+
if (/extension world not ready for frame/i.test(message)) {
|
|
57
|
+
return new BrowseToolError("frame_unavailable", "Stagehand cannot reach that document: legacy <frame> pages, browser error pages, and frames still loading are unsupported. Take a snapshot and use its refs, or wait for the page and retry.");
|
|
58
|
+
}
|
|
59
|
+
return error;
|
|
60
|
+
}
|
|
61
|
+
export function abortError(message = "Operation cancelled.") {
|
|
62
|
+
return new BrowseToolError("cancelled", message);
|
|
63
|
+
}
|
|
64
|
+
/** Stops waiting immediately; the caller is responsible for closing the remote browser. */
|
|
65
|
+
export function abortable(promise, signal) {
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
const abort = () => reject(signal.reason ?? abortError());
|
|
68
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
69
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
70
|
+
if (signal.aborted)
|
|
71
|
+
abort();
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
export async function deadline(promise, ms) {
|
|
75
|
+
const controller = new AbortController();
|
|
76
|
+
const timer = setTimeout(() => controller.abort(new BrowseToolError("timeout", "Browser cleanup timed out.")), ms);
|
|
77
|
+
try {
|
|
78
|
+
return await abortable(promise, controller.signal);
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ClientGenerate } from "./session.ts";
|
|
2
|
+
export interface HostModelRequest {
|
|
3
|
+
systemPrompt: string[];
|
|
4
|
+
messages: {
|
|
5
|
+
role: "user";
|
|
6
|
+
content: ({
|
|
7
|
+
type: "text";
|
|
8
|
+
text: string;
|
|
9
|
+
} | {
|
|
10
|
+
type: "image";
|
|
11
|
+
data: string;
|
|
12
|
+
mimeType: string;
|
|
13
|
+
})[];
|
|
14
|
+
}[];
|
|
15
|
+
temperature?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface HostModelReply {
|
|
18
|
+
text: string;
|
|
19
|
+
inputTokens: number;
|
|
20
|
+
outputTokens: number;
|
|
21
|
+
cachedInputTokens: number;
|
|
22
|
+
}
|
|
23
|
+
/** Stagehand's single-turn model protocol. The host owns model selection, cancellation, credentials and cost accounting. */
|
|
24
|
+
export declare function hostModelGenerate(complete: (request: HostModelRequest) => Promise<HostModelReply>): ClientGenerate;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Stagehand's single-turn model protocol. The host owns model selection, cancellation, credentials and cost accounting. */
|
|
2
|
+
export function hostModelGenerate(complete) {
|
|
3
|
+
return async (params) => {
|
|
4
|
+
if ("tools" in params && params.tools?.length)
|
|
5
|
+
throw new Error("Stagehand tool calls are not supported on host models.");
|
|
6
|
+
const messages = params.messages.map(message => {
|
|
7
|
+
if (message.role !== "user")
|
|
8
|
+
throw new Error("A host model accepts only single-turn Stagehand requests.");
|
|
9
|
+
const blocks = Array.isArray(message.content) ? message.content : [message.content];
|
|
10
|
+
return { role: "user", content: blocks.map(block => {
|
|
11
|
+
if (block.type === "text")
|
|
12
|
+
return { type: "text", text: block.text };
|
|
13
|
+
if (block.type === "image")
|
|
14
|
+
return { type: "image", mimeType: block.mimeType, data: block.data };
|
|
15
|
+
throw new Error("Unsupported Stagehand content: " + block.type);
|
|
16
|
+
}) };
|
|
17
|
+
});
|
|
18
|
+
const schema = params.responseFormat?.type === "json_schema" ? params.responseFormat.schema : undefined;
|
|
19
|
+
const systemPrompt = params.systemPrompt ? [params.systemPrompt] : [];
|
|
20
|
+
if (schema !== undefined)
|
|
21
|
+
systemPrompt.push("Reply with only one JSON value matching this JSON Schema, with no prose:\n" + JSON.stringify(schema));
|
|
22
|
+
const { text: raw, inputTokens, outputTokens, cachedInputTokens } = await complete({ systemPrompt, messages, temperature: params.temperature });
|
|
23
|
+
const text = raw.trim(), content = { type: "text", text }, usage = { inputTokens, outputTokens, cachedInputTokens, totalTokens: inputTokens + outputTokens };
|
|
24
|
+
if (schema === undefined)
|
|
25
|
+
return { role: "assistant", content, outputFormat: "text", usage };
|
|
26
|
+
let structuredContent;
|
|
27
|
+
try {
|
|
28
|
+
structuredContent = JSON.parse(/^```(?:json)?\s*([\s\S]*?)\s*```$/.exec(text)?.[1] ?? text);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new Error("The host model did not return valid JSON for Stagehand.");
|
|
32
|
+
}
|
|
33
|
+
return { role: "assistant", content, outputFormat: "json_schema", structuredContent, usage };
|
|
34
|
+
};
|
|
35
|
+
}
|