@usecrow/client 0.1.33 → 0.1.35

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/browser.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./browserUse-CAnPpcJX.cjs");e.setPageController(e.PageController);let r=null;function w(){r&&(console.log("[Crow] Stopping active browser-use automation"),r.stop(),r=null)}function a(t,u){return async n=>{const s=n.instruction||n.instruction;if(!s)return{status:"error",error:"Missing instruction parameter for browser_use tool"};const l=window.__crow_browser_callbacks,o=u||l,i=new e.CrowBrowserUse({productId:t.productId,apiUrl:t.apiUrl,onConfirmation:o==null?void 0:o.onConfirmation,onQuestion:o==null?void 0:o.onQuestion,onProgress:o==null?void 0:o.onProgress});r=i;try{return await i.execute(s)}finally{r=null}}}exports.CrowBrowserUse=e.CrowBrowserUse;exports.PageController=e.PageController;exports.createBrowserUseTool=a;exports.stopActiveBrowserUse=w;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("./PageController-BDcmu8Xe.cjs"),e=require("./browserUse-BjeJDX8x.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.js CHANGED
@@ -1,7 +1,8 @@
1
- import { C as a, s as l, P as w } from "./browserUse-DHVE_OuS.js";
2
- l(w);
1
+ import { PageController as l } from "./PageController-BweWYS-Z.js";
2
+ import { C as w, s as a } from "./browserUse-Btg7osSj.js";
3
+ a(l);
3
4
  let r = null;
4
- function p() {
5
+ function m() {
5
6
  r && (console.log("[Crow] Stopping active browser-use automation"), r.stop(), r = null);
6
7
  }
7
8
  function U(n, i) {
@@ -12,7 +13,7 @@ function U(n, i) {
12
13
  status: "error",
13
14
  error: "Missing instruction parameter for browser_use tool"
14
15
  };
15
- const u = window.__crow_browser_callbacks, o = i || u, e = new a({
16
+ const u = window.__crow_browser_callbacks, o = i || u, e = new w({
16
17
  productId: n.productId,
17
18
  apiUrl: n.apiUrl,
18
19
  onConfirmation: o == null ? void 0 : o.onConfirmation,
@@ -28,8 +29,8 @@ function U(n, i) {
28
29
  };
29
30
  }
30
31
  export {
31
- a as CrowBrowserUse,
32
- w as PageController,
32
+ w as CrowBrowserUse,
33
+ l as PageController,
33
34
  U as createBrowserUseTool,
34
- p as stopActiveBrowserUse
35
+ m as stopActiveBrowserUse
35
36
  };
@@ -0,0 +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-BDcmu8Xe.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;
@@ -0,0 +1,235 @@
1
+ let d = null, h = null;
2
+ function B(w) {
3
+ d = w;
4
+ }
5
+ async function _() {
6
+ if (d)
7
+ return d;
8
+ if (!h)
9
+ try {
10
+ h = await import("./PageController-BweWYS-Z.js");
11
+ } catch {
12
+ throw new Error(
13
+ 'PageController not available. Either import from "@usecrow/client/browser" or use the bundled version.'
14
+ );
15
+ }
16
+ return h.PageController;
17
+ }
18
+ class T {
19
+ constructor(e) {
20
+ this.pageController = null, this.sessionId = null, this.maxSteps = 20, this.aborted = !1, this.config = e;
21
+ }
22
+ /**
23
+ * Initialize PageController with non-blocking pointer
24
+ */
25
+ async initPageController() {
26
+ if (this.pageController)
27
+ return this.pageController;
28
+ try {
29
+ const e = await _();
30
+ this.pageController = new e({
31
+ enableMask: !0,
32
+ viewportExpansion: 500,
33
+ highlightLabelOpacity: 0,
34
+ // Hide numbered labels from users
35
+ highlightOpacity: 0
36
+ // Hide highlight boxes from users
37
+ }), await this.pageController.showMask();
38
+ const s = this.pageController.mask;
39
+ return s != null && s.wrapper && (s.wrapper.style.pointerEvents = "none"), console.log("[CrowBrowserUse] PageController initialized with non-blocking pointer"), this.pageController;
40
+ } catch (e) {
41
+ throw console.error("[CrowBrowserUse] Failed to initialize PageController:", e), new Error(
42
+ "Failed to initialize browser automation. Please import from @usecrow/client/browser."
43
+ );
44
+ }
45
+ }
46
+ /**
47
+ * Execute a browser automation task
48
+ */
49
+ async execute(e) {
50
+ var s, n, r, o, c, g, f, m, C, y, x, U, b, S;
51
+ if (console.log("[CrowBrowserUse] Starting task:", e), this.config.onConfirmation && !await this.config.onConfirmation(e))
52
+ return console.log("[CrowBrowserUse] User declined browser automation"), (n = (s = this.config).onProgress) == null || n.call(s, -1, this.maxSteps), {
53
+ status: "error",
54
+ error: "User declined browser automation",
55
+ data: { declined: !0 }
56
+ };
57
+ try {
58
+ const i = await this.initPageController(), P = await this.startSession(e);
59
+ this.sessionId = P.session_id, this.maxSteps = P.max_steps, console.log("[CrowBrowserUse] Session started:", this.sessionId);
60
+ let l = 0, a;
61
+ for (; l < this.maxSteps; ) {
62
+ if (this.aborted)
63
+ return console.log("[CrowBrowserUse] Task cancelled by user"), await this.cleanup(), (o = (r = this.config).onProgress) == null || o.call(r, -1, this.maxSteps), {
64
+ status: "error",
65
+ error: "Task cancelled by user"
66
+ };
67
+ l++;
68
+ const k = await i.getBrowserState(), u = i.mask;
69
+ u != null && u.wrapper && (u.wrapper.style.pointerEvents = "none");
70
+ const t = await this.processStep(k, a);
71
+ if (t.needs_user_input && t.question) {
72
+ if (console.log("[CrowBrowserUse] Asking user:", t.question), !this.config.onQuestion) {
73
+ a = "User input not available - no callback provided", console.warn("[CrowBrowserUse] No onQuestion callback provided");
74
+ continue;
75
+ }
76
+ try {
77
+ const p = await this.config.onQuestion(t.question);
78
+ a = `User answered: ${p}`, console.log("[CrowBrowserUse] User answered:", p);
79
+ } catch (p) {
80
+ if (a = "User cancelled or failed to respond", console.log("[CrowBrowserUse] User cancelled or error:", p), this.aborted)
81
+ return console.log("[CrowBrowserUse] Aborted after user cancelled"), await this.cleanup(), (g = (c = this.config).onProgress) == null || g.call(c, -1, this.maxSteps), {
82
+ status: "error",
83
+ error: "Task cancelled by user"
84
+ };
85
+ }
86
+ continue;
87
+ }
88
+ if (t.done)
89
+ return console.log("[CrowBrowserUse] Task completed:", t.message), await this.cleanup(), (m = (f = this.config).onProgress) == null || m.call(f, l, this.maxSteps), {
90
+ status: t.success ? "success" : "error",
91
+ data: {
92
+ message: t.message,
93
+ steps: l
94
+ },
95
+ error: t.success ? void 0 : t.message
96
+ };
97
+ if (t.error)
98
+ return console.error("[CrowBrowserUse] Error:", t.error), await this.cleanup(), (y = (C = this.config).onProgress) == null || y.call(C, -1, this.maxSteps), {
99
+ status: "error",
100
+ error: t.error
101
+ };
102
+ 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);
103
+ }
104
+ return await this.cleanup(), (U = (x = this.config).onProgress) == null || U.call(x, -1, this.maxSteps), {
105
+ status: "error",
106
+ error: `Task incomplete after ${this.maxSteps} steps`
107
+ };
108
+ } catch (i) {
109
+ return console.error("[CrowBrowserUse] Error:", i), await this.cleanup(), (S = (b = this.config).onProgress) == null || S.call(b, -1, this.maxSteps), {
110
+ status: "error",
111
+ error: i instanceof Error ? i.message : String(i)
112
+ };
113
+ }
114
+ }
115
+ /**
116
+ * Start a browser-use session on the server
117
+ */
118
+ async startSession(e) {
119
+ const s = await fetch(`${this.config.apiUrl}/api/browser-use/start`, {
120
+ method: "POST",
121
+ headers: { "Content-Type": "application/json" },
122
+ body: JSON.stringify({
123
+ product_id: this.config.productId,
124
+ task: e
125
+ })
126
+ });
127
+ if (!s.ok) {
128
+ const n = await s.json().catch(() => ({ detail: "Unknown error" }));
129
+ throw new Error(n.detail || `Failed to start session: ${s.status}`);
130
+ }
131
+ return s.json();
132
+ }
133
+ /**
134
+ * Process a step on the server
135
+ */
136
+ async processStep(e, s) {
137
+ const n = await fetch(`${this.config.apiUrl}/api/browser-use/step`, {
138
+ method: "POST",
139
+ headers: { "Content-Type": "application/json" },
140
+ body: JSON.stringify({
141
+ session_id: this.sessionId,
142
+ product_id: this.config.productId,
143
+ browser_state: e,
144
+ action_result: s
145
+ })
146
+ });
147
+ if (!n.ok) {
148
+ const r = await n.json().catch(() => ({ detail: "Unknown error" }));
149
+ throw new Error(r.detail || `Failed to process step: ${n.status}`);
150
+ }
151
+ return n.json();
152
+ }
153
+ /**
154
+ * Execute an action using PageController
155
+ */
156
+ async executeAction(e, s) {
157
+ const n = Object.keys(s)[0], r = s[n];
158
+ try {
159
+ switch (n) {
160
+ case "click_element_by_index":
161
+ return (await e.clickElement(r.index)).message;
162
+ case "input_text":
163
+ return (await e.inputText(
164
+ r.index,
165
+ r.text
166
+ )).message;
167
+ case "select_dropdown_option":
168
+ return (await e.selectOption(
169
+ r.index,
170
+ r.text
171
+ )).message;
172
+ case "scroll":
173
+ return (await e.scroll({
174
+ down: r.down,
175
+ numPages: r.num_pages,
176
+ pixels: r.pixels,
177
+ index: r.index
178
+ })).message;
179
+ case "scroll_horizontally":
180
+ return (await e.scrollHorizontally({
181
+ right: r.right,
182
+ pixels: r.pixels,
183
+ index: r.index
184
+ })).message;
185
+ case "wait": {
186
+ const o = r.seconds || 1;
187
+ return await new Promise((c) => setTimeout(c, o * 1e3)), `Waited ${o} seconds`;
188
+ }
189
+ case "done":
190
+ return "Task completed";
191
+ default:
192
+ return `Unknown action: ${n}`;
193
+ }
194
+ } catch (o) {
195
+ return `Action failed: ${o instanceof Error ? o.message : String(o)}`;
196
+ }
197
+ }
198
+ /**
199
+ * Cleanup resources
200
+ */
201
+ async cleanup() {
202
+ if (this.pageController) {
203
+ try {
204
+ await this.pageController.hideMask(), await this.pageController.cleanUpHighlights(), this.pageController.dispose();
205
+ } catch (e) {
206
+ console.warn("[CrowBrowserUse] Cleanup error:", e);
207
+ }
208
+ this.pageController = null;
209
+ }
210
+ if (this.sessionId) {
211
+ try {
212
+ await fetch(`${this.config.apiUrl}/api/browser-use/end`, {
213
+ method: "POST",
214
+ headers: { "Content-Type": "application/json" },
215
+ body: JSON.stringify({
216
+ session_id: this.sessionId,
217
+ product_id: this.config.productId
218
+ })
219
+ });
220
+ } catch {
221
+ }
222
+ this.sessionId = null;
223
+ }
224
+ }
225
+ /**
226
+ * Stop the current task
227
+ */
228
+ async stop() {
229
+ this.aborted = !0, await this.cleanup();
230
+ }
231
+ }
232
+ export {
233
+ T as C,
234
+ B as s
235
+ };
package/dist/index.cjs CHANGED
@@ -1,7 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("./browserUse-CAnPpcJX.cjs");class k{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 C{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 n=r instanceof Error?r.message:String(r);return console.error(`[Crow] Tool ${e} failed:`,r),{status:"error",error:n}}}}const $="crow_conv_";class v{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(o){if(o==="[DONE]")return{type:"done"};try{const e=JSON.parse(o);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,arguments:e.arguments||{}};case"tool_call_complete":return{type:"tool_call_complete",toolName:e.tool_name,success:e.success};case"client_tool_call":return{type:"client_tool_call",toolName:e.tool_name,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:",o),null}}function*b(o){const e=o.split(`
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=S(u);if(l&&(l.type==="content"?(r+=l.text,yield{...l,accumulated:r}):yield l,l.type==="done"))return}}}finally{t.releaseLock()}}const g={refreshPage:async()=>{try{return window.location.reload(),{status:"success",data:{message:"Page refresh initiated"}}}catch(o){return{status:"error",error:String(o)}}},whatsOnScreen:async()=>{try{const o=new _.PageController({viewportExpansion:500}),e=await o.getBrowserState();return o.dispose(),{status:"success",data:{url:e.url,title:e.title,content:`${e.header}
4
-
5
- ${e.content}
6
-
7
- ${e.footer}`}}}catch(o){return console.error("[Crow] whatsOnScreen error:",o),{status:"error",error:String(o)}}}},T=Object.keys(g),E="https://api.usecrow.org",L="claude-sonnet-4-20250514";class U{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||E,model:e.model||L},this.identity=new k,this.tools=new C,this.conversations=new v(this.config.productId,this.config.apiUrl),this.tools.register(g),console.log("[Crow] Default tools registered:",T.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 I(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 O(o,e){return async t=>{try{const s=t.page,r=t.params,n=t.url;let i=null;if(s){if(i=I(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=_.CrowBrowserUse;exports.ConversationManager=v;exports.CrowClient=U;exports.DEFAULT_TOOLS=g;exports.DEFAULT_TOOL_NAMES=T;exports.IdentityManager=k;exports.ToolManager=C;exports.createNavigateToPageTool=O;exports.parseSSEChunk=b;exports.parseSSEData=S;exports.resolveRoute=I;exports.streamResponse=M;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("./browserUse-BjeJDX8x.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 k{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 n=r instanceof Error?r.message:String(r);return console.error(`[Crow] Tool ${e} failed:`,r),{status:"error",error:n}}}}const E="crow_conv_";class v{constructor(e,t){this.currentId=null,this.productId=e,this.apiUrl=t,this.currentId=this.loadFromStorage()}getStorageKey(){return`${E}${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 C(o){if(o==="[DONE]")return{type:"done"};try{const e=JSON.parse(o);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:",o),null}}function*b(o){const e=o.split(`
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;
package/dist/index.d.ts CHANGED
@@ -313,19 +313,7 @@ export declare interface CrowEventCallbacks {
313
313
 
314
314
  export declare const DEFAULT_TOOL_NAMES: DefaultToolName[];
315
315
 
316
- /**
317
- * SDK Default Tools - automatically registered, zero configuration
318
- */
319
- export declare const DEFAULT_TOOLS: {
320
- /**
321
- * Refresh the current page in the user's browser
322
- */
323
- readonly refreshPage: () => Promise<ToolResult>;
324
- /**
325
- * Capture what's on the user's screen (DOM snapshot)
326
- */
327
- readonly whatsOnScreen: () => Promise<ToolResult>;
328
- };
316
+ export declare const DEFAULT_TOOLS: ToolHandlers;
329
317
 
330
318
  export declare type DefaultToolName = keyof typeof DEFAULT_TOOLS;
331
319
 
@@ -438,14 +426,17 @@ export declare type StreamEvent = {
438
426
  } | {
439
427
  type: 'tool_call_start';
440
428
  toolName: string;
429
+ displayName?: string;
441
430
  arguments: Record<string, unknown>;
442
431
  } | {
443
432
  type: 'tool_call_complete';
444
433
  toolName: string;
434
+ displayName?: string;
445
435
  success: boolean;
446
436
  } | {
447
437
  type: 'client_tool_call';
448
438
  toolName: string;
439
+ displayName?: string;
449
440
  arguments: Record<string, unknown>;
450
441
  } | {
451
442
  type: 'workflow_started';
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
- import { P as _ } from "./browserUse-DHVE_OuS.js";
2
- import { C as R } from "./browserUse-DHVE_OuS.js";
3
- class k {
1
+ import { C as R } from "./browserUse-Btg7osSj.js";
2
+ class _ {
4
3
  constructor() {
5
4
  this.state = {
6
5
  token: null,
@@ -72,7 +71,7 @@ class k {
72
71
  t(e);
73
72
  }
74
73
  }
75
- class C {
74
+ class k {
76
75
  constructor() {
77
76
  this.handlers = {};
78
77
  }
@@ -125,7 +124,7 @@ class C {
125
124
  }
126
125
  }
127
126
  const v = "crow_conv_";
128
- class b {
127
+ class C {
129
128
  constructor(e, t) {
130
129
  this.currentId = null, this.productId = e, this.apiUrl = t, this.currentId = this.loadFromStorage();
131
130
  }
@@ -270,7 +269,7 @@ class b {
270
269
  return e;
271
270
  }
272
271
  }
273
- function S(o) {
272
+ function b(o) {
274
273
  if (o === "[DONE]")
275
274
  return { type: "done" };
276
275
  try {
@@ -314,18 +313,21 @@ function S(o) {
314
313
  return {
315
314
  type: "tool_call_start",
316
315
  toolName: e.tool_name,
316
+ displayName: e.display_name || void 0,
317
317
  arguments: e.arguments || {}
318
318
  };
319
319
  case "tool_call_complete":
320
320
  return {
321
321
  type: "tool_call_complete",
322
322
  toolName: e.tool_name,
323
+ displayName: e.display_name || void 0,
323
324
  success: e.success
324
325
  };
325
326
  case "client_tool_call":
326
327
  return {
327
328
  type: "client_tool_call",
328
329
  toolName: e.tool_name,
330
+ displayName: e.display_name || void 0,
329
331
  arguments: e.arguments || {}
330
332
  };
331
333
  case "workflow_started":
@@ -374,7 +376,7 @@ async function* M(o, e) {
374
376
  if (i) break;
375
377
  const h = s.decode(d);
376
378
  for (const u of I(h)) {
377
- const l = S(u);
379
+ const l = b(u);
378
380
  if (l && (l.type === "content" ? (r += l.text, yield { ...l, accumulated: r }) : yield l, l.type === "done"))
379
381
  return;
380
382
  }
@@ -383,50 +385,50 @@ async function* M(o, e) {
383
385
  t.releaseLock();
384
386
  }
385
387
  }
386
- const w = {
387
- /**
388
- * Refresh the current page in the user's browser
389
- */
390
- refreshPage: async () => {
391
- try {
392
- return window.location.reload(), { status: "success", data: { message: "Page refresh initiated" } };
393
- } catch (o) {
394
- return { status: "error", error: String(o) };
395
- }
396
- },
397
- /**
398
- * Capture what's on the user's screen (DOM snapshot)
399
- */
400
- whatsOnScreen: async () => {
401
- try {
402
- const o = new _({ viewportExpansion: 500 }), e = await o.getBrowserState();
403
- return o.dispose(), {
404
- status: "success",
405
- data: {
406
- url: e.url,
407
- title: e.title,
408
- content: `${e.header}
409
-
410
- ${e.content}
411
-
412
- ${e.footer}`
413
- }
414
- };
415
- } catch (o) {
416
- return console.error("[Crow] whatsOnScreen error:", o), { status: "error", error: String(o) };
417
- }
388
+ async function S() {
389
+ try {
390
+ return window.location.reload(), { status: "success", data: { refreshed: !0 } };
391
+ } catch (o) {
392
+ return {
393
+ status: "error",
394
+ error: o instanceof Error ? o.message : "Failed to refresh page"
395
+ };
418
396
  }
419
- }, T = Object.keys(w), $ = "https://api.usecrow.org", E = "claude-sonnet-4-20250514";
397
+ }
398
+ async function T() {
399
+ var o;
400
+ try {
401
+ 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();
402
+ return {
403
+ status: "success",
404
+ data: {
405
+ title: e,
406
+ url: t,
407
+ pathname: s,
408
+ visibleText: r
409
+ }
410
+ };
411
+ } catch (e) {
412
+ return {
413
+ status: "error",
414
+ error: e instanceof Error ? e.message : "Failed to read screen"
415
+ };
416
+ }
417
+ }
418
+ const w = {
419
+ refreshPage: S,
420
+ whatsOnScreen: T
421
+ }, $ = Object.keys(w), E = "https://api.usecrow.org", L = "claude-sonnet-4-20250514";
420
422
  class x {
421
423
  constructor(e) {
422
424
  this.context = {}, this.abortController = null, this.callbacks = {}, this._messages = [], this.messageListeners = /* @__PURE__ */ new Set(), this._isLoading = !1, this.loadingListeners = /* @__PURE__ */ new Set(), this.config = {
423
425
  productId: e.productId,
424
- apiUrl: e.apiUrl || $,
425
- model: e.model || E
426
- }, this.identity = new k(), this.tools = new C(), this.conversations = new b(
426
+ apiUrl: e.apiUrl || E,
427
+ model: e.model || L
428
+ }, this.identity = new _(), this.tools = new k(), this.conversations = new C(
427
429
  this.config.productId,
428
430
  this.config.apiUrl
429
- ), this.tools.register(w), console.log("[Crow] Default tools registered:", T.join(", ")), this.identity.subscribe((t) => {
431
+ ), this.tools.register(w), console.log("[Crow] Default tools registered:", $.join(", ")), this.identity.subscribe((t) => {
430
432
  var s, r;
431
433
  (r = (s = this.callbacks).onVerificationStatus) == null || r.call(s, t.isVerified);
432
434
  });
@@ -745,7 +747,7 @@ class x {
745
747
  this.stop(), this.messageListeners.clear(), this.loadingListeners.clear();
746
748
  }
747
749
  }
748
- function L(o, e, t) {
750
+ function U(o, e, t) {
749
751
  const s = o.find(
750
752
  (n) => n.name.toLowerCase() === e.toLowerCase()
751
753
  );
@@ -762,7 +764,7 @@ function O(o, e) {
762
764
  const s = t.page, r = t.params, n = t.url;
763
765
  let i = null;
764
766
  if (s) {
765
- if (i = L(o, s, r), !i)
767
+ if (i = U(o, s, r), !i)
766
768
  return {
767
769
  status: "error",
768
770
  error: `Unknown page: "${s}". Available pages: ${o.map((h) => h.name).join(", ")}`
@@ -802,16 +804,16 @@ function O(o, e) {
802
804
  };
803
805
  }
804
806
  export {
805
- b as ConversationManager,
807
+ C as ConversationManager,
806
808
  R as CrowBrowserUse,
807
809
  x as CrowClient,
808
810
  w as DEFAULT_TOOLS,
809
- T as DEFAULT_TOOL_NAMES,
810
- k as IdentityManager,
811
- C as ToolManager,
811
+ $ as DEFAULT_TOOL_NAMES,
812
+ _ as IdentityManager,
813
+ k as ToolManager,
812
814
  O as createNavigateToPageTool,
813
815
  I as parseSSEChunk,
814
- S as parseSSEData,
815
- L as resolveRoute,
816
+ b as parseSSEData,
817
+ U as resolveRoute,
816
818
  M as streamResponse
817
819
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usecrow/client",
3
- "version": "0.1.33",
3
+ "version": "0.1.35",
4
4
  "description": "Headless client for Crow AI agents - streaming, auth, tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",