unbrowse 3.1.0-experiments.995f8bb → 3.1.0-experiments.9cbcb13

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.
Files changed (105) hide show
  1. package/dist/cli.js +79 -33
  2. package/dist/index.js +2 -6
  3. package/dist/mcp.js +73 -22
  4. package/dist/server.js +25994 -0
  5. package/package.json +1 -2
  6. package/vendor/kuri/manifest.json +1 -1
  7. package/runtime-src/agent-outcome.ts +0 -166
  8. package/runtime-src/analytics-session.ts +0 -55
  9. package/runtime-src/api/browse-index.ts +0 -343
  10. package/runtime-src/api/browse-session.ts +0 -572
  11. package/runtime-src/api/browse-submit-prereqs.ts +0 -48
  12. package/runtime-src/api/browse-submit.ts +0 -1184
  13. package/runtime-src/api/routes.ts +0 -1833
  14. package/runtime-src/auth/browser-cookies.ts +0 -423
  15. package/runtime-src/auth/index.ts +0 -535
  16. package/runtime-src/auth/runtime.ts +0 -116
  17. package/runtime-src/browser/index.ts +0 -659
  18. package/runtime-src/browser/types.ts +0 -41
  19. package/runtime-src/build-info.generated.ts +0 -6
  20. package/runtime-src/capture/index.ts +0 -1929
  21. package/runtime-src/capture/prefetch.ts +0 -95
  22. package/runtime-src/capture/rsc.ts +0 -45
  23. package/runtime-src/cli/shortcuts.ts +0 -273
  24. package/runtime-src/cli.ts +0 -1734
  25. package/runtime-src/client/graph-client.ts +0 -100
  26. package/runtime-src/client/index.ts +0 -1425
  27. package/runtime-src/debug-trace.ts +0 -18
  28. package/runtime-src/domain.ts +0 -38
  29. package/runtime-src/execution/index.ts +0 -3407
  30. package/runtime-src/execution/retry.ts +0 -46
  31. package/runtime-src/execution/robots.ts +0 -167
  32. package/runtime-src/execution/search-forms.ts +0 -188
  33. package/runtime-src/execution/token-resolver.ts +0 -135
  34. package/runtime-src/extraction/index.ts +0 -1507
  35. package/runtime-src/foundry/publish-bundle.ts +0 -392
  36. package/runtime-src/graph/agent-augment.ts +0 -315
  37. package/runtime-src/graph/index.ts +0 -1532
  38. package/runtime-src/graph/local-fixtures.ts +0 -393
  39. package/runtime-src/graph/local-harness.ts +0 -646
  40. package/runtime-src/graph/planner.ts +0 -411
  41. package/runtime-src/graph/session.ts +0 -294
  42. package/runtime-src/graph/trace-store.ts +0 -136
  43. package/runtime-src/impact-log.ts +0 -227
  44. package/runtime-src/index.ts +0 -24
  45. package/runtime-src/indexer/index.ts +0 -465
  46. package/runtime-src/intent-match.ts +0 -1515
  47. package/runtime-src/kuri/client.ts +0 -1839
  48. package/runtime-src/logger.ts +0 -30
  49. package/runtime-src/marketplace/index.ts +0 -111
  50. package/runtime-src/mcp.ts +0 -1911
  51. package/runtime-src/orchestrator/browser-agent.ts +0 -374
  52. package/runtime-src/orchestrator/dag-advisor.ts +0 -59
  53. package/runtime-src/orchestrator/dag-feedback.ts +0 -257
  54. package/runtime-src/orchestrator/first-pass-action.ts +0 -403
  55. package/runtime-src/orchestrator/index.ts +0 -4480
  56. package/runtime-src/orchestrator/passive-publish.ts +0 -187
  57. package/runtime-src/orchestrator/timing-economics.ts +0 -80
  58. package/runtime-src/payments/cascade.ts +0 -137
  59. package/runtime-src/payments/index.ts +0 -270
  60. package/runtime-src/payments/lobster-pay.ts +0 -182
  61. package/runtime-src/payments/wallet.ts +0 -98
  62. package/runtime-src/publish/review-context.ts +0 -93
  63. package/runtime-src/publish/sanitize.ts +0 -197
  64. package/runtime-src/publish/schema-review.ts +0 -192
  65. package/runtime-src/publish-admission.ts +0 -388
  66. package/runtime-src/ratelimit/index.ts +0 -23
  67. package/runtime-src/reverse-engineer/bundle-scanner.ts +0 -127
  68. package/runtime-src/reverse-engineer/description-prompt.ts +0 -213
  69. package/runtime-src/reverse-engineer/index.ts +0 -1551
  70. package/runtime-src/reverse-engineer/token-sources.ts +0 -379
  71. package/runtime-src/router.ts +0 -17
  72. package/runtime-src/routing-telemetry.ts +0 -395
  73. package/runtime-src/runtime/browser-access.ts +0 -11
  74. package/runtime-src/runtime/browser-auth.ts +0 -12
  75. package/runtime-src/runtime/browser-host.ts +0 -48
  76. package/runtime-src/runtime/lifecycle.ts +0 -17
  77. package/runtime-src/runtime/local-server.ts +0 -311
  78. package/runtime-src/runtime/paths.ts +0 -99
  79. package/runtime-src/runtime/setup.ts +0 -251
  80. package/runtime-src/runtime/supervisor.ts +0 -69
  81. package/runtime-src/runtime/update-hints.ts +0 -351
  82. package/runtime-src/server.ts +0 -100
  83. package/runtime-src/session-logs.ts +0 -142
  84. package/runtime-src/settings.ts +0 -221
  85. package/runtime-src/single-binary.ts +0 -143
  86. package/runtime-src/site-policy.ts +0 -54
  87. package/runtime-src/stale-cleanup-runner.ts +0 -144
  88. package/runtime-src/stale-cleanup.ts +0 -133
  89. package/runtime-src/telemetry-attribution.ts +0 -120
  90. package/runtime-src/telemetry.ts +0 -253
  91. package/runtime-src/template-params.ts +0 -141
  92. package/runtime-src/transform/drift.ts +0 -60
  93. package/runtime-src/transform/index.ts +0 -277
  94. package/runtime-src/types/index.ts +0 -1
  95. package/runtime-src/types/skill.ts +0 -931
  96. package/runtime-src/vault/index.ts +0 -196
  97. package/runtime-src/verification/auth-gate.ts +0 -8
  98. package/runtime-src/verification/candidates.ts +0 -27
  99. package/runtime-src/verification/index.ts +0 -120
  100. package/runtime-src/verification/matrix.ts +0 -30
  101. package/runtime-src/version.ts +0 -148
  102. package/runtime-src/workflow/artifact.ts +0 -161
  103. package/runtime-src/workflow/compile.ts +0 -808
  104. package/runtime-src/workflow/publish.ts +0 -225
  105. package/runtime-src/workflow/runtime.ts +0 -213
@@ -1,659 +0,0 @@
1
- import * as kuri from "../kuri/client.js";
2
- import type { KuriHarEntry } from "../kuri/client.js";
3
- import { resolveAndExecute } from "../orchestrator/index.js";
4
- import { generateLocalDescription } from "../orchestrator/index.js";
5
- import { extractEndpoints, extractAuthHeaders } from "../reverse-engineer/index.js";
6
- import type { RawRequest } from "../capture/index.js";
7
- import { queueBackgroundIndex } from "../indexer/index.js";
8
- import { mergeEndpoints } from "../marketplace/index.js";
9
- import { buildSkillOperationGraph } from "../graph/index.js";
10
- import { findExistingSkillForDomain, cachePublishedSkill } from "../client/index.js";
11
- import { storeCredential } from "../vault/index.js";
12
- import { getRegistrableDomain } from "../domain.js";
13
- import {
14
- importBrowserCookiesIntoTab,
15
- loadAuthProfileBestEffort,
16
- saveAuthProfileBestEffort,
17
- } from "../auth/index.js";
18
- import { UnbrowseResponse, type BrowserLaunchOptions, type GotoOptions, type SkillResolutionResult } from "./types.js";
19
- import type { SkillManifest } from "../types/index.js";
20
- import { nanoid } from "nanoid";
21
-
22
- /**
23
- * Infer a search intent from a URL's path and query params.
24
- * e.g. "https://github.com/search?q=react" → "search react on github.com"
25
- */
26
- function inferIntentFromUrl(url: string): string {
27
- try {
28
- const u = new URL(url);
29
- const pathSegments = u.pathname.split("/").filter(Boolean);
30
- const query = u.searchParams.get("q") ?? u.searchParams.get("query") ?? u.searchParams.get("search") ?? "";
31
- const action = pathSegments[pathSegments.length - 1] ?? "browse";
32
- const parts = [action];
33
- if (query) parts.push(query);
34
- parts.push("on", u.hostname);
35
- return parts.join(" ");
36
- } catch {
37
- return `browse ${url}`;
38
- }
39
- }
40
-
41
- /** Require a live browser tab, throw if page resolved from skill cache */
42
- function requireTab(tabId: string | null): string {
43
- if (!tabId) throw new Error("No browser tab — page resolved from skill cache. Call goto() with a URL that requires browser interaction.");
44
- return tabId;
45
- }
46
-
47
- /** Convert Kuri HAR entries to RawRequest format for extractEndpoints */
48
- function harEntriesToRawRequests(entries: KuriHarEntry[]): RawRequest[] {
49
- return entries
50
- .filter(e => e.request && e.response)
51
- .map(e => ({
52
- url: e.request.url,
53
- method: e.request.method,
54
- request_headers: Object.fromEntries(
55
- (e.request.headers ?? []).map(h => [h.name.toLowerCase(), h.value])
56
- ),
57
- request_body: e.request.postData?.text,
58
- response_status: e.response.status,
59
- response_headers: Object.fromEntries(
60
- (e.response.headers ?? []).map(h => [h.name.toLowerCase(), h.value])
61
- ),
62
- response_body: e.response.content?.text,
63
- timestamp: e.startedDateTime ?? new Date().toISOString(),
64
- }));
65
- }
66
-
67
- /** Process captured HAR entries into routes and queue for background indexing */
68
- /** Full passive indexing pipeline — same enrichment as explicit capture */
69
- function passiveIndexHar(entries: KuriHarEntry[], pageUrl: string): void {
70
- if (entries.length === 0) return;
71
- const requests = harEntriesToRawRequests(entries);
72
- if (requests.length === 0) return;
73
-
74
- let domain: string;
75
- try { domain = new URL(pageUrl).hostname; } catch { return; }
76
- const intent = `browse ${domain}`;
77
-
78
- void (async () => {
79
- try {
80
- const rawEndpoints = extractEndpoints(requests, undefined, { pageUrl, finalUrl: pageUrl });
81
- if (rawEndpoints.length === 0) return;
82
-
83
- // Store auth credentials
84
- const capturedAuthHeaders = extractAuthHeaders(requests);
85
- if (Object.keys(capturedAuthHeaders).length > 0) {
86
- await storeCredential(`${getRegistrableDomain(domain)}-session`, JSON.stringify({ headers: capturedAuthHeaders }));
87
- }
88
-
89
- // Merge with existing skill (never reduce endpoint count)
90
- const existingSkill = findExistingSkillForDomain(domain, intent);
91
- const mergedEndpoints = existingSkill
92
- ? mergeEndpoints(existingSkill.endpoints, rawEndpoints)
93
- : rawEndpoints;
94
- if (existingSkill && mergedEndpoints.length < existingSkill.endpoints.length) {
95
- console.error(`[passive-index] ${domain}: skipping — would reduce endpoints`);
96
- return;
97
- }
98
-
99
- // Generate descriptions
100
- for (const ep of mergedEndpoints) {
101
- if (!ep.description) ep.description = generateLocalDescription(ep);
102
- }
103
-
104
- // No LLM augmentation — the calling agent IS the LLM
105
- const enrichedEndpoints = mergedEndpoints;
106
-
107
- // Build operation graph
108
- const operationGraph = buildSkillOperationGraph(enrichedEndpoints);
109
-
110
- const skill: SkillManifest = {
111
- skill_id: existingSkill?.skill_id ?? nanoid(),
112
- version: "1.0.0",
113
- schema_version: "1",
114
- lifecycle: "active" as const,
115
- execution_type: "http" as const,
116
- created_at: existingSkill?.created_at ?? new Date().toISOString(),
117
- updated_at: new Date().toISOString(),
118
- name: domain,
119
- intent_signature: intent,
120
- domain,
121
- description: `API skill for ${domain}`,
122
- owner_type: "agent" as const,
123
- endpoints: enrichedEndpoints,
124
- operation_graph: operationGraph,
125
- intents: Array.from(new Set([...(existingSkill?.intents ?? []), intent])),
126
- };
127
-
128
- try { cachePublishedSkill(skill); } catch { /* best-effort */ }
129
- queueBackgroundIndex({ skill, domain, intent, contextUrl: pageUrl, cacheKey: `passive:${domain}:${Date.now()}` });
130
- console.error(`[passive-index] ${domain}: ${enrichedEndpoints.length} endpoints indexed`);
131
- } catch (err) {
132
- console.error(`[passive-index] ${domain} failed: ${err instanceof Error ? err.message : err}`);
133
- }
134
- })();
135
- }
136
-
137
-
138
- /**
139
- * Page — Kuri browser tab with Unbrowse acceleration.
140
- *
141
- * Kuri is the primary browser primitive. Every method proxies directly to
142
- * Kuri's CDP-based HTTP API. The one exception is goto(): Unbrowse
143
- * transparently checks the skill cache and shared route graph first,
144
- * returning structured API data in <200ms when a cached route exists.
145
- * On cache miss, goto() falls through to Kuri navigation and captures
146
- * traffic in the background for future acceleration.
147
- */
148
- export class Page {
149
- private _tabId: string | null = null;
150
- private _url: string = "about:blank";
151
- private _skillResult: SkillResolutionResult | null = null;
152
- private _html: string | null = null;
153
- private _closed = false;
154
- private _defaultIntent?: string;
155
- private _harActive = false;
156
-
157
- /** @internal */
158
- constructor(tabId: string | null, defaultIntent?: string) {
159
- this._tabId = tabId;
160
- this._defaultIntent = defaultIntent;
161
- // Start passive HAR recording so all network traffic is captured
162
- if (tabId) {
163
- kuri.harStart(tabId).then(() => { this._harActive = true; }).catch(() => {});
164
- }
165
- }
166
-
167
- /** Whether this page has a live browser tab (vs skill-cache-only) */
168
- get hasTab(): boolean { return this._tabId !== null; }
169
-
170
- /** The raw Kuri tab ID, for direct kuri API calls */
171
- get tabId(): string | null { return this._tabId; }
172
-
173
- private async ensureLiveTab(): Promise<string | null> {
174
- if (this._tabId) return this._tabId;
175
- try {
176
- const tabId = await kuri.newTab();
177
- if (!tabId) return null;
178
- this._tabId = tabId;
179
- try {
180
- await kuri.harStart(tabId);
181
- this._harActive = true;
182
- } catch {
183
- this._harActive = false;
184
- }
185
- return tabId;
186
- } catch {
187
- return null;
188
- }
189
- }
190
-
191
- // ── Navigation ──────────────────────────────────────────────────────
192
-
193
- /**
194
- * Navigate to a URL. Unbrowse transparently checks skill cache first —
195
- * if a cached route exists, returns structured API data without opening
196
- * a browser tab. On cache miss, navigates via Kuri and captures traffic
197
- * in the background for future acceleration.
198
- */
199
- async goto(url: string, options?: GotoOptions): Promise<UnbrowseResponse> {
200
- const previousUrl = this._url;
201
- this._url = url;
202
- this._skillResult = null;
203
- this._html = null;
204
-
205
- const intent = options?.intent ?? this._defaultIntent ?? inferIntentFromUrl(url);
206
- const domain = new URL(url).hostname;
207
-
208
- try {
209
- const result = await resolveAndExecute(
210
- intent,
211
- {},
212
- { url, domain },
213
- undefined,
214
- { intent },
215
- );
216
-
217
- const status = typeof result.result === "object" && result.result
218
- ? (result.result as Record<string, unknown>).status
219
- : undefined;
220
- if (result.trace.success && result.result && status !== "no_cached_match" && !Array.isArray((result as { available_endpoints?: unknown }).available_endpoints)) {
221
- this._skillResult = {
222
- skill: result.skill,
223
- trace: result.trace,
224
- result: result.result,
225
- source: result.source ?? "unknown",
226
- };
227
-
228
- return new UnbrowseResponse({
229
- status: 200,
230
- headers: { "content-type": "application/json", "x-unbrowse-source": String(result.source ?? "skill") },
231
- url,
232
- body: result.result,
233
- });
234
- }
235
- } catch {
236
- // Resolve failed — fall through to kuri navigation
237
- }
238
-
239
- // Cache miss or resolve failure — navigate via Kuri directly.
240
- const liveTabId = await this.ensureLiveTab();
241
- if (liveTabId) {
242
- const newDomain = new URL(url).hostname.replace(/^www\./, "");
243
- const oldDomain = previousUrl !== "about:blank" ? (() => { try { return new URL(previousUrl).hostname.replace(/^www\./, ""); } catch { return ""; } })() : "";
244
-
245
- // Flush any prior HAR entries before navigating to a new page
246
- if (this._harActive && previousUrl !== "about:blank") {
247
- try {
248
- const { entries } = await kuri.harStop(liveTabId);
249
- passiveIndexHar(entries, previousUrl);
250
- } catch { /* non-fatal */ }
251
- this._harActive = false;
252
- }
253
-
254
- // Auto-save auth profile for old domain, then restore fresh browser cookies
255
- // before any saved auth profile for the new domain.
256
- if (oldDomain && oldDomain !== newDomain) {
257
- await saveAuthProfileBestEffort(liveTabId, oldDomain, "browser_goto");
258
- }
259
- if (newDomain && newDomain !== oldDomain) {
260
- await importBrowserCookiesIntoTab(liveTabId, newDomain);
261
- await loadAuthProfileBestEffort(liveTabId, newDomain, "browser_goto");
262
- }
263
-
264
- await kuri.navigate(liveTabId, url);
265
- const finalUrl = await kuri.getCurrentUrl(liveTabId).catch(() => url);
266
- if (typeof finalUrl === "string" && finalUrl.startsWith("http")) {
267
- this._url = finalUrl;
268
- }
269
-
270
- // Restart HAR recording for the new page
271
- if (!this._harActive) {
272
- kuri.harStart(liveTabId).then(() => { this._harActive = true; }).catch(() => {});
273
- }
274
-
275
- try {
276
- const html = await kuri.getPageHtml(liveTabId);
277
- if (typeof html === "string" && html.startsWith("<")) {
278
- this._html = html;
279
- }
280
- } catch {
281
- // Non-fatal — content() will retry on demand
282
- }
283
- }
284
-
285
- return new UnbrowseResponse({
286
- status: 200,
287
- headers: { "x-unbrowse-source": "browser" },
288
- url: this._url,
289
- body: this._html ?? null,
290
- });
291
- }
292
-
293
- /** Navigate back */
294
- async goBack(): Promise<void> {
295
- await kuri.goBack(requireTab(this._tabId));
296
- }
297
-
298
- /** Navigate forward */
299
- async goForward(): Promise<void> {
300
- await kuri.goForward(requireTab(this._tabId));
301
- }
302
-
303
- /** Reload the page */
304
- async reload(): Promise<void> {
305
- await kuri.reload(requireTab(this._tabId));
306
- }
307
-
308
- /** Get current URL */
309
- url(): string {
310
- return this._url;
311
- }
312
-
313
- // ── Content Extraction ──────────────────────────────────────────────
314
-
315
- /** Get page HTML content */
316
- async content(): Promise<string> {
317
- if (this._skillResult) {
318
- const data = this._skillResult.result;
319
- return `<!DOCTYPE html><html><body><script type="application/json" id="unbrowse-data">${JSON.stringify(data)}</script></body></html>`;
320
- }
321
- if (this._tabId) {
322
- const html = await kuri.getPageHtml(this._tabId).catch(() => "");
323
- if (typeof html === "string" && html.startsWith("<")) {
324
- this._html = html;
325
- return html;
326
- }
327
- }
328
- return this._html ?? "";
329
- }
330
-
331
- /** Get page text content (stripped of HTML) */
332
- async text(): Promise<string> {
333
- return kuri.getText(requireTab(this._tabId));
334
- }
335
-
336
- /** Get page content as Markdown */
337
- async markdown(): Promise<string> {
338
- return kuri.getMarkdown(requireTab(this._tabId));
339
- }
340
-
341
- /** Extract all links from the page */
342
- async links(): Promise<unknown> {
343
- return kuri.getLinks(requireTab(this._tabId));
344
- }
345
-
346
- /**
347
- * Get accessibility tree snapshot — token-optimized for LLMs.
348
- * Returns elements with stable @eN refs for use with click/fill/action.
349
- * This is Kuri's primary observation primitive for agent loops.
350
- */
351
- async snapshot(filter?: string): Promise<string> {
352
- return kuri.snapshot(requireTab(this._tabId), filter);
353
- }
354
-
355
- // ── Actions (ref-based via Kuri) ────────────────────────────────────
356
-
357
- /**
358
- * Click an element by ref (from snapshot) or CSS selector.
359
- * Ref-based clicks (e.g. "e5") use Kuri's native action system.
360
- * CSS selectors fall back to evaluate-based clicking.
361
- */
362
- async click(refOrSelector: string): Promise<void> {
363
- const tabId = requireTab(this._tabId);
364
- if (/^e\d+$/.test(refOrSelector)) {
365
- await kuri.click(tabId, refOrSelector);
366
- } else {
367
- await kuri.evaluate(tabId, `document.querySelector(${JSON.stringify(refOrSelector)})?.click()`);
368
- }
369
- }
370
-
371
- /**
372
- * Fill an input by ref (from snapshot) or CSS selector.
373
- * Ref-based fills use Kuri's native action system with input event dispatch.
374
- */
375
- async fill(refOrSelector: string, value: string): Promise<void> {
376
- const tabId = requireTab(this._tabId);
377
- if (/^e\d+$/.test(refOrSelector)) {
378
- await kuri.fill(tabId, refOrSelector, value);
379
- } else {
380
- await kuri.evaluate(tabId, `(() => { const el = document.querySelector(${JSON.stringify(refOrSelector)}); if (el) { el.value = ${JSON.stringify(value)}; el.dispatchEvent(new Event('input', {bubbles:true})); } })()`);
381
- }
382
- }
383
-
384
- /** Select an option by ref */
385
- async select(ref: string, value: string): Promise<void> {
386
- await kuri.select(requireTab(this._tabId), ref, value);
387
- }
388
-
389
- /** Scroll by direction */
390
- async scroll(direction: "up" | "down" | "left" | "right" = "down", amount?: number): Promise<void> {
391
- await kuri.scroll(requireTab(this._tabId), direction, amount);
392
- }
393
-
394
- /** Scroll an element into view by ref */
395
- async scrollIntoView(ref: string): Promise<void> {
396
- await kuri.scrollIntoView(requireTab(this._tabId), ref);
397
- }
398
-
399
- /** Drag from one ref to another */
400
- async drag(fromRef: string, toRef: string): Promise<void> {
401
- await kuri.drag(requireTab(this._tabId), fromRef, toRef);
402
- }
403
-
404
- /** Press a key (e.g. "Enter", "Tab", "Escape") */
405
- async press(key: string): Promise<void> {
406
- await kuri.press(requireTab(this._tabId), key);
407
- }
408
-
409
- /** Perform a raw Kuri action by ref */
410
- async action(actionType: string, ref: string, value?: string): Promise<unknown> {
411
- return kuri.action(requireTab(this._tabId), actionType as any, ref, value);
412
- }
413
-
414
- // ── Keyboard ────────────────────────────────────────────────────────
415
-
416
- /** Type text with key events */
417
- async type(text: string): Promise<void> {
418
- await kuri.keyboardType(requireTab(this._tabId), text);
419
- }
420
-
421
- /** Insert text directly (no key events) */
422
- async insertText(text: string): Promise<void> {
423
- await kuri.keyboardInsertText(requireTab(this._tabId), text);
424
- }
425
-
426
- /** Dispatch a keydown event */
427
- async keyDown(key: string): Promise<void> {
428
- await kuri.keyDown(requireTab(this._tabId), key);
429
- }
430
-
431
- /** Dispatch a keyup event */
432
- async keyUp(key: string): Promise<void> {
433
- await kuri.keyUp(requireTab(this._tabId), key);
434
- }
435
-
436
- // ── Wait ────────────────────────────────────────────────────────────
437
-
438
- /** Wait for a CSS selector to appear */
439
- async waitForSelector(selector: string, options?: { timeout?: number }): Promise<void> {
440
- if (!this._tabId) return; // No-op for skill-resolved pages
441
- const timeout = options?.timeout ?? 5000;
442
- const start = Date.now();
443
- while (Date.now() - start < timeout) {
444
- const found = await kuri.evaluate(this._tabId, `!!document.querySelector(${JSON.stringify(selector)})`);
445
- if (found === "true" || found === true) return;
446
- await new Promise(r => setTimeout(r, 200));
447
- }
448
- throw new Error(`waitForSelector: timeout waiting for ${selector}`);
449
- }
450
-
451
- /** Wait for page load */
452
- async waitForLoad(): Promise<void> {
453
- await kuri.waitForLoad(requireTab(this._tabId));
454
- }
455
-
456
- // ── Evaluate ────────────────────────────────────────────────────────
457
-
458
- /** Evaluate JavaScript in page context */
459
- async evaluate<T = unknown>(fn: string | (() => T)): Promise<T> {
460
- const tabId = requireTab(this._tabId);
461
- const script = typeof fn === "function" ? `(${fn.toString()})()` : fn;
462
- const result = await kuri.evaluate(tabId, script);
463
- return result as T;
464
- }
465
-
466
- // ── DOM Queries ─────────────────────────────────────────────────────
467
-
468
- /** Query DOM elements by CSS selector */
469
- async query(selector: string): Promise<unknown> {
470
- return kuri.domQuery(requireTab(this._tabId), selector);
471
- }
472
-
473
- /** Get element HTML by CSS selector */
474
- async innerHTML(selector: string): Promise<unknown> {
475
- return kuri.domHtml(requireTab(this._tabId), selector);
476
- }
477
-
478
- /** Get element attributes by ref */
479
- async attributes(ref: string): Promise<unknown> {
480
- return kuri.domAttributes(requireTab(this._tabId), ref);
481
- }
482
-
483
- /** Find text matches in the page */
484
- async findText(query: string): Promise<unknown> {
485
- return kuri.findText(requireTab(this._tabId), query);
486
- }
487
-
488
- // ── Screenshots & Media ─────────────────────────────────────────────
489
-
490
- /** Take a screenshot (returns base64-encoded PNG string) */
491
- async screenshot(): Promise<string> {
492
- return kuri.screenshot(requireTab(this._tabId));
493
- }
494
-
495
- // ── Cookies & Auth ──────────────────────────────────────────────────
496
-
497
- /** Get cookies for the current page */
498
- async cookies(): Promise<unknown> {
499
- return kuri.getCookies(requireTab(this._tabId));
500
- }
501
-
502
- /** Set a cookie */
503
- async setCookie(name: string, value: string, domain?: string): Promise<void> {
504
- await kuri.setCookie(requireTab(this._tabId), name, value, domain);
505
- }
506
-
507
- /** Set custom request headers */
508
- async setHeaders(headers: Record<string, string>): Promise<void> {
509
- await kuri.setHeaders(requireTab(this._tabId), headers);
510
- }
511
-
512
- // ── HAR Recording ───────────────────────────────────────────────────
513
-
514
- /** Start recording network traffic (HAR format) */
515
- async harStart(): Promise<void> {
516
- await kuri.harStart(requireTab(this._tabId));
517
- }
518
-
519
- /** Stop recording and return HAR 1.2 JSON */
520
- async harStop(): Promise<unknown> {
521
- return kuri.harStop(requireTab(this._tabId));
522
- }
523
-
524
- /** Get network events */
525
- async networkEvents(): Promise<unknown> {
526
- return kuri.getNetworkEvents(requireTab(this._tabId));
527
- }
528
-
529
- // ── Viewport & Emulation ────────────────────────────────────────────
530
-
531
- /** Set viewport size */
532
- async setViewport(width: number, height: number): Promise<void> {
533
- await kuri.setViewport(requireTab(this._tabId), width, height);
534
- }
535
-
536
- /** Override user agent */
537
- async setUserAgent(ua: string): Promise<void> {
538
- await kuri.setUserAgent(requireTab(this._tabId), ua);
539
- }
540
-
541
- /** Set HTTP basic auth credentials */
542
- async setCredentials(username: string, password: string): Promise<void> {
543
- await kuri.setCredentials(requireTab(this._tabId), username, password);
544
- }
545
-
546
- // ── Session ─────────────────────────────────────────────────────────
547
-
548
- /** Save browser session (cookies + storage) */
549
- async sessionSave(name: string): Promise<void> {
550
- await kuri.sessionSave(requireTab(this._tabId), name);
551
- }
552
-
553
- /** Restore a saved browser session */
554
- async sessionLoad(name: string): Promise<void> {
555
- await kuri.sessionLoad(requireTab(this._tabId), name);
556
- }
557
-
558
- /** List saved sessions */
559
- async sessionList(): Promise<unknown> {
560
- return kuri.sessionList(requireTab(this._tabId));
561
- }
562
-
563
- // ── Debug ───────────────────────────────────────────────────────────
564
-
565
- /** Get console messages */
566
- async console(): Promise<unknown> {
567
- return kuri.getConsole(requireTab(this._tabId));
568
- }
569
-
570
- /** Get page/runtime errors */
571
- async errors(): Promise<unknown> {
572
- return kuri.getErrors(requireTab(this._tabId));
573
- }
574
-
575
- /** Inject JavaScript into the page */
576
- async injectScript(script: string): Promise<void> {
577
- await kuri.scriptInject(requireTab(this._tabId), script);
578
- }
579
-
580
- // ── Lifecycle ───────────────────────────────────────────────────────
581
-
582
- /** Close this page. Saves auth profile, stops HAR, indexes captured traffic. */
583
- async close(): Promise<void> {
584
- if (this._tabId && !this._closed) {
585
- // Save auth profile for current domain before closing
586
- if (this._url !== "about:blank") {
587
- try {
588
- const domain = new URL(this._url).hostname.replace(/^www\./, "");
589
- await saveAuthProfileBestEffort(this._tabId, domain, "browser_close");
590
- } catch { /* non-fatal */ }
591
- }
592
-
593
- // Stop HAR and passively index any captured API traffic
594
- if (this._harActive) {
595
- try {
596
- const { entries } = await kuri.harStop(this._tabId);
597
- passiveIndexHar(entries, this._url);
598
- } catch { /* HAR stop failure is non-fatal */ }
599
- this._harActive = false;
600
- }
601
- await kuri.closeTab(this._tabId).catch(() => {});
602
- this._closed = true;
603
- }
604
- }
605
-
606
- /** Access raw unbrowse skill data (non-Playwright extension) */
607
- get $unbrowse(): SkillResolutionResult | null {
608
- return this._skillResult;
609
- }
610
- }
611
-
612
- /**
613
- * Browser — launches Kuri (Zig-native CDP broker) as the primary browser.
614
- *
615
- * Kuri is the agent's browser. Unbrowse runs in the background, learning
616
- * internal APIs from traffic and progressively replacing browser calls with
617
- * direct API calls via the skill cache.
618
- */
619
- export class Browser {
620
- private _pages: Page[] = [];
621
- private _defaultIntent?: string;
622
- private _started = false;
623
-
624
- private constructor(options?: BrowserLaunchOptions) {
625
- this._defaultIntent = options?.intent;
626
- }
627
-
628
- /** Launch Kuri browser instance */
629
- static async launch(options?: BrowserLaunchOptions): Promise<Browser> {
630
- const browser = new Browser(options);
631
- await kuri.start().catch(() => {});
632
- browser._started = true;
633
- return browser;
634
- }
635
-
636
- /** Create a new page (tab) */
637
- async newPage(): Promise<Page> {
638
- const page = new Page(null, this._defaultIntent);
639
- this._pages.push(page);
640
- return page;
641
- }
642
-
643
- /** Get all open pages */
644
- pages(): Page[] {
645
- return [...this._pages];
646
- }
647
-
648
- /** Close the browser and all pages */
649
- async close(): Promise<void> {
650
- for (const page of this._pages) {
651
- await page.close();
652
- }
653
- this._pages = [];
654
- if (this._started) {
655
- await kuri.stop().catch(() => {});
656
- this._started = false;
657
- }
658
- }
659
- }
@@ -1,41 +0,0 @@
1
- import type { SkillManifest, ExecutionTrace } from "../types/index.js";
2
-
3
- export interface UnbrowseResponseData {
4
- status: number;
5
- headers: Record<string, string>;
6
- url: string;
7
- body: unknown;
8
- }
9
-
10
- export class UnbrowseResponse {
11
- private _data: UnbrowseResponseData;
12
- constructor(data: UnbrowseResponseData) { this._data = data; }
13
- status(): number { return this._data.status; }
14
- headers(): Record<string, string> { return this._data.headers; }
15
- url(): string { return this._data.url; }
16
- async json(): Promise<unknown> { return this._data.body; }
17
- async text(): Promise<string> { return typeof this._data.body === "string" ? this._data.body : JSON.stringify(this._data.body); }
18
- }
19
-
20
- export interface GotoOptions {
21
- /** Override inferred intent for resolve */
22
- intent?: string;
23
- /** Timeout in ms */
24
- timeout?: number;
25
- /** Wait until condition */
26
- waitUntil?: "load" | "domcontentloaded" | "networkidle";
27
- }
28
-
29
- export interface BrowserLaunchOptions {
30
- /** Headless mode (default true) */
31
- headless?: boolean;
32
- /** Default intent for resolve calls */
33
- intent?: string;
34
- }
35
-
36
- export interface SkillResolutionResult {
37
- skill: SkillManifest;
38
- trace: ExecutionTrace;
39
- result: unknown;
40
- source: string;
41
- }