@oya-ai/browser 1.0.97 → 1.0.99

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