@browserbasehq/stagehand 1.0.3-alpha.2 → 1.0.3

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.
@@ -0,0 +1,2 @@
1
+ (() => {
2
+ })();
package/dist/index.d.ts CHANGED
@@ -81,6 +81,9 @@ declare class Stagehand {
81
81
  debugUrl: string;
82
82
  sessionUrl: string;
83
83
  }>;
84
+ initFromPage(page: Page, modelName?: AvailableModel): Promise<{
85
+ context: BrowserContext;
86
+ }>;
84
87
  private pending_logs_to_send_to_browserbase;
85
88
  private is_processing_browserbase_logs;
86
89
  log({ message, category, level, }: {
package/dist/index.js CHANGED
@@ -283,8 +283,10 @@ var metadataSystemPrompt = `You are an AI assistant tasked with evaluating the p
283
283
  Analyze the extraction response and determine if the task is completed or if more information is needed.
284
284
 
285
285
  Strictly abide by the following criteria:
286
- 1. If you are certain that the instruction is completed, set the completion status to true, even if there are still chunks left.
287
- 2. If there could still be more information to extract and there are still chunks left, set the completion status to false.`;
286
+ 1. Once the instruction has been satisfied by the current extraction response, ALWAYS set completion status to true and stop processing, regardless of remaining chunks.
287
+ 2. Only set completion status to false if BOTH of these conditions are true:
288
+ - The instruction has not been satisfied yet
289
+ - There are still chunks left to process (chunksTotal > chunksSeen)`;
288
290
  function buildMetadataSystemPrompt() {
289
291
  return {
290
292
  role: "system",
@@ -296,8 +298,8 @@ function buildMetadataPrompt(instruction, extractionResponse, chunksSeen, chunks
296
298
  role: "user",
297
299
  content: `Instruction: ${instruction}
298
300
  Extracted content: ${JSON.stringify(extractionResponse, null, 2)}
299
- Chunks seen: ${chunksSeen}
300
- Chunks total: ${chunksTotal}`
301
+ chunksSeen: ${chunksSeen}
302
+ chunksTotal: ${chunksTotal}`
301
303
  };
302
304
  }
303
305
  var observeSystemPrompt = `
@@ -768,6 +770,9 @@ var LLMProvider = class {
768
770
  }
769
771
  };
770
772
 
773
+ // lib/index.ts
774
+ var import_path2 = __toESM(require("path"));
775
+
771
776
  // lib/browserbase.ts
772
777
  var Browserbase = class {
773
778
  createSession() {
@@ -1169,11 +1174,44 @@ var Stagehand = class {
1169
1174
  yield this.page.setViewportSize({ width: 1280, height: 720 });
1170
1175
  }
1171
1176
  yield this.page.addInitScript({
1172
- content: '(()=>{var B=Object.defineProperty;var M=Object.getOwnPropertySymbols;var I=Object.prototype.hasOwnProperty,V=Object.prototype.propertyIsEnumerable;var $=(e,t,o)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,x=(e,t)=>{for(var o in t||(t={}))I.call(t,o)&&$(e,o,t[o]);if(M)for(var o of M(t))V.call(t,o)&&$(e,o,t[o]);return e};var d=(e,t,o)=>new Promise((n,s)=>{var c=a=>{try{l(o.next(a))}catch(u){s(u)}},i=a=>{try{l(o.throw(a))}catch(u){s(u)}},l=a=>a.done?n(a.value):Promise.resolve(a.value).then(c,i);l((o=o.apply(e,t)).next())});function _(e){return d(this,null,function*(){let{chunk:t,chunksArray:o}=yield Q(e),{outputString:n,selectorMap:s}=yield C(t);return console.log(`Stagehand (Browser Process): Extracted dom elements:${n}`),{outputString:n,selectorMap:s,chunk:t,chunks:o}})}function F(){return d(this,null,function*(){console.log("Stagehand (Browser Process): Processing all of DOM");let e=window.innerHeight,t=document.documentElement.scrollHeight,o=Math.ceil(t/e),n=0,s=[];for(let l=0;l<o;l++){let a=yield C(l,!0,n);s.push(a),n+=Object.keys(a.selectorMap).length}yield k(0);let c=s.map(l=>l.outputString).join(""),i=s.reduce((l,a)=>x(x({},l),a.selectorMap),{});return console.log(`Stagehand (Browser Process): All dom elements: ${c}`),{outputString:c,selectorMap:i}})}function k(e){return d(this,null,function*(){window.scrollTo({top:e,left:0,behavior:"smooth"}),yield new Promise(t=>{let o,n=()=>{clearTimeout(o),o=window.setTimeout(()=>{window.removeEventListener("scroll",n),t()},200)};window.addEventListener("scroll",n,{passive:!0}),n()})})}function C(e,t=!0,o=0){return d(this,null,function*(){console.time("processElements:total");let s=window.innerHeight*e,c=document.documentElement.scrollHeight-window.innerHeight,i=Math.min(s,c);t&&(console.time("processElements:scroll"),yield k(i),console.timeEnd("processElements:scroll"));let l=[],a=[...document.body.childNodes],u=new Map;for(console.log("Stagehand (Browser Process): Generating candidate elements"),console.time("processElements:findCandidates");a.length>0;){let r=a.pop(),h=!1;if(r&&b(r)){let p=r.childNodes.length;for(let w=p-1;w>=0;w--){let E=r.childNodes[w];a.push(E)}J(r)&&D(r)&&H(r)&&(h=!0),K(r)&&D(r)&&H(r)&&(h=!0)}r&&y(r)&&G(r)&&(h=!0),h&&l.push(r)}console.timeEnd("processElements:findCandidates");let m={},g="";return console.log(`Stagehand (Browser Process): Processing candidate elements: ${l.length}`),console.time("processElements:processCandidates"),l.forEach((r,h)=>{var w,E;let p=u.get(r);if(p||(p=j(r),u.set(r,p)),y(r)){let f=(w=r.textContent)==null?void 0:w.trim();f&&(g+=`${h+o}:${f}`)}else if(b(r)){let f=r.tagName.toLowerCase(),A=X(r),L=`<${f}${A?" "+A:""}>`,P=`</${f}>`,O=((E=r.textContent)==null?void 0:E.trim())||"";g+=`${h+o}:${L}${O}${P}`}m[h+o]=p}),console.timeEnd("processElements:processCandidates"),console.timeEnd("processElements:total"),{outputString:g,selectorMap:m}})}function X(e){let o=["id","class","href","src","aria-label","aria-name","aria-role","aria-description","aria-expanded","aria-haspopup"].map(n=>{let s=e.getAttribute(n);return s?`${n}="${s}"`:""}).filter(n=>n!=="");return Array.from(e.attributes).forEach(n=>{n.name.startsWith("data-")&&o.push(`${n.name}="${n.value}"`)}),o.join(" ")}window.processDom=_;window.processAllOfDom=F;window.processElements=C;window.scrollToHeight=k;function j(e){if(b(e)&&e.id)return`//*[@id="${e.id}"]`;let t=[];for(;e&&(y(e)||b(e));){let o=0,n=!1,s=e.parentElement?Array.from(e.parentElement.childNodes):[];for(let c=0;c<s.length;c++){let i=s[c];if(i.nodeType===e.nodeType&&i.nodeName===e.nodeName&&(o=o+1,n=!0,i.isSameNode(e)))break}if(e.nodeName!=="#text"){let c=e.nodeName.toLowerCase(),i=n?`[${o}]`:"";t.unshift(`${c}${i}`)}e=e.parentElement}return t.length?`/${t.join("/")}`:""}var U=["SVG","IFRAME","SCRIPT","STYLE","LINK"],Y=["A","BUTTON","DETAILS","EMBED","INPUT","LABEL","MENU","MENUITEM","OBJECT","SELECT","TEXTAREA","SUMMARY"],z=["button","menu","menuitem","link","checkbox","radio","slider","tab","tabpanel","textbox","combobox","grid","listbox","option","progressbar","scrollbar","searchbox","switch","tree","treeitem","spinbutton","tooltip"],q=["menu","menuitem","button"];function b(e){return e.nodeType===Node.ELEMENT_NODE}function y(e){var o;let t=(o=e.textContent)==null?void 0:o.trim().replace(/s/g,"");return e.nodeType===Node.TEXT_NODE&&t!==""}var H=e=>{let t=e.getBoundingClientRect();return t.width===0||t.height===0||t.top<0||t.top>window.innerHeight||!R(e,t)?!1:e.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})},G=e=>{let t=document.createRange();t.selectNodeContents(e);let o=t.getBoundingClientRect();if(o.width===0||o.height===0||o.top<0||o.top>window.innerHeight)return!1;let n=e.parentElement;return!n||!R(n,o)?!1:n.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})};function R(e,t){return[{x:t.left+t.width*.25,y:t.top+t.height*.25},{x:t.left+t.width*.75,y:t.top+t.height*.25},{x:t.left+t.width*.25,y:t.top+t.height*.75},{x:t.left+t.width*.75,y:t.top+t.height*.75},{x:t.left+t.width/2,y:t.top+t.height/2}].some(n=>{let c=document.elementFromPoint(n.x,n.y);for(;c&&c!==document.body;){if(c.isSameNode(e))return!0;c=c.parentElement}return!1})}var D=e=>!(e.hasAttribute("disabled")||e.hasAttribute("hidden")||e.getAttribute("aria-disabled")==="true"),J=e=>{let t=e.tagName,o=e.getAttribute("role"),n=e.getAttribute("aria-role");return t&&Y.includes(t)||o&&z.includes(o)||n&&q.includes(n)},K=e=>e.textContent===""?!1:e.childNodes.length===0?!U.includes(e.tagName):!!(e.childNodes.length===1&&y(e.childNodes[0]));function Q(e){return d(this,null,function*(){let t=window.innerHeight,o=document.documentElement.scrollHeight,n=Math.ceil(o/t),s=Array.from({length:n},(u,m)=>m),c=s.filter(u=>!e.includes(u)),i=window.scrollY,a=c.reduce((u,m)=>{let g=t*m,r=t*u;return Math.abs(i-g)<Math.abs(i-r)?m:u},c[0]);if(a===void 0)throw new Error(`No chunks remaining to check: ${c}`);return{chunk:a,chunksArray:s}})}function W(){return d(this,null,function*(){return new Promise(e=>{let t=()=>setTimeout(()=>{e()},2e3),o=t();new MutationObserver(()=>{clearTimeout(o),o=t()}).observe(window.document.body,{childList:!0,subtree:!0})})})}window.waitForDomSettle=W;function Z(){return d(this,null,function*(){window.chunkNumber=0;let{selectorMap:e,outputString:t}=yield window.processElements(window.chunkNumber);T(e),S()})}function T(e){N(),Object.entries(e).forEach(([t,o])=>{let n=document.evaluate(o,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;if(n){let s;if(n.nodeType===Node.ELEMENT_NODE)s=n.getBoundingClientRect();else{let l=document.createRange();l.selectNodeContents(n),s=l.getBoundingClientRect()}let c="grey",i=document.createElement("div");i.style.position="absolute",i.style.left=`${s.left+window.scrollX}px`,i.style.top=`${s.top+window.scrollY}px`,i.style.padding="2px",i.style.width=`${s.width}px`,i.style.height=`${s.height}px`,i.style.backgroundColor=c,i.className="stagehand-marker",i.style.opacity="0.3",i.style.zIndex="1000000000",i.style.border="1px solid",i.style.pointerEvents="none",document.body.appendChild(i)}})}function ee(){return d(this,null,function*(){N(),v()})}function N(){document.querySelectorAll(".stagehand-marker").forEach(t=>{t.remove()})}function v(){document.querySelectorAll(".stagehand-nav").forEach(t=>{t.remove()})}function S(){let e=window.innerHeight,t=document.documentElement.scrollHeight,o=Math.ceil(t/e);if(window.chunkNumber>0){let n=document.createElement("button");n.className="stagehand-nav",n.textContent="Previous",n.style.marginLeft="50px",n.style.position="fixed",n.style.bottom="10px",n.style.left="50%",n.style.transform="translateX(-50%)",n.style.zIndex="1000000000",n.onclick=()=>d(this,null,function*(){N(),v(),window.chunkNumber-=1,window.scrollTo(0,window.chunkNumber*window.innerHeight),yield window.waitForDomSettle();let{selectorMap:s}=yield processElements(window.chunkNumber);T(s),S()}),document.body.appendChild(n)}if(o>window.chunkNumber){let n=document.createElement("button");n.className="stagehand-nav",n.textContent="Next",n.style.marginRight="50px",n.style.position="fixed",n.style.bottom="10px",n.style.right="50%",n.style.transform="translateX(50%)",n.style.zIndex="1000000000",n.onclick=()=>d(this,null,function*(){N(),v(),window.chunkNumber+=1,window.scrollTo(0,window.chunkNumber*window.innerHeight),yield window.waitForDomSettle();let{selectorMap:s}=yield processElements(window.chunkNumber);T(s),S()}),document.body.appendChild(n)}}window.debugDom=Z;window.cleanupDebug=ee;})();'
1177
+ path: import_path2.default.join(__dirname, "..", "dist", "dom", "build", "process.js")
1178
+ });
1179
+ yield this.page.addInitScript({
1180
+ path: import_path2.default.join(__dirname, "..", "dist", "dom", "build", "utils.js")
1181
+ });
1182
+ yield this.page.addInitScript({
1183
+ path: import_path2.default.join(__dirname, "..", "dist", "dom", "build", "debug.js")
1173
1184
  });
1174
1185
  return { debugUrl, sessionUrl };
1175
1186
  });
1176
1187
  }
1188
+ initFromPage(page, modelName) {
1189
+ return __async(this, null, function* () {
1190
+ this.page = page;
1191
+ this.context = page.context();
1192
+ this.defaultModelName = modelName || this.defaultModelName;
1193
+ const originalGoto = this.page.goto.bind(this.page);
1194
+ this.page.goto = (url, options) => __async(this, null, function* () {
1195
+ const result = yield originalGoto(url, options);
1196
+ yield this.page.waitForLoadState("domcontentloaded");
1197
+ yield this._waitForSettledDom();
1198
+ return result;
1199
+ });
1200
+ if (this.headless) {
1201
+ yield this.page.setViewportSize({ width: 1280, height: 720 });
1202
+ }
1203
+ yield this.page.addInitScript({
1204
+ path: import_path2.default.join(__dirname, "..", "dist", "dom", "build", "process.js")
1205
+ });
1206
+ yield this.page.addInitScript({
1207
+ path: import_path2.default.join(__dirname, "..", "dist", "dom", "build", "utils.js")
1208
+ });
1209
+ yield this.page.addInitScript({
1210
+ path: import_path2.default.join(__dirname, "..", "dist", "dom", "build", "debug.js")
1211
+ });
1212
+ return { context: this.context };
1213
+ });
1214
+ }
1177
1215
  log({
1178
1216
  message,
1179
1217
  category,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@browserbasehq/stagehand",
3
- "version": "1.0.3-alpha.2",
3
+ "version": "1.0.3",
4
4
  "description": "An AI web browsing framework focused on simplicity and extensibility.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",