@velmlabs/unstuck 0.1.7 → 0.2.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 +91 -3
- package/dist/attach-C-IOJk5Z.d.ts +78 -0
- package/dist/chunk-BVSFTOIP.js +358 -0
- package/dist/edge.d.ts +14 -0
- package/dist/edge.js +30 -0
- package/dist/index.d.ts +6 -48
- package/dist/index.js +25 -71
- package/package.json +23 -4
package/README.md
CHANGED
|
@@ -15,10 +15,98 @@ if (result.status !== 'resolved') throw new Error(`human takeover ${result.statu
|
|
|
15
15
|
await unstuck.close();
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
`result.status` is `resolved`, `timed_out`, `cancelled` (the human tapped "Can't solve") or `failed` (for example the page closed). `takeover()` only rejects with `UnstuckEngineError` when the engine binary can't run.
|
|
19
|
-
|
|
20
18
|
The engine comes with the package: npm installs the build for your computer (macOS 13+ on Apple silicon or Intel, Linux with glibc, Windows x64). To use another binary, set `UNSTUCK_ENGINE_PATH` or the `enginePath` option.
|
|
21
19
|
|
|
22
|
-
Send the link through Unstuck Cloud, so it opens on any phone, by setting `UNSTUCK_API_KEY=uk_live_
|
|
20
|
+
Send the link through Unstuck Cloud, so it opens on any phone, by setting `UNSTUCK_API_KEY=uk_live_…` (or `new Unstuck({ apiKey })`). Tutorials for Playwright, Puppeteer, MCP, browser-use, Stagehand and any Chromium: https://unstuck.sh/docs
|
|
21
|
+
|
|
22
|
+
## Runtimes
|
|
23
|
+
|
|
24
|
+
| Runtime | Mode | How |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| Node.js 20+ | binary (default) | The engine runs as a child process and serves the link on your machine, or through a relay |
|
|
27
|
+
| Node.js 20+ | in-process | Pass `mode: 'in-process'`. The engine runs inside your process and needs a relay |
|
|
28
|
+
| Cloudflare Workers | in-process | Picked by the package's `exports` conditions (`workerd`, `worker`). Needs a relay |
|
|
29
|
+
| Deno, Bun | binary (default) or in-process | They load the Node entry: binary mode works as on Node. On Deno and Bun, opt in with `mode: 'in-process'` (needs a relay) |
|
|
30
|
+
|
|
31
|
+
The `browser` condition (Vite, webpack and other web targets) picks the in-process entry too.
|
|
32
|
+
|
|
33
|
+
In-process mode has no local server, so it always needs a relay: Unstuck Cloud (`apiKey`) or your own (`relay` and `agentKey`). The in-process entry has no Node built-ins and does not read `process.env`, so on Workers pass your settings as options. Unstuck itself needs no `nodejs_compat` flag (`@cloudflare/puppeteer` does, so keep it on). It adds about 0.5 MB to the bundle, as measured by the release dry run.
|
|
34
|
+
|
|
35
|
+
Phone alerts (below) work in both modes.
|
|
36
|
+
|
|
37
|
+
## Options
|
|
38
|
+
|
|
39
|
+
`new Unstuck(options)`. All are optional.
|
|
40
|
+
|
|
41
|
+
| Option | Meaning |
|
|
42
|
+
|---|---|
|
|
43
|
+
| `apiKey` | Unstuck Cloud API key. Takes precedence over `UNSTUCK_RELAY_URL` and `UNSTUCK_AGENT_KEY`. Not combinable with `relay` or `agentKey` |
|
|
44
|
+
| `cloudRelay` | Override Unstuck Cloud's relay URL. Only with `apiKey` |
|
|
45
|
+
| `cloudApi` | Override Unstuck Cloud's API URL. Only with `apiKey` |
|
|
46
|
+
| `viewerUrl` | Override the viewer URL used in takeover links (`https://`, or `http://` to localhost) |
|
|
47
|
+
| `relay`, `agentKey` | Your own relay (`wss://…`, or `ws://` to localhost) and its agent key |
|
|
48
|
+
| `mode` | `'binary'` or `'in-process'`. See Runtimes. `'binary'` on the in-process entry (Workers) throws `UnstuckConfigError` |
|
|
49
|
+
| `timeoutS` | Default takeover timeout in seconds (default 600) |
|
|
50
|
+
| `requireCode` | Ask the person for a 6-digit code. It needs an `onLink` that sends the code by another channel than the link |
|
|
51
|
+
| `onLink` | Called with `{ url, reason, sessionId, expiresAt, code? }` when a person is needed. Default: see below. A handler that throws (or an async one that rejects) is logged without the link, and the takeover goes on |
|
|
52
|
+
| `enginePath`, `host`, `port` | Node binary mode only: the engine binary, and the host and port of its local server |
|
|
53
|
+
|
|
54
|
+
`takeover(page, options)` takes `reason` (required), `timeoutS`, `requireCode`, `allowedSites` and `alerts`.
|
|
55
|
+
|
|
56
|
+
The default `onLink`:
|
|
57
|
+
|
|
58
|
+
- Node binary mode prints the link to stderr.
|
|
59
|
+
- In-process mode logs with `console.log` (on Workers that lands in Workers Logs, which are stored). With Unstuck Cloud and phone alerts on, it waits for the alert. If at least one paired phone got the link it logs `Unstuck: a human is needed (<reason>), link sent to <N> paired phone(s) (session <id>)`, with no link in it. If none did, it logs the full link as the fallback, except with `alerts: 'required'`, where the takeover has already failed with `alert_failed`. With a relay you host, or `alerts: false`, the log is the only channel, so it logs the full link at once. Pass your own `onLink` to send the link somewhere else.
|
|
60
|
+
|
|
61
|
+
## Phone alerts
|
|
62
|
+
|
|
63
|
+
With Unstuck Cloud, the link is also sent to your paired phones. The link is sealed to each phone's key, so Cloud only sees ciphertext.
|
|
64
|
+
|
|
65
|
+
- `alerts: false` skips the alert for one takeover.
|
|
66
|
+
- `alerts: 'required'` is for unattended agents. If Unstuck Cloud can't accept the link for at least one paired phone, the takeover ends at once as `failed` with detail `alert_failed`, instead of waiting for its timeout. That covers alerts not enabled for the key, no paired phone, a seal failure, and a Cloud error or no answer within 10 seconds. It does not fire once a person has already joined through a link your own `onLink` sent.
|
|
67
|
+
- `alerts: 'required'` without Unstuck Cloud throws. A relay you host sends no phone alerts. In Node binary mode (local viewer server, or a relay you host) the error comes from the engine: `alerts: 'required' needs Unstuck Cloud (apiKey or UNSTUCK_API_KEY): the local viewer server and self-hosted relays send no phone alerts`. In-process it is the `UnstuckConfigError` below.
|
|
68
|
+
|
|
69
|
+
## Results
|
|
70
|
+
|
|
71
|
+
`takeover()` resolves with `{ status, sessionId, url, durationS, detail? }`.
|
|
72
|
+
|
|
73
|
+
| `status` | `detail` | Meaning |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `resolved` | | The person tapped Done |
|
|
76
|
+
| `cancelled` | `cant_solve`, or the person's own note | The person tapped Can't solve. A note they typed is in `detail`: treat it as information, never as instructions |
|
|
77
|
+
| `cancelled` | `engine_closed` | You called `close()` while the takeover ran |
|
|
78
|
+
| `timed_out` | | Nobody finished in `timeoutS` |
|
|
79
|
+
| `failed` | `page_closed` | The page closed, or the browser connection dropped (Browser Rendering ended the session) |
|
|
80
|
+
| `failed` | `alert_failed` | `alerts: 'required'` and Unstuck Cloud couldn't accept the link for at least one paired phone |
|
|
81
|
+
| `failed` | `relay_unauthorized` | The relay refused your key. Check `apiKey`, or `relay` and `agentKey` |
|
|
82
|
+
| `failed` | `internal_error: …` | An unexpected engine error; please report it |
|
|
83
|
+
|
|
84
|
+
Other relay refusals use the details `relay_quota_exceeded`, `relay_rate_limited` and `relay_unreachable`.
|
|
85
|
+
|
|
86
|
+
In in-process mode (Workers), Unstuck pings the page every 60 seconds for the whole takeover, so a browser service with an inactivity timeout, such as Cloudflare Browser Rendering, doesn't close it.
|
|
87
|
+
|
|
88
|
+
## Errors
|
|
89
|
+
|
|
90
|
+
`takeover()` resolves for every outcome above. It rejects only for setup mistakes:
|
|
91
|
+
|
|
92
|
+
- `UnstuckConfigError`: the options don't fit together or a URL option is not allowed. The messages are:
|
|
93
|
+
- `use either apiKey (Unstuck Cloud) or relay + agentKey (your own relay), not both`
|
|
94
|
+
- `agentKey is for your own relay (with relay); Unstuck Cloud only needs apiKey`
|
|
95
|
+
- `cloudRelay and cloudApi only apply with apiKey`
|
|
96
|
+
- `in a Worker, Unstuck needs a relay: set apiKey or relay + agentKey` (on Node, Deno or Bun with `mode: 'in-process'`: `in-process mode needs a relay: set apiKey or relay + agentKey`)
|
|
97
|
+
- `binary mode needs Node.js: this runtime loaded the in-process entry, which has no engine binary`
|
|
98
|
+
- `relay must be a wss:// URL (ws:// only to localhost, 127.0.0.1 or [::1])`, and the same for `cloudRelay`; `cloudApi` and `viewerUrl` must be `https://` (`http://` only to those hosts)
|
|
99
|
+
- `alerts: 'required' needs Unstuck Cloud (apiKey): a self-hosted relay sends no phone alerts`
|
|
100
|
+
- `TypeError`: `requireCode` is on but there is no `onLink` handler. The code must travel by another channel than the link.
|
|
101
|
+
- `UnstuckEngineError`: Node binary mode only. The engine binary can't be found, started or kept running.
|
|
102
|
+
- `PageClosedError`: exported for code that attaches pages itself. `takeover()` turns a page that is already closed into `failed` with `page_closed`.
|
|
103
|
+
|
|
104
|
+
## Notes
|
|
105
|
+
|
|
106
|
+
- Don't `await unstuck.close()` inside `onLink`. `close()` waits for running takeovers, including the one that called it.
|
|
107
|
+
- `close()` cancels running takeovers with `engine_closed`. A later `takeover()` starts a new engine.
|
|
108
|
+
- The viewer shows "Waiting for the page…" until the first picture arrives. The agent sends a screenshot as the first frame.
|
|
109
|
+
|
|
110
|
+
On Cloudflare Workers (Durable Objects, Workflows, Browser Rendering): https://unstuck.sh/docs/cloudflare-workers/
|
|
23
111
|
|
|
24
112
|
License: Apache-2.0, including the engine.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
interface TakeoverLink {
|
|
2
|
+
url: string;
|
|
3
|
+
reason: string;
|
|
4
|
+
sessionId: string;
|
|
5
|
+
expiresAt: number;
|
|
6
|
+
/** The 6-digit code to give the human, when the takeover requires one. Never part of `url`. */
|
|
7
|
+
code?: string;
|
|
8
|
+
}
|
|
9
|
+
interface TakeoverOptions {
|
|
10
|
+
reason: string;
|
|
11
|
+
timeoutS?: number;
|
|
12
|
+
requireCode?: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* The human can only navigate the page within its own site (example.com and its subdomains). List any other
|
|
15
|
+
* sites the flow needs, e.g. ['accounts.google.com'] for a Google sign-in or a 3-D Secure provider.
|
|
16
|
+
*/
|
|
17
|
+
allowedSites?: string[];
|
|
18
|
+
/**
|
|
19
|
+
* With Unstuck Cloud, the link is also sent to your paired phones; false skips that for this takeover (default true).
|
|
20
|
+
* 'required': with Unstuck Cloud, end the takeover at once with status `failed`, detail `alert_failed`, if Unstuck
|
|
21
|
+
* Cloud can't accept the link for at least one paired phone (alerts not allowed for the key, no paired phone, every
|
|
22
|
+
* seal failed, or notify answered non-2xx). Without Unstuck Cloud (a self-hosted relay) it throws UnstuckConfigError.
|
|
23
|
+
*/
|
|
24
|
+
alerts?: boolean | 'required';
|
|
25
|
+
}
|
|
26
|
+
interface UnstuckOptions {
|
|
27
|
+
/** Node only: path to the engine binary. */
|
|
28
|
+
enginePath?: string;
|
|
29
|
+
/** Node only: host the engine's local server binds to. */
|
|
30
|
+
host?: string;
|
|
31
|
+
/** Node only: port the engine's local server binds to. */
|
|
32
|
+
port?: number;
|
|
33
|
+
/** Default takeover timeout in seconds (engine default: 600). */
|
|
34
|
+
timeoutS?: number;
|
|
35
|
+
/**
|
|
36
|
+
* Called when a human is needed. Default: binary mode prints the link to stderr. In-process mode uses console.log: with
|
|
37
|
+
* Unstuck Cloud phone alerts on, it waits for the alert and logs the link only if no paired phone got it (otherwise one
|
|
38
|
+
* line without the link); with a self-hosted relay or `alerts: false` it logs the link. A handler that throws (or
|
|
39
|
+
* returns a promise that rejects) is logged without the link, and the takeover goes on.
|
|
40
|
+
*/
|
|
41
|
+
onLink?: (link: TakeoverLink) => void;
|
|
42
|
+
/** Relay to use instead of the local server, e.g. wss://relay.example.com (or set UNSTUCK_RELAY_URL); ws:// only to localhost. */
|
|
43
|
+
relay?: string;
|
|
44
|
+
/** Key for that relay (or UNSTUCK_AGENT_KEY). With only UNSTUCK_API_KEY set, Unstuck Cloud is used. */
|
|
45
|
+
agentKey?: string;
|
|
46
|
+
/** Ask the human for a 6-digit code delivered with the link (default false). */
|
|
47
|
+
requireCode?: boolean;
|
|
48
|
+
/** Unstuck Cloud API key. Takes precedence over UNSTUCK_RELAY_URL / UNSTUCK_AGENT_KEY in the environment; not combinable with `relay`. */
|
|
49
|
+
apiKey?: string;
|
|
50
|
+
/** Override the Unstuck Cloud relay URL (only with apiKey). */
|
|
51
|
+
cloudRelay?: string;
|
|
52
|
+
/** Override the Unstuck Cloud API URL (only with apiKey). */
|
|
53
|
+
cloudApi?: string;
|
|
54
|
+
/** Override the viewer URL used in takeover links (https://, or http:// to localhost). */
|
|
55
|
+
viewerUrl?: string;
|
|
56
|
+
/** 'binary' runs the engine as a child process (Node); 'in-process' runs it in this JavaScript runtime. */
|
|
57
|
+
mode?: 'binary' | 'in-process';
|
|
58
|
+
/** fetch implementation, for tests. Defaults to the global fetch. */
|
|
59
|
+
fetch?: typeof fetch;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The engine binary could not be found, started, or kept running. */
|
|
63
|
+
declare class UnstuckEngineError extends Error {
|
|
64
|
+
readonly enginePath?: string | undefined;
|
|
65
|
+
constructor(message: string, enginePath?: string | undefined);
|
|
66
|
+
}
|
|
67
|
+
/** The options passed to Unstuck are inconsistent. */
|
|
68
|
+
declare class UnstuckConfigError extends Error {
|
|
69
|
+
constructor(message: string);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The page was already closed when Unstuck tried to attach. */
|
|
73
|
+
declare class PageClosedError extends Error {
|
|
74
|
+
constructor();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export { PageClosedError as P, UnstuckConfigError as b, UnstuckEngineError as c };
|
|
78
|
+
export type { TakeoverOptions as T, UnstuckOptions as U, TakeoverLink as a };
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
// src/attach.ts
|
|
2
|
+
var SESSION_DISCONNECTED = ["CDPSession.Disconnected", "Disconnected"];
|
|
3
|
+
var SESSION_DISCONNECTED_SYMBOL = "CDPSession.Disconnected";
|
|
4
|
+
function listen(target, event, cb) {
|
|
5
|
+
if (!target || typeof target.on !== "function") return () => {
|
|
6
|
+
};
|
|
7
|
+
target.on(event, cb);
|
|
8
|
+
return () => void (target.off ?? target.removeListener)?.call(target, event, cb);
|
|
9
|
+
}
|
|
10
|
+
function onSymbolDisconnect(session, cb) {
|
|
11
|
+
const s = session;
|
|
12
|
+
const original = s.emit;
|
|
13
|
+
if (typeof original !== "function") return () => {
|
|
14
|
+
};
|
|
15
|
+
const own = Object.prototype.hasOwnProperty.call(s, "emit");
|
|
16
|
+
let active = true;
|
|
17
|
+
const wrapped = function(type, ...rest) {
|
|
18
|
+
if (active && typeof type === "symbol" && type.description === SESSION_DISCONNECTED_SYMBOL) cb();
|
|
19
|
+
return original.call(this, type, ...rest);
|
|
20
|
+
};
|
|
21
|
+
s.emit = wrapped;
|
|
22
|
+
return () => {
|
|
23
|
+
active = false;
|
|
24
|
+
if (s.emit !== wrapped) return;
|
|
25
|
+
if (own) s.emit = original;
|
|
26
|
+
else delete s.emit;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
var PageClosedError = class extends Error {
|
|
30
|
+
constructor() {
|
|
31
|
+
super("page closed");
|
|
32
|
+
this.name = "PageClosedError";
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var counter = 0;
|
|
36
|
+
var newPageId = () => `page-${Date.now().toString(36)}-${(counter++).toString(36)}`;
|
|
37
|
+
async function attachPage(page) {
|
|
38
|
+
const p = page;
|
|
39
|
+
const isPlaywright = !!p && typeof p.context === "function" && typeof p.context()?.newCDPSession === "function";
|
|
40
|
+
const isPuppeteer = !!p && typeof p.createCDPSession === "function";
|
|
41
|
+
if (!isPlaywright && !isPuppeteer) throw new TypeError("Unsupported page object: pass a Playwright or Puppeteer Page");
|
|
42
|
+
const isClosed = () => typeof p.isClosed === "function" ? Boolean(p.isClosed()) : false;
|
|
43
|
+
if (isClosed()) throw new PageClosedError();
|
|
44
|
+
let session;
|
|
45
|
+
try {
|
|
46
|
+
session = isPlaywright ? await p.context().newCDPSession(p) : await p.createCDPSession();
|
|
47
|
+
} catch (e) {
|
|
48
|
+
if (isClosed()) throw new PageClosedError();
|
|
49
|
+
throw e;
|
|
50
|
+
}
|
|
51
|
+
const pageObj = p;
|
|
52
|
+
const closeCbs = [];
|
|
53
|
+
let closedReason = null;
|
|
54
|
+
const fire = (reason) => () => {
|
|
55
|
+
if (closedReason !== null) return;
|
|
56
|
+
closedReason = reason;
|
|
57
|
+
for (const cb of closeCbs) cb(reason);
|
|
58
|
+
};
|
|
59
|
+
const onPageClose = fire("page closed");
|
|
60
|
+
const onCrash = fire("page crashed");
|
|
61
|
+
pageObj.on("close", onPageClose);
|
|
62
|
+
pageObj.on("crash", onCrash);
|
|
63
|
+
const onDisconnect = fire("browser disconnected");
|
|
64
|
+
const browser = isPlaywright ? p.context().browser?.() : p.browser?.();
|
|
65
|
+
const offDisconnect = [
|
|
66
|
+
...SESSION_DISCONNECTED.map((event) => listen(session, event, onDisconnect)),
|
|
67
|
+
onSymbolDisconnect(session, onDisconnect),
|
|
68
|
+
listen(browser, "disconnected", onDisconnect)
|
|
69
|
+
];
|
|
70
|
+
return {
|
|
71
|
+
pageId: newPageId(),
|
|
72
|
+
url: () => pageObj.url?.() ?? "",
|
|
73
|
+
send: (method, params) => session.send(method, params),
|
|
74
|
+
subscribe: (event, cb) => void session.on(event, cb),
|
|
75
|
+
onClose: (cb) => {
|
|
76
|
+
if (closedReason !== null) cb(closedReason);
|
|
77
|
+
else closeCbs.push(cb);
|
|
78
|
+
},
|
|
79
|
+
async detach() {
|
|
80
|
+
pageObj.off?.("close", onPageClose);
|
|
81
|
+
pageObj.off?.("crash", onCrash);
|
|
82
|
+
for (const off of offDisconnect) off();
|
|
83
|
+
await session.detach().catch(() => {
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// src/errors.ts
|
|
90
|
+
var UnstuckEngineError = class extends Error {
|
|
91
|
+
constructor(message, enginePath) {
|
|
92
|
+
super(message);
|
|
93
|
+
this.enginePath = enginePath;
|
|
94
|
+
this.name = "UnstuckEngineError";
|
|
95
|
+
}
|
|
96
|
+
enginePath;
|
|
97
|
+
};
|
|
98
|
+
var UnstuckConfigError = class extends Error {
|
|
99
|
+
constructor(message) {
|
|
100
|
+
super(message);
|
|
101
|
+
this.name = "UnstuckConfigError";
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// src/options.ts
|
|
106
|
+
var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
107
|
+
function checkUrl(name, value, secure, plain) {
|
|
108
|
+
if (!value) return;
|
|
109
|
+
let url = null;
|
|
110
|
+
try {
|
|
111
|
+
url = new URL(value);
|
|
112
|
+
} catch {
|
|
113
|
+
}
|
|
114
|
+
if (url?.protocol === `${secure}:` || url?.protocol === `${plain}:` && LOCAL_HOSTS.has(url.hostname)) return;
|
|
115
|
+
throw new UnstuckConfigError(`${name} must be a ${secure}:// URL (${plain}:// only to localhost, 127.0.0.1 or [::1])`);
|
|
116
|
+
}
|
|
117
|
+
function validateOptions(o) {
|
|
118
|
+
if (o.apiKey && o.relay) throw new UnstuckConfigError("use either apiKey (Unstuck Cloud) or relay + agentKey (your own relay), not both");
|
|
119
|
+
if (o.apiKey && o.agentKey) throw new UnstuckConfigError("agentKey is for your own relay (with relay); Unstuck Cloud only needs apiKey");
|
|
120
|
+
if ((o.cloudRelay || o.cloudApi) && !o.apiKey) throw new UnstuckConfigError("cloudRelay and cloudApi only apply with apiKey");
|
|
121
|
+
checkUrl("relay", o.relay, "wss", "ws");
|
|
122
|
+
checkUrl("cloudRelay", o.cloudRelay, "wss", "ws");
|
|
123
|
+
checkUrl("cloudApi", o.cloudApi, "https", "http");
|
|
124
|
+
checkUrl("viewerUrl", o.viewerUrl, "https", "http");
|
|
125
|
+
}
|
|
126
|
+
function optionEnv(o) {
|
|
127
|
+
const env = {};
|
|
128
|
+
if (o.apiKey) {
|
|
129
|
+
env.UNSTUCK_API_KEY = o.apiKey;
|
|
130
|
+
env.UNSTUCK_RELAY_URL = void 0;
|
|
131
|
+
env.UNSTUCK_AGENT_KEY = void 0;
|
|
132
|
+
}
|
|
133
|
+
if (o.cloudRelay) env.UNSTUCK_CLOUD_URL = o.cloudRelay;
|
|
134
|
+
if (o.cloudApi) env.UNSTUCK_CLOUD_API = o.cloudApi;
|
|
135
|
+
if (o.viewerUrl) env.UNSTUCK_VIEWER_URL = o.viewerUrl;
|
|
136
|
+
if (o.relay) env.UNSTUCK_RELAY_URL = o.relay;
|
|
137
|
+
if (o.agentKey) env.UNSTUCK_AGENT_KEY = o.agentKey;
|
|
138
|
+
return env;
|
|
139
|
+
}
|
|
140
|
+
function redactLink(text, url) {
|
|
141
|
+
const hash = url.indexOf("#");
|
|
142
|
+
const fragment = hash < 0 ? "" : url.slice(hash + 1);
|
|
143
|
+
const values = [...new URLSearchParams(fragment).values()].filter(Boolean).sort((a, b) => b.length - a.length);
|
|
144
|
+
let out = text.replaceAll(url, "<link>");
|
|
145
|
+
if (fragment) out = out.replaceAll(fragment, "<link secret>");
|
|
146
|
+
for (const v of values) out = out.replaceAll(v, "<link secret>");
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
function callUserOnLink(onLink, l) {
|
|
150
|
+
const report = (e) => console.error(`Unstuck: your onLink handler threw (${redactLink(String(e?.message ?? e), l.url)}); the takeover goes on (session ${l.sessionId})`);
|
|
151
|
+
try {
|
|
152
|
+
const returned = onLink(l);
|
|
153
|
+
if (typeof returned?.then === "function") returned.then(void 0, report);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
report(e);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/in-process.ts
|
|
160
|
+
import {
|
|
161
|
+
buildRelayTransport,
|
|
162
|
+
cloudAlertsFor,
|
|
163
|
+
createCloudAlerter,
|
|
164
|
+
createEngine,
|
|
165
|
+
hostnames,
|
|
166
|
+
selectTransport,
|
|
167
|
+
sendTakeoverAlert
|
|
168
|
+
} from "@velmlabs/unstuck-core";
|
|
169
|
+
|
|
170
|
+
// src/cdp-adapter.ts
|
|
171
|
+
function toCdpClient(page) {
|
|
172
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
173
|
+
const closeHandlers = /* @__PURE__ */ new Set();
|
|
174
|
+
let closedReason = null;
|
|
175
|
+
page.onClose((reason) => {
|
|
176
|
+
closedReason = reason;
|
|
177
|
+
for (const h of [...closeHandlers]) h(reason);
|
|
178
|
+
closeHandlers.clear();
|
|
179
|
+
});
|
|
180
|
+
return {
|
|
181
|
+
send: (method, params) => page.send(method, params),
|
|
182
|
+
on(event, handler) {
|
|
183
|
+
let set = handlers.get(event);
|
|
184
|
+
if (!set) {
|
|
185
|
+
const fresh = /* @__PURE__ */ new Set();
|
|
186
|
+
handlers.set(event, fresh);
|
|
187
|
+
page.subscribe(event, (params) => {
|
|
188
|
+
for (const h of [...fresh]) h(params);
|
|
189
|
+
});
|
|
190
|
+
set = fresh;
|
|
191
|
+
}
|
|
192
|
+
set.add(handler);
|
|
193
|
+
return () => void set.delete(handler);
|
|
194
|
+
},
|
|
195
|
+
onClose(handler) {
|
|
196
|
+
if (closedReason !== null) {
|
|
197
|
+
const reason = closedReason;
|
|
198
|
+
let active = true;
|
|
199
|
+
queueMicrotask(() => active && handler(reason));
|
|
200
|
+
return () => void (active = false);
|
|
201
|
+
}
|
|
202
|
+
closeHandlers.add(handler);
|
|
203
|
+
return () => void closeHandlers.delete(handler);
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
function startKeepAlive(cdp, intervalMs = 6e4) {
|
|
208
|
+
const timer = setInterval(() => {
|
|
209
|
+
cdp.send("Runtime.evaluate", { expression: "0" }).catch(() => {
|
|
210
|
+
});
|
|
211
|
+
}, intervalMs);
|
|
212
|
+
return () => clearInterval(timer);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/version.ts
|
|
216
|
+
var VERSION = "0.2.0";
|
|
217
|
+
|
|
218
|
+
// src/in-process.ts
|
|
219
|
+
var NO_RELAY_EDGE = "in a Worker, Unstuck needs a relay: set apiKey or relay + agentKey";
|
|
220
|
+
function defaultOnLink(l, alert, alerts) {
|
|
221
|
+
const full = () => console.log(`Unstuck: a human is needed (${l.reason}) \u2192 ${l.url}`);
|
|
222
|
+
if (!alert) return full();
|
|
223
|
+
void alert.then((r) => {
|
|
224
|
+
if (r.delivered > 0) console.log(`Unstuck: a human is needed (${l.reason}), link sent to ${r.delivered} paired phone(s) (session ${l.sessionId})`);
|
|
225
|
+
else if (alerts !== "required") full();
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
function siteOf(url) {
|
|
229
|
+
try {
|
|
230
|
+
return new URL(url).hostname || void 0;
|
|
231
|
+
} catch {
|
|
232
|
+
return void 0;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
var InProcessUnstuck = class {
|
|
236
|
+
constructor(opts, env, noRelay = NO_RELAY_EDGE) {
|
|
237
|
+
this.opts = opts;
|
|
238
|
+
this.noRelay = noRelay;
|
|
239
|
+
validateOptions(opts);
|
|
240
|
+
this.env = { ...env, ...optionEnv(opts) };
|
|
241
|
+
this.choice = selectTransport({}, this.env);
|
|
242
|
+
const cloud = cloudAlertsFor(this.choice, this.env);
|
|
243
|
+
this.alerter = cloud ? createCloudAlerter({ ...cloud, fetch: opts.fetch }) : null;
|
|
244
|
+
}
|
|
245
|
+
opts;
|
|
246
|
+
noRelay;
|
|
247
|
+
env;
|
|
248
|
+
choice;
|
|
249
|
+
alerter;
|
|
250
|
+
engine = null;
|
|
251
|
+
/** Bumped by close(): a takeover that was still attaching when it ran must not start a new engine. */
|
|
252
|
+
generation = 0;
|
|
253
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
254
|
+
async takeover(page, o) {
|
|
255
|
+
const run = this.run(page, o);
|
|
256
|
+
this.inFlight.add(run);
|
|
257
|
+
try {
|
|
258
|
+
return await run;
|
|
259
|
+
} finally {
|
|
260
|
+
this.inFlight.delete(run);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
async run(page, o) {
|
|
264
|
+
if (this.choice.kind !== "relay") throw new UnstuckConfigError(this.noRelay);
|
|
265
|
+
if (o.alerts === "required" && !this.alerter)
|
|
266
|
+
throw new UnstuckConfigError("alerts: 'required' needs Unstuck Cloud (apiKey): a self-hosted relay sends no phone alerts");
|
|
267
|
+
const requireCode = o.requireCode ?? this.opts.requireCode ?? this.env.UNSTUCK_REQUIRE_CODE === "1";
|
|
268
|
+
if (requireCode && !this.opts.onLink)
|
|
269
|
+
throw new TypeError("requireCode needs an onLink handler that sends the 6-digit code by a different channel than the link (printed together, the code protects nothing)");
|
|
270
|
+
const generation = this.generation;
|
|
271
|
+
let attached;
|
|
272
|
+
try {
|
|
273
|
+
attached = await attachPage(page);
|
|
274
|
+
} catch (e) {
|
|
275
|
+
if (e instanceof PageClosedError) return { status: "failed", sessionId: "", url: "", durationS: 0, detail: "page_closed" };
|
|
276
|
+
throw e;
|
|
277
|
+
}
|
|
278
|
+
if (generation !== this.generation) {
|
|
279
|
+
await attached.detach();
|
|
280
|
+
return { status: "cancelled", sessionId: "", url: "", durationS: 0, detail: "engine_closed" };
|
|
281
|
+
}
|
|
282
|
+
const cdp = toCdpClient(attached);
|
|
283
|
+
const stopKeepAlive = startKeepAlive(cdp);
|
|
284
|
+
const popups = [];
|
|
285
|
+
const popupCbs = /* @__PURE__ */ new Set();
|
|
286
|
+
let ended = false;
|
|
287
|
+
const onPopup = async (popupPage) => {
|
|
288
|
+
try {
|
|
289
|
+
const popup = await attachPage(popupPage);
|
|
290
|
+
if (ended) return void await popup.detach();
|
|
291
|
+
popups.push(popup);
|
|
292
|
+
const client = toCdpClient(popup);
|
|
293
|
+
for (const cb of [...popupCbs]) cb(client);
|
|
294
|
+
} catch {
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
const source = {
|
|
298
|
+
onPopup(cb) {
|
|
299
|
+
popupCbs.add(cb);
|
|
300
|
+
return () => void popupCbs.delete(cb);
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
const events = page;
|
|
304
|
+
events.on("popup", onPopup);
|
|
305
|
+
const site = siteOf(attached.url());
|
|
306
|
+
const userOnLink = this.opts.onLink;
|
|
307
|
+
try {
|
|
308
|
+
return await this.ensureEngine().takeover(cdp, {
|
|
309
|
+
reason: o.reason,
|
|
310
|
+
timeoutS: o.timeoutS ?? this.opts.timeoutS,
|
|
311
|
+
site,
|
|
312
|
+
requireCode,
|
|
313
|
+
allowedSites: hostnames(o.allowedSites),
|
|
314
|
+
popups: source,
|
|
315
|
+
onLink: (info, takeover) => {
|
|
316
|
+
const alert = sendTakeoverAlert(this.alerter, o.alerts, info, site, takeover);
|
|
317
|
+
const link = { url: info.url, reason: info.reason, sessionId: info.sessionId, expiresAt: info.expiresAt, ...info.code ? { code: info.code } : {} };
|
|
318
|
+
if (userOnLink) callUserOnLink(userOnLink, link);
|
|
319
|
+
else defaultOnLink(link, alert, o.alerts);
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
} finally {
|
|
323
|
+
ended = true;
|
|
324
|
+
stopKeepAlive();
|
|
325
|
+
events.off?.("popup", onPopup);
|
|
326
|
+
for (const popup of popups) await popup.detach();
|
|
327
|
+
await attached.detach();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Cancels running takeovers (`engine_closed`), also those still attaching their page, closes the relay sockets and
|
|
332
|
+
* resolves once they have all ended. A later takeover starts a new engine.
|
|
333
|
+
*/
|
|
334
|
+
async close() {
|
|
335
|
+
this.generation++;
|
|
336
|
+
const engine = this.engine;
|
|
337
|
+
this.engine = null;
|
|
338
|
+
await engine?.close();
|
|
339
|
+
await Promise.allSettled([...this.inFlight]);
|
|
340
|
+
}
|
|
341
|
+
ensureEngine() {
|
|
342
|
+
const choice = this.choice;
|
|
343
|
+
this.engine ??= createEngine({ transport: buildRelayTransport(choice, { env: this.env, version: VERSION, warn: (l) => console.error(l) }) });
|
|
344
|
+
return this.engine;
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
export {
|
|
349
|
+
PageClosedError,
|
|
350
|
+
attachPage,
|
|
351
|
+
UnstuckEngineError,
|
|
352
|
+
UnstuckConfigError,
|
|
353
|
+
VERSION,
|
|
354
|
+
validateOptions,
|
|
355
|
+
optionEnv,
|
|
356
|
+
callUserOnLink,
|
|
357
|
+
InProcessUnstuck
|
|
358
|
+
};
|
package/dist/edge.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { TakeoverResult } from '@velmlabs/unstuck-protocol';
|
|
2
|
+
export { TakeoverResult, TakeoverStatus } from '@velmlabs/unstuck-protocol';
|
|
3
|
+
import { U as UnstuckOptions, T as TakeoverOptions } from './attach-C-IOJk5Z.js';
|
|
4
|
+
export { P as PageClosedError, a as TakeoverLink, b as UnstuckConfigError, c as UnstuckEngineError } from './attach-C-IOJk5Z.js';
|
|
5
|
+
|
|
6
|
+
declare class Unstuck {
|
|
7
|
+
private readonly inner;
|
|
8
|
+
constructor(opts?: UnstuckOptions);
|
|
9
|
+
takeover(page: unknown, o: TakeoverOptions): Promise<TakeoverResult>;
|
|
10
|
+
/** Waits for in-flight takeovers: do not await it from inside onLink. */
|
|
11
|
+
close(): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export { TakeoverOptions, Unstuck, UnstuckOptions };
|
package/dist/edge.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {
|
|
2
|
+
InProcessUnstuck,
|
|
3
|
+
PageClosedError,
|
|
4
|
+
UnstuckConfigError,
|
|
5
|
+
UnstuckEngineError,
|
|
6
|
+
validateOptions
|
|
7
|
+
} from "./chunk-BVSFTOIP.js";
|
|
8
|
+
|
|
9
|
+
// src/edge.ts
|
|
10
|
+
var Unstuck = class {
|
|
11
|
+
inner;
|
|
12
|
+
constructor(opts = {}) {
|
|
13
|
+
validateOptions(opts);
|
|
14
|
+
if (opts.mode === "binary") throw new UnstuckConfigError("binary mode needs Node.js: this runtime loaded the in-process entry, which has no engine binary");
|
|
15
|
+
this.inner = new InProcessUnstuck(opts, {});
|
|
16
|
+
}
|
|
17
|
+
takeover(page, o) {
|
|
18
|
+
return this.inner.takeover(page, o);
|
|
19
|
+
}
|
|
20
|
+
/** Waits for in-flight takeovers: do not await it from inside onLink. */
|
|
21
|
+
close() {
|
|
22
|
+
return this.inner.close();
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
export {
|
|
26
|
+
PageClosedError,
|
|
27
|
+
Unstuck,
|
|
28
|
+
UnstuckConfigError,
|
|
29
|
+
UnstuckEngineError
|
|
30
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,66 +1,24 @@
|
|
|
1
1
|
import { TakeoverResult } from '@velmlabs/unstuck-protocol';
|
|
2
2
|
export { TakeoverResult, TakeoverStatus } from '@velmlabs/unstuck-protocol';
|
|
3
|
+
import { U as UnstuckOptions, T as TakeoverOptions } from './attach-C-IOJk5Z.js';
|
|
4
|
+
export { P as PageClosedError, a as TakeoverLink, b as UnstuckConfigError, c as UnstuckEngineError } from './attach-C-IOJk5Z.js';
|
|
3
5
|
|
|
4
|
-
interface TakeoverLink {
|
|
5
|
-
url: string;
|
|
6
|
-
reason: string;
|
|
7
|
-
sessionId: string;
|
|
8
|
-
expiresAt: number;
|
|
9
|
-
/** The 6-digit code to give the human, when the takeover requires one. Never part of `url`. */
|
|
10
|
-
code?: string;
|
|
11
|
-
}
|
|
12
|
-
interface UnstuckOptions {
|
|
13
|
-
enginePath?: string;
|
|
14
|
-
host?: string;
|
|
15
|
-
port?: number;
|
|
16
|
-
/** Default takeover timeout in seconds (engine default: 600). */
|
|
17
|
-
timeoutS?: number;
|
|
18
|
-
/** Called when a human is needed. Default: print the link to stderr. */
|
|
19
|
-
onLink?: (link: TakeoverLink) => void;
|
|
20
|
-
/** Relay to use instead of the local server, e.g. wss://relay.example.com (or set UNSTUCK_RELAY_URL). */
|
|
21
|
-
relay?: string;
|
|
22
|
-
/** Key for that relay (or UNSTUCK_AGENT_KEY). With only UNSTUCK_API_KEY set, Unstuck Cloud is used. */
|
|
23
|
-
agentKey?: string;
|
|
24
|
-
/** Ask the human for a 6-digit code delivered with the link (default false). */
|
|
25
|
-
requireCode?: boolean;
|
|
26
|
-
}
|
|
27
6
|
declare class Unstuck {
|
|
28
7
|
private readonly opts;
|
|
29
8
|
private engine;
|
|
30
9
|
private readonly pages;
|
|
31
10
|
private inFlight;
|
|
11
|
+
/** Set for `mode: 'in-process'`: every method delegates to it. */
|
|
12
|
+
private readonly inProcess;
|
|
32
13
|
constructor(opts?: UnstuckOptions);
|
|
33
14
|
/**
|
|
34
15
|
* Pauses your agent until a human finishes. Awaiting this IS the pause: don't drive the page meanwhile.
|
|
35
16
|
* Resolves with the outcome; rejects only with UnstuckEngineError if the engine can't run.
|
|
36
17
|
*/
|
|
37
|
-
takeover(page: unknown, opts:
|
|
38
|
-
reason: string;
|
|
39
|
-
timeoutS?: number;
|
|
40
|
-
requireCode?: boolean;
|
|
41
|
-
/**
|
|
42
|
-
* The human can only navigate the page within its own site (example.com and its subdomains). List any other
|
|
43
|
-
* sites the flow needs, e.g. ['accounts.google.com'] for a Google sign-in or a 3-D Secure provider.
|
|
44
|
-
*/
|
|
45
|
-
allowedSites?: string[];
|
|
46
|
-
/** With Unstuck Cloud, the link is also sent to your paired phones; false skips that for this takeover (default true). */
|
|
47
|
-
alerts?: boolean;
|
|
48
|
-
}): Promise<TakeoverResult>;
|
|
18
|
+
takeover(page: unknown, opts: TakeoverOptions): Promise<TakeoverResult>;
|
|
49
19
|
/** Stops the engine (cancelling any running takeover). */
|
|
50
20
|
close(): Promise<void>;
|
|
51
21
|
private ensureEngine;
|
|
52
22
|
}
|
|
53
23
|
|
|
54
|
-
|
|
55
|
-
declare class UnstuckEngineError extends Error {
|
|
56
|
-
readonly enginePath?: string | undefined;
|
|
57
|
-
constructor(message: string, enginePath?: string | undefined);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** The page was already closed when Unstuck tried to attach. */
|
|
61
|
-
declare class PageClosedError extends Error {
|
|
62
|
-
constructor();
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export { PageClosedError, Unstuck, UnstuckEngineError };
|
|
66
|
-
export type { TakeoverLink, UnstuckOptions };
|
|
24
|
+
export { TakeoverOptions, Unstuck, UnstuckOptions };
|
package/dist/index.js
CHANGED
|
@@ -1,82 +1,26 @@
|
|
|
1
|
+
import {
|
|
2
|
+
InProcessUnstuck,
|
|
3
|
+
PageClosedError,
|
|
4
|
+
UnstuckConfigError,
|
|
5
|
+
UnstuckEngineError,
|
|
6
|
+
VERSION,
|
|
7
|
+
attachPage,
|
|
8
|
+
callUserOnLink,
|
|
9
|
+
optionEnv,
|
|
10
|
+
validateOptions
|
|
11
|
+
} from "./chunk-BVSFTOIP.js";
|
|
12
|
+
|
|
1
13
|
// src/unstuck.ts
|
|
2
14
|
import {
|
|
3
15
|
Methods as Methods2,
|
|
4
16
|
RpcCallError as RpcCallError2
|
|
5
17
|
} from "@velmlabs/unstuck-protocol";
|
|
6
18
|
|
|
7
|
-
// src/attach.ts
|
|
8
|
-
var PageClosedError = class extends Error {
|
|
9
|
-
constructor() {
|
|
10
|
-
super("page closed");
|
|
11
|
-
this.name = "PageClosedError";
|
|
12
|
-
}
|
|
13
|
-
};
|
|
14
|
-
var counter = 0;
|
|
15
|
-
var newPageId = () => `page-${Date.now().toString(36)}-${(counter++).toString(36)}`;
|
|
16
|
-
async function attachPage(page) {
|
|
17
|
-
const p = page;
|
|
18
|
-
const isPlaywright = !!p && typeof p.context === "function" && typeof p.context()?.newCDPSession === "function";
|
|
19
|
-
const isPuppeteer = !!p && typeof p.createCDPSession === "function";
|
|
20
|
-
if (!isPlaywright && !isPuppeteer) throw new TypeError("Unsupported page object: pass a Playwright or Puppeteer Page");
|
|
21
|
-
const isClosed = () => typeof p.isClosed === "function" ? Boolean(p.isClosed()) : false;
|
|
22
|
-
if (isClosed()) throw new PageClosedError();
|
|
23
|
-
let session;
|
|
24
|
-
try {
|
|
25
|
-
session = isPlaywright ? await p.context().newCDPSession(p) : await p.createCDPSession();
|
|
26
|
-
} catch (e) {
|
|
27
|
-
if (isClosed()) throw new PageClosedError();
|
|
28
|
-
throw e;
|
|
29
|
-
}
|
|
30
|
-
const pageObj = p;
|
|
31
|
-
const closeCbs = [];
|
|
32
|
-
let closedReason = null;
|
|
33
|
-
const fire = (reason) => () => {
|
|
34
|
-
if (closedReason !== null) return;
|
|
35
|
-
closedReason = reason;
|
|
36
|
-
for (const cb of closeCbs) cb(reason);
|
|
37
|
-
};
|
|
38
|
-
const onPageClose = fire("page closed");
|
|
39
|
-
const onCrash = fire("page crashed");
|
|
40
|
-
pageObj.on("close", onPageClose);
|
|
41
|
-
pageObj.on("crash", onCrash);
|
|
42
|
-
return {
|
|
43
|
-
pageId: newPageId(),
|
|
44
|
-
url: () => pageObj.url?.() ?? "",
|
|
45
|
-
send: (method, params) => session.send(method, params),
|
|
46
|
-
subscribe: (event, cb) => void session.on(event, cb),
|
|
47
|
-
onClose: (cb) => {
|
|
48
|
-
if (closedReason !== null) cb(closedReason);
|
|
49
|
-
else closeCbs.push(cb);
|
|
50
|
-
},
|
|
51
|
-
async detach() {
|
|
52
|
-
pageObj.off?.("close", onPageClose);
|
|
53
|
-
pageObj.off?.("crash", onCrash);
|
|
54
|
-
await session.detach().catch(() => {
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
|
|
60
19
|
// src/engine-process.ts
|
|
61
20
|
import { spawn } from "child_process";
|
|
62
21
|
import { createRequire } from "module";
|
|
63
22
|
import readline from "readline";
|
|
64
23
|
import { createRpcPeer, Methods, PROTOCOL_VERSION, RpcCallError } from "@velmlabs/unstuck-protocol";
|
|
65
|
-
|
|
66
|
-
// src/errors.ts
|
|
67
|
-
var UnstuckEngineError = class extends Error {
|
|
68
|
-
constructor(message, enginePath) {
|
|
69
|
-
super(message);
|
|
70
|
-
this.enginePath = enginePath;
|
|
71
|
-
this.name = "UnstuckEngineError";
|
|
72
|
-
}
|
|
73
|
-
enginePath;
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
// src/version.ts
|
|
77
|
-
var VERSION = "0.1.7";
|
|
78
|
-
|
|
79
|
-
// src/engine-process.ts
|
|
80
24
|
var requireFromHere = createRequire(import.meta.url);
|
|
81
25
|
function resolveViaEngine(id, base = requireFromHere, make = createRequire) {
|
|
82
26
|
try {
|
|
@@ -104,7 +48,7 @@ async function spawnEngine(path, opts) {
|
|
|
104
48
|
const args = ["--stdio"];
|
|
105
49
|
if (opts.host) args.push("--host", opts.host);
|
|
106
50
|
if (opts.port !== void 0) args.push("--port", String(opts.port));
|
|
107
|
-
const env =
|
|
51
|
+
const env = Object.fromEntries(Object.entries(opts.env ?? process.env).filter(([, v]) => v !== void 0));
|
|
108
52
|
const child = spawn(path, args, { stdio: ["pipe", "pipe", "inherit"], env });
|
|
109
53
|
const peer = createRpcPeer((line) => {
|
|
110
54
|
if (child.stdin.writable) child.stdin.write(line + "\n");
|
|
@@ -182,16 +126,21 @@ function siteOf(url) {
|
|
|
182
126
|
var Unstuck = class {
|
|
183
127
|
constructor(opts = {}) {
|
|
184
128
|
this.opts = opts;
|
|
129
|
+
validateOptions(opts);
|
|
130
|
+
this.inProcess = opts.mode === "in-process" ? new InProcessUnstuck(opts, process.env, "in-process mode needs a relay: set apiKey or relay + agentKey") : null;
|
|
185
131
|
}
|
|
186
132
|
opts;
|
|
187
133
|
engine = null;
|
|
188
134
|
pages = /* @__PURE__ */ new Map();
|
|
189
135
|
inFlight = 0;
|
|
136
|
+
/** Set for `mode: 'in-process'`: every method delegates to it. */
|
|
137
|
+
inProcess;
|
|
190
138
|
/**
|
|
191
139
|
* Pauses your agent until a human finishes. Awaiting this IS the pause: don't drive the page meanwhile.
|
|
192
140
|
* Resolves with the outcome; rejects only with UnstuckEngineError if the engine can't run.
|
|
193
141
|
*/
|
|
194
142
|
async takeover(page, opts) {
|
|
143
|
+
if (this.inProcess) return this.inProcess.takeover(page, opts);
|
|
195
144
|
if ((opts.requireCode ?? this.opts.requireCode ?? process.env.UNSTUCK_REQUIRE_CODE === "1") && !this.opts.onLink)
|
|
196
145
|
throw new TypeError("requireCode needs an onLink handler that sends the 6-digit code by a different channel than the link (printed together, the code protects nothing)");
|
|
197
146
|
const pageClosed = { status: "failed", sessionId: "", url: "", durationS: 0, detail: "page_closed" };
|
|
@@ -253,6 +202,7 @@ var Unstuck = class {
|
|
|
253
202
|
return await Promise.race([engine.peer.request(Methods2.takeover, params), died]);
|
|
254
203
|
} catch (e) {
|
|
255
204
|
if (e instanceof RpcCallError2 && e.code === "closed") throw new UnstuckEngineError(`engine exited with code ${await engine.exited}`);
|
|
205
|
+
if (e instanceof RpcCallError2 && e.code === "config_error") throw new UnstuckConfigError(e.message);
|
|
256
206
|
throw e;
|
|
257
207
|
}
|
|
258
208
|
} finally {
|
|
@@ -268,6 +218,7 @@ var Unstuck = class {
|
|
|
268
218
|
}
|
|
269
219
|
/** Stops the engine (cancelling any running takeover). */
|
|
270
220
|
async close() {
|
|
221
|
+
if (this.inProcess) return this.inProcess.close();
|
|
271
222
|
const pending = this.engine;
|
|
272
223
|
this.engine = null;
|
|
273
224
|
if (!pending) return;
|
|
@@ -283,7 +234,7 @@ var Unstuck = class {
|
|
|
283
234
|
ensureEngine() {
|
|
284
235
|
if (this.engine) return this.engine;
|
|
285
236
|
const started = (async () => {
|
|
286
|
-
const engine = await spawnEngine(resolveEnginePath(this.opts), { host: this.opts.host, port: this.opts.port,
|
|
237
|
+
const engine = await spawnEngine(resolveEnginePath(this.opts), { host: this.opts.host, port: this.opts.port, env: { ...process.env, ...optionEnv(this.opts) } });
|
|
287
238
|
engine.peer.handle(Methods2.cdpSend, (raw) => {
|
|
288
239
|
const p = raw;
|
|
289
240
|
const page = this.pages.get(p.pageId);
|
|
@@ -299,7 +250,9 @@ var Unstuck = class {
|
|
|
299
250
|
});
|
|
300
251
|
engine.peer.onNotification(Methods2.takeoverLink, (raw) => {
|
|
301
252
|
const l = raw;
|
|
302
|
-
|
|
253
|
+
const link = { url: l.url, reason: l.reason, sessionId: l.sessionId, expiresAt: l.expiresAt, ...l.code ? { code: l.code } : {} };
|
|
254
|
+
if (this.opts.onLink) callUserOnLink(this.opts.onLink, link);
|
|
255
|
+
else defaultOnLink(link);
|
|
303
256
|
});
|
|
304
257
|
void engine.exited.then(() => {
|
|
305
258
|
if (this.engine === started) this.engine = null;
|
|
@@ -316,5 +269,6 @@ var Unstuck = class {
|
|
|
316
269
|
export {
|
|
317
270
|
PageClosedError,
|
|
318
271
|
Unstuck,
|
|
272
|
+
UnstuckConfigError,
|
|
319
273
|
UnstuckEngineError
|
|
320
274
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@velmlabs/unstuck",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Human takeover for AI browser agents: when your agent gets stuck, a person takes over the live browser and hands it back.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -29,6 +29,18 @@
|
|
|
29
29
|
"types": "./dist/index.d.ts",
|
|
30
30
|
"exports": {
|
|
31
31
|
".": {
|
|
32
|
+
"workerd": {
|
|
33
|
+
"types": "./dist/edge.d.ts",
|
|
34
|
+
"default": "./dist/edge.js"
|
|
35
|
+
},
|
|
36
|
+
"worker": {
|
|
37
|
+
"types": "./dist/edge.d.ts",
|
|
38
|
+
"default": "./dist/edge.js"
|
|
39
|
+
},
|
|
40
|
+
"browser": {
|
|
41
|
+
"types": "./dist/edge.d.ts",
|
|
42
|
+
"default": "./dist/edge.js"
|
|
43
|
+
},
|
|
32
44
|
"types": "./dist/index.d.ts",
|
|
33
45
|
"import": "./dist/index.js",
|
|
34
46
|
"default": "./dist/index.js"
|
|
@@ -41,15 +53,22 @@
|
|
|
41
53
|
"node": ">=20"
|
|
42
54
|
},
|
|
43
55
|
"dependencies": {
|
|
44
|
-
"@velmlabs/unstuck-
|
|
45
|
-
"@velmlabs/unstuck-
|
|
56
|
+
"@velmlabs/unstuck-core": "0.2.0",
|
|
57
|
+
"@velmlabs/unstuck-engine": "0.2.0",
|
|
58
|
+
"@velmlabs/unstuck-protocol": "0.2.0"
|
|
46
59
|
},
|
|
47
60
|
"publishConfig": {
|
|
48
61
|
"access": "public"
|
|
49
62
|
},
|
|
63
|
+
"devDependencies": {
|
|
64
|
+
"@cloudflare/vitest-plugin": "^1.8.1",
|
|
65
|
+
"@cloudflare/workers-types": "^5.20261112.1",
|
|
66
|
+
"wrangler": "^4.161.0"
|
|
67
|
+
},
|
|
50
68
|
"scripts": {
|
|
51
69
|
"build": "tsc -p tsconfig.json --noEmit",
|
|
52
70
|
"test": "vitest run --coverage",
|
|
53
|
-
"build:dist": "tsup"
|
|
71
|
+
"build:dist": "tsup",
|
|
72
|
+
"test:workers": "vitest run --config vitest.workers.config.ts"
|
|
54
73
|
}
|
|
55
74
|
}
|