@usecrow/client 0.1.36 → 0.1.37
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/PageController-Cu6KUkcn.cjs +9 -0
- package/dist/{PageController-BweWYS-Z.js → PageController-D3uwrwlG.js} +588 -382
- package/dist/browser.cjs +1 -1
- package/dist/browser.d.ts +65 -0
- package/dist/browser.js +2 -2
- package/dist/{browserUse-Btg7osSj.js → browserUse-Cioetz2-.js} +1 -1
- package/dist/{browserUse-BjeJDX8x.cjs → browserUse-DYW8fqvT.cjs} +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.ts +415 -0
- package/dist/index.js +208 -78
- package/package.json +1 -1
- package/dist/PageController-BDcmu8Xe.cjs +0 -9
package/dist/browser.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("./PageController-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("./PageController-Cu6KUkcn.cjs"),e=require("./browserUse-DYW8fqvT.cjs");e.setPageController(u.PageController);let o=null;function a(){o&&(console.log("[Crow] Stopping active browser-use automation"),o.stop(),o=null)}function c(t,l){return async n=>{const s=n.instruction||n.instruction;if(!s)return{status:"error",error:"Missing instruction parameter for browser_use tool"};const w=window.__crow_browser_callbacks,r=l||w,i=new e.CrowBrowserUse({productId:t.productId,apiUrl:t.apiUrl,onConfirmation:r==null?void 0:r.onConfirmation,onQuestion:r==null?void 0:r.onQuestion,onProgress:r==null?void 0:r.onProgress});o=i;try{return await i.execute(s)}finally{o=null}}}exports.PageController=u.PageController;exports.CrowBrowserUse=e.CrowBrowserUse;exports.createBrowserUseTool=c;exports.stopActiveBrowserUse=a;
|
package/dist/browser.d.ts
CHANGED
|
@@ -301,6 +301,71 @@ export declare class PageController extends EventTarget {
|
|
|
301
301
|
* Execute arbitrary JavaScript on the page
|
|
302
302
|
*/
|
|
303
303
|
executeJavascript(script: string): Promise<ActionResult>;
|
|
304
|
+
/**
|
|
305
|
+
* Find an interactive element index by visible text (exact match).
|
|
306
|
+
* Scans the elementTextMap for a match.
|
|
307
|
+
*/
|
|
308
|
+
findElementByText(text: string, exact?: boolean): number | null;
|
|
309
|
+
/**
|
|
310
|
+
* Find an interactive element index by CSS selector.
|
|
311
|
+
* Queries the DOM, then reverse-looks up in selectorMap.
|
|
312
|
+
*/
|
|
313
|
+
findElementBySelector(cssSelector: string): number | null;
|
|
314
|
+
/**
|
|
315
|
+
* Find an interactive element index by XPath.
|
|
316
|
+
* Evaluates the XPath, then reverse-looks up in selectorMap.
|
|
317
|
+
*/
|
|
318
|
+
findElementByXPath(xpath: string): number | null;
|
|
319
|
+
/**
|
|
320
|
+
* Find an interactive element index by aria-label attribute.
|
|
321
|
+
*/
|
|
322
|
+
findElementByAriaLabel(label: string): number | null;
|
|
323
|
+
/**
|
|
324
|
+
* Find an interactive element index by placeholder text.
|
|
325
|
+
*/
|
|
326
|
+
findElementByPlaceholder(placeholder: string): number | null;
|
|
327
|
+
/**
|
|
328
|
+
* Multi-strategy element finder. Tries strategies in priority order.
|
|
329
|
+
* Returns the index of the first match, or null if nothing found.
|
|
330
|
+
*/
|
|
331
|
+
findElementByStrategies(strategies: Array<{
|
|
332
|
+
type: 'text_exact' | 'text_contains' | 'aria_label' | 'placeholder' | 'css' | 'xpath';
|
|
333
|
+
value: string;
|
|
334
|
+
priority: number;
|
|
335
|
+
}>): number | null;
|
|
336
|
+
/**
|
|
337
|
+
* Press a key on an element (or the active element if no index provided).
|
|
338
|
+
*/
|
|
339
|
+
pressKey(key: string, index?: number): Promise<ActionResult>;
|
|
340
|
+
/**
|
|
341
|
+
* Navigate to a URL. Restricts to same-origin http(s) URLs for security.
|
|
342
|
+
*/
|
|
343
|
+
navigateToUrl(url: string): Promise<ActionResult>;
|
|
344
|
+
/**
|
|
345
|
+
* Go back in browser history.
|
|
346
|
+
*/
|
|
347
|
+
goBack(): Promise<ActionResult>;
|
|
348
|
+
/**
|
|
349
|
+
* Go forward in browser history.
|
|
350
|
+
*/
|
|
351
|
+
goForward(): Promise<ActionResult>;
|
|
352
|
+
/**
|
|
353
|
+
* Wait until an element matching the given strategies appears in the DOM,
|
|
354
|
+
* or until the timeout is reached. Refreshes the DOM tree on each poll.
|
|
355
|
+
*/
|
|
356
|
+
waitForElement(strategies: Array<{
|
|
357
|
+
type: 'text_exact' | 'text_contains' | 'aria_label' | 'placeholder' | 'css' | 'xpath';
|
|
358
|
+
value: string;
|
|
359
|
+
priority: number;
|
|
360
|
+
}>, timeoutMs?: number, pollIntervalMs?: number): Promise<number | null>;
|
|
361
|
+
/**
|
|
362
|
+
* Get the current selectorMap (for external use like WorkflowExecutor).
|
|
363
|
+
*/
|
|
364
|
+
getSelectorMap(): Map<number, InteractiveElementDomNode>;
|
|
365
|
+
/**
|
|
366
|
+
* Get the current elementTextMap (for external use like WorkflowExecutor).
|
|
367
|
+
*/
|
|
368
|
+
getElementTextMap(): Map<number, string>;
|
|
304
369
|
/**
|
|
305
370
|
* Show the visual mask overlay.
|
|
306
371
|
* Only works after mask is setup.
|
package/dist/browser.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { PageController as l } from "./PageController-
|
|
2
|
-
import { C as w, s as a } from "./browserUse-
|
|
1
|
+
import { PageController as l } from "./PageController-D3uwrwlG.js";
|
|
2
|
+
import { C as w, s as a } from "./browserUse-Cioetz2-.js";
|
|
3
3
|
a(l);
|
|
4
4
|
let r = null;
|
|
5
5
|
function m() {
|
|
@@ -7,7 +7,7 @@ async function _() {
|
|
|
7
7
|
return d;
|
|
8
8
|
if (!h)
|
|
9
9
|
try {
|
|
10
|
-
h = await import("./PageController-
|
|
10
|
+
h = await import("./PageController-D3uwrwlG.js");
|
|
11
11
|
} catch {
|
|
12
12
|
throw new Error(
|
|
13
13
|
'PageController not available. Either import from "@usecrow/client/browser" or use the bundled version.'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";let d=null,h=null;function B(p){d=p}async function _(){if(d)return d;if(!h)try{h=await Promise.resolve().then(()=>require("./PageController-
|
|
1
|
+
"use strict";let d=null,h=null;function B(p){d=p}async function _(){if(d)return d;if(!h)try{h=await Promise.resolve().then(()=>require("./PageController-Cu6KUkcn.cjs"))}catch{throw new Error('PageController not available. Either import from "@usecrow/client/browser" or use the bundled version.')}return h.PageController}class T{constructor(e){this.pageController=null,this.sessionId=null,this.maxSteps=20,this.aborted=!1,this.config=e}async initPageController(){if(this.pageController)return this.pageController;try{const e=await _();this.pageController=new e({enableMask:!0,viewportExpansion:500,highlightLabelOpacity:0,highlightOpacity:0}),await this.pageController.showMask();const s=this.pageController.mask;return s!=null&&s.wrapper&&(s.wrapper.style.pointerEvents="none"),console.log("[CrowBrowserUse] PageController initialized with non-blocking pointer"),this.pageController}catch(e){throw console.error("[CrowBrowserUse] Failed to initialize PageController:",e),new Error("Failed to initialize browser automation. Please import from @usecrow/client/browser.")}}async execute(e){var s,n,r,o,c,g,f,C,m,y,x,U,b,S;if(console.log("[CrowBrowserUse] Starting task:",e),this.config.onConfirmation&&!await this.config.onConfirmation(e))return console.log("[CrowBrowserUse] User declined browser automation"),(n=(s=this.config).onProgress)==null||n.call(s,-1,this.maxSteps),{status:"error",error:"User declined browser automation",data:{declined:!0}};try{const i=await this.initPageController(),P=await this.startSession(e);this.sessionId=P.session_id,this.maxSteps=P.max_steps,console.log("[CrowBrowserUse] Session started:",this.sessionId);let l=0,a;for(;l<this.maxSteps;){if(this.aborted)return console.log("[CrowBrowserUse] Task cancelled by user"),await this.cleanup(),(o=(r=this.config).onProgress)==null||o.call(r,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"};l++;const k=await i.getBrowserState(),u=i.mask;u!=null&&u.wrapper&&(u.wrapper.style.pointerEvents="none");const t=await this.processStep(k,a);if(t.needs_user_input&&t.question){if(console.log("[CrowBrowserUse] Asking user:",t.question),!this.config.onQuestion){a="User input not available - no callback provided",console.warn("[CrowBrowserUse] No onQuestion callback provided");continue}try{const w=await this.config.onQuestion(t.question);a=`User answered: ${w}`,console.log("[CrowBrowserUse] User answered:",w)}catch(w){if(a="User cancelled or failed to respond",console.log("[CrowBrowserUse] User cancelled or error:",w),this.aborted)return console.log("[CrowBrowserUse] Aborted after user cancelled"),await this.cleanup(),(g=(c=this.config).onProgress)==null||g.call(c,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"}}continue}if(t.done)return console.log("[CrowBrowserUse] Task completed:",t.message),await this.cleanup(),(C=(f=this.config).onProgress)==null||C.call(f,l,this.maxSteps),{status:t.success?"success":"error",data:{message:t.message,steps:l},error:t.success?void 0:t.message};if(t.error)return console.error("[CrowBrowserUse] Error:",t.error),await this.cleanup(),(y=(m=this.config).onProgress)==null||y.call(m,-1,this.maxSteps),{status:"error",error:t.error};t.action&&(a=await this.executeAction(i,t.action),console.log(`[CrowBrowserUse] Step ${l}:`,a)),t.reflection&&console.log("[CrowBrowserUse] Reflection:",t.reflection.next_goal)}return await this.cleanup(),(U=(x=this.config).onProgress)==null||U.call(x,-1,this.maxSteps),{status:"error",error:`Task incomplete after ${this.maxSteps} steps`}}catch(i){return console.error("[CrowBrowserUse] Error:",i),await this.cleanup(),(S=(b=this.config).onProgress)==null||S.call(b,-1,this.maxSteps),{status:"error",error:i instanceof Error?i.message:String(i)}}}async startSession(e){const s=await fetch(`${this.config.apiUrl}/api/browser-use/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:this.config.productId,task:e})});if(!s.ok){const n=await s.json().catch(()=>({detail:"Unknown error"}));throw new Error(n.detail||`Failed to start session: ${s.status}`)}return s.json()}async processStep(e,s){const n=await fetch(`${this.config.apiUrl}/api/browser-use/step`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId,browser_state:e,action_result:s})});if(!n.ok){const r=await n.json().catch(()=>({detail:"Unknown error"}));throw new Error(r.detail||`Failed to process step: ${n.status}`)}return n.json()}async executeAction(e,s){const n=Object.keys(s)[0],r=s[n];try{switch(n){case"click_element_by_index":return(await e.clickElement(r.index)).message;case"input_text":return(await e.inputText(r.index,r.text)).message;case"select_dropdown_option":return(await e.selectOption(r.index,r.text)).message;case"scroll":return(await e.scroll({down:r.down,numPages:r.num_pages,pixels:r.pixels,index:r.index})).message;case"scroll_horizontally":return(await e.scrollHorizontally({right:r.right,pixels:r.pixels,index:r.index})).message;case"wait":{const o=r.seconds||1;return await new Promise(c=>setTimeout(c,o*1e3)),`Waited ${o} seconds`}case"done":return"Task completed";default:return`Unknown action: ${n}`}}catch(o){return`Action failed: ${o instanceof Error?o.message:String(o)}`}}async cleanup(){if(this.pageController){try{await this.pageController.hideMask(),await this.pageController.cleanUpHighlights(),this.pageController.dispose()}catch(e){console.warn("[CrowBrowserUse] Cleanup error:",e)}this.pageController=null}if(this.sessionId){try{await fetch(`${this.config.apiUrl}/api/browser-use/end`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId})})}catch{}this.sessionId=null}}async stop(){this.aborted=!0,await this.cleanup()}}exports.CrowBrowserUse=T;exports.setPageController=B;
|
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("./browserUse-
|
|
2
|
-
`).replace(/\\'/g,"'")}return e}}function
|
|
3
|
-
`);for(const t of e)t.startsWith("data: ")&&(yield t.slice(6).trim())}async function*M(o,e){var n;const t=(n=o.body)==null?void 0:n.getReader();if(!t)throw new Error("Response body is not readable");const s=new TextDecoder;let r="";try{for(;;){if(e!=null&&e.aborted){t.cancel();return}const{done:i,value:d}=await t.read();if(i)break;const h=s.decode(d);for(const u of b(h)){const l=C(u);if(l&&(l.type==="content"?(r+=l.text,yield{...l,accumulated:r}):yield l,l.type==="done"))return}}}finally{t.releaseLock()}}async function L(){try{return window.location.reload(),{status:"success",data:{refreshed:!0}}}catch(o){return{status:"error",error:o instanceof Error?o.message:"Failed to refresh page"}}}async function $(){var o;try{const e=document.title,t=window.location.href,s=window.location.pathname,r=(((o=document.body)==null?void 0:o.innerText)||"").slice(0,2e3).trim();return{status:"success",data:{title:e,url:t,pathname:s,visibleText:r}}}catch(e){return{status:"error",error:e instanceof Error?e.message:"Failed to read screen"}}}const g={refreshPage:L,whatsOnScreen:$},S=Object.keys(g),U="https://api.usecrow.org",x="claude-sonnet-4-20250514";class O{constructor(e){this.context={},this.abortController=null,this.callbacks={},this._messages=[],this.messageListeners=new Set,this._isLoading=!1,this.loadingListeners=new Set,this.config={productId:e.productId,apiUrl:e.apiUrl||U,model:e.model||x},this.identity=new _,this.tools=new k,this.conversations=new v(this.config.productId,this.config.apiUrl),this.tools.register(g),console.log("[Crow] Default tools registered:",S.join(", ")),this.identity.subscribe(t=>{var s,r;(r=(s=this.callbacks).onVerificationStatus)==null||r.call(s,t.isVerified)})}get productId(){return this.config.productId}get apiUrl(){return this.config.apiUrl}get model(){return this.config.model}set model(e){this.config.model=e}on(e){this.callbacks={...this.callbacks,...e}}identify(e){this.identity.identify(e)}resetUser(){this.identity.reset(),this.clearMessages()}isIdentified(){return this.identity.isIdentified()}isVerified(){return this.identity.isVerified()}registerTools(e){this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}getRegisteredTools(){return this.tools.getRegisteredTools()}setContext(e){this.context={...this.context,...e}}clearContext(){this.context={}}get messages(){return[...this._messages]}get isLoading(){return this._isLoading}onMessages(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onLoading(e){return this.loadingListeners.add(e),()=>this.loadingListeners.delete(e)}clearMessages(){this._messages=[],this.conversations.clear(),this.notifyMessages()}loadMessages(e){this._messages=e,this.notifyMessages()}notifyMessages(){const e=this.messages;for(const t of this.messageListeners)t(e)}setLoading(e){this._isLoading=e;for(const t of this.loadingListeners)t(e)}addMessage(e){var t,s;this._messages=[...this._messages,e],this.notifyMessages(),(s=(t=this.callbacks).onMessage)==null||s.call(t,e)}updateMessage(e,t){var s,r;this._messages=this._messages.map(n=>n.id===e?{...n,...t}:n),this.notifyMessages(),(r=(s=this.callbacks).onMessageUpdate)==null||r.call(s,e,t)}generateMessageId(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}get conversationId(){return this.conversations.getCurrentId()}set conversationId(e){this.conversations.setCurrentId(e)}async getConversations(){const e=this.identity.getToken();return e?this.conversations.getConversations(e):(console.warn("[Crow] Cannot get conversations: user not identified"),[])}async loadHistory(e){const t=this.identity.getToken();return t?this.conversations.loadHistory(e,t):this.conversations.loadAnonymousHistory(e)}async switchConversation(e){const t=await this.loadHistory(e);this.conversations.setCurrentId(e),this.loadMessages(t)}async*sendMessage(e){var i,d,h,u,l,f,p,y,m,w;if(!e.trim())return;const t=this.generateMessageId("user");this.addMessage({id:t,content:e,role:"user",timestamp:new Date});const s=this.generateMessageId("assistant");this.addMessage({id:s,content:"",role:"assistant",timestamp:new Date}),this.setLoading(!0),this.abortController=new AbortController;let r="",n="";try{const c=await fetch(`${this.config.apiUrl}/api/chat/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:this.config.productId,message:e,conversation_id:this.conversations.getCurrentId(),identity_token:this.identity.getToken(),model:this.config.model,context:Object.keys(this.context).length>0?this.context:void 0}),signal:this.abortController.signal});if(!c.ok)throw new Error(`HTTP error: ${c.status}`);for await(const a of M(c,this.abortController.signal)){switch(a.type){case"content":r=a.accumulated,this.updateMessage(s,{content:r});break;case"thinking":n+=a.content,this.updateMessage(s,{thinking:n});break;case"thinking_complete":this.updateMessage(s,{thinkingComplete:!0});break;case"citations":this.updateMessage(s,{citations:a.citations});break;case"verification_status":this.identity.setVerified(a.isVerified);break;case"conversation_id":this.conversations.setCurrentId(a.conversationId);break;case"client_tool_call":await this.tools.execute(a.toolName,a.arguments),(d=(i=this.callbacks).onToolCall)==null||d.call(i,a);break;case"tool_call_start":case"tool_call_complete":(u=(h=this.callbacks).onToolCall)==null||u.call(h,a);break;case"workflow_started":case"workflow_todo_updated":case"workflow_ended":case"workflow_complete_prompt":(f=(l=this.callbacks).onWorkflow)==null||f.call(l,a);break;case"error":this.updateMessage(s,{content:a.message}),(y=(p=this.callbacks).onError)==null||y.call(p,new Error(a.message));break}yield a}}catch(c){if(c instanceof Error&&c.name==="AbortError"){r?this.updateMessage(s,{content:r}):(this._messages=this._messages.filter(a=>a.id!==s),this.notifyMessages());return}console.error("[Crow] Error:",c),this.updateMessage(s,{content:"Sorry, I encountered an error. Please try again."}),(w=(m=this.callbacks).onError)==null||w.call(m,c instanceof Error?c:new Error(String(c)))}finally{this.setLoading(!1),this.abortController=null}}async send(e){let t=null;for await(const r of this.sendMessage(e))if(r.type==="done")break;const s=this.messages;return s.length>0&&(t=s[s.length-1],t.role==="assistant")?t:null}stop(){this.abortController&&(this.abortController.abort(),this.setLoading(!1))}destroy(){this.stop(),this.messageListeners.clear(),this.loadingListeners.clear()}}function T(o,e,t){const s=o.find(n=>n.name.toLowerCase()===e.toLowerCase());if(!s)return null;let r=s.path;if(t)for(const[n,i]of Object.entries(t))r=r.replace(`:${n}`,String(i));return r}function A(o,e){return async t=>{try{const s=t.page,r=t.params,n=t.url;let i=null;if(s){if(i=T(o,s,r),!i)return{status:"error",error:`Unknown page: "${s}". Available pages: ${o.map(h=>h.name).join(", ")}`}}else if(n)i=n;else return{status:"error",error:'Either "page" or "url" parameter is required'};const d=i.match(/:([a-zA-Z_][a-zA-Z0-9_]*)/g);return d?{status:"error",error:`Missing parameters: ${d.join(", ")}. Please provide values for these parameters.`}:e?(e(i),{status:"success",data:{navigated_to:i,page:s||void 0,method:"spa_router"}}):(window.location.href=i,{status:"success",data:{navigated_to:i,page:s||void 0,method:"full_navigation"}})}catch(s){return{status:"error",error:String(s)}}}}exports.CrowBrowserUse=I.CrowBrowserUse;exports.ConversationManager=v;exports.CrowClient=O;exports.DEFAULT_TOOLS=g;exports.DEFAULT_TOOL_NAMES=S;exports.IdentityManager=_;exports.ToolManager=k;exports.createNavigateToPageTool=A;exports.parseSSEChunk=b;exports.parseSSEData=C;exports.resolveRoute=T;exports.streamResponse=M;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("./browserUse-DYW8fqvT.cjs");class _{constructor(){this.state={token:null,metadata:{},isVerified:!1},this.listeners=new Set}identify(e){const{token:t,...s}=e;this.state={token:t,metadata:s,isVerified:!1},this.notify(),console.log("[Crow] User identified")}setVerified(e){this.state={...this.state,isVerified:e},this.notify()}reset(){this.state={token:null,metadata:{},isVerified:!1},this.notify(),console.log("[Crow] User reset")}getToken(){return this.state.token}getState(){return{...this.state}}isIdentified(){return this.state.token!==null}isVerified(){return this.state.isVerified}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){const e=this.getState();for(const t of this.listeners)t(e)}}class v{constructor(){this.handlers={}}register(e){for(const[t,s]of Object.entries(e))typeof s=="function"?(this.handlers[t]=s,console.log(`[Crow] Registered client tool: ${t}`)):console.warn(`[Crow] Skipping ${t}: handler is not a function`)}unregister(e){delete this.handlers[e],console.log(`[Crow] Unregistered client tool: ${e}`)}has(e){return e in this.handlers}getRegisteredTools(){return Object.keys(this.handlers)}async execute(e,t){const s=this.handlers[e];if(!s)return console.warn(`[Crow] No handler registered for tool: ${e}`),{status:"error",error:`No handler registered for tool: ${e}`};try{console.log(`[Crow] Executing client tool: ${e}`,t);const r=await s(t);return console.log(`[Crow] Tool ${e} completed:`,r),r}catch(r){const o=r instanceof Error?r.message:String(r);return console.error(`[Crow] Tool ${e} failed:`,r),{status:"error",error:o}}}}const $="crow_conv_";class k{constructor(e,t){this.currentId=null,this.productId=e,this.apiUrl=t,this.currentId=this.loadFromStorage()}getStorageKey(){return`${$}${this.productId}`}loadFromStorage(){try{return localStorage.getItem(this.getStorageKey())}catch{return null}}saveToStorage(e){try{localStorage.setItem(this.getStorageKey(),e)}catch{}}clearStorage(){try{localStorage.removeItem(this.getStorageKey())}catch{}}getCurrentId(){return this.currentId}setCurrentId(e){this.currentId=e,e?this.saveToStorage(e):this.clearStorage()}hasRestoredConversation(){return this.currentId!==null}clear(){this.currentId=null,this.clearStorage()}async getConversations(e){try{const t=await fetch(`${this.apiUrl}/api/chat/conversations?product_id=${this.productId}&identity_token=${encodeURIComponent(e)}`);if(!t.ok)throw new Error(`HTTP error: ${t.status}`);return(await t.json()).conversations||[]}catch(t){return console.error("[Crow] Failed to load conversations:",t),[]}}async loadHistory(e,t){try{const s=await fetch(`${this.apiUrl}/api/chat/conversations/${e}/history?product_id=${this.productId}&identity_token=${encodeURIComponent(t)}`);if(!s.ok)throw new Error(`HTTP error: ${s.status}`);const r=await s.json();return this.parseHistoryMessages(r.messages||[])}catch(s){return console.error("[Crow] Failed to load conversation history:",s),[]}}async loadAnonymousHistory(e){try{const t=await fetch(`${this.apiUrl}/api/chat/conversations/${e}/history/anonymous?product_id=${this.productId}`);if(!t.ok)throw new Error(`HTTP error: ${t.status}`);const s=await t.json();return this.parseHistoryMessages(s.messages||[])}catch(t){return console.error("[Crow] Failed to load anonymous conversation history:",t),[]}}parseHistoryMessages(e){return e.filter(t=>t.role!=="tool"&&!t.content.startsWith("[Client Tool Result:")).map((t,s)=>({id:`history-${s}`,content:this.parseContent(t.content),role:t.role==="assistant"?"assistant":"user",timestamp:new Date}))}parseContent(e){try{const t=JSON.parse(e);if(Array.isArray(t)){const s=t.find(r=>r.type==="text");return(s==null?void 0:s.text)||e}}catch{}if(e.includes("'type': 'text'")){const t=e.match(/\{'text':\s*'((?:[^'\\]|\\.)*)'\s*,\s*'type':\s*'text'/);if(t)return t[1].replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\'/g,"'")}return e}}function S(a){if(a==="[DONE]")return{type:"done"};try{const e=JSON.parse(a);switch(e.type){case"verification_status":return{type:"verification_status",isVerified:e.is_verified===!0};case"conversation_id":return{type:"conversation_id",conversationId:e.conversation_id};case"thinking":return e.status==="complete"?{type:"thinking_complete"}:null;case"thinking_token":return{type:"thinking",content:e.content||""};case"content":return{type:"content",text:e.content||"",accumulated:""};case"citations":return{type:"citations",citations:e.citations};case"error":return{type:"error",message:e.message||"Unknown error"};case"tool_call_start":return{type:"tool_call_start",toolName:e.tool_name,displayName:e.display_name||void 0,arguments:e.arguments||{}};case"tool_call_complete":return{type:"tool_call_complete",toolName:e.tool_name,displayName:e.display_name||void 0,success:e.success};case"client_tool_call":return{type:"client_tool_call",toolName:e.tool_name,displayName:e.display_name||void 0,arguments:e.arguments||{}};case"workflow_started":return{type:"workflow_started",name:e.name,todos:e.todos};case"todo_updated":return{type:"workflow_todo_updated",todoId:e.id,status:e.status};case"workflow_ended":return{type:"workflow_ended"};case"workflow_complete_prompt":return{type:"workflow_complete_prompt"};default:return null}}catch{return console.error("[Crow] Failed to parse SSE data:",a),null}}function*C(a){const e=a.split(`
|
|
3
|
+
`);for(const t of e)t.startsWith("data: ")&&(yield t.slice(6).trim())}async function*T(a,e){var o;const t=(o=a.body)==null?void 0:o.getReader();if(!t)throw new Error("Response body is not readable");const s=new TextDecoder;let r="";try{for(;;){if(e!=null&&e.aborted){t.cancel();return}const{done:n,value:u}=await t.read();if(n)break;const d=s.decode(u);for(const l of C(d)){const h=S(l);if(h&&(h.type==="content"?(r+=h.text,yield{...h,accumulated:r}):yield h,h.type==="done"))return}}}finally{t.releaseLock()}}async function M(){try{return window.location.reload(),{status:"success",data:{refreshed:!0}}}catch(a){return{status:"error",error:a instanceof Error?a.message:"Failed to refresh page"}}}async function x(){var a;try{const e=document.title,t=window.location.href,s=window.location.pathname,r=(((a=document.body)==null?void 0:a.innerText)||"").slice(0,2e3).trim();return{status:"success",data:{title:e,url:t,pathname:s,visibleText:r}}}catch(e){return{status:"error",error:e instanceof Error?e.message:"Failed to read screen"}}}const g={refreshPage:M,whatsOnScreen:x},b=Object.keys(g),L="https://api.usecrow.org",U="claude-sonnet-4-20250514";class O{constructor(e){this.context={},this.abortController=null,this.callbacks={},this._messages=[],this.messageListeners=new Set,this._isLoading=!1,this.loadingListeners=new Set,this.config={productId:e.productId,apiUrl:e.apiUrl||L,model:e.model||U},this.identity=new _,this.tools=new v,this.conversations=new k(this.config.productId,this.config.apiUrl),this.tools.register(g),console.log("[Crow] Default tools registered:",b.join(", ")),this.identity.subscribe(t=>{var s,r;(r=(s=this.callbacks).onVerificationStatus)==null||r.call(s,t.isVerified)})}get productId(){return this.config.productId}get apiUrl(){return this.config.apiUrl}get model(){return this.config.model}set model(e){this.config.model=e}on(e){this.callbacks={...this.callbacks,...e}}identify(e){this.identity.identify(e)}resetUser(){this.identity.reset(),this.clearMessages()}isIdentified(){return this.identity.isIdentified()}isVerified(){return this.identity.isVerified()}registerTools(e){this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}getRegisteredTools(){return this.tools.getRegisteredTools()}setContext(e){this.context={...this.context,...e}}clearContext(){this.context={}}get messages(){return[...this._messages]}get isLoading(){return this._isLoading}onMessages(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onLoading(e){return this.loadingListeners.add(e),()=>this.loadingListeners.delete(e)}clearMessages(){this._messages=[],this.conversations.clear(),this.notifyMessages()}loadMessages(e){this._messages=e,this.notifyMessages()}notifyMessages(){const e=this.messages;for(const t of this.messageListeners)t(e)}setLoading(e){this._isLoading=e;for(const t of this.loadingListeners)t(e)}addMessage(e){var t,s;this._messages=[...this._messages,e],this.notifyMessages(),(s=(t=this.callbacks).onMessage)==null||s.call(t,e)}updateMessage(e,t){var s,r;this._messages=this._messages.map(o=>o.id===e?{...o,...t}:o),this.notifyMessages(),(r=(s=this.callbacks).onMessageUpdate)==null||r.call(s,e,t)}generateMessageId(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}get conversationId(){return this.conversations.getCurrentId()}set conversationId(e){this.conversations.setCurrentId(e)}async getConversations(){const e=this.identity.getToken();return e?this.conversations.getConversations(e):(console.warn("[Crow] Cannot get conversations: user not identified"),[])}async loadHistory(e){const t=this.identity.getToken();return t?this.conversations.loadHistory(e,t):this.conversations.loadAnonymousHistory(e)}async switchConversation(e){const t=await this.loadHistory(e);this.conversations.setCurrentId(e),this.loadMessages(t)}async*sendMessage(e){var n,u,d,l,h,p,f,m,y,w;if(!e.trim())return;const t=this.generateMessageId("user");this.addMessage({id:t,content:e,role:"user",timestamp:new Date});const s=this.generateMessageId("assistant");this.addMessage({id:s,content:"",role:"assistant",timestamp:new Date}),this.setLoading(!0),this.abortController=new AbortController;let r="",o="";try{const c=await fetch(`${this.config.apiUrl}/api/chat/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:this.config.productId,message:e,conversation_id:this.conversations.getCurrentId(),identity_token:this.identity.getToken(),model:this.config.model,context:Object.keys(this.context).length>0?this.context:void 0}),signal:this.abortController.signal});if(!c.ok)throw new Error(`HTTP error: ${c.status}`);for await(const i of T(c,this.abortController.signal)){switch(i.type){case"content":r=i.accumulated,this.updateMessage(s,{content:r});break;case"thinking":o+=i.content,this.updateMessage(s,{thinking:o});break;case"thinking_complete":this.updateMessage(s,{thinkingComplete:!0});break;case"citations":this.updateMessage(s,{citations:i.citations});break;case"verification_status":this.identity.setVerified(i.isVerified);break;case"conversation_id":this.conversations.setCurrentId(i.conversationId);break;case"client_tool_call":await this.tools.execute(i.toolName,i.arguments),(u=(n=this.callbacks).onToolCall)==null||u.call(n,i);break;case"tool_call_start":case"tool_call_complete":(l=(d=this.callbacks).onToolCall)==null||l.call(d,i);break;case"workflow_started":case"workflow_todo_updated":case"workflow_ended":case"workflow_complete_prompt":(p=(h=this.callbacks).onWorkflow)==null||p.call(h,i);break;case"error":this.updateMessage(s,{content:i.message}),(m=(f=this.callbacks).onError)==null||m.call(f,new Error(i.message));break}yield i}}catch(c){if(c instanceof Error&&c.name==="AbortError"){r?this.updateMessage(s,{content:r}):(this._messages=this._messages.filter(i=>i.id!==s),this.notifyMessages());return}console.error("[Crow] Error:",c),this.updateMessage(s,{content:"Sorry, I encountered an error. Please try again."}),(w=(y=this.callbacks).onError)==null||w.call(y,c instanceof Error?c:new Error(String(c)))}finally{this.setLoading(!1),this.abortController=null}}async send(e){let t=null;for await(const r of this.sendMessage(e))if(r.type==="done")break;const s=this.messages;return s.length>0&&(t=s[s.length-1],t.role==="assistant")?t:null}stop(){this.abortController&&(this.abortController.abort(),this.setLoading(!1))}destroy(){this.stop(),this.messageListeners.clear(),this.loadingListeners.clear()}}function E(a,e,t){const s=a.find(o=>o.name.toLowerCase()===e.toLowerCase());if(!s)return null;let r=s.path;if(t)for(const[o,n]of Object.entries(t))r=r.replace(`:${o}`,String(n));return r}function R(a,e){return async t=>{try{const s=t.page,r=t.params,o=t.url;let n=null;if(s){if(n=E(a,s,r),!n)return{status:"error",error:`Unknown page: "${s}". Available pages: ${a.map(d=>d.name).join(", ")}`}}else if(o)n=o;else return{status:"error",error:'Either "page" or "url" parameter is required'};const u=n.match(/:([a-zA-Z_][a-zA-Z0-9_]*)/g);return u?{status:"error",error:`Missing parameters: ${u.join(", ")}. Please provide values for these parameters.`}:e?(e(n),{status:"success",data:{navigated_to:n,page:s||void 0,method:"spa_router"}}):(window.location.href=n,{status:"success",data:{navigated_to:n,page:s||void 0,method:"full_navigation"}})}catch(s){return{status:"error",error:String(s)}}}}class A{constructor(e,t={}){this.controller=e,this.config={waitTimeout:t.waitTimeout??3e3,pollInterval:t.pollInterval??300,stepDelay:t.stepDelay??500,stopOnFailure:t.stopOnFailure??!1,onStepProgress:t.onStepProgress??(()=>{})}}async execute(e,t={}){const s=[];let r=0;console.log(`[WorkflowExecutor] Starting workflow: ${e.name} (${e.steps.length} steps)`);for(let n=0;n<e.steps.length;n++){const u=e.steps[n],d=this.resolveVariables(u,t);console.log(`[WorkflowExecutor] Step ${n+1}/${e.steps.length}: ${d.description}`);const l=await this.executeStep(d,n);if(s.push(l),this.config.onStepProgress(l),!l.success&&(r++,console.warn(`[WorkflowExecutor] Step ${n+1} failed: ${l.message}`),this.config.stopOnFailure))return{success:!1,workflow_name:e.name,total_steps:e.steps.length,completed_steps:n+1,failed_steps:r,step_results:s,error:`Stopped at step ${n+1}: ${l.message}`};n<e.steps.length-1&&await this.delay(this.config.stepDelay)}const o=r===0;return console.log(`[WorkflowExecutor] Workflow "${e.name}" ${o?"completed successfully":`completed with ${r} failures`}`),{success:o,workflow_name:e.name,total_steps:e.steps.length,completed_steps:e.steps.length,failed_steps:r,step_results:s}}async executeStep(e,t){const s={step_index:t,step_type:e.type,description:e.description,success:!1,message:""};try{if(e.type==="navigation"){if(!e.url)return{...s,message:"Navigation step has no URL"};const o=await this.controller.navigateToUrl(e.url);return await this.delay(1e3),{...s,success:o.success,message:o.message}}await this.controller.updateTree();let r=this.controller.findElementByStrategies(e.selector_strategies);if(r===null&&e.selector_strategies.length>0&&(console.log(`[WorkflowExecutor] Element not found, waiting up to ${this.config.waitTimeout}ms...`),r=await this.controller.waitForElement(e.selector_strategies,this.config.waitTimeout,this.config.pollInterval)),r===null&&e.target_text&&(await this.controller.updateTree(),r=this.controller.findElementByText(e.target_text,!0),r===null&&(r=this.controller.findElementByText(e.target_text,!1))),r===null)return{...s,message:`Element not found for step: ${e.description} (target_text: "${e.target_text}")`};switch(s.element_index=r,e.type){case"click":{const o=await this.controller.clickElement(r);return{...s,success:o.success,message:o.message}}case"input":{if(e.value===void 0||e.value===null)return{...s,message:"Input step has no value"};const o=await this.controller.inputText(r,e.value);return{...s,success:o.success,message:o.message}}case"select":{if(!e.value)return{...s,message:"Select step has no value"};const o=await this.controller.selectOption(r,e.value);return{...s,success:o.success,message:o.message}}case"keypress":{if(!e.value)return{...s,message:"Keypress step has no key"};const o=await this.controller.pressKey(e.value,r);return{...s,success:o.success,message:o.message}}default:return{...s,message:`Unknown step type: ${e.type}`}}}catch(r){return{...s,message:`Error executing step: ${r instanceof Error?r.message:String(r)}`}}}resolveVariables(e,t){const s=r=>!r||!r.includes("{")?r:r.replace(/\{(\w+)\}/g,(o,n)=>n in t?String(t[n]):o);return{...e,description:s(e.description)||e.description,target_text:s(e.target_text)||e.target_text,value:s(e.value),url:s(e.url),selector_strategies:e.selector_strategies.map(r=>({...r,value:s(r.value)||r.value}))}}delay(e){return new Promise(t=>setTimeout(t,e))}}exports.CrowBrowserUse=I.CrowBrowserUse;exports.ConversationManager=k;exports.CrowClient=O;exports.DEFAULT_TOOLS=g;exports.DEFAULT_TOOL_NAMES=b;exports.IdentityManager=_;exports.ToolManager=v;exports.WorkflowExecutor=A;exports.createNavigateToPageTool=R;exports.parseSSEChunk=C;exports.parseSSEData=S;exports.resolveRoute=E;exports.streamResponse=T;
|