fastbrowse 0.0.0 → 0.5.19
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/LICENSE +21 -0
- package/README.md +48 -1
- package/dist/abort.d.ts +8 -0
- package/dist/abort.js +29 -0
- package/dist/binary.d.ts +14 -0
- package/dist/binary.js +58 -0
- package/dist/callbacks.d.ts +16 -0
- package/dist/callbacks.js +103 -0
- package/dist/errors.d.ts +26 -0
- package/dist/errors.js +40 -0
- package/dist/fastbrowse.d.ts +51 -0
- package/dist/fastbrowse.js +118 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +3 -0
- package/dist/output.d.ts +76 -0
- package/dist/output.js +57 -0
- package/dist/protocol.d.ts +377 -0
- package/dist/protocol.js +26 -0
- package/dist/rpc.d.ts +18 -0
- package/dist/rpc.js +104 -0
- package/dist/run.d.ts +89 -0
- package/dist/run.js +62 -0
- package/package.json +33 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Agent Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1 +1,48 @@
|
|
|
1
|
-
|
|
1
|
+
# fastbrowse
|
|
2
|
+
|
|
3
|
+
A browser agent for Node.js. It picks one of the controls a page has instead of generating an action, and each
|
|
4
|
+
fact in its answer cites a quote from a page it read. This package is the TypeScript SDK. It runs the agent as
|
|
5
|
+
a native binary, so the machine needs no Python.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install fastbrowse
|
|
11
|
+
export OPENROUTER_API_KEY=...
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
With it npm installs the binary for your platform as an optional dependency: `@fastbrowse/darwin-arm64`,
|
|
15
|
+
`darwin-x64`, `linux-arm64`, `linux-x64` or `win32-x64`. No install script runs and nothing is downloaded on
|
|
16
|
+
first use. It needs Node.js 20 or newer, and on Linux it needs glibc.
|
|
17
|
+
|
|
18
|
+
The binary brings no browser. `local: true` drives the Chrome on your machine. Without it a run starts a
|
|
19
|
+
Browser Use Cloud browser, which needs `BROWSER_USE_API_KEY`.
|
|
20
|
+
|
|
21
|
+
## First run
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { Fastbrowse } from 'fastbrowse';
|
|
25
|
+
|
|
26
|
+
const fb = await Fastbrowse.start({ local: true });
|
|
27
|
+
try {
|
|
28
|
+
const result = await fb.run('Find the httpx package and report its latest released version.', {
|
|
29
|
+
start: 'https://pypi.org/',
|
|
30
|
+
limits: { maxDollars: 0.1 },
|
|
31
|
+
});
|
|
32
|
+
console.log(result.status, result.answer);
|
|
33
|
+
for (const evidence of result.evidence) console.log(` "${evidence.quote}" from ${evidence.url}`);
|
|
34
|
+
} finally {
|
|
35
|
+
await fb.close();
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`run` resolves with the result whatever status the run ended in, and only `complete` is success. Read
|
|
40
|
+
`result.status` before you use the answer.
|
|
41
|
+
|
|
42
|
+
## The rest
|
|
43
|
+
|
|
44
|
+
[Use it from JavaScript](https://github.com/agent-labs-dev/fastbrowse#use-it-from-javascript) in the repository
|
|
45
|
+
README covers output typed by a Zod or JSON Schema, secrets your own code resolves, the `until` check, step
|
|
46
|
+
events, live frames and stopping a run with an `AbortSignal`.
|
|
47
|
+
|
|
48
|
+
MIT licence.
|
package/dist/abort.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Make the `run` request with `send`, and call `cancel` if `signal` aborts while it is waiting on its reply.
|
|
3
|
+
*
|
|
4
|
+
* The server answers a cancelled run with the `cancelled` error once the run's browser has closed, and that
|
|
5
|
+
* reply is what rejects with `AbortError`. A run that finished before the cancellation reached it resolves
|
|
6
|
+
* with its result.
|
|
7
|
+
*/
|
|
8
|
+
export declare function abortable<Result>(signal: AbortSignal | undefined, send: () => Promise<Result>, cancel: () => void): Promise<Result>;
|
package/dist/abort.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// A run the caller can stop with an `AbortSignal`.
|
|
2
|
+
import { AbortError, RpcError } from './errors.js';
|
|
3
|
+
import { ErrorCode } from './protocol.js';
|
|
4
|
+
/**
|
|
5
|
+
* Make the `run` request with `send`, and call `cancel` if `signal` aborts while it is waiting on its reply.
|
|
6
|
+
*
|
|
7
|
+
* The server answers a cancelled run with the `cancelled` error once the run's browser has closed, and that
|
|
8
|
+
* reply is what rejects with `AbortError`. A run that finished before the cancellation reached it resolves
|
|
9
|
+
* with its result.
|
|
10
|
+
*/
|
|
11
|
+
export async function abortable(signal, send, cancel) {
|
|
12
|
+
if (!signal)
|
|
13
|
+
return send();
|
|
14
|
+
if (signal.aborted)
|
|
15
|
+
throw new AbortError(signal.reason);
|
|
16
|
+
signal.addEventListener('abort', cancel, { once: true });
|
|
17
|
+
try {
|
|
18
|
+
return await send();
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
// `shutdown` cancels a run too, and that one the caller did not abort.
|
|
22
|
+
if (signal.aborted && error instanceof RpcError && error.code === ErrorCode.CANCELLED)
|
|
23
|
+
throw new AbortError(signal.reason);
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
signal.removeEventListener('abort', cancel);
|
|
28
|
+
}
|
|
29
|
+
}
|
package/dist/binary.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** What resolution asks of the machine it runs on. */
|
|
2
|
+
export interface Host {
|
|
3
|
+
platform: string;
|
|
4
|
+
arch: string;
|
|
5
|
+
/** Whether the C library is musl, as on Alpine. Asked on Linux only. */
|
|
6
|
+
musl(): boolean;
|
|
7
|
+
/** The path of a module installed where this package can import it. Throws when there is none. */
|
|
8
|
+
resolve(specifier: string): string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The executable to start: the caller's own path first, then the one the environment names, then the one in
|
|
12
|
+
* the platform package installed beside this package.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveBinary(binaryPath: string | undefined, env: NodeJS.ProcessEnv, on?: Host): string;
|
package/dist/binary.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { FastbrowseError } from './errors.js';
|
|
4
|
+
/** The `<platform>-<arch>` pairs a binary is published for, each as the package `@fastbrowse/<pair>`. */
|
|
5
|
+
const TARGETS = ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64', 'win32-x64'];
|
|
6
|
+
const OWN_BINARY = 'pass binaryPath or set FASTBROWSE_BINARY to run a binary of your own';
|
|
7
|
+
const host = {
|
|
8
|
+
platform: process.platform,
|
|
9
|
+
arch: process.arch,
|
|
10
|
+
musl() {
|
|
11
|
+
// Node's report names the glibc it runs on, and has no such entry on musl. It also lists the network
|
|
12
|
+
// interfaces unless told not to, which is slow on a machine with many. Node 20.13 added the switch, later
|
|
13
|
+
// than the types this package builds against.
|
|
14
|
+
const report = process.report;
|
|
15
|
+
const listed = report.excludeNetwork;
|
|
16
|
+
report.excludeNetwork = true;
|
|
17
|
+
try {
|
|
18
|
+
return report.getReport().header.glibcVersionRuntime === undefined;
|
|
19
|
+
}
|
|
20
|
+
finally {
|
|
21
|
+
if (listed !== undefined)
|
|
22
|
+
report.excludeNetwork = listed;
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
resolve: createRequire(import.meta.url).resolve,
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* The executable to start: the caller's own path first, then the one the environment names, then the one in
|
|
29
|
+
* the platform package installed beside this package.
|
|
30
|
+
*/
|
|
31
|
+
export function resolveBinary(binaryPath, env, on = host) {
|
|
32
|
+
const named = binaryPath ?? env.FASTBROWSE_BINARY;
|
|
33
|
+
if (named)
|
|
34
|
+
return named;
|
|
35
|
+
const target = `${on.platform}-${on.arch}`;
|
|
36
|
+
if (!TARGETS.includes(target)) {
|
|
37
|
+
throw new FastbrowseError(`fastbrowse has no binary for ${on.platform} ${on.arch}. It is published for ${TARGETS.join(', ')}. ` +
|
|
38
|
+
`On another platform, ${OWN_BINARY}.`);
|
|
39
|
+
}
|
|
40
|
+
// Asked before the package is looked for: a package manager that does not read `libc` installs the glibc
|
|
41
|
+
// build on musl, where starting it fails with a "no such file" that names a file which is there.
|
|
42
|
+
if (on.platform === 'linux' && on.musl()) {
|
|
43
|
+
throw new FastbrowseError(`fastbrowse has no binary for ${on.platform} ${on.arch} with musl, the C library this system uses. ` +
|
|
44
|
+
`Its Linux binaries need glibc. On musl, ${OWN_BINARY}.`);
|
|
45
|
+
}
|
|
46
|
+
const name = `@fastbrowse/${target}`;
|
|
47
|
+
let manifest;
|
|
48
|
+
try {
|
|
49
|
+
// A platform package has no `exports`, and its manifest is the one file certain to be at its root.
|
|
50
|
+
manifest = on.resolve(`${name}/package.json`);
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
throw new FastbrowseError(`${name}, which holds the fastbrowse binary for ${on.platform} ${on.arch}, is not installed. It is an ` +
|
|
54
|
+
'optional dependency of fastbrowse, so install without --omit=optional or --no-optional. ' +
|
|
55
|
+
`Or ${OWN_BINARY}.`, { cause: error });
|
|
56
|
+
}
|
|
57
|
+
return join(dirname(manifest), 'fastbrowse', on.platform === 'win32' ? 'fastbrowse.exe' : 'fastbrowse');
|
|
58
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type RunResult } from './protocol.ts';
|
|
2
|
+
import type { Connection } from './rpc.ts';
|
|
3
|
+
import type { RunOptions } from './run.ts';
|
|
4
|
+
export declare class Callbacks {
|
|
5
|
+
#private;
|
|
6
|
+
constructor(connection: Connection);
|
|
7
|
+
/**
|
|
8
|
+
* Hand the server's calls for run `runId` to `options` until `run` settles, and settle as it does.
|
|
9
|
+
*
|
|
10
|
+
* A request the server makes is answered with an error when its callback throws, and the server ends the
|
|
11
|
+
* run for that. `onEvent` and `onFrame` are notifications with no reply to fail, so one that throws has the
|
|
12
|
+
* run cancelled from here and resolved as the server would have: status `error`, and the text naming the
|
|
13
|
+
* method and the message.
|
|
14
|
+
*/
|
|
15
|
+
during(runId: string, options: RunOptions, cancel: () => void, run: () => Promise<RunResult>): Promise<RunResult>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// What the server sends while a run is under way, handed to the callbacks of the run it names.
|
|
2
|
+
import { FastbrowseError, messageOf, RpcError } from './errors.js';
|
|
3
|
+
import { ErrorCode, ServerMethod, } from './protocol.js';
|
|
4
|
+
export class Callbacks {
|
|
5
|
+
#runs = new Map();
|
|
6
|
+
constructor(connection) {
|
|
7
|
+
connection.onNotification(ServerMethod.RUN_EVENT, params => {
|
|
8
|
+
const { run_id: runId, event } = params;
|
|
9
|
+
this.#tell(runId, ServerMethod.RUN_EVENT, options => options.onEvent?.(event));
|
|
10
|
+
});
|
|
11
|
+
connection.onNotification(ServerMethod.RUN_FRAME, params => {
|
|
12
|
+
const { run_id: runId, frame } = params;
|
|
13
|
+
const jpeg = Uint8Array.from(Buffer.from(frame, 'base64'));
|
|
14
|
+
this.#tell(runId, ServerMethod.RUN_FRAME, options => options.onFrame?.(jpeg));
|
|
15
|
+
});
|
|
16
|
+
connection.onRequest(ServerMethod.RUN_UNTIL, async (params) => {
|
|
17
|
+
const { run_id: runId, url } = params;
|
|
18
|
+
// The server ends the run as an error on any reply but a boolean, and a check in plain JavaScript can
|
|
19
|
+
// return anything.
|
|
20
|
+
return (await this.#asked(runId, 'until')(url)) === true;
|
|
21
|
+
});
|
|
22
|
+
connection.onRequest(ServerMethod.SECRETS_RESOLVE, async (params) => {
|
|
23
|
+
const { run_id: runId, name, origin } = params;
|
|
24
|
+
const secrets = this.#asked(runId, 'secrets');
|
|
25
|
+
try {
|
|
26
|
+
return await secrets.resolve(name, origin);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// What a resolver throws may quote the value, so it stays in this process.
|
|
30
|
+
throw new FastbrowseError(`the resolver threw for the secret '${name}'`);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Hand the server's calls for run `runId` to `options` until `run` settles, and settle as it does.
|
|
36
|
+
*
|
|
37
|
+
* A request the server makes is answered with an error when its callback throws, and the server ends the
|
|
38
|
+
* run for that. `onEvent` and `onFrame` are notifications with no reply to fail, so one that throws has the
|
|
39
|
+
* run cancelled from here and resolved as the server would have: status `error`, and the text naming the
|
|
40
|
+
* method and the message.
|
|
41
|
+
*/
|
|
42
|
+
async during(runId, options, cancel, run) {
|
|
43
|
+
const served = { options, cancel };
|
|
44
|
+
this.#runs.set(runId, served);
|
|
45
|
+
try {
|
|
46
|
+
const result = await run();
|
|
47
|
+
// A run can finish before the cancellation reaches it, and its callback failed all the same.
|
|
48
|
+
return served.failure === undefined ? result : endedBy(served.failure);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (served.failure !== undefined && error instanceof RpcError && error.code === ErrorCode.CANCELLED) {
|
|
52
|
+
return endedBy(served.failure);
|
|
53
|
+
}
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
this.#runs.delete(runId);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
#tell(runId, method, call) {
|
|
61
|
+
const served = this.#runs.get(runId);
|
|
62
|
+
if (!served || served.failure !== undefined)
|
|
63
|
+
return;
|
|
64
|
+
const fail = (error) => {
|
|
65
|
+
// An async callback can reject after its run was answered, and then there is no run left to end.
|
|
66
|
+
if (served.failure !== undefined || this.#runs.get(runId) !== served)
|
|
67
|
+
return;
|
|
68
|
+
served.failure = `${method}: ${messageOf(error)}`;
|
|
69
|
+
served.cancel();
|
|
70
|
+
};
|
|
71
|
+
// A callback that throws is known to have failed before the next line is read, so it is not called again.
|
|
72
|
+
try {
|
|
73
|
+
Promise.resolve(call(served.options)).catch(fail);
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
fail(error);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
#asked(runId, name) {
|
|
80
|
+
const callback = this.#runs.get(runId)?.options[name];
|
|
81
|
+
if (!callback)
|
|
82
|
+
throw new FastbrowseError(`run '${runId}' has no ${name} callback waiting`);
|
|
83
|
+
return callback;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** The result of a run that a throwing callback ended, in the shape the server gives one. */
|
|
87
|
+
function endedBy(failure) {
|
|
88
|
+
return {
|
|
89
|
+
status: 'error',
|
|
90
|
+
budget: null,
|
|
91
|
+
answer: null,
|
|
92
|
+
data: null,
|
|
93
|
+
evidence: [],
|
|
94
|
+
steps: [],
|
|
95
|
+
cost: { lines: [] },
|
|
96
|
+
artifacts: [],
|
|
97
|
+
citations: [],
|
|
98
|
+
error: failure,
|
|
99
|
+
final_url: null,
|
|
100
|
+
would_fire: [],
|
|
101
|
+
recordings: [],
|
|
102
|
+
};
|
|
103
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Every error this package throws, so one `instanceof` tells its failures from the caller's own. */
|
|
2
|
+
export declare class FastbrowseError extends Error {
|
|
3
|
+
constructor(message: string, options?: ErrorOptions);
|
|
4
|
+
}
|
|
5
|
+
/** The fastbrowse process is gone, so what was waiting on it, or is asked of it later, has no answer. */
|
|
6
|
+
export declare class ProcessExitedError extends FastbrowseError {
|
|
7
|
+
/** The code the process exited with, or null when a signal ended it. */
|
|
8
|
+
readonly exitCode: number | null;
|
|
9
|
+
/** The signal that ended the process, or null when it exited by itself. */
|
|
10
|
+
readonly signal: NodeJS.Signals | null;
|
|
11
|
+
constructor(exitCode: number | null, signal: NodeJS.Signals | null);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The caller's `AbortSignal` stopped the run. `cause` is the signal's reason, which for `AbortSignal.timeout`
|
|
15
|
+
* is a `TimeoutError`.
|
|
16
|
+
*/
|
|
17
|
+
export declare class AbortError extends FastbrowseError {
|
|
18
|
+
constructor(reason: unknown);
|
|
19
|
+
}
|
|
20
|
+
/** What a thrown value says. A callback is the caller's code, and it can throw anything. */
|
|
21
|
+
export declare function messageOf(thrown: unknown): string;
|
|
22
|
+
/** The server's error reply to a request. `code` is one of the protocol's error codes. */
|
|
23
|
+
export declare class RpcError extends FastbrowseError {
|
|
24
|
+
readonly code: number;
|
|
25
|
+
constructor(code: number, message: string);
|
|
26
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Every error this package throws, so one `instanceof` tells its failures from the caller's own. */
|
|
2
|
+
export class FastbrowseError extends Error {
|
|
3
|
+
constructor(message, options) {
|
|
4
|
+
super(message, options);
|
|
5
|
+
this.name = new.target.name;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
/** The fastbrowse process is gone, so what was waiting on it, or is asked of it later, has no answer. */
|
|
9
|
+
export class ProcessExitedError extends FastbrowseError {
|
|
10
|
+
/** The code the process exited with, or null when a signal ended it. */
|
|
11
|
+
exitCode;
|
|
12
|
+
/** The signal that ended the process, or null when it exited by itself. */
|
|
13
|
+
signal;
|
|
14
|
+
constructor(exitCode, signal) {
|
|
15
|
+
super(`the fastbrowse process ${signal ? `was killed by ${signal}` : `exited with code ${exitCode}`}`);
|
|
16
|
+
this.exitCode = exitCode;
|
|
17
|
+
this.signal = signal;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The caller's `AbortSignal` stopped the run. `cause` is the signal's reason, which for `AbortSignal.timeout`
|
|
22
|
+
* is a `TimeoutError`.
|
|
23
|
+
*/
|
|
24
|
+
export class AbortError extends FastbrowseError {
|
|
25
|
+
constructor(reason) {
|
|
26
|
+
super('the run was aborted', { cause: reason });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** What a thrown value says. A callback is the caller's code, and it can throw anything. */
|
|
30
|
+
export function messageOf(thrown) {
|
|
31
|
+
return thrown instanceof Error ? thrown.message : String(thrown);
|
|
32
|
+
}
|
|
33
|
+
/** The server's error reply to a request. `code` is one of the protocol's error codes. */
|
|
34
|
+
export class RpcError extends FastbrowseError {
|
|
35
|
+
code;
|
|
36
|
+
constructor(code, message) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.code = code;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { Writable } from 'node:stream';
|
|
2
|
+
import { type OutputSchema, type TypedRunResult } from './output.ts';
|
|
3
|
+
import { type BrowserOptions, type RunOptions } from './run.ts';
|
|
4
|
+
/** How to start the fastbrowse process, and the browser every run uses unless that run says otherwise. */
|
|
5
|
+
export interface StartOptions extends BrowserOptions {
|
|
6
|
+
/**
|
|
7
|
+
* The fastbrowse executable to run. Without it, the `FASTBROWSE_BINARY` environment variable names one, and
|
|
8
|
+
* without that it is the one in the `@fastbrowse/<platform>-<arch>` package installed with this package.
|
|
9
|
+
*/
|
|
10
|
+
binaryPath?: string;
|
|
11
|
+
/** Environment variables for the fastbrowse process, on top of the ones this process has. */
|
|
12
|
+
env?: Record<string, string>;
|
|
13
|
+
/**
|
|
14
|
+
* Where the fastbrowse process's stderr goes, which is where it logs. `'inherit'`, the default, is this
|
|
15
|
+
* process's own stderr. A stream receives it and is left open when the process ends.
|
|
16
|
+
*/
|
|
17
|
+
stderr?: 'inherit' | 'ignore' | Writable;
|
|
18
|
+
}
|
|
19
|
+
export interface CloseOptions {
|
|
20
|
+
/** How long the process gets to exit after `shutdown` before it is killed. Thirty seconds by default. */
|
|
21
|
+
gracePeriodMs?: number;
|
|
22
|
+
}
|
|
23
|
+
export declare class Fastbrowse {
|
|
24
|
+
#private;
|
|
25
|
+
/** The version of the fastbrowse binary this instance drives. */
|
|
26
|
+
readonly fastbrowseVersion: string;
|
|
27
|
+
private constructor();
|
|
28
|
+
/** Start a fastbrowse process and check that it speaks this SDK's protocol version. */
|
|
29
|
+
static start(options?: StartOptions): Promise<Fastbrowse>;
|
|
30
|
+
/**
|
|
31
|
+
* Run a task and resolve with its result, whatever status it ended in: a run that needs a login or got stuck
|
|
32
|
+
* is read from `status`, and is not an exception.
|
|
33
|
+
*
|
|
34
|
+
* Rejects with `RpcError` when the server refuses the request, which it does before a browser opens: for a
|
|
35
|
+
* bad option, for a missing key, and with the busy code while another run on this instance is active. A run
|
|
36
|
+
* that fails after that resolves with status `error`. Rejects with `ProcessExitedError` when the fastbrowse
|
|
37
|
+
* process is gone. Rejects with `AbortError` when `signal` stopped the run.
|
|
38
|
+
*
|
|
39
|
+
* With `output`, the result's `output` is the data as that schema validated it. A schema that cannot be sent
|
|
40
|
+
* rejects before anything is, a keyword the server cannot enforce rejects with its `unsupported_schema` code,
|
|
41
|
+
* and data the schema refuses rejects with `OutputValidationError`, which carries the result.
|
|
42
|
+
*/
|
|
43
|
+
run<Schema extends OutputSchema>(task: string, options?: RunOptions & {
|
|
44
|
+
output?: Schema;
|
|
45
|
+
}): Promise<TypedRunResult<Schema>>;
|
|
46
|
+
/**
|
|
47
|
+
* Ask the fastbrowse process to shut down and wait until it has exited. A process still running when the
|
|
48
|
+
* grace period ends is killed. Every call after the first returns the first one's promise.
|
|
49
|
+
*/
|
|
50
|
+
close(options?: CloseOptions): Promise<void>;
|
|
51
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { abortable } from './abort.js';
|
|
4
|
+
import { Callbacks } from './callbacks.js';
|
|
5
|
+
import { resolveBinary } from './binary.js';
|
|
6
|
+
import { FastbrowseError, ProcessExitedError } from './errors.js';
|
|
7
|
+
import { withOutput } from './output.js';
|
|
8
|
+
import { Method, PROTOCOL_VERSION, } from './protocol.js';
|
|
9
|
+
import { Connection } from './rpc.js';
|
|
10
|
+
import { browserParams, runParams } from './run.js';
|
|
11
|
+
// Three times the 10 s the server gives Chrome to exit before it kills it: a server killed first orphans that Chrome.
|
|
12
|
+
const DEFAULT_GRACE_PERIOD_MS = 30_000;
|
|
13
|
+
export class Fastbrowse {
|
|
14
|
+
/** The version of the fastbrowse binary this instance drives. */
|
|
15
|
+
fastbrowseVersion;
|
|
16
|
+
#server;
|
|
17
|
+
#browser;
|
|
18
|
+
#callbacks;
|
|
19
|
+
#closed;
|
|
20
|
+
constructor(server, fastbrowseVersion, browser) {
|
|
21
|
+
this.#server = server;
|
|
22
|
+
this.fastbrowseVersion = fastbrowseVersion;
|
|
23
|
+
this.#browser = browser;
|
|
24
|
+
this.#callbacks = new Callbacks(server.connection);
|
|
25
|
+
}
|
|
26
|
+
/** Start a fastbrowse process and check that it speaks this SDK's protocol version. */
|
|
27
|
+
static async start(options = {}) {
|
|
28
|
+
const env = { ...process.env, ...options.env };
|
|
29
|
+
const binary = resolveBinary(options.binaryPath, env);
|
|
30
|
+
const server = new Server(binary, env, options.stderr ?? 'inherit');
|
|
31
|
+
try {
|
|
32
|
+
const hello = { protocol_version: PROTOCOL_VERSION };
|
|
33
|
+
const reply = (await server.connection.request(Method.INITIALIZE, hello));
|
|
34
|
+
if (reply.protocol_version !== PROTOCOL_VERSION) {
|
|
35
|
+
throw new FastbrowseError(`this SDK speaks protocol version ${PROTOCOL_VERSION}, and fastbrowse ${reply.fastbrowse_version} at ` +
|
|
36
|
+
`${binary} speaks protocol version ${reply.protocol_version}: install matching versions of the two`);
|
|
37
|
+
}
|
|
38
|
+
return new Fastbrowse(server, reply.fastbrowse_version, browserParams(options));
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
await server.kill();
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Run a task and resolve with its result, whatever status it ended in: a run that needs a login or got stuck
|
|
47
|
+
* is read from `status`, and is not an exception.
|
|
48
|
+
*
|
|
49
|
+
* Rejects with `RpcError` when the server refuses the request, which it does before a browser opens: for a
|
|
50
|
+
* bad option, for a missing key, and with the busy code while another run on this instance is active. A run
|
|
51
|
+
* that fails after that resolves with status `error`. Rejects with `ProcessExitedError` when the fastbrowse
|
|
52
|
+
* process is gone. Rejects with `AbortError` when `signal` stopped the run.
|
|
53
|
+
*
|
|
54
|
+
* With `output`, the result's `output` is the data as that schema validated it. A schema that cannot be sent
|
|
55
|
+
* rejects before anything is, a keyword the server cannot enforce rejects with its `unsupported_schema` code,
|
|
56
|
+
* and data the schema refuses rejects with `OutputValidationError`, which carries the result.
|
|
57
|
+
*/
|
|
58
|
+
async run(task, options = {}) {
|
|
59
|
+
// The server names the run in every event it sends, which is how a run refused as busy hears nothing of
|
|
60
|
+
// the one that is active.
|
|
61
|
+
const runId = randomUUID();
|
|
62
|
+
const params = runParams(runId, task, this.#browser, options);
|
|
63
|
+
const { connection } = this.#server;
|
|
64
|
+
// The reply says only that the request was read, and a process that has gone rejects the run itself.
|
|
65
|
+
const cancel = () => void connection.request(Method.RUN_CANCEL, { run_id: runId }).catch(() => { });
|
|
66
|
+
const result = await this.#callbacks.during(runId, options, cancel, () => abortable(options.signal, () => connection.request(Method.RUN, params), cancel));
|
|
67
|
+
return withOutput(result, options.output);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Ask the fastbrowse process to shut down and wait until it has exited. A process still running when the
|
|
71
|
+
* grace period ends is killed. Every call after the first returns the first one's promise.
|
|
72
|
+
*/
|
|
73
|
+
close(options = {}) {
|
|
74
|
+
this.#closed ??= this.#close(options.gracePeriodMs ?? DEFAULT_GRACE_PERIOD_MS);
|
|
75
|
+
return this.#closed;
|
|
76
|
+
}
|
|
77
|
+
async #close(gracePeriodMs) {
|
|
78
|
+
// The reply says nothing the exit does not, and a process that died earlier answers with a rejection.
|
|
79
|
+
this.#server.connection.request(Method.SHUTDOWN).catch(() => { });
|
|
80
|
+
const overdue = setTimeout(() => void this.#server.kill(), gracePeriodMs);
|
|
81
|
+
await this.#server.exited;
|
|
82
|
+
clearTimeout(overdue);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** The fastbrowse process and the connection over its stdin and stdout. */
|
|
86
|
+
class Server {
|
|
87
|
+
connection;
|
|
88
|
+
/** Resolves once the process is gone and its output has been read to the end. Never rejects. */
|
|
89
|
+
exited;
|
|
90
|
+
#process;
|
|
91
|
+
constructor(binary, env, stderr) {
|
|
92
|
+
const child = spawn(binary, ['serve', '--stdio'], {
|
|
93
|
+
env,
|
|
94
|
+
// `spawn` takes a stream only when a file descriptor backs it, so any other stream is fed from a pipe.
|
|
95
|
+
stdio: ['pipe', 'pipe', typeof stderr === 'string' ? stderr : 'pipe'],
|
|
96
|
+
windowsHide: true,
|
|
97
|
+
});
|
|
98
|
+
if (typeof stderr !== 'string')
|
|
99
|
+
child.stderr.pipe(stderr, { end: false });
|
|
100
|
+
this.#process = child;
|
|
101
|
+
this.connection = new Connection(child.stdout, child.stdin);
|
|
102
|
+
this.exited = new Promise(resolve => {
|
|
103
|
+
// A binary that cannot be started gets `error` and no `close`.
|
|
104
|
+
child.once('error', error => {
|
|
105
|
+
this.connection.end(new FastbrowseError(`could not start ${binary}: ${error.message}`, { cause: error }));
|
|
106
|
+
resolve();
|
|
107
|
+
});
|
|
108
|
+
child.once('close', (code, signal) => {
|
|
109
|
+
this.connection.end(new ProcessExitedError(code, signal));
|
|
110
|
+
resolve();
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
async kill() {
|
|
115
|
+
this.#process.kill('SIGKILL');
|
|
116
|
+
await this.exited;
|
|
117
|
+
}
|
|
118
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { AbortError, FastbrowseError, ProcessExitedError, RpcError } from './errors.ts';
|
|
2
|
+
export { type CloseOptions, Fastbrowse, type StartOptions } from './fastbrowse.ts';
|
|
3
|
+
export { type JsonSchema, type OutputIssue, type OutputOf, type OutputSchema, OutputValidationError, type StandardOutputSchema, type TypedRunResult, } from './output.ts';
|
|
4
|
+
export type { Artifact, BrowserEvent, BudgetStop, Citation, CostBreakdown, CostLine, ErrorCode, Evidence, RunResult, SecretRef, Status, StepEvent, StepFact, StepResult, } from './protocol.ts';
|
|
5
|
+
export type { Attachment, BrowserOptions, RunOptions, Secrets } from './run.ts';
|
package/dist/index.js
ADDED
package/dist/output.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { FastbrowseError } from './errors.ts';
|
|
2
|
+
import type { RunResult, Status } from './protocol.ts';
|
|
3
|
+
/** The draft `fastbrowse serve` reads. */
|
|
4
|
+
declare const TARGET = "draft-2020-12";
|
|
5
|
+
/** One thing a schema found wrong with the data, as Standard Schema reports it. */
|
|
6
|
+
export interface OutputIssue {
|
|
7
|
+
readonly message: string;
|
|
8
|
+
readonly path?: ReadonlyArray<PropertyKey | {
|
|
9
|
+
readonly key: PropertyKey;
|
|
10
|
+
}> | undefined;
|
|
11
|
+
}
|
|
12
|
+
type Validation<Output> = {
|
|
13
|
+
readonly value: Output;
|
|
14
|
+
readonly issues?: undefined;
|
|
15
|
+
} | {
|
|
16
|
+
readonly issues: ReadonlyArray<OutputIssue>;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* A schema that can both write itself as JSON Schema and validate: `StandardSchemaV1 & StandardJSONSchemaV1`
|
|
20
|
+
* of `@standard-schema/spec`, which Zod and ArkType schemas are, and a Valibot schema is once
|
|
21
|
+
* `@valibot/to-json-schema` has wrapped it.
|
|
22
|
+
*
|
|
23
|
+
* The two interfaces are written out here because the published declarations cannot import a package the SDK
|
|
24
|
+
* does not depend on. Only the members `run` uses are named.
|
|
25
|
+
*/
|
|
26
|
+
export interface StandardOutputSchema<Output = unknown> {
|
|
27
|
+
readonly '~standard': {
|
|
28
|
+
readonly version: 1;
|
|
29
|
+
readonly vendor: string;
|
|
30
|
+
readonly types?: {
|
|
31
|
+
readonly input: unknown;
|
|
32
|
+
readonly output: Output;
|
|
33
|
+
} | undefined;
|
|
34
|
+
readonly validate: (value: unknown) => Validation<Output> | Promise<Validation<Output>>;
|
|
35
|
+
readonly jsonSchema: {
|
|
36
|
+
readonly input: (options: {
|
|
37
|
+
readonly target: typeof TARGET;
|
|
38
|
+
}) => Record<string, unknown>;
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/** A JSON Schema, draft 2020-12, with an object at its root. It is sent as it is. */
|
|
43
|
+
export interface JsonSchema {
|
|
44
|
+
readonly [keyword: string]: unknown;
|
|
45
|
+
readonly '~standard'?: never;
|
|
46
|
+
}
|
|
47
|
+
export type OutputSchema = StandardOutputSchema | JsonSchema;
|
|
48
|
+
/** What `output` holds for a schema: its output type when the schema can validate, and otherwise `unknown`. */
|
|
49
|
+
export type OutputOf<Schema> = Schema extends StandardOutputSchema<infer Output> ? Output : unknown;
|
|
50
|
+
/**
|
|
51
|
+
* The result of a run and, in `output`, its `data` as the `output` schema validated it, with the schema's
|
|
52
|
+
* transforms and defaults applied. `data` stays what the server sent. With a plain JSON Schema or no schema
|
|
53
|
+
* there is nothing to validate with, and `output` is `data`.
|
|
54
|
+
*
|
|
55
|
+
* A run that ended before it read any data has none to validate, so `output` is null there, and checking
|
|
56
|
+
* `status` first leaves the schema's own type.
|
|
57
|
+
*/
|
|
58
|
+
export type TypedRunResult<Schema> = RunResult & ({
|
|
59
|
+
status: 'complete';
|
|
60
|
+
output: OutputOf<Schema>;
|
|
61
|
+
} | {
|
|
62
|
+
status: Exclude<Status, 'complete'>;
|
|
63
|
+
output: OutputOf<Schema> | null;
|
|
64
|
+
});
|
|
65
|
+
/** The data of a run did not pass the `output` schema's own validation. */
|
|
66
|
+
export declare class OutputValidationError extends FastbrowseError {
|
|
67
|
+
/** The result as the server sent it, with the data that failed in `data`. */
|
|
68
|
+
readonly result: RunResult;
|
|
69
|
+
readonly issues: ReadonlyArray<OutputIssue>;
|
|
70
|
+
constructor(result: RunResult, issues: ReadonlyArray<OutputIssue>);
|
|
71
|
+
}
|
|
72
|
+
/** The JSON Schema that goes to the server as `output_schema`. */
|
|
73
|
+
export declare function wireSchema(schema: OutputSchema): Record<string, unknown>;
|
|
74
|
+
/** The result with its `output`. Rejects with `OutputValidationError` when the schema refuses the data. */
|
|
75
|
+
export declare function withOutput<Schema extends OutputSchema>(result: RunResult, schema: Schema | undefined): Promise<TypedRunResult<Schema>>;
|
|
76
|
+
export {};
|