@beyondwork/wb-cli 0.1.42 → 0.1.44
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 +19 -0
- package/out/cli.js +659 -188
- package/out/extension.js +142 -141
- package/out/headless-host.js +1 -1
- package/package.json +5 -6
- package/wb-cli/skills/bw-workblock/SKILL.md +154 -63
- package/wb-cli/skills/bw-workblock/references/browser-validation.md +4 -4
package/out/headless-host.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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(()=>{}))}},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()=>{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(()=>{}))}},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?`
|
|
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?`
|
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.44",
|
|
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"
|
|
@@ -121,15 +121,13 @@
|
|
|
121
121
|
"@types/node": "~20.19.0",
|
|
122
122
|
"@types/vscode": "^1.94.0",
|
|
123
123
|
"@types/ws": "^8.5.12",
|
|
124
|
-
"@typescript-eslint/eslint-plugin": "^8.8.1",
|
|
125
|
-
"@typescript-eslint/parser": "^8.8.1",
|
|
126
124
|
"@vscode/test-cli": "^0.0.15",
|
|
127
125
|
"@vscode/test-electron": "^2.4.1",
|
|
128
126
|
"@vscode/vsce": "^3.9.2",
|
|
129
127
|
"esbuild": "^0.27.0",
|
|
130
|
-
"eslint": "^9.12.0",
|
|
131
128
|
"npm": "^10.7.0",
|
|
132
|
-
"
|
|
129
|
+
"oxlint": "1.89.0",
|
|
130
|
+
"typescript": "^7.0.2"
|
|
133
131
|
},
|
|
134
132
|
"dependencies": {
|
|
135
133
|
"@inquirer/prompts": "^8.5.2",
|
|
@@ -155,11 +153,12 @@
|
|
|
155
153
|
"scripts": {
|
|
156
154
|
"compile": "pnpm run check-types && node esbuild.js --production",
|
|
157
155
|
"check-types": "tsc --noEmit",
|
|
156
|
+
"lint": "oxlint .",
|
|
158
157
|
"watch": "node esbuild.js --watch",
|
|
159
158
|
"watch:esbuild": "node esbuild.js --watch",
|
|
160
159
|
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
|
|
161
160
|
"package": "pnpm run check-types && node esbuild.js --production",
|
|
162
161
|
"vsix": "bazel build //src/vscode/beyondwork:package",
|
|
163
|
-
"test": "pnpm run check-types && node esbuild.js --tests && mocha 'out/lib/**/*.test.js'"
|
|
162
|
+
"test": "pnpm run check-types && node esbuild.js --tests && mocha --timeout 10000 'out/lib/**/*.test.js'"
|
|
164
163
|
}
|
|
165
164
|
}
|
|
@@ -1,26 +1,58 @@
|
|
|
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>) or a workblock id,
|
|
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>) or a workblock id, 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, and where the authoring knowledge (skills, docs) lands in the checkout.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# bw-workblock
|
|
7
7
|
|
|
8
|
-
`wb-cli` (the npm package `@beyondwork/wb-cli`) turns a workblock on a tenant into local
|
|
9
|
-
saves them back
|
|
8
|
+
`wb-cli` (the npm package `@beyondwork/wb-cli`) turns a branch of a workblock on a tenant into local
|
|
9
|
+
files and saves them back to that branch as commits. In the Beyond Work monorepo, call the wrapper by
|
|
10
10
|
its path, `<monorepo>/bin/wb-cli`, wherever this skill says `wb-cli`, and put checkouts outside the
|
|
11
11
|
monorepo. `clone` and `create` write the checkout to the directory you give them. Every other verb
|
|
12
12
|
acts on the checkout that holds the current directory, so run it from there. The request is the whole
|
|
13
|
-
job,
|
|
14
|
-
|
|
13
|
+
job, pushes included: do not stop to ask. Deployment to `main` and branch deletion stay in Studio.
|
|
14
|
+
|
|
15
|
+
## Branches and the user's words
|
|
16
|
+
|
|
17
|
+
wb-cli works on branches of a workblock, as git does. This skill uses three kinds of branch, and
|
|
18
|
+
Studio and its users name them differently. Use their words when you talk to the user.
|
|
19
|
+
|
|
20
|
+
| Branch | In this skill | Studio and its users |
|
|
21
|
+
| --- | --- | --- |
|
|
22
|
+
| `main` | `main` | The deployed workblock |
|
|
23
|
+
| `features/<name>` | Version branch (the API's `feature_branch`) | A version |
|
|
24
|
+
| `features/<name>@stream/<workspace-id>` | Conversation branch | A conversation in a Studio workspace |
|
|
25
|
+
|
|
26
|
+
"Branch" alone means any of the three. wb-cli adds `features/` to a name you give it, so
|
|
27
|
+
`integration` stands for `features/integration`. The option `create --new-version` keeps the
|
|
28
|
+
Studio word.
|
|
15
29
|
|
|
16
30
|
## The loop
|
|
17
31
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
32
|
+
Every change goes into a new version branch that you start, named after what you implement: a few
|
|
33
|
+
lowercase words joined by hyphens, such as `due-date-field` or `summary-full-stop`. Make no change
|
|
34
|
+
in an existing version branch, `initial-version` included, unless the request tells you to work in
|
|
35
|
+
that version branch. The reason: when a browser check opens your work in Studio, Studio can publish
|
|
36
|
+
your conversation to its version branch before the check ends, also when a check fails. Give each agent a
|
|
37
|
+
separate checkout directory, even when agents share one machine. A request that only checks a
|
|
38
|
+
branch changes nothing: clone that branch and skip `checkout -b`.
|
|
39
|
+
|
|
40
|
+
`wb-cli push` saves your work: no other branch changes, and `test` and `run` check what you pushed.
|
|
41
|
+
`wb-cli push --to <target>` publishes your pushed commit to the target: the version branch that the
|
|
42
|
+
request names, such as `integration`, or, when the request names none, your new version branch.
|
|
43
|
+
Report the target,
|
|
44
|
+
so that the user can deploy it from Studio.
|
|
45
|
+
|
|
46
|
+
1. **Get the files.** For a new workblock, `wb-cli create <tenant-host> "<name>" <dir> --new-version
|
|
47
|
+
<name of what you build> -m "<what it is for>"` makes it, on a new version branch with that name.
|
|
48
|
+
Otherwise clone the branch that your work starts from: the target, `wb-cli clone <studio-url> <dir>
|
|
49
|
+
--branch <target>`, or, when the request names no target, `main`, or, while `main` is empty, the
|
|
50
|
+
version branch that changed last (`wb-cli branches <studio-url>`). To continue work that a person left in
|
|
51
|
+
a Studio workspace (`/w/studio/s/<id>`), clone that URL without `--branch`; the target is then the
|
|
52
|
+
version branch that the workspace belongs to. Then start your version branch: `wb-cli checkout -b <name>`. When
|
|
53
|
+
the name exists, wb-cli refuses: add a word that tells your change apart. When the request tells
|
|
54
|
+
you to work in an existing version branch, skip `checkout -b`: it is the target, and your
|
|
55
|
+
browser checks can publish to it. `.bw/workblock.json` binds the checkout to the platform; do not edit it.
|
|
24
56
|
2. **Read before writing.** `AGENTS.md`, then the `.skills/` entries for the area you touch, then
|
|
25
57
|
`.docs/docs.md` for each platform API you call. The platform changes faster than your memory of
|
|
26
58
|
it, and validation catches only part of what the docs would have told you.
|
|
@@ -32,33 +64,45 @@ done from Studio.
|
|
|
32
64
|
4. **Edit.** A test is an entry under the module's `tests:` (`name`, `type: pytest`) plus
|
|
33
65
|
`<module>/tests/<name>.py`. A task's code reaches a test as a pytest fixture, not as a module to
|
|
34
66
|
import: `def test_x(flag_gaps): assert flag_gaps.flag(...)` gets task "Flag Gaps", the parameter
|
|
35
|
-
being the task name in lower case with spaces replaced by underscores. A
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
67
|
+
being the task name in lower case with spaces replaced by underscores. A new module, task or test
|
|
68
|
+
needs no `id` line, because wb-cli derives the id from its name. Never copy the `id` of another
|
|
69
|
+
entry. A file no manifest entry claims is not pushed. Change only what the request asks for: no
|
|
70
|
+
fixes to nearby tasks, no tidying of files you did not need to touch, and no tasks beyond the
|
|
71
|
+
request and the experience of step 3.
|
|
39
72
|
5. **Validate** with `wb-cli validate` until it reports no errors. Warnings are advisory.
|
|
40
|
-
6. **
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
73
|
+
6. **Push** with `wb-cli push -m "<what changed>" -m "<why>"`. Each push saves one commit, and other
|
|
74
|
+
agents and people read its message with `wb-cli log` and in Studio.
|
|
75
|
+
7. **Prove it.** `wb-cli test` and `wb-cli run` check only what you pushed, and print the commit they
|
|
76
|
+
ran on. Run `wb-cli test [<module>]` when the module has tests, then `wb-cli run <module>`, or
|
|
77
|
+
`wb-cli run <module>/<task> --inputs '{...}'`, for what you changed. Since wb-cli 0.1.36, `wb-cli
|
|
78
|
+
run <module>/<task>` calls an invokable task without a run. It returns no run id and no logs, and
|
|
79
|
+
the active run stays unchanged. A single task takes the outputs of the module's latest run, and
|
|
80
|
+
`--inputs` gives only what no task of that run produced.
|
|
81
|
+
A run stops at a task UI. Check each task UI that you changed with `wb-cli ui <module>/<task>`,
|
|
82
|
+
which shows it in a headless browser with Playwright. Look at its screenshots. To go through a
|
|
83
|
+
run, open each waiting UI with `wb-cli ui <module>/<task> --in-run` and press Submit.
|
|
84
|
+
`references/browser-validation.md` describes both. Studio's Start and its "Configure & Run
|
|
85
|
+
module" form need a browser tool in the user's signed-in browser. What you did not see run,
|
|
86
|
+
report as not checked.
|
|
87
|
+
8. **Publish** with `wb-cli push --to <target>`. It moves the target to your pushed commit. When the
|
|
88
|
+
target has commits that you lack, it refuses: run `wb-cli merge <target> -m "<what you took in>"`,
|
|
89
|
+
settle any conflicts (see Working beside others), prove the merged commit again as step 7 says,
|
|
90
|
+
and push --to again. The server refuses publication if the target changes after the CLI checks it.
|
|
91
|
+
Publication runs server validation on the saved commit and refuses errors. It refuses data-model changes
|
|
92
|
+
because this API cannot validate them. Use `push --update` to validate and publish those changes
|
|
93
|
+
to your own version branch. To bring them into another version branch, clone that branch, run
|
|
94
|
+
`wb-cli push` without edits to give the checkout a conversation branch, `wb-cli merge` your version
|
|
95
|
+
branch, validate and test the result, and publish it with `wb-cli push --update`.
|
|
96
|
+
Publication does not require stored test results: report only checks that ran on the published commit.
|
|
97
|
+
9. **Report** the target's Studio URL, your version branch, the files changed, each check with the commit it
|
|
98
|
+
ran on (or why there was none), and the commit that you published. As proof of a publish, list
|
|
99
|
+
only the checks that ran on the published commit.
|
|
56
100
|
|
|
57
101
|
## Credentials
|
|
58
102
|
|
|
59
|
-
`wb-cli tenants
|
|
60
|
-
`~/.config/beyondwork/credentials.json`, with the user each one
|
|
61
|
-
sign-in or an API token. You never handle a credential: do not open the credentials file, source an
|
|
103
|
+
`wb-cli tenants <host>` checks the credential of one tenant and names the user it belongs to; without
|
|
104
|
+
a host it lists every tenant in `~/.config/beyondwork/credentials.json`, with the user each one
|
|
105
|
+
belongs to and whether it is a sign-in or an API token. You never handle a credential: do not open the credentials file, source an
|
|
62
106
|
environment file that holds one, ask for it, or put it in a command, because your transcript and the
|
|
63
107
|
shell history are kept. When a tenant has no credential, or wb-cli reports that the sign-in expired
|
|
64
108
|
or was revoked, ask the user to run `wb-cli login <host>` in their own terminal. `login` waits for a
|
|
@@ -67,34 +111,81 @@ such as a devenv tenant, pipe an API token from a tool that already holds it int
|
|
|
67
111
|
`wb-cli add-tenant <host>`, because the token then reaches neither your transcript nor a command
|
|
68
112
|
line.
|
|
69
113
|
|
|
70
|
-
##
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
114
|
+
## Local Git and platform history
|
|
115
|
+
|
|
116
|
+
wb-cli records local Git snapshots of the authoring files when it clones, pulls, merges, or pushes.
|
|
117
|
+
These snapshots have their own commit IDs and history, separate from the platform's commits.
|
|
118
|
+
`git status` lists local edits, including new files; `git diff HEAD` shows edits to tracked files.
|
|
119
|
+
`git log -p` shows changes between local snapshots.
|
|
120
|
+
Use `wb-cli log [<branch>]` for platform commit IDs and the messages that authors supplied.
|
|
121
|
+
Local Git commit IDs cannot be used as platform commit references.
|
|
122
|
+
|
|
123
|
+
## Pushes and refusals
|
|
124
|
+
|
|
125
|
+
`main` is empty until the first deploy. Your pushes go to the conversation branch of your version branch,
|
|
126
|
+
`features/<name>@stream/<workspace-id>`: wb-cli names it in its output, and `wb-cli branches
|
|
127
|
+
<studio-url>` lists every branch. Studio or another checkout can still save to that branch; a stale
|
|
128
|
+
push refuses instead of replacing the newer save. When the CLI refuses (exit 3), its message names
|
|
129
|
+
the remedy. Do not pipe `merge` or `push` through `tail`, because the pipe hides the exit code.
|
|
130
|
+
|
|
131
|
+
- **Stale snapshot.** Someone saved to your work after you read it, for example Studio or a person.
|
|
132
|
+
Run `wb-cli pull`: it keeps their change and puts your edits back on top. Resolve any conflict
|
|
133
|
+
markers, then validate, push, and prove the pushed commit again.
|
|
134
|
+
- **Local merge conflict.** Nothing was saved. Resolve the conflict markers in the named local files,
|
|
135
|
+
then validate and push again.
|
|
136
|
+
|
|
137
|
+
## Working beside others
|
|
138
|
+
|
|
139
|
+
Other agents and people can change the workblock while you work. Choose the flow that fits the
|
|
140
|
+
request. For example, use one version branch for the whole change, or one for each agent, which one
|
|
141
|
+
agent then merges. Separate version branches keep each agent's pushes and checks apart until the
|
|
142
|
+
merge. A target version branch that does not exist yet starts with `wb-cli checkout -b <name>` in a
|
|
143
|
+
checkout of the commit that it starts from. Whatever the flow, wb-cli guarantees:
|
|
144
|
+
|
|
145
|
+
- `push` saves only on top of the commit that you read. If someone saved after that, it refuses,
|
|
146
|
+
and `pull` takes in their work.
|
|
147
|
+
- `merge --continue` writes only if both branches still point at the commits that you resolved.
|
|
148
|
+
- `push --to` moves a version branch only forward to your saved commit, and only if no one moved it
|
|
149
|
+
after wb-cli read it.
|
|
150
|
+
|
|
151
|
+
The building blocks:
|
|
152
|
+
|
|
153
|
+
- **Push edits only to your own version branch.** Another agent's version branch, a shared target, and a person's
|
|
154
|
+
Studio conversation are shared. Merge their work into your checkout, then publish to the target
|
|
155
|
+
with `wb-cli push --to`. A data-model change reaches the target through a conversation branch of
|
|
156
|
+
the target instead (step 8).
|
|
157
|
+
- **Conflicts.** `wb-cli merge` leaves the authoring files unchanged until the merge succeeds.
|
|
158
|
+
Text conflicts wait under `.bw/merge/files/`, in the platform's layout (one `manifest.yaml` for each
|
|
159
|
+
module and task). Resolve them there. Local Git ignores these files: `git status` can stay clean,
|
|
160
|
+
and `git diff` and editor Git conflict tools do not show the resolutions.
|
|
161
|
+
Local tests still read the unchanged authoring files.
|
|
162
|
+
Combine both sides shown by the conflict markers; use `wb-cli log <branch>` for each branch's platform history.
|
|
163
|
+
Remove the markers, then run
|
|
164
|
+
`wb-cli merge --continue -m "<what you merged>" -m "<how you settled each conflict>"`.
|
|
165
|
+
If either branch moved, the resolution is refused; abort, merge again, and resolve against the new commits.
|
|
166
|
+
The checkout pulls a successful merge. A binary file, or one that a side deleted or
|
|
167
|
+
renamed, takes a whole side: `--keep <path>` or `--take <path>`. An edit that you make in the
|
|
168
|
+
checkout while the merge waits is not part of the merge commit: `--continue` puts it back on top,
|
|
169
|
+
and you push it after. `wb-cli test` and `wb-cli run` refuse while the merge is pending.
|
|
170
|
+
After `--continue`, validate, test, and run the merged workblock. `wb-cli merge --abort` gives up.
|
|
171
|
+
- **Studio conversations.** Work that a person did not publish is on a conversation. Take it in with
|
|
172
|
+
`wb-cli merge features/<name>@stream/<id> -m "<what you took in>"`. Never push to it.
|
|
173
|
+
- **Version branches you made.** Delete abandoned ones from Studio, where they are versions. The CLI
|
|
174
|
+
does not delete branches.
|
|
175
|
+
- **Publishing a snapshot.** `push --to` publishes the checkout's saved commit. Newer changes on
|
|
176
|
+
its source branch or another version branch stay there. To include them, pull your source branch
|
|
177
|
+
or merge the other version branch first.
|
|
178
|
+
- **`main`.** Publish to the target version branch, then report its Studio URL and the checks you ran. The
|
|
179
|
+
user deploys it from Studio; `wb-cli push --to main` is refused.
|
|
180
|
+
|
|
181
|
+
## Spaces and `wb-cli use`
|
|
182
|
+
|
|
183
|
+
A Space module, like any run that you start outside a Studio workspace, runs the branch of the
|
|
184
|
+
workblock that you chose with `wb-cli use`: `main` or a version branch. It is `main` until you
|
|
185
|
+
change it, and `main` is empty until the first deploy. To try a version branch in a Space, publish
|
|
186
|
+
it with `wb-cli push --to <name>`, run `wb-cli use <name>` in the checkout, and reload the Space. The
|
|
187
|
+
choice applies only to you: each user makes their own, and a Space cannot name a version branch for
|
|
188
|
+
a module. `wb-cli use` without a name prints your choice. Run `wb-cli use main` when you are done.
|
|
98
189
|
|
|
99
190
|
## Other platform requests
|
|
100
191
|
|
|
@@ -104,5 +195,5 @@ run. `wb-cli api --list <word>` finds the verb; `wb-cli api <verb> --describe` s
|
|
|
104
195
|
|
|
105
196
|
## Row store
|
|
106
197
|
|
|
107
|
-
Workblock-scoped rows are shared by `main`, every
|
|
198
|
+
Workblock-scoped rows are shared by `main`, every branch and every workspace of the workblock, so a
|
|
108
199
|
test that writes rows uses keys of its own and never resets the store.
|
|
@@ -23,8 +23,8 @@ Check the UI in these cases:
|
|
|
23
23
|
| `<module>` | `detached` | The UI of a UI-only module, as a Space shows it. | The data that the module gives its UI. |
|
|
24
24
|
| `<module>/<task> --in-run`, or `<module> --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
|
-
- The tenant builds the UI from the workspace's last commit, not from your files. Push first.
|
|
27
|
-
|
|
26
|
+
- The tenant builds the UI from the workspace's last commit, not from your files. Push first. The command
|
|
27
|
+
refuses unpushed edits, an unfinished merge, or a workspace at a different commit.
|
|
28
28
|
- In a preview, Submit and continue record the data and send nothing. In a UI-only module, Submit,
|
|
29
29
|
actions and continue fail, because the module has no run.
|
|
30
30
|
- In a run, Submit and the actions `continue` and `continue_next` send the data to the run, as
|
|
@@ -101,7 +101,6 @@ with fixed delays.
|
|
|
101
101
|
|
|
102
102
|
| `event` | Fields | Meaning |
|
|
103
103
|
| --- | --- | --- |
|
|
104
|
-
| `note` | `message` | The page does not show your files: the workspace and your files differ, or the workspace holds content that is not at a commit. |
|
|
105
104
|
| `ready` | `url`, `frame`, `mode`, `module_id`, `task_id`, `commit_ref`, `data_from`, `run_id`, `task_run_id` | The page is served. `data_from` is `file` or `run`. In a preview, `task_run_id` is the task run whose data the preview shows. In a run, `run_id` and `task_run_id` name the run and the task run that waits. |
|
|
106
105
|
| `host_event` | `kind`, and the fields of the kind | The page reports `ready`, `submit` (with `data`, or `error` when the component rejected it; in a run also `sent`, which is true when the run received the data), `console` (error lines of the UI), `page_error`, and `bridge` (each platform request of the UI, with `ok` and `error`). |
|
|
107
106
|
| `result` | `value` | What the `--exec` script returned. |
|
|
@@ -143,7 +142,8 @@ prints.
|
|
|
143
142
|
|
|
144
143
|
That browser acts as the user with all of the user's rights, not only the token's scopes:
|
|
145
144
|
|
|
146
|
-
- Open only this checkout's workspace, the URL that `wb-cli status` prints.
|
|
145
|
+
- Open only this checkout's workspace, the URL that `wb-cli status` prints. Opening it can publish
|
|
146
|
+
the conversation to its version branch (SKILL.md, The loop).
|
|
147
147
|
- Press only Start, the controls of the task UIs, Submit and the details of a toast.
|
|
148
148
|
- Never press Deploy. Never change sharing, permissions or settings. Never delete anything.
|
|
149
149
|
- On a login page, stop and ask the user to sign in in that browser. Never type credentials.
|