Skip to content
Open
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
3 changes: 3 additions & 0 deletions .github/workflows/publish-npm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ jobs:
- name: Install dependencies
run: yarn install --frozen-lockfile

- name: Typecheck tests
run: yarn typecheck:tests

- name: Build package
run: yarn build

Expand Down
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
"type": "commonjs",
"license": "MIT",
"scripts": {
"build": "tsc",
"clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
"build": "yarn clean && tsc",
"typecheck:tests": "tsc -p tsconfig.tests.json --noEmit",
"lint": "eslint src/**/*.ts",
"prepare": "yarn build",
"test": "vitest run",
Expand All @@ -40,16 +42,16 @@
"ai"
],
"dependencies": {
"@types/node": "^22.9.1",
"@types/node-fetch": "^2.6.4",
"@types/ws": "^8.18.1",
"form-data": "^4.0.1",
"node-fetch": "2.7.0",
"ws": "^8.19.0",
"zod": "^4.1.12",
"zod-to-json-schema": "^3.25.0"
},
"devDependencies": {
"@types/node": "^22.9.1",
"@types/node-fetch": "^2.6.4",
"@types/ws": "^8.18.1",
"@typescript-eslint/eslint-plugin": "^8.15.0",
"@typescript-eslint/parser": "^8.15.0",
"dotenv": "^17.3.1",
Expand Down
2 changes: 1 addition & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { HyperAgentService } from "./services/agents/hyper-agent";
import { TeamService } from "./services/team";
import { ComputerActionService } from "./services/computer-action";
import { GeminiComputerUseService } from "./services/agents/gemini-computer-use";
import { WebService } from "./services/web";
import { WebService } from "./services/web/index";
import { SandboxesService } from "./services/sandboxes";
import { VolumesService } from "./services/volumes";

Expand Down
5 changes: 3 additions & 2 deletions src/sandbox/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,13 @@ export class RuntimeTransport {

async requestJSON<T>(path: string, init?: RequestInit, params?: RuntimeParams): Promise<T> {
const response = await this.fetchWithAuth(path, init, params);
if (response.headers.get("content-length") === "0") {
const responseText = await response.text();
if (!responseText) {
return {} as T;
}

try {
return (await response.json()) as T;
return JSON.parse(responseText) as T;
} catch {
throw new HyperbrowserError("Failed to parse JSON response", {
statusCode: response.status,
Expand Down
65 changes: 43 additions & 22 deletions src/sandbox/files.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Blob, Buffer } from "buffer";
import nodePath from "path";
import nodePath from "node:path/posix";
import { ReadableStream } from "node:stream/web";
import WebSocket from "ws";
import { HyperbrowserError } from "../client";
Expand Down Expand Up @@ -158,7 +158,7 @@ const relativeWatchName = (root: string, absolutePath: string): string => {
if (!relative || relative === ".") {
return nodePath.basename(absolutePath);
}
return relative.split(nodePath.sep).join("/");
return relative;
};

const isReadableStreamLike = (value: SandboxFileWriteData): value is ReadableStream<Uint8Array> => {
Expand Down Expand Up @@ -248,9 +248,10 @@ const encodeWriteData = async (
class RuntimeFileWatchHandle {
constructor(
private readonly transport: RuntimeTransport,
private readonly getConnectionInfo: () => Promise<RuntimeConnectionInfo>,
private readonly getConnectionInfo: (forceRefresh?: boolean) => Promise<RuntimeConnectionInfo>,
private readonly status: RawFileWatchStatus,
private readonly runtimeProxyOverride?: string
private readonly runtimeProxyOverride?: string,
private readonly webSocketTimeout?: number
) {}

get id(): string {
Expand All @@ -271,23 +272,40 @@ class RuntimeFileWatchHandle {
}

async *events(cursor?: number): AsyncGenerator<RawFileWatchEvent> {
const connectionInfo = await this.getConnectionInfo();
const target = toWebSocketUrl(
connectionInfo.baseUrl,
`/sandbox/files/watch/${this.status.id}/ws?sessionId=${encodeURIComponent(
connectionInfo.sandboxId
)}${cursor !== undefined ? `&cursor=${encodeURIComponent(String(cursor))}` : ""}`,
this.runtimeProxyOverride
);
const buildTarget = async (forceRefresh: boolean = false) => {
const connectionInfo = await this.getConnectionInfo(forceRefresh);
const target = toWebSocketUrl(
connectionInfo.baseUrl,
`/sandbox/files/watch/${this.status.id}/ws?sessionId=${encodeURIComponent(
connectionInfo.sandboxId
)}${cursor !== undefined ? `&cursor=${encodeURIComponent(String(cursor))}` : ""}`,
this.runtimeProxyOverride
);

const headers: Record<string, string> = {
Authorization: `Bearer ${connectionInfo.token}`,
};
if (target.hostHeader) {
headers.Host = target.hostHeader;
}

const headers: Record<string, string> = {
Authorization: `Bearer ${connectionInfo.token}`,
return { target, headers };
};
if (target.hostHeader) {
headers.Host = target.hostHeader;
}

const ws = await openRuntimeWebSocket(target, headers);
const openSocket = async () => {
const { target, headers } = await buildTarget();
try {
return await openRuntimeWebSocket(target, headers, this.webSocketTimeout);
} catch (error) {
if (error instanceof HyperbrowserError && error.statusCode === 401) {
const refreshed = await buildTarget(true);
return openRuntimeWebSocket(refreshed.target, refreshed.headers, this.webSocketTimeout);
}
throw error;
}
};

const ws = await openSocket();
const queue = new AsyncEventQueue<RawFileWatchEvent>();

ws.on("message", (data) => {
Expand Down Expand Up @@ -405,9 +423,10 @@ export class SandboxWatchDirHandle {
export class SandboxFilesApi {
constructor(
private readonly transport: RuntimeTransport,
private readonly getConnectionInfo: () => Promise<RuntimeConnectionInfo>,
private readonly getConnectionInfo: (forceRefresh?: boolean) => Promise<RuntimeConnectionInfo>,
private readonly runtimeProxyOverride?: string,
private readonly defaultRunAs?: string
private readonly defaultRunAs?: string,
private readonly webSocketTimeout?: number
) {}

withRunAs(runAs?: string): SandboxFilesApi {
Expand All @@ -416,7 +435,8 @@ export class SandboxFilesApi {
this.transport,
this.getConnectionInfo,
this.runtimeProxyOverride,
normalized ? normalized : undefined
normalized ? normalized : undefined,
this.webSocketTimeout
);
}

Expand Down Expand Up @@ -716,7 +736,8 @@ export class SandboxFilesApi {
this.transport,
this.getConnectionInfo,
response.watch,
this.runtimeProxyOverride
this.runtimeProxyOverride,
this.webSocketTimeout
);

return new SandboxWatchDirHandle(watch, onEvent, options.onExit, options.timeoutMs);
Expand Down
67 changes: 43 additions & 24 deletions src/sandbox/terminal.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import WebSocket from "ws";
import { RuntimeTransport } from "./base";
import { AsyncEventQueue, openRuntimeWebSocket, toWebSocketUrl } from "./ws";
import { HyperbrowserError } from "../client";
import {
SandboxTerminalCreateParams,
SandboxTerminalEvent,
Expand Down Expand Up @@ -180,9 +181,10 @@ export class SandboxTerminalConnection {
export class SandboxTerminalHandle {
constructor(
private readonly transport: RuntimeTransport,
private readonly getConnectionInfo: () => Promise<RuntimeConnectionInfo>,
private readonly getConnectionInfo: (forceRefresh?: boolean) => Promise<RuntimeConnectionInfo>,
private status: SandboxTerminalStatus,
private readonly runtimeProxyOverride?: string
private readonly runtimeProxyOverride?: string,
private readonly webSocketTimeout?: number
) {}

get id(): string {
Expand Down Expand Up @@ -268,27 +270,41 @@ export class SandboxTerminalHandle {
}

async attach(cursor?: number | string): Promise<SandboxTerminalConnection> {
const connectionInfo = await this.getConnectionInfo();
const query = new URLSearchParams({
sessionId: connectionInfo.sandboxId,
});
if (cursor !== undefined) {
query.set("cursor", String(cursor));
}
const target = toWebSocketUrl(
connectionInfo.baseUrl,
`/sandbox/pty/${this.id}/ws?${query.toString()}`,
this.runtimeProxyOverride
);
const buildTarget = async (forceRefresh: boolean = false) => {
const connectionInfo = await this.getConnectionInfo(forceRefresh);
const query = new URLSearchParams({
sessionId: connectionInfo.sandboxId,
});
if (cursor !== undefined) {
query.set("cursor", String(cursor));
}
const target = toWebSocketUrl(
connectionInfo.baseUrl,
`/sandbox/pty/${this.id}/ws?${query.toString()}`,
this.runtimeProxyOverride
);

const headers: Record<string, string> = {
Authorization: `Bearer ${connectionInfo.token}`,
};
if (target.hostHeader) {
headers.Host = target.hostHeader;
}

const headers: Record<string, string> = {
Authorization: `Bearer ${connectionInfo.token}`,
return { target, headers };
};
if (target.hostHeader) {
headers.Host = target.hostHeader;
}

const ws = await openRuntimeWebSocket(target, headers);
const { target, headers } = await buildTarget();
let ws: WebSocket;
try {
ws = await openRuntimeWebSocket(target, headers, this.webSocketTimeout);
} catch (error) {
if (!(error instanceof HyperbrowserError) || error.statusCode !== 401) {
throw error;
}
const refreshed = await buildTarget(true);
ws = await openRuntimeWebSocket(refreshed.target, refreshed.headers, this.webSocketTimeout);
}

return new SandboxTerminalConnection(ws);
}
Expand All @@ -297,8 +313,9 @@ export class SandboxTerminalHandle {
export class SandboxTerminalApi {
constructor(
private readonly transport: RuntimeTransport,
private readonly getConnectionInfo: () => Promise<RuntimeConnectionInfo>,
private readonly runtimeProxyOverride?: string
private readonly getConnectionInfo: (forceRefresh?: boolean) => Promise<RuntimeConnectionInfo>,
private readonly runtimeProxyOverride?: string,
private readonly webSocketTimeout?: number
) {}

async create(params: SandboxTerminalCreateParams): Promise<SandboxTerminalHandle> {
Expand All @@ -314,7 +331,8 @@ export class SandboxTerminalApi {
this.transport,
this.getConnectionInfo,
normalizeTerminalStatus(response.pty),
this.runtimeProxyOverride
this.runtimeProxyOverride,
this.webSocketTimeout
);
}

Expand All @@ -329,7 +347,8 @@ export class SandboxTerminalApi {
this.transport,
this.getConnectionInfo,
normalizeTerminalStatus(response.pty),
this.runtimeProxyOverride
this.runtimeProxyOverride,
this.webSocketTimeout
);
}
}
7 changes: 4 additions & 3 deletions src/sandbox/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ export const resolveRuntimeTransportTarget = (
url.username = override.username;
url.password = override.password;
url.hostname = override.hostname;
url.port = override.port || url.port;
url.port = override.port;

return {
url: url.toString(),
Expand Down Expand Up @@ -252,12 +252,13 @@ const buildHandshakeError = async (response: IncomingMessage): Promise<Hyperbrow

export const openRuntimeWebSocket = async (
target: RuntimeTransportTarget,
headers: Record<string, string>
headers: Record<string, string>,
timeout: number = 30000
): Promise<WebSocket> =>
new Promise<WebSocket>((resolve, reject) => {
let settled = false;

const socket = new WebSocket(target.url, { headers });
const socket = new WebSocket(target.url, { headers, handshakeTimeout: timeout });

const rejectOnce = (error: unknown) => {
if (settled) {
Expand Down
5 changes: 3 additions & 2 deletions src/services/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,13 @@ export class BaseService {
});
}

if (response.headers.get("content-length") === "0") {
const responseText = await response.text();
if (!responseText) {
return {} as T;
}

try {
return (await response.json()) as T;
return JSON.parse(responseText) as T;
} catch {
throw new HyperbrowserError("Failed to parse JSON response", {
statusCode: response.status,
Expand Down
2 changes: 1 addition & 1 deletion src/services/crawl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class CrawlService extends BaseService {
while (true) {
try {
const { status } = await this.getStatus(jobId);
if (status === "completed" || status === "failed") {
if (status === "completed" || status === "failed" || status === "stopped") {
jobStatus = status;
break;
}
Expand Down
2 changes: 1 addition & 1 deletion src/services/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export class ExtractService extends BaseService {
while (true) {
try {
const { status } = await this.getStatus(jobId);
if (status === "completed" || status === "failed") {
if (status === "completed" || status === "failed" || status === "stopped") {
return await this.get(jobId);
}
failures = 0;
Expand Down
15 changes: 9 additions & 6 deletions src/services/sandboxes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,13 +204,16 @@ export class SandboxHandle {
this.processes = new SandboxProcessesApi(this.transport);
this.files = new SandboxFilesApi(
this.transport,
() => this.resolveRuntimeSocketConnectionInfo(),
service.runtimeProxyOverride
(forceRefresh) => this.resolveRuntimeSocketConnectionInfo(forceRefresh),
service.runtimeProxyOverride,
undefined,
service.runtimeTimeout
);
this.terminal = new SandboxTerminalApi(
this.transport,
() => this.resolveRuntimeSocketConnectionInfo(),
service.runtimeProxyOverride
(forceRefresh) => this.resolveRuntimeSocketConnectionInfo(forceRefresh),
service.runtimeProxyOverride,
service.runtimeTimeout
);
this.pty = this.terminal;
}
Expand Down Expand Up @@ -342,12 +345,12 @@ export class SandboxHandle {
};
}

private async resolveRuntimeSocketConnectionInfo(): Promise<{
private async resolveRuntimeSocketConnectionInfo(forceRefresh: boolean = false): Promise<{
sandboxId: string;
baseUrl: string;
token: string;
}> {
const session = await this.ensureRuntimeSession();
const session = await this.ensureRuntimeSession(forceRefresh);
return {
sandboxId: this.id,
baseUrl: session.runtime.baseUrl,
Expand Down
Loading