> ## Documentation Index
> Fetch the complete documentation index at: https://docs-preview.webcompute.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK reference

> Reference the Webcompute TypeScript SDK entry point, client configuration, errors, warnings, and exported symbols.

The TypeScript SDK is the canonical Webcompute SDK today.

```ts theme={null}
import { Web, WebcomputeError } from "@webcompute/sdk";

const web = new Web({
  apiKey: process.env.WEBCOMPUTE_API_KEY!,
});
```

This reference covers the SDK entry point, shared configuration, errors, warnings, and export inventory. The deeper references cover:

| Area                                                                    | Page                                                                  |
| ----------------------------------------------------------------------- | --------------------------------------------------------------------- |
| Browser agents                                                          | [SDK agent reference](/reference/sdk-agent-reference)                 |
| Managed browsers and advanced browser-code execution                    | [SDK browser reference](/reference/sdk-browser-reference)             |
| Files, downloads, dialogs, permissions, recordings, events, and CAPTCHA | [SDK resources reference](/reference/sdk-resources-reference)         |
| Deterministic scrape, screenshot, and PDF actions                       | [SDK quick actions reference](/reference/sdk-quick-actions-reference) |
| Browser navigation policy                                               | [Policy reference](/reference/policy-reference)                       |
| Custom proxies                                                          | [Proxy reference](/reference/proxy-reference)                         |

<Note>
  The Python package currently contains a stub module only. Use the TypeScript SDK for the full public SDK surface. Python users should call the REST API directly until the Python SDK graduates from stub status.
</Note>

## Constructor

```ts theme={null}
new Web(options?: Partial<WebcomputeConfig>)
```

`Web` exposes browser lifecycle helpers, deterministic quick actions, health checks, and `web.agent()`.

| Property or method | Signature                                                              | Description                                    |
| ------------------ | ---------------------------------------------------------------------- | ---------------------------------------------- |
| `web.browser`      | `WebBrowserResource`                                                   | Managed browser lifecycle and browser handles. |
| `web.health.check` | `() => Promise<{ status: string; version?: string; uptime?: number }>` | Gateway health check.                          |
| `web.scrape`       | `(options: ScrapeInput) => Promise<ScrapeResponse>`                    | Read a URL through an ephemeral browser.       |
| `web.screenshot`   | `(options: ScreenshotOptions) => Promise<ScreenshotResponse>`          | Capture an image through an ephemeral browser. |
| `web.pdf`          | `(options: PdfOptions) => Promise<PdfResponse>`                        | Generate a PDF through an ephemeral browser.   |
| `web.agent`        | `<TOutput = unknown>(config: WebAgentConfig<TOutput>) => WebAgent`     | Create a model-backed browser agent.           |

## `WebcomputeConfig`

| Field         | Type                      | Default                                                 | Description                                                                                                                                   |
| ------------- | ------------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`      | `string`                  | `WEBCOMPUTE_API_KEY`                                    | Webcompute API key. Required through either explicit config or environment.                                                                   |
| `serverUrl`   | `string`                  | `WEBCOMPUTE_SERVER_URL` or `https://api.webcompute.dev` | Gateway base URL. `http` is accepted only for localhost or loopback hosts.                                                                    |
| `timeoutMs`   | `number`                  | `WEBCOMPUTE_TIMEOUT` or `120000`                        | Default request timeout in milliseconds.                                                                                                      |
| `retryConfig` | `RetryConfig`             | `DEFAULT_RETRY_CONFIG`                                  | Retry behavior for retryable HTTP failures.                                                                                                   |
| `debug`       | `boolean`                 | `WEBCOMPUTE_DEBUG === "true"`                           | Enables debug logging.                                                                                                                        |
| `policy`      | `BrowserNavigationPolicy` | None                                                    | Default browser policy for browsers and quick actions.                                                                                        |
| `onWarning`   | `WarningCallback`         | None                                                    | Callback invoked once per structured warning returned by Gateway responses. Callback errors are caught and logged only when debug is enabled. |

## Errors

All SDK HTTP errors extend `WebcomputeError`.

```ts theme={null}
try {
  const browser = await web.browser.get("browser_missing");
} catch (error) {
  if (error instanceof WebcomputeError) {
    console.error(error.code, error.type, error.next, error.retryable);
  }
}
```

`WebcomputeError` fields:

| Field        | Type                              | Description                                                                                                                               |
| ------------ | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `statusCode` | `number`                          | HTTP status code.                                                                                                                         |
| `type`       | `SdkErrorType`                    | Normalized category such as `authentication`, `not_found`, `rate_limit`, or `upstream_timeout`.                                           |
| `code`       | `SdkErrorCode`                    | Normalized machine code. Legacy codes are mapped to current codes.                                                                        |
| `requestId`  | `string \| undefined`             | Request ID when provided by the server.                                                                                                   |
| `retryable`  | `boolean`                         | Whether the SDK considers the error retryable.                                                                                            |
| `next`       | `SdkErrorNext`                    | Suggested next action such as `authenticate`, `retry`, `retry_after`, `refresh_browser`, `change_request`, `contact_support`, or `abort`. |
| `param`      | `string \| undefined`             | Request parameter associated with a validation failure when known.                                                                        |
| `details`    | `Record<string, unknown> \| null` | Redacted structured details.                                                                                                              |
| `helpUrl`    | `string \| undefined`             | Documentation URL for common errors when available.                                                                                       |

Exported error classes:

| Class                     | Common status | Description                                     |
| ------------------------- | ------------- | ----------------------------------------------- |
| `AuthenticationError`     | `401`         | Missing or invalid API key.                     |
| `ValidationError`         | `400`         | Invalid request parameters.                     |
| `NotFoundError`           | `404`         | Browser or artifact was not found.              |
| `ConflictError`           | `409`         | Operation conflicts with current browser state. |
| `RateLimitError`          | `429`         | Rate limit or quota backoff case.               |
| `PayloadTooLargeError`    | `413`         | Request or payload exceeds size limits.         |
| `ResourceLimitError`      | varies        | Resource or concurrency limit.                  |
| `TimeoutError`            | `504`         | Upstream timeout.                               |
| `BrowserUnavailableError` | varies        | Browser runtime is unavailable or unhealthy.    |
| `RequestAbortedError`     | varies        | Caller aborted the request.                     |
| `ConnectionError`         | varies        | Network or connection failure.                  |
| `InternalError`           | `5xx`         | Server-side failure.                            |
| `BrowserPolicyTipError`   | `400`         | Browser policy produced a blocking policy tip.  |

## Warnings

Gateway responses may include structured warnings. The SDK exposes them in response fields where the response type includes `warnings`, and can centralize handling through `onWarning`.

```ts theme={null}
const web = new Web({
  apiKey: process.env.WEBCOMPUTE_API_KEY!,
  onWarning: (warning, context) => {
    console.warn(context.path, warning.code, warning.message);
  },
});
```

Use `parseWarning` when you need to normalize unknown warning payloads, and `redactValueForObservability` before logging data that may contain credentials, tokens, cookies, proxy URLs, signed URLs, or local file paths.

## MCP prompt helper

`mcpPrompt` returns SDK-owned guidance for parent agents that connect to the
self-hosted Webcompute MCP server.

```ts theme={null}
import { mcpPrompt } from "@webcompute/sdk";

mcpPrompt("agent");
mcpPrompt("runtime");
mcpPrompt("all");
mcpPrompt({ surface: "agent", toolPrefix: "mcp__webcompute__" });
```

`mcpPrompt()` equals `mcpPrompt("runtime")`. Agent-mode examples should call
`mcpPrompt("agent")` explicitly.

`WebcomputeMcpPromptOptions` supports:

| Field            | Type                         | Description                                           |
| ---------------- | ---------------------------- | ----------------------------------------------------- |
| `surface`        | `WebcomputeMcpPromptSurface` | `agent`, `runtime`, or `all`.                         |
| `toolPrefix`     | `string`                     | Prefix tool names for hosts such as Claude Agent SDK. |
| `toolNames`      | `object`                     | Override MCP tool names when a host remaps them.      |
| `allowedDomains` | `string[]`                   | Include a domain-boundary reminder.                   |
| `close`          | `created \| never`           | Browser cleanup guidance for runtime mode.            |

## Export inventory

This inventory is generated from `packages/sdk-typescript/src/index.ts` and grouped by reader task.

### Client and config

`Web`, `WebcomputeConfig`, `RetryConfig`, `DEFAULT_RETRY_CONFIG`, `ErrorResponseBody`.

### Agent exports

`WebAgent`, `WebAgentApprovalMode`, `WebAgentApprovalRisk`, `WebAgentArtifact`, `WebAgentArtifactOptions`, `WebAgentBrowserConfig`, `WebAgentCaptchaResolutionOptions`, `WebAgentCaptchaResolutionSummary`, `WebAgentCaptureOptions`, `WebAgentCodePolicy`, `WebAgentConfig`, `WebAgentConfirmationDecision`, `WebAgentConfirmationHandler`, `WebAgentConfirmationRequest`, `WebAgentEnvironment`, `WebAgentError`, `WebAgentJsonSchemaObject`, `WebAgentModelAccessFlags`, `WebAgentModelConfig`, `WebAgentModelProfile`, `WebAgentModelProfileConfig`, `WebAgentModelRoute`, `WebAgentRawJsonSchema`, `WebAgentResult`, `WebAgentRoute`, `WebAgentRunInput`, `WebAgentSchema`, `WebAgentSchemaIssue`, `WebAgentSchemaMetadata`, `WebAgentSchemaValidationResult`, `WebAgentSession`, `WebAgentStandardSchema`, `WebAgentStep`, `WebAgentStreamEvent`, `WebAgentTranscriptItem`, `WebAgentToolCall`, `WebAgentToolCompletionSummary`, `WebAgentToolProgressReturnedSummary`, `WebAgentToolProgressSummary`, `WebAgentToolResult`, `WebAgentToolResultSummary`, `WebAgentToolResultSummaryItem`, `WebAgentUsage`, `WebAgentVariable`, `WebAgentVariables`, `WebAgentZodLikeSchema`.

Agent helper exports:

`inferWebAgentModelRoute`, `mcpPrompt`, `normalizeOutputSchema`, `normalizeWebAgentModelProfile`, `parseWebAgentModelRoute`, `resolveWebAgentModelAccess`, `WEB_AGENT_APPROVAL_RISK_VALUES`, `webAgentModelConfigForAccess`, `webAgentModelSetupMessage`.

Model-profile helpers work with profile-shaped config supplied by application code. They do not load CLI model profiles automatically; see [SDK agent reference](/reference/sdk-agent-reference) for explicit agent model config.

### Model profile exports

`NormalizedWebAgentModelProfile`, `ResolvedWebAgentModelAccess`, `ResolveWebAgentModelAccessOptions`.

### MCP prompt exports

`WEBCOMPUTE_MCP_PROMPTS`, `WebcomputeMcpPromptDefinition`, `WebcomputeMcpPromptOptions`, `WebcomputeMcpPromptSurface`.

### Browser and runtime exports

`Browser`, `BrowserId`, `BrowserArtifactListOptions`, `BrowserCaptcha`, `BrowserCaptchaResolveOptions`, `BrowserCreateOptions`, `BrowserDialogs`, `BrowserDownloadSaveOptions`, `BrowserDownloadSaveResult`, `BrowserDownloads`, `BrowserEvent`, `BrowserEventCategory`, `BrowserEventSeverity`, `BrowserEventStreamOptions`, `BrowserEventsOptions`, `BrowserEventType`, `BrowserEventVisibility`, `BrowserFiles`, `BrowserLifecycleMeta`, `BrowserLifecycleResponse`, `BrowserListOptions`, `BrowserListResponse`, `BrowserNavigationPolicy`, `BrowserPageSummary`, `BrowserPermissions`, `BrowserPlaywright`, `BrowserPlaywrightActivityCaptureOptions`, `BrowserPlaywrightExecuteOptions`, `BrowserPlaywrightExecuteRequest`, `BrowserPlaywrightExecuteResponse`, `BrowserPlaywrightExecutionActivity`, `BrowserRecordings`, `BrowserRuntimeStatusSummary`, `BrowserStatusOptions`, `BrowserStatusResponse`, `CreateBrowserFileFromPathOptions`, `CreateBrowserFileOptions`, `FileId`, `PageId`, `RecordingDownloadResult`, `RecordingEventsOptions`, `RecordingListOptions`, `WebBrowserResource`.

### Policy and warning exports

`BrowserPolicyMode`, `BrowserPolicyTip`, `BrowserPrivateAccess`, `WebcomputeWarning`, `ParsedWarning`, `WarningCallback`, `parseWarning`, `RedactValueForObservabilityOptions`, `redactValueForObservability`.

### Error exports

`AuthenticationError`, `BrowserPolicyTipError`, `BrowserUnavailableError`, `ConflictError`, `ConnectionError`, `InternalError`, `mapResponseToError`, `NotFoundError`, `PayloadTooLargeError`, `RateLimitError`, `RequestAbortedError`, `ResourceLimitError`, `TimeoutError`, `ValidationError`, `WebcomputeError`.
