@beyondwork/wb-cli 0.1.51 → 0.1.55
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/CHANGELOG.md +23 -0
- package/out/cli.js +342 -176
- package/out/extension.js +85 -85
- package/out/headless-host.js +4 -4
- package/package.json +1 -1
- package/wb-cli/skills/bw-workblock/SKILL.md +17 -8
- package/wb-cli/skills/bw-workblock/references/browser-validation.md +8 -8
package/out/headless-host.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(){var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function t(t){return typeof t==`string`&&e.test(t)}function n(e){return typeof e==`string`&&e.startsWith(`::bw:data:`)}function r(e){return t(e)?{task_id:e}:{task_name:e}}function i(e,t){return{...r(e.taskName),workblock_id:t.workblockId,module_id:t.moduleId,inputs:e.inputArgs,commit_ref:t.commitRef,data_environment_id:t.dataEnvironmentId}}function a(e,t){return{...r(e.taskName),run_id:t.runId,inputs:e.inputArgs,ui_task_run_id:t.uiTaskRunId}}async function o(e,t){let r={...e};return await Promise.all(Object.entries(r).map(async([e,i])=>{n(i)?r[e]=await t(i):typeof i==`string`&&i.startsWith(`$$$::bw:data:`)&&(r[e]=i.substring(3))})),r}function s(e,t,n){let r=new Set,i=!1;return{mountWidget:async(a,o)=>{if(i)throw Error(`Chat is unmounted`);if(!(a instanceof HTMLElement))throw Error(`Chat widget needs an element`);let s=crypto.randomUUID(),c=document.createElement(`iframe`),l=new MessageChannel,u=!1,d=!1,f=0,p,m=(e,t)=>{u||!d||l.port1.postMessage({requestId:++f,payload:{type:`ON_EVENT`,event:e,data:t}})},h=n(`__embedded_chat_widget__${s}`,e=>{!e||typeof e!=`object`||!(`event`in e)||!(`data`in e)||(e.event===`chat_ui_state`&&(p=e.data),(e.event===`chat_ui_state`||e.event===`chat_ui_submit_failed`)&&m(e.event,e.data))}),g=()=>{u||d||(d=!0,c.contentWindow?.postMessage({type:`INIT_CHANNEL`,initialRoute:`/`},`*`,[l.port2]))},_=async()=>{u||(u=!0,r.delete(_),h(),c.removeEventListener(`load`,g),l.port1.onmessage=null,l.port1.close(),l.port2.close(),c.remove(),await e({type:`UNMOUNT_CHAT_WIDGET`,mountId:t,widgetMountId:s}))};r.add(_),l.port1.onmessage=async n=>{if(u||!n.data||`replyTo`in n.data)return;let{requestId:r,payload:i}=n.data;if(!(!Number.isFinite(r)||!i||typeof i.type!=`string`))try{i.type===`REPORT_HEIGHT`&&Number.isFinite(i.height)&&(c.style.height=`${Math.max(32,Math.min(i.height,2e3))}px`,p&&m(`chat_ui_state`,p));let n=await e({type:`CHAT_WIDGET_REQUEST`,mountId:t,widgetMountId:s,request:i});if(u)return;if(n.type!==`CHAT_WIDGET_RESPONSE`)throw Error(`Unexpected chat widget response`);l.port1.postMessage({replyTo:r,payload:n.response}),i.type===`CONSOLE_LOG`&&i.level===`fatal`&&a.dispatchEvent(new CustomEvent(`bw:widget-error`,{detail:Error(i.message)}))}catch(e){if(u)return;l.port1.postMessage({replyTo:r,payload:{type:`ERROR`,message:e instanceof Error?e.message:`Chat widget request failed`}})}};try{let n=await e({type:`PREPARE_CHAT_WIDGET`,mountId:t,widgetMountId:s,...o});if(u||i)throw Error(`Chat widget was unmounted`);if(n.type!==`PREPARE_CHAT_WIDGET_RESPONSE`)throw Error(`Unexpected chat widget response`);n.submitted&&(p={submitted:!0,submission:n.submission}),c.title=n.title;let r=new Set([`allow-scripts`,`allow-forms`,`allow-popups`,`allow-popups-to-escape-sandbox`,`allow-downloads`]);return c.setAttribute(`sandbox`,n.sandbox.split(/\s+/).filter(e=>r.has(e)).join(` `)),c.referrerPolicy=`no-referrer`,c.style.cssText=`width:100%;height:80px;border:0;display:block;`,c.addEventListener(`load`,g,{once:!0}),c.srcdoc=n.srcDoc,a.appendChild(c),{unmount:_}}catch(e){throw await _().catch(()=>{}),e}},clear:()=>{i=!0;for(let e of r)e().catch(()=>{})}}}function c(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}function l(e){let t=null,n=0,r=[],i=null,a=null,o={},s={},c,l=new Map,u=new Map,d=new Map,f=new Map,p=0,m=`/`,h=null,g=null,_=[],v=new Map;function y(e){return(e??``).replace(/\s+/g,` `).trim()}function b(e,t){return y(e).toLowerCase().includes(y(t).toLowerCase())}function x(e){let t=globalThis.CSS;return t?.escape?t.escape(e):e.replace(/["\\]/g,`\\$&`)}function S(e){let t=[];return(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&t.push(...Array.from(e.labels??[]).map(e=>y(e.textContent))),e.id&&t.push(...Array.from(document.querySelectorAll(`label[for="${x(e.id)}"]`)).map(e=>y(e.textContent))),t.filter(Boolean)}function C(e){return e.split(/\s+/).map(e=>document.getElementById(e)?.textContent).map(y).filter(Boolean).join(` `)}function w(e){let t=e.tagName.toLowerCase();if(t===`button`)return`button`;if(t===`a`&&e.hasAttribute(`href`))return`link`;if(t===`textarea`)return`textbox`;if(t===`select`)return`combobox`;if(t===`form`)return`form`;if(t===`img`)return`img`;if(/^h[1-6]$/.test(t))return`heading`;if(t===`ul`||t===`ol`)return`list`;if(t===`li`)return`listitem`;if(t===`table`)return`table`;if(t===`tr`)return`row`;if(t===`td`||t===`th`)return`cell`;if(t!==`input`)return null;let n=(e.type||`text`).toLowerCase();return n===`checkbox`?`checkbox`:n===`radio`?`radio`:[`button`,`submit`,`reset`].includes(n)?`button`:n===`range`?`slider`:`textbox`}function T(e){return e.getAttribute(`role`)?.split(/\s+/)[0]||w(e)}function E(e){let t=e.getAttribute(`aria-label`);if(t)return y(t);let n=e.getAttribute(`aria-labelledby`);if(n)return C(n);let r=S(e);return r.length>0?r.join(` `):e instanceof HTMLInputElement&&[`button`,`submit`,`reset`].includes(e.type)?y(e.value):e instanceof HTMLImageElement?y(e.alt):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?y(e.placeholder):y(e.getAttribute(`title`)||e.textContent)}function D(){return Array.from(document.body.querySelectorAll(`*`))}function O(e,t){let n=e.toLowerCase();return D().filter(e=>T(e)?.toLowerCase()===n?!t||b(E(e),t):!1)}function k(e){return D().filter(t=>S(t).some(t=>b(t,e))?!0:b(t.getAttribute(`aria-label`),e))}function A(e){return D().filter(t=>t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?b(t.placeholder,e):!1)}function j(e){return D().filter(t=>b(t.textContent,e)?!Array.from(t.children).some(t=>b(t.textContent,e)):!1)}function M(e){return e.length===0?null:e.length===1?e[0]:e.find(e=>F(e))??e[0]}async function N(e){return e.selector?document.querySelector(e.selector):e.testid?M(Array.from(document.querySelectorAll(`[data-testid="${x(e.testid)}"]`))):e.role?M(O(e.role,e.name)):e.label?M(k(e.label)):e.placeholder?M(A(e.placeholder)):e.text?M(j(e.text)):null}function P(e){return e.selector?`selector "${e.selector}"`:e.testid?`testid "${e.testid}"`:e.role&&e.name?`role "${e.role}" with name "${e.name}"`:e.role?`role "${e.role}"`:e.label?`label "${e.label}"`:e.placeholder?`placeholder "${e.placeholder}"`:e.text?`text "${e.text}"`:`empty query`}function F(e){let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0}async function I(e){let t=await N(e);if(!t)return null;let n=t.getBoundingClientRect(),r={};for(let e of t.attributes)r[e.name]=e.value;return{exists:!0,visible:F(t),text:t.textContent?.trim()||``,value:t.value,attributes:r,rect:{x:n.x,y:n.y,width:n.width,height:n.height},tagName:t.tagName.toLowerCase()}}async function L(e){let t=await N(e);return t?t instanceof HTMLElement?(t.click(),{success:!0}):{success:!1,error:`Element is not clickable: ${P(e)}`}:{success:!1,error:`Element not found: ${P(e)}`}}function R(e,t){let n=e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(n,`value`)?.set;r?r.call(e,t):e.value=t}async function z(e,t,n,r){let i=await N(e);return i?i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?(i.focus(),R(i,n?t:i.value+t),i.dispatchEvent(new Event(`input`,{bubbles:!0})),i.dispatchEvent(new Event(`change`,{bubbles:!0})),r&&(i.dispatchEvent(new KeyboardEvent(`keydown`,{key:`Enter`,code:`Enter`,bubbles:!0})),i.dispatchEvent(new KeyboardEvent(`keypress`,{key:`Enter`,code:`Enter`,bubbles:!0})),i.dispatchEvent(new KeyboardEvent(`keyup`,{key:`Enter`,code:`Enter`,bubbles:!0}))),{success:!0}):{success:!1,error:`Element is not an input: ${P(e)}`}:{success:!1,error:`Element not found: ${P(e)}`}}async function B(e,t){let n=e?await N(e):document.activeElement;if(!(n instanceof HTMLElement))return{success:!1,error:e?`Element not found: ${P(e)}`:`No active element`};n.focus();for(let e of[`keydown`,`keypress`,`keyup`])n.dispatchEvent(new KeyboardEvent(e,{key:t,code:t,bubbles:!0,cancelable:!0}));return{success:!0}}async function V(e,t,n){let r=e?await N(e):document.scrollingElement;return r instanceof Element?(r.scrollBy({left:t,top:n,behavior:`auto`}),r.dispatchEvent(new Event(`scroll`,{bubbles:!0})),{success:!0}):{success:!1,error:e?`Element not found: ${P(e)}`:`No scrolling element`}}async function ee(e,t,n=5e3){let r=Date.now(),i=async()=>{let n=await N(e);switch(t){case`attached`:return n!==null;case`detached`:return n===null;case`visible`:return n!==null&&F(n);case`hidden`:return n===null||!F(n)}};return new Promise(a=>{let o=async()=>{if(await i()){a({success:!0});return}if(Date.now()-r>=n){a({success:!1,error:`Timeout waiting for element ${P(e)} to be ${t}`});return}requestAnimationFrame(o)};o()})}let H=null,U=null;async function te(){return H||U||(U=new Promise((e,t)=>{let n=document.createElement(`script`);n.src=`https://unpkg.com/html-to-image@1.11.13/dist/html-to-image.js`,n.onload=()=>{H=window.htmlToImage,H?e(H):t(Error(`html-to-image not found on window`))},n.onerror=()=>t(Error(`Failed to load html-to-image`)),document.head.appendChild(n)}),U)}async function ne(e){let t=document.body.style.width,n=document.documentElement.style.width,r=document.documentElement.style.overflow;e&&(document.documentElement.style.width=`${e}px`,document.body.style.width=`${e}px`,document.documentElement.style.overflow=`hidden`,document.body.offsetHeight,await new Promise(e=>requestAnimationFrame(e)));try{let e=await(await te()).toPng(document.body,{backgroundColor:`#ffffff`,pixelRatio:1});return e.startsWith(`data:image/png;base64,`)?e.split(`,`)[1]:e}catch(e){return console.error(`Error capturing screenshot:`,e),``}finally{e&&(document.body.style.width=t,document.documentElement.style.width=n,document.documentElement.style.overflow=r)}}function W(e){if(e.id)return`#${e.id}`;let t=e.getAttribute(`data-testid`);if(t)return`[data-testid="${t}"]`;let n=[e.tagName.toLowerCase()],r=e.getAttribute(`role`);r&&n.push(`[role="${r}"]`);let i=e.getAttribute(`type`);i&&n.push(`[type="${i}"]`);let a=e.getAttribute(`name`);a&&n.push(`[name="${a}"]`);let o=Array.from(e.classList).find(e=>!e.startsWith(`_`)&&e.length<30);o&&n.push(`.${o}`);let s=n.join(``);if(document.querySelectorAll(s).length===1)return s;let c=e.parentElement;return c?`${s}:nth-of-type(${Array.from(c.children).filter(t=>t.tagName===e.tagName).indexOf(e)+1})`:s}function re(){let e=[];document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`).forEach(t=>{let n=E(t)||t.value||``;e.push({text:n,selector:W(t),disabled:t.disabled||t.getAttribute(`aria-disabled`)===`true`})});let t=[];document.querySelectorAll(`input, textarea, select`).forEach(e=>{let n=e;t.push({selector:W(e),type:n.type||e.tagName.toLowerCase(),name:n.name||E(e)||void 0,value:n.value||void 0})});let n=[];document.querySelectorAll(`form`).forEach(e=>{n.push({id:e.id||void 0,name:e.name||void 0,inputCount:e.querySelectorAll(`input, textarea, select`).length})});let r=[];return document.querySelectorAll(`a[href]`).forEach(e=>{r.push({text:E(e)||``,href:e.href})}),{title:document.title,url:window.location.href,forms:n,buttons:e,inputs:t,links:r}}function ie(e){let t=e.data;`replyTo`in t?oe(t):ae(t)}async function ae(e){if(!t)throw Error(`Communication channel not initialized, but since we received a message, this should not happen`);switch(e.payload.type){case`GET_DATA`:{let n={status:`OK`};if($.onGetData)try{let e=await $.onGetData();if($._usingSetSubmitHandler)n={status:`OK`,data:e};else{if(!e||typeof e!=`object`||!(`status`in e))throw Error(`Unexpected result shape returned by bw.onGetData callback. Expected { status: "OK" | "ERROR", data?: any, error?: string }`);n=e}}catch(e){if($._usingSetSubmitHandler)n={status:`ERROR`,error:e instanceof Error?e.message:`Unknown error`};else throw e}let r={type:`GET_DATA_RESPONSE`,data:n};t.postMessage({replyTo:e.requestId,payload:r});break}case`ON_ACTION`:{let n=e.payload.key,i=r[parseInt(n,10)];if(typeof i.execute!=`string`)try{i.execute()}catch(e){console.error(`Error in action handler:`,e)}t.postMessage({replyTo:e.requestId,payload:{type:`ACK`}});break}case`ON_EVENT`:{e.payload.event===`chat_ui_state`&&(c={data:e.payload.data});let n=o[e.payload.event];if(n)try{n(e.payload.data)}catch(e){console.error(`Error in event handler:`,e)}t.postMessage({replyTo:e.requestId,payload:{type:`ACK`}});break}case`TEST_QUERY_ELEMENT`:{let n=await I(e.payload.query);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_QUERY_ELEMENT_RESPONSE`,result:n}});break}case`TEST_CLICK_ELEMENT`:{let n=await L(e.payload.query);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_CLICK_ELEMENT_RESPONSE`,...n}});break}case`TEST_TYPE_INTO_ELEMENT`:{let n=await z(e.payload.query,e.payload.text,e.payload.clear,e.payload.pressEnter);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_TYPE_INTO_ELEMENT_RESPONSE`,...n}});break}case`TEST_PRESS_KEY`:{let n=await B(e.payload.query,e.payload.key);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_PRESS_KEY_RESPONSE`,...n}});break}case`TEST_SCROLL`:{let n=await V(e.payload.query,e.payload.deltaX??0,e.payload.deltaY??600);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_SCROLL_RESPONSE`,...n}});break}case`TEST_WAIT_FOR_ELEMENT`:{let n=await ee(e.payload.query,e.payload.state,e.payload.timeout);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_WAIT_FOR_ELEMENT_RESPONSE`,...n}});break}case`TEST_GET_SCREENSHOT`:{let n=await ne(e.payload.width);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_SCREENSHOT_RESPONSE`,imageBase64:n}});break}case`TEST_GET_PAGE_STRUCTURE`:{let n=re();t.postMessage({replyTo:e.requestId,payload:{type:`TEST_PAGE_STRUCTURE_RESPONSE`,structure:n}});break}case`SET_ROUTE`:{let{url:n}=e.payload;n!==m&&(m=n,h&&h(m)),t.postMessage({replyTo:e.requestId,payload:{type:`SET_ROUTE_ACK`}});break}default:t.postMessage({type:`ERROR`,message:`Unknown request type`}),e.payload}}function oe(e){let t=v.get(e.replyTo);t&&(e.payload&&e.payload.type===`ERROR`?t.reject(Error(e.payload.message??`Unknown error`)):e.payload&&t.resolve(e.payload),v.delete(e.replyTo))}async function G(e){return new Promise((r,i)=>{let a=++n;v.set(a,{resolve:r,reject:i});let o={requestId:a,payload:e};t?t.postMessage(o):_.push(o)})}function K(){o.__yjs_event__||=e=>{let t=e,n=t.data_key;n&&l.get(n)?.forEach(e=>{e(t)})},o.__yjs_events_reset__||=e=>{let t=e;u.get(t.data_key)?.forEach(e=>{e()})}}function se(){o.__graphlake_change__||=e=>{let{subscriptionId:t,...n}=e;f.get(t)?.onDelta(n)},o.__graphlake_ended__||=e=>{let t=e,n=f.get(t.subscriptionId);f.delete(t.subscriptionId),n?.onError?.(Error(t.error??`The GraphLake subscription ended: ${t.reason}`))}}function q(){return[...new Set([...d.values()].flat())]}function J(){G({type:`SET_SHORTCUTS`,shortcuts:q()}).catch(()=>{})}function ce(e){let t=e;q().includes(t.shortcut)&&document.body.dispatchEvent(new KeyboardEvent(`keydown`,{key:t.key,code:t.code,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,repeat:t.repeat,bubbles:!0,cancelable:!0,composed:!0}))}function Y(e){return(l.get(e)?.size??0)+(u.get(e)?.size??0)}function X(e){Y(e)===1&&G({type:`YJS_SUBSCRIBE_EVENTS`,dataKey:e}).catch(e=>{console.error(`Failed to subscribe to YJS events:`,e)})}function Z(e){Y(e)===0&&G({type:`YJS_UNSUBSCRIBE_EVENTS`,dataKey:e}).catch(e=>{console.error(`Failed to unsubscribe from YJS events:`,e)})}function le(e){if(e.source!==window.parent)return;let n=e.ports?.[0];(e.data===`INIT_CHANNEL`||e.data&&typeof e.data==`object`&&e.data.type===`INIT_CHANNEL`)&&n&&(t=n,t.onmessage=ie,typeof e.data==`object`&&e.data.initialRoute&&e.data.initialRoute!==`/`&&(m=e.data.initialRoute,h&&h(m)),_.forEach(e=>{e.payload.type===`ROUTE_CHANGED`&&(e.payload.url=m),n.postMessage(e)}))}window.addEventListener(`message`,le);async function Q(e){r=e,await G({type:`SET_ACTIONS`,actions:e.map((e,t)=>{let n;return n=typeof e.execute==`string`?e.execute:t.toString(),{label:e.label,disabled:e.disabled,variant:e.variant,key:n}})})}let $={request:G,saveBlob:async e=>{let t=await G({type:`SAVE_BLOB`,blob:e});if(t.type===`SAVE_BLOB_RESPONSE`)return t.blobRef;throw Error(`Failed to save blob`)},fetchBlob:async e=>{if(typeof e!=`string`||!e.startsWith(`::bw:data:`))throw Error(`Unexpected argument to bw.fetchBlob. Argument is not a blob reference.`);let t=await G({type:`FETCH_BLOB`,blobRef:e});if(t.type===`FETCH_BLOB_RESPONSE`)return t.blob;throw Error(`Failed to fetch blob`)},getData:async()=>{let e=await G({type:`GET_UI_DATA`});if(e.type===`GET_UI_DATA_RESPONSE`)return e.data;throw Error(`Failed to get data`)},invokeTask:(async(e,t,n=30,r=void 0)=>{let i=await G({type:`INVOKE_TASK`,taskName:e,inputArgs:t,timeout:n});if(i.type===`INVOKE_RESPONSE`)return r?i.result[r]:{...i,status:`OK`};throw Error(`Failed to invoke task`)}),continue:async e=>{await G({type:`CONTINUE_UI`,inputArgs:e})},setActions:e=>{let t=r,n=i,a=Symbol(`actions`);return i=a,Q(e),()=>{i===a&&(i=n,Q(t))}},setEventHandler:(e,t)=>{let n=Symbol(`eventHandler`);if(o[e]=t,s[e]=n,e===`chat_ui_state`&&c)try{t(c.data)}catch{}return()=>{s[e]===n&&(delete o[e],delete s[e])}},registerShortcuts:e=>{let t=Symbol(`shortcuts`);return d.set(t,[...e]),o.__shortcut__=ce,J(),()=>{d.delete(t)&&J()}},setSubmitHandler:e=>{let t=Symbol(`submitHandler`);return $.onGetData=e,$._usingSetSubmitHandler=!0,a=t,G({type:`SET_SUBMIT_HANDLER`,present:!0}).catch(()=>{}),()=>{a===t&&(delete $.onGetData,$._usingSetSubmitHandler=!1,a=null,G({type:`SET_SUBMIT_HANDLER`,present:!1}).catch(()=>{}))}},startChild:async e=>{let t=await G({type:`START_CHILD`,options:e});if(t.type!==`START_CHILD_RESPONSE`)throw Error(`Unexpected response to startChild: ${t.type}`);return t.result},setChildRunListener:e=>{o.__child_runs__=e,G({type:`SUBSCRIBE_CHILD_RUNS`}).then(t=>{t.type===`CHILD_RUNS_UPDATE`&&e(t.childRuns)}).catch(t=>{console.error(`Failed to subscribe to child runs:`,t),e([])})},navigate:e=>{e!==m&&(m=e,G({type:`ROUTE_CHANGED`,url:e}))},getRoute:()=>m,onRouteChange:e=>{h=e},connectRouter:e=>{let t=Symbol();g=t,G({type:`ROUTE_CHANGED`,url:m}),G({type:`ROUTES_CHANGED`,routes:e.routes??[]});let n=e.subscribe(e=>{g===t&&$.navigate(e)});return h=t=>{e.navigate(t)},e.navigate(m),()=>{n(),g===t&&(g=null,h=null,G({type:`ROUTES_CHANGED`,routes:[]}))}},navigateToStream:async e=>{await G({type:`NAVIGATE_TO_STREAM`,streamId:e})},createChat:async t=>{let n=crypto.randomUUID(),r=`__embedded_chat__${n}`,i=new Set,a=[],o=new Set,s,c=$.setEventHandler(`__embedded_chat_state__${n}`,e=>{let t=e;if(!(s&&t.revision<=s.revision)){s=t;for(let e of o)try{e(t)}catch{}}}),l=e?.(G,n,$.setEventHandler),u=!1,d=$.setEventHandler(r,e=>{let t=e;if(i.size===0&&!u){a.length>=64&&a.shift(),a.push(t);return}for(let e of i)try{e(t)}catch{}}),f=!1,p;try{p=await G({type:`CREATE_CHAT`,mountId:n,options:t})}catch(e){throw d(),c(),l?.clear(),e}if(p.type!==`CREATE_CHAT_RESPONSE`)throw d(),c(),l?.clear(),Error(`Unexpected chat creation response`);return(!s||s.revision<p.state.revision)&&(s=p.state),{streamId:p.streamId,getState:()=>s,onState:e=>{if(f)return()=>{};o.add(e);try{e(s)}catch{}return()=>{o.delete(e)}},loadMore:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`LOAD_MORE_CHAT`,mountId:n})},stop:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`STOP_CHAT`,mountId:n})},reconnect:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`RECONNECT_CHAT`,mountId:n})},mountWidget:async(e,t)=>{if(f)throw Error(`Chat is unmounted`);if(!l)throw Error(`Chat widgets are unavailable`);return l.mountWidget(e,t)},retry:async e=>{if(f)throw Error(`Chat is unmounted`);await G({type:`RETRY_CHAT_MESSAGE`,mountId:n,messageId:e})},discard:async e=>{if(f)throw Error(`Chat is unmounted`);await G({type:`DISCARD_CHAT_MESSAGE`,mountId:n,messageId:e})},onEvent:e=>{if(f)return()=>{};u=!0,i.add(e);for(let t of a.splice(0))try{e(t)}catch{}return()=>i.delete(e)},send:async(e,t)=>{if(f)throw Error(`Chat is unmounted`);let r=await G({type:`SEND_CHAT`,mountId:n,message:e,options:t});if(r.type===`SEND_CHAT_RESPONSE`&&r.error)throw Object.assign(Error(r.error),{outgoingMessageId:r.outgoingMessageId})},unmount:async()=>{f||(f=!0,d(),c(),o.clear(),l?.clear(),i.clear(),await G({type:`UNMOUNT_CHAT`,mountId:n}))}}},openPlatformChat:async e=>{let t=await G({type:`OPEN_PLATFORM_CHAT`,emptyState:e?.emptyState,placeholder:e?.placeholder,id:e?.id,agent:e?.agent,args:e?.args,reset:e?.reset});if(t?.type===`OPEN_PLATFORM_CHAT_RESPONSE`)return{streamId:t.streamId,close:e=>$.closePlatformChat(e)};throw Error(`Unexpected response from openPlatformChat`)},closePlatformChat:async e=>{await G({type:`CLOSE_PLATFORM_CHAT`,closeStream:e?.closeStream})},emitYjsEvent:async(e,t,n)=>{let r=await G({type:`YJS_EMIT_EVENT`,dataKey:e,data:t,transient:n?.transient});if(r.type===`YJS_EMIT_EVENT_RESPONSE`)return r.event;throw Error(`Failed to emit YJS event`)},getYjsEvents:async e=>{let t=await G({type:`YJS_GET_EVENTS`,dataKey:e});if(t.type===`YJS_GET_EVENTS_RESPONSE`)return t.events;throw Error(`Failed to get YJS events`)},resetYjsEvents:async e=>{await G({type:`YJS_RESET_EVENTS`,dataKey:e})},subscribeYjsEvents:(e,t)=>{let n=l.get(e)??new Set;return n.add(t),l.set(e,n),K(),X(e),()=>{let n=l.get(e);n&&(n.delete(t),n.size===0&&l.delete(e),Z(e))}},onYjsEventsReset:(e,t)=>{let n=u.get(e)??new Set;return n.add(t),u.set(e,n),K(),X(e),()=>{let n=u.get(e);n&&(n.delete(t),n.size===0&&u.delete(e),Z(e))}},graphlake:{query:async(e,t)=>{let n=await G({type:`GRAPHLAKE_QUERY`,glq:e,params:t?.params,pageSize:t?.pageSize,pageToken:t?.pageToken});if(n.type===`GRAPHLAKE_QUERY_RESPONSE`)return n.page;throw Error(`Failed to query GraphLake`)},subscribe:(e,t,n)=>{p+=1;let r=`graphlake-${p}`;return f.set(r,{onDelta:n,onError:t?.onError}),se(),G({type:`GRAPHLAKE_SUBSCRIBE`,subscriptionId:r,glq:e,params:t?.params}).catch(e=>{let t=f.get(r);f.delete(r);let n=e instanceof Error?e:Error(String(e));t?.onError?t.onError(n):t&&console.error(`Failed to subscribe to GraphLake:`,n)}),()=>{f.delete(r)&&G({type:`GRAPHLAKE_UNSUBSCRIBE`,subscriptionId:r}).catch(()=>{})}}},bindYjsDoc:(e,t,n)=>{let r=n?.doc??new t.Doc,i=n?.awareness?.module??null,a=n?.awareness?.instance??(i?new i.Awareness(r):null),o=!1,s=!1,c=32*1024,l=e=>{let t=``;for(let n=0;n<e.length;n+=c)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+c)));return btoa(t)},u=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},d=!1,f=[],p=e=>{s=!0,t.applyUpdate(r,e),s=!1},m=t=>{o||s||$.emitYjsEvent(e,l(t)).catch(e=>{console.error(`Failed to emit yjs doc update:`,e)})};r.on(`update`,m);let h=$.subscribeYjsEvents(e,e=>{if(o)return;let t=u(e.data);if(!d){f.push(t);return}p(t)});$.getYjsEvents(e).then(e=>{if(!o){for(let t of e)p(u(t.data));for(let e of f)p(e);f.length=0,d=!0}}).catch(e=>{console.error(`Failed to load yjs snapshot:`,e),d=!0;for(let e of f)p(e);f.length=0});let g=$.onYjsEventsReset(e,()=>{if(o)return;s=!0;let e=new t.Doc,n=t.encodeStateAsUpdate(e);t.applyUpdate(r,n),s=!1}),_=`${e}:awareness`,v=null;if(a&&i){v=({added:e,updated:t,removed:n})=>{if(o)return;let r=[...e,...t,...n],s=i.encodeAwarenessUpdate(a,r);$.emitYjsEvent(_,l(s),{transient:!0}).catch(e=>{console.error(`Failed to emit awareness update:`,e)})},a.on(`update`,v);let e={unsubscribeAwareness:$.subscribeYjsEvents(_,e=>{o||i.applyAwarenessUpdate(a,u(e.data),`remote`)})};return{doc:r,awareness:a,destroy:()=>{o=!0,r.off(`update`,m),h(),g(),e.unsubscribeAwareness(),v&&a.off(`update`,v),i.removeAwarenessStates(a,[r.clientID],null)}}}return{doc:r,awareness:a,destroy:()=>{o=!0,r.off(`update`,m),h(),g()}}}};return $}var u=/^[a-zA-Z][a-zA-Z0-9-]*$/,d=/^[a-zA-Z0-9 \-_.+/=:*'@~%]*$/;function f(e){let t=new Map;for(let n of e.split(`;`)){let e=n.trim();if(!e)continue;let r=e.search(/\s/),i=(r===-1?e:e.slice(0,r)).toLowerCase(),a=r===-1?``:e.slice(r+1).trim().replace(/\s+/g,` `);if(!u.test(i))throw Error(`Invalid CSP directive name: ${JSON.stringify(i)}`);if(!d.test(a))throw Error(`Invalid CSP directive value for ${JSON.stringify(i)}`);t.set(i,a)}return t}function p(e,t){let n=f(e.join(`; `));if(t)for(let[e,r]of f(t))n.set(e,r);return Array.from(n,([e,t])=>t?`${e} ${t}`:e).join(`; `)}function m(e){let t=`default`,n=0,r=!1,i=new Map,a=e=>e===`granted`||e==="default"?e:`denied`,o=e=>{let t=e?.id;return typeof t==`string`?t:``},s=()=>{r||!e.bw||(r=!0,e.bw.setEventHandler(`__notification_click__`,e=>i.get(o(e))?.fire(`click`)),e.bw.setEventHandler(`__notification_close__`,e=>{let t=i.get(o(e));i.delete(o(e)),t?.fire(`close`)}))},c=async n=>{if(!e.bw)return t;s();try{let r=await e.bw.request({type:`NOTIFICATIONS_REQUEST_PERMISSION`,prompt:n});r.type===`NOTIFICATIONS_PERMISSION_RESPONSE`&&(t=a(r.permission))}catch{return t}return t};class l extends EventTarget{static get permission(){return t}static requestPermission(e){let t=c(!0);return e&&t.then(e),t}constructor(t,r){super(),n+=1,Object.assign(this,{title:String(t),body:typeof r?.body==`string`?r.body:``,tag:typeof r?.tag==`string`?r.tag:``,onclick:null,onclose:null,onerror:null,onshow:null,id:`notification-${n}`}),i.set(this.id,this);let a=()=>{i.delete(this.id),this.fire(`error`)};if(!e.bw){queueMicrotask(a);return}s(),e.bw.request({type:`NOTIFICATIONS_SHOW`,id:this.id,title:this.title,body:this.body||void 0,tag:this.tag||void 0}).then(e=>e.type===`NOTIFICATIONS_SHOW_RESPONSE`&&e.shown?this.fire(`show`):a()).catch(a)}close(){i.delete(this.id)&&(e.bw?.request({type:`NOTIFICATIONS_CLOSE`,id:this.id}).catch(()=>{}),this.fire(`close`))}fire(e){let t=new Event(e);({click:this.onclick,close:this.onclose,error:this.onerror,show:this.onshow})[e]?.call(this,t),this.dispatchEvent(t)}}e.Notification=l,c(!1)}function h(e){let t=new TextEncoder().encode(e),n=``,r=8192;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,Math.min(e+r,t.length)));return btoa(n)}function g(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return new TextDecoder().decode(r)}function _({content:e,runtime:t,csp:n,restrictEgress:r,inline:i,locale:a,reportBackground:o,blobUrl:u}){let d=[`default-src 'none'`,`connect-src blob: https://unpkg.com`,`worker-src blob:`,`frame-src about:`,`form-action 'self'`,`img-src 'self' data: blob:`,`media-src blob:`,`script-src 'self' data: 'unsafe-inline' 'wasm-unsafe-eval' blob: https://unpkg.com ${`${window.location.origin}/pdf-viewer.js`}`,`style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net/npm/bulma@1.0.2/css/bulma.min.css`,`base-uri 'none'`],f=r?[`default-src 'none'`,`connect-src blob:`,`script-src 'unsafe-inline' 'wasm-unsafe-eval' blob: data:`,`style-src 'unsafe-inline'`,`img-src data: blob:`,`media-src blob:`,`worker-src blob:`,`frame-src about:`,`form-action 'none'`,`base-uri 'none'`].join(`; `):p(d,n);function _(){let e={log:console.log,error:console.error,warn:console.warn,info:console.info,debug:console.debug};[`log`,`error`,`warn`,`info`,`debug`].forEach(t=>{console[t]=(...n)=>{e[t](...n),window.bw&&window.bw.request({type:`CONSOLE_LOG`,level:t,message:n.map(e=>{try{return typeof e==`string`?e:JSON.stringify(e)}catch{return String(e)}}).join(` `),timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send console log via sandbox API:`,t)})}}),window.addEventListener(`error`,t=>{(async()=>{let n=window;if(!n.bw)return;let r=t.error?`${t.error.message}${t.error.stack?`
|
|
1
|
+
(function(){var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function t(t){return typeof t==`string`&&e.test(t)}function n(e){return typeof e==`string`&&e.startsWith(`::bw:data:`)}function r(e){return t(e)?{task_id:e}:{task_name:e}}function i(e,t){return{...r(e.taskName),workblock_id:t.workblockId,module_id:t.moduleId,inputs:e.inputArgs,commit_ref:t.commitRef,data_environment_id:t.dataEnvironmentId}}function a(e,t){return{...r(e.taskName),run_id:t.runId,inputs:e.inputArgs,ui_task_run_id:t.uiTaskRunId}}async function o(e,t){let r={...e};return await Promise.all(Object.entries(r).map(async([e,i])=>{n(i)?r[e]=await t(i):typeof i==`string`&&i.startsWith(`$$$::bw:data:`)&&(r[e]=i.substring(3))})),r}function s(e,t,n){let r=new Set,i=!1;return{mountWidget:async(a,o)=>{if(i)throw Error(`Chat is unmounted`);if(!(a instanceof HTMLElement))throw Error(`Chat widget needs an element`);let s=crypto.randomUUID(),c=document.createElement(`iframe`),l=new MessageChannel,u=!1,d=!1,f=0,p,m=(e,t)=>{!u&&d&&l.port1.postMessage({requestId:++f,payload:{type:`ON_EVENT`,event:e,data:t}})},h=n(`__embedded_chat_widget__${s}`,e=>{e&&typeof e==`object`&&`event`in e&&`data`in e&&(e.event===`chat_ui_state`&&(p=e.data),(e.event===`chat_ui_state`||e.event===`chat_ui_submit_failed`)&&m(e.event,e.data))}),g=()=>{u||d||(d=!0,c.contentWindow?.postMessage({type:`INIT_CHANNEL`,initialRoute:`/`},`*`,[l.port2]))},_=async()=>{u||(u=!0,r.delete(_),h(),c.removeEventListener(`load`,g),l.port1.onmessage=null,l.port1.close(),l.port2.close(),c.remove(),await e({type:`UNMOUNT_CHAT_WIDGET`,mountId:t,widgetMountId:s}))};r.add(_),l.port1.onmessage=async n=>{if(u||!n.data||`replyTo`in n.data)return;let{requestId:r,payload:i}=n.data;if(Number.isFinite(r)&&i&&typeof i.type==`string`)try{i.type===`REPORT_HEIGHT`&&Number.isFinite(i.height)&&(c.style.height=`${Math.max(32,Math.min(i.height,2e3))}px`,p&&m(`chat_ui_state`,p));let n=await e({type:`CHAT_WIDGET_REQUEST`,mountId:t,widgetMountId:s,request:i});if(u)return;if(n.type!==`CHAT_WIDGET_RESPONSE`)throw Error(`Unexpected chat widget response`);l.port1.postMessage({replyTo:r,payload:n.response}),i.type===`CONSOLE_LOG`&&i.level===`fatal`&&a.dispatchEvent(new CustomEvent(`bw:widget-error`,{detail:Error(i.message)}))}catch(e){if(u)return;l.port1.postMessage({replyTo:r,payload:{type:`ERROR`,message:e instanceof Error?e.message:`Chat widget request failed`}})}};try{let n=await e({type:`PREPARE_CHAT_WIDGET`,mountId:t,widgetMountId:s,...o});if(u||i)throw Error(`Chat widget was unmounted`);if(n.type!==`PREPARE_CHAT_WIDGET_RESPONSE`)throw Error(`Unexpected chat widget response`);n.submitted&&(p={submitted:!0,submission:n.submission}),c.title=n.title;let r=new Set([`allow-scripts`,`allow-forms`,`allow-popups`,`allow-popups-to-escape-sandbox`,`allow-downloads`]);return c.setAttribute(`sandbox`,n.sandbox.split(/\s+/).filter(e=>r.has(e)).join(` `)),c.referrerPolicy=`no-referrer`,c.style.cssText=`width:100%;height:80px;border:0;display:block;`,c.addEventListener(`load`,g,{once:!0}),c.srcdoc=n.srcDoc,a.appendChild(c),{unmount:_}}catch(e){throw await _().catch(()=>{}),e}},clear:()=>{i=!0;for(let e of r)e().catch(()=>{})}}}function c(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}function l(e){let t=null,n=0,r=[],i=null,a=null,o={},s={},c,l=new Map,u=new Map,d=new Map,f=new Map,p=0,m=`/`,h=null,g=null,_=[],v=new Map;function y(e){return(e??``).replace(/\s+/g,` `).trim()}function b(e,t){return y(e).toLowerCase().includes(y(t).toLowerCase())}function x(e){let t=globalThis.CSS;return t?.escape?t.escape(e):e.replace(/["\\]/g,`\\$&`)}function S(e){let t=[];return(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&t.push(...Array.from(e.labels??[]).map(e=>y(e.textContent))),e.id&&t.push(...Array.from(document.querySelectorAll(`label[for="${x(e.id)}"]`)).map(e=>y(e.textContent))),t.filter(Boolean)}function C(e){return e.split(/\s+/).map(e=>document.getElementById(e)?.textContent).map(y).filter(Boolean).join(` `)}function w(e){let t=e.tagName.toLowerCase();if(t===`button`)return`button`;if(t===`a`&&e.hasAttribute(`href`))return`link`;if(t===`textarea`)return`textbox`;if(t===`select`)return`combobox`;if(t===`form`)return`form`;if(t===`img`)return`img`;if(/^h[1-6]$/.test(t))return`heading`;if(t===`ul`||t===`ol`)return`list`;if(t===`li`)return`listitem`;if(t===`table`)return`table`;if(t===`tr`)return`row`;if(t===`td`||t===`th`)return`cell`;if(t!==`input`)return null;let n=(e.type||`text`).toLowerCase();return n===`checkbox`?`checkbox`:n===`radio`?`radio`:[`button`,`submit`,`reset`].includes(n)?`button`:n===`range`?`slider`:`textbox`}function T(e){return e.getAttribute(`role`)?.split(/\s+/)[0]||w(e)}function E(e){let t=e.getAttribute(`aria-label`);if(t)return y(t);let n=e.getAttribute(`aria-labelledby`);if(n)return C(n);let r=S(e);return r.length>0?r.join(` `):e instanceof HTMLInputElement&&[`button`,`submit`,`reset`].includes(e.type)?y(e.value):e instanceof HTMLImageElement?y(e.alt):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?y(e.placeholder):y(e.getAttribute(`title`)||e.textContent)}function D(){return Array.from(document.body.querySelectorAll(`*`))}function O(e,t){let n=e.toLowerCase();return D().filter(e=>T(e)?.toLowerCase()===n?!t||b(E(e),t):!1)}function k(e){return D().filter(t=>S(t).some(t=>b(t,e))?!0:b(t.getAttribute(`aria-label`),e))}function A(e){return D().filter(t=>t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?b(t.placeholder,e):!1)}function j(e){return D().filter(t=>b(t.textContent,e)?!Array.from(t.children).some(t=>b(t.textContent,e)):!1)}function M(e){return e.length===0?null:e.length===1?e[0]:e.find(e=>F(e))??e[0]}async function N(e){return e.selector?document.querySelector(e.selector):e.testid?M(Array.from(document.querySelectorAll(`[data-testid="${x(e.testid)}"]`))):e.role?M(O(e.role,e.name)):e.label?M(k(e.label)):e.placeholder?M(A(e.placeholder)):e.text?M(j(e.text)):null}function P(e){return e.selector?`selector "${e.selector}"`:e.testid?`testid "${e.testid}"`:e.role&&e.name?`role "${e.role}" with name "${e.name}"`:e.role?`role "${e.role}"`:e.label?`label "${e.label}"`:e.placeholder?`placeholder "${e.placeholder}"`:e.text?`text "${e.text}"`:`empty query`}function F(e){let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0}async function I(e){let t=await N(e);if(!t)return null;let n=t.getBoundingClientRect(),r={};for(let e of t.attributes)r[e.name]=e.value;return{exists:!0,visible:F(t),text:t.textContent?.trim()||``,value:t.value,attributes:r,rect:{x:n.x,y:n.y,width:n.width,height:n.height},tagName:t.tagName.toLowerCase()}}async function L(e){let t=await N(e);return t?t instanceof HTMLElement?(t.click(),{success:!0}):{success:!1,error:`Element is not clickable: ${P(e)}`}:{success:!1,error:`Element not found: ${P(e)}`}}function R(e,t){let n=e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(n,`value`)?.set;r?r.call(e,t):e.value=t}async function z(e,t,n,r){let i=await N(e);return i?i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?(i.focus(),R(i,n?t:i.value+t),i.dispatchEvent(new Event(`input`,{bubbles:!0})),i.dispatchEvent(new Event(`change`,{bubbles:!0})),r&&(i.dispatchEvent(new KeyboardEvent(`keydown`,{key:`Enter`,code:`Enter`,bubbles:!0})),i.dispatchEvent(new KeyboardEvent(`keypress`,{key:`Enter`,code:`Enter`,bubbles:!0})),i.dispatchEvent(new KeyboardEvent(`keyup`,{key:`Enter`,code:`Enter`,bubbles:!0}))),{success:!0}):{success:!1,error:`Element is not an input: ${P(e)}`}:{success:!1,error:`Element not found: ${P(e)}`}}async function B(e,t){let n=e?await N(e):document.activeElement;if(!(n instanceof HTMLElement))return{success:!1,error:e?`Element not found: ${P(e)}`:`No active element`};n.focus();for(let e of[`keydown`,`keypress`,`keyup`])n.dispatchEvent(new KeyboardEvent(e,{key:t,code:t,bubbles:!0,cancelable:!0}));return{success:!0}}async function V(e,t,n){let r=e?await N(e):document.scrollingElement;return r instanceof Element?(r.scrollBy({left:t,top:n,behavior:`auto`}),r.dispatchEvent(new Event(`scroll`,{bubbles:!0})),{success:!0}):{success:!1,error:e?`Element not found: ${P(e)}`:`No scrolling element`}}async function ee(e,t,n=5e3){let r=Date.now(),i=async()=>{let n=await N(e);switch(t){case`attached`:return n!==null;case`detached`:return n===null;case`visible`:return n!==null&&F(n);case`hidden`:return n===null||!F(n)}};return new Promise(a=>{let o=async()=>{await i()?a({success:!0}):Date.now()-r>=n?a({success:!1,error:`Timeout waiting for element ${P(e)} to be ${t}`}):requestAnimationFrame(o)};o()})}let H=null,U=null;async function te(){return H||U||(U=new Promise((e,t)=>{let n=document.createElement(`script`);n.src=`https://unpkg.com/html-to-image@1.11.13/dist/html-to-image.js`,n.onload=()=>{H=window.htmlToImage,H?e(H):t(Error(`html-to-image not found on window`))},n.onerror=()=>t(Error(`Failed to load html-to-image`)),document.head.appendChild(n)}),U)}async function ne(e){let t=document.body.style.width,n=document.documentElement.style.width,r=document.documentElement.style.overflow;e&&(document.documentElement.style.width=`${e}px`,document.body.style.width=`${e}px`,document.documentElement.style.overflow=`hidden`,document.body.offsetHeight,await new Promise(e=>requestAnimationFrame(e)));try{let e=await(await te()).toPng(document.body,{backgroundColor:`#ffffff`,pixelRatio:1});return e.startsWith(`data:image/png;base64,`)?e.split(`,`)[1]:e}catch(e){return console.error(`Error capturing screenshot:`,e),``}finally{e&&(document.body.style.width=t,document.documentElement.style.width=n,document.documentElement.style.overflow=r)}}function W(e){if(e.id)return`#${e.id}`;let t=e.getAttribute(`data-testid`);if(t)return`[data-testid="${t}"]`;let n=[e.tagName.toLowerCase()],r=e.getAttribute(`role`);r&&n.push(`[role="${r}"]`);let i=e.getAttribute(`type`);i&&n.push(`[type="${i}"]`);let a=e.getAttribute(`name`);a&&n.push(`[name="${a}"]`);let o=Array.from(e.classList).find(e=>!e.startsWith(`_`)&&e.length<30);o&&n.push(`.${o}`);let s=n.join(``);if(document.querySelectorAll(s).length===1)return s;let c=e.parentElement;return c?`${s}:nth-of-type(${Array.from(c.children).filter(t=>t.tagName===e.tagName).indexOf(e)+1})`:s}function re(){let e=[];document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`).forEach(t=>{let n=E(t)||t.value||``;e.push({text:n,selector:W(t),disabled:t.disabled||t.getAttribute(`aria-disabled`)===`true`})});let t=[];document.querySelectorAll(`input, textarea, select`).forEach(e=>{let n=e;t.push({selector:W(e),type:n.type||e.tagName.toLowerCase(),name:n.name||E(e)||void 0,value:n.value||void 0})});let n=[];document.querySelectorAll(`form`).forEach(e=>{n.push({id:e.id||void 0,name:e.name||void 0,inputCount:e.querySelectorAll(`input, textarea, select`).length})});let r=[];return document.querySelectorAll(`a[href]`).forEach(e=>{r.push({text:E(e)||``,href:e.href})}),{title:document.title,url:window.location.href,forms:n,buttons:e,inputs:t,links:r}}function ie(e){let t=e.data;`replyTo`in t?oe(t):ae(t)}async function ae(e){if(!t)throw Error(`Communication channel not initialized, but since we received a message, this should not happen`);switch(e.payload.type){case`GET_DATA`:{let n={status:`OK`};if($.onGetData)try{let e=await $.onGetData();if($._usingSetSubmitHandler)n={status:`OK`,data:e};else{if(!e||typeof e!=`object`||!(`status`in e))throw Error(`Unexpected result shape returned by bw.onGetData callback. Expected { status: "OK" | "ERROR", data?: any, error?: string }`);n=e}}catch(e){if($._usingSetSubmitHandler)n={status:`ERROR`,error:e instanceof Error?e.message:`Unknown error`};else throw e}let r={type:`GET_DATA_RESPONSE`,data:n};t.postMessage({replyTo:e.requestId,payload:r});break}case`ON_ACTION`:{let n=e.payload.key,i=r[parseInt(n,10)];if(typeof i.execute!=`string`)try{i.execute()}catch(e){console.error(`Error in action handler:`,e)}t.postMessage({replyTo:e.requestId,payload:{type:`ACK`}});break}case`ON_EVENT`:{e.payload.event===`chat_ui_state`&&(c={data:e.payload.data});let n=o[e.payload.event];if(n)try{n(e.payload.data)}catch(e){console.error(`Error in event handler:`,e)}t.postMessage({replyTo:e.requestId,payload:{type:`ACK`}});break}case`TEST_QUERY_ELEMENT`:{let n=await I(e.payload.query);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_QUERY_ELEMENT_RESPONSE`,result:n}});break}case`TEST_CLICK_ELEMENT`:{let n=await L(e.payload.query);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_CLICK_ELEMENT_RESPONSE`,...n}});break}case`TEST_TYPE_INTO_ELEMENT`:{let n=await z(e.payload.query,e.payload.text,e.payload.clear,e.payload.pressEnter);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_TYPE_INTO_ELEMENT_RESPONSE`,...n}});break}case`TEST_PRESS_KEY`:{let n=await B(e.payload.query,e.payload.key);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_PRESS_KEY_RESPONSE`,...n}});break}case`TEST_SCROLL`:{let n=await V(e.payload.query,e.payload.deltaX??0,e.payload.deltaY??600);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_SCROLL_RESPONSE`,...n}});break}case`TEST_WAIT_FOR_ELEMENT`:{let n=await ee(e.payload.query,e.payload.state,e.payload.timeout);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_WAIT_FOR_ELEMENT_RESPONSE`,...n}});break}case`TEST_GET_SCREENSHOT`:{let n=await ne(e.payload.width);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_SCREENSHOT_RESPONSE`,imageBase64:n}});break}case`TEST_GET_PAGE_STRUCTURE`:{let n=re();t.postMessage({replyTo:e.requestId,payload:{type:`TEST_PAGE_STRUCTURE_RESPONSE`,structure:n}});break}case`SET_ROUTE`:{let{url:n}=e.payload;n!==m&&(m=n,h&&h(m)),t.postMessage({replyTo:e.requestId,payload:{type:`SET_ROUTE_ACK`}});break}default:t.postMessage({type:`ERROR`,message:`Unknown request type`}),e.payload}}function oe(e){let t=v.get(e.replyTo);t&&(e.payload&&e.payload.type===`ERROR`?t.reject(Error(e.payload.message??`Unknown error`)):e.payload&&t.resolve(e.payload),v.delete(e.replyTo))}async function G(e){return new Promise((r,i)=>{let a=++n;v.set(a,{resolve:r,reject:i});let o={requestId:a,payload:e};t?t.postMessage(o):_.push(o)})}function K(){o.__yjs_event__||=e=>{let t=e,n=t.data_key;n&&l.get(n)?.forEach(e=>{e(t)})},o.__yjs_events_reset__||=e=>{let t=e;u.get(t.data_key)?.forEach(e=>{e()})}}function se(){o.__graphlake_change__||=e=>{let{subscriptionId:t,...n}=e;f.get(t)?.onDelta(n)},o.__graphlake_ended__||=e=>{let t=e,n=f.get(t.subscriptionId);f.delete(t.subscriptionId),n?.onError?.(Error(t.error??`The GraphLake subscription ended: ${t.reason}`))}}function q(){return[...new Set([...d.values()].flat())]}function J(){G({type:`SET_SHORTCUTS`,shortcuts:q()}).catch(()=>{})}function ce(e){let t=e;q().includes(t.shortcut)&&document.body.dispatchEvent(new KeyboardEvent(`keydown`,{key:t.key,code:t.code,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,repeat:t.repeat,bubbles:!0,cancelable:!0,composed:!0}))}function Y(e){return(l.get(e)?.size??0)+(u.get(e)?.size??0)}function X(e){Y(e)===1&&G({type:`YJS_SUBSCRIBE_EVENTS`,dataKey:e}).catch(e=>{console.error(`Failed to subscribe to YJS events:`,e)})}function Z(e){Y(e)===0&&G({type:`YJS_UNSUBSCRIBE_EVENTS`,dataKey:e}).catch(e=>{console.error(`Failed to unsubscribe from YJS events:`,e)})}function le(e){if(e.source!==window.parent)return;let n=e.ports?.[0];(e.data===`INIT_CHANNEL`||e.data&&typeof e.data==`object`&&e.data.type===`INIT_CHANNEL`)&&n&&(t=n,t.onmessage=ie,typeof e.data==`object`&&e.data.initialRoute&&e.data.initialRoute!==`/`&&(m=e.data.initialRoute,h&&h(m)),_.forEach(e=>{e.payload.type===`ROUTE_CHANGED`&&(e.payload.url=m),n.postMessage(e)}))}window.addEventListener(`message`,le);async function Q(e){r=e,await G({type:`SET_ACTIONS`,actions:e.map((e,t)=>{let n;return n=typeof e.execute==`string`?e.execute:t.toString(),{label:e.label,disabled:e.disabled,variant:e.variant,key:n}})})}let $={request:G,saveBlob:async e=>{let t=await G({type:`SAVE_BLOB`,blob:e});if(t.type===`SAVE_BLOB_RESPONSE`)return t.blobRef;throw Error(`Failed to save blob`)},fetchBlob:async e=>{if(typeof e!=`string`||!e.startsWith(`::bw:data:`))throw Error(`Unexpected argument to bw.fetchBlob. Argument is not a blob reference.`);let t=await G({type:`FETCH_BLOB`,blobRef:e});if(t.type===`FETCH_BLOB_RESPONSE`)return t.blob;throw Error(`Failed to fetch blob`)},getData:async()=>{let e=await G({type:`GET_UI_DATA`});if(e.type===`GET_UI_DATA_RESPONSE`)return e.data;throw Error(`Failed to get data`)},invokeTask:(async(e,t,n=30,r=void 0)=>{let i=await G({type:`INVOKE_TASK`,taskName:e,inputArgs:t,timeout:n});if(i.type===`INVOKE_RESPONSE`)return r?i.result[r]:{...i,status:`OK`};throw Error(`Failed to invoke task`)}),continue:async e=>{await G({type:`CONTINUE_UI`,inputArgs:e})},setActions:e=>{let t=r,n=i,a=Symbol(`actions`);return i=a,Q(e),()=>{i===a&&(i=n,Q(t))}},setEventHandler:(e,t)=>{let n=Symbol(`eventHandler`);if(o[e]=t,s[e]=n,e===`chat_ui_state`&&c)try{t(c.data)}catch{}return()=>{s[e]===n&&(delete o[e],delete s[e])}},registerShortcuts:e=>{let t=Symbol(`shortcuts`);return d.set(t,[...e]),o.__shortcut__=ce,J(),()=>{d.delete(t)&&J()}},setSubmitHandler:e=>{let t=Symbol(`submitHandler`);return $.onGetData=e,$._usingSetSubmitHandler=!0,a=t,G({type:`SET_SUBMIT_HANDLER`,present:!0}).catch(()=>{}),()=>{a===t&&(delete $.onGetData,$._usingSetSubmitHandler=!1,a=null,G({type:`SET_SUBMIT_HANDLER`,present:!1}).catch(()=>{}))}},startChild:async e=>{let t=await G({type:`START_CHILD`,options:e});if(t.type!==`START_CHILD_RESPONSE`)throw Error(`Unexpected response to startChild: ${t.type}`);return t.result},setChildRunListener:e=>{o.__child_runs__=e,G({type:`SUBSCRIBE_CHILD_RUNS`}).then(t=>{t.type===`CHILD_RUNS_UPDATE`&&e(t.childRuns)}).catch(t=>{console.error(`Failed to subscribe to child runs:`,t),e([])})},navigate:e=>{e!==m&&(m=e,G({type:`ROUTE_CHANGED`,url:e}))},getRoute:()=>m,onRouteChange:e=>{h=e},connectRouter:e=>{let t=Symbol();g=t,G({type:`ROUTE_CHANGED`,url:m}),G({type:`ROUTES_CHANGED`,routes:e.routes??[]});let n=e.subscribe(e=>{g===t&&$.navigate(e)});return h=t=>{e.navigate(t)},e.navigate(m),()=>{n(),g===t&&(g=null,h=null,G({type:`ROUTES_CHANGED`,routes:[]}))}},navigateToStream:async e=>{await G({type:`NAVIGATE_TO_STREAM`,streamId:e})},createChat:async t=>{let n=crypto.randomUUID(),r=`__embedded_chat__${n}`,i=new Set,a=[],o=new Set,s,c=$.setEventHandler(`__embedded_chat_state__${n}`,e=>{let t=e;if(!(s&&t.revision<=s.revision)){s=t;for(let e of o)try{e(t)}catch{}}}),l=e?.(G,n,$.setEventHandler),u=!1,d=$.setEventHandler(r,e=>{let t=e;if(i.size===0&&!u)a.length>=64&&a.shift(),a.push(t);else for(let e of i)try{e(t)}catch{}}),f=!1,p;try{p=await G({type:`CREATE_CHAT`,mountId:n,options:t})}catch(e){throw d(),c(),l?.clear(),e}if(p.type!==`CREATE_CHAT_RESPONSE`)throw d(),c(),l?.clear(),Error(`Unexpected chat creation response`);return(!s||s.revision<p.state.revision)&&(s=p.state),{streamId:p.streamId,getState:()=>s,onState:e=>{if(f)return()=>{};o.add(e);try{e(s)}catch{}return()=>{o.delete(e)}},loadMore:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`LOAD_MORE_CHAT`,mountId:n})},stop:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`STOP_CHAT`,mountId:n})},reconnect:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`RECONNECT_CHAT`,mountId:n})},mountWidget:async(e,t)=>{if(f)throw Error(`Chat is unmounted`);if(!l)throw Error(`Chat widgets are unavailable`);return l.mountWidget(e,t)},retry:async e=>{if(f)throw Error(`Chat is unmounted`);await G({type:`RETRY_CHAT_MESSAGE`,mountId:n,messageId:e})},discard:async e=>{if(f)throw Error(`Chat is unmounted`);await G({type:`DISCARD_CHAT_MESSAGE`,mountId:n,messageId:e})},onEvent:e=>{if(f)return()=>{};u=!0,i.add(e);for(let t of a.splice(0))try{e(t)}catch{}return()=>i.delete(e)},send:async(e,t)=>{if(f)throw Error(`Chat is unmounted`);let r=await G({type:`SEND_CHAT`,mountId:n,message:e,options:t});if(r.type===`SEND_CHAT_RESPONSE`&&r.error)throw Object.assign(Error(r.error),{outgoingMessageId:r.outgoingMessageId})},transcribe:async e=>{if(f)throw Error(`Chat is unmounted`);let t=await G({type:`TRANSCRIBE_CHAT_AUDIO`,mountId:n,audio:e});if(t?.type!==`TRANSCRIBE_CHAT_AUDIO_RESPONSE`)throw Error(`Unexpected transcription response`);return t.text},enqueue:async(e,t)=>{if(f)throw Error(`Chat is unmounted`);await G({type:`QUEUE_CHAT_MESSAGE`,mountId:n,message:e,options:t})},editQueued:async(e,t)=>{if(f)throw Error(`Chat is unmounted`);await G({type:`EDIT_QUEUED_CHAT_MESSAGE`,mountId:n,messageId:e,message:t})},removeQueued:async e=>{if(f)throw Error(`Chat is unmounted`);await G({type:`REMOVE_QUEUED_CHAT_MESSAGE`,mountId:n,messageId:e})},sendQueuedNow:async e=>{if(f)throw Error(`Chat is unmounted`);await G({type:`SEND_QUEUED_CHAT_MESSAGE`,mountId:n,messageId:e})},unmount:async()=>{f||(f=!0,d(),c(),o.clear(),l?.clear(),i.clear(),await G({type:`UNMOUNT_CHAT`,mountId:n}))}}},openPlatformChat:async e=>{let t=await G({type:`OPEN_PLATFORM_CHAT`,emptyState:e?.emptyState,placeholder:e?.placeholder,id:e?.id,agent:e?.agent,args:e?.args,reset:e?.reset});if(t?.type===`OPEN_PLATFORM_CHAT_RESPONSE`)return{streamId:t.streamId,close:e=>$.closePlatformChat(e)};throw Error(`Unexpected response from openPlatformChat`)},closePlatformChat:async e=>{await G({type:`CLOSE_PLATFORM_CHAT`,closeStream:e?.closeStream})},emitYjsEvent:async(e,t,n)=>{let r=await G({type:`YJS_EMIT_EVENT`,dataKey:e,data:t,transient:n?.transient});if(r.type===`YJS_EMIT_EVENT_RESPONSE`)return r.event;throw Error(`Failed to emit YJS event`)},getYjsEvents:async e=>{let t=await G({type:`YJS_GET_EVENTS`,dataKey:e});if(t.type===`YJS_GET_EVENTS_RESPONSE`)return t.events;throw Error(`Failed to get YJS events`)},resetYjsEvents:async e=>{await G({type:`YJS_RESET_EVENTS`,dataKey:e})},subscribeYjsEvents:(e,t)=>{let n=l.get(e)??new Set;return n.add(t),l.set(e,n),K(),X(e),()=>{let n=l.get(e);n&&(n.delete(t),n.size===0&&l.delete(e),Z(e))}},onYjsEventsReset:(e,t)=>{let n=u.get(e)??new Set;return n.add(t),u.set(e,n),K(),X(e),()=>{let n=u.get(e);n&&(n.delete(t),n.size===0&&u.delete(e),Z(e))}},graphlake:{query:async(e,t)=>{let n=await G({type:`GRAPHLAKE_QUERY`,glq:e,params:t?.params,pageSize:t?.pageSize,pageToken:t?.pageToken});if(n.type===`GRAPHLAKE_QUERY_RESPONSE`)return n.page;throw Error(`Failed to query GraphLake`)},subscribe:(e,t,n)=>{p+=1;let r=`graphlake-${p}`;return f.set(r,{onDelta:n,onError:t?.onError}),se(),G({type:`GRAPHLAKE_SUBSCRIBE`,subscriptionId:r,glq:e,params:t?.params}).catch(e=>{let t=f.get(r);f.delete(r);let n=e instanceof Error?e:Error(String(e));t?.onError?t.onError(n):t&&console.error(`Failed to subscribe to GraphLake:`,n)}),()=>{f.delete(r)&&G({type:`GRAPHLAKE_UNSUBSCRIBE`,subscriptionId:r}).catch(()=>{})}}},bindYjsDoc:(e,t,n)=>{let r=n?.doc??new t.Doc,i=n?.awareness?.module??null,a=n?.awareness?.instance??(i?new i.Awareness(r):null),o=!1,s=!1,c=32768,l=e=>{let t=``;for(let n=0;n<e.length;n+=c)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+c)));return btoa(t)},u=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},d=!1,f=[],p=e=>{s=!0,t.applyUpdate(r,e),s=!1},m=t=>{o||s||$.emitYjsEvent(e,l(t)).catch(e=>{console.error(`Failed to emit yjs doc update:`,e)})};r.on(`update`,m);let h=$.subscribeYjsEvents(e,e=>{if(o)return;let t=u(e.data);d?p(t):f.push(t)});$.getYjsEvents(e).then(e=>{if(!o){for(let t of e)p(u(t.data));for(let e of f)p(e);f.length=0,d=!0}}).catch(e=>{console.error(`Failed to load yjs snapshot:`,e),d=!0;for(let e of f)p(e);f.length=0});let g=$.onYjsEventsReset(e,()=>{if(o)return;s=!0;let e=new t.Doc,n=t.encodeStateAsUpdate(e);t.applyUpdate(r,n),s=!1}),_=`${e}:awareness`,v=null;if(a&&i){v=({added:e,updated:t,removed:n})=>{if(o)return;let r=[...e,...t,...n],s=i.encodeAwarenessUpdate(a,r);$.emitYjsEvent(_,l(s),{transient:!0}).catch(e=>{console.error(`Failed to emit awareness update:`,e)})},a.on(`update`,v);let e={unsubscribeAwareness:$.subscribeYjsEvents(_,e=>{o||i.applyAwarenessUpdate(a,u(e.data),`remote`)})};return{doc:r,awareness:a,destroy:()=>{o=!0,r.off(`update`,m),h(),g(),e.unsubscribeAwareness(),v&&a.off(`update`,v),i.removeAwarenessStates(a,[r.clientID],null)}}}return{doc:r,awareness:a,destroy:()=>{o=!0,r.off(`update`,m),h(),g()}}}};return $}var u=/^[a-zA-Z][a-zA-Z0-9-]*$/,d=/^[a-zA-Z0-9 \-_.+/=:*'@~%]*$/;function f(e){let t=new Map;for(let n of e.split(`;`)){let e=n.trim();if(!e)continue;let r=e.search(/\s/),i=(r===-1?e:e.slice(0,r)).toLowerCase(),a=r===-1?``:e.slice(r+1).trim().replace(/\s+/g,` `);if(!u.test(i))throw Error(`Invalid CSP directive name: ${JSON.stringify(i)}`);if(!d.test(a))throw Error(`Invalid CSP directive value for ${JSON.stringify(i)}`);t.set(i,a)}return t}function p(e,t){let n=f(e.join(`; `));if(t)for(let[e,r]of f(t))n.set(e,r);return Array.from(n,([e,t])=>t?`${e} ${t}`:e).join(`; `)}function m(e){let t=`default`,n=0,r=!1,i=new Map,a=e=>e===`granted`||e==="default"?e:`denied`,o=e=>{let t=e?.id;return typeof t==`string`?t:``},s=()=>{!r&&e.bw&&(r=!0,e.bw.setEventHandler(`__notification_click__`,e=>i.get(o(e))?.fire(`click`)),e.bw.setEventHandler(`__notification_close__`,e=>{let t=i.get(o(e));i.delete(o(e)),t?.fire(`close`)}))},c=async n=>{if(!e.bw)return t;s();try{let r=await e.bw.request({type:`NOTIFICATIONS_REQUEST_PERMISSION`,prompt:n});r.type===`NOTIFICATIONS_PERMISSION_RESPONSE`&&(t=a(r.permission))}catch{return t}return t};class l extends EventTarget{static get permission(){return t}static requestPermission(e){let t=c(!0);return e&&t.then(e),t}constructor(t,r){super(),n+=1,Object.assign(this,{title:String(t),body:typeof r?.body==`string`?r.body:``,tag:typeof r?.tag==`string`?r.tag:``,onclick:null,onclose:null,onerror:null,onshow:null,id:`notification-${n}`}),i.set(this.id,this);let a=()=>{i.delete(this.id),this.fire(`error`)};e.bw?(s(),e.bw.request({type:`NOTIFICATIONS_SHOW`,id:this.id,title:this.title,body:this.body||void 0,tag:this.tag||void 0}).then(e=>e.type===`NOTIFICATIONS_SHOW_RESPONSE`&&e.shown?this.fire(`show`):a()).catch(a)):queueMicrotask(a)}close(){i.delete(this.id)&&(e.bw?.request({type:`NOTIFICATIONS_CLOSE`,id:this.id}).catch(()=>{}),this.fire(`close`))}fire(e){let t=new Event(e);({click:this.onclick,close:this.onclose,error:this.onerror,show:this.onshow})[e]?.call(this,t),this.dispatchEvent(t)}}e.Notification=l,c(!1)}function h(e){let t=new TextEncoder().encode(e),n=``,r=8192;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,Math.min(e+r,t.length)));return btoa(n)}function g(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return new TextDecoder().decode(r)}function _({content:e,runtime:t,csp:n,restrictEgress:r,inline:i,locale:a,reportBackground:o,blobUrl:u}){let d=[`default-src 'none'`,`connect-src blob: https://unpkg.com`,`worker-src blob:`,`frame-src about:`,`form-action 'self'`,`img-src 'self' data: blob:`,`media-src blob:`,`script-src 'self' data: 'unsafe-inline' 'wasm-unsafe-eval' blob: https://unpkg.com ${`${window.location.origin}/pdf-viewer.js`}`,`style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net/npm/bulma@1.0.2/css/bulma.min.css`,`base-uri 'none'`],f=r?`default-src 'none'; connect-src blob:; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob: data:; style-src 'unsafe-inline'; img-src data: blob:; media-src blob:; worker-src blob:; frame-src about:; form-action 'none'; base-uri 'none'`:p(d,n);function _(){let e={log:console.log,error:console.error,warn:console.warn,info:console.info,debug:console.debug};[`log`,`error`,`warn`,`info`,`debug`].forEach(t=>{console[t]=(...n)=>{e[t](...n),window.bw&&window.bw.request({type:`CONSOLE_LOG`,level:t,message:n.map(e=>{try{return typeof e==`string`?e:JSON.stringify(e)}catch{return String(e)}}).join(` `),timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send console log via sandbox API:`,t)})}}),window.addEventListener(`error`,t=>{(async()=>{let n=window;if(!n.bw)return;let r=t.error?`${t.error.message}${t.error.stack?`
|
|
2
2
|
|
|
3
3
|
Stack trace:
|
|
4
4
|
`+t.error.stack:``}`:t.message;try{t.error&&t.error.stack&&(r=await c(t.error?t.error.message:t.message,t.error.stack))}catch(t){e.log(`Failed to map and enhance stack trace: ${t}`)}e.error(`Javascript Error: `,t),n.bw.request({type:`CONSOLE_LOG`,level:`fatal`,message:`JavaScript Error: ${s(r,5e4)}`,timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send JavaScript error via sandbox API:`,t)})})()}),window.addEventListener(`unhandledrejection`,t=>{(async()=>{e.error(`Uncaught rejection error:`,t);let n=window;if(!n.bw)return;let r=t.reason,i=`Unhandled Promise Rejection`,a;if(r instanceof Error)i=r.message+(r.stack?`
|
|
5
5
|
|
|
6
6
|
Stack trace:
|
|
7
|
-
`+r.stack:``),a=r.stack;else if(typeof r==`string`)i=r;else try{i=JSON.stringify(r)}catch{i=String(r)}try{a&&(i=await c(r.message,a))}catch{}n.bw.request({type:`CONSOLE_LOG`,level:`fatal`,message:`Unhandled Promise Rejection: ${s(i,5e4)}`,timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send promise rejection via sandbox API:`,t)})})()});let t=null;function n(){return t||(t=new Promise(e=>{if(window.StackTrace&&window.StackTraceGPS&&e({StackTrace:window.StackTrace,StackTraceGPS:window.StackTraceGPS}))return;let t=e=>new Promise(t=>{let n=document.createElement(`script`);n.src=e,n.async=!0,n.onload=()=>t(!0),n.onerror=()=>t(!1),document.head.appendChild(n)});Promise.all([t(`https://unpkg.com/stacktrace-js@2.0.2/dist/stacktrace.min.js`),t(`https://unpkg.com/stacktrace-gps@3.1.2/dist/stacktrace-gps.min.js`)]).then(()=>{window.StackTrace&&window.StackTraceGPS?e({StackTrace:window.StackTrace,StackTraceGPS:window.StackTraceGPS}):e(null)}),setTimeout(()=>{
|
|
7
|
+
`+r.stack:``),a=r.stack;else if(typeof r==`string`)i=r;else try{i=JSON.stringify(r)}catch{i=String(r)}try{a&&(i=await c(r.message,a))}catch{}n.bw.request({type:`CONSOLE_LOG`,level:`fatal`,message:`Unhandled Promise Rejection: ${s(i,5e4)}`,timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send promise rejection via sandbox API:`,t)})})()});let t=null;function n(){return t||(t=new Promise(e=>{if(window.StackTrace&&window.StackTraceGPS&&e({StackTrace:window.StackTrace,StackTraceGPS:window.StackTraceGPS}))return;let t=e=>new Promise(t=>{let n=document.createElement(`script`);n.src=e,n.async=!0,n.onload=()=>t(!0),n.onerror=()=>t(!1),document.head.appendChild(n)});Promise.all([t(`https://unpkg.com/stacktrace-js@2.0.2/dist/stacktrace.min.js`),t(`https://unpkg.com/stacktrace-gps@3.1.2/dist/stacktrace-gps.min.js`)]).then(()=>{window.StackTrace&&window.StackTraceGPS?e({StackTrace:window.StackTrace,StackTraceGPS:window.StackTraceGPS}):e(null)}),setTimeout(()=>{window.StackTrace&&window.StackTraceGPS||e(null)},5e3)}),t)}function r(e){if(!e)return null;let t=e.match(/[#@]\s*sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+)/);if(!t)return null;try{return JSON.parse(atob(t[1]))}catch{return null}}let i=null;function a(){return i||(i=(async()=>{try{let e=r(window.__sandboxAppCode);if(e)return e;let t=window.__sandboxSourceMapRef;if(!t||!window.bw)return null;let n=await window.bw.fetchBlob(t);return n?JSON.parse(new TextDecoder().decode(n)):null}catch{return null}})(),i)}function o(e,t){if(!e)return null;if(!t)return new e({});let n=null;async function r(){if(n||!t)return n;let e=await new Promise(e=>{let t=document.createElement(`script`);t.src=`https://unpkg.com/source-map-js@1.2.1/source-map.js`,t.async=!0,t.onload=()=>e(window.sourceMap),t.onerror=()=>e(null),document.head.appendChild(t)});if(e&&e.SourceMapConsumer)try{n=new e.SourceMapConsumer(t)}catch{n=null}return n}let i=`/inline-app.js.map`,a=new e({sourceCache:window.__sandboxSourceMapRef?{[i]:t}:{},async ajax(e){if(e===`inline://app.js`){let e=window.__sandboxAppCode||``;return window.__sandboxSourceMapRef?`${e}\n//# sourceMappingURL=${i}`:e}return``}});return a._getMapping=async e=>{let t=await r();if(!t)return e;try{let n=t.originalPositionFor({line:e.lineNumber,column:e.columnNumber});if(n&&n.source)return{functionName:e.functionName,fileName:n.source,lineNumber:n.line||e.lineNumber,columnNumber:n.column||e.columnNumber}}catch{}return e},a}function s(e,t=6e4){return e&&e.length>t?e.slice(0,t)+`...<truncated>`:e}async function c(t,r){if(!r)return t;try{let i=await n();if(!i)return t;let{StackTrace:s,StackTraceGPS:c}=i,l=Error(t);try{l.stack=r}catch{}try{s.getSource&&=()=>Promise.resolve(``),s._getSource&&=()=>Promise.resolve(``)}catch{}let u=await s.fromError(l,{offline:!0}).catch(()=>[]);if(!Array.isArray(u)||!u.length)return t;let d=o(c,await a()),f=[];for(let t of u){let n=t;if(d)try{if(n=await d.pinpoint(t).catch(()=>t),n.functionName===`react_stack_bottom_frame`)break}catch(r){e.log(`Stack trace mapping failed`,r),n=t}let r=n.functionName||t.functionName||`<anonymous>`,i=n.fileName||n.source||t.fileName||`<unknown>`,a=n.lineNumber||t.lineNumber||0,o=n.columnNumber||t.columnNumber||0;f.push(` at ${r} (${i}:${a}:${o})`)}return f.length?t+`
|
|
8
8
|
|
|
9
9
|
Parsed & Mapped Stack:
|
|
10
10
|
`+f.join(`
|
|
@@ -61,11 +61,11 @@ Parsed & Mapped Stack:
|
|
|
61
61
|
${T}
|
|
62
62
|
</body>
|
|
63
63
|
</html>
|
|
64
|
-
`}var v=class extends MessageChannel{#e;#t;#n;#r;#i=0;#a=new Map;constructor(e){super(),this.#e=e.sandboxIframe,this.#t=e.onRequest,this.#n=e.onError,this.#r=e.getInitialRoute,this.port1.onmessage=this.#c,this.port2.onmessageerror=e=>{this.#n(Error(e.data))},this.#e.contentDocument?.readyState===`complete`&&this.#o()?queueMicrotask(this.#s):this.#e.addEventListener(`load`,this.#s,{once:!0})}request=(e,t={})=>new Promise((n,r)=>{let i=++this.#i,a=t.timeoutMs&&t.timeoutMs>0?setTimeout(()=>{this.#a.delete(i),r(Error(`Sandbox request timed out after ${t.timeoutMs}ms (${e.type})`))},t.timeoutMs):void 0;this.#a.set(i,{resolve:n,reject:r,timeoutId:a});let o={requestId:i,payload:e};this.port1.postMessage(o)});close(){this.#e.removeEventListener(`load`,this.#s);for(let[e,t]of this.#a)t.timeoutId&&clearTimeout(t.timeoutId),t.reject(Error(`Sandbox message channel closed`)),this.#a.delete(e);this.port1.close(),this.port2.close()}#o=()=>{try{let e=this.#e.contentWindow?.location.href;return!!e&&e!==`about:blank`}catch{return!1}};#s=()=>{this.#e.contentWindow?this.#e.contentWindow.postMessage({type:`INIT_CHANNEL`,initialRoute:this.#r?.()??`/`},`*`,[this.port2]):this.#n(Error(`Missing contentWindow on iframe`))};#c=async e=>{`replyTo`in e.data?this.#l(e.data):this.#u(e.data)};#l=async e=>{let t=this.#a.get(e.replyTo);t?.timeoutId&&clearTimeout(t.timeoutId),t?.resolve(e.payload),this.#a.delete(e.replyTo)};#u=async e=>{let{requestId:t,payload:n}=e;if(n.type===`ERROR`)return this.#n(Error(n.message));let r;try{let e=await this.#t(n);r={replyTo:t,payload:e?.type===`GET_UI_DATA_RESPONSE`?JSON.parse(JSON.stringify(e)):e}}catch(e){r={replyTo:t,payload:{type:`ERROR`,message:e.message}}}this.port1.postMessage(r)}},y=500,b=2e3,x=`bw-ui`,S=new Set([`error`,`fatal`]),C=new Set([`continue`,`continue_next`]);function w(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function T(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function E(e){let t=new TextDecoder().decode(T(e.base64));try{return JSON.parse(t)}catch{return t}}function D(e){return{ready:!1,mode:e,log:[],submits:[]}}function O(e,t){e.ready||(e.ready=!0,k(e,t,{kind:`ready`}))}function k(e,t,n){e.log.push(n),e.log.length>y&&e.log.shift(),n.kind===`submit`&&e.submits.push(n);let r=n.kind!==`console`||S.has(n.level.toLowerCase());n.kind!==`chrome`&&r&&t.call(`host_event`,n).catch(()=>{})}function A(e){let{init:t,transport:r,state:s,controls:c}=e,l=e=>k(s,r,e),u=e=>{if(t.mode===`detached`)throw Error(`${e} is not available in a UI-only module`)},d=()=>{if(!t.runId||!t.taskRunId)throw Error(`A headless host in run mode needs the run and the task run`);return{runId:t.runId,uiTaskRunId:t.taskRunId}},f=async(e,t)=>{try{let n=await r.call(e,t);return l({kind:`bridge`,method:e,ok:!0}),n}catch(t){throw l({kind:`bridge`,method:e,ok:!1,error:t.message}),t}},p=async e=>E(await f(`blob_get`,{key:e}));return async e=>{switch(e.type){case`INVOKE_TASK`:{let{outputs:n}=t.mode===`run`?await f(`invoke_run_task`,{...a(e,d()),timeout_seconds:e.timeout}):await f(`invoke_workblock_task`,{...i(e,t),timeout_seconds:e.timeout});return{type:`INVOKE_RESPONSE`,result:await o(n,p)}}case`SAVE_BLOB`:{let t=e.blob instanceof Blob?e.blob:new Blob([new Uint8Array(e.blob)]),{blob_ref:n}=await f(`blob_put`,{content_type:t.type||`application/octet-stream`,base64:w(new Uint8Array(await t.arrayBuffer()))});return{type:`SAVE_BLOB_RESPONSE`,blobRef:n}}case`FETCH_BLOB`:return{type:`FETCH_BLOB_RESPONSE`,blob:T((await f(`blob_get`,{key:e.blobRef})).base64)};case`GET_UI_DATA`:{let e=n(t.data)?await p(t.data):t.data;return O(s,r),e==null?{type:`GET_UI_DATA_RESPONSE`}:{type:`GET_UI_DATA_RESPONSE`,data:e}}case`SET_ACTIONS`:e.actions.length>0&&u(`Actions are`),c.setActions(e.actions);return;case`SET_SUBMIT_HANDLER`:e.present&&u(`A submit handler is`),c.setSubmitVisible(e.present);return;case`CONTINUE_UI`:if(u(`Continue is`),t.mode===`run`){l({kind:`chrome`,type:e.type});return}l({kind:`submit`,via:`continue`,data:e.inputArgs});return;case`CONSOLE_LOG`:l({kind:`console`,level:e.level,message:e.message});return;case`ERROR`:throw l({kind:`page_error`,message:e.message}),Error(`Received error from sandbox ${e.message}`);case`SUBSCRIBE_CHILD_RUNS`:return{type:`CHILD_RUNS_UPDATE`,childRuns:t.mode===`run`?t.childRuns??[]:[]};case`START_CHILD`:throw Error(`Background runs are not available in a headless UI test`);case`YJS_EMIT_EVENT`:return{type:`YJS_EMIT_EVENT_RESPONSE`,event:await f(`yjs_emit_event`,{data_key:e.dataKey,data:e.data,transient:e.transient})};case`YJS_GET_EVENTS`:return{type:`YJS_GET_EVENTS_RESPONSE`,events:await f(`yjs_get_events`,{data_key:e.dataKey})};case`YJS_SUBSCRIBE_EVENTS`:await f(`yjs_subscribe_events`,{data_key:e.dataKey});return;case`YJS_UNSUBSCRIBE_EVENTS`:await f(`yjs_unsubscribe_events`,{data_key:e.dataKey});return;case`YJS_RESET_EVENTS`:throw Error(`A headless host does not reset collaborative history`);case`GRAPHLAKE_QUERY`:case`GRAPHLAKE_SUBSCRIBE`:case`GRAPHLAKE_UNSUBSCRIBE`:throw Error(`GraphLake data is not available in a headless host`);case`OPEN_PLATFORM_CHAT`:case`CLOSE_PLATFORM_CHAT`:throw l({kind:`chrome`,type:e.type}),Error(`The platform chat is not available in a headless host`);case`CREATE_CHAT`:case`UNMOUNT_CHAT`:case`SEND_CHAT`:case`LOAD_MORE_CHAT`:case`STOP_CHAT`:case`RECONNECT_CHAT`:case`RETRY_CHAT_MESSAGE`:case`DISCARD_CHAT_MESSAGE`:case`PREPARE_CHAT_WIDGET`:case`CHAT_WIDGET_REQUEST`:case`UNMOUNT_CHAT_WIDGET`:throw Error(`Embedded chat is not available in a headless host`);case`NOTIFICATIONS_REQUEST_PERMISSION`:return l({kind:`chrome`,type:e.type}),{type:`NOTIFICATIONS_PERMISSION_RESPONSE`,permission:`unsupported`};case`NOTIFICATIONS_SHOW`:return l({kind:`chrome`,type:e.type}),{type:`NOTIFICATIONS_SHOW_RESPONSE`,shown:!1};case`NOTIFICATIONS_CLOSE`:case`SET_SHORTCUTS`:case`REPORT_HEIGHT`:case`REPORT_BACKGROUND`:case`NAVIGATE_TO_STREAM`:case`ROUTE_CHANGED`:case`ROUTES_CHANGED`:l({kind:`chrome`,type:e.type});return;default:return e}}}async function j(e){let{init:t,transport:n,state:r,action:i}=e,a=e=>k(r,n,e),o;try{let t=await e.request({type:`GET_DATA`});if(t.type!==`GET_DATA_RESPONSE`){a({kind:`submit`,via:`submit`,action:i,error:`Unexpected response ${t.type}`});return}if(t.data.status===`ERROR`){a({kind:`submit`,via:`submit`,action:i,error:t.data.error??`Submission rejected`});return}o=t.data.data}catch(e){a({kind:`submit`,via:`submit`,action:i,error:e.message});return}if(t.mode!==`run`)
|
|
64
|
+
`}var v=class extends MessageChannel{#e;#t;#n;#r;#i=0;#a=new Map;constructor(e){super(),this.#e=e.sandboxIframe,this.#t=e.onRequest,this.#n=e.onError,this.#r=e.getInitialRoute,this.port1.onmessage=this.#c,this.port2.onmessageerror=e=>{this.#n(Error(e.data))},this.#e.contentDocument?.readyState===`complete`&&this.#o()?queueMicrotask(this.#s):this.#e.addEventListener(`load`,this.#s,{once:!0})}request=(e,t={})=>new Promise((n,r)=>{let i=++this.#i,a=t.timeoutMs&&t.timeoutMs>0?setTimeout(()=>{this.#a.delete(i),r(Error(`Sandbox request timed out after ${t.timeoutMs}ms (${e.type})`))},t.timeoutMs):void 0;this.#a.set(i,{resolve:n,reject:r,timeoutId:a});let o={requestId:i,payload:e};this.port1.postMessage(o)});close(){this.#e.removeEventListener(`load`,this.#s);for(let[e,t]of this.#a)t.timeoutId&&clearTimeout(t.timeoutId),t.reject(Error(`Sandbox message channel closed`)),this.#a.delete(e);this.port1.close(),this.port2.close()}#o=()=>{try{let e=this.#e.contentWindow?.location.href;return!!e&&e!==`about:blank`}catch{return!1}};#s=()=>{this.#e.contentWindow?this.#e.contentWindow.postMessage({type:`INIT_CHANNEL`,initialRoute:this.#r?.()??`/`},`*`,[this.port2]):this.#n(Error(`Missing contentWindow on iframe`))};#c=async e=>{`replyTo`in e.data?this.#l(e.data):this.#u(e.data)};#l=async e=>{let t=this.#a.get(e.replyTo);t?.timeoutId&&clearTimeout(t.timeoutId),t?.resolve(e.payload),this.#a.delete(e.replyTo)};#u=async e=>{let{requestId:t,payload:n}=e;if(n.type===`ERROR`)return this.#n(Error(n.message));let r;try{let e=await this.#t(n);r={replyTo:t,payload:e?.type===`GET_UI_DATA_RESPONSE`?JSON.parse(JSON.stringify(e)):e}}catch(e){r={replyTo:t,payload:{type:`ERROR`,message:e.message}}}this.port1.postMessage(r)}},y=500,b=2e3,x=`bw-ui`,S=new Set([`error`,`fatal`]),C=new Set([`continue`,`continue_next`]);function w(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function T(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function E(e){let t=new TextDecoder().decode(T(e.base64));try{return JSON.parse(t)}catch{return t}}function D(e){return{ready:!1,mode:e,log:[],submits:[]}}function O(e,t){e.ready||(e.ready=!0,k(e,t,{kind:`ready`}))}function k(e,t,n){e.log.push(n),e.log.length>y&&e.log.shift(),n.kind===`submit`&&e.submits.push(n);let r=n.kind!==`console`||S.has(n.level.toLowerCase());n.kind!==`chrome`&&r&&t.call(`host_event`,n).catch(()=>{})}function A(e){let{init:t,transport:r,state:s,controls:c}=e,l=e=>k(s,r,e),u=e=>{if(t.mode===`detached`)throw Error(`${e} is not available in a UI-only module`)},d=()=>{if(!t.runId||!t.taskRunId)throw Error(`A headless host in run mode needs the run and the task run`);return{runId:t.runId,uiTaskRunId:t.taskRunId}},f=async(e,t)=>{try{let n=await r.call(e,t);return l({kind:`bridge`,method:e,ok:!0}),n}catch(t){throw l({kind:`bridge`,method:e,ok:!1,error:t.message}),t}},p=async e=>E(await f(`blob_get`,{key:e}));return async e=>{switch(e.type){case`INVOKE_TASK`:{let{outputs:n}=t.mode===`run`?await f(`invoke_run_task`,{...a(e,d()),timeout_seconds:e.timeout}):await f(`invoke_workblock_task`,{...i(e,t),timeout_seconds:e.timeout});return{type:`INVOKE_RESPONSE`,result:await o(n,p)}}case`SAVE_BLOB`:{let t=e.blob instanceof Blob?e.blob:new Blob([new Uint8Array(e.blob)]),{blob_ref:n}=await f(`blob_put`,{content_type:t.type||`application/octet-stream`,base64:w(new Uint8Array(await t.arrayBuffer()))});return{type:`SAVE_BLOB_RESPONSE`,blobRef:n}}case`FETCH_BLOB`:return{type:`FETCH_BLOB_RESPONSE`,blob:T((await f(`blob_get`,{key:e.blobRef})).base64)};case`GET_UI_DATA`:{let e=n(t.data)?await p(t.data):t.data;return O(s,r),e==null?{type:`GET_UI_DATA_RESPONSE`}:{type:`GET_UI_DATA_RESPONSE`,data:e}}case`SET_ACTIONS`:e.actions.length>0&&u(`Actions are`),c.setActions(e.actions);return;case`SET_SUBMIT_HANDLER`:e.present&&u(`A submit handler is`),c.setSubmitVisible(e.present);return;case`CONTINUE_UI`:if(u(`Continue is`),t.mode===`run`){l({kind:`chrome`,type:e.type});return}l({kind:`submit`,via:`continue`,data:e.inputArgs});return;case`CONSOLE_LOG`:l({kind:`console`,level:e.level,message:e.message});return;case`ERROR`:throw l({kind:`page_error`,message:e.message}),Error(`Received error from sandbox ${e.message}`);case`SUBSCRIBE_CHILD_RUNS`:return{type:`CHILD_RUNS_UPDATE`,childRuns:t.mode===`run`?t.childRuns??[]:[]};case`START_CHILD`:throw Error(`Background runs are not available in a headless UI test`);case`YJS_EMIT_EVENT`:return{type:`YJS_EMIT_EVENT_RESPONSE`,event:await f(`yjs_emit_event`,{data_key:e.dataKey,data:e.data,transient:e.transient})};case`YJS_GET_EVENTS`:return{type:`YJS_GET_EVENTS_RESPONSE`,events:await f(`yjs_get_events`,{data_key:e.dataKey})};case`YJS_SUBSCRIBE_EVENTS`:await f(`yjs_subscribe_events`,{data_key:e.dataKey});return;case`YJS_UNSUBSCRIBE_EVENTS`:await f(`yjs_unsubscribe_events`,{data_key:e.dataKey});return;case`YJS_RESET_EVENTS`:throw Error(`A headless host does not reset collaborative history`);case`GRAPHLAKE_QUERY`:case`GRAPHLAKE_SUBSCRIBE`:case`GRAPHLAKE_UNSUBSCRIBE`:throw Error(`GraphLake data is not available in a headless host`);case`OPEN_PLATFORM_CHAT`:case`CLOSE_PLATFORM_CHAT`:throw l({kind:`chrome`,type:e.type}),Error(`The platform chat is not available in a headless host`);case`CREATE_CHAT`:case`UNMOUNT_CHAT`:case`SEND_CHAT`:case`TRANSCRIBE_CHAT_AUDIO`:case`QUEUE_CHAT_MESSAGE`:case`EDIT_QUEUED_CHAT_MESSAGE`:case`REMOVE_QUEUED_CHAT_MESSAGE`:case`SEND_QUEUED_CHAT_MESSAGE`:case`LOAD_MORE_CHAT`:case`STOP_CHAT`:case`RECONNECT_CHAT`:case`RETRY_CHAT_MESSAGE`:case`DISCARD_CHAT_MESSAGE`:case`PREPARE_CHAT_WIDGET`:case`CHAT_WIDGET_REQUEST`:case`UNMOUNT_CHAT_WIDGET`:throw Error(`Embedded chat is not available in a headless host`);case`NOTIFICATIONS_REQUEST_PERMISSION`:return l({kind:`chrome`,type:e.type}),{type:`NOTIFICATIONS_PERMISSION_RESPONSE`,permission:`unsupported`};case`NOTIFICATIONS_SHOW`:return l({kind:`chrome`,type:e.type}),{type:`NOTIFICATIONS_SHOW_RESPONSE`,shown:!1};case`NOTIFICATIONS_CLOSE`:case`SET_SHORTCUTS`:case`REPORT_HEIGHT`:case`REPORT_BACKGROUND`:case`NAVIGATE_TO_STREAM`:case`ROUTE_CHANGED`:case`ROUTES_CHANGED`:l({kind:`chrome`,type:e.type});return;default:return e}}}async function j(e){let{init:t,transport:n,state:r,action:i}=e,a=e=>k(r,n,e),o;try{let t=await e.request({type:`GET_DATA`});if(t.type!==`GET_DATA_RESPONSE`){a({kind:`submit`,via:`submit`,action:i,error:`Unexpected response ${t.type}`});return}if(t.data.status===`ERROR`){a({kind:`submit`,via:`submit`,action:i,error:t.data.error??`Submission rejected`});return}o=t.data.data}catch(e){a({kind:`submit`,via:`submit`,action:i,error:e.message});return}if(t.mode!==`run`)a({kind:`submit`,via:`submit`,action:i,data:o});else try{await n.call(`continue_ui`,{task_id:t.taskRunId,data:o}),a({kind:`submit`,via:`submit`,action:i,data:o,sent:!0})}catch(e){a({kind:`submit`,via:`submit`,action:i,data:o,sent:!1,error:e.message})}}var M=`
|
|
65
65
|
html, body { margin: 0; height: 100%; font-family: system-ui, sans-serif; }
|
|
66
66
|
#bw-frame { height: 100%; }
|
|
67
67
|
#bw-frame.with-controls { height: calc(100% - 52px); }
|
|
68
68
|
#bw-frame iframe { border: 0; width: 100%; height: 100%; display: block; }
|
|
69
69
|
#bw-controls { height: 52px; box-sizing: border-box; display: flex; gap: 8px; align-items: center; padding: 0 12px; border-top: 1px solid #e5e5e5; }
|
|
70
70
|
#bw-controls[hidden] { display: none; }
|
|
71
|
-
`;function N(e,t){let n=D(e.mode),r=document,i=r.createElement(`style`);i.textContent=M,r.head.appendChild(i);let a=r.createElement(`div`);a.id=`bw-frame`;let o=r.createElement(`div`);o.id=`bw-controls`,o.hidden=!0;let s=r.createElement(`button`);s.type=`button`,s.textContent=`Submit`,s.hidden=!0,o.appendChild(s),r.body.append(a,o);let c=r.createElement(`iframe`);c.name=x,c.title=`Task UI`,c.setAttribute(`sandbox`,`allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-top-navigation-by-user-activation`),c.srcdoc=_({content:e.bundle,runtime:e.runtime,csp:e.csp,locale:e.locale??`en`}),c.addEventListener(`load`,()=>setTimeout(()=>O(n,t),b),{once:!0}),a.appendChild(c);let l=[],u=()=>{let e=!s.hidden||l.length>0;o.hidden=!e,a.classList.toggle(`with-controls`,e)},d=e=>k(n,t,e),f=new v({sandboxIframe:c,onRequest:A({init:e,transport:t,state:n,controls:{setSubmitVisible:e=>{s.hidden=!e,u()},setActions:e=>{l.forEach(e=>e.remove()),l=e.map(e=>{let t=r.createElement(`button`);return t.type=`button`,t.textContent=e.label,t.disabled=e.disabled??!1,t.onclick=()=>{
|
|
71
|
+
`;function N(e,t){let n=D(e.mode),r=document,i=r.createElement(`style`);i.textContent=M,r.head.appendChild(i);let a=r.createElement(`div`);a.id=`bw-frame`;let o=r.createElement(`div`);o.id=`bw-controls`,o.hidden=!0;let s=r.createElement(`button`);s.type=`button`,s.textContent=`Submit`,s.hidden=!0,o.appendChild(s),r.body.append(a,o);let c=r.createElement(`iframe`);c.name=x,c.title=`Task UI`,c.setAttribute(`sandbox`,`allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-top-navigation-by-user-activation`),c.srcdoc=_({content:e.bundle,runtime:e.runtime,csp:e.csp,locale:e.locale??`en`}),c.addEventListener(`load`,()=>setTimeout(()=>O(n,t),b),{once:!0}),a.appendChild(c);let l=[],u=()=>{let e=!s.hidden||l.length>0;o.hidden=!e,a.classList.toggle(`with-controls`,e)},d=e=>k(n,t,e),f=new v({sandboxIframe:c,onRequest:A({init:e,transport:t,state:n,controls:{setSubmitVisible:e=>{s.hidden=!e,u()},setActions:e=>{l.forEach(e=>e.remove()),l=e.map(e=>{let t=r.createElement(`button`);return t.type=`button`,t.textContent=e.label,t.disabled=e.disabled??!1,t.onclick=()=>{C.has(e.key)?p(e.key):f.request({type:`ON_ACTION`,key:e.key}).catch(e=>{d({kind:`page_error`,message:e.message})})},o.appendChild(t),t}),u()}}}),onError:e=>d({kind:`page_error`,message:e.message})}),p=r=>j({init:e,transport:t,state:n,action:r,request:e=>f.request(e,{timeoutMs:3e4})});return s.onclick=()=>void p(),t.subscribe(e=>{let t=e.type===`yjs_event`?`__yjs_event__`:`__yjs_events_reset__`;f.request({type:`ON_EVENT`,event:t,data:e.data}).catch(()=>{})}),n}function P(e){return{call:(t,n)=>e(t,n),subscribe:()=>{}}}function F(e,t){return{call:async(t,n)=>{let r=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({method:t,body:n})}),i={};try{i=await r.json()}catch{throw Error(`Bridge call ${t} failed with HTTP status ${r.status}`)}if(!r.ok||!i.ok)throw Error(i.error??`Bridge call ${t} failed with HTTP status ${r.status}`);return i.result},subscribe:e=>{if(!t)return;let n=new EventSource(t);n.onmessage=t=>{e(JSON.parse(t.data))}}}}var I=document.currentScript?.dataset??{};function L(){if(typeof window.bwTransport==`function`)return P(window.bwTransport);if(I.bridgeUrl)return F(I.bridgeUrl,I.eventsUrl);throw Error(`The headless host has no transport: define window.bwTransport or data-bridge-url`)}var R={start(e){if(R.state)throw Error(`The headless host already started`);return R.state=N(e,L()),R.state}};window.bwHeadlessHost=R,I.initUrl&&fetch(I.initUrl).then(e=>{if(!e.ok)throw Error(`Loading ${I.initUrl} failed with HTTP status ${e.status}`);return e.json()}).then(e=>R.start(e)).catch(e=>{document.body.textContent=e.message,console.error(e)})})();
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publisher": "beyondwork",
|
|
4
4
|
"displayName": "Beyond Work",
|
|
5
5
|
"description": "Tool for interacting with Beyond Work workblocks from VS Code and CLI.",
|
|
6
|
-
"version": "0.1.
|
|
6
|
+
"version": "0.1.55",
|
|
7
7
|
"vsce": {
|
|
8
8
|
"baseContentUrl": "https://github.com/bwllaming/code/blob/HEAD/src/vscode/beyondwork",
|
|
9
9
|
"baseImagesUrl": "https://github.com/bwllaming/code/raw/HEAD/src/vscode/beyondwork"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: bw-workblock
|
|
3
|
-
description: Create or edit a Beyond Work workblock that lives on a tenant, from a coding agent session, with `wb-cli`. Use whenever the user asks to create, change, fix, extend, inspect, run or validate a workblock on a tenant, names a Studio URL (https://<tenant>/w/studio/detail/<id> or /w/studio/s/<id>), a Space URL (https://<tenant>/w/spaces/<space>) or a workblock id, wants a Space's menu changed or a workblock added to a Space, wants a change pushed to a workblock version, or has several agents build one workblock and combine their work. Covers credentials, create/clone/checkout/pull/push, validation, unit tests, runs, version branches (which Studio calls versions), merging and resolving conflicts, publishing to another branch, Spaces, and where the authoring knowledge (skills, docs) lands in the checkout.
|
|
3
|
+
description: Create or edit a Beyond Work workblock that lives on a tenant, from a coding agent session, with `wb-cli`. Use whenever the user asks to create, change, fix, extend, inspect, run or validate a workblock on a tenant, names a Studio URL (https://<tenant>/w/studio/detail/<id> or /w/studio/s/<id>), a Space URL (https://<tenant>/w/spaces/<space>) or a workblock id, wants a Space's menu changed or a workblock added to a Space, wants a change pushed to a workblock version, or has several agents build one workblock and combine their work. Covers credentials, create/clone/checkout/pull/push, validation, unit tests, runs, chats with agent modules, version branches (which Studio calls versions), merging and resolving conflicts, publishing to another branch, Spaces, and where the authoring knowledge (skills, docs) lands in the checkout.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# bw-workblock
|
|
@@ -88,17 +88,26 @@ follow the confirmation warning above before sending the API request.
|
|
|
88
88
|
intent from its message, in `git log`, `wb-cli log` and Studio. Studio's own messages use the
|
|
89
89
|
same shape.
|
|
90
90
|
7. **Prove it.** `wb-cli test` and `wb-cli run` check only what you pushed, and print the commit they
|
|
91
|
-
ran on.
|
|
92
|
-
`wb-cli
|
|
93
|
-
|
|
91
|
+
ran on. They, `wb-cli ui` and `wb-cli chat` name a module or task by its `id` in `manifest.yaml`,
|
|
92
|
+
never by name. Run `wb-cli test [<module-id>]` when the module has tests, then `wb-cli run
|
|
93
|
+
<module-id>`, or `wb-cli run <task-id> --inputs '{...}'`, for what you changed. `wb-cli test`
|
|
94
|
+
sends one request for each module, with a limit of 180 seconds. When a module's tests need longer,
|
|
95
|
+
or a request fails, use `wb-cli test --by-file`: it sends one request for each test file, and
|
|
96
|
+
when a request fails, it stops and prints the commands that run the rest. `wb-cli run
|
|
97
|
+
<task-id>` calls an invokable task without a run. It returns no run id and no logs, and
|
|
94
98
|
the active run stays unchanged. A single task takes the outputs of the module's latest run, and
|
|
95
99
|
`--inputs` gives only what no task of that run produced.
|
|
96
|
-
A run stops at a task UI. Check each task UI that you changed with `wb-cli ui <
|
|
100
|
+
A run stops at a task UI. Check each task UI that you changed with `wb-cli ui <task-id>`,
|
|
97
101
|
which shows it in a headless browser with Playwright. Look at its screenshots. To go through a
|
|
98
|
-
run, open each waiting UI with `wb-cli ui <
|
|
102
|
+
run, open each waiting UI with `wb-cli ui <task-id> --in-run` and press Submit.
|
|
99
103
|
`references/browser-validation.md` describes both. Studio's Start and its "Configure & Run
|
|
100
|
-
module" form need a browser tool in the user's signed-in browser.
|
|
101
|
-
|
|
104
|
+
module" form need a browser tool in the user's signed-in browser.
|
|
105
|
+
An agent module acts only when someone chats with it. Prove it with `wb-cli chat <module-id> "<what
|
|
106
|
+
a user would write>"` (`--persona <id>` picks one of its `agent_configs`): the agent loads your pushed branch, and the command prints its reply, each
|
|
107
|
+
tool it called with the arguments and result, and the conversation id. Follow up with `wb-cli chat
|
|
108
|
+
-c <conversation> "<message>"`. A conversation's agent keeps the definition that it loaded for
|
|
109
|
+
the conversation's first message, so after a push, start a new conversation. `wb-cli chat -c
|
|
110
|
+
<conversation>` shows the whole conversation. What you did not see run, report as not checked.
|
|
102
111
|
8. **Publish** with `wb-cli push --to <target>`. It moves the target to your pushed commit. When the
|
|
103
112
|
target has commits that you lack, it refuses: run `wb-cli merge <target> -m "<what you took in>"`,
|
|
104
113
|
settle any conflicts (see Working beside others), prove the merged commit again as step 7 says,
|
|
@@ -19,9 +19,9 @@ Check the UI in these cases:
|
|
|
19
19
|
|
|
20
20
|
| Target | Mode | The page shows | Data |
|
|
21
21
|
| --- | --- | --- | --- |
|
|
22
|
-
| `<
|
|
23
|
-
| `<module>` | `detached` | The UI of a UI-only module, as a Space shows it. | The data that the module gives its UI. |
|
|
24
|
-
| `<
|
|
22
|
+
| `<task-id>` | `preview` | The task's UI, with Submit and the UI's action buttons below it. | The JSON file of `--data <file>`. Without `--data`: the data that the task showed in the workspace's latest run. |
|
|
23
|
+
| `<module-id>` | `detached` | The UI of a UI-only module, as a Space shows it. | The data that the module gives its UI. |
|
|
24
|
+
| `<task-id> --in-run`, or `<module-id> --in-run` | `run` | The task UI that waits in the workspace's run, as Studio shows it, with Submit and the UI's action buttons below it. | The data of that run. |
|
|
25
25
|
|
|
26
26
|
- The tenant builds the UI from the workspace's last commit, not from your files. Push first. The command
|
|
27
27
|
refuses unpushed edits, an unfinished merge, or a workspace at a different commit.
|
|
@@ -61,9 +61,9 @@ Run each command from inside the checkout. `wb-cli ui` prints one JSON object pe
|
|
|
61
61
|
|
|
62
62
|
| Route | Command | It ends |
|
|
63
63
|
| --- | --- | --- |
|
|
64
|
-
| A screenshot | `wb-cli ui <
|
|
65
|
-
| A Playwright script | `wb-cli ui <
|
|
66
|
-
| Playwright MCP, or your own browser tool | `wb-cli ui <
|
|
64
|
+
| A screenshot | `wb-cli ui <id> --screenshot ../shots/review.png` | After the PNG is written. |
|
|
65
|
+
| A Playwright script | `wb-cli ui <id> --exec ../drive.mjs` | After the script returns. Exit 1 when it throws. |
|
|
66
|
+
| Playwright MCP, or your own browser tool | `wb-cli ui <id>` in the background, then open the URL of the `ready` line. | On Ctrl-C (SIGINT) or SIGTERM. Exit 1 when the tenant closes the connection. |
|
|
67
67
|
|
|
68
68
|
`--exec` and `--screenshot` can go together: the script runs first. The screenshot shows the whole
|
|
69
69
|
UI, up to 8000 px high.
|
|
@@ -114,9 +114,9 @@ Compare each `submit` with the outputs that the request asks for.
|
|
|
114
114
|
|
|
115
115
|
`wb-cli ui` without `--in-run` never continues a run. To finish a run that waits at a task UI:
|
|
116
116
|
|
|
117
|
-
1. Start the run with `wb-cli run <module>`. It reports `waiting` when a task UI waits.
|
|
117
|
+
1. Start the run with `wb-cli run <module-id>`. It reports `waiting` when a task UI waits.
|
|
118
118
|
2. Open that UI in the run and press Submit, as a person would:
|
|
119
|
-
`wb-cli ui <
|
|
119
|
+
`wb-cli ui <task-id> --in-run --exec ../submit.mjs`. The script fills the UI and clicks
|
|
120
120
|
`page.getByRole("button", { name: "Submit" })`. The `submit` event shows `sent: true` when the run
|
|
121
121
|
received the data.
|
|
122
122
|
3. Run `wb-cli run --wait-for latest`. It prints the state and the outputs of every task. Compare the
|