@oya-ai/browser 1.0.97 → 1.0.101

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/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
- // src/types.ts
1
+ // src/errors.ts
2
2
  var OyaError = class extends Error {
3
+ /** The HTTP status, or the SDK's own status for errors it raises itself. */
3
4
  status;
5
+ /** The server's response body, parsed when it was JSON. */
4
6
  body;
7
+ /** Records the message, status and body. */
5
8
  constructor(message, status, body) {
6
9
  super(message);
7
10
  this.name = "OyaError";
@@ -10,8 +13,44 @@ var OyaError = class extends Error {
10
13
  }
11
14
  };
12
15
 
16
+ // src/constants.ts
17
+ var DEFAULT_BASE_URL = "https://browser.getoya.ai";
18
+ var DEFAULT_TIMEOUT_MS = 6e4;
19
+ var START_TIMEOUT_MS = 12e4;
20
+ var READY_TIMEOUT_MS = 12e4;
21
+ var READY_POLL_MS = 2e3;
22
+ var NAVIGATE_TIMEOUT_MS = 12e4;
23
+ var CHALLENGE_TIMEOUT_MS = 18e4;
24
+ var AGENT_TIMEOUT_MS = 6e5;
25
+ var PLAYBOOK_TIMEOUT_MS = 12e4;
26
+ var STOP_TIMEOUT_MS = 6e4;
27
+ var WAIT_FOR_DEFAULT_MS = 3e4;
28
+ var WAIT_FOR_GRACE_MS = 5e3;
29
+ var AIMED_SCROLL_AMOUNT = 500;
30
+ var RUN_POLL_MS = 2e3;
31
+ var MAX_RUN_POLL_ERRORS = 5;
32
+ var BYTES_PER_MB = 1048576;
33
+ var MAX_FILE_MB = 10;
34
+ var BASE64_CHUNK_BYTES = 8192;
35
+ var MS_PER_SECOND = 1e3;
36
+ var Status = {
37
+ /** The caller passed something unusable, such as a non-numeric element id. */
38
+ BAD_REQUEST: 400,
39
+ /** The server does not know that session. */
40
+ NOT_FOUND: 404,
41
+ /** The browser is in a state that needs attention first. */
42
+ CONFLICT: 409,
43
+ /** A browser command ran and failed. */
44
+ UNPROCESSABLE: 422,
45
+ /** A run failed without saying why. */
46
+ SERVER_ERROR: 500,
47
+ /** A browser did not come up in time. */
48
+ GATEWAY_TIMEOUT: 504
49
+ };
50
+
13
51
  // src/client.ts
14
52
  var Http = class {
53
+ /** Stores where to call, with which key, how long to wait and which fetch to use. */
15
54
  constructor(baseUrl, apiKey, timeoutMs, fetchImpl) {
16
55
  this.baseUrl = baseUrl;
17
56
  this.apiKey = apiKey;
@@ -22,36 +61,141 @@ var Http = class {
22
61
  apiKey;
23
62
  timeoutMs;
24
63
  fetchImpl;
64
+ /** Sends one request and returns the parsed answer, or throws an OyaError when it failed. */
25
65
  async request(method, path, body, timeoutMs = this.timeoutMs, headers = {}) {
26
- const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
27
- method,
28
- headers: {
29
- Authorization: `Bearer ${this.apiKey}`,
30
- ...headers,
31
- ...body === void 0 ? {} : { "Content-Type": "application/json" }
32
- },
33
- body: body === void 0 ? void 0 : JSON.stringify(body),
34
- signal: AbortSignal.timeout(timeoutMs)
66
+ const init = requestInit(method, body, timeoutMs, { Authorization: `Bearer ${this.apiKey}`, ...headers });
67
+ return readAnswer(await this.fetchImpl(`${this.baseUrl}${path}`, init), `${method} ${path}`, this.baseUrl);
68
+ }
69
+ };
70
+ function requestInit(method, body, timeoutMs, headers) {
71
+ const json = body === void 0 ? {} : { "Content-Type": "application/json" };
72
+ const payload = body === void 0 ? void 0 : JSON.stringify(body);
73
+ return { method, headers: { ...headers, ...json }, body: payload, signal: AbortSignal.timeout(timeoutMs) };
74
+ }
75
+ async function readAnswer(res, call2, baseUrl) {
76
+ const payload = parseBody(await res.text());
77
+ if (!res.ok) throw failure(call2, res.status, payload, baseUrl);
78
+ return payload;
79
+ }
80
+ function parseBody(text) {
81
+ try {
82
+ return text ? JSON.parse(text) : null;
83
+ } catch {
84
+ return text;
85
+ }
86
+ }
87
+ function failure(call2, status, payload, baseUrl) {
88
+ let message = payload?.error || `${call2} failed (${status})`;
89
+ if (message === "Invalid API key") {
90
+ message += ` for ${baseUrl}. Check OYA_API_KEY: a value exported in your shell beats .env.`;
91
+ }
92
+ return new OyaError(message, status, payload);
93
+ }
94
+ var env = (name) => globalThis.process?.env?.[name];
95
+ function createHttp(options) {
96
+ const apiKey = options.apiKey || env("OYA_API_KEY");
97
+ if (!apiKey) {
98
+ throw new Error("No API key. Pass { apiKey } or set OYA_API_KEY \u2014 run `oya login` to get one.");
99
+ }
100
+ const baseUrl = (options.baseUrl || env("OYA_BASE_URL") || DEFAULT_BASE_URL).replace(/\/+$/, "");
101
+ const fetchImpl = options.fetch || globalThis.fetch;
102
+ if (!fetchImpl) throw new Error("No fetch available \u2014 pass { fetch } or use Node 18+.");
103
+ return new Http(baseUrl, apiKey, options.timeoutMs ?? DEFAULT_TIMEOUT_MS, fetchImpl.bind(globalThis));
104
+ }
105
+
106
+ // src/run-watch.ts
107
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
108
+ async function call(fn) {
109
+ try {
110
+ await fn();
111
+ } catch (err) {
112
+ console.error("[oya] run callback threw:", err);
113
+ }
114
+ }
115
+ async function watchRun(run, baseUrl, cb, pollMs) {
116
+ const watch = { run, baseUrl, cb, errors: 0 };
117
+ for (; ; ) {
118
+ const result = await step(watch);
119
+ if (result) return result;
120
+ await sleep(pollMs);
121
+ }
122
+ }
123
+ async function step(watch) {
124
+ const info = await poll(watch);
125
+ if (!info) return void 0;
126
+ noticeAttention(watch, info);
127
+ if (info.status === "succeeded") return succeed(watch.cb, info);
128
+ if (info.status === "failed") return fail(watch.cb, info);
129
+ return void 0;
130
+ }
131
+ async function poll(watch) {
132
+ try {
133
+ const info = await watch.run.status();
134
+ watch.errors = 0;
135
+ return info;
136
+ } catch (err) {
137
+ if (++watch.errors < MAX_RUN_POLL_ERRORS) return null;
138
+ return giveUp(watch.cb, err);
139
+ }
140
+ }
141
+ async function giveUp(cb, err) {
142
+ const failure2 = err instanceof OyaError ? err : new OyaError(String(err), 0, null);
143
+ await call(() => cb.onFailure?.(failure2));
144
+ throw failure2;
145
+ }
146
+ function noticeAttention(watch, info) {
147
+ if (info.status !== "needs_attention" || !info.attention || info.attention.id === watch.seen) return;
148
+ watch.seen = info.attention.id;
149
+ const request = {
150
+ ...info.attention,
151
+ liveViewUrl: info.attention.liveViewUrl && new URL(info.attention.liveViewUrl, watch.baseUrl).href,
152
+ respond: (response) => watch.run.respond(response)
153
+ };
154
+ void call(() => watch.cb.onHumanAttention?.(request));
155
+ }
156
+ async function succeed(cb, info) {
157
+ const result = info.result || {};
158
+ if (result.healed) await call(() => cb.onHealed?.(result));
159
+ await call(() => cb.onSuccess?.(result));
160
+ return result;
161
+ }
162
+ async function fail(cb, info) {
163
+ const failure2 = new OyaError(info.error || "Run failed", info.errorStatus ?? Status.SERVER_ERROR, info);
164
+ await call(() => cb.onFailure?.(failure2));
165
+ throw failure2;
166
+ }
167
+
168
+ // src/run.ts
169
+ var Run = class {
170
+ /** Starts watching the run straight away. */
171
+ constructor(http, id, callbacks, pollMs = RUN_POLL_MS) {
172
+ this.http = http;
173
+ this.id = id;
174
+ this.done = this.watch(callbacks, pollMs);
175
+ this.done.catch(() => {
35
176
  });
36
- const text = await res.text();
37
- let payload;
38
- try {
39
- payload = text ? JSON.parse(text) : null;
40
- } catch {
41
- payload = text;
42
- }
43
- if (!res.ok) {
44
- let message = payload?.error || `${method} ${path} failed (${res.status})`;
45
- if (message === "Invalid API key") message += ` for ${this.baseUrl}. Check OYA_API_KEY: a value exported in your shell beats .env.`;
46
- throw new OyaError(message, res.status, payload);
47
- }
48
- return payload;
177
+ }
178
+ http;
179
+ id;
180
+ /** Settles with the result when the run succeeds, or rejects when it fails. */
181
+ done;
182
+ /** The run's current state. */
183
+ status() {
184
+ return this.http.request("GET", `/api/runs/${encodeURIComponent(this.id)}`);
185
+ }
186
+ /** Answer the open attention request: `'done'` after handling it by hand, or your reply to the agent. */
187
+ async respond(response = "done") {
188
+ await this.http.request("POST", `/api/runs/${encodeURIComponent(this.id)}/respond`, { response });
189
+ }
190
+ /** Polls until the run ends, firing callbacks on the way. */
191
+ watch(cb, pollMs) {
192
+ return watchRun(this, this.http.baseUrl, cb, pollMs);
49
193
  }
50
194
  };
51
195
 
52
196
  // src/browser.ts
53
- var NAVIGATE_TIMEOUT_MS = 12e4;
54
197
  var Browser = class {
198
+ /** Wraps a started browser; `autoCaptcha` solves CAPTCHAs after every `goto()`. */
55
199
  constructor(http, info, autoCaptcha) {
56
200
  this.http = http;
57
201
  this.autoCaptcha = autoCaptcha;
@@ -62,51 +206,52 @@ var Browser = class {
62
206
  }
63
207
  http;
64
208
  autoCaptcha;
209
+ /** The browser's id. */
65
210
  id;
211
+ /** Which provider runs it. */
66
212
  provider;
213
+ /** Which persona it runs as. */
67
214
  persona;
68
215
  /** Point Playwright, Puppeteer or browser-use here. */
69
216
  cdpUrl;
217
+ /** Runs one browser command; a command that ran and failed throws. */
70
218
  async command(action, params = {}, timeoutMs) {
71
- const result = await this.http.request(
72
- "POST",
73
- `/api/browsers/${this.id}/command`,
74
- { action, params },
75
- timeoutMs
76
- );
77
- if (result.ok === false) throw new OyaError(result.error || `${action} failed`, 422, result);
219
+ const path = `/api/browsers/${this.id}/command`;
220
+ const result = await this.http.request("POST", path, { action, params }, timeoutMs);
221
+ if (result.ok === false) throw new OyaError(result.error || `${action} failed`, Status.UNPROCESSABLE, result);
78
222
  return result.data;
79
223
  }
224
+ /** Navigates, then clears any CAPTCHA when `captcha: 'auto'` was asked for. */
80
225
  async goto(url) {
81
226
  await this.command("navigate", { url }, NAVIGATE_TIMEOUT_MS);
82
- if (this.autoCaptcha) {
83
- const result = await this.solveCaptcha();
84
- if (result.present && !result.solved && !result.invisible) throw new OyaError(result.error || "CAPTCHA needs attention. Call solveCaptcha() again or open the live view.", 409, result);
85
- }
227
+ if (this.autoCaptcha) assertCaptchaCleared(await this.solveCaptcha());
86
228
  }
87
- /** The page as markdown plus numbered elements to act on. */
88
- async analyze() {
89
- return this.command("analyze");
229
+ /**
230
+ * The page, written as markdown (the default), TOON or JSONL, plus its blocks and
231
+ * the numbered elements to act on.
232
+ */
233
+ async analyze(options = {}) {
234
+ return this.command("analyze", options.format ? { format: options.format } : {});
90
235
  }
91
236
  /** Only the visible elements, which is what an agent almost always wants. */
92
237
  async elements() {
93
238
  return (await this.analyze()).elements.filter((e) => e.visible);
94
239
  }
240
+ /** Clicks an element by its id from `analyze()`. */
95
241
  async click(elementId) {
96
242
  const id = this.elementId(elementId);
97
243
  await this.command("click", { element_id: id, selector: `[data-ac-id="${id}"]` });
98
244
  }
245
+ /** Types into an element by its id from `analyze()`. */
99
246
  async type(elementId, text) {
100
247
  const id = this.elementId(elementId);
101
248
  return this.command("type", { element_id: id, selector: `[data-ac-id="${id}"]`, text });
102
249
  }
250
+ /** A valid element id, or an OyaError saying where ids come from. */
103
251
  elementId(value) {
104
- const id = Number(value);
105
- if (typeof value !== "number" && typeof value !== "string" || value === "" || !Number.isInteger(id) || id < 0) {
106
- throw new OyaError("Use a numeric element id from browser.analyze().", 400, null);
107
- }
108
- return id;
252
+ return toElementId(value);
109
253
  }
254
+ /** Presses one key, such as Enter or Escape. */
110
255
  async pressKey(key) {
111
256
  await this.command("press_key", { key });
112
257
  }
@@ -120,47 +265,49 @@ var Browser = class {
120
265
  }
121
266
  /** `at` aims the wheel at an inner scroller (a results panel, a chat pane) instead of the page. */
122
267
  async scroll(direction, amount, at) {
123
- await this.command("scroll", at ? { direction, amount: amount ?? 500, ...at, smooth: false } : { direction, amount });
268
+ await this.command("scroll", scrollParams(direction, amount, at));
124
269
  }
125
- async waitFor(selector, timeout = 3e4) {
126
- await this.command("wait", { selector, timeout }, timeout + 5e3);
270
+ /** Waits until `selector` matches, up to `timeout` milliseconds. */
271
+ async waitFor(selector, timeout = WAIT_FOR_DEFAULT_MS) {
272
+ await this.command("wait", { selector, timeout }, timeout + WAIT_FOR_GRACE_MS);
127
273
  }
128
274
  /** A `data:image/…;base64,` URL. PNG or JPEG depending on the driver. */
129
275
  async screenshot() {
130
- const data = await this.command("screenshot");
131
- return data.screenshot;
276
+ return (await this.command("screenshot")).screenshot;
132
277
  }
278
+ /** The active tab's URL, or empty when there is none. */
133
279
  async url() {
134
- const tabs = await this.tabs();
135
- return tabs.find((t) => t.active)?.url || "";
280
+ return (await this.tabs()).find((t) => t.active)?.url || "";
136
281
  }
282
+ /** Every open tab. */
137
283
  async tabs() {
138
- const data = await this.command("list_tabs");
139
- return data.tabs || [];
284
+ return (await this.command("list_tabs")).tabs || [];
140
285
  }
286
+ /** Opens a tab, optionally at `url`, and returns its id. */
141
287
  async openTab(url) {
142
- const data = await this.command("open_tab", { url }, NAVIGATE_TIMEOUT_MS);
143
- return data.tab_id;
288
+ return (await this.command("open_tab", { url }, NAVIGATE_TIMEOUT_MS)).tab_id;
144
289
  }
290
+ /** Makes a tab the one commands act on. */
145
291
  async switchTab(tabId) {
146
292
  await this.command("switch_tab", { tab_id: tabId });
147
293
  }
294
+ /** Closes a tab. */
148
295
  async closeTab(tabId) {
149
296
  await this.command("close_tab", { tab_id: tabId });
150
297
  }
151
298
  /**
152
- x * Detect and clear a CAPTCHA. Providers that solve natively are left to do
299
+ * Detect and clear a CAPTCHA. Providers that solve natively are left to do
153
300
  * it; everything else goes to the configured solver.
154
301
  */
155
302
  solveCaptcha() {
156
- return this.http.request("POST", `/api/browsers/${this.id}/captcha`, {}, 18e4);
303
+ return this.http.request("POST", `/api/browsers/${this.id}/captcha`, {}, CHALLENGE_TIMEOUT_MS);
157
304
  }
158
305
  /**
159
306
  * Answer an MFA prompt with the persona's configured factor. When nothing can
160
307
  * answer it, `liveViewUrl` is where a person finishes by hand.
161
308
  */
162
309
  async completeMfa() {
163
- const result = await this.http.request("POST", `/api/browsers/${this.id}/mfa`, {}, 18e4);
310
+ const result = await this.http.request("POST", `/api/browsers/${this.id}/mfa`, {}, CHALLENGE_TIMEOUT_MS);
164
311
  if (result.liveViewUrl) result.liveViewUrl = new URL(result.liveViewUrl, this.http.baseUrl).href;
165
312
  return result;
166
313
  }
@@ -171,14 +318,9 @@ var Browser = class {
171
318
  * with filters like `{{name|first}}`, so a playbook saved from the run stores no values.
172
319
  */
173
320
  async ask(prompt, { data, secrets } = {}) {
174
- const res = await this.http.request(
175
- "POST",
176
- `/api/browsers/${this.id}/chat`,
177
- { messages: [{ role: "user", content: prompt }], data, secrets },
178
- 6e5
179
- );
180
- if (res.error) throw new OyaError(res.error, res.status ?? 500, res);
181
- return res.text;
321
+ const body = { messages: [{ role: "user", content: prompt }], data, secrets };
322
+ const path = `/api/browsers/${this.id}/chat`;
323
+ return agentAnswer(await this.http.request("POST", path, body, AGENT_TIMEOUT_MS)).text;
182
324
  }
183
325
  /**
184
326
  * Save the last `ask()` on this browser as a named playbook. Every value that was
@@ -187,7 +329,7 @@ var Browser = class {
187
329
  * swapped. `code` is the same flow as a Playwright module, to read or run yourself.
188
330
  */
189
331
  toPlaybook(name) {
190
- return this.http.request("POST", `/api/browsers/${this.id}/playbooks`, { name }, 12e4);
332
+ return this.http.request("POST", `/api/browsers/${this.id}/playbooks`, { name }, PLAYBOOK_TIMEOUT_MS);
191
333
  }
192
334
  /**
193
335
  * Replay a playbook with no LLM in the loop. Variables left out reuse the
@@ -197,14 +339,10 @@ var Browser = class {
197
339
  * Play `'<name>:draft'` to try a draft before promoting it.
198
340
  */
199
341
  async play(name, data = {}, { autoHeal = true } = {}) {
200
- const res = await this.http.request(
201
- "POST",
202
- `/api/browsers/${this.id}/playbooks/${encodeURIComponent(name)}/play`,
203
- { variables: data, autoHeal },
204
- 6e5
342
+ const path = `/api/browsers/${this.id}/playbooks/${encodeURIComponent(name)}/play`;
343
+ return agentAnswer(
344
+ await this.http.request("POST", path, { variables: data, autoHeal }, AGENT_TIMEOUT_MS)
205
345
  );
206
- if (res.error) throw new OyaError(res.error, res.status ?? 500, res);
207
- return res;
208
346
  }
209
347
  /**
210
348
  * Start a prompt or playbook in the background and hear back through callbacks.
@@ -218,19 +356,11 @@ var Browser = class {
218
356
  return new Run(this.http, started.id, { onSuccess, onFailure, onHumanAttention, onHealed }, pollMs);
219
357
  }
220
358
  /**
221
- * Watch it work: the console, opened on this browser.
222
- *
223
- * This used to return the raw frame stream with the project's API key in the
224
- * query string — a permanent credential in browser history, Referer headers
225
- * and every proxy log on the way, and a URL that renders as a wall of
226
- * text/event-stream if a person actually opens it. It is the console deep
227
- * link now, the same one the server hands back from `completeMfa()`, and it
228
- * carries no credential at all.
229
- *
230
- * For the frames themselves, use `liveStreamUrl()`.
359
+ * Watch it work: the console, opened on this browser. It carries no
360
+ * credential. For the frames themselves, use `liveStreamUrl()`.
231
361
  */
232
362
  liveViewUrl() {
233
- return `${this.http.baseUrl}/dashboard/?browser=${encodeURIComponent(this.id)}`;
363
+ return consoleLink(this.http.baseUrl, this.id);
234
364
  }
235
365
  /**
236
366
  * The SSE stream of JPEG frames, for embedding in your own UI. EventSource
@@ -238,11 +368,8 @@ var Browser = class {
238
368
  * 60 seconds. Mint one per viewer — the first connection spends it.
239
369
  */
240
370
  async liveStreamUrl() {
241
- const { ticket } = await this.http.request(
242
- "POST",
243
- `/api/control/sessions/${encodeURIComponent(this.id)}/ticket`,
244
- {}
245
- );
371
+ const path = `/api/control/sessions/${encodeURIComponent(this.id)}/ticket`;
372
+ const { ticket } = await this.http.request("POST", path, {});
246
373
  return `${this.http.baseUrl}/api/live/${this.id}?ticket=${encodeURIComponent(ticket)}`;
247
374
  }
248
375
  /**
@@ -257,12 +384,9 @@ var Browser = class {
257
384
  * expires or you revoke it, so treat it like a password.
258
385
  */
259
386
  async shareUrl({ control = false, expiresInSeconds = 3600 } = {}) {
260
- const c = await this.http.request(
261
- "POST",
262
- `/api/control/sessions/${encodeURIComponent(this.id)}/share`,
263
- { control, expiresIn: expiresInSeconds }
264
- );
265
- return { url: `${this.http.baseUrl}/live/${encodeURIComponent(this.id)}#t=${encodeURIComponent(c.token)}`, id: c.id, expiresAt: c.expiresAt };
387
+ const path = `/api/control/sessions/${encodeURIComponent(this.id)}/share`;
388
+ const c = await this.http.request("POST", path, { control, expiresIn: expiresInSeconds });
389
+ return { url: shareLink(this.http.baseUrl, this.id, c.token), id: c.id, expiresAt: c.expiresAt };
266
390
  }
267
391
  /** Revoke a link from `shareUrl()` before it expires, by the id it returned. */
268
392
  async revokeShare(id) {
@@ -277,7 +401,7 @@ var Browser = class {
277
401
  * CDP session is handed back to its provider, a desktop browser disconnects.
278
402
  */
279
403
  stop() {
280
- return this.http.request("POST", `/api/browsers/${this.id}/stop`, {}, 6e4);
404
+ return this.http.request("POST", `/api/browsers/${this.id}/stop`, {}, STOP_TIMEOUT_MS);
281
405
  }
282
406
  /** `await using browser = await oya.browser.start()` stops it however the block exits, errors included. */
283
407
  async [Symbol.asyncDispose]() {
@@ -288,75 +412,258 @@ var Browser = class {
288
412
  await this.stop();
289
413
  }
290
414
  };
291
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
292
- var Run = class {
293
- constructor(http, id, callbacks, pollMs = 2e3) {
294
- this.http = http;
295
- this.id = id;
296
- this.done = this.watch(callbacks, pollMs);
297
- this.done.catch(() => {
298
- });
299
- }
300
- http;
301
- id;
302
- done;
303
- status() {
304
- return this.http.request("GET", `/api/runs/${encodeURIComponent(this.id)}`);
305
- }
306
- /** Answer the open attention request: `'done'` after handling it by hand, or your reply to the agent. */
307
- async respond(response = "done") {
308
- await this.http.request("POST", `/api/runs/${encodeURIComponent(this.id)}/respond`, { response });
415
+ function assertCaptchaCleared(result) {
416
+ if (!result.present || result.solved || result.invisible) return;
417
+ const message = result.error || "CAPTCHA needs attention. Call solveCaptcha() again or open the live view.";
418
+ throw new OyaError(message, Status.CONFLICT, result);
419
+ }
420
+ function toElementId(value) {
421
+ const id = Number(value);
422
+ const wrongType = typeof value !== "number" && typeof value !== "string";
423
+ if (wrongType || value === "" || !Number.isInteger(id) || id < 0) {
424
+ throw new OyaError("Use a numeric element id from browser.analyze().", Status.BAD_REQUEST, null);
309
425
  }
310
- async watch(cb, pollMs) {
311
- const call = async (fn) => {
312
- try {
313
- await fn();
314
- } catch (err) {
315
- console.error("[oya] run callback threw:", err);
316
- }
317
- };
318
- let seen;
319
- for (let errors = 0; ; ) {
320
- let run;
321
- try {
322
- run = await this.status();
323
- errors = 0;
324
- } catch (err) {
325
- if (++errors < 5) {
326
- await sleep(pollMs);
327
- continue;
328
- }
329
- const failure = err instanceof OyaError ? err : new OyaError(String(err), 0, null);
330
- await call(() => cb.onFailure?.(failure));
331
- throw failure;
332
- }
333
- if (run.status === "needs_attention" && run.attention && run.attention.id !== seen) {
334
- seen = run.attention.id;
335
- const request = {
336
- ...run.attention,
337
- liveViewUrl: run.attention.liveViewUrl && new URL(run.attention.liveViewUrl, this.http.baseUrl).href,
338
- respond: (response) => this.respond(response)
339
- };
340
- void call(() => cb.onHumanAttention?.(request));
341
- }
342
- if (run.status === "succeeded") {
343
- const result = run.result || {};
344
- if (result.healed) await call(() => cb.onHealed?.(result));
345
- await call(() => cb.onSuccess?.(result));
346
- return result;
347
- }
348
- if (run.status === "failed") {
349
- const failure = new OyaError(run.error || "Run failed", run.errorStatus ?? 500, run);
350
- await call(() => cb.onFailure?.(failure));
351
- throw failure;
352
- }
353
- await sleep(pollMs);
426
+ return id;
427
+ }
428
+ function scrollParams(direction, amount, at) {
429
+ if (!at) return { direction, amount };
430
+ return { direction, amount: amount ?? AIMED_SCROLL_AMOUNT, ...at, smooth: false };
431
+ }
432
+ function agentAnswer(res) {
433
+ if (res.error) throw new OyaError(res.error, res.status ?? Status.SERVER_ERROR, res);
434
+ return res;
435
+ }
436
+ function consoleLink(baseUrl, id) {
437
+ return `${baseUrl}/dashboard/?browser=${encodeURIComponent(id)}`;
438
+ }
439
+ function shareLink(baseUrl, id, token) {
440
+ return `${baseUrl}/live/${encodeURIComponent(id)}#t=${encodeURIComponent(token)}`;
441
+ }
442
+
443
+ // src/api/browsers.ts
444
+ function startBody(options) {
445
+ const { profile, persona, provider, wsUrl, name, queueMs, priority, budgetUsd, governed, policy } = options;
446
+ return { profile: profile || persona, provider, wsUrl, name, queueMs, priority, budgetUsd, governed, policy };
447
+ }
448
+ async function start(http, wait, options) {
449
+ const headers = { "Idempotency-Key": options.idempotencyKey || globalThis.crypto.randomUUID() };
450
+ const path = "/api/browsers/start";
451
+ const started = await http().request("POST", path, startBody(options), START_TIMEOUT_MS, headers);
452
+ if (started.status === "starting") {
453
+ await wait(started.id, options.readyTimeoutMs ?? READY_TIMEOUT_MS + (options.queueMs || 0));
454
+ started.cdpUrl = (await fetchBrowser(http, started.id)).cdpUrl;
455
+ }
456
+ return new Browser(http(), started, options.captcha === "auto");
457
+ }
458
+ var fetchBrowser = (http, id) => http().request("GET", `/api/browsers/${encodeURIComponent(id)}`);
459
+ async function reattach(http, id) {
460
+ const found = await fetchBrowser(http, id);
461
+ return new Browser(http(), asStarted(found), false);
462
+ }
463
+ function asStarted(found) {
464
+ const provider = found.provider || "cdp";
465
+ return { id: found.id, provider, persona: found.persona || "default", status: "ready", cdpUrl: found.cdpUrl };
466
+ }
467
+ var stopBrowsers = (http, ids) => http().request("POST", "/api/browsers/stop", ids === "all" ? { all: true } : { ids }, START_TIMEOUT_MS);
468
+ var browserApi = (http, wait) => ({
469
+ /** Start a browser and wait until it can take commands. */
470
+ start: (options = {}) => start(http, wait, options),
471
+ /** Reattach to a browser that is already running. */
472
+ get: (id) => reattach(http, id),
473
+ /** Every browser on this key. */
474
+ list: () => http().request("GET", "/api/browsers"),
475
+ /** Stop some (`ids`) or every browser on this key. Each reports separately. */
476
+ stop: (ids) => stopBrowsers(http, ids),
477
+ /** Stop every browser on this key; returns how many stopped. */
478
+ stopAll: async () => (await stopBrowsers(http, "all")).stopped
479
+ });
480
+
481
+ // src/api/control.ts
482
+ var session = (id, action = "") => `/api/control/sessions/${encodeURIComponent(id)}${action}`;
483
+ var item = (kind, id) => `/api/control/${kind}/${encodeURIComponent(id)}`;
484
+ var sessionCalls = (http) => ({
485
+ /** Settings, sessions and recent events at a glance. */
486
+ overview: () => http().request("GET", "/api/control"),
487
+ /** Every session, including disconnected and cleanup-pending ones. */
488
+ sessions: () => http().request("GET", "/api/control/sessions"),
489
+ /** One session. */
490
+ session: (id) => http().request("GET", session(id)),
491
+ /** Update limits, rate cards and retention. */
492
+ settings: (changes) => http().request("PATCH", "/api/control/project", changes)
493
+ });
494
+ var lifecycleCalls = (http) => ({
495
+ /** Cancel queued or provisioning work. */
496
+ cancel: (id) => http().request("POST", session(id, "/cancel"), {}),
497
+ /** Stop a session; `force` stops despite a profile-save error, or reconciles. */
498
+ stop: (id, force = false) => http().request("POST", session(id, "/stop"), { force }),
499
+ /** Acquire or release human control, or acknowledge the agent's resume. */
500
+ takeover: (id, action) => http().request("POST", session(id, "/control"), { action }),
501
+ /** Send one input as the human holding the control lease. */
502
+ input: (id, action, params) => http().request("POST", session(id, "/input"), { action, params })
503
+ });
504
+ var recoveryCalls = (http) => ({
505
+ /** Explicitly recover a session, or replace it with a fresh one. */
506
+ recover: (id, replace = false) => http().request("POST", session(id, "/recover"), { replace }),
507
+ /** A single-use ticket for the live stream. */
508
+ ticket: (id) => http().request("POST", session(id, "/ticket"), {}),
509
+ /** Durable lifecycle events after a cursor. */
510
+ events: (after = 0) => http().request("GET", `/api/control/events?after=${after}`)
511
+ });
512
+ var credentialCalls = (http) => ({
513
+ /** Mint a service credential. Its token is returned this once. */
514
+ createCredential: (options) => http().request("POST", "/api/control/credentials", options),
515
+ /** Revoke a service credential. */
516
+ revokeCredential: (id) => http().request("DELETE", item("credentials", id))
517
+ });
518
+ var memberCalls = (http) => ({
519
+ /** The owner and every member. */
520
+ members: () => http().request("GET", "/api/control/members"),
521
+ /** An invitation code for a new member. */
522
+ inviteMember: (role = "operator") => http().request("POST", "/api/control/members/invite", { role }),
523
+ /** Remove a member. */
524
+ removeMember: (userId) => http().request("DELETE", item("members", userId))
525
+ });
526
+ var webhookCalls = (http) => ({
527
+ /** Register a webhook; `types` limits which events it receives. */
528
+ createWebhook: (url, types = []) => http().request("POST", "/api/control/webhooks", { url, types }),
529
+ /** Disable a webhook. */
530
+ removeWebhook: (id) => http().request("DELETE", item("webhooks", id)),
531
+ /** Send a delivery again. */
532
+ replayDelivery: (id) => http().request("POST", `${item("deliveries", id)}/replay`, {})
533
+ });
534
+ var controlApi = (http) => ({
535
+ ...sessionCalls(http),
536
+ ...lifecycleCalls(http),
537
+ ...recoveryCalls(http),
538
+ ...credentialCalls(http),
539
+ ...memberCalls(http),
540
+ ...webhookCalls(http)
541
+ });
542
+
543
+ // src/api/playbooks.ts
544
+ var playbook = (name) => `/api/playbooks/${encodeURIComponent(name)}`;
545
+ var playbookApi = (http) => ({
546
+ /** Every saved playbook, with any draft waiting on it. */
547
+ list: async () => (await http().request("GET", "/api/playbooks")).playbooks,
548
+ /** Delete a playbook and its draft, or only the draft with `'<name>:draft'`. */
549
+ remove: async (name) => {
550
+ await http().request("DELETE", playbook(name));
551
+ },
552
+ /** Replace a playbook with the draft a healed replay saved. Try it first with `browser.play('<name>:draft')`. */
553
+ promote: (name) => http().request("POST", `${playbook(name)}/promote`, {})
554
+ });
555
+
556
+ // src/api/proxies.ts
557
+ var proxyApi = (http) => ({
558
+ /** Every proxy this key can use, shared ones included. */
559
+ list: async () => (await http().request("GET", "/api/proxies")).proxies,
560
+ /** Add a proxy. Its credentials are never read back. */
561
+ create: (proxy) => http().request("POST", "/api/proxies", proxy),
562
+ /** Remove one of this key's proxies. */
563
+ remove: async (id) => {
564
+ await http().request("DELETE", `/api/proxies/${encodeURIComponent(id)}`);
565
+ },
566
+ /** Dial each proxy and learn its real exit IP. Failing ones cool down and are skipped. */
567
+ check: async () => (await http().request("POST", "/api/proxies/check", {})).results
568
+ });
569
+
570
+ // src/api/personas.ts
571
+ var identityCalls = (http) => ({
572
+ /** Every persona on this key. */
573
+ list: async () => (await http().request("GET", "/api/personas")).personas,
574
+ /** One persona. */
575
+ get: (id) => http().request("GET", `/api/personas/${id}`),
576
+ /**
577
+ * Create an identity. The device — platform, timezone, locale — is chosen
578
+ * here and fixed for its life; `preview()` shows what a choice produces.
579
+ */
580
+ create: (options = {}) => http().request("POST", "/api/personas", options),
581
+ /** Name, concurrency cap and proxy hint. Never the device — clone for that. */
582
+ update: (id, changes) => http().request("PUT", `/api/personas/${id}`, changes),
583
+ /** A new persona of the same kind of device: same choices, fresh identity, empty jar. */
584
+ clone: (id, options = {}) => http().request("POST", `/api/personas/${id}/clone`, options)
585
+ });
586
+ var deviceCalls = (http) => ({
587
+ /** The fingerprint these choices would produce. Persists nothing. */
588
+ preview: async (prefs = {}) => (await http().request("POST", "/api/personas/preview", { prefs })).fingerprint,
589
+ /** Platforms, and the timezones and locales each may coherently claim. */
590
+ options: () => http().request("GET", "/api/personas/options"),
591
+ /** Pin the persona to one of your proxies, or `null` to let assignment happen at connect. */
592
+ pinProxy: (id, proxyId) => http().request("PUT", `/api/personas/${id}/proxy`, { proxyId }),
593
+ /** Delete a persona. */
594
+ remove: async (id) => {
595
+ await http().request("DELETE", `/api/personas/${id}`);
596
+ }
597
+ });
598
+ var mfaCalls = (http) => ({
599
+ /** Store the second factor for this identity. Sealed at rest, never read back. */
600
+ setMfa: (id, config) => http().request("PUT", `/api/personas/${id}/mfa`, config),
601
+ /** Remove the persona-wide factor, or the one filed against `domain`. */
602
+ clearMfa: async (id, domain) => {
603
+ await http().request("DELETE", `/api/personas/${id}/mfa${domain ? `?domain=${encodeURIComponent(domain)}` : ""}`);
604
+ }
605
+ });
606
+ var loginCalls = (http) => ({
607
+ /**
608
+ * Store a site login for this identity. Sealed at rest, never read back.
609
+ *
610
+ * Signing in once on the desktop and inheriting the cookies is still the
611
+ * better path. This is for portals that expire a session server-side
612
+ * between runs, where an unattended run has nothing else to recover with.
613
+ */
614
+ setCredentials: (id, config) => http().request("PUT", `/api/personas/${id}/credentials`, config),
615
+ /** Which sites this identity can sign in to. Usernames only. */
616
+ credentials: (id) => http().request("GET", `/api/personas/${id}/credentials`),
617
+ /** Remove the login stored for one site. */
618
+ clearCredentials: async (id, domain) => {
619
+ await http().request("DELETE", `/api/personas/${id}/credentials?domain=${encodeURIComponent(domain)}`);
620
+ }
621
+ });
622
+ var personaApi = (http) => ({
623
+ ...identityCalls(http),
624
+ ...deviceCalls(http),
625
+ ...mfaCalls(http),
626
+ ...loginCalls(http)
627
+ });
628
+
629
+ // src/api/config.ts
630
+ var configApi = (http) => ({
631
+ /** This key's settings. Secrets read back masked. */
632
+ get: () => http().request("GET", "/api/config"),
633
+ /** Change settings; `null` clears a field back to the deployment default. */
634
+ set: (values) => http().request("POST", "/api/config", values)
635
+ });
636
+
637
+ // src/api/ready.ts
638
+ var ENDED = ["failed", "stopped", "unknown_outcome"];
639
+ async function waitUntilConnected(checks, id, timeoutMs) {
640
+ const deadline = Date.now() + timeoutMs;
641
+ while (Date.now() < deadline) {
642
+ if (await isUp(checks, id)) return;
643
+ await new Promise((r) => setTimeout(r, READY_POLL_MS));
644
+ }
645
+ const seconds = Math.round(timeoutMs / MS_PER_SECOND);
646
+ throw new OyaError(`Browser ${id} did not come up within ${seconds}s`, Status.GATEWAY_TIMEOUT, null);
647
+ }
648
+ async function isUp(checks, id) {
649
+ const all = await checks.list();
650
+ if (all.some((b) => b.id === id && b.health !== "dead")) return true;
651
+ await assertNotEnded(checks, id);
652
+ return false;
653
+ }
654
+ async function assertNotEnded(checks, id) {
655
+ try {
656
+ const session2 = await checks.session(id);
657
+ if (ENDED.includes(session2.state)) {
658
+ throw new OyaError(`Browser creation ended in ${session2.state}`, Status.CONFLICT, session2);
354
659
  }
660
+ } catch (e) {
661
+ if (!(e instanceof OyaError) || e.status !== Status.NOT_FOUND) throw e;
355
662
  }
356
- };
663
+ }
357
664
 
358
665
  // src/file.ts
359
- var MAX_FILE_BYTES = 10 * 1024 * 1024;
666
+ var MAX_FILE_BYTES = MAX_FILE_MB * BYTES_PER_MB;
360
667
  var NODE_FS = "node:fs/promises";
361
668
  var MIME = {
362
669
  pdf: "application/pdf",
@@ -384,172 +691,67 @@ var base64 = (bytes) => {
384
691
  const buffer = globalThis.Buffer;
385
692
  if (buffer) return buffer.from(bytes).toString("base64");
386
693
  let binary = "";
387
- for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
694
+ for (let i = 0; i < bytes.length; i += BASE64_CHUNK_BYTES) {
695
+ binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK_BYTES));
696
+ }
388
697
  return btoa(binary);
389
698
  };
390
- async function file(source, options = {}) {
391
- let bytes;
392
- let name = options.name;
393
- if (typeof source === "string") {
394
- const fs = await import(
395
- /* webpackIgnore: true */
396
- /* @vite-ignore */
397
- NODE_FS
398
- );
399
- bytes = new Uint8Array(await fs.readFile(source));
400
- name ||= source.split(/[\\/]/).pop() || "file";
401
- } else if (source instanceof Uint8Array) {
402
- bytes = source;
403
- } else {
404
- bytes = new Uint8Array(await source.arrayBuffer());
405
- name ||= source.name;
406
- }
407
- name ||= "file";
408
- if (bytes.length > MAX_FILE_BYTES) {
409
- throw new Error(`${name} is ${Math.round(bytes.length / 1024 / 1024)}MB; the limit for a task file is ${MAX_FILE_BYTES / 1024 / 1024}MB.`);
410
- }
699
+ async function readPath(path) {
700
+ const fs = await import(
701
+ /* webpackIgnore: true */
702
+ /* @vite-ignore */
703
+ NODE_FS
704
+ );
705
+ return { bytes: new Uint8Array(await fs.readFile(path)), name: path.split(/[\\/]/).pop() || "file" };
706
+ }
707
+ async function readSource(source) {
708
+ if (typeof source === "string") return readPath(source);
709
+ if (source instanceof Uint8Array) return { bytes: source };
710
+ return { bytes: new Uint8Array(await source.arrayBuffer()), name: source.name };
711
+ }
712
+ function checkSize(name, bytes) {
713
+ if (bytes.length <= MAX_FILE_BYTES) return;
714
+ throw new Error(
715
+ `${name} is ${Math.round(bytes.length / BYTES_PER_MB)}MB; the limit for a task file is ${MAX_FILE_BYTES / BYTES_PER_MB}MB.`
716
+ );
717
+ }
718
+ function mimeFor(name) {
411
719
  const ext = name.includes(".") ? name.split(".").pop().toLowerCase() : "";
412
- return { file: name, type: options.type || MIME[ext] || "application/octet-stream", b64: base64(bytes) };
720
+ return MIME[ext] || "application/octet-stream";
721
+ }
722
+ function fileValue(name, bytes, type) {
723
+ checkSize(name, bytes);
724
+ return { file: name, type: type || mimeFor(name), b64: base64(bytes) };
725
+ }
726
+ async function file(source, options = {}) {
727
+ const read = await readSource(source);
728
+ return fileValue(options.name || read.name || "file", read.bytes, options.type);
413
729
  }
414
730
 
415
731
  // src/index.ts
416
- var DEFAULT_BASE_URL = "https://browser.getoya.ai";
417
- var READY_POLL_MS = 2e3;
418
- var env = (name) => globalThis.process?.env?.[name];
419
732
  var Oya = class {
733
+ /** The one HTTP path every call goes through. */
420
734
  http;
735
+ /** Reads the key and URL from `options`, then OYA_API_KEY and OYA_BASE_URL. Throws without a key. */
421
736
  constructor(options = {}) {
422
- const apiKey = options.apiKey || env("OYA_API_KEY");
423
- if (!apiKey) {
424
- throw new Error("No API key. Pass { apiKey } or set OYA_API_KEY \u2014 run `oya login` to get one.");
425
- }
426
- const baseUrl = (options.baseUrl || env("OYA_BASE_URL") || DEFAULT_BASE_URL).replace(/\/+$/, "");
427
- const fetchImpl = options.fetch || globalThis.fetch;
428
- if (!fetchImpl) throw new Error("No fetch available \u2014 pass { fetch } or use Node 18+.");
429
- this.http = new Http(baseUrl, apiKey, options.timeoutMs ?? 6e4, fetchImpl.bind(globalThis));
430
- }
431
- browser = {
432
- /** Start a browser and wait until it can take commands. */
433
- start: async (options = {}) => {
434
- const started = await this.http.request("POST", "/api/browsers/start", {
435
- profile: options.profile || options.persona,
436
- provider: options.provider,
437
- wsUrl: options.wsUrl,
438
- name: options.name,
439
- queueMs: options.queueMs,
440
- priority: options.priority,
441
- budgetUsd: options.budgetUsd,
442
- governed: options.governed,
443
- policy: options.policy
444
- }, 12e4, { "Idempotency-Key": options.idempotencyKey || globalThis.crypto.randomUUID() });
445
- if (started.status === "starting") {
446
- await this.waitUntilConnected(started.id, options.readyTimeoutMs ?? 12e4 + (options.queueMs || 0));
447
- const connected = await this.http.request("GET", `/api/browsers/${encodeURIComponent(started.id)}`);
448
- started.cdpUrl = connected.cdpUrl;
449
- }
450
- return new Browser(this.http, started, options.captcha === "auto");
451
- },
452
- /** Reattach to a browser that is already running. */
453
- get: async (id) => {
454
- const found = await this.http.request("GET", `/api/browsers/${encodeURIComponent(id)}`);
455
- return new Browser(this.http, {
456
- id: found.id,
457
- provider: found.provider || "cdp",
458
- persona: found.persona || "default",
459
- status: "ready",
460
- cdpUrl: found.cdpUrl
461
- }, false);
462
- },
463
- list: () => this.http.request("GET", "/api/browsers"),
464
- /** Stop some (`ids`) or every browser on this key. Each reports separately. */
465
- stop: (ids) => this.http.request("POST", "/api/browsers/stop", ids === "all" ? { all: true } : { ids }, 12e4),
466
- stopAll: async () => (await this.browser.stop("all")).stopped
467
- };
737
+ this.http = createHttp(options);
738
+ }
739
+ /** Start, reattach to, list and stop browsers. */
740
+ browser = browserApi(
741
+ () => this.http,
742
+ (id, timeoutMs) => this.waitUntilConnected(id, timeoutMs)
743
+ );
468
744
  /** Durable operational controls, including disconnected and cleanup-pending sessions. */
469
- control = {
470
- overview: () => this.http.request("GET", "/api/control"),
471
- sessions: () => this.http.request("GET", "/api/control/sessions"),
472
- session: (id) => this.http.request("GET", `/api/control/sessions/${encodeURIComponent(id)}`),
473
- settings: (changes) => this.http.request("PATCH", "/api/control/project", changes),
474
- cancel: (id) => this.http.request("POST", `/api/control/sessions/${encodeURIComponent(id)}/cancel`, {}),
475
- stop: (id, force = false) => this.http.request("POST", `/api/control/sessions/${encodeURIComponent(id)}/stop`, { force }),
476
- takeover: (id, action) => this.http.request("POST", `/api/control/sessions/${encodeURIComponent(id)}/control`, { action }),
477
- input: (id, action, params) => this.http.request("POST", `/api/control/sessions/${encodeURIComponent(id)}/input`, { action, params }),
478
- recover: (id, replace = false) => this.http.request("POST", `/api/control/sessions/${encodeURIComponent(id)}/recover`, { replace }),
479
- ticket: (id) => this.http.request("POST", `/api/control/sessions/${encodeURIComponent(id)}/ticket`, {}),
480
- events: (after = 0) => this.http.request("GET", `/api/control/events?after=${after}`),
481
- createCredential: (options) => this.http.request("POST", "/api/control/credentials", options),
482
- revokeCredential: (id) => this.http.request("DELETE", `/api/control/credentials/${encodeURIComponent(id)}`),
483
- members: () => this.http.request("GET", "/api/control/members"),
484
- inviteMember: (role = "operator") => this.http.request("POST", "/api/control/members/invite", { role }),
485
- removeMember: (userId) => this.http.request("DELETE", `/api/control/members/${encodeURIComponent(userId)}`),
486
- createWebhook: (url, types = []) => this.http.request("POST", "/api/control/webhooks", { url, types }),
487
- removeWebhook: (id) => this.http.request("DELETE", `/api/control/webhooks/${encodeURIComponent(id)}`),
488
- replayDelivery: (id) => this.http.request("POST", `/api/control/deliveries/${encodeURIComponent(id)}/replay`, {})
489
- };
745
+ control = controlApi(() => this.http);
490
746
  /** Playbooks saved with `browser.toPlaybook()`. */
491
- playbooks = {
492
- list: async () => (await this.http.request("GET", "/api/playbooks")).playbooks,
493
- /** Delete a playbook and its draft, or only the draft with `'<name>:draft'`. */
494
- remove: async (name) => {
495
- await this.http.request("DELETE", `/api/playbooks/${encodeURIComponent(name)}`);
496
- },
497
- /** Replace a playbook with the draft a healed replay saved. Try it first with `browser.play('<name>:draft')`. */
498
- promote: (name) => this.http.request("POST", `/api/playbooks/${encodeURIComponent(name)}/promote`, {})
499
- };
747
+ playbooks = playbookApi(() => this.http);
500
748
  /**
501
749
  * Proxy exits for your personas. A persona takes one at first connect (by its
502
750
  * geo hint) or by `personas.pinProxy`, and keeps it.
503
751
  */
504
- proxies = {
505
- list: async () => (await this.http.request("GET", "/api/proxies")).proxies,
506
- create: (proxy) => this.http.request("POST", "/api/proxies", proxy),
507
- remove: async (id) => {
508
- await this.http.request("DELETE", `/api/proxies/${encodeURIComponent(id)}`);
509
- },
510
- /** Dial each proxy and learn its real exit IP. Failing ones cool down and are skipped. */
511
- check: async () => (await this.http.request("POST", "/api/proxies/check", {})).results
512
- };
513
- personas = {
514
- list: async () => (await this.http.request("GET", "/api/personas")).personas,
515
- get: (id) => this.http.request("GET", `/api/personas/${id}`),
516
- /**
517
- * Create an identity. The device — platform, timezone, locale — is chosen
518
- * here and fixed for its life; `preview()` shows what a choice produces.
519
- */
520
- create: (options = {}) => this.http.request("POST", "/api/personas", options),
521
- /** Name, concurrency cap and proxy hint. Never the device — clone for that. */
522
- update: (id, changes) => this.http.request("PUT", `/api/personas/${id}`, changes),
523
- /** A new persona of the same kind of device: same choices, fresh identity, empty jar. */
524
- clone: (id, options = {}) => this.http.request("POST", `/api/personas/${id}/clone`, options),
525
- /** The fingerprint these choices would produce. Persists nothing. */
526
- preview: async (prefs = {}) => (await this.http.request("POST", "/api/personas/preview", { prefs })).fingerprint,
527
- /** Platforms, and the timezones and locales each may coherently claim. */
528
- options: () => this.http.request("GET", "/api/personas/options"),
529
- /** Pin the persona to one of your proxies, or `null` to let assignment happen at connect. */
530
- pinProxy: (id, proxyId) => this.http.request("PUT", `/api/personas/${id}/proxy`, { proxyId }),
531
- remove: async (id) => {
532
- await this.http.request("DELETE", `/api/personas/${id}`);
533
- },
534
- /** Store the second factor for this identity. Sealed at rest, never read back. */
535
- setMfa: (id, config) => this.http.request("PUT", `/api/personas/${id}/mfa`, config),
536
- clearMfa: async (id, domain) => {
537
- await this.http.request("DELETE", `/api/personas/${id}/mfa${domain ? `?domain=${encodeURIComponent(domain)}` : ""}`);
538
- },
539
- /**
540
- * Store a site login for this identity. Sealed at rest, never read back.
541
- *
542
- * Signing in once on the desktop and inheriting the cookies is still the
543
- * better path. This is for portals that expire a session server-side
544
- * between runs, where an unattended run has nothing else to recover with.
545
- */
546
- setCredentials: (id, config) => this.http.request("PUT", `/api/personas/${id}/credentials`, config),
547
- /** Which sites this identity can sign in to. Usernames only. */
548
- credentials: (id) => this.http.request("GET", `/api/personas/${id}/credentials`),
549
- clearCredentials: async (id, domain) => {
550
- await this.http.request("DELETE", `/api/personas/${id}/credentials?domain=${encodeURIComponent(domain)}`);
551
- }
552
- };
752
+ proxies = proxyApi(() => this.http);
753
+ /** Identities: fingerprint, cookie jar and proxy bound together, plus their stored factors and logins. */
754
+ personas = personaApi(() => this.http);
553
755
  /**
554
756
  * This key's settings: LLM credentials, browser provider, solver.
555
757
  *
@@ -561,29 +763,17 @@ var Oya = class {
561
763
  * project-scoped endpoint, set `openai_base_url` to `.../endpoints/openapi` and pass an
562
764
  * OAuth access token as `openai_api_key`. See {@link ConfigUpdate} for every field.
563
765
  */
564
- config = {
565
- get: () => this.http.request("GET", "/api/config"),
566
- set: (values) => this.http.request("POST", "/api/config", values)
567
- };
766
+ config = configApi(() => this.http);
568
767
  /** Saved profiles. `personas` is retained as an alias for existing clients. */
569
768
  profiles = this.personas;
769
+ /** What this key has spent. */
570
770
  usage() {
571
771
  return this.http.request("GET", "/api/usage");
572
772
  }
773
+ /** Waits for a starting browser to dial in, through this client's own list and session calls. */
573
774
  async waitUntilConnected(id, timeoutMs) {
574
- const deadline = Date.now() + timeoutMs;
575
- while (Date.now() < deadline) {
576
- const all = await this.browser.list();
577
- if (all.some((b) => b.id === id && b.health !== "dead")) return;
578
- try {
579
- const session = await this.control.session(id);
580
- if (["failed", "stopped", "unknown_outcome"].includes(session.state)) throw new OyaError(`Browser creation ended in ${session.state}`, 409, session);
581
- } catch (e) {
582
- if (!(e instanceof OyaError) || e.status !== 404) throw e;
583
- }
584
- await new Promise((r) => setTimeout(r, READY_POLL_MS));
585
- }
586
- throw new OyaError(`Browser ${id} did not come up within ${Math.round(timeoutMs / 1e3)}s`, 504, null);
775
+ const checks = { list: () => this.browser.list(), session: (sid) => this.control.session(sid) };
776
+ await waitUntilConnected(checks, id, timeoutMs);
587
777
  }
588
778
  };
589
779
  var index_default = Oya;