@opengeni/sdk 7.1.0 → 7.1.1

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.
Files changed (47) hide show
  1. package/README.md +6 -0
  2. package/dist/artifacts.js +5 -5
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +3 -3
  5. package/dist/chat/index.js +6 -6
  6. package/dist/{chunk-MG4QFBKR.js → chunk-B7S4YVGX.js} +2 -2
  7. package/dist/{chunk-LSO66LQA.js → chunk-E5WAYGHT.js} +1 -1
  8. package/dist/chunk-E5WAYGHT.js.map +1 -0
  9. package/dist/{chunk-YHF66FWZ.js → chunk-MPN5UJWE.js} +2 -2
  10. package/dist/{chunk-Y7DRKEFZ.js → chunk-NP7DDXHK.js} +94 -5
  11. package/dist/chunk-NP7DDXHK.js.map +1 -0
  12. package/dist/{chunk-ZN6WWXAX.js → chunk-PCVFOBSV.js} +2 -2
  13. package/dist/{chunk-X6Y2JCAN.js → chunk-RAG3P2UV.js} +2 -2
  14. package/dist/{chunk-QTBAMHEF.js → chunk-YUOPVPZW.js} +25 -1
  15. package/dist/chunk-YUOPVPZW.js.map +1 -0
  16. package/dist/client.d.ts +10 -2
  17. package/dist/core.js +4 -4
  18. package/dist/document-authority.js +4 -4
  19. package/dist/editable-artifacts.js +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +7 -7
  22. package/dist/interaction.d.ts +35 -0
  23. package/dist/interaction.js +1 -1
  24. package/dist/knowledge.d.ts +1 -1
  25. package/dist/knowledge.js.map +1 -1
  26. package/dist/session-message-search.d.ts +12 -0
  27. package/dist/site-browser-runtime.gen.d.ts +1 -1
  28. package/dist/site-document.js +1 -1
  29. package/dist/site-document.js.map +1 -1
  30. package/dist/site.js +4 -4
  31. package/dist/types.d.ts +3 -3
  32. package/package.json +2 -2
  33. package/src/browser.ts +2 -0
  34. package/src/client.ts +146 -2
  35. package/src/index.ts +2 -0
  36. package/src/interaction.ts +102 -0
  37. package/src/knowledge.ts +1 -0
  38. package/src/session-message-search.ts +8 -0
  39. package/src/site-browser-runtime.gen.ts +1 -1
  40. package/src/types.ts +5 -0
  41. package/dist/chunk-LSO66LQA.js.map +0 -1
  42. package/dist/chunk-QTBAMHEF.js.map +0 -1
  43. package/dist/chunk-Y7DRKEFZ.js.map +0 -1
  44. /package/dist/{chunk-MG4QFBKR.js.map → chunk-B7S4YVGX.js.map} +0 -0
  45. /package/dist/{chunk-YHF66FWZ.js.map → chunk-MPN5UJWE.js.map} +0 -0
  46. /package/dist/{chunk-ZN6WWXAX.js.map → chunk-PCVFOBSV.js.map} +0 -0
  47. /package/dist/{chunk-X6Y2JCAN.js.map → chunk-RAG3P2UV.js.map} +0 -0
@@ -1 +1 @@
1
- export declare const SITE_BROWSER_RUNTIME = "(()=>{var At=Object.defineProperty;var Pt=(e)=>e;function qt(e,t){this[e]=Pt.bind(null,t)}var Ot=(e,t)=>{for(var n in t)At(e,n,{get:t[n],enumerable:!0,configurable:!0,set:qt.bind(t,n)})};var me=(e,t)=>()=>(e&&(t=e(e=0)),t);function Tt(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!==\"object\"||Array.isArray(t))return null;let n=t,s=n.error&&typeof n.error===\"object\"&&!Array.isArray(n.error)?n.error:n,r=re(s.code),i=re(s.message),o=Re(s.requestId),a=typeof s.retryable===\"boolean\"?s.retryable:void 0,c=typeof s.outcomeUnknown===\"boolean\"?s.outcomeUnknown:void 0,l=Et(s.details);if(!r&&!i&&!o&&a===void 0&&c===void 0&&!l)return null;return{code:r,message:i,requestId:o,retryable:a,outcomeUnknown:c,details:l}}catch{return null}}function Et(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return;let t=Object.entries(e).slice(0,16),n={};for(let[s,r]of t){if(!/^[a-zA-Z][\\w.-]{0,63}$/.test(s))continue;if(typeof r===\"string\"){let i=re(r);if(i!==void 0)n[s]=i}else if(typeof r===\"number\"||typeof r===\"boolean\"||r===null)n[s]=r}return Object.keys(n).length>0?n:void 0}function re(e){if(typeof e!==\"string\")return;let t=new TextEncoder().encode(e);return t.byteLength<=512?e:new TextDecoder().decode(t.slice(0,512))}function Gt(e){return e===408||e===409||e===425||e===429||e>=500}function Re(e){if(typeof e!==\"string\"||e.length>128||!/^[\\w.:-]+$/.test(e))return;return e}function P(e){return e instanceof DOMException&&e.name===\"AbortError\"||e instanceof Error&&e.name===\"AbortError\"}function q(e){if(e instanceof y)return e.retryable;return e instanceof TypeError}var y,K,ie,H,I;var G=me(()=>{y=class y extends Error{status;code;retryable;correlationId;outcomeUnknown;body;details;constructor(e,t,n={}){let s=Tt(t),r=s?.requestId??Re(n.correlationId),i=e>=502&&e<=504,o=n.mutation!==void 0,a=s?.message??(o?\"Request failed.\":t||\"(empty body)\"),c=n.displayMessage??(i&&o?s?.message??\"OpenGeni is temporarily unavailable \u2014 retry.\":`OpenGeni API ${e}: ${a}`);super(r?`${c} Reference: ${r}.`:c);this.name=\"OpenGeniApiError\",this.status=e,this.code=n.code??s?.code??(i&&o?\"upstream_unavailable\":void 0),this.retryable=n.retryable??s?.retryable??Gt(e),this.correlationId=r,this.outcomeUnknown=n.outcomeUnknown??s?.outcomeUnknown??(i&&!!n.mutation&&!s),this.body=!o||s?t:\"\",this.details=s?.details}};K=class K extends Error{code=\"secure_context_required\";retryable=!1;reason;constructor(e){super(e===\"insecure_context\"?\"Couldn\u2019t attach this file because OpenGeni is open over HTTP. Attachments require a secure HTTPS connection. Open the secure site or configure HTTPS for this deployment.\":\"Couldn\u2019t attach this file because secure browser cryptography is unavailable. Attachments require HTTPS and Web Crypto support. Open a secure site in a supported browser or configure HTTPS for this deployment.\");this.name=\"OpenGeniSecureContextRequiredError\",this.reason=e}};ie=class ie extends y{};H=class H extends Error{expected;actual;constructor(e,t){super(`OpenGeni API contract mismatch: client expects ${e}, API serves ${t}`);this.name=\"OpenGeniApiContractMismatchError\",this.expected=e,this.actual=t}};I=class I extends Error{constructor(e){super(e);this.name=\"OpenGeniStreamError\"}}});var he={};Ot(he,{OpenGeniToolCallError:()=>oe,OpenGeniToolReapprovalRequiredError:()=>Y,OpenGeniToolsClient:()=>Q});class Q{transport;constructor(e){this.transport=e}forWorkspace(e){let t=Bt(e,\"workspaceId\"),n=null,s=new Map,r=async(d={})=>{if(n&&!d.refresh)return n;let p=await this.transport.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(t)}/tools/catalog`,void 0,{},d.signal?{signal:d.signal}:{});return n=p,p},i=async(d,p,u)=>{if(u.approvalToken&&!u.operationId)throw TypeError(\"operationId is required when using an approval token\");let g=u.operationId??crypto.randomUUID(),b=await r({...u.refreshCatalog===void 0?{}:{refresh:u.refreshCatalog},...u.signal?{signal:u.signal}:{}}),m=async(w)=>{let h=d(w),A=u.approvalToken?s.get(u.approvalToken):void 0;if(A&&(A.operationId!==g||A.catalogDigest!==w.digest||!Mt(A.identity,h)))throw new Y(g,A.catalogDigest,w.digest,h);let F={operationId:g,catalogDigest:w.digest,identity:h,arguments:p,...u.approvalToken?{approvalToken:u.approvalToken}:{}},E;try{E=await this.transport.requestJson(\"POST\",`/v1/workspaces/${encodeURIComponent(t)}/tools/calls`,F,{},u.signal?{signal:u.signal}:{})}catch(ge){if(X(ge))n=null;else if(u.approvalToken)s.delete(u.approvalToken);throw ge}if(u.approvalToken)s.delete(u.approvalToken);if(E.catalogDigest!==w.digest)n=null;if(E.result.isError)throw new oe(E.result);return be(w,h)?.outputSchema&&E.result.structuredContent!==void 0?E.result.structuredContent:E.result};try{return await m(b)}catch(w){if(!X(w))throw w}let f=await r({refresh:!0,...u.signal?{signal:u.signal}:{}}),R=d(f);if(u.approvalToken&&f.digest!==b.digest)throw new Y(g,b.digest,f.digest,R);return await m(f)},o=async(d,p={},u={})=>await i((g)=>we(g,d),p,u),a=async(d,p={},u={})=>{let g=u.operationId??crypto.randomUUID(),b=async(R)=>{let w={operationId:g,catalogDigest:R.digest,identity:we(R,d),arguments:p};try{let h=await this.transport.requestJson(\"POST\",`/v1/workspaces/${encodeURIComponent(t)}/tools/approvals`,w,{},u.signal?{signal:u.signal}:{});return s.set(h.approvalToken,{operationId:h.operationId,catalogDigest:h.catalogDigest,identity:h.identity}),h}catch(h){if(X(h))n=null;throw h}},m=await r(u.signal?{signal:u.signal}:{});try{return await b(m)}catch(R){if(!X(R))throw R}let f=await r({refresh:!0,...u.signal?{signal:u.signal}:{}});return await b(f)},c=async(d,p={},u={})=>await i((g)=>$t(g,d).identity,p,u),l=(d)=>new Proxy(async(p={},u={})=>await c(d,p,u),{get:(p,u)=>{if(u===\"then\")return;if(typeof u!==\"string\")return;return l([...d,u])}});return new Proxy(Object.create(null),{get:(d,p)=>{if(p===\"then\")return;if(p===\"$catalog\")return r;if(p===\"$call\")return o;if(p===\"$approve\")return a;if(p===\"$declarations\")return async(u={})=>await this.transport.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(t)}/tools/declarations`,void 0,{},u.signal?{signal:u.signal}:{});if(typeof p!==\"string\")return;return l([p])}})}}function be(e,t){return e.entries.find((n)=>n.identity.serverId===t.serverId&&n.identity.toolName===t.toolName)}function Mt(e,t){return e.serverId===t.serverId&&e.toolName===t.toolName}function we(e,t){let n=be(e,t);if(!n)throw Error(`Tool is not present in the workspace catalog: ${t.serverId}/${t.toolName}`);return n.identity}function $t(e,t){let n=e.entries.find((s)=>s.codemodePath.length===t.length&&s.codemodePath.every((r,i)=>r===t[i]));if(!n)throw Error(`Tool is not present in the workspace catalog: ${t.join(\".\")}`);return n}function X(e){return e instanceof y&&e.status===409&&e.details?.code===\"catalog_stale\"||typeof e===\"object\"&&e!==null&&\"code\"in e&&e.code===\"catalog_stale\"}function Bt(e,t){let n=e.trim();if(!n)throw TypeError(`${t} is required`);return n}var oe,Y;var ae=me(()=>{G();oe=class oe extends Error{result;code;retryable;outcomeUnknown;constructor(e){let t=e.structuredContent;super(typeof t?.error?.message===\"string\"?t.error.message:\"OpenGeni tool call failed\");this.result=e;this.name=\"OpenGeniToolCallError\",this.code=typeof t?.error?.code===\"string\"?t.error.code:\"tool_error\",this.retryable=t?.error?.retryable===!0,this.outcomeUnknown=t?.error?.outcomeUnknown===!0}};Y=class Y extends Error{operationId;previousCatalogDigest;catalogDigest;identity;code=\"tool_reapproval_required\";retryable=!1;constructor(e,t,n,s){super(\"The workspace tool catalog changed after approval. Request a new approval for the refreshed tool identity and retry with the same operation ID.\");this.operationId=e;this.previousCatalogDigest=t;this.catalogDigest=n;this.identity=s;this.name=\"OpenGeniToolReapprovalRequiredError\"}}});class ye extends Error{code=\"site_session_path_unsupported\";constructor(){super(\"Unsupported Site session API path\");this.name=\"SiteSessionPathError\"}}function z(e,t,n=\"GET\",s){let r=e.split(\"?\")[0];if(!(r===\"/v1/workspaces/site-host\"||r.startsWith(\"/v1/workspaces/site-host/\"))&&r!==\"/v1/config/client\"||/[%\\\\#\\u0000-\\u0020\\u007f]/u.test(r)||r.split(\"/\").some((l)=>l===\".\"||l===\"..\"))throw new ye;let a=e.replace(\"/workspaces/site-host\",`/workspaces/${encodeURIComponent(t)}`),c=new URL(a,\"http://site.invalid\");if(c.searchParams.get(\"originSiteId\")===\"current\"&&t!==\"site-host\")return c.searchParams.set(\"originSiteId\",s??\"00000000-0000-0000-0000-000000000000\"),c.pathname+c.search;return a}var _t=\"opengeni.site.http\",j=\"site-host\";async function fe(e,t,n){let s=new Request(t,n),r=new URL(s.url),i=`${r.pathname}${r.search}`;z(i,j,s.method);let o=new MessageChannel,a=crypto.randomUUID(),c=s.body?await s.text():void 0;return await new Promise((l,d)=>{let p,u=!1,g=()=>{u=!0,s.signal.removeEventListener(\"abort\",b),o.port1.close()},b=()=>{if(u)return;e.postMessage({type:\"opengeni.site.cancel\",version:2,requestId:a});let m=s.signal.reason??new DOMException(\"Cancelled\",\"AbortError\");p?.error(m),d(m),g()};if(o.port1.onmessage=(m)=>{let f=m.data;if(f.error){let R=Error(f.error);p?.error(R),d(R),g()}else if(f.status){let R=f.body?new ReadableStream({start(w){p=w},pull(){o.port1.postMessage(\"pull\")},cancel(){p=void 0,b()}}):null;if(l(new Response(R,{status:f.status,headers:f.headers})),!f.body)g()}else if(f.done)p?.close(),g();else if(f.chunk)p?.enqueue(f.chunk)},s.signal.aborted){b();return}s.signal.addEventListener(\"abort\",b,{once:!0}),e.postMessage({type:_t,requestId:a,path:i,method:s.method,headers:[...s.headers],...c===void 0?{}:{body:c}},[o.port2])})}ae();G();G();async function*O(e){let t=e.getReader(),n=new TextDecoder,s=\"\",r,i,o=null,a=()=>{let l=o===null?null:{...r!==void 0?{id:r}:{},...i!==void 0?{event:i}:{},data:o.join(`\n`)};return r=void 0,i=void 0,o=null,l},c=(l)=>{if(l===\"\")return a();if(l.startsWith(\":\"))return null;let d=l.indexOf(\":\"),p=d===-1?l:l.slice(0,d),u=d===-1?\"\":l.slice(d+1);if(u.startsWith(\" \"))u=u.slice(1);if(p===\"data\")(o??=[]).push(u);else if(p===\"event\")i=u;else if(p===\"id\")r=u;return null};try{while(!0){let{done:l,value:d}=await t.read();if(l)break;s+=n.decode(d,{stream:!0});let p=s.indexOf(`\n`);while(p!==-1){let u=s.slice(0,p);if(s=s.slice(p+1),u.endsWith(\"\\r\"))u=u.slice(0,-1);let g=c(u);if(g)yield g;p=s.indexOf(`\n`)}}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}var Ut=Symbol.for(\"@opengeni/sdk/session-event-stream-covered-through\");async function*ve(e,t={}){let n=t.signal,s=t.reconnect??!0,r=t.reconnectDelayMs??500,i=t.maxReconnectDelayMs??1e4,o=t.reconnectJitterRatio??0.2,a=t.beforeLiveTimeoutMs??15000,c=t.heartbeatTimeoutMs??45000,l=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=t.after??0,p=0,u=r,g=!1;while(!0){if(n?.aborted)break;t.onStateChange?.(g||p>0?\"reconnecting\":\"connecting\");let b=d;try{let m=await e.openStream(d,n);g=!0,p=0,u=r;try{t.onOpen?.()}catch{}await _(t.beforeLive,a,n),t.onStateChange?.(\"live\");for await(let f of O(M(m,c,n))){if(n?.aborted)return;let R=Lt(f.data);if(!R)continue;let w=Wt(f.id,R.sequence);if(Ft(R,w),w<=d)continue;if(R.sequence>d+1){for await(let h of Dt(e,d,R.sequence-1))if(d=h.sequence,yield h,n?.aborted)return}d=w,yield R}if(!s)return;if(d===b)await Se(C(r,o),n);continue}catch(m){if(n?.aborted||P(m))return;if(!s||!q(m))throw m;if(p+=1,p>l)throw new I(`event stream gave up after ${l} consecutive failed reconnect attempts: ${m instanceof Error?m.message:String(m)}`)}await Se(C(u,o),n),u=Math.min(Math.max(u*2,r),i)}}async function _(e,t,n){if(!e)return;let s,r,i=new Promise((o,a)=>{if(s=setTimeout(()=>a(TypeError(`stream reconciliation timed out after ${t}ms`)),t),n)r=()=>a(new DOMException(\"Aborted\",\"AbortError\")),n.addEventListener(\"abort\",r,{once:!0})});try{await Promise.race([Promise.resolve().then(e),i])}finally{if(s!==void 0)clearTimeout(s);if(n&&r)n.removeEventListener(\"abort\",r)}}function C(e,t){if(e<=0||t<=0)return e;let n=Math.min(t,1),s=e*n;return Math.max(0,e-s+Math.random()*s*2)}function M(e,t,n){if(!Number.isSafeInteger(t)||t<=0)throw RangeError(\"stream heartbeat timeout must be a positive safe integer\");let s=e.getReader();return new ReadableStream({pull:async(r)=>{let i,o;try{let a=await Promise.race([s.read(),new Promise((c,l)=>{if(i=setTimeout(()=>l(TypeError(`event stream heartbeat timed out after ${t}ms`)),t),n)o=()=>l(new DOMException(\"Aborted\",\"AbortError\")),n.addEventListener(\"abort\",o,{once:!0})})]);if(a.done)r.close();else r.enqueue(a.value)}catch(a){s.cancel(a).catch(()=>{}),r.error(a)}finally{if(i!==void 0)clearTimeout(i);if(n&&o)n.removeEventListener(\"abort\",o)}},cancel:async(r)=>{await s.cancel(r)}})}async function*Dt(e,t,n){let s=t;while(s<n){let i=(await e.listEvents(s,Math.min(500,n-s))).filter((o)=>o.sequence>s&&o.sequence<=n).sort((o,a)=>o.sequence-a.sequence);if(i.length===0)throw new I(`event replay backfill stalled: expected sequences ${s+1}..${n} but the replay endpoint returned none of them`);for(let o of i){if(o.sequence!==s+1)throw new I(`event replay backfill is missing sequence ${s+1} (replay endpoint skipped to ${o.sequence}); refusing to deliver with a gap`);s=o.sequence,yield o}}}function Lt(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!==\"object\"||t===null||typeof t.sequence!==\"number\"||typeof t.type!==\"string\"||typeof t.id!==\"string\")return null;return t}function Wt(e,t){if(e===void 0||!/^\\d+$/.test(e))return t;let n=Number(e);return Number.isSafeInteger(n)&&n>=t?n:t}function Ft(e,t){Object.defineProperty(e,Ut,{value:t,enumerable:!1,configurable:!1,writable:!1})}async function Se(e,t){if(t?.aborted||e<=0)return;await new Promise((n)=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t?.removeEventListener(\"abort\",r),n()}t?.addEventListener(\"abort\",r,{once:!0})})}G();async function*Ie(e,t={}){let n=t.signal,s=t.reconnect??!0,r=t.reconnectDelayMs??500,i=t.maxReconnectDelayMs??1e4,o=t.reconnectJitterRatio??0.2,a=t.beforeLiveTimeoutMs??15000,c=t.heartbeatTimeoutMs??45000,l=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=t.after??0,p=0,u=r,g=!1;for(;;){if(n?.aborted)return;t.onStateChange?.(g||p>0?\"reconnecting\":\"connecting\");let b=d;try{let m=await e.openStream(d,n);g=!0,p=0,u=r,await _(t.beforeLive,a,n),t.onStateChange?.(\"live\");for await(let f of O(M(m,c,n))){if(n?.aborted)return;let R=zt(f.data);if(!R||R.sequence<=d)continue;d=R.sequence,yield R}if(!s)return;if(d===b)await ke(C(r,o),n);continue}catch(m){if(n?.aborted||P(m))return;if(!s||!q(m))throw m;if(p+=1,p>l)throw new I(`workspace control stream gave up after ${l} reconnect attempts: ${m instanceof Error?m.message:String(m)}`)}await ke(C(u,o),n),u=Math.min(Math.max(u*2,r),i)}}function zt(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!==\"object\"||t===null||t.type!==\"workspace.control.changed\"||typeof t.id!==\"string\"||typeof t.sequence!==\"number\")return null;return t}async function ke(e,t){if(t?.aborted||e<=0)return;await new Promise((n)=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t?.removeEventListener(\"abort\",r),n()}t?.addEventListener(\"abort\",r,{once:!0})})}G();async function*xe(e,t={}){let n=t.signal,s=t.reconnect??!0,r=t.reconnectDelayMs??500,i=t.maxReconnectDelayMs??1e4,o=t.reconnectJitterRatio??0.2,a=t.beforeLiveTimeoutMs??15000,c=t.heartbeatTimeoutMs??45000,l=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=t.after??0,p=0,u=r,g=!1;for(;;){if(n?.aborted)return;t.onStateChange?.(g||p>0?\"reconnecting\":\"connecting\");let b=d;try{let m=await e.openStream(d,n);g=!0,p=0,u=r,await _(t.beforeLive,a,n),t.onStateChange?.(\"live\");for await(let f of O(M(m,c,n))){if(n?.aborted)return;let R=Jt(f.data);if(!R||R.sequence<=d)continue;d=R.sequence,yield R}if(!s)return;if(d===b)await Ce(C(r,o),n);continue}catch(m){if(n?.aborted||P(m))return;if(!s||!q(m))throw m;if(p+=1,p>l)throw new I(`workspace interaction stream gave up after ${l} reconnect attempts: ${m instanceof Error?m.message:String(m)}`)}await Ce(C(u,o),n),u=Math.min(Math.max(u*2,r),i)}}function Jt(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Vt(t)||t.type!==\"workspace.interaction.changed\"||typeof t.workspaceId!==\"string\"||typeof t.sequence!==\"number\"||!Number.isSafeInteger(t.sequence)||t.sequence<0||t.revision!==t.sequence||typeof t.occurredAt!==\"string\")return null;return t}function Vt(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}async function Ce(e,t){if(t?.aborted||e<=0)return;await new Promise((n)=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t?.removeEventListener(\"abort\",r),n()}t?.addEventListener(\"abort\",r,{once:!0})})}G();async function*Pe(e,t={}){let n=t.signal,s=t.reconnect??!0,r=t.reconnectDelayMs??500,i=t.maxReconnectDelayMs??1e4,o=t.reconnectJitterRatio??0.2,a=t.beforeLiveTimeoutMs??15000,c=t.heartbeatTimeoutMs??45000,l=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=t.controlAfter??0,p=t.interactionAfter??0,u=0,g=r,b=!1;for(;;){if(n?.aborted)return;t.onStateChange?.(b||u>0?\"reconnecting\":\"connecting\");let m=`${d}:${p}`;try{let f=await e.openStream(d,p,n);b=!0,u=0,g=r,await _(t.beforeLive,a,n),t.onStateChange?.(\"live\");for await(let R of O(M(f,c,n))){if(n?.aborted)return;let w=Nt(R.data);if(!w)continue;if(w.type===\"workspace.control.changed\"){if(w.sequence<=d)continue;d=w.sequence}else{if(w.sequence<=p)continue;p=w.sequence}yield w}if(!s)return;if(`${d}:${p}`===m)await Ae(C(r,o),n);continue}catch(f){if(n?.aborted||P(f))return;if(!s||!q(f))throw f;if(u+=1,u>l)throw new I(`workspace live stream gave up after ${l} reconnect attempts: ${f instanceof Error?f.message:String(f)}`)}await Ae(C(g,o),n),g=Math.min(Math.max(g*2,r),i)}}function Nt(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Kt(t)||typeof t.sequence!==\"number\")return null;if(t.type===\"workspace.control.changed\"&&typeof t.id===\"string\"&&Number.isSafeInteger(t.sequence))return t;if(t.type===\"workspace.interaction.changed\"&&typeof t.workspaceId===\"string\"&&Number.isSafeInteger(t.sequence)&&t.sequence>=0&&t.revision===t.sequence&&typeof t.occurredAt===\"string\")return t;return null}function Kt(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}async function Ae(e,t){if(t?.aborted||e<=0)return;await new Promise((n)=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t?.removeEventListener(\"abort\",r),n()}t?.addEventListener(\"abort\",r,{once:!0})})}var qe=32768,Ht=1e8;class ce{attachedBrowsers;authRuns;browsers;computers;identities;interventions;networkRoutes;siteAuthConnections;constructor(e){this.attachedBrowsers=new Le(e),this.authRuns=new $e(e),this.browsers=new Je(e),this.computers=new Xe(e),this.identities=new Fe(e),this.interventions=new Ue(e),this.networkRoutes=new Ee(e),this.siteAuthConnections=new _e(e)}}class Ee{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listNetworkRoutes(e,t)}route(e,t){return new Ge(this.transport,e,t)}async create(e,t,n={}){let s=await this.transport.createNetworkRoute(e,t,n);return this.route(e,s.route.id)}}class Ge{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getNetworkRoute(this.workspaceId,this.id,e)}async update(e,t={}){return await this.transport.updateNetworkRoute(this.workspaceId,this.id,e,t)}}class _e{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listSiteAuthConnections(e,t)}connection(e,t){return new Me(this.transport,e,t)}async create(e,t,n={}){let s=await this.transport.createSiteAuthConnection(e,t,n);return this.connection(e,s.connection.id)}}class Me{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getSiteAuthConnection(this.workspaceId,this.id,e)}async update(e,t={}){return await this.transport.updateSiteAuthConnection(this.workspaceId,this.id,e,t)}}class $e{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listAuthRuns(e,t)}async get(e,t,n={}){return await this.transport.getAuthRun(e,t,n)}run(e,t,n){return new ue(this.transport,e,t,n)}}class Be{transport;workspaceId;browserSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.browserSessionId=n}async list(e={}){return await this.transport.listAuthRuns(this.workspaceId,{...e,browserSessionId:this.browserSessionId})}run(e){return new ue(this.transport,this.workspaceId,this.browserSessionId,e)}async start(e,t={}){let n=await this.transport.startBrowserAuthRun(this.workspaceId,this.browserSessionId,e,t);return this.run(n.run.id)}}class ue{transport;workspaceId;browserSessionId;id;constructor(e,t,n,s){this.transport=e;this.workspaceId=t;this.browserSessionId=n;this.id=s}async get(e={}){let t=await this.transport.getAuthRun(this.workspaceId,this.id,e);if(t.browserSessionId!==this.browserSessionId)throw Error(\"AuthRun belongs to another BrowserSession\");return t}async report(e,t={}){return await this.transport.reportBrowserAuthRun(this.workspaceId,this.browserSessionId,this.id,e,t)}async protectedFill(e,t={}){return await this.transport.protectedBrowserAuthFill(this.workspaceId,this.browserSessionId,this.id,e,t)}async advanceExternal(e,t={}){return await this.transport.advanceExternalBrowserAuthRun(this.workspaceId,this.browserSessionId,this.id,e,t)}async openExternalFlow(e,t={}){return await this.transport.openExternalBrowserAuthFlow(this.workspaceId,this.browserSessionId,this.id,e,t)}async verify(e,t={}){return await this.transport.verifyBrowserAuthRun(this.workspaceId,this.browserSessionId,this.id,e,t)}}class Ue{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listInteractionInterventions(e,t)}intervention(e,t){return new De(this.transport,e,t)}async create(e,t,n={}){let s=await this.transport.createInteractionIntervention(e,t,n);return this.intervention(e,s.intervention.id)}}class De{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getInteractionIntervention(this.workspaceId,this.id,e)}async resolve(e,t={}){return await this.transport.resolveInteractionIntervention(this.workspaceId,this.id,e,t)}}class Le{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listAttachedBrowsers(e,t)}device(e,t){return new We(this.transport,e,t)}}class We{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getAttachedBrowser(this.workspaceId,this.id,e)}}class Fe{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listBrowserIdentities(e,t)}identity(e,t){return new ze(this.transport,e,t)}async create(e,t,n={}){let s=await this.transport.createBrowserIdentity(e,t,n);return this.identity(e,s.identity.id)}}class ze{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getBrowserIdentity(this.workspaceId,this.id,e)}async revisions(e={}){return await this.transport.listBrowserRevisions(this.workspaceId,this.id,e)}async update(e,t={}){return await this.transport.updateBrowserIdentity(this.workspaceId,this.id,e,t)}}class Je{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listBrowserSessions(e,t)}session(e,t){return new Ve(this.transport,e,t)}async open(e,t,n={}){let s=await this.transport.createBrowserSession(e,t,n);return this.session(e,s.session.id)}async currentOrOpen(e){let t=e.signal?{signal:e.signal}:{},n=await this.list(e.workspaceId,t),s=Xt(n.sessions,e.associationSessionId);if(s){let r=this.session(e.workspaceId,s.id);if(s.lifecycle===\"suspended\")await r.resume({operationId:e.operationId??crypto.randomUUID()},t);return r}return await this.open(e.workspaceId,{operationId:e.operationId??crypto.randomUUID(),sessionId:e.associationSessionId,...e.name!==void 0?{name:e.name}:{},...e.initialUrl!==void 0?{initialUrl:e.initialUrl}:{},...e.headless!==void 0?{headless:e.headless}:{},...e.placement!==void 0?{placement:e.placement}:{},...e.identityId!==void 0?{identityId:e.identityId}:{},...e.baseRevisionId!==void 0?{baseRevisionId:e.baseRevisionId}:{},...e.networkRouteId!==void 0?{networkRouteId:e.networkRouteId}:{},...e.linkedComputerSessionId!==void 0?{linkedComputerSessionId:e.linkedComputerSessionId}:{}},t)}}class Ve{transport;workspaceId;id;auth;clipboard;downloads;tabs;targets;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n;this.auth=new Be(e,t,n),this.clipboard=new Ne(e,t,n),this.downloads=new Ke(e,t,n),this.tabs=new je(e,t,n),this.targets=this.tabs}async get(e={}){return await this.transport.getBrowserSession(this.workspaceId,this.id,e)}async observe(e,t={}){return await this.transport.observeBrowserTarget(this.workspaceId,this.id,e,t)}async act(e,t={}){return await this.transport.actInBrowser(this.workspaceId,this.id,e,t)}async receipt(e,t={}){return await this.transport.getBrowserActionReceipt(this.workspaceId,this.id,e,t)}async diagnostics(e,t={}){return await this.transport.listBrowserDiagnostics(this.workspaceId,this.id,e,t)}async attach(e,t={}){return await this.transport.attachBrowserSession(this.workspaceId,this.id,e,t)}async heartbeat(e={}){return await this.transport.heartbeatBrowserSession(this.workspaceId,this.id,e)}async publishRevision(e,t={}){return await this.transport.publishBrowserRevision(this.workspaceId,this.id,e,t)}async suspend(e={operationId:crypto.randomUUID()},t={}){return await this.transport.suspendBrowserSession(this.workspaceId,this.id,e,t)}async resume(e={operationId:crypto.randomUUID()},t={}){return await this.transport.resumeBrowserSession(this.workspaceId,this.id,e,t)}async end(e={operationId:crypto.randomUUID()},t={}){return await this.transport.endBrowserSession(this.workspaceId,this.id,e,t)}}class Ne{transport;workspaceId;browserSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.browserSessionId=n}async read(e={}){let t=await this.transport.readBrowserClipboard(this.workspaceId,this.browserSessionId,e);if(t.browserSessionId!==this.browserSessionId)throw Error(\"Browser clipboard belongs to another BrowserSession\");return t}}class Ke{transport;workspaceId;browserSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.browserSessionId=n}async list(e={}){return await this.transport.listBrowserDownloads(this.workspaceId,this.browserSessionId,e)}download(e){return new He(this.transport,this.workspaceId,this.browserSessionId,e)}}class He{transport;workspaceId;browserSessionId;id;constructor(e,t,n,s){this.transport=e;this.workspaceId=t;this.browserSessionId=n;this.id=s}async get(e={}){let t=await this.transport.getBrowserDownload(this.workspaceId,this.browserSessionId,this.id,e);if(t.browserSessionId!==this.browserSessionId)throw Error(\"BrowserDownload belongs to another BrowserSession\");return t}async saveToWorkspace(e,t={}){let{operationId:n=crypto.randomUUID(),overwrite:s=!1,...r}=t,i=await this.transport.saveBrowserDownload(this.workspaceId,this.browserSessionId,this.id,{operationId:n,destinationPath:e,overwrite:s},r);if(i.download.id!==this.id||i.download.browserSessionId!==this.browserSessionId)throw Error(\"BrowserDownload save returned another resource\");return i}}class je{transport;workspaceId;browserSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.browserSessionId=n}async list(e={}){return await this.transport.listBrowserTargets(this.workspaceId,this.browserSessionId,e)}async open(e,t={}){return await this.transport.openBrowserTarget(this.workspaceId,this.browserSessionId,e===void 0?{}:{url:e},t)}async select(e,t={}){return await this.transport.selectBrowserTarget(this.workspaceId,this.browserSessionId,e,t)}async close(e,t={}){return await this.transport.closeBrowserTarget(this.workspaceId,this.browserSessionId,e,t)}}class Xe{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listComputerSessions(e,t)}session(e,t){return new Ye(this.transport,e,t)}async open(e,t,n={}){let s=await this.transport.createComputerSession(e,t,n);return this.session(e,s.session.id)}async currentOrOpen(e){let t=e.signal?{signal:e.signal}:{},n=await this.list(e.workspaceId,t),s=Yt(n.sessions,e.associationSessionId);if(s)return this.session(e.workspaceId,s.id);return await this.open(e.workspaceId,{operationId:e.operationId??crypto.randomUUID(),sessionId:e.associationSessionId,...e.name!==void 0?{name:e.name}:{},...e.placement!==void 0?{placement:e.placement}:{}},t)}}class Ye{transport;workspaceId;id;targets;apps;clipboard;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n;this.targets=new Ze(e,t,n),this.apps=this.targets,this.clipboard=new Qe(e,t,n)}async get(e={}){return await this.transport.getComputerSession(this.workspaceId,this.id,e)}async observe(e,t={}){return await this.transport.observeComputerTarget(this.workspaceId,this.id,e,t)}async capture(e,t={}){return await this.transport.captureComputerTarget(this.workspaceId,this.id,e,t)}async act(e,t={}){return await this.transport.actInComputer(this.workspaceId,this.id,e,t)}async receipt(e,t={}){return await this.transport.getComputerActionReceipt(this.workspaceId,this.id,e,t)}async attach(e,t={}){return await this.transport.attachComputerSession(this.workspaceId,this.id,e,t)}async heartbeat(e={}){return await this.transport.heartbeatComputerSession(this.workspaceId,this.id,e)}async end(e={operationId:crypto.randomUUID()},t={}){return await this.transport.endComputerSession(this.workspaceId,this.id,e,t)}}class Qe{transport;workspaceId;computerSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.computerSessionId=n}async read(e={}){let t=await this.transport.readComputerClipboard(this.workspaceId,this.computerSessionId,e);if(t.computerSessionId!==this.computerSessionId)throw Error(\"Computer clipboard belongs to another ComputerSession\");return t}}class Ze{transport;workspaceId;computerSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.computerSessionId=n}async list(e={}){return await this.transport.listComputerTargets(this.workspaceId,this.computerSessionId,e)}}function jt(e){if(!tn(e))throw Error(\"computer frame metadata is invalid\");let t=new Set([\"frameId\",\"computerSessionId\",\"controllerGeneration\",\"targetId\",\"targetGeneration\",\"sequence\",\"mediaType\",\"width\",\"height\",\"capturedAt\",\"sha256\"]);if(Object.keys(e).some((r)=>!t.has(r)))throw Error(\"computer frame metadata contains unknown fields\");let n=[\"frameId\",\"computerSessionId\",\"controllerGeneration\",\"targetId\",\"targetGeneration\",\"mediaType\",\"capturedAt\",\"sha256\"];for(let r of n){let i=e[r],o=r===\"targetId\"?512:r===\"capturedAt\"?128:256;if(typeof i!==\"string\"||i.length<1||Zt(i)>o)throw Error(\"computer frame metadata is invalid\")}let s=e;if(!Number.isSafeInteger(s.sequence)||s.sequence<0||!Number.isSafeInteger(s.width)||!Number.isSafeInteger(s.height))throw Error(\"computer frame metadata integers are invalid\");if(Qt(s.width,s.height),s.mediaType!==\"image/jpeg\"&&s.mediaType!==\"image/png\")throw Error(\"computer frame media type is invalid\");if(!en(s.computerSessionId))throw Error(\"computer frame session id is invalid\");if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(s.controllerGeneration))throw Error(\"computer frame controller generation is invalid\");if(!Number.isFinite(new Date(s.capturedAt).valueOf()))throw Error(\"computer frame timestamp is invalid\");if(!/^[0-9a-f]{64}$/u.test(s.sha256))throw Error(\"computer frame digest is invalid\");return s}function et(e){if(!e||e.length>32768||!/^[A-Za-z0-9_-]+$/u.test(e))throw Error(\"computer frame metadata header is invalid\");let t=e.replace(/-/gu,\"+\").replace(/_/gu,\"/\"),n=t.padEnd(Math.ceil(t.length/4)*4,\"=\"),s;try{s=atob(n)}catch{throw Error(\"computer frame metadata header is invalid\")}let r=Uint8Array.from(s,(o)=>o.charCodeAt(0)),i;try{i=JSON.parse(new TextDecoder(\"utf-8\",{fatal:!0}).decode(r))}catch{throw Error(\"computer frame metadata header is invalid\")}return jt(i)}function Xt(e,t){let n=e.filter((s)=>![\"ending\",\"ended\",\"failed\",\"lost\"].includes(s.lifecycle)&&s.associations.some((r)=>r.sessionId===t));return n.sort((s,r)=>Oe(r,t)-Oe(s,t)),n[0]??null}function Yt(e,t){let n=e.filter((s)=>[\"starting\",\"active\",\"restoring\"].includes(s.lifecycle)&&s.associations.some((r)=>r.sessionId===t));return n.sort((s,r)=>Te(r,t)-Te(s,t)),n[0]??null}function Oe(e,t){let n=e.associations.filter((r)=>r.sessionId===t).map((r)=>Date.parse(r.lastUsedAt)).filter(Number.isFinite).reduce((r,i)=>Math.max(r,i),0),s=Date.parse(e.lastUsedAt);return Math.max(n,Number.isFinite(s)?s:0)}function Te(e,t){let n=e.associations.filter((r)=>r.sessionId===t).map((r)=>Date.parse(r.lastUsedAt)).filter(Number.isFinite).reduce((r,i)=>Math.max(r,i),0),s=Date.parse(e.lastUsedAt);return Math.max(n,Number.isFinite(s)?s:0)}function Qt(e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<1||t<1||e>qe||t>qe||e*t>Ht)throw Error(\"browser image dimensions exceed their bounded envelope\")}function Zt(e){return new TextEncoder().encode(e).byteLength}function en(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e)}function tn(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}var U=\"2026-09-plugins-and-skills-v1\",de=\"x-opengeni-api-contract\",Z=\"x-opengeni-correlation-id\";var ee=1048576,tt=33554432;var nt=536870912;var ne=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,st=/^[0-9a-f]{64}$/,rt=/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/,it=/^\\/v1\\/workspaces\\/([0-9a-f-]+)\\/artifacts\\/([0-9a-f-]+)\\/content$/;function ot(e,t){if(!B(e,sn))return null;let n=e;if(n.available!==!0||n.kind!==\"file\"||typeof n.artifactId!==\"string\"||!ne.test(n.artifactId)||typeof n.contentType!==\"string\"||!/^[a-z0-9][a-z0-9!#$&^_.+-]{0,62}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,62}$/.test(n.contentType)||!te(n.originalBytes,1,26214399)||typeof n.sha256!==\"string\"||!st.test(n.sha256)||typeof n.retainedAt!==\"string\"||n.retainedAt.length>64||!rt.test(n.retainedAt)||!Number.isFinite(Date.parse(n.retainedAt))||!B(n.retention,ct)||!B(n.retrieval,ut))return null;let s=n.retention;if(s.policy!==\"workspace_file\"||s.expiresAt!==null)return null;let r=n.retrieval;if(r.method!==\"GET\"||r.acceptRanges!==\"bytes\"||r.maxRangeBytes!==1048576||typeof r.path!==\"string\"||r.path.length>256)return null;let i=it.exec(r.path);if(!i||!ne.test(i[1]??\"\")||i[2]!==n.artifactId||t!==void 0&&i[1]!==t)return null;return e}function at(e,t){if(!B(e,nn))return null;let n=e;if(n.available!==!0||n.kind!==\"generated_image\"||typeof n.artifactId!==\"string\"||!ne.test(n.artifactId)||![\"image/png\",\"image/jpeg\",\"image/webp\"].includes(String(n.contentType))||!te(n.originalBytes,1,67108864)||typeof n.sha256!==\"string\"||!st.test(n.sha256)||typeof n.retainedAt!==\"string\"||n.retainedAt.length>64||!rt.test(n.retainedAt)||!Number.isFinite(Date.parse(n.retainedAt))||!B(n.dimensions,rn)||!B(n.retention,ct)||!B(n.retrieval,ut))return null;let s=n.dimensions;if(!te(s.width,1,16384)||!te(s.height,1,16384)||Number(s.width)*Number(s.height)>67108864)return null;let r=n.retention;if(r.policy!==\"workspace_file\"||r.expiresAt!==null)return null;let i=n.retrieval;if(i.method!==\"GET\"||i.acceptRanges!==\"bytes\"||i.maxRangeBytes!==1048576||typeof i.path!==\"string\"||i.path.length>256)return null;let o=it.exec(i.path);if(!o||!ne.test(o[1]??\"\")||o[2]!==n.artifactId||t!==void 0&&o[1]!==t)return null;return e}var nn=new Set([\"available\",\"artifactId\",\"kind\",\"contentType\",\"originalBytes\",\"sha256\",\"retainedAt\",\"dimensions\",\"retention\",\"retrieval\"]),sn=new Set([\"available\",\"artifactId\",\"kind\",\"contentType\",\"originalBytes\",\"sha256\",\"retainedAt\",\"retention\",\"retrieval\"]),rn=new Set([\"width\",\"height\"]),ct=new Set([\"policy\",\"expiresAt\"]),ut=new Set([\"method\",\"path\",\"acceptRanges\",\"maxRangeBytes\"]);function B(e,t){return e!==null&&typeof e===\"object\"&&!Array.isArray(e)&&Object.keys(e).length===t.size&&Object.keys(e).every((n)=>t.has(n))}function te(e,t,n){return Number.isSafeInteger(e)&&Number(e)>=t&&Number(e)<=n}function dt(e){let{limit:t,parentSessionId:n,scopeSubjectId:s}=e;return{...e.originSiteId?{originSiteId:e.originSiteId}:{},...t===void 0?{}:{limit:String(t)},...n===void 0?{}:{parentSessionId:n??\"null\"},...s===void 0?{}:{scopeSubjectId:s}}}function lt(e){return e.originSiteId!==void 0||e.channelId!==void 0||e.createdBy!==void 0||e.updatedFrom!==void 0||e.updatedBefore!==void 0||e.createdFrom!==void 0||e.createdBefore!==void 0}function pt(e,t){let n,s,r=new Promise((i,o)=>{n=i,s=o});return{controller:new AbortController,consumers:0,generation:e,promise:r,resolve:n,reject:s,started:!1,listeners:new Set(t?[t]:[])}}function gt(e){if(Object.prototype.hasOwnProperty.call(e,\"tools\"))throw TypeError(\"Message-level tools are not supported; update the session tool policy before sending.\")}function mt(e){if(!(\"agentConfig\"in e)||!e.agentConfig?.machineTarget)return e;let{workingDir:t,...n}=e.agentConfig.machineTarget;if(t===void 0)return e;let s=t.trim();return{...e,agentConfig:{...e.agentConfig,machineTarget:{...n,...s?{workingDir:s}:{}}}}}function on(e){return{forWorkspace(t){let n=t.trim();if(!n)throw TypeError(\"workspaceId is required\");let s,r=()=>s??=Promise.resolve().then(() => (ae(),he)).then(({OpenGeniToolsClient:o})=>new o(e).forWorkspace(n)),i=(o)=>new Proxy(async(...a)=>{let c=await r();for(let l of o)c=c[l];if(typeof c!==\"function\")throw TypeError(\"OpenGeni tool path is not callable\");return await Reflect.apply(c,void 0,a)},{get:(a,c)=>{if(c===\"then\")return;if(typeof c!==\"string\")return;return i([...o,c])}});return new Proxy(Object.create(null),{get:(o,a)=>{if(a===\"then\")return;if(typeof a!==\"string\")return;return i([a])}})}}}class le{externalActorHeader;baseUrl;options;fetchImpl;sessionCommandTimeoutMs;active=new Map;generations=new Map;queued=new Map;interaction;tools;constructor(e){this.baseUrl=e.baseUrl.replace(/\\/+$/,\"\"),this.options=e,this.fetchImpl=e.fetch??((n,s)=>fetch(n,s));let t=e.sessionCommandTimeoutMs??15000;if(!Number.isFinite(t)||t<=0)throw RangeError(\"sessionCommandTimeoutMs must be a finite positive number\");this.sessionCommandTimeoutMs=t,this.interaction=new ce(this),this.tools=on(this)}async transcribeAudio(e,t){let n=crypto.randomUUID(),s=new FormData,r=dn(t.mimeType),i=t.audio instanceof File?t.audio:t.audio instanceof Uint8Array?new File([Uint8Array.from(t.audio)],r,{type:t.mimeType}):new File([t.audio],r,{type:t.mimeType||t.audio.type});if(s.append(\"audio\",i,r),s.append(\"mimeType\",t.mimeType),t.durationSeconds!==void 0)s.append(\"durationSeconds\",String(t.durationSeconds));let o;try{o=await this.fetchImpl(this.url(`/v1/workspaces/${e}/transcriptions`),{method:\"POST\",headers:{...this.headers(n),Accept:\"application/json\"},body:s,...t.signal?{signal:t.signal}:{}})}catch(c){if(t.signal?.aborted)throw c;throw D(n)}if(v(o),!o.ok)throw await S(o,{method:\"POST\",correlationId:n});await N(o,{method:\"POST\",correlationId:n});let a;try{a=await o.json()}catch{throw new y(o.status,\"Invalid transcription response.\",{code:\"invalid_response\",mutation:!0,correlationId:n})}if(!an(a))throw new y(o.status,\"Invalid transcription response.\",{code:\"invalid_response\",mutation:!0,correlationId:n});return a}async createTranscriptionRecording(e,t){return J(await this.requestJson(\"POST\",`/v1/workspaces/${e}/transcription-recordings`,{recordingId:t.recordingId,mimeType:t.mimeType},{},t.signal?{signal:t.signal}:{}))}async getTranscriptionRecording(e,t,n={}){return J(await this.requestJson(\"GET\",`/v1/workspaces/${e}/transcription-recordings/${t}`,void 0,{},n.signal?{signal:n.signal}:{}))}async listTranscriptionRecordings(e,t={}){let n=await this.requestJson(\"GET\",`/v1/workspaces/${e}/transcription-recordings`,void 0,{},t.signal?{signal:t.signal}:{});if(!un(n))throw new y(502,\"Invalid transcription recording list response.\",{code:\"invalid_response\"});return n}async uploadTranscriptionRecordingChunk(e,t,n,s){let r=crypto.randomUUID(),i;try{i=await this.fetchImpl(this.url(`/v1/workspaces/${e}/transcription-recordings/${t}/chunks/${n}`),{method:\"PUT\",headers:{...this.headers(r),Accept:\"application/json\",\"Content-Type\":s.mimeType,\"x-opengeni-chunk-sha256\":s.sha256,\"x-opengeni-chunk-start-milliseconds\":String(s.startMilliseconds),\"x-opengeni-chunk-duration-milliseconds\":String(s.durationMilliseconds)},body:s.audio instanceof Uint8Array?Uint8Array.from(s.audio):s.audio,...s.signal?{signal:s.signal}:{}})}catch(a){if(s.signal?.aborted)throw a;throw D(r)}if(v(i),!i.ok)throw await S(i,{method:\"PUT\",correlationId:r});await N(i,{method:\"PUT\",correlationId:r});let o=await i.json().catch(()=>null);if(!cn(o))throw new y(i.status,\"Invalid transcription chunk response.\",{code:\"invalid_response\",mutation:!0,correlationId:r});return o}async finalizeTranscriptionRecording(e,t,n){return J(await this.requestJson(\"POST\",`/v1/workspaces/${e}/transcription-recordings/${t}/finalize`,{chunkCount:n.chunkCount,totalBytes:n.totalBytes,totalDurationMilliseconds:n.totalDurationMilliseconds},{},n.signal?{signal:n.signal}:{}))}async processNextTranscriptionRecordingSegment(e,t,n={}){return J(await this.requestJson(\"POST\",`/v1/workspaces/${e}/transcription-recordings/${t}/process-next`,{},{},n.signal?{signal:n.signal}:{}))}async discardTranscriptionRecording(e,t,n={}){return J(await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/transcription-recordings/${t}`,void 0,{},n.signal?{signal:n.signal}:{}))}async createSession(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${encodeURIComponent(e)}/sessions`,t)}async getNewSessionDraft(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/new-session-draft`,void 0,{},t)}async saveNewSessionDraft(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/new-session-draft`,t)}async createFeedback(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/feedback`,t)}async listOwnFeedback(e,t={}){let n=new URLSearchParams;if(t.sessionId)n.set(\"sessionId\",t.sessionId);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));if(t.includeTurns!==void 0)n.set(\"includeTurns\",String(t.includeTurns));return this.requestJson(\"GET\",`/v1/workspaces/${e}/feedback${n.size?`?${n}`:\"\"}`)}async getSession(e,t,n={}){let s=`/v1/workspaces/${e}/sessions/${t}`;return await this.sharedRead(s,(r)=>this.requestJson(\"GET\",s,void 0,{},{signal:r}),n)}async getSessionModelContext(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/model-context`)}async updateSession(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/sessions/${t}`,n)}async updateSessionVariableSets(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/variable-sets`,n)}async getSessionTenancyCreateCapabilities(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/session-tenancy/capabilities`)}async updateSessionVisibility(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/visibility`,n)}async forkSession(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/forks`,n)}async updateSessionToolPolicy(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/tool-policy`,n)}async updateSessionMcpApprovalPolicy(e,t,n,s){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/sessions/${t}/mcp-servers/${encodeURIComponent(n)}/approval-policy`,s)}async searchSessionMessages(e,t,n={}){return this.requestJson(\"GET\",`/v1/workspaces/${e}/session-message-search`,void 0,{query:t.query,...t.sessionId!==void 0?{sessionId:t.sessionId}:{},...t.groupBy!==void 0?{groupBy:t.groupBy}:{},...t.archiveStatus!==void 0?{archiveStatus:t.archiveStatus}:{},...t.limit!==void 0?{limit:String(t.limit)}:{},...t.cursor!==void 0?{cursor:t.cursor}:{}},n)}async listSessions(e,t={}){if(t.search?.trim()||t.originSiteId){let n=await this.listSessionPage(e,t);return[...n.pinned,...n.sessions]}return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions`,void 0,dt(t))}async listSessionBackgroundCommands(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/background-commands`,void 0,{},n)}async cancelSessionBackgroundCommand(e,t,n){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}/background-commands/${n}`)}async listSessionPage(e,t={}){let n=t.search?.trim(),s;try{s=await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions`,void 0,{view:\"page\",...dt(t),...t.cursor!==void 0?{cursor:t.cursor}:{},...n?{search:n}:{},...t.channelId!==void 0?{channelId:t.channelId??\"null\"}:{},...t.createdBy?{createdByKind:t.createdBy.kind,createdBySubjectId:t.createdBy.subjectId}:{},...t.updatedFrom?{updatedFrom:t.updatedFrom}:{},...t.updatedBefore?{updatedBefore:t.updatedBefore}:{},...t.createdFrom?{createdFrom:t.createdFrom}:{},...t.createdBefore?{createdBefore:t.createdBefore}:{},...t.pinsOnly?{pinsOnly:\"true\"}:{},...t.archivedOnly?{archivedOnly:\"true\"}:{},...t.sortBy?{sortBy:t.sortBy}:{},...t.archiveStatus?{archiveStatus:t.archiveStatus}:{}},{signal:t.signal})}catch(r){if(r instanceof y&&r.status===410)throw new ie(r.status,r.body,{...r.code?{code:r.code}:{},retryable:r.retryable,...r.correlationId?{correlationId:r.correlationId}:{},outcomeUnknown:r.outcomeUnknown,displayMessage:\"The session list changed \u2014 refresh and try again.\"});throw r}if(t.sortBy!==void 0&&(Array.isArray(s)||s.sortBy!==t.sortBy)||t.archiveStatus!==void 0&&(Array.isArray(s)||s.archiveStatus!==t.archiveStatus))throw Error(\"The connected OpenGeni API does not support the requested session sorting/archive filter\");if(Array.isArray(s)){if(t.cursor)throw Error(\"The connected OpenGeni API does not support stable session-page cursors\");if(n)throw Error(\"The connected OpenGeni API does not support session search\");if(t.pinsOnly)throw Error(\"The connected OpenGeni API does not support pins-only session lists\");if(t.archivedOnly)throw Error(\"The connected OpenGeni API does not support archived session lists\");if(lt(t))throw Error(\"The connected OpenGeni API does not support filtered session lists\");return{pinned:[],sessions:s,nextCursor:null}}if(lt(t)&&s.filtersApplied!==!0)throw Error(\"The connected OpenGeni API does not support filtered session lists\");if(t.originSiteId&&(!s.originSiteId||t.originSiteId!==\"current\"&&s.originSiteId!==t.originSiteId))throw Error(\"The connected OpenGeni API does not support Site-filtered session lists\");return s}async listAgentTopology(e,t={}){let n=t.query?.trim()||t.search?.trim();if(n&&t.subject)throw TypeError(\"listAgentTopology query cannot be combined with an exact subject\");return await this.requestJson(\"GET\",`/v1/workspaces/${e}/agent-topology`,void 0,{...t.limit!==void 0?{limit:String(t.limit)}:{},...t.parentSessionId===void 0?{}:{parentSessionId:t.parentSessionId??\"null\"},...t.rootSessionId?{rootSessionId:t.rootSessionId}:{},...t.cursor?{cursor:t.cursor}:{},...n?{query:n}:{},...t.statuses?.length?{statuses:t.statuses.join(\",\")}:{},...t.activeOnly!==void 0?{activeOnly:t.activeOnly?\"true\":\"false\"}:{},...t.recentHours!==void 0?{recentHours:String(t.recentHours)}:{},...t.subject?{subjectNamespace:t.subject.namespace,subjectType:t.subject.type,subjectKey:t.subject.canonicalKey}:{},...t.claimLimit!==void 0?{claimLimit:String(t.claimLimit)}:{}})}async updateSessionPin(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/pin`,n)}async updateSessionAttention(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/attention`,n)}async updateSessionArchive(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/archive`,n)}async deleteSession(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}`)}async getSessionLineage(e,t,n={}){let s=`/v1/workspaces/${e}/sessions/${t}/lineage`;return await this.sharedRead(s,(r)=>this.requestJson(\"GET\",s,void 0,{},{signal:r}),n)}sharedRead(e,t,n={}){if(n.signal?.aborted)return Promise.reject(n.signal.reason??new DOMException(\"Request aborted\",\"AbortError\"));let s=this.active.get(e);if(s){if(!n.fresh)return this.observeRead(s,n.onRequestStart),this.consumeSharedRead(e,s,n.signal);let c=s.generation+1,l=this.queued.get(e);if(l&&l.generation>=c)return this.observeRead(l,n.onRequestStart),this.consumeSharedRead(e,l,n.signal);let d=l?.promise??s.promise;return this.queueRead(e,d,c,t,n)}let r=this.queued.get(e);if(r&&(!n.fresh||!r.started))return this.observeRead(r,n.onRequestStart),this.consumeSharedRead(e,r,n.signal);if(r)return this.queueRead(e,r.promise,r.generation+1,t,n);let i=(this.generations.get(e)??0)+1,o=pt(i,n.onRequestStart),a=this.consumeSharedRead(e,o,n.signal);return this.launchRead(e,o,t),a}queueRead(e,t,n,s,r){let i=pt(n,r.onRequestStart),o=this.consumeSharedRead(e,i,r.signal);this.queued.set(e,i);let a=()=>this.launchRead(e,i,s);t.then(a,a);let c=()=>{if(this.queued.get(e)!==i)return;if(this.queued.delete(e),!this.active.has(e))this.generations.delete(e)};return i.promise.then(c,c),o}launchRead(e,t,n){if(t.controller.signal.aborted)return;t.started=!0,this.generations.set(e,t.generation),this.active.set(e,t);try{t.stamp=this.options.beginSharedRead?.()}catch{}for(let i of t.listeners)try{i(t.stamp)}catch{}t.listeners.clear();let s=()=>{if(this.active.get(e)!==t)return;if(this.active.delete(e),!this.queued.has(e))this.generations.delete(e)},r;try{r=n(t.controller.signal)}catch(i){s(),t.reject(i);return}r.then((i)=>{s(),t.resolve(i)},(i)=>{s(),t.reject(i)})}consumeSharedRead(e,t,n){t.consumers+=1;let s=!1,r=()=>{if(s)return;if(s=!0,t.consumers-=1,!n?.aborted||t.consumers>0)return;let o=n.reason;if(t.controller.abort(o),this.active.get(e)===t)this.active.delete(e);if(this.queued.get(e)===t)this.queued.delete(e);if(!this.active.has(e)&&!this.queued.has(e))this.generations.delete(e);t.reject(o)};return n?.addEventListener(\"abort\",r,{once:!0}),V(t.promise,n).finally(()=>{n?.removeEventListener(\"abort\",r),r()})}observeRead(e,t){if(!t)return;if(!e.started){e.listeners.add(t);return}if(e.stamp===void 0)return;try{t(e.stamp)}catch{}}async negotiateCodexRealtimeWebrtc(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/webrtc`,n,{},{signal:s.signal})}async negotiateGatewayRealtime(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/gateway`,n,{},{signal:s.signal})}async negotiateXaiSubscriptionRealtime(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/supergrok`,n,{},{signal:s.signal})}async activateCodexRealtimeConnection(e,t,n,s,r,i={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/${n}/connections/${s}/activate`,r,{},{signal:i.signal})}async beginSessionRealtime(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime`,n)}async heartbeatSessionRealtime(e,t,n,s){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/sessions/${t}/realtime/${n}/heartbeat`,s)}async syncSessionRealtimeLedger(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/${n}/sync`,s)}async endSessionRealtime(e,t,n,s){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}/realtime/${n}`,s)}async listTurns(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/turns`,void 0,{...n.limit!==void 0?{limit:String(n.limit)}:{},...n.latestStarted?{latestStarted:\"1\"}:{}},{signal:n.signal})}async getLatestStartedTurn(e,t,n={}){return(await this.listTurns(e,t,{latestStarted:!0,signal:n.signal}))[0]??null}async listMachines(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/machines`,void 0,{...t.sessionId!==void 0?{sessionId:t.sessionId}:{}},{signal:t.signal})}async updateMachineAgent(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/machines/${t}/update`)}async updateMachineOperationPolicy(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/machines/${t}/operation-policy`,n)}async machineMetricsSeries(e,t,n={}){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/machines/${t}/metrics/series`,void 0,{...n.window!==void 0?{window:n.window}:{}})).samples}async removeEnrollment(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/enrollments/${t}/revoke`,n)}async lookupDeviceEnrollment(e){return await this.requestJson(\"POST\",\"/v1/enrollments/device/lookup\",{userCode:e})}async approveDeviceEnrollment(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/enrollments/device/approve`,{userCode:t.userCode,allowScreenControl:t.allowScreenControl??!1,...t.scope?{scope:t.scope}:{}})}async denyDeviceEnrollment(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/enrollments/device/deny`,{userCode:t.userCode})}async mintEnrollToken(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/enrollments/token`,{allowScreenControl:t.allowScreenControl??!1})}async swapActiveSandbox(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/active-sandbox`,n)}async listScheduledTasks(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/scheduled-tasks`,void 0,{...t.offset!==void 0?{offset:String(t.offset)}:{},...t.sessionId?{sessionId:t.sessionId}:{},...t.limit!==void 0?{limit:String(t.limit)}:{}})}async getScheduledTask(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/scheduled-tasks/${t}`)}async listEvents(e,t,n={}){return(await this.listEventPage(e,t,n)).events}async listEventPage(e,t,n={}){if(n.latest&&[\"includeTypes\",\"excludeTypes\",\"includeClasses\",\"excludeClasses\"].some((h)=>Object.prototype.hasOwnProperty.call(n,h)))throw TypeError(\"latest cannot be combined with event filters\");if(n.resultMode===\"compact\"&&!n.latest)throw TypeError(\"resultMode=compact requires latest\");let s=n.resultMode===\"compact\"?null:n,r=crypto.randomUUID(),i=await this.fetchImpl(this.url(`/v1/workspaces/${e}/sessions/${t}/events`,{...s?.after!==void 0?{after:String(s.after)}:{},...s?.before!==void 0?{before:String(s.before)}:{},...s?.limit!==void 0?{limit:String(s.limit)}:{},...s?.compact?{compact:\"1\"}:{},...n.mode?{mode:n.mode}:{},...s?.direction?{direction:s.direction}:{},...n.payloadMode?{payloadMode:n.payloadMode}:{},...n.resultMode?{resultMode:n.resultMode}:{},...s?.includeTypes?.length?{includeTypes:s.includeTypes.join(\",\")}:{},...s?.excludeTypes?.length?{excludeTypes:s.excludeTypes.join(\",\")}:{},...s?.includeClasses?.length?{includeClasses:s.includeClasses.join(\",\")}:{},...s?.excludeClasses?.length?{excludeClasses:s.excludeClasses.join(\",\")}:{},...n.latest?{latest:n.latest}:{}}),{method:\"GET\",headers:{...this.headers(r),Accept:\"application/json\"}});if(v(i),!i.ok)throw await S(i,{method:\"GET\",correlationId:r});await N(i,{method:\"GET\",correlationId:r});let o=await i.json();if(n.resultMode===\"compact\")return o;let a=o,c=(h)=>{let A=i.headers.get(h);if(A===null)return null;let F=Number(A);return Number.isSafeInteger(F)&&F>=0?F:null},l=i.headers.get(\"X-OpenGeni-Event-Mode\")===\"forensic\"?\"forensic\":\"monitoring\",d=i.headers.get(\"X-OpenGeni-Event-Direction\")===\"after\"?\"after\":\"before\",p=i.headers.get(\"X-OpenGeni-Payload-Mode\"),u=p===\"none\"||p===\"full\"?p:\"summary\",g=c(\"X-OpenGeni-Covered-First\"),b=c(\"X-OpenGeni-Covered-Last\"),m=c(\"X-OpenGeni-Page-Bytes\")??new TextEncoder().encode(JSON.stringify(a)).byteLength,f=c(\"X-OpenGeni-Page-Max-Bytes\")??1048576,R=i.headers.get(\"X-OpenGeni-Truncated-By\"),w=R===\"count\"||R===\"bytes\"||R===\"http_bytes\"?R:null;return{events:a,mode:l,payloadMode:u,direction:d,bytes:m,maxBytes:f,truncated:i.headers.get(\"X-OpenGeni-Page-Truncated\")===\"true\",hasMore:i.headers.get(\"X-OpenGeni-Has-More\")===\"true\",truncatedBy:w,coveredSequence:g===null||b===null?null:{first:g,last:b},nextAfter:c(\"X-OpenGeni-Next-After\"),nextBefore:c(\"X-OpenGeni-Next-Before\"),forensicExact:i.headers.get(\"X-OpenGeni-Forensic-Exact\")===\"true\"}}async getLatestEventResult(e,t,n={latest:\"terminal\"}){return await this.listEventPage(e,t,{...n,resultMode:\"compact\"})}async sendEvent(e,t,n){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/events`,n)}async sendMessage(e,t,n){let s=typeof n===\"string\"?{text:n}:n;gt(s);let{clientEventId:r,...i}=s;return await this.sendEvent(e,t,{type:\"user.message\",...r!==void 0?{clientEventId:r}:{},payload:i})}async pauseSession(e,t,n={}){return await this.controlSession(e,t,{action:\"pause\",clientEventId:n.clientEventId??crypto.randomUUID(),...n.reason?{reason:n.reason}:{},...n.expectedControlEtag?{expectedControlEtag:n.expectedControlEtag}:{}})}async sendApprovalDecision(e,t,n){let{clientEventId:s,...r}=n;return await this.sendEvent(e,t,{type:\"user.approvalDecision\",...s!==void 0?{clientEventId:s}:{},payload:r})}async listHumanInputRequests(e,t,n={}){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/human-input-requests`,void 0,n.status?{status:n.status}:void 0)).requests}async getHumanInputRequest(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/human-input-requests/${n}`)}async submitHumanInputResponse(e,t,n,s,r={}){return await this.sendEvent(e,t,{type:\"user.humanInputResponse\",...r.clientEventId?{clientEventId:r.clientEventId}:{},payload:{requestId:n,response:s}})}streamEvents(e,t,n={}){return ve(this.eventStreamTransport(e,t),n)}eventStreamTransport(e,t){return{openStream:async(n,s)=>await this.openEventStream(e,t,{after:n,...s?{signal:s}:{}}),listEvents:async(n,s)=>await this.listEvents(e,t,{after:n,limit:s})}}async openEventStream(e,t,n={}){let s=this.url(`/v1/workspaces/${e}/sessions/${t}/events/stream`,{after:String(n.after??0)}),r=crypto.randomUUID(),i=await this.fetchImpl(s,{method:\"GET\",headers:{...this.headers(r),Accept:\"text/event-stream\"},...n.signal?{signal:n.signal}:{}});if(v(i),!i.ok)throw await S(i,{method:\"GET\",correlationId:r});if(!i.body)throw new y(i.status,\"SSE response did not include a readable body\");return i.body}async getQueue(e,t){let n=`/v1/workspaces/${e}/sessions/${t}/queue`;return await this.sharedRead(n,()=>this.requestSessionCommand(\"GET\",n))}async moveQueueItem(e,t,n,s){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/queue/${n}/move`,s)}async editQueueItem(e,t,n,s){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/queue/${n}/edit`,s)}async steerQueueItem(e,t,n,s){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/queue/${n}/steer`,s)}async deleteQueueItem(e,t,n,s){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/queue/${n}/delete`,s)}async getComposerDraft(e,t,n={}){return await this.requestSessionCommand(\"GET\",`/v1/workspaces/${e}/sessions/${t}/composer-draft`,void 0,n)}async saveComposerDraft(e,t,n){return await this.requestSessionCommand(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/composer-draft`,n)}async submitComposerDraft(e,t,n){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/composer-draft/submit`,n)}async getSandboxRecovery(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/sandbox-recovery`)}async recoverSandbox(e,t,n){return this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/sandbox-recovery`,n)}async retrySession(e,t,n){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/retry`,n)}async controlSession(e,t,n){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/control`,n)}async resumeSession(e,t,n={}){return await this.controlSession(e,t,{action:\"resume\",clientEventId:n.clientEventId??crypto.randomUUID(),...n.reason?{reason:n.reason}:{},...n.expectedControlEtag?{expectedControlEtag:n.expectedControlEtag}:{}})}async cancelSession(e,t,n={}){return await this.controlSession(e,t,{action:\"cancel\",clientEventId:n.clientEventId??crypto.randomUUID(),...n.reason?{reason:n.reason}:{},...n.expectedControlEtag?{expectedControlEtag:n.expectedControlEtag}:{}})}async setWorkspacePauseTimer(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/pause-timer`,t)}async setWorkspaceInferenceState(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/inference-control`,t)}async listWorkspaceControlEvents(e,t={}){return(await this.listWorkspaceControlEventPage(e,t)).events}async listWorkspaceControlEventPage(e,t={}){let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(`/v1/workspaces/${e}/control-events`,{...t.after!==void 0?{after:String(t.after)}:{},...t.limit!==void 0?{limit:String(t.limit)}:{}}),{method:\"GET\",headers:{...this.headers(n),Accept:\"application/json\"}});if(v(s),!s.ok)throw await S(s,{method:\"GET\",correlationId:n});await N(s,{method:\"GET\",correlationId:n});let r=await s.json(),i=s.headers.get(\"X-OpenGeni-Page-Bytes\"),o=s.headers.get(\"X-OpenGeni-Next-After\"),a=i===null?Number.NaN:Number(i),c=o===null?null:Number(o);return{events:r,bytes:Number.isSafeInteger(a)&&a>=0?a:new TextEncoder().encode(JSON.stringify(r)).byteLength,truncated:s.headers.get(\"X-OpenGeni-Page-Truncated\")===\"true\",nextAfter:c!==null&&Number.isSafeInteger(c)&&c>=0?c:null}}streamWorkspaceControlEvents(e,t={}){return Ie(this.workspaceControlStreamTransport(e),t)}streamWorkspaceLiveEvents(e,t={}){return Pe(this.workspaceLiveStreamTransport(e),t)}workspaceLiveStreamTransport(e){return{openStream:async(t,n,s)=>await this.openWorkspaceLiveEventStream(e,{controlAfter:t,interactionAfter:n,...s?{signal:s}:{}})}}async openWorkspaceLiveEventStream(e,t={}){let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(`/v1/workspaces/${e}/live-events/stream`,{controlAfter:String(t.controlAfter??0),interactionAfter:String(t.interactionAfter??0)}),{method:\"GET\",headers:{...this.headers(n),Accept:\"text/event-stream\"},...t.signal?{signal:t.signal}:{}});if(v(s),!s.ok)throw await S(s,{method:\"GET\",correlationId:n});if(!s.body)throw new y(s.status,\"SSE response did not include a readable body\");return s.body}workspaceControlStreamTransport(e){return{openStream:async(t,n)=>await this.openWorkspaceControlEventStream(e,{after:t,...n?{signal:n}:{}})}}async openWorkspaceControlEventStream(e,t={}){let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(`/v1/workspaces/${e}/control-events/stream`,{after:String(t.after??0)}),{method:\"GET\",headers:{...this.headers(n),Accept:\"text/event-stream\"},...t.signal?{signal:t.signal}:{}});if(v(s),!s.ok)throw await S(s,{method:\"GET\",correlationId:n});if(!s.body)throw new y(s.status,\"SSE response did not include a readable body\");return s.body}async steerMessage(e,t,n){let s=typeof n===\"string\"?{text:n}:n;return gt(s),await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/steer`,s)}async getGoal(e,t,n={}){let s=`/v1/workspaces/${e}/sessions/${t}/goal`;return await this.sharedRead(s,(r)=>this.requestJson(\"GET\",s,void 0,{},{signal:r}),n)}async updateGoal(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/sessions/${t}/goal`,n)}async listGoalRevisions(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions`)}async listGoalRevisionPage(e,t,n={}){let s=new URLSearchParams;if(n.limit!==void 0)s.set(\"limit\",String(n.limit));if(n.before!==void 0)s.set(\"before\",n.before);let r=s.size>0?`?${s.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions/page${r}`)}async rejectGoalRevision(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions/${n}/reject`,s)}async rollbackGoalRevision(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions/${n}/rollback`,s)}async applyGoalRevision(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions/${n}/apply`,s)}async deleteGoal(e,t){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}/goal`)}async pauseGoal(e,t,n={}){return await this.updateGoal(e,t,{status:\"paused\",...n.rationale!==void 0?{rationale:n.rationale}:{}})}async resumeGoal(e,t){return await this.updateGoal(e,t,{status:\"active\"})}async clearSessionContext(e,t){await this.requestVoid(\"POST\",`/v1/workspaces/${e}/sessions/${t}/context/clear`,{confirm:!0})}async compactSessionContext(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/context/compact`,{})}async fsList(e,t,n={},s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/list`,n,{},s)}async fsListBatch(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/list-batch`,n,{},s)}async fsRead(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/read`,n,{},s)}async publishSandboxFileArtifact(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/artifacts/publish`,n,{},s)}async fsWrite(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/write`,n)}async fsDelete(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/delete`,n)}async fsMove(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/move`,n)}async fsMkdir(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/mkdir`,n)}async gitStatus(e,t,n={},s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/status`,n,{},s)}async gitDiff(e,t,n={},s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/diff`,n,{},s)}async gitReadBatch(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/read-batch`,n,{},s)}async gitLog(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/log`,n)}async gitShow(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/show`,n)}async getWorkspaceCapture(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/workspace/capture`,void 0,{},n)}async getWorkspaceCaptureFile(e,t,n,s,r={}){let i={path:n};if(s!==void 0)i.revision=String(s);return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/workspace/capture/file`,void 0,i,r)}async terminalExec(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/exec`,n)}async terminalPtyOpen(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/pty`,n)}async terminalPtyWrite(e,t,n){await this.requestVoid(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/pty/write`,n)}async terminalPtyResize(e,t,n){await this.requestVoid(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/pty/resize`,n)}async terminalPtyClose(e,t,n){await this.requestVoid(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/pty/close`,n)}async getStreamCapabilities(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/stream-capabilities`,void 0,{},n)}async acknowledgeStream(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/stream-capabilities/acknowledge`,n)}async attachViewer(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/viewers`,n)}async heartbeatViewer(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/viewers/${n}/heartbeat`,s)}async detachViewer(e,t,n){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}/viewers/${n}`)}streamWorkspaceInteractionRevisions(e,t={}){return xe(this.workspaceInteractionRevisionStreamTransport(e),t)}workspaceInteractionRevisionStreamTransport(e){return{openStream:async(t,n)=>await this.openWorkspaceInteractionRevisionStream(e,{after:t,...n?{signal:n}:{}})}}async openWorkspaceInteractionRevisionStream(e,t={}){let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(`/v1/workspaces/${e}/interaction-events/stream`,{after:String(t.after??0)}),{method:\"GET\",headers:{...this.headers(n),Accept:\"text/event-stream\"},...t.signal?{signal:t.signal}:{}});if(v(s),!s.ok)throw await S(s,{method:\"GET\",correlationId:n});if(!s.body)throw new y(s.status,\"SSE response did not include a readable body\");return s.body}async listNetworkRoutes(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/network-routes`,void 0,t.includeArchived?{includeArchived:\"true\"}:{},t)}async getNetworkRoute(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/network-routes/${encodeURIComponent(t)}`,void 0,{},n)}async createNetworkRoute(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/network-routes`,t,{},n)}async updateNetworkRoute(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/network-routes/${encodeURIComponent(t)}`,n,{},s)}async listSiteAuthConnections(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/site-auth-connections`,void 0,t.includeArchived?{includeArchived:\"true\"}:{},t)}async getSiteAuthConnection(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/site-auth-connections/${encodeURIComponent(t)}`,void 0,{},n)}async createSiteAuthConnection(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/site-auth-connections`,t,{},n)}async updateSiteAuthConnection(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/site-auth-connections/${encodeURIComponent(t)}`,n,{},s)}async listAuthRuns(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/auth-runs`,void 0,{...t.browserSessionId?{browserSessionId:t.browserSessionId}:{},...t.siteAuthConnectionId?{siteAuthConnectionId:t.siteAuthConnectionId}:{},...t.includeSettled?{includeSettled:\"true\"}:{}},t)}async getAuthRun(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/auth-runs/${encodeURIComponent(t)}`,void 0,{},n)}async startBrowserAuthRun(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs`,n,{},s)}async reportBrowserAuthRun(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/report`,s,{},r)}async protectedBrowserAuthFill(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/protected-fill`,s,{},r)}async advanceExternalBrowserAuthRun(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/external-auth`,s,{},r)}async openExternalBrowserAuthFlow(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/external-auth/interactive`,s,{},r)}async verifyBrowserAuthRun(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/verify`,s,{},r)}async listInteractionInterventions(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/interaction-interventions`,void 0,{...t.resourceKind?{resourceKind:t.resourceKind}:{},...t.resourceId?{resourceId:t.resourceId}:{},...t.includeSettled?{includeSettled:\"true\"}:{}},t)}async getInteractionIntervention(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/interaction-interventions/${encodeURIComponent(t)}`,void 0,{},n)}async createInteractionIntervention(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/interaction-interventions`,t,{},n)}async resolveInteractionIntervention(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/interaction-interventions/${encodeURIComponent(t)}/resolve`,n,{},s)}async listAttachedBrowsers(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/attached-browsers`,void 0,t.includeDisconnected?{includeDisconnected:\"true\"}:{},t)}async getAttachedBrowser(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/attached-browsers/${encodeURIComponent(t)}`,void 0,{},n)}async listBrowserIdentities(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-identities`,void 0,t.includeArchived?{includeArchived:\"true\"}:{},t)}async getBrowserIdentity(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-identities/${encodeURIComponent(t)}`,void 0,{},n)}async createBrowserIdentity(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-identities`,t,{},n)}async updateBrowserIdentity(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/browser-identities/${encodeURIComponent(t)}`,n,{},s)}async listBrowserRevisions(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-identities/${encodeURIComponent(t)}/revisions`,void 0,{},n)}async listBrowserSessions(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions`,void 0,{},t)}async getBrowserSession(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}`,void 0,{},n)}async readBrowserClipboard(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/clipboard`,void 0,{},n)}async listBrowserDownloads(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/downloads`,void 0,{},n)}async getBrowserDownload(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/downloads/${encodeURIComponent(n)}`,void 0,{},s)}async saveBrowserDownload(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/downloads/${encodeURIComponent(n)}/save`,s,{},r)}async createBrowserSession(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions`,t,{},n)}async listBrowserTargets(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets`,void 0,{},n)}async openBrowserTarget(e,t,n={},s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets`,n,{},s)}async selectBrowserTarget(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/select`,{},{},s)}async closeBrowserTarget(e,t,n,s={}){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}`,void 0,{},s)}async observeBrowserTarget(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/observation`,void 0,{},s)}async actInBrowser(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/actions`,n,{},s)}async getBrowserActionReceipt(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/operations/${encodeURIComponent(n)}`,void 0,{},s)}async listBrowserDiagnostics(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/diagnostics`,void 0,{...s.kinds?.length?{kinds:s.kinds.join(\",\")}:{},...s.after!==void 0?{after:String(s.after)}:{},...s.limit!==void 0?{limit:String(s.limit)}:{}},s.signal?{signal:s.signal}:{})}async attachBrowserSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/attachments`,n,{},s)}async heartbeatBrowserSession(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/heartbeat`,{},{},n)}async publishBrowserRevision(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/revisions`,n,{},s)}async suspendBrowserSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/suspend`,n,{},s)}async resumeBrowserSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/resume`,n,{},s)}async endBrowserSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/end`,n,{},s)}async listComputerSessions(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions`,void 0,{},t)}async getComputerSession(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}`,void 0,{},n)}async readComputerClipboard(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/clipboard`,void 0,{},n)}async createComputerSession(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions`,t,{},n)}async listComputerTargets(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/targets`,void 0,{},n)}async observeComputerTarget(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/observation`,void 0,{},s)}async captureComputerTarget(e,t,n,s={}){let r=await this.requestResponse(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/screenshot`,{},s),i=r.headers.get(\"content-type\")?.split(\";\",1)[0]?.trim().toLowerCase();if(i!==\"image/jpeg\"&&i!==\"image/png\")throw await x(r,\"computer frame media type is invalid\"),new y(502,\"computer frame media type is invalid\");let o=r.headers.get(\"x-opengeni-computer-frame\");if(!o||o.length>32768)throw await x(r,\"computer frame metadata is invalid\"),new y(502,\"computer frame metadata is invalid\");let a;try{a=et(o)}catch{throw await x(r,\"computer frame metadata is invalid\"),new y(502,\"computer frame metadata is invalid\")}let c=await se(r,262144,null);if(yn(a,{computerSessionId:t,targetId:n,mediaType:i,sha256:await Rt(c)}))throw new y(502,\"computer frame evidence does not match its request\");return{...a,data:c}}async actInComputer(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/actions`,n,{},s)}async getComputerActionReceipt(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/operations/${encodeURIComponent(n)}`,void 0,{},s)}async attachComputerSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/attachments`,n,{},s)}async heartbeatComputerSession(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/heartbeat`,{},{},n)}async endComputerSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/end`,n,{},s)}async getClientConfig(e={}){let t=await this.requestJson(\"GET\",\"/v1/config/client\",void 0,{},e);if(t.apiContractRevision!==U)throw new H(U,String(t.apiContractRevision||\"(missing)\"));return t}async getWorkspaceModelCatalog(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/model-catalog`,void 0,{},t)}async listWorkspaceGatewayCustomModels(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/gateway-custom-models`)}async createWorkspaceGatewayCustomModel(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/gateway-custom-models`,t)}async deleteWorkspaceGatewayCustomModel(e,t,n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t))throw TypeError(\"customModelId must be a UUID\");await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/gateway-custom-models/${encodeURIComponent(t)}`,n)}async listWorkspaceOpenRouterCustomModels(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/openrouter-custom-models`)}async createWorkspaceOpenRouterCustomModel(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/openrouter-custom-models`,t)}async deleteWorkspaceOpenRouterCustomModel(e,t,n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t))throw TypeError(\"customModelId must be a UUID\");await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/openrouter-custom-models/${encodeURIComponent(t)}`,n)}async getOrganizationModelProviderConnection(e,t){return await this.requestJson(\"GET\",`/v1/organizations/${e}/model-providers/${t}`)}async upsertOrganizationModelProviderConnection(e,t,n){return await this.requestJson(\"PUT\",`/v1/organizations/${e}/model-providers/${t}`,n)}async revokeOrganizationModelProviderConnection(e,t,n){return await this.requestJson(\"DELETE\",`/v1/organizations/${e}/model-providers/${t}`,n)}async listOrganizationProviderCustomModels(e,t){return await this.requestJson(\"GET\",`/v1/organizations/${e}/model-providers/${t}/custom-models`)}async createOrganizationProviderCustomModel(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/model-providers/${t}/custom-models`,n)}async deleteOrganizationProviderCustomModel(e,t,n,s){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(n))throw TypeError(\"customModelId must be a UUID\");return await this.requestJson(\"DELETE\",`/v1/organizations/${e}/model-providers/${t}/custom-models/${encodeURIComponent(n)}`,s)}async getWorkspaceModelAccessPolicy(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/model-policy`)}async updateWorkspaceModelAccessPolicy(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/model-policy`,t)}async getWorkspaceRealtimeModelCatalog(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/realtime-model-catalog`,void 0,{},t)}async getAccessContext(){return await this.requestJson(\"GET\",\"/v1/access/me\")}async listOrganizationMemberships(){return await this.requestJson(\"GET\",\"/v1/organization-memberships\")}async listUserResourceAuthorities(e,t){let n=new URLSearchParams({scope:\"user\",resourceKind:t.resourceKind});if(t.cursor)n.set(\"cursor\",t.cursor);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));return await this.requestJson(\"GET\",`/v1/workspaces/${e}/user-resource-authorities?${n.toString()}`)}async revokeUserResourceGrant(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/user-resource-authorities/grants/${t}?scope=user`)}async createOrganization(e){return await this.requestJson(\"POST\",\"/v1/organizations\",e)}async createAdditionalOrganization(e){return await this.requestJson(\"POST\",\"/v1/organizations/additional\",e)}async listOrganizationInvitations(e={}){let t=new URLSearchParams;if(e.cursor)t.set(\"cursor\",e.cursor);if(e.limit!==void 0)t.set(\"limit\",String(e.limit));let n=t.size>0?`?${t.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/organization-invitations${n}`)}async listOrganizationInvitationsForOrganization(e,t={}){let n=new URLSearchParams;if(t.cursor)n.set(\"cursor\",t.cursor);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.size>0?`?${n.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/organizations/${e}/invitations${s}`)}async createOrganizationInvitation(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/invitations`,t)}async acceptOrganizationInvitation(e,t){return await this.requestJson(\"POST\",`/v1/organization-invitations/${e}/accept`,t)}async revokeOrganizationInvitation(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/invitations/${t}/revoke`,n)}async listOrganizationAdministrationMembers(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/members`)}async listOrganizationMembers(e){return await this.listOrganizationAdministrationMembers(e)}async getOrganizationAdministrationOverview(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/overview`)}async createOrganizationWorkspace(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/workspaces`,t)}async updateOrganizationWorkspace(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/workspaces/${t}`,n)}async updateOrganizationWorkspaceSettings(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/workspaces/${t}/settings`,n)}async deleteOrganizationWorkspace(e,t){await this.requestVoid(\"DELETE\",`/v1/organizations/${e}/workspaces/${t}`)}async putOrganizationWorkspaceMember(e,t,n,s){return await this.requestJson(\"PUT\",`/v1/organizations/${e}/workspaces/${t}/members/${n}`,s)}async revokeOrganizationWorkspaceMember(e,t,n,s){return await this.requestJson(\"POST\",`/v1/organizations/${e}/workspaces/${t}/members/${n}/revoke`,s)}async updateOrganizationName(e,t){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}`,t)}async updateOrganizationMember(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/members/${t}`,n)}async getOrganizationRetentionPolicy(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/retention-policy`)}async updateOrganizationRetentionPolicy(e,t){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/retention-policy`,t)}async getOrganizationRecovery(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/recovery`)}async configureOrganizationRecoveryPolicy(e,t){return await this.requestJson(\"PUT\",`/v1/organizations/${e}/recovery/policy`,t)}async acceptOrganizationRecoveryCustody(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/policy/accept`,t)}async disableOrganizationRecoveryPolicy(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/policy/disable`,t)}async startOrganizationRecoveryOperation(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/operations`,t)}async approveOrganizationRecoveryOperation(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/operations/${t}/approve`,n)}async cancelOrganizationRecoveryOperation(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/operations/${t}/cancel`,n)}async executeOrganizationRecoveryOperation(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/operations/${t}/execute`,n)}async searchPublicSkills(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/skills/search?q=${encodeURIComponent(t)}`)}async listWorkspaces(){return await this.requestJson(\"GET\",\"/v1/workspaces\")}connectTransport(){let e=(t)=>`/v1/workspaces/${encodeURIComponent(t)}/connect`;return{catalog:(t,n)=>this.requestJson(\"GET\",`${e(t)}/catalog`,void 0,void 0,n),accounts:(t,n)=>this.requestJson(\"GET\",`${e(t)}/accounts`,void 0,void 0,n),pending:(t,n)=>this.requestJson(\"GET\",`${e(t)}/attempts`,void 0,void 0,n),begin:(t,n,s)=>this.requestJson(\"POST\",`${e(t)}/attempts`,n,void 0,s),get:(t,n,s)=>this.requestJson(\"GET\",`${e(t)}/attempts/${encodeURIComponent(n)}`,void 0,void 0,s),advance:(t,n,s,r)=>this.requestJson(\"POST\",`${e(t)}/attempts/${encodeURIComponent(n)}/advance`,s,void 0,r),cancel:(t,n,s,r)=>this.requestJson(\"POST\",`${e(t)}/attempts/${encodeURIComponent(n)}/cancel`,s,void 0,r),disconnect:async(t,n,s)=>{if(n.startsWith(\"social:\")){let o=n.slice(7);if(!/^[0-9a-f-]{36}$/i.test(o))throw Error(\"Invalid social account ID\");await this.disconnectSocialConnection(t,o);return}if(n.startsWith(\"lens-registration:\")){let o=n.slice(18);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o))throw Error(\"Invalid Lens registration ID\");await this.requestJson(\"DELETE\",`/v1/workspaces/${encodeURIComponent(t)}/pr-review/registrations/${o}`,void 0,void 0,s);return}if(n.startsWith(\"github-installation:\")){let o=n.slice(20);if(!/^[1-9][0-9]*$/.test(o)||!Number.isSafeInteger(Number(o)))throw Error(\"Invalid GitHub installation ID\");await this.requestJson(\"DELETE\",`/v1/workspaces/${encodeURIComponent(t)}/github/installations/${o}`,void 0,void 0,s);return}let r=s?.expectedVersion;if(r!==void 0&&(!Number.isSafeInteger(r)||r<1))throw Error(\"invalid expected connection version\");let i=r===void 0?\"\":`?expectedVersion=${r}`;await this.requestJson(\"DELETE\",`/v1/workspaces/${encodeURIComponent(t)}/connections/${encodeURIComponent(n)}${i}`,void 0,void 0,s)}}}async browseAtlassianSources(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/atlassian/${t}/browse`)}async saveAtlassianSources(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/atlassian/${t}/source`,n)}async setAtlassianLifecycle(e,t,n){return this.requestJson(\"PATCH\",`/v1/workspaces/${e}/connections/atlassian/${t}/lifecycle`,n)}async beginConnect(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/connect/attempts`,t)}async createWorkspace(e){return await this.requestJson(\"POST\",\"/v1/workspaces\",e)}async ensureWorkspace(e){return await this.requestJson(\"PUT\",\"/v1/workspaces/external\",e)}async getWorkspace(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}`)}async getWorkspaceState(e,t={}){let n=new URLSearchParams;if(t.attemptId)n.set(\"attemptId\",t.attemptId);let s=n.size>0?`?${n.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${e}/workspace-state${s}`)}async exportWorkspaceState(e,t={}){let n=new URLSearchParams;if(t.attemptId)n.set(\"attemptId\",t.attemptId);let s=n.size>0?`?${n.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${e}/workspace-state/export${s}`)}async updateWorkspace(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}`,t)}async listWorkspaceInstructionPolicies(e,t={}){let n=new URLSearchParams;if(t.kind!==void 0)n.set(\"kind\",t.kind);if(t.scope!==void 0)n.set(\"scope\",t.scope);if(t.roleKey!==void 0)n.set(\"roleKey\",t.roleKey);if(t.afterRevision!==void 0)n.set(\"afterRevision\",String(t.afterRevision));if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/instruction-policies${s?`?${s}`:\"\"}`)}async getWorkspaceLearningHistory(e,t={}){let n=new URLSearchParams;if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/learning${s?`?${s}`:\"\"}`)}async undoGovernedLearningActivation(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/learning/activations/${encodeURIComponent(t)}/undo`,n)}async getWorkspaceInstructionPolicyRevision(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/instruction-policies/${encodeURIComponent(t)}`)}async createWorkspaceInstructionPolicyDraft(e,t,n={}){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/instruction-policies/drafts`,t,n)}async listWorkspaceInstructionPolicyOnboardingProposals(e,t={}){let n=new URLSearchParams;if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/instruction-policies/onboarding-proposals${s?`?${s}`:\"\"}`)}async createWorkspaceInstructionPolicyOnboardingProposal(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/instruction-policies/onboarding-proposals`,t)}async importLegacyWorkspaceInstructionPolicyDraft(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/instruction-policies/import-legacy`,t)}async diffWorkspaceInstructionPolicyRevisions(e,t){let n=new URLSearchParams({fromRevisionId:t.fromRevisionId,toRevisionId:t.toRevisionId});return await this.requestJson(\"GET\",`/v1/workspaces/${e}/instruction-policies/diff?${n}`)}async activateWorkspaceInstructionPolicyRevision(e,t,n,s={}){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/instruction-policies/${encodeURIComponent(t)}/activate`,n,s)}async rollbackWorkspaceInstructionPolicyRevision(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/instruction-policies/rollback`,t)}async listCompanyProfile(e,t={}){let n=new URLSearchParams;if(t.afterRevision!==void 0)n.set(\"afterRevision\",String(t.afterRevision));if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/company-profile${s?`?${s}`:\"\"}`)}async getCompanyProfileRevision(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/company-profile/revisions/${encodeURIComponent(t)}`)}async getCompanyProfileAgentPolicy(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/company-profile/agent-policy`)}async updateCompanyProfileAgentPolicy(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/company-profile/agent-policy`,t)}async updateCompanyProfile(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/company-profile`,t)}async diffCompanyProfileRevisions(e,t){let n=new URLSearchParams(t);return await this.requestJson(\"GET\",`/v1/workspaces/${e}/company-profile/diff?${n}`)}async activateCompanyProfileRevision(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/company-profile/revisions/${encodeURIComponent(t)}/activate`,n)}async rollbackCompanyProfile(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/company-profile/rollback`,t)}async listPreferenceRegistry(e,t={}){let n=new URLSearchParams;if(t.scope)n.set(\"scope\",t.scope);if(t.status)n.set(\"status\",t.status);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/preferences${s?`?${s}`:\"\"}`)}async getPreferenceRegistry(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}`)}async createPreferenceRegistryProposal(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/proposals`,t)}async activatePreferenceRegistryRevision(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/activate`,n)}async correctPreferenceRegistry(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/correct`,n)}async changePreferenceRegistryScope(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/scope`,n)}async deactivatePreferenceRegistry(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/deactivate`,n)}async supersedePreferenceRegistry(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/supersede`,n)}async rejectPreferenceRegistryProposal(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/reject`,n)}async getPreferenceRegistrySummary(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/preferences/summary`)}async getPreferenceRegistryFullContent(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/full-content`,{retrievalHandle:t})}async deleteWorkspace(e){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}`)}async listWorkspaceMembers(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/members`)).members}async listWorkspaceMemberCandidates(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/member-candidates`)).members}async addWorkspaceMember(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/members`,t)}async updateWorkspaceMember(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/members/${encodeURIComponent(t)}`,n)}async removeWorkspaceMember(e,t){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/members/${encodeURIComponent(t)}`)}async prepareSlackUserLinkAccess(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/slack/user-link-intents`,t)}async getSlackUserLinkAccess(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/slack/user-link-intents/${t}`)}async requestSlackUserLinkWorkspaceAccess(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/slack/user-link-intents/${t}/request-access`,n)}async cancelSlackUserLinkAccess(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/slack/user-link-intents/${t}/cancel`,n)}async listSlackUserLinkAccessRequests(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/members/access-requests/slack`)).requests}async approveSlackUserLinkAccessRequest(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/members/access-requests/slack/${t}/approve`,n)}async denySlackUserLinkAccessRequest(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/members/access-requests/slack/${t}/deny`,n)}async createScheduledTask(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/scheduled-tasks`,mt(t))}async updateScheduledTask(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/scheduled-tasks/${t}`,mt(n))}async pauseScheduledTask(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/scheduled-tasks/${t}/pause`)}async resumeScheduledTask(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/scheduled-tasks/${t}/resume`)}async triggerScheduledTask(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/scheduled-tasks/${t}/trigger`,n.triggerId?{triggerId:n.triggerId}:void 0)}async deleteScheduledTask(e,t){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/scheduled-tasks/${t}`)}async listScheduledTaskRuns(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/scheduled-tasks/${t}/runs`,void 0,{...n.limit!==void 0?{limit:String(n.limit)}:{}})}async listVariableSets(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/variable-sets`)}async resolveVariableSetAttachments(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/variable-sets/resolve-attachments`,t)}async createVariableSet(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/variable-sets`,t)}async getVariableSet(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/variable-sets/${t}`)}async getVariableSetVariable(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/variable-sets/${t}/variables/${encodeURIComponent(n)}`)}async updateVariableSet(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/variable-sets/${t}`,n)}async deleteVariableSet(e,t){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/variable-sets/${t}`)}async setVariableSetVariable(e,t,n,s){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/variable-sets/${t}/variables/${encodeURIComponent(n)}`,{value:s})}async deleteVariableSetVariable(e,t,n){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/variable-sets/${t}/variables/${encodeURIComponent(n)}`)}async listChannels(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/channels`)}async createChannel(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/channels`,t)}async updateChannel(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/channels/${t}`,n)}async reorderChannels(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/channels/order`,t)}async deleteChannel(e,t){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/channels/${t}`)}async updateSessionChannel(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/channel`,n)}async listRigs(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs`)}async createRig(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs`,t)}async getRig(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs/${t}`)}async updateRig(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/rigs/${t}`,n)}async deleteRig(e,t){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/rigs/${t}`)}async listRigVersions(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs/${t}/versions`)}async activateRigVersion(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/versions/${n}/activate`)}async listRigChanges(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs/${t}/changes`)}async proposeRigChange(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/changes`,n)}async getRigChange(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs/${t}/changes/${n}`)}async verifyRigChange(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/changes/${n}/verify`)}async promoteRigChange(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/changes/${n}/promote`)}async verifyRig(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/verify`)}async listEnvironments(e){return await this.listVariableSets(e)}async createEnvironment(e,t){return await this.createVariableSet(e,t)}async getEnvironment(e,t){return await this.getVariableSet(e,t)}async updateEnvironment(e,t,n){return await this.updateVariableSet(e,t,n)}async deleteEnvironment(e,t){await this.deleteVariableSet(e,t)}async setEnvironmentVariable(e,t,n,s){return await this.setVariableSetVariable(e,t,n,s)}async deleteEnvironmentVariable(e,t,n){await this.deleteVariableSetVariable(e,t,n)}async beginFileUpload(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/files/uploads`,t,{},n)}async completeFileUpload(e,t,n={}){return(await this.requestJson(\"POST\",`/v1/workspaces/${e}/files/uploads/${t}/complete`,void 0,{},n)).file}async uploadFile(e,t){if(t.timeoutMs!==void 0&&(!Number.isFinite(t.timeoutMs)||t.timeoutMs<=0))throw Error(\"File upload timeout must be a positive number\");gn();let n=async(l,d)=>{let p=new AbortController,u,g=new Promise((b,m)=>{u=setTimeout(()=>{p.abort(),m(Error(\"File upload timed out. Retry the upload.\"))},l)});try{return await Promise.race([d(p.signal),g])}finally{if(u!==void 0)clearTimeout(u)}},s=t.data instanceof Uint8Array?new Blob([t.data.slice()]):t.data instanceof ArrayBuffer?t.data.slice(0):t.data,r=typeof s===\"string\"?new TextEncoder().encode(s).byteLength:s instanceof Blob?s.size:s.byteLength,i=t.sha256??await mn(s),o=await n(30000,async(l)=>await this.beginFileUpload(e,{filename:t.filename,contentType:t.contentType,...t.scope?{scope:t.scope}:{},sizeBytes:r,sha256:i},{signal:l})),a=t.timeoutMs??Math.max(120000,Math.ceil(r/262144)*1000),c=await n(a,async(l)=>await this.fetchImpl(o.putUrl,{method:\"PUT\",credentials:\"omit\",headers:{...o.requiredHeaders},body:s,signal:l}));if(!c.ok)throw await S(c,{method:\"PUT\"});return await n(30000,async(l)=>await this.completeFileUpload(e,o.uploadId,{signal:l}))}async listFiles(e,t={}){let n=new URLSearchParams;if(t.scope)n.set(\"scope\",t.scope);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));if(t.cursor)n.set(\"cursor\",t.cursor);return this.requestJson(\"GET\",`/v1/workspaces/${e}/files${n.size?`?${n}`:\"\"}`)}async getFile(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/files/${t}${n.sessionId?`?sessionId=${encodeURIComponent(n.sessionId)}`:\"\"}`,void 0,{},n)}async getRetainedArtifact(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/artifacts/${t}`)}async getRetainedArtifactContent(e,t,n={}){return await this.getRetainedArtifactContentAtPath(`/v1/workspaces/${e}/artifacts/${t}/content`,n)}async getSessionRetainedArtifact(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/artifacts/${n}`)}async getSessionRetainedArtifactContent(e,t,n,s={}){return await this.getRetainedArtifactContentAtPath(`/v1/workspaces/${e}/sessions/${t}/artifacts/${n}/content`,s)}async downloadRetainedArtifact(e,t,n={}){ft(e,t);let s=await this.downloadRetainedArtifactBytes(t,n);return{artifact:t,bytes:s}}async createRetainedArtifactDownloadUrl(e,t,n={}){ft(e,t);let s=await this.createFileDownloadUrl(e,t.artifactId,n);return bt(s),s}async downloadRetainedScreenshot(e,t,n,s={}){let r=await this.getSessionRetainedArtifact(e,t,n);if(!r.available)return{metadata:r,bytes:null};if(r.kind!==\"computer_screenshot\"||r.contentType!==\"image/png\"||!r.dimensions||r.originalBytes<=0||r.originalBytes>tt)throw new y(502,\"retained screenshot metadata is invalid\");let i=await this.downloadRetainedArtifactBytes(r,s);return{metadata:r,bytes:i}}async downloadRetainedArtifactBytes(e,t){let n=t.maxRetries??2;if(!Number.isInteger(n)||n<0||n>3)throw RangeError(\"retained artifact maxRetries must be an integer from 0 to 3\");let s=new Uint8Array(e.originalBytes),r=Math.min(e.retrieval.maxRangeBytes,ee);if(!Number.isSafeInteger(r)||r<=0)throw new y(502,\"retained artifact range metadata is invalid\");for(let i=0;i<s.byteLength;i+=r){t.signal?.throwIfAborted();let o=Math.min(i+r,s.byteLength)-1,a=null;for(let l=0;l<=n;l+=1)try{a=await this.getRetainedArtifactContentAtPath(e.retrieval.path,{range:`bytes=${i}-${o}`,...t.signal?{signal:t.signal}:{}});break}catch(d){if(t.signal?.throwIfAborted(),l>=n||d instanceof y&&d.status>=400&&d.status<500)throw d}if(!a)throw new y(502,\"retained artifact range retry exhausted\");let c=o-i+1;if(a.status!==206||a.contentType!==e.contentType||a.contentLength!==c||a.contentRange!==`bytes ${i}-${o}/${e.originalBytes}`)throw new y(502,\"retained artifact range response is invalid\");s.set(a.bytes,i)}if(await Rt(s)!==e.sha256)throw new y(502,\"retained artifact checksum mismatch\");return s}async getRetainedArtifactContentAtPath(e,t){if(t.range&&(t.range.length>128||/[^\\x20-\\x7e]/.test(t.range)))throw RangeError(\"retained artifact range must be at most 128 printable ASCII bytes\");let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(e),{method:\"GET\",headers:{...this.headers(n),Accept:\"application/octet-stream\",...t.range?{Range:t.range}:{}},...t.signal?{signal:t.signal}:{}});try{v(s)}catch(o){throw await x(s,\"retained artifact API contract mismatch\"),o}if(!s.ok)throw await S(s,{method:\"GET\",correlationId:n});if(s.status!==200&&s.status!==206)throw await x(s,\"unexpected retained artifact response status\"),new y(s.status,\"unexpected retained artifact response status\");if(s.headers.get(\"accept-ranges\")!==\"bytes\")throw await x(s,\"retained artifact response omitted byte-range support\"),new y(502,\"retained artifact response omitted byte-range support\");let r;try{r=fn(s.headers.get(\"content-length\"))}catch(o){throw await x(s,\"invalid retained artifact content-length\"),o}let i=await se(s,ee,r);return{bytes:i,status:s.status,contentType:s.headers.get(\"content-type\")??\"application/octet-stream\",contentLength:i.byteLength,contentRange:s.headers.get(\"content-range\"),acceptRanges:\"bytes\"}}async createFileDownloadUrl(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/files/${t}/download-url${n.sessionId?`?sessionId=${encodeURIComponent(n.sessionId)}`:\"\"}`,void 0,{},n)}async getVideoGenerationSettings(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/video-generation`,void 0,{},t)}async updateVideoGenerationPolicy(e,t,n={}){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/video-generation/policy`,t,{},n)}async getVideoGenerationOperation(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/video-generation/operations/${t}`,void 0,{},n)}async createVideoArtifactPlaybackSource(e,t,n={}){let s=await this.requestJson(\"POST\",`/v1/workspaces/${e}/artifacts/${t}/playback-source`,void 0,{},n);return Rn(s,t),s}async createDocumentBase(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/document-bases`,t)}async getDocumentBase(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/document-bases/${t}`)}async addDocument(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/document-bases/${t}/documents`,n)}async listDocuments(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/document-bases/${t}/documents`)}async getDocumentOriginalFile(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/documents/${t}/original-file`)}async createKnowledgeDrop(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/drops`,t)}async moveDocument(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/documents/${t}/move`,n)}async deleteDocument(e,t,n){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/document-bases/${t}/documents/${n}`)}async listKnowledgeEntries(e,t={}){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/search`,t)}async getKnowledgeEntry(e,t,n={}){let s=new URLSearchParams;if(n.revisionId!==void 0)s.set(\"revisionId\",n.revisionId);if(n.view!==void 0)s.set(\"view\",n.view);let r=s.toString();return this.requestJson(\"GET\",`/v1/workspaces/${e}/knowledge/entries/${t}${r?`?${r}`:\"\"}`)}async createKnowledgeFileDownloadUrl(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/${t}/file/download-url`,n?{revisionId:n}:{})}async saveKnowledgeEntry(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries`,t)}async reviewKnowledgeEntry(e,t){let{entryId:n,...s}=t;return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/${n}/review`,s)}async listKnowledgeReviewBatches(e,t={}){let n=new URLSearchParams;for(let[s,r]of Object.entries(t))if(r!==void 0)n.set(s,String(r));return this.requestJson(\"GET\",`/v1/workspaces/${e}/knowledge/review-groups?${n}`)}async reviewKnowledgeEntries(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/review`,t)}async listKnowledgeEntryHistory(e,t,n){return this.requestJson(\"GET\",`/v1/workspaces/${e}/knowledge/entries/${t}/history${n?`?beforeRevision=${n}`:\"\"}`)}async restoreKnowledgeEntry(e,t){let{entryId:n,...s}=t;return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/${n}/restore`,s)}async archiveKnowledgeEntry(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/${t}/archive`,n)}async getAgentLearningSettings(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/agent-learning/read`,{scope:t,source:n})}async saveAgentLearningSettings(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/agent-learning`,t)}async listAgentLearningOverrides(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/agent-learning/overrides?scope=${t}`)}async reviewAgentInstruction(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/agent-learning/instructions/review`,t)}async listAgentInstructionReviews(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/agent-learning/instructions/reviews${t?`?cursor=${encodeURIComponent(t)}`:\"\"}`)}async updateWorkspaceSettings(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/settings`,t)}async setWorkspaceDefaultRig(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/default-rig`,t)}async listCapabilities(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/capabilities`)}async createCapability(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/capabilities`,t)}async getConnectorToolPermissions(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/capabilities/${encodeURIComponent(t)}/tool-permissions`,void 0,{},n)}async updateConnectorToolPermissions(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/capabilities/${encodeURIComponent(t)}/tool-permissions`,n,{},s)}async enableCapability(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/capabilities/${encodeURIComponent(t)}/enable`,n)}async disableCapability(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/capabilities/${encodeURIComponent(t)}/disable`)}async listArtifactCatalog(e,t={}){let n=new URLSearchParams;for(let r of[\"sourceSessionId\",\"q\",\"kind\",\"sort\",\"status\",\"limit\",\"cursor\"])if(t[r]!==void 0)n.set(r,String(t[r]));let s=n.size?`?${n.toString()}`:\"\";return this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/artifact-catalog${s}`,void 0,void 0,t)}async listWorkspaceArtifacts(e,t={}){let n=new URLSearchParams;if(t.limit!==void 0)n.set(\"limit\",String(t.limit));if(t.cursor)n.set(\"cursor\",t.cursor);if(t.status)n.set(\"status\",t.status);if(t.sourceSessionId)n.set(\"sourceSessionId\",t.sourceSessionId);let s=n.size>0?`?${n.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts${s}`,void 0,void 0,t)}async getWorkspaceArtifact(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts/${encodeURIComponent(t)}`,void 0,void 0,n)}async getWorkspaceArtifactHtml(e,t,n){return(await this.requestResponse(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts/${encodeURIComponent(t)}/html`,{versionId:n.versionId},n)).text()}async rollbackWorkspaceArtifact(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts/${encodeURIComponent(t)}/rollback`,n,void 0,s)}async setWorkspaceArtifactStatus(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts/${encodeURIComponent(t)}/status`,n,void 0,s)}async discoverMcpCapabilities(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/capabilities/discovery/mcp-registry`,void 0,{...t.query!==void 0?{query:t.query}:{},...t.limit!==void 0?{limit:String(t.limit)}:{}})}async discoverPlugins(e,t={}){return this.requestJson(\"GET\",\"/v1/workspaces/\"+e+\"/capabilities/discovery/plugins\",void 0,{...t.id?{id:t.id}:{},...t.query?{query:t.query}:{},...t.provider?{provider:t.provider}:{},...t.offset!==void 0?{offset:String(t.offset)}:{}})}async inspectMcpAuthentication(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/capabilities/discovery/mcp-auth`,{url:t})}async listApiIntegrations(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations`)}async listIntegrationDefinitions(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/definitions`)}async previewApiIntegration(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/preview`,t)}async startApiIntegrationOAuth(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/oauth/start`,t)}async installApiIntegration(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/install`,t)}async previewApiIntegrationUninstall(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/uninstall-preview`)}async uninstallApiIntegration(e,t,n,s){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}`,s)}async listIntegrationFacets(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets`)}async configureIntegrationFacet(e,t,n,s,r){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}`,r)}async browseGoogleDriveFacetSource(e,t,n,s,r={}){let i=new URLSearchParams;if(r.parentId)i.set(\"parentId\",r.parentId);if(r.pageToken)i.set(\"pageToken\",r.pageToken);let o=i.size>0?`?${i}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}/browse${o}`)}async saveGoogleDriveFacetSource(e,t,n,s,r){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}/source`,r)}async pauseIntegrationFacet(e,t,n,s,r){return await this.mutateIntegrationFacetLifecycle(e,t,n,s,\"pause\",r)}async resumeIntegrationFacet(e,t,n,s,r){return await this.mutateIntegrationFacetLifecycle(e,t,n,s,\"resume\",r)}async removeIntegrationFacet(e,t,n,s,r){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}`,r)}async mutateIntegrationFacetLifecycle(e,t,n,s,r,i){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}/${r}`,i)}async previewPlugin(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/plugins/preview`,t)}async getInstalledPluginDetails(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/plugins/details`,void 0,{pluginKey:t})}async listInstalledPlugins(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/plugins`)}async installPlugin(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/plugins/install`,t)}async previewPluginUninstall(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/plugins/${encodeURIComponent(t)}/uninstall-preview`)}async uninstallPlugin(e,t,n){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/plugins/${encodeURIComponent(t)}`,n)}async previewSkillImport(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/preview`,t)}async installSkill(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/install`,t)}async listInstalledSkills(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/skills`)}async listWorkspaceSkills(e,t={}){let n=new URLSearchParams;if(t.cursor!==void 0)n.set(\"cursor\",t.cursor);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));if(t.sessionId!==void 0)n.set(\"sessionId\",t.sessionId);let s=n.size?`?${n.toString()}`:\"\";return this.requestJson(\"GET\",`/v1/workspaces/${e}/skills/content${s}`)}async readWorkspaceSkill(e,t,n){let s=n?`?revisionId=${encodeURIComponent(n)}`:\"\";return this.requestJson(\"GET\",`/v1/workspaces/${e}/skills/content/${encodeURIComponent(t)}${s}`)}async saveWorkspaceSkill(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/content/save`,t)}async approveWorkspaceSkill(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/content/${encodeURIComponent(t)}/approve`,n)}async restoreWorkspaceSkill(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/content/${encodeURIComponent(t)}/restore`,n)}async rejectWorkspaceSkill(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/content/${encodeURIComponent(t)}/reject`,n)}async installLibrarySkill(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/library/${encodeURIComponent(t)}/install`,n)}async previewSkillUninstall(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/skills/${encodeURIComponent(t)}/uninstall-preview`)}async uninstallSkill(e,t,n){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/skills/${encodeURIComponent(t)}`,n)}async listOwnConnectionAccounts(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/accounts`)).connections}async listConnections(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections`)).connections}async personalGitHubStatus(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/github`)}async startPersonalGitHubOAuth(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/github/oauth/start`,t)}async reconnectPersonalGitHub(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/${t}/github/reconnect`,n)}async disconnectPersonalGitHub(e,t,n){return(await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/connections/${t}`,n)).connection}async listPersonalGitHubRepositories(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/${t}/github/repositories`,void 0,{...n.cursor!==void 0?{cursor:String(n.cursor)}:{},...n.limit!==void 0?{limit:String(n.limit)}:{}})}async replacePersonalGitHubRepositorySelections(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/connections/${t}/github/repositories`,n)}async verifyPersonalGitHubRepositorySelections(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/${t}/github/repositories/verify`,n)}async listSlackInstallationBindings(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/slack-bot/bindings`)).bindings}async createConnection(e,t){return(await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections`,t)).connection}async installFikenConnection(e,t){return(await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/fiken/install`,t)).connection}async startFikenOAuth(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/fiken/oauth/start`,t)}async startOpenGeniSlackBotInstall(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/slack-bot/install`,t)}async listOpenGeniSlackReactionChannels(e,t,n){let s=new URLSearchParams({connectionId:t});if(n)s.set(\"cursor\",n);return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/slack/reaction-channels?${s}`)}async listOpenGeniSlackChannelRoutes(e,t){let n=new URLSearchParams({connectionId:t});return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/slack/channel-routes?${n}`)}async updateOpenGeniSlackChannelRoutes(e,t){await this.requestJson(\"PUT\",`/v1/workspaces/${e}/integrations/slack/channel-routes`,t)}async updateConnection(e,t,n){return(await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/connections/${t}`,n)).connection}async deleteConnection(e,t){return(await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/connections/${t}`)).connection}async disconnectGoogleDriveConnection(e,t,n){return(await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/connections/${t}`,n)).connection}async transitionGoogleDriveLifecycle(e,t,n){return(await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/connections/google-drive/${t}/lifecycle`,n)).connection}async startConnectionOAuth(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/oauth/start`,t,{},n)}async startSocialOAuth(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/social/oauth/start`,t)}async listSocialConnections(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/social/connections`)}async disconnectSocialConnection(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/social/connections/${t}`)}catalogAssetUrl(e){return e?`${this.baseUrl}/v1/${e}`:null}async downloadCatalogAsset(e,t={}){if(!/^catalog-assets\\/[a-zA-Z0-9_./-]+$/.test(e)||e.split(\"/\").some((i)=>!i||i===\".\"||i===\"..\"))throw TypeError(\"A catalog asset path is required\");let n=await this.requestResponse(\"GET\",`/v1/${e}`,{},t),s=n.headers.get(\"content-type\")?.split(\";\")[0]??\"\";if(!s.startsWith(\"image/\"))throw await n.body?.cancel(),Error(\"The catalog asset is not an image\");let r=await se(n,2000000,null);return new Blob([Uint8Array.from(r)],{type:s})}async getGitHubApp(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/github/app`,void 0,t.returnPath?{returnPath:t.returnPath}:void 0)}githubConnectUrl(e,t){return this.url(`/v1/workspaces/${e}/github/connect`,{state:t})}async listGitHubRepositories(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/github/repositories`)}async getGitHubActionPolicies(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/github/action-policies`)}async updateGitHubActionPolicy(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/github/action-policies`,t)}async syncGitHubRepositories(e){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/github/repositories/sync`)}async unlinkGitHubInstallation(e,t){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/github/installations/${t}`)}async createGitHubAppManifest(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/github/app-manifest`,t)}async listApiKeys(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/api-keys`)).apiKeys}async createApiKey(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/api-keys`,t)}async deleteApiKey(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/api-keys/${t}`)}async listOrganizationApiKeys(e){return(await this.requestJson(\"GET\",`/v1/organizations/${e}/api-keys`)).apiKeys}async createOrganizationApiKey(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/api-keys`,t)}async deleteOrganizationApiKey(e,t){return await this.requestJson(\"DELETE\",`/v1/organizations/${e}/api-keys/${t}`)}async listOrganizationSessions(e,t={}){return await this.requestJson(\"GET\",`/v1/organizations/${e}/sessions`,void 0,{...t.limit===void 0?{}:{limit:String(t.limit)},...t.cursor===void 0?{}:{cursor:t.cursor},...t.scopeSubjectId?{scopeSubjectId:t.scopeSubjectId}:{},...t.status===void 0?{}:{status:t.status}},{signal:t.signal})}async*iterateOrganizationSessions(e,t={}){let n;do{let s=await this.listOrganizationSessions(e,{...t,...n===void 0?{}:{cursor:n}});for(let r of s.sessions)yield r;n=s.nextCursor??void 0}while(n!==void 0)}async getBilling(e={}){return await this.requestJson(\"GET\",\"/v1/billing\",void 0,{...e.accountId!==void 0?{accountId:e.accountId}:{}})}async getOrganizationUsageSummary(e,t={}){return await this.requestJson(\"GET\",\"/v1/billing/usage-summary\",void 0,{accountId:e.accountId,period:e.period??\"month\"},t)}async getOrganizationUsageWorkspacePage(e,t={}){return await this.requestJson(\"GET\",\"/v1/billing/usage-workspaces\",void 0,{accountId:e.accountId,period:e.period??\"month\",until:e.until,...e.afterWorkspaceId?{afterWorkspaceId:e.afterWorkspaceId}:{}},t)}async getBillingUsage(e={}){return await this.requestJson(\"GET\",\"/v1/billing/usage\",void 0,{...e.accountId!==void 0?{accountId:e.accountId}:{},...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}})}async getWorkspaceInsights(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/insights`,void 0,{range:t.range??\"week\",...t.provider!==void 0?{provider:t.provider}:{},...t.model!==void 0?{model:t.model}:{}},{signal:t.signal})}async getBillingEntitlements(e={}){return await this.requestJson(\"GET\",\"/v1/billing/entitlements\",void 0,{...e.accountId!==void 0?{accountId:e.accountId}:{}})}async createBillingCheckout(e){return await this.requestJson(\"POST\",\"/v1/billing/checkout\",e)}async createBillingPortalSession(e={}){return await this.requestJson(\"POST\",\"/v1/billing/portal\",e)}headers(e){let t=typeof this.options.headers===\"function\"?this.options.headers():this.options.headers,n={...this.options.apiKey?{Authorization:`Bearer ${this.options.apiKey}`}:{},...t,[de]:U,...e?{[Z]:e}:{}};if(this.externalActorHeader){for(let s of Object.keys(n))if(s.toLowerCase()===\"x-opengeni-external-actor\")delete n[s];n[\"x-opengeni-external-actor\"]=this.externalActorHeader}return n}url(e,t={}){let n=new URLSearchParams(t).toString();return`${this.baseUrl}${e}${n?`?${n}`:\"\"}`}async codexStatus(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/status`)}async codexConnectStart(e){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/connect/start`)}async codexConnectPoll(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/connect/poll`,{state:t})}async codexUsage(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/usage`)}async codexAccountUsage(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/accounts/${t}/usage`)}async refreshCodexUsage(e){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/usage/refresh`)}async codexOverview(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/overview`)}async codexDisconnect(e){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/codex`)}async listCodexAccounts(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/accounts`)}async listSessionCodexAccounts(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/codex-accounts`)}async activateCodexAccount(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/accounts/${t}/activate`)}async designateCodexAppsAccount(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/apps`,{accountId:t,expectedVersion:n})}async clearCodexAppsAccount(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/codex/apps`,{expectedVersion:t})}async setCodexRotationSettings(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/codex/settings`,t)}async setCodexAccountAllocator(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/codex/accounts/${t}/allocator`,n)}async disconnectCodexAccount(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/codex/accounts/${t}`)}async renameCodexAccount(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/codex/accounts/${t}`,{label:n})}async pinSessionCodexAccount(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/codex-account`,{target:n})}async getModelConnectionAccess(e){return await this.requestJson(\"GET\",`/v1/${e.scope}/${encodeURIComponent(e.scopeId)}/model-connections/${e.kind}/${encodeURIComponent(e.connectionId)}/access`)}async updateModelConnectionAccess(e,t){return await this.requestJson(\"PUT\",`/v1/${e.scope}/${encodeURIComponent(e.scopeId)}/model-connections/${e.kind}/${encodeURIComponent(e.connectionId)}/access`,t)}async listOrganizationSuperGrokAccounts(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/supergrok/accounts`)}async organizationSupergrokConnectStart(e){return await this.requestJson(\"POST\",`/v1/organizations/${e}/supergrok/connect/start`,{})}async organizationSupergrokConnectPoll(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/supergrok/connect/poll`,{state:t})}async activateOrganizationSuperGrokAccount(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/supergrok/accounts/${t}/activate`,{})}async setOrganizationSuperGrokRotationSettings(e,t){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/supergrok/settings`,t)}async setOrganizationSuperGrokAccountAllocator(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/supergrok/accounts/${t}/allocator`,n)}async renameOrganizationSuperGrokAccount(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/supergrok/accounts/${t}`,{label:n})}async disconnectOrganizationSuperGrokAccount(e,t){return await this.requestJson(\"DELETE\",`/v1/organizations/${e}/supergrok/accounts/${t}`,{})}async supergrokStatus(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/supergrok/status`)}async supergrokConnectStart(e,t=\"workspace\"){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/supergrok/connect/start`,{scope:t})}async supergrokConnectPoll(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/supergrok/connect/poll`,{state:t})}async listSuperGrokAccounts(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/supergrok/accounts`)}async activateSuperGrokAccount(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/supergrok/accounts/${t}/activate`,{})}async setSuperGrokRotationSettings(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/supergrok/settings`,t)}async setSuperGrokAccountAllocator(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/supergrok/accounts/${t}/allocator`,n)}async renameSuperGrokAccount(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/supergrok/accounts/${t}`,{label:n})}async disconnectSuperGrokAccount(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/supergrok/accounts/${t}`,{})}async requestSessionCommand(e,t,n,s={}){return await this.requestJson(e,t,n,{},{signal:s.signal,timeoutMs:s.timeoutMs??this.sessionCommandTimeoutMs})}async requestJson(e,t,n,s={},r={}){let i=crypto.randomUUID(),o=ln(r);try{if(o.signal?.aborted)throw o.signal.reason??new DOMException(\"Request aborted\",\"AbortError\");let a;try{a=await V(this.fetchImpl(this.url(t,s),{method:e,headers:{...this.headers(i),Accept:\"application/json\",...n!==void 0?{\"Content-Type\":\"application/json\"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{},...o.signal?{signal:o.signal}:{}}),o.signal)}catch(c){if(r.signal?.aborted)throw c;if(L(e))throw D(i);throw c}v(a);try{if(!a.ok)throw await V(S(a,{method:e,correlationId:i}),o.signal);return await V(N(a,{method:e,correlationId:i}),o.signal),await V(a.json(),o.signal)}catch(c){if(r.signal?.aborted)throw c;if(c instanceof y)throw c;if(L(e))throw D(i);throw c}}finally{o.dispose()}}async requestResponse(e,t,n={},s={}){let r=crypto.randomUUID(),i;try{i=await this.fetchImpl(this.url(t,n),{method:e,headers:{...this.headers(r),Accept:\"application/octet-stream\"},...s.signal?{signal:s.signal}:{}})}catch(o){if(L(e))throw D(r);throw o}if(v(i),!i.ok)throw await S(i,{method:e,correlationId:r});return i}async requestVoid(e,t,n){let s=crypto.randomUUID(),r;try{r=await this.fetchImpl(this.url(t),{method:e,headers:{...this.headers(s),Accept:\"application/json\",...n!==void 0?{\"Content-Type\":\"application/json\"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}})}catch(i){if(L(e))throw D(s);throw i}if(v(r),!r.ok)throw await S(r,{method:e,correlationId:s})}}function v(e){let t=e.headers.get(de);if(t&&t!==U)throw new H(U,t)}function an(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return!1;let t=e;return typeof t.text===\"string\"&&Array.isArray(t.languages)&&t.languages.every((n)=>typeof n===\"string\")}function cn(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return!1;let t=e;if(!pe({recording:t.recording,segments:[]}))return!1;if(!t.chunk||typeof t.chunk!==\"object\"||Array.isArray(t.chunk))return!1;let n=t.chunk;return typeof n.chunkNumber===\"number\"&&typeof n.byteLength===\"number\"&&typeof n.sha256===\"string\"&&typeof n.startMilliseconds===\"number\"&&typeof n.durationMilliseconds===\"number\"&&typeof n.deduplicated===\"boolean\"}function pe(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return!1;let t=e;if(!t.recording||typeof t.recording!==\"object\"||Array.isArray(t.recording))return!1;let n=t.recording;return typeof n.id===\"string\"&&typeof n.workspaceId===\"string\"&&typeof n.mimeType===\"string\"&&typeof n.state===\"string\"&&typeof n.nextChunkNumber===\"number\"&&typeof n.chunkCount===\"number\"&&typeof n.totalBytes===\"number\"&&typeof n.totalDurationMilliseconds===\"number\"&&typeof n.segmentCount===\"number\"&&typeof n.completedSegmentCount===\"number\"&&(n.transcriptText===null||typeof n.transcriptText===\"string\")&&Array.isArray(n.languages)&&(n.errorCode===null||typeof n.errorCode===\"string\")&&typeof n.retryable===\"boolean\"&&typeof n.objectsCleaned===\"boolean\"&&typeof n.createdAt===\"string\"&&typeof n.updatedAt===\"string\"&&typeof n.expiresAt===\"string\"&&(t.retryAfterMilliseconds===void 0||typeof t.retryAfterMilliseconds===\"number\"&&Number.isInteger(t.retryAfterMilliseconds)&&t.retryAfterMilliseconds>0&&t.retryAfterMilliseconds<=60000)&&Array.isArray(t.segments)}function J(e){if(pe(e))return e;throw new y(502,\"Invalid transcription recording response.\",{code:\"invalid_response\"})}function un(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return!1;let t=e.recordings;return Array.isArray(t)&&t.length<=50&&t.every((n)=>pe({recording:n,segments:[]}))}function dn(e){switch(e.trim().toLowerCase().split(\";\")[0]??\"audio/webm\"){case\"audio/mp4\":case\"audio/m4a\":return\"audio.mp4\";case\"audio/ogg\":return\"audio.ogg\";case\"audio/mpeg\":case\"audio/mp3\":return\"audio.mp3\";case\"audio/wav\":case\"audio/x-wav\":return\"audio.wav\";case\"audio/webm\":default:return\"audio.webm\"}}var yt=16384;function ln(e){let t=e.timeoutMs??0;if(t<=0)return{signal:e.signal,dispose:()=>{return}};let n=new AbortController,s=()=>n.abort(e.signal?.reason);if(e.signal?.aborted)s();else e.signal?.addEventListener(\"abort\",s,{once:!0});let r=setTimeout(()=>n.abort(new DOMException(\"Request timed out\",\"TimeoutError\")),t);return{signal:n.signal,dispose:()=>{clearTimeout(r),e.signal?.removeEventListener(\"abort\",s)}}}async function V(e,t){if(!t)return await e;if(t.aborted)throw t.reason??new DOMException(\"Request aborted\",\"AbortError\");return await new Promise((n,s)=>{let r=()=>{i(),s(t.reason??new DOMException(\"Request aborted\",\"AbortError\"))},i=()=>t.removeEventListener(\"abort\",r);t.addEventListener(\"abort\",r,{once:!0}),e.then((o)=>{i(),n(o)},(o)=>{i(),s(o)})})}async function S(e,t){return new y(e.status,await pn(e),{correlationId:e.headers.get(Z)??t.correlationId,mutation:L(t.method)})}async function N(e,t){if(wt(e.headers.get(\"content-type\")))return;throw await x(e,\"unexpected non-JSON API response\"),new y(502,\"\",{code:\"upstream_unavailable\",retryable:!0,correlationId:e.headers.get(Z)??t.correlationId,outcomeUnknown:L(t.method),displayMessage:\"OpenGeni is temporarily unavailable \u2014 retry.\"})}async function pn(e){if(!wt(e.headers.get(\"content-type\")))return await x(e,\"discarding API error body\"),\"\";if(Number(e.headers.get(\"content-length\"))>yt)return await x(e,\"discarding API error body\"),\"\";try{return new TextDecoder().decode(await se(e,yt,null))}catch{return\"\"}}function wt(e){return/^(application\\/json|[^;]+\\+json)\\s*(;|$)/i.test(e??\"\")}function L(e){return e!==\"GET\"&&e!==\"HEAD\"&&e!==\"OPTIONS\"}function D(e){return new y(0,\"\",{code:\"network_error\",retryable:!0,correlationId:e,outcomeUnknown:!0,mutation:!0,displayMessage:\"OpenGeni could not confirm the request \u2014 reconcile before retrying.\"})}function gn(){let e=typeof window<\"u\"?window.isSecureContext:typeof globalThis.isSecureContext===\"boolean\"?globalThis.isSecureContext:void 0;if(e===void 0)return;if(!e)throw new K(\"insecure_context\");if(typeof globalThis.crypto>\"u\"||typeof globalThis.crypto.subtle?.digest!==\"function\")throw new K(\"web_crypto_unavailable\")}async function mn(e){let t=typeof e===\"string\"?new TextEncoder().encode(e):e instanceof Blob?new Uint8Array(await e.arrayBuffer()):new Uint8Array(e),n=await globalThis.crypto.subtle.digest(\"SHA-256\",t);return[...new Uint8Array(n)].map((s)=>s.toString(16).padStart(2,\"0\")).join(\"\")}async function Rt(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest(\"SHA-256\",t.buffer);return[...new Uint8Array(n)].map((s)=>s.toString(16).padStart(2,\"0\")).join(\"\")}function yn(e,t){if(e.computerSessionId!==t.computerSessionId)return\"frame_session_mismatch\";if(e.targetId!==t.targetId)return\"frame_target_mismatch\";if(e.mediaType!==t.mediaType)return\"frame_media_mismatch\";if(e.sha256!==t.sha256)return\"frame_digest_mismatch\";return null}async function x(e,t){await e.body?.cancel(t).catch(()=>{return})}function ft(e,t){if(!at(t,e)&&!ot(t,e))throw new y(502,\"retained workspace artifact receipt is invalid\")}function bt(e){if(!e||typeof e.url!==\"string\"||typeof e.expiresAt!==\"string\"||!Number.isFinite(Date.parse(e.expiresAt)))throw new y(502,\"retained artifact download URL is invalid\");let t;try{t=new URL(e.url)}catch{throw new y(502,\"retained artifact download URL is invalid\")}if(![\"http:\",\"https:\"].includes(t.protocol)||t.username||t.password)throw new y(502,\"retained artifact download URL is unsafe\")}function Rn(e,t){if(!e||e.schemaVersion!==1||e.artifactId!==t||e.contentType!==\"video/mp4\"||e.acceptRanges!==\"bytes\"||!Number.isSafeInteger(e.sizeBytes)||e.sizeBytes<=0||e.sizeBytes>nt||!/^[0-9a-f]{64}$/.test(e.sha256))throw new y(502,\"generated-video playback source is invalid\");bt({url:e.url,expiresAt:e.expiresAt})}function fn(e){if(e===null)return null;if(!/^\\d+$/.test(e))throw new y(502,\"invalid retained artifact content-length\");let t=Number(e);if(!Number.isSafeInteger(t)||t>ee)throw new y(502,\"retained artifact response exceeds the SDK byte limit\");return t}async function se(e,t,n){if(!e.body){if(n!==null&&n!==0)throw new y(502,\"retained artifact response length mismatch\");return new Uint8Array}let s=e.body.getReader(),r=[],i=0;try{while(!0){let{done:c,value:l}=await s.read();if(c)break;if(i+=l.byteLength,i>t)throw await s.cancel(\"retained artifact response exceeded the SDK byte limit\").catch(()=>{return}),new y(502,\"retained artifact response exceeds the SDK byte limit\");r.push(l)}}finally{s.releaseLock()}if(n!==null&&i!==n)throw new y(502,\"retained artifact response length mismatch\");let o=new Uint8Array(i),a=0;for(let c of r)o.set(c,a),a+=c.byteLength;return o}var W=2,wn=\"opengeni.site.connect\",vt=\"opengeni.site.ready\",bn=\"opengeni.site.request\",hn=\"opengeni.site.response\",Sn=\"opengeni.site.cancel\",kt=\"__opengeniSiteBridgeBootstrapV2\",vn=\"/__opengeni/site-tools\";class k extends Error{code;retryable;outcomeUnknown;constructor(e,t,n=!1,s=!1){super(t);this.code=e;this.retryable=n;this.outcomeUnknown=s;this.name=\"OpenGeniSiteBridgeError\"}}function It(e={}){let t=kn(e)?new Ct(e):new xt(e);return{client:new le({baseUrl:\"https://site.opengeni.invalid\",fetch:(n,s)=>t.fetch(n,s)}),workspaceId:j,tools:new Q(t).forWorkspace(\"site-host\"),close:()=>t.close()}}class Ct{fetchImpl;basePath;constructor(e){this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis);let t=e.localCodemodePath;this.basePath=(typeof t===\"string\"?t:vn).replace(/\\/+$/u,\"\")}close(){}async fetch(e,t){let n=new Request(e,t),s=new URL(n.url),r=`${s.pathname}${s.search}`;return z(r,j,n.method),this.fetchImpl(`${this.basePath}/sdk${r}`,{method:n.method,headers:n.headers,signal:n.signal,...n.body?{body:await n.text()}:{}})}async requestJson(e,t,n,s,r={}){let i=In(e,t),o=await this.fetchImpl(`${this.basePath}${i}`,{method:e,...r.signal?{signal:r.signal}:{},...n===void 0?{}:{headers:{\"content-type\":\"application/json\"},body:JSON.stringify(n)}}),a=await o.json();if(o.ok)return a;let c=T(a)&&T(a.error)?a.error:{};throw new k(typeof c.code===\"string\"?c.code:\"local_codemode_error\",typeof c.message===\"string\"?c.message:`Local Site tool request failed with HTTP ${o.status}`,c.retryable===!0,c.outcomeUnknown===!0)}}function kn(e){if(e.localCodemodePath===!1||e.bootstrapPort)return!1;if(typeof e.localCodemodePath===\"string\")return!0;let t=e.siteWindow??globalThis.window;return Boolean(t&&t.parent===t)}function In(e,t){if(e===\"GET\"&&t.endsWith(\"/tools/catalog\"))return\"/catalog\";if(e===\"GET\"&&t.endsWith(\"/tools/declarations\"))return\"/declarations\";if(e===\"POST\"&&t.endsWith(\"/tools/calls\"))return\"/calls\";throw new k(\"unsupported_request\",\"Unsupported Site tool request\")}function Cn(e){return{...e.operationId===void 0?{}:{operationId:e.operationId},catalogDigest:e.catalogDigest,identity:e.identity,arguments:e.arguments}}class xt{options;bootstrap;port=null;connecting=null;closed=!1;constructor(e){this.options=e,this.bootstrap=xn(e)}async fetch(e,t){return fe(await this.connect(),e,t)}async requestJson(e,t,n,s,r={}){if(e===\"GET\"&&t.endsWith(\"/tools/catalog\"))return await this.request({method:\"catalog\"},r);if(e===\"GET\"&&t.endsWith(\"/tools/declarations\"))return await this.request({method:\"declarations\"},r);if(e===\"POST\"&&t.endsWith(\"/tools/calls\")){if(!T(n))throw TypeError(\"Site tool call payload is required\");return await this.request({method:\"call\",payload:Cn(n)},r)}throw new k(\"unsupported_request\",\"Unsupported Site bridge request\")}close(){if(this.closed)return;this.closed=!0,this.bootstrap.close(),this.port?.close(),this.port=null}async request(e,t){let n=await this.connect(),s=crypto.randomUUID(),r=St(t.timeoutMs??this.options.requestTimeoutMs??120000,\"requestTimeoutMs\");return await new Promise((i,o)=>{let a=setTimeout(()=>{d(),ht(n,s),o(e.method===\"call\"?new k(\"timeout\",\"Site tool request timed out after execution may have started\",!1,!0):new k(\"timeout\",\"Site tool request timed out\",!0))},r),c=()=>{d(),ht(n,s),o(t.signal?.reason??new DOMException(\"Request aborted\",\"AbortError\"))},l=(p)=>{let u=p.data;if(!T(u)||u.type!==hn||u.version!==W||u.requestId!==s||typeof u.ok!==\"boolean\")return;if(d(),u.ok){i(u.value);return}let g=T(u.error)?u.error:{};o(new k(typeof g.code===\"string\"?g.code:\"bridge_error\",typeof g.message===\"string\"?g.message:\"Site tool request failed\",g.retryable===!0,g.outcomeUnknown===!0))},d=()=>{clearTimeout(a),t.signal?.removeEventListener(\"abort\",c),n.removeEventListener(\"message\",l)};if(t.signal?.aborted){c();return}t.signal?.addEventListener(\"abort\",c,{once:!0}),n.addEventListener(\"message\",l),n.postMessage({type:bn,version:W,requestId:s,...e})})}async connect(){if(this.closed)throw new k(\"closed\",\"Site bridge is closed\");if(this.port)return this.port;if(this.connecting)return await this.connecting;let e=(this.options.createMessageChannel??(()=>new MessageChannel))(),t=St(this.options.connectTimeoutMs??1e4,\"connectTimeoutMs\");return this.connecting=new Promise((n,s)=>{let r=!0,i=setTimeout(()=>{a(),e.port1.close(),s(new k(\"host_timeout\",\"OpenGeni Site host did not respond\"))},t),o=(c)=>{let l=c.data;if(!T(l)||l.type!==vt||l.version!==W)return;a(),this.port=e.port1,n(e.port1)},a=()=>{r=!1,clearTimeout(i),e.port1.removeEventListener(\"message\",o)};e.port1.addEventListener(\"message\",o),e.port1.start(),this.bootstrap.port().then((c)=>{if(!r)return;if(this.closed)throw new k(\"closed\",\"Site bridge is closed\");c.postMessage({type:wn,version:W},[e.port2])}).catch((c)=>{a(),e.port1.close(),s(c)})}).finally(()=>{this.connecting=null}),await this.connecting}}function xn(e){if(e.bootstrapPort)return{port:async()=>e.bootstrapPort,close:()=>e.bootstrapPort?.close()};let t=e.siteWindow??globalThis.window,n=e.parentWindow??t?.parent;if(!t||!n||n===t)return{port:async()=>{throw new k(\"host_unavailable\",\"OpenGeni Site client must run inside a hosted iframe\")},close:()=>{return}};let s=An(t);if(s)return{port:async()=>s,close:()=>{return}};let r=null,i=null,o=(d)=>{if(d.source!==n||!qn(d.data)||d.ports.length!==1)return;c(),r=d.ports[0],r.start(),Pn(t,r),a?.(r)},a=null,c=()=>t.removeEventListener(\"message\",o),l=new Promise((d,p)=>{a=d,i=p,t.addEventListener(\"message\",o)});return l.catch(()=>{return}),{port:async()=>await l,close:()=>{c(),i?.(new k(\"closed\",\"Site bridge is closed\")),a=null,i=null}}}function An(e){let t=e[kt];if(!T(t))return null;let n=t.port;return n&&typeof n.postMessage===\"function\"&&typeof n.addEventListener===\"function\"&&typeof n.start===\"function\"?n:null}function Pn(e,t){try{Object.defineProperty(e,kt,{configurable:!0,value:{port:t}})}catch{}}function qn(e){return T(e)&&e.type===vt&&e.version===W}function ht(e,t){e.postMessage({type:Sn,version:W,requestId:t})}function St(e,t){if(!Number.isFinite(e)||e<=0)throw RangeError(`${t} must be positive`);return e}function T(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}Object.defineProperty(globalThis,\"createOpenGeniSiteClient\",{configurable:!0,value:It});})();\n";
1
+ export declare const SITE_BROWSER_RUNTIME = "(()=>{var Et=Object.defineProperty;var Gt=(e)=>e;function _t(e,t){this[e]=Gt.bind(null,t)}var Mt=(e,t)=>{for(var n in t)Et(e,n,{get:t[n],enumerable:!0,configurable:!0,set:_t.bind(t,n)})};var me=(e,t)=>()=>(e&&(t=e(e=0)),t);function Bt(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!==\"object\"||Array.isArray(t))return null;let n=t,s=n.error&&typeof n.error===\"object\"&&!Array.isArray(n.error)?n.error:n,r=re(s.code),i=re(s.message),o=Re(s.requestId),a=typeof s.retryable===\"boolean\"?s.retryable:void 0,c=typeof s.outcomeUnknown===\"boolean\"?s.outcomeUnknown:void 0,l=$t(s.details);if(!r&&!i&&!o&&a===void 0&&c===void 0&&!l)return null;return{code:r,message:i,requestId:o,retryable:a,outcomeUnknown:c,details:l}}catch{return null}}function $t(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return;let t=Object.entries(e).slice(0,16),n={};for(let[s,r]of t){if(!/^[a-zA-Z][\\w.-]{0,63}$/.test(s))continue;if(typeof r===\"string\"){let i=re(r);if(i!==void 0)n[s]=i}else if(typeof r===\"number\"||typeof r===\"boolean\"||r===null)n[s]=r}return Object.keys(n).length>0?n:void 0}function re(e){if(typeof e!==\"string\")return;let t=new TextEncoder().encode(e);return t.byteLength<=512?e:new TextDecoder().decode(t.slice(0,512))}function Ut(e){return e===408||e===409||e===425||e===429||e>=500}function Re(e){if(typeof e!==\"string\"||e.length>128||!/^[\\w.:-]+$/.test(e))return;return e}function A(e){return e instanceof DOMException&&e.name===\"AbortError\"||e instanceof Error&&e.name===\"AbortError\"}function q(e){if(e instanceof g)return e.retryable;return e instanceof TypeError}var g,H,ie,j,C;var G=me(()=>{g=class g extends Error{status;code;retryable;correlationId;outcomeUnknown;body;details;constructor(e,t,n={}){let s=Bt(t),r=s?.requestId??Re(n.correlationId),i=e>=502&&e<=504,o=n.mutation!==void 0,a=s?.message??(o?\"Request failed.\":t||\"(empty body)\"),c=n.displayMessage??(i&&o?s?.message??\"OpenGeni is temporarily unavailable \u2014 retry.\":`OpenGeni API ${e}: ${a}`);super(r?`${c} Reference: ${r}.`:c);this.name=\"OpenGeniApiError\",this.status=e,this.code=n.code??s?.code??(i&&o?\"upstream_unavailable\":void 0),this.retryable=n.retryable??s?.retryable??Ut(e),this.correlationId=r,this.outcomeUnknown=n.outcomeUnknown??s?.outcomeUnknown??(i&&!!n.mutation&&!s),this.body=!o||s?t:\"\",this.details=s?.details}};H=class H extends Error{code=\"secure_context_required\";retryable=!1;reason;constructor(e){super(e===\"insecure_context\"?\"Couldn\u2019t attach this file because OpenGeni is open over HTTP. Attachments require a secure HTTPS connection. Open the secure site or configure HTTPS for this deployment.\":\"Couldn\u2019t attach this file because secure browser cryptography is unavailable. Attachments require HTTPS and Web Crypto support. Open a secure site in a supported browser or configure HTTPS for this deployment.\");this.name=\"OpenGeniSecureContextRequiredError\",this.reason=e}};ie=class ie extends g{};j=class j extends Error{expected;actual;constructor(e,t){super(`OpenGeni API contract mismatch: client expects ${e}, API serves ${t}`);this.name=\"OpenGeniApiContractMismatchError\",this.expected=e,this.actual=t}};C=class C extends Error{constructor(e){super(e);this.name=\"OpenGeniStreamError\"}}});var he={};Mt(he,{OpenGeniToolCallError:()=>oe,OpenGeniToolReapprovalRequiredError:()=>Q,OpenGeniToolsClient:()=>Z});class Z{transport;constructor(e){this.transport=e}forWorkspace(e){let t=Ft(e,\"workspaceId\"),n=null,s=new Map,r=async(d={})=>{if(n&&!d.refresh)return n;let p=await this.transport.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(t)}/tools/catalog`,void 0,{},d.signal?{signal:d.signal}:{});return n=p,p},i=async(d,p,u)=>{if(u.approvalToken&&!u.operationId)throw TypeError(\"operationId is required when using an approval token\");let m=u.operationId??crypto.randomUUID(),b=await r({...u.refreshCatalog===void 0?{}:{refresh:u.refreshCatalog},...u.signal?{signal:u.signal}:{}}),y=async(w)=>{let h=d(w),x=u.approvalToken?s.get(u.approvalToken):void 0;if(x&&(x.operationId!==m||x.catalogDigest!==w.digest||!Lt(x.identity,h)))throw new Q(m,x.catalogDigest,w.digest,h);let F={operationId:m,catalogDigest:w.digest,identity:h,arguments:p,...u.approvalToken?{approvalToken:u.approvalToken}:{}},E;try{E=await this.transport.requestJson(\"POST\",`/v1/workspaces/${encodeURIComponent(t)}/tools/calls`,F,{},u.signal?{signal:u.signal}:{})}catch(ge){if(Y(ge))n=null;else if(u.approvalToken)s.delete(u.approvalToken);throw ge}if(u.approvalToken)s.delete(u.approvalToken);if(E.catalogDigest!==w.digest)n=null;if(E.result.isError)throw new oe(E.result);return be(w,h)?.outputSchema&&E.result.structuredContent!==void 0?E.result.structuredContent:E.result};try{return await y(b)}catch(w){if(!Y(w))throw w}let f=await r({refresh:!0,...u.signal?{signal:u.signal}:{}}),R=d(f);if(u.approvalToken&&f.digest!==b.digest)throw new Q(m,b.digest,f.digest,R);return await y(f)},o=async(d,p={},u={})=>await i((m)=>we(m,d),p,u),a=async(d,p={},u={})=>{let m=u.operationId??crypto.randomUUID(),b=async(R)=>{let w={operationId:m,catalogDigest:R.digest,identity:we(R,d),arguments:p};try{let h=await this.transport.requestJson(\"POST\",`/v1/workspaces/${encodeURIComponent(t)}/tools/approvals`,w,{},u.signal?{signal:u.signal}:{});return s.set(h.approvalToken,{operationId:h.operationId,catalogDigest:h.catalogDigest,identity:h.identity}),h}catch(h){if(Y(h))n=null;throw h}},y=await r(u.signal?{signal:u.signal}:{});try{return await b(y)}catch(R){if(!Y(R))throw R}let f=await r({refresh:!0,...u.signal?{signal:u.signal}:{}});return await b(f)},c=async(d,p={},u={})=>await i((m)=>Wt(m,d).identity,p,u),l=(d)=>new Proxy(async(p={},u={})=>await c(d,p,u),{get:(p,u)=>{if(u===\"then\")return;if(typeof u!==\"string\")return;return l([...d,u])}});return new Proxy(Object.create(null),{get:(d,p)=>{if(p===\"then\")return;if(p===\"$catalog\")return r;if(p===\"$call\")return o;if(p===\"$approve\")return a;if(p===\"$declarations\")return async(u={})=>await this.transport.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(t)}/tools/declarations`,void 0,{},u.signal?{signal:u.signal}:{});if(typeof p!==\"string\")return;return l([p])}})}}function be(e,t){return e.entries.find((n)=>n.identity.serverId===t.serverId&&n.identity.toolName===t.toolName)}function Lt(e,t){return e.serverId===t.serverId&&e.toolName===t.toolName}function we(e,t){let n=be(e,t);if(!n)throw Error(`Tool is not present in the workspace catalog: ${t.serverId}/${t.toolName}`);return n.identity}function Wt(e,t){let n=e.entries.find((s)=>s.codemodePath.length===t.length&&s.codemodePath.every((r,i)=>r===t[i]));if(!n)throw Error(`Tool is not present in the workspace catalog: ${t.join(\".\")}`);return n}function Y(e){return e instanceof g&&e.status===409&&e.details?.code===\"catalog_stale\"||typeof e===\"object\"&&e!==null&&\"code\"in e&&e.code===\"catalog_stale\"}function Ft(e,t){let n=e.trim();if(!n)throw TypeError(`${t} is required`);return n}var oe,Q;var ae=me(()=>{G();oe=class oe extends Error{result;code;retryable;outcomeUnknown;constructor(e){let t=e.structuredContent;super(typeof t?.error?.message===\"string\"?t.error.message:\"OpenGeni tool call failed\");this.result=e;this.name=\"OpenGeniToolCallError\",this.code=typeof t?.error?.code===\"string\"?t.error.code:\"tool_error\",this.retryable=t?.error?.retryable===!0,this.outcomeUnknown=t?.error?.outcomeUnknown===!0}};Q=class Q extends Error{operationId;previousCatalogDigest;catalogDigest;identity;code=\"tool_reapproval_required\";retryable=!1;constructor(e,t,n,s){super(\"The workspace tool catalog changed after approval. Request a new approval for the refreshed tool identity and retry with the same operation ID.\");this.operationId=e;this.previousCatalogDigest=t;this.catalogDigest=n;this.identity=s;this.name=\"OpenGeniToolReapprovalRequiredError\"}}});class ye extends Error{code=\"site_session_path_unsupported\";constructor(){super(\"Unsupported Site session API path\");this.name=\"SiteSessionPathError\"}}function z(e,t,n=\"GET\",s){let r=e.split(\"?\")[0];if(!(r===\"/v1/workspaces/site-host\"||r.startsWith(\"/v1/workspaces/site-host/\"))&&r!==\"/v1/config/client\"||/[%\\\\#\\u0000-\\u0020\\u007f]/u.test(r)||r.split(\"/\").some((l)=>l===\".\"||l===\"..\"))throw new ye;let a=e.replace(\"/workspaces/site-host\",`/workspaces/${encodeURIComponent(t)}`),c=new URL(a,\"http://site.invalid\");if(c.searchParams.get(\"originSiteId\")===\"current\"&&t!==\"site-host\")return c.searchParams.set(\"originSiteId\",s??\"00000000-0000-0000-0000-000000000000\"),c.pathname+c.search;return a}var Dt=\"opengeni.site.http\",X=\"site-host\";async function fe(e,t,n){let s=new Request(t,n),r=new URL(s.url),i=`${r.pathname}${r.search}`;z(i,X,s.method);let o=new MessageChannel,a=crypto.randomUUID(),c=s.body?await s.text():void 0;return await new Promise((l,d)=>{let p,u=!1,m=()=>{u=!0,s.signal.removeEventListener(\"abort\",b),o.port1.close()},b=()=>{if(u)return;e.postMessage({type:\"opengeni.site.cancel\",version:2,requestId:a});let y=s.signal.reason??new DOMException(\"Cancelled\",\"AbortError\");p?.error(y),d(y),m()};if(o.port1.onmessage=(y)=>{let f=y.data;if(f.error){let R=Error(f.error);p?.error(R),d(R),m()}else if(f.status){let R=f.body?new ReadableStream({start(w){p=w},pull(){o.port1.postMessage(\"pull\")},cancel(){p=void 0,b()}}):null;if(l(new Response(R,{status:f.status,headers:f.headers})),!f.body)m()}else if(f.done)p?.close(),m();else if(f.chunk)p?.enqueue(f.chunk)},s.signal.aborted){b();return}s.signal.addEventListener(\"abort\",b,{once:!0}),e.postMessage({type:Dt,requestId:a,path:i,method:s.method,headers:[...s.headers],...c===void 0?{}:{body:c}},[o.port2])})}ae();G();G();async function*O(e){let t=e.getReader(),n=new TextDecoder,s=\"\",r,i,o=null,a=()=>{let l=o===null?null:{...r!==void 0?{id:r}:{},...i!==void 0?{event:i}:{},data:o.join(`\n`)};return r=void 0,i=void 0,o=null,l},c=(l)=>{if(l===\"\")return a();if(l.startsWith(\":\"))return null;let d=l.indexOf(\":\"),p=d===-1?l:l.slice(0,d),u=d===-1?\"\":l.slice(d+1);if(u.startsWith(\" \"))u=u.slice(1);if(p===\"data\")(o??=[]).push(u);else if(p===\"event\")i=u;else if(p===\"id\")r=u;return null};try{while(!0){let{done:l,value:d}=await t.read();if(l)break;s+=n.decode(d,{stream:!0});let p=s.indexOf(`\n`);while(p!==-1){let u=s.slice(0,p);if(s=s.slice(p+1),u.endsWith(\"\\r\"))u=u.slice(0,-1);let m=c(u);if(m)yield m;p=s.indexOf(`\n`)}}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}var zt=Symbol.for(\"@opengeni/sdk/session-event-stream-covered-through\");async function*ve(e,t={}){let n=t.signal,s=t.reconnect??!0,r=t.reconnectDelayMs??500,i=t.maxReconnectDelayMs??1e4,o=t.reconnectJitterRatio??0.2,a=t.beforeLiveTimeoutMs??15000,c=t.heartbeatTimeoutMs??45000,l=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=t.after??0,p=0,u=r,m=!1;while(!0){if(n?.aborted)break;t.onStateChange?.(m||p>0?\"reconnecting\":\"connecting\");let b=d;try{let y=await e.openStream(d,n);m=!0,p=0,u=r;try{t.onOpen?.()}catch{}await _(t.beforeLive,a,n),t.onStateChange?.(\"live\");for await(let f of O(M(y,c,n))){if(n?.aborted)return;let R=Vt(f.data);if(!R)continue;let w=Nt(f.id,R.sequence);if(Kt(R,w),w<=d)continue;if(R.sequence>d+1){for await(let h of Jt(e,d,R.sequence-1))if(d=h.sequence,yield h,n?.aborted)return}d=w,yield R}if(!s)return;if(d===b)await Se(P(r,o),n);continue}catch(y){if(n?.aborted||A(y))return;if(!s||!q(y))throw y;if(p+=1,p>l)throw new C(`event stream gave up after ${l} consecutive failed reconnect attempts: ${y instanceof Error?y.message:String(y)}`)}await Se(P(u,o),n),u=Math.min(Math.max(u*2,r),i)}}async function _(e,t,n){if(!e)return;let s,r,i=new Promise((o,a)=>{if(s=setTimeout(()=>a(TypeError(`stream reconciliation timed out after ${t}ms`)),t),n)r=()=>a(new DOMException(\"Aborted\",\"AbortError\")),n.addEventListener(\"abort\",r,{once:!0})});try{await Promise.race([Promise.resolve().then(e),i])}finally{if(s!==void 0)clearTimeout(s);if(n&&r)n.removeEventListener(\"abort\",r)}}function P(e,t){if(e<=0||t<=0)return e;let n=Math.min(t,1),s=e*n;return Math.max(0,e-s+Math.random()*s*2)}function M(e,t,n){if(!Number.isSafeInteger(t)||t<=0)throw RangeError(\"stream heartbeat timeout must be a positive safe integer\");let s=e.getReader();return new ReadableStream({pull:async(r)=>{let i,o;try{let a=await Promise.race([s.read(),new Promise((c,l)=>{if(i=setTimeout(()=>l(TypeError(`event stream heartbeat timed out after ${t}ms`)),t),n)o=()=>l(new DOMException(\"Aborted\",\"AbortError\")),n.addEventListener(\"abort\",o,{once:!0})})]);if(a.done)r.close();else r.enqueue(a.value)}catch(a){s.cancel(a).catch(()=>{}),r.error(a)}finally{if(i!==void 0)clearTimeout(i);if(n&&o)n.removeEventListener(\"abort\",o)}},cancel:async(r)=>{await s.cancel(r)}})}async function*Jt(e,t,n){let s=t;while(s<n){let i=(await e.listEvents(s,Math.min(500,n-s))).filter((o)=>o.sequence>s&&o.sequence<=n).sort((o,a)=>o.sequence-a.sequence);if(i.length===0)throw new C(`event replay backfill stalled: expected sequences ${s+1}..${n} but the replay endpoint returned none of them`);for(let o of i){if(o.sequence!==s+1)throw new C(`event replay backfill is missing sequence ${s+1} (replay endpoint skipped to ${o.sequence}); refusing to deliver with a gap`);s=o.sequence,yield o}}}function Vt(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!==\"object\"||t===null||typeof t.sequence!==\"number\"||typeof t.type!==\"string\"||typeof t.id!==\"string\")return null;return t}function Nt(e,t){if(e===void 0||!/^\\d+$/.test(e))return t;let n=Number(e);return Number.isSafeInteger(n)&&n>=t?n:t}function Kt(e,t){Object.defineProperty(e,zt,{value:t,enumerable:!1,configurable:!1,writable:!1})}async function Se(e,t){if(t?.aborted||e<=0)return;await new Promise((n)=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t?.removeEventListener(\"abort\",r),n()}t?.addEventListener(\"abort\",r,{once:!0})})}G();async function*Ie(e,t={}){let n=t.signal,s=t.reconnect??!0,r=t.reconnectDelayMs??500,i=t.maxReconnectDelayMs??1e4,o=t.reconnectJitterRatio??0.2,a=t.beforeLiveTimeoutMs??15000,c=t.heartbeatTimeoutMs??45000,l=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=t.after??0,p=0,u=r,m=!1;for(;;){if(n?.aborted)return;t.onStateChange?.(m||p>0?\"reconnecting\":\"connecting\");let b=d;try{let y=await e.openStream(d,n);m=!0,p=0,u=r,await _(t.beforeLive,a,n),t.onStateChange?.(\"live\");for await(let f of O(M(y,c,n))){if(n?.aborted)return;let R=Ht(f.data);if(!R||R.sequence<=d)continue;d=R.sequence,yield R}if(!s)return;if(d===b)await ke(P(r,o),n);continue}catch(y){if(n?.aborted||A(y))return;if(!s||!q(y))throw y;if(p+=1,p>l)throw new C(`workspace control stream gave up after ${l} reconnect attempts: ${y instanceof Error?y.message:String(y)}`)}await ke(P(u,o),n),u=Math.min(Math.max(u*2,r),i)}}function Ht(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!==\"object\"||t===null||t.type!==\"workspace.control.changed\"||typeof t.id!==\"string\"||typeof t.sequence!==\"number\")return null;return t}async function ke(e,t){if(t?.aborted||e<=0)return;await new Promise((n)=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t?.removeEventListener(\"abort\",r),n()}t?.addEventListener(\"abort\",r,{once:!0})})}G();async function*Pe(e,t={}){let n=t.signal,s=t.reconnect??!0,r=t.reconnectDelayMs??500,i=t.maxReconnectDelayMs??1e4,o=t.reconnectJitterRatio??0.2,a=t.beforeLiveTimeoutMs??15000,c=t.heartbeatTimeoutMs??45000,l=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=t.after??0,p=0,u=r,m=!1;for(;;){if(n?.aborted)return;t.onStateChange?.(m||p>0?\"reconnecting\":\"connecting\");let b=d;try{let y=await e.openStream(d,n);m=!0,p=0,u=r,await _(t.beforeLive,a,n),t.onStateChange?.(\"live\");for await(let f of O(M(y,c,n))){if(n?.aborted)return;let R=jt(f.data);if(!R||R.sequence<=d)continue;d=R.sequence,yield R}if(!s)return;if(d===b)await Ce(P(r,o),n);continue}catch(y){if(n?.aborted||A(y))return;if(!s||!q(y))throw y;if(p+=1,p>l)throw new C(`workspace interaction stream gave up after ${l} reconnect attempts: ${y instanceof Error?y.message:String(y)}`)}await Ce(P(u,o),n),u=Math.min(Math.max(u*2,r),i)}}function jt(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Xt(t)||t.type!==\"workspace.interaction.changed\"||typeof t.workspaceId!==\"string\"||typeof t.sequence!==\"number\"||!Number.isSafeInteger(t.sequence)||t.sequence<0||t.revision!==t.sequence||typeof t.occurredAt!==\"string\")return null;return t}function Xt(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}async function Ce(e,t){if(t?.aborted||e<=0)return;await new Promise((n)=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t?.removeEventListener(\"abort\",r),n()}t?.addEventListener(\"abort\",r,{once:!0})})}G();async function*Ae(e,t={}){let n=t.signal,s=t.reconnect??!0,r=t.reconnectDelayMs??500,i=t.maxReconnectDelayMs??1e4,o=t.reconnectJitterRatio??0.2,a=t.beforeLiveTimeoutMs??15000,c=t.heartbeatTimeoutMs??45000,l=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=t.controlAfter??0,p=t.interactionAfter??0,u=0,m=r,b=!1;for(;;){if(n?.aborted)return;t.onStateChange?.(b||u>0?\"reconnecting\":\"connecting\");let y=`${d}:${p}`;try{let f=await e.openStream(d,p,n);b=!0,u=0,m=r,await _(t.beforeLive,a,n),t.onStateChange?.(\"live\");for await(let R of O(M(f,c,n))){if(n?.aborted)return;let w=Yt(R.data);if(!w)continue;if(w.type===\"workspace.control.changed\"){if(w.sequence<=d)continue;d=w.sequence}else{if(w.sequence<=p)continue;p=w.sequence}yield w}if(!s)return;if(`${d}:${p}`===y)await xe(P(r,o),n);continue}catch(f){if(n?.aborted||A(f))return;if(!s||!q(f))throw f;if(u+=1,u>l)throw new C(`workspace live stream gave up after ${l} reconnect attempts: ${f instanceof Error?f.message:String(f)}`)}await xe(P(m,o),n),m=Math.min(Math.max(m*2,r),i)}}function Yt(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Qt(t)||typeof t.sequence!==\"number\")return null;if(t.type===\"workspace.control.changed\"&&typeof t.id===\"string\"&&Number.isSafeInteger(t.sequence))return t;if(t.type===\"workspace.interaction.changed\"&&typeof t.workspaceId===\"string\"&&Number.isSafeInteger(t.sequence)&&t.sequence>=0&&t.revision===t.sequence&&typeof t.occurredAt===\"string\")return t;return null}function Qt(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}async function xe(e,t){if(t?.aborted||e<=0)return;await new Promise((n)=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t?.removeEventListener(\"abort\",r),n()}t?.addEventListener(\"abort\",r,{once:!0})})}var qe=32768,Zt=1e8;class ce{attachedBrowsers;authRuns;browsers;computers;identities;interventions;networkRoutes;siteAuthConnections;constructor(e){this.attachedBrowsers=new Le(e),this.authRuns=new Be(e),this.browsers=new Je(e),this.computers=new Xe(e),this.identities=new Fe(e),this.interventions=new Ue(e),this.networkRoutes=new Ee(e),this.siteAuthConnections=new _e(e)}}class Ee{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listNetworkRoutes(e,t)}route(e,t){return new Ge(this.transport,e,t)}async create(e,t,n={}){let s=await this.transport.createNetworkRoute(e,t,n);return this.route(e,s.route.id)}}class Ge{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getNetworkRoute(this.workspaceId,this.id,e)}async update(e,t={}){return await this.transport.updateNetworkRoute(this.workspaceId,this.id,e,t)}}class _e{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listSiteAuthConnections(e,t)}connection(e,t){return new Me(this.transport,e,t)}async create(e,t,n={}){let s=await this.transport.createSiteAuthConnection(e,t,n);return this.connection(e,s.connection.id)}}class Me{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getSiteAuthConnection(this.workspaceId,this.id,e)}async update(e,t={}){return await this.transport.updateSiteAuthConnection(this.workspaceId,this.id,e,t)}}class Be{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listAuthRuns(e,t)}async get(e,t,n={}){return await this.transport.getAuthRun(e,t,n)}run(e,t,n){return new ue(this.transport,e,t,n)}}class $e{transport;workspaceId;browserSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.browserSessionId=n}async list(e={}){return await this.transport.listAuthRuns(this.workspaceId,{...e,browserSessionId:this.browserSessionId})}run(e){return new ue(this.transport,this.workspaceId,this.browserSessionId,e)}async start(e,t={}){let n=await this.transport.startBrowserAuthRun(this.workspaceId,this.browserSessionId,e,t);return this.run(n.run.id)}}class ue{transport;workspaceId;browserSessionId;id;constructor(e,t,n,s){this.transport=e;this.workspaceId=t;this.browserSessionId=n;this.id=s}async get(e={}){let t=await this.transport.getAuthRun(this.workspaceId,this.id,e);if(t.browserSessionId!==this.browserSessionId)throw Error(\"AuthRun belongs to another BrowserSession\");return t}async report(e,t={}){return await this.transport.reportBrowserAuthRun(this.workspaceId,this.browserSessionId,this.id,e,t)}async protectedFill(e,t={}){return await this.transport.protectedBrowserAuthFill(this.workspaceId,this.browserSessionId,this.id,e,t)}async advanceExternal(e,t={}){return await this.transport.advanceExternalBrowserAuthRun(this.workspaceId,this.browserSessionId,this.id,e,t)}async openExternalFlow(e,t={}){return await this.transport.openExternalBrowserAuthFlow(this.workspaceId,this.browserSessionId,this.id,e,t)}async verify(e,t={}){return await this.transport.verifyBrowserAuthRun(this.workspaceId,this.browserSessionId,this.id,e,t)}}class Ue{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listInteractionInterventions(e,t)}intervention(e,t){return new De(this.transport,e,t)}async create(e,t,n={}){let s=await this.transport.createInteractionIntervention(e,t,n);return this.intervention(e,s.intervention.id)}}class De{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getInteractionIntervention(this.workspaceId,this.id,e)}async resolve(e,t={}){return await this.transport.resolveInteractionIntervention(this.workspaceId,this.id,e,t)}}class Le{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listAttachedBrowsers(e,t)}device(e,t){return new We(this.transport,e,t)}}class We{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getAttachedBrowser(this.workspaceId,this.id,e)}}class Fe{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listBrowserIdentities(e,t)}identity(e,t){return new ze(this.transport,e,t)}async create(e,t,n={}){let s=await this.transport.createBrowserIdentity(e,t,n);return this.identity(e,s.identity.id)}}class ze{transport;workspaceId;id;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n}async get(e={}){return await this.transport.getBrowserIdentity(this.workspaceId,this.id,e)}async revisions(e={}){return await this.transport.listBrowserRevisions(this.workspaceId,this.id,e)}async update(e,t={}){return await this.transport.updateBrowserIdentity(this.workspaceId,this.id,e,t)}}class Je{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listBrowserSessions(e,t)}session(e,t){return new Ve(this.transport,e,t)}async open(e,t,n={}){let s=await this.transport.createBrowserSession(e,t,n);return this.session(e,s.session.id)}async currentOrOpen(e){let t=e.signal?{signal:e.signal}:{},n=await this.list(e.workspaceId,t),s=tn(n.sessions,e.associationSessionId);if(s){let r=this.session(e.workspaceId,s.id);if(s.lifecycle===\"suspended\")await r.resume({operationId:e.operationId??crypto.randomUUID()},t);return r}return await this.open(e.workspaceId,{operationId:e.operationId??crypto.randomUUID(),sessionId:e.associationSessionId,...e.name!==void 0?{name:e.name}:{},...e.initialUrl!==void 0?{initialUrl:e.initialUrl}:{},...e.headless!==void 0?{headless:e.headless}:{},...e.placement!==void 0?{placement:e.placement}:{},...e.identityId!==void 0?{identityId:e.identityId}:{},...e.baseRevisionId!==void 0?{baseRevisionId:e.baseRevisionId}:{},...e.networkRouteId!==void 0?{networkRouteId:e.networkRouteId}:{},...e.linkedComputerSessionId!==void 0?{linkedComputerSessionId:e.linkedComputerSessionId}:{}},t)}}class Ve{transport;workspaceId;id;auth;clipboard;downloads;tabs;targets;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n;this.auth=new $e(e,t,n),this.clipboard=new Ne(e,t,n),this.downloads=new Ke(e,t,n),this.tabs=new je(e,t,n),this.targets=this.tabs}async get(e={}){return await this.transport.getBrowserSession(this.workspaceId,this.id,e)}async observe(e,t={}){return await this.transport.observeBrowserTarget(this.workspaceId,this.id,e,t)}async targetState(e,t={}){return await this.transport.getBrowserTargetState(this.workspaceId,this.id,e,t)}async readDom(e,t,n={}){return await this.transport.readBrowserDom(this.workspaceId,this.id,e,t,n)}async capture(e,t={},n={}){return await this.transport.captureBrowserTarget(this.workspaceId,this.id,e,t,n)}async screenshot(e,t={},n={}){return await this.capture(e,n,t)}async act(e,t={}){return await this.transport.actInBrowser(this.workspaceId,this.id,e,t)}async receipt(e,t={}){return await this.transport.getBrowserActionReceipt(this.workspaceId,this.id,e,t)}async diagnostics(e,t={}){return await this.transport.listBrowserDiagnostics(this.workspaceId,this.id,e,t)}async attach(e,t={}){return await this.transport.attachBrowserSession(this.workspaceId,this.id,e,t)}async heartbeat(e={}){return await this.transport.heartbeatBrowserSession(this.workspaceId,this.id,e)}async publishRevision(e,t={}){return await this.transport.publishBrowserRevision(this.workspaceId,this.id,e,t)}async suspend(e={operationId:crypto.randomUUID()},t={}){return await this.transport.suspendBrowserSession(this.workspaceId,this.id,e,t)}async resume(e={operationId:crypto.randomUUID()},t={}){return await this.transport.resumeBrowserSession(this.workspaceId,this.id,e,t)}async end(e={operationId:crypto.randomUUID()},t={}){return await this.transport.endBrowserSession(this.workspaceId,this.id,e,t)}}class Ne{transport;workspaceId;browserSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.browserSessionId=n}async read(e={}){let t=await this.transport.readBrowserClipboard(this.workspaceId,this.browserSessionId,e);if(t.browserSessionId!==this.browserSessionId)throw Error(\"Browser clipboard belongs to another BrowserSession\");return t}}class Ke{transport;workspaceId;browserSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.browserSessionId=n}async list(e={}){return await this.transport.listBrowserDownloads(this.workspaceId,this.browserSessionId,e)}download(e){return new He(this.transport,this.workspaceId,this.browserSessionId,e)}}class He{transport;workspaceId;browserSessionId;id;constructor(e,t,n,s){this.transport=e;this.workspaceId=t;this.browserSessionId=n;this.id=s}async get(e={}){let t=await this.transport.getBrowserDownload(this.workspaceId,this.browserSessionId,this.id,e);if(t.browserSessionId!==this.browserSessionId)throw Error(\"BrowserDownload belongs to another BrowserSession\");return t}async saveToWorkspace(e,t={}){let{operationId:n=crypto.randomUUID(),overwrite:s=!1,...r}=t,i=await this.transport.saveBrowserDownload(this.workspaceId,this.browserSessionId,this.id,{operationId:n,destinationPath:e,overwrite:s},r);if(i.download.id!==this.id||i.download.browserSessionId!==this.browserSessionId)throw Error(\"BrowserDownload save returned another resource\");return i}}class je{transport;workspaceId;browserSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.browserSessionId=n}async list(e={}){return await this.transport.listBrowserTargets(this.workspaceId,this.browserSessionId,e)}async open(e,t={}){return await this.transport.openBrowserTarget(this.workspaceId,this.browserSessionId,e===void 0?{}:{url:e},t)}async select(e,t={}){return await this.transport.selectBrowserTarget(this.workspaceId,this.browserSessionId,e,t)}async close(e,t={}){return await this.transport.closeBrowserTarget(this.workspaceId,this.browserSessionId,e,t)}}class Xe{transport;constructor(e){this.transport=e}async list(e,t={}){return await this.transport.listComputerSessions(e,t)}session(e,t){return new Ye(this.transport,e,t)}async open(e,t,n={}){let s=await this.transport.createComputerSession(e,t,n);return this.session(e,s.session.id)}async currentOrOpen(e){let t=e.signal?{signal:e.signal}:{},n=await this.list(e.workspaceId,t),s=nn(n.sessions,e.associationSessionId);if(s)return this.session(e.workspaceId,s.id);return await this.open(e.workspaceId,{operationId:e.operationId??crypto.randomUUID(),sessionId:e.associationSessionId,...e.name!==void 0?{name:e.name}:{},...e.placement!==void 0?{placement:e.placement}:{}},t)}}class Ye{transport;workspaceId;id;targets;apps;clipboard;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.id=n;this.targets=new Ze(e,t,n),this.apps=this.targets,this.clipboard=new Qe(e,t,n)}async get(e={}){return await this.transport.getComputerSession(this.workspaceId,this.id,e)}async observe(e,t={}){return await this.transport.observeComputerTarget(this.workspaceId,this.id,e,t)}async capture(e,t={}){return await this.transport.captureComputerTarget(this.workspaceId,this.id,e,t)}async act(e,t={}){return await this.transport.actInComputer(this.workspaceId,this.id,e,t)}async receipt(e,t={}){return await this.transport.getComputerActionReceipt(this.workspaceId,this.id,e,t)}async attach(e,t={}){return await this.transport.attachComputerSession(this.workspaceId,this.id,e,t)}async heartbeat(e={}){return await this.transport.heartbeatComputerSession(this.workspaceId,this.id,e)}async end(e={operationId:crypto.randomUUID()},t={}){return await this.transport.endComputerSession(this.workspaceId,this.id,e,t)}}class Qe{transport;workspaceId;computerSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.computerSessionId=n}async read(e={}){let t=await this.transport.readComputerClipboard(this.workspaceId,this.computerSessionId,e);if(t.computerSessionId!==this.computerSessionId)throw Error(\"Computer clipboard belongs to another ComputerSession\");return t}}class Ze{transport;workspaceId;computerSessionId;constructor(e,t,n){this.transport=e;this.workspaceId=t;this.computerSessionId=n}async list(e={}){return await this.transport.listComputerTargets(this.workspaceId,this.computerSessionId,e)}}function et(e){if(!it(e))throw Error(\"browser frame metadata is invalid\");let t=new Set([\"frameId\",\"browserSessionId\",\"controllerGeneration\",\"targetId\",\"targetGeneration\",\"documentGeneration\",\"sequence\",\"mediaType\",\"width\",\"height\",\"deviceScaleFactor\",\"scrollX\",\"scrollY\",\"capturedAt\"]);if(Object.keys(e).some((i)=>!t.has(i)))throw Error(\"browser frame metadata contains unknown fields\");let n=[\"frameId\",\"browserSessionId\",\"controllerGeneration\",\"targetId\",\"targetGeneration\",\"documentGeneration\",\"mediaType\",\"capturedAt\"];for(let i of n){let o=e[i],a=i===\"targetId\"?512:i===\"capturedAt\"?128:256;if(typeof o!==\"string\"||o.length<1||st(o)>a)throw Error(\"browser frame metadata is invalid\")}let s=[\"sequence\",\"width\",\"height\",\"deviceScaleFactor\",\"scrollX\",\"scrollY\"];for(let i of s)if(typeof e[i]!==\"number\"||!Number.isFinite(e[i]))throw Error(\"browser frame metadata is invalid\");let r=e;if(!Number.isSafeInteger(r.sequence)||r.sequence<0||!Number.isSafeInteger(r.width)||!Number.isSafeInteger(r.height))throw Error(\"browser frame metadata integers are invalid\");if(nt(r.width,r.height),r.deviceScaleFactor<=0||r.deviceScaleFactor>16||Math.abs(r.scrollX)>1e9||Math.abs(r.scrollY)>1e9)throw Error(\"browser frame geometry metadata is invalid\");if(r.mediaType!==\"image/jpeg\"&&r.mediaType!==\"image/png\")throw Error(\"browser frame media type is invalid\");if(!rt(r.browserSessionId))throw Error(\"browser frame session id is invalid\");if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(r.controllerGeneration))throw Error(\"browser frame controller generation is invalid\");if(!Number.isFinite(new Date(r.capturedAt).valueOf()))throw Error(\"browser frame timestamp is invalid\");return r}function en(e){if(!it(e))throw Error(\"computer frame metadata is invalid\");let t=new Set([\"frameId\",\"computerSessionId\",\"controllerGeneration\",\"targetId\",\"targetGeneration\",\"sequence\",\"mediaType\",\"width\",\"height\",\"capturedAt\",\"sha256\"]);if(Object.keys(e).some((r)=>!t.has(r)))throw Error(\"computer frame metadata contains unknown fields\");let n=[\"frameId\",\"computerSessionId\",\"controllerGeneration\",\"targetId\",\"targetGeneration\",\"mediaType\",\"capturedAt\",\"sha256\"];for(let r of n){let i=e[r],o=r===\"targetId\"?512:r===\"capturedAt\"?128:256;if(typeof i!==\"string\"||i.length<1||st(i)>o)throw Error(\"computer frame metadata is invalid\")}let s=e;if(!Number.isSafeInteger(s.sequence)||s.sequence<0||!Number.isSafeInteger(s.width)||!Number.isSafeInteger(s.height))throw Error(\"computer frame metadata integers are invalid\");if(nt(s.width,s.height),s.mediaType!==\"image/jpeg\"&&s.mediaType!==\"image/png\")throw Error(\"computer frame media type is invalid\");if(!rt(s.computerSessionId))throw Error(\"computer frame session id is invalid\");if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(s.controllerGeneration))throw Error(\"computer frame controller generation is invalid\");if(!Number.isFinite(new Date(s.capturedAt).valueOf()))throw Error(\"computer frame timestamp is invalid\");if(!/^[0-9a-f]{64}$/u.test(s.sha256))throw Error(\"computer frame digest is invalid\");return s}function tt(e){if(!e||e.length>32768||!/^[A-Za-z0-9_-]+$/u.test(e))throw Error(\"computer frame metadata header is invalid\");let t=e.replace(/-/gu,\"+\").replace(/_/gu,\"/\"),n=t.padEnd(Math.ceil(t.length/4)*4,\"=\"),s;try{s=atob(n)}catch{throw Error(\"computer frame metadata header is invalid\")}let r=Uint8Array.from(s,(o)=>o.charCodeAt(0)),i;try{i=JSON.parse(new TextDecoder(\"utf-8\",{fatal:!0}).decode(r))}catch{throw Error(\"computer frame metadata header is invalid\")}return en(i)}function tn(e,t){let n=e.filter((s)=>![\"ending\",\"ended\",\"failed\",\"lost\"].includes(s.lifecycle)&&s.associations.some((r)=>r.sessionId===t));return n.sort((s,r)=>Oe(r,t)-Oe(s,t)),n[0]??null}function nn(e,t){let n=e.filter((s)=>[\"starting\",\"active\",\"restoring\"].includes(s.lifecycle)&&s.associations.some((r)=>r.sessionId===t));return n.sort((s,r)=>Te(r,t)-Te(s,t)),n[0]??null}function Oe(e,t){let n=e.associations.filter((r)=>r.sessionId===t).map((r)=>Date.parse(r.lastUsedAt)).filter(Number.isFinite).reduce((r,i)=>Math.max(r,i),0),s=Date.parse(e.lastUsedAt);return Math.max(n,Number.isFinite(s)?s:0)}function Te(e,t){let n=e.associations.filter((r)=>r.sessionId===t).map((r)=>Date.parse(r.lastUsedAt)).filter(Number.isFinite).reduce((r,i)=>Math.max(r,i),0),s=Date.parse(e.lastUsedAt);return Math.max(n,Number.isFinite(s)?s:0)}function nt(e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<1||t<1||e>qe||t>qe||e*t>Zt)throw Error(\"browser image dimensions exceed their bounded envelope\")}function st(e){return new TextEncoder().encode(e).byteLength}function rt(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e)}function it(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}var U=\"2026-09-plugins-and-skills-v1\",de=\"x-opengeni-api-contract\",ee=\"x-opengeni-correlation-id\";var te=1048576,ot=33554432;var at=536870912;var se=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,ct=/^[0-9a-f]{64}$/,ut=/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/,dt=/^\\/v1\\/workspaces\\/([0-9a-f-]+)\\/artifacts\\/([0-9a-f-]+)\\/content$/;function lt(e,t){if(!B(e,rn))return null;let n=e;if(n.available!==!0||n.kind!==\"file\"||typeof n.artifactId!==\"string\"||!se.test(n.artifactId)||typeof n.contentType!==\"string\"||!/^[a-z0-9][a-z0-9!#$&^_.+-]{0,62}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,62}$/.test(n.contentType)||!ne(n.originalBytes,1,26214399)||typeof n.sha256!==\"string\"||!ct.test(n.sha256)||typeof n.retainedAt!==\"string\"||n.retainedAt.length>64||!ut.test(n.retainedAt)||!Number.isFinite(Date.parse(n.retainedAt))||!B(n.retention,gt)||!B(n.retrieval,mt))return null;let s=n.retention;if(s.policy!==\"workspace_file\"||s.expiresAt!==null)return null;let r=n.retrieval;if(r.method!==\"GET\"||r.acceptRanges!==\"bytes\"||r.maxRangeBytes!==1048576||typeof r.path!==\"string\"||r.path.length>256)return null;let i=dt.exec(r.path);if(!i||!se.test(i[1]??\"\")||i[2]!==n.artifactId||t!==void 0&&i[1]!==t)return null;return e}function pt(e,t){if(!B(e,sn))return null;let n=e;if(n.available!==!0||n.kind!==\"generated_image\"||typeof n.artifactId!==\"string\"||!se.test(n.artifactId)||![\"image/png\",\"image/jpeg\",\"image/webp\"].includes(String(n.contentType))||!ne(n.originalBytes,1,67108864)||typeof n.sha256!==\"string\"||!ct.test(n.sha256)||typeof n.retainedAt!==\"string\"||n.retainedAt.length>64||!ut.test(n.retainedAt)||!Number.isFinite(Date.parse(n.retainedAt))||!B(n.dimensions,on)||!B(n.retention,gt)||!B(n.retrieval,mt))return null;let s=n.dimensions;if(!ne(s.width,1,16384)||!ne(s.height,1,16384)||Number(s.width)*Number(s.height)>67108864)return null;let r=n.retention;if(r.policy!==\"workspace_file\"||r.expiresAt!==null)return null;let i=n.retrieval;if(i.method!==\"GET\"||i.acceptRanges!==\"bytes\"||i.maxRangeBytes!==1048576||typeof i.path!==\"string\"||i.path.length>256)return null;let o=dt.exec(i.path);if(!o||!se.test(o[1]??\"\")||o[2]!==n.artifactId||t!==void 0&&o[1]!==t)return null;return e}var sn=new Set([\"available\",\"artifactId\",\"kind\",\"contentType\",\"originalBytes\",\"sha256\",\"retainedAt\",\"dimensions\",\"retention\",\"retrieval\"]),rn=new Set([\"available\",\"artifactId\",\"kind\",\"contentType\",\"originalBytes\",\"sha256\",\"retainedAt\",\"retention\",\"retrieval\"]),on=new Set([\"width\",\"height\"]),gt=new Set([\"policy\",\"expiresAt\"]),mt=new Set([\"method\",\"path\",\"acceptRanges\",\"maxRangeBytes\"]);function B(e,t){return e!==null&&typeof e===\"object\"&&!Array.isArray(e)&&Object.keys(e).length===t.size&&Object.keys(e).every((n)=>t.has(n))}function ne(e,t,n){return Number.isSafeInteger(e)&&Number(e)>=t&&Number(e)<=n}function yt(e){let{limit:t,parentSessionId:n,scopeSubjectId:s}=e;return{...e.originSiteId?{originSiteId:e.originSiteId}:{},...t===void 0?{}:{limit:String(t)},...n===void 0?{}:{parentSessionId:n??\"null\"},...s===void 0?{}:{scopeSubjectId:s}}}function Rt(e){return e.originSiteId!==void 0||e.channelId!==void 0||e.createdBy!==void 0||e.updatedFrom!==void 0||e.updatedBefore!==void 0||e.createdFrom!==void 0||e.createdBefore!==void 0}function ft(e,t){let n,s,r=new Promise((i,o)=>{n=i,s=o});return{controller:new AbortController,consumers:0,generation:e,promise:r,resolve:n,reject:s,started:!1,listeners:new Set(t?[t]:[])}}function wt(e){if(Object.prototype.hasOwnProperty.call(e,\"tools\"))throw TypeError(\"Message-level tools are not supported; update the session tool policy before sending.\")}function bt(e){if(!(\"agentConfig\"in e)||!e.agentConfig?.machineTarget)return e;let{workingDir:t,...n}=e.agentConfig.machineTarget;if(t===void 0)return e;let s=t.trim();return{...e,agentConfig:{...e.agentConfig,machineTarget:{...n,...s?{workingDir:s}:{}}}}}function an(e){return{forWorkspace(t){let n=t.trim();if(!n)throw TypeError(\"workspaceId is required\");let s,r=()=>s??=Promise.resolve().then(() => (ae(),he)).then(({OpenGeniToolsClient:o})=>new o(e).forWorkspace(n)),i=(o)=>new Proxy(async(...a)=>{let c=await r();for(let l of o)c=c[l];if(typeof c!==\"function\")throw TypeError(\"OpenGeni tool path is not callable\");return await Reflect.apply(c,void 0,a)},{get:(a,c)=>{if(c===\"then\")return;if(typeof c!==\"string\")return;return i([...o,c])}});return new Proxy(Object.create(null),{get:(o,a)=>{if(a===\"then\")return;if(typeof a!==\"string\")return;return i([a])}})}}}class le{externalActorHeader;baseUrl;options;fetchImpl;sessionCommandTimeoutMs;active=new Map;generations=new Map;queued=new Map;interaction;tools;constructor(e){this.baseUrl=e.baseUrl.replace(/\\/+$/,\"\"),this.options=e,this.fetchImpl=e.fetch??((n,s)=>fetch(n,s));let t=e.sessionCommandTimeoutMs??15000;if(!Number.isFinite(t)||t<=0)throw RangeError(\"sessionCommandTimeoutMs must be a finite positive number\");this.sessionCommandTimeoutMs=t,this.interaction=new ce(this),this.tools=an(this)}async transcribeAudio(e,t){let n=crypto.randomUUID(),s=new FormData,r=ln(t.mimeType),i=t.audio instanceof File?t.audio:t.audio instanceof Uint8Array?new File([Uint8Array.from(t.audio)],r,{type:t.mimeType}):new File([t.audio],r,{type:t.mimeType||t.audio.type});if(s.append(\"audio\",i,r),s.append(\"mimeType\",t.mimeType),t.durationSeconds!==void 0)s.append(\"durationSeconds\",String(t.durationSeconds));let o;try{o=await this.fetchImpl(this.url(`/v1/workspaces/${e}/transcriptions`),{method:\"POST\",headers:{...this.headers(n),Accept:\"application/json\"},body:s,...t.signal?{signal:t.signal}:{}})}catch(c){if(t.signal?.aborted)throw c;throw D(n)}if(v(o),!o.ok)throw await S(o,{method:\"POST\",correlationId:n});await N(o,{method:\"POST\",correlationId:n});let a;try{a=await o.json()}catch{throw new g(o.status,\"Invalid transcription response.\",{code:\"invalid_response\",mutation:!0,correlationId:n})}if(!cn(a))throw new g(o.status,\"Invalid transcription response.\",{code:\"invalid_response\",mutation:!0,correlationId:n});return a}async createTranscriptionRecording(e,t){return J(await this.requestJson(\"POST\",`/v1/workspaces/${e}/transcription-recordings`,{recordingId:t.recordingId,mimeType:t.mimeType},{},t.signal?{signal:t.signal}:{}))}async getTranscriptionRecording(e,t,n={}){return J(await this.requestJson(\"GET\",`/v1/workspaces/${e}/transcription-recordings/${t}`,void 0,{},n.signal?{signal:n.signal}:{}))}async listTranscriptionRecordings(e,t={}){let n=await this.requestJson(\"GET\",`/v1/workspaces/${e}/transcription-recordings`,void 0,{},t.signal?{signal:t.signal}:{});if(!dn(n))throw new g(502,\"Invalid transcription recording list response.\",{code:\"invalid_response\"});return n}async uploadTranscriptionRecordingChunk(e,t,n,s){let r=crypto.randomUUID(),i;try{i=await this.fetchImpl(this.url(`/v1/workspaces/${e}/transcription-recordings/${t}/chunks/${n}`),{method:\"PUT\",headers:{...this.headers(r),Accept:\"application/json\",\"Content-Type\":s.mimeType,\"x-opengeni-chunk-sha256\":s.sha256,\"x-opengeni-chunk-start-milliseconds\":String(s.startMilliseconds),\"x-opengeni-chunk-duration-milliseconds\":String(s.durationMilliseconds)},body:s.audio instanceof Uint8Array?Uint8Array.from(s.audio):s.audio,...s.signal?{signal:s.signal}:{}})}catch(a){if(s.signal?.aborted)throw a;throw D(r)}if(v(i),!i.ok)throw await S(i,{method:\"PUT\",correlationId:r});await N(i,{method:\"PUT\",correlationId:r});let o=await i.json().catch(()=>null);if(!un(o))throw new g(i.status,\"Invalid transcription chunk response.\",{code:\"invalid_response\",mutation:!0,correlationId:r});return o}async finalizeTranscriptionRecording(e,t,n){return J(await this.requestJson(\"POST\",`/v1/workspaces/${e}/transcription-recordings/${t}/finalize`,{chunkCount:n.chunkCount,totalBytes:n.totalBytes,totalDurationMilliseconds:n.totalDurationMilliseconds},{},n.signal?{signal:n.signal}:{}))}async processNextTranscriptionRecordingSegment(e,t,n={}){return J(await this.requestJson(\"POST\",`/v1/workspaces/${e}/transcription-recordings/${t}/process-next`,{},{},n.signal?{signal:n.signal}:{}))}async discardTranscriptionRecording(e,t,n={}){return J(await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/transcription-recordings/${t}`,void 0,{},n.signal?{signal:n.signal}:{}))}async createSession(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${encodeURIComponent(e)}/sessions`,t)}async getNewSessionDraft(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/new-session-draft`,void 0,{},t)}async saveNewSessionDraft(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/new-session-draft`,t)}async createFeedback(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/feedback`,t)}async listOwnFeedback(e,t={}){let n=new URLSearchParams;if(t.sessionId)n.set(\"sessionId\",t.sessionId);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));if(t.includeTurns!==void 0)n.set(\"includeTurns\",String(t.includeTurns));return this.requestJson(\"GET\",`/v1/workspaces/${e}/feedback${n.size?`?${n}`:\"\"}`)}async getSession(e,t,n={}){let s=`/v1/workspaces/${e}/sessions/${t}`;return await this.sharedRead(s,(r)=>this.requestJson(\"GET\",s,void 0,{},{signal:r}),n)}async getSessionModelContext(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/model-context`)}async updateSession(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/sessions/${t}`,n)}async updateSessionVariableSets(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/variable-sets`,n)}async getSessionTenancyCreateCapabilities(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/session-tenancy/capabilities`)}async updateSessionVisibility(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/visibility`,n)}async forkSession(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/forks`,n)}async updateSessionToolPolicy(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/tool-policy`,n)}async updateSessionMcpApprovalPolicy(e,t,n,s){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/sessions/${t}/mcp-servers/${encodeURIComponent(n)}/approval-policy`,s)}async searchSessionMessages(e,t,n={}){return this.requestJson(\"GET\",`/v1/workspaces/${e}/session-message-search`,void 0,{query:t.query,...t.sessionId!==void 0?{sessionId:t.sessionId}:{},...t.groupBy!==void 0?{groupBy:t.groupBy}:{},...t.archiveStatus!==void 0?{archiveStatus:t.archiveStatus}:{},...t.limit!==void 0?{limit:String(t.limit)}:{},...t.cursor!==void 0?{cursor:t.cursor}:{}},n)}async getSessionMessagePreview(e,t,n,s={}){return this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/events/${encodeURIComponent(n.eventId)}/message-preview`,void 0,{sequence:String(n.sequence)},s)}async listSessions(e,t={}){if(t.search?.trim()||t.originSiteId){let n=await this.listSessionPage(e,t);return[...n.pinned,...n.sessions]}return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions`,void 0,yt(t))}async listSessionBackgroundCommands(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/background-commands`,void 0,{},n)}async cancelSessionBackgroundCommand(e,t,n){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}/background-commands/${n}`)}async listSessionPage(e,t={}){let n=t.search?.trim(),s;try{s=await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions`,void 0,{view:\"page\",...yt(t),...t.cursor!==void 0?{cursor:t.cursor}:{},...n?{search:n}:{},...t.channelId!==void 0?{channelId:t.channelId??\"null\"}:{},...t.createdBy?{createdByKind:t.createdBy.kind,createdBySubjectId:t.createdBy.subjectId}:{},...t.updatedFrom?{updatedFrom:t.updatedFrom}:{},...t.updatedBefore?{updatedBefore:t.updatedBefore}:{},...t.createdFrom?{createdFrom:t.createdFrom}:{},...t.createdBefore?{createdBefore:t.createdBefore}:{},...t.pinsOnly?{pinsOnly:\"true\"}:{},...t.archivedOnly?{archivedOnly:\"true\"}:{},...t.sortBy?{sortBy:t.sortBy}:{},...t.archiveStatus?{archiveStatus:t.archiveStatus}:{}},{signal:t.signal})}catch(r){if(r instanceof g&&r.status===410)throw new ie(r.status,r.body,{...r.code?{code:r.code}:{},retryable:r.retryable,...r.correlationId?{correlationId:r.correlationId}:{},outcomeUnknown:r.outcomeUnknown,displayMessage:\"The session list changed \u2014 refresh and try again.\"});throw r}if(t.sortBy!==void 0&&(Array.isArray(s)||s.sortBy!==t.sortBy)||t.archiveStatus!==void 0&&(Array.isArray(s)||s.archiveStatus!==t.archiveStatus))throw Error(\"The connected OpenGeni API does not support the requested session sorting/archive filter\");if(Array.isArray(s)){if(t.cursor)throw Error(\"The connected OpenGeni API does not support stable session-page cursors\");if(n)throw Error(\"The connected OpenGeni API does not support session search\");if(t.pinsOnly)throw Error(\"The connected OpenGeni API does not support pins-only session lists\");if(t.archivedOnly)throw Error(\"The connected OpenGeni API does not support archived session lists\");if(Rt(t))throw Error(\"The connected OpenGeni API does not support filtered session lists\");return{pinned:[],sessions:s,nextCursor:null}}if(Rt(t)&&s.filtersApplied!==!0)throw Error(\"The connected OpenGeni API does not support filtered session lists\");if(t.originSiteId&&(!s.originSiteId||t.originSiteId!==\"current\"&&s.originSiteId!==t.originSiteId))throw Error(\"The connected OpenGeni API does not support Site-filtered session lists\");return s}async listAgentTopology(e,t={}){let n=t.query?.trim()||t.search?.trim();if(n&&t.subject)throw TypeError(\"listAgentTopology query cannot be combined with an exact subject\");return await this.requestJson(\"GET\",`/v1/workspaces/${e}/agent-topology`,void 0,{...t.limit!==void 0?{limit:String(t.limit)}:{},...t.parentSessionId===void 0?{}:{parentSessionId:t.parentSessionId??\"null\"},...t.rootSessionId?{rootSessionId:t.rootSessionId}:{},...t.cursor?{cursor:t.cursor}:{},...n?{query:n}:{},...t.statuses?.length?{statuses:t.statuses.join(\",\")}:{},...t.activeOnly!==void 0?{activeOnly:t.activeOnly?\"true\":\"false\"}:{},...t.recentHours!==void 0?{recentHours:String(t.recentHours)}:{},...t.subject?{subjectNamespace:t.subject.namespace,subjectType:t.subject.type,subjectKey:t.subject.canonicalKey}:{},...t.claimLimit!==void 0?{claimLimit:String(t.claimLimit)}:{}})}async updateSessionPin(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/pin`,n)}async updateSessionAttention(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/attention`,n)}async updateSessionArchive(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/archive`,n)}async deleteSession(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}`)}async getSessionLineage(e,t,n={}){let s=`/v1/workspaces/${e}/sessions/${t}/lineage`;return await this.sharedRead(s,(r)=>this.requestJson(\"GET\",s,void 0,{},{signal:r}),n)}sharedRead(e,t,n={}){if(n.signal?.aborted)return Promise.reject(n.signal.reason??new DOMException(\"Request aborted\",\"AbortError\"));let s=this.active.get(e);if(s){if(!n.fresh)return this.observeRead(s,n.onRequestStart),this.consumeSharedRead(e,s,n.signal);let c=s.generation+1,l=this.queued.get(e);if(l&&l.generation>=c)return this.observeRead(l,n.onRequestStart),this.consumeSharedRead(e,l,n.signal);let d=l?.promise??s.promise;return this.queueRead(e,d,c,t,n)}let r=this.queued.get(e);if(r&&(!n.fresh||!r.started))return this.observeRead(r,n.onRequestStart),this.consumeSharedRead(e,r,n.signal);if(r)return this.queueRead(e,r.promise,r.generation+1,t,n);let i=(this.generations.get(e)??0)+1,o=ft(i,n.onRequestStart),a=this.consumeSharedRead(e,o,n.signal);return this.launchRead(e,o,t),a}queueRead(e,t,n,s,r){let i=ft(n,r.onRequestStart),o=this.consumeSharedRead(e,i,r.signal);this.queued.set(e,i);let a=()=>this.launchRead(e,i,s);t.then(a,a);let c=()=>{if(this.queued.get(e)!==i)return;if(this.queued.delete(e),!this.active.has(e))this.generations.delete(e)};return i.promise.then(c,c),o}launchRead(e,t,n){if(t.controller.signal.aborted)return;t.started=!0,this.generations.set(e,t.generation),this.active.set(e,t);try{t.stamp=this.options.beginSharedRead?.()}catch{}for(let i of t.listeners)try{i(t.stamp)}catch{}t.listeners.clear();let s=()=>{if(this.active.get(e)!==t)return;if(this.active.delete(e),!this.queued.has(e))this.generations.delete(e)},r;try{r=n(t.controller.signal)}catch(i){s(),t.reject(i);return}r.then((i)=>{s(),t.resolve(i)},(i)=>{s(),t.reject(i)})}consumeSharedRead(e,t,n){t.consumers+=1;let s=!1,r=()=>{if(s)return;if(s=!0,t.consumers-=1,!n?.aborted||t.consumers>0)return;let o=n.reason;if(t.controller.abort(o),this.active.get(e)===t)this.active.delete(e);if(this.queued.get(e)===t)this.queued.delete(e);if(!this.active.has(e)&&!this.queued.has(e))this.generations.delete(e);t.reject(o)};return n?.addEventListener(\"abort\",r,{once:!0}),V(t.promise,n).finally(()=>{n?.removeEventListener(\"abort\",r),r()})}observeRead(e,t){if(!t)return;if(!e.started){e.listeners.add(t);return}if(e.stamp===void 0)return;try{t(e.stamp)}catch{}}async negotiateCodexRealtimeWebrtc(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/webrtc`,n,{},{signal:s.signal})}async negotiateGatewayRealtime(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/gateway`,n,{},{signal:s.signal})}async negotiateXaiSubscriptionRealtime(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/supergrok`,n,{},{signal:s.signal})}async activateCodexRealtimeConnection(e,t,n,s,r,i={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/${n}/connections/${s}/activate`,r,{},{signal:i.signal})}async beginSessionRealtime(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime`,n)}async heartbeatSessionRealtime(e,t,n,s){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/sessions/${t}/realtime/${n}/heartbeat`,s)}async syncSessionRealtimeLedger(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/realtime/${n}/sync`,s)}async endSessionRealtime(e,t,n,s){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}/realtime/${n}`,s)}async listTurns(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/turns`,void 0,{...n.limit!==void 0?{limit:String(n.limit)}:{},...n.latestStarted?{latestStarted:\"1\"}:{}},{signal:n.signal})}async getLatestStartedTurn(e,t,n={}){return(await this.listTurns(e,t,{latestStarted:!0,signal:n.signal}))[0]??null}async listMachines(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/machines`,void 0,{...t.sessionId!==void 0?{sessionId:t.sessionId}:{}},{signal:t.signal})}async updateMachineAgent(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/machines/${t}/update`)}async updateMachineOperationPolicy(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/machines/${t}/operation-policy`,n)}async machineMetricsSeries(e,t,n={}){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/machines/${t}/metrics/series`,void 0,{...n.window!==void 0?{window:n.window}:{}})).samples}async removeEnrollment(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/enrollments/${t}/revoke`,n)}async lookupDeviceEnrollment(e){return await this.requestJson(\"POST\",\"/v1/enrollments/device/lookup\",{userCode:e})}async approveDeviceEnrollment(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/enrollments/device/approve`,{userCode:t.userCode,allowScreenControl:t.allowScreenControl??!1,...t.scope?{scope:t.scope}:{}})}async denyDeviceEnrollment(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/enrollments/device/deny`,{userCode:t.userCode})}async mintEnrollToken(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/enrollments/token`,{allowScreenControl:t.allowScreenControl??!1})}async swapActiveSandbox(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/active-sandbox`,n)}async listScheduledTasks(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/scheduled-tasks`,void 0,{...t.offset!==void 0?{offset:String(t.offset)}:{},...t.sessionId?{sessionId:t.sessionId}:{},...t.limit!==void 0?{limit:String(t.limit)}:{}})}async getScheduledTask(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/scheduled-tasks/${t}`)}async listEvents(e,t,n={}){return(await this.listEventPage(e,t,n)).events}async listEventPage(e,t,n={}){if(n.latest&&[\"includeTypes\",\"excludeTypes\",\"includeClasses\",\"excludeClasses\"].some((h)=>Object.prototype.hasOwnProperty.call(n,h)))throw TypeError(\"latest cannot be combined with event filters\");if(n.resultMode===\"compact\"&&!n.latest)throw TypeError(\"resultMode=compact requires latest\");let s=n.resultMode===\"compact\"?null:n,r=crypto.randomUUID(),i=await this.fetchImpl(this.url(`/v1/workspaces/${e}/sessions/${t}/events`,{...s?.after!==void 0?{after:String(s.after)}:{},...s?.before!==void 0?{before:String(s.before)}:{},...s?.limit!==void 0?{limit:String(s.limit)}:{},...s?.compact?{compact:\"1\"}:{},...n.mode?{mode:n.mode}:{},...s?.direction?{direction:s.direction}:{},...n.payloadMode?{payloadMode:n.payloadMode}:{},...n.resultMode?{resultMode:n.resultMode}:{},...s?.includeTypes?.length?{includeTypes:s.includeTypes.join(\",\")}:{},...s?.excludeTypes?.length?{excludeTypes:s.excludeTypes.join(\",\")}:{},...s?.includeClasses?.length?{includeClasses:s.includeClasses.join(\",\")}:{},...s?.excludeClasses?.length?{excludeClasses:s.excludeClasses.join(\",\")}:{},...n.latest?{latest:n.latest}:{}}),{method:\"GET\",headers:{...this.headers(r),Accept:\"application/json\"}});if(v(i),!i.ok)throw await S(i,{method:\"GET\",correlationId:r});await N(i,{method:\"GET\",correlationId:r});let o=await i.json();if(n.resultMode===\"compact\")return o;let a=o,c=(h)=>{let x=i.headers.get(h);if(x===null)return null;let F=Number(x);return Number.isSafeInteger(F)&&F>=0?F:null},l=i.headers.get(\"X-OpenGeni-Event-Mode\")===\"forensic\"?\"forensic\":\"monitoring\",d=i.headers.get(\"X-OpenGeni-Event-Direction\")===\"after\"?\"after\":\"before\",p=i.headers.get(\"X-OpenGeni-Payload-Mode\"),u=p===\"none\"||p===\"full\"?p:\"summary\",m=c(\"X-OpenGeni-Covered-First\"),b=c(\"X-OpenGeni-Covered-Last\"),y=c(\"X-OpenGeni-Page-Bytes\")??new TextEncoder().encode(JSON.stringify(a)).byteLength,f=c(\"X-OpenGeni-Page-Max-Bytes\")??1048576,R=i.headers.get(\"X-OpenGeni-Truncated-By\"),w=R===\"count\"||R===\"bytes\"||R===\"http_bytes\"?R:null;return{events:a,mode:l,payloadMode:u,direction:d,bytes:y,maxBytes:f,truncated:i.headers.get(\"X-OpenGeni-Page-Truncated\")===\"true\",hasMore:i.headers.get(\"X-OpenGeni-Has-More\")===\"true\",truncatedBy:w,coveredSequence:m===null||b===null?null:{first:m,last:b},nextAfter:c(\"X-OpenGeni-Next-After\"),nextBefore:c(\"X-OpenGeni-Next-Before\"),forensicExact:i.headers.get(\"X-OpenGeni-Forensic-Exact\")===\"true\"}}async getLatestEventResult(e,t,n={latest:\"terminal\"}){return await this.listEventPage(e,t,{...n,resultMode:\"compact\"})}async sendEvent(e,t,n){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/events`,n)}async sendMessage(e,t,n){let s=typeof n===\"string\"?{text:n}:n;wt(s);let{clientEventId:r,...i}=s;return await this.sendEvent(e,t,{type:\"user.message\",...r!==void 0?{clientEventId:r}:{},payload:i})}async pauseSession(e,t,n={}){return await this.controlSession(e,t,{action:\"pause\",clientEventId:n.clientEventId??crypto.randomUUID(),...n.reason?{reason:n.reason}:{},...n.expectedControlEtag?{expectedControlEtag:n.expectedControlEtag}:{}})}async sendApprovalDecision(e,t,n){let{clientEventId:s,...r}=n;return await this.sendEvent(e,t,{type:\"user.approvalDecision\",...s!==void 0?{clientEventId:s}:{},payload:r})}async listHumanInputRequests(e,t,n={}){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/human-input-requests`,void 0,n.status?{status:n.status}:void 0)).requests}async getHumanInputRequest(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/human-input-requests/${n}`)}async submitHumanInputResponse(e,t,n,s,r={}){return await this.sendEvent(e,t,{type:\"user.humanInputResponse\",...r.clientEventId?{clientEventId:r.clientEventId}:{},payload:{requestId:n,response:s}})}streamEvents(e,t,n={}){return ve(this.eventStreamTransport(e,t),n)}eventStreamTransport(e,t){return{openStream:async(n,s)=>await this.openEventStream(e,t,{after:n,...s?{signal:s}:{}}),listEvents:async(n,s)=>await this.listEvents(e,t,{after:n,limit:s})}}async openEventStream(e,t,n={}){let s=this.url(`/v1/workspaces/${e}/sessions/${t}/events/stream`,{after:String(n.after??0)}),r=crypto.randomUUID(),i=await this.fetchImpl(s,{method:\"GET\",headers:{...this.headers(r),Accept:\"text/event-stream\"},...n.signal?{signal:n.signal}:{}});if(v(i),!i.ok)throw await S(i,{method:\"GET\",correlationId:r});if(!i.body)throw new g(i.status,\"SSE response did not include a readable body\");return i.body}async getQueue(e,t){let n=`/v1/workspaces/${e}/sessions/${t}/queue`;return await this.sharedRead(n,()=>this.requestSessionCommand(\"GET\",n))}async moveQueueItem(e,t,n,s){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/queue/${n}/move`,s)}async editQueueItem(e,t,n,s){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/queue/${n}/edit`,s)}async steerQueueItem(e,t,n,s){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/queue/${n}/steer`,s)}async deleteQueueItem(e,t,n,s){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/queue/${n}/delete`,s)}async getComposerDraft(e,t,n={}){return await this.requestSessionCommand(\"GET\",`/v1/workspaces/${e}/sessions/${t}/composer-draft`,void 0,n)}async saveComposerDraft(e,t,n){return await this.requestSessionCommand(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/composer-draft`,n)}async submitComposerDraft(e,t,n){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/composer-draft/submit`,n)}async getSandboxRecovery(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/sandbox-recovery`)}async recoverSandbox(e,t,n){return this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/sandbox-recovery`,n)}async retrySession(e,t,n){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/retry`,n)}async controlSession(e,t,n){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/control`,n)}async resumeSession(e,t,n={}){return await this.controlSession(e,t,{action:\"resume\",clientEventId:n.clientEventId??crypto.randomUUID(),...n.reason?{reason:n.reason}:{},...n.expectedControlEtag?{expectedControlEtag:n.expectedControlEtag}:{}})}async cancelSession(e,t,n={}){return await this.controlSession(e,t,{action:\"cancel\",clientEventId:n.clientEventId??crypto.randomUUID(),...n.reason?{reason:n.reason}:{},...n.expectedControlEtag?{expectedControlEtag:n.expectedControlEtag}:{}})}async setWorkspacePauseTimer(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/pause-timer`,t)}async setWorkspaceInferenceState(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/inference-control`,t)}async listWorkspaceControlEvents(e,t={}){return(await this.listWorkspaceControlEventPage(e,t)).events}async listWorkspaceControlEventPage(e,t={}){let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(`/v1/workspaces/${e}/control-events`,{...t.after!==void 0?{after:String(t.after)}:{},...t.limit!==void 0?{limit:String(t.limit)}:{}}),{method:\"GET\",headers:{...this.headers(n),Accept:\"application/json\"}});if(v(s),!s.ok)throw await S(s,{method:\"GET\",correlationId:n});await N(s,{method:\"GET\",correlationId:n});let r=await s.json(),i=s.headers.get(\"X-OpenGeni-Page-Bytes\"),o=s.headers.get(\"X-OpenGeni-Next-After\"),a=i===null?Number.NaN:Number(i),c=o===null?null:Number(o);return{events:r,bytes:Number.isSafeInteger(a)&&a>=0?a:new TextEncoder().encode(JSON.stringify(r)).byteLength,truncated:s.headers.get(\"X-OpenGeni-Page-Truncated\")===\"true\",nextAfter:c!==null&&Number.isSafeInteger(c)&&c>=0?c:null}}streamWorkspaceControlEvents(e,t={}){return Ie(this.workspaceControlStreamTransport(e),t)}streamWorkspaceLiveEvents(e,t={}){return Ae(this.workspaceLiveStreamTransport(e),t)}workspaceLiveStreamTransport(e){return{openStream:async(t,n,s)=>await this.openWorkspaceLiveEventStream(e,{controlAfter:t,interactionAfter:n,...s?{signal:s}:{}})}}async openWorkspaceLiveEventStream(e,t={}){let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(`/v1/workspaces/${e}/live-events/stream`,{controlAfter:String(t.controlAfter??0),interactionAfter:String(t.interactionAfter??0)}),{method:\"GET\",headers:{...this.headers(n),Accept:\"text/event-stream\"},...t.signal?{signal:t.signal}:{}});if(v(s),!s.ok)throw await S(s,{method:\"GET\",correlationId:n});if(!s.body)throw new g(s.status,\"SSE response did not include a readable body\");return s.body}workspaceControlStreamTransport(e){return{openStream:async(t,n)=>await this.openWorkspaceControlEventStream(e,{after:t,...n?{signal:n}:{}})}}async openWorkspaceControlEventStream(e,t={}){let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(`/v1/workspaces/${e}/control-events/stream`,{after:String(t.after??0)}),{method:\"GET\",headers:{...this.headers(n),Accept:\"text/event-stream\"},...t.signal?{signal:t.signal}:{}});if(v(s),!s.ok)throw await S(s,{method:\"GET\",correlationId:n});if(!s.body)throw new g(s.status,\"SSE response did not include a readable body\");return s.body}async steerMessage(e,t,n){let s=typeof n===\"string\"?{text:n}:n;return wt(s),await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/sessions/${t}/steer`,s)}async getGoal(e,t,n={}){let s=`/v1/workspaces/${e}/sessions/${t}/goal`;return await this.sharedRead(s,(r)=>this.requestJson(\"GET\",s,void 0,{},{signal:r}),n)}async updateGoal(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/sessions/${t}/goal`,n)}async listGoalRevisions(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions`)}async listGoalRevisionPage(e,t,n={}){let s=new URLSearchParams;if(n.limit!==void 0)s.set(\"limit\",String(n.limit));if(n.before!==void 0)s.set(\"before\",n.before);let r=s.size>0?`?${s.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions/page${r}`)}async rejectGoalRevision(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions/${n}/reject`,s)}async rollbackGoalRevision(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions/${n}/rollback`,s)}async applyGoalRevision(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/goal/revisions/${n}/apply`,s)}async deleteGoal(e,t){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}/goal`)}async pauseGoal(e,t,n={}){return await this.updateGoal(e,t,{status:\"paused\",...n.rationale!==void 0?{rationale:n.rationale}:{}})}async resumeGoal(e,t){return await this.updateGoal(e,t,{status:\"active\"})}async clearSessionContext(e,t){await this.requestVoid(\"POST\",`/v1/workspaces/${e}/sessions/${t}/context/clear`,{confirm:!0})}async compactSessionContext(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/context/compact`,{})}async fsList(e,t,n={},s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/list`,n,{},s)}async fsListBatch(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/list-batch`,n,{},s)}async fsRead(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/read`,n,{},s)}async publishSandboxFileArtifact(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/artifacts/publish`,n,{},s)}async fsWrite(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/write`,n)}async fsDelete(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/delete`,n)}async fsMove(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/move`,n)}async fsMkdir(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/fs/mkdir`,n)}async gitStatus(e,t,n={},s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/status`,n,{},s)}async gitDiff(e,t,n={},s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/diff`,n,{},s)}async gitReadBatch(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/read-batch`,n,{},s)}async gitLog(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/log`,n)}async gitShow(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/git/show`,n)}async getWorkspaceCapture(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/workspace/capture`,void 0,{},n)}async getWorkspaceCaptureFile(e,t,n,s,r={}){let i={path:n};if(s!==void 0)i.revision=String(s);return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/workspace/capture/file`,void 0,i,r)}async terminalExec(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/exec`,n)}async terminalPtyOpen(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/pty`,n)}async terminalPtyWrite(e,t,n){await this.requestVoid(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/pty/write`,n)}async terminalPtyResize(e,t,n){await this.requestVoid(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/pty/resize`,n)}async terminalPtyClose(e,t,n){await this.requestVoid(\"POST\",`/v1/workspaces/${e}/sessions/${t}/terminal/pty/close`,n)}async getStreamCapabilities(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/stream-capabilities`,void 0,{},n)}async acknowledgeStream(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/stream-capabilities/acknowledge`,n)}async attachViewer(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/viewers`,n)}async heartbeatViewer(e,t,n,s){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/viewers/${n}/heartbeat`,s)}async detachViewer(e,t,n){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/sessions/${t}/viewers/${n}`)}streamWorkspaceInteractionRevisions(e,t={}){return Pe(this.workspaceInteractionRevisionStreamTransport(e),t)}workspaceInteractionRevisionStreamTransport(e){return{openStream:async(t,n)=>await this.openWorkspaceInteractionRevisionStream(e,{after:t,...n?{signal:n}:{}})}}async openWorkspaceInteractionRevisionStream(e,t={}){let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(`/v1/workspaces/${e}/interaction-events/stream`,{after:String(t.after??0)}),{method:\"GET\",headers:{...this.headers(n),Accept:\"text/event-stream\"},...t.signal?{signal:t.signal}:{}});if(v(s),!s.ok)throw await S(s,{method:\"GET\",correlationId:n});if(!s.body)throw new g(s.status,\"SSE response did not include a readable body\");return s.body}async listNetworkRoutes(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/network-routes`,void 0,t.includeArchived?{includeArchived:\"true\"}:{},t)}async getNetworkRoute(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/network-routes/${encodeURIComponent(t)}`,void 0,{},n)}async createNetworkRoute(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/network-routes`,t,{},n)}async updateNetworkRoute(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/network-routes/${encodeURIComponent(t)}`,n,{},s)}async listSiteAuthConnections(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/site-auth-connections`,void 0,t.includeArchived?{includeArchived:\"true\"}:{},t)}async getSiteAuthConnection(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/site-auth-connections/${encodeURIComponent(t)}`,void 0,{},n)}async createSiteAuthConnection(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/site-auth-connections`,t,{},n)}async updateSiteAuthConnection(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/site-auth-connections/${encodeURIComponent(t)}`,n,{},s)}async listAuthRuns(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/auth-runs`,void 0,{...t.browserSessionId?{browserSessionId:t.browserSessionId}:{},...t.siteAuthConnectionId?{siteAuthConnectionId:t.siteAuthConnectionId}:{},...t.includeSettled?{includeSettled:\"true\"}:{}},t)}async getAuthRun(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/auth-runs/${encodeURIComponent(t)}`,void 0,{},n)}async startBrowserAuthRun(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs`,n,{},s)}async reportBrowserAuthRun(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/report`,s,{},r)}async protectedBrowserAuthFill(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/protected-fill`,s,{},r)}async advanceExternalBrowserAuthRun(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/external-auth`,s,{},r)}async openExternalBrowserAuthFlow(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/external-auth/interactive`,s,{},r)}async verifyBrowserAuthRun(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/auth-runs/${encodeURIComponent(n)}/verify`,s,{},r)}async listInteractionInterventions(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/interaction-interventions`,void 0,{...t.resourceKind?{resourceKind:t.resourceKind}:{},...t.resourceId?{resourceId:t.resourceId}:{},...t.includeSettled?{includeSettled:\"true\"}:{}},t)}async getInteractionIntervention(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/interaction-interventions/${encodeURIComponent(t)}`,void 0,{},n)}async createInteractionIntervention(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/interaction-interventions`,t,{},n)}async resolveInteractionIntervention(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/interaction-interventions/${encodeURIComponent(t)}/resolve`,n,{},s)}async listAttachedBrowsers(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/attached-browsers`,void 0,t.includeDisconnected?{includeDisconnected:\"true\"}:{},t)}async getAttachedBrowser(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/attached-browsers/${encodeURIComponent(t)}`,void 0,{},n)}async listBrowserIdentities(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-identities`,void 0,t.includeArchived?{includeArchived:\"true\"}:{},t)}async getBrowserIdentity(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-identities/${encodeURIComponent(t)}`,void 0,{},n)}async createBrowserIdentity(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-identities`,t,{},n)}async updateBrowserIdentity(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/browser-identities/${encodeURIComponent(t)}`,n,{},s)}async listBrowserRevisions(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-identities/${encodeURIComponent(t)}/revisions`,void 0,{},n)}async listBrowserSessions(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions`,void 0,{},t)}async getBrowserSession(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}`,void 0,{},n)}async readBrowserClipboard(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/clipboard`,void 0,{},n)}async listBrowserDownloads(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/downloads`,void 0,{},n)}async getBrowserDownload(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/downloads/${encodeURIComponent(n)}`,void 0,{},s)}async saveBrowserDownload(e,t,n,s,r={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/downloads/${encodeURIComponent(n)}/save`,s,{},r)}async createBrowserSession(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions`,t,{},n)}async listBrowserTargets(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets`,void 0,{},n)}async openBrowserTarget(e,t,n={},s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets`,n,{},s)}async selectBrowserTarget(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/select`,{},{},s)}async captureBrowserTarget(e,t,n,s={},r={}){let i=new URLSearchParams;if(r.fullPage!==void 0){if(typeof r.fullPage!==\"boolean\")throw TypeError(\"browser screenshot fullPage must be a boolean\");i.set(\"fullPage\",String(r.fullPage))}if(r.format!==void 0){if(r.format!==\"jpeg\"&&r.format!==\"png\")throw TypeError(\"browser screenshot format must be jpeg or png\");i.set(\"format\",r.format)}if(r.quality!==void 0){if(!Number.isSafeInteger(r.quality)||r.quality<1||r.quality>100)throw RangeError(\"browser screenshot quality must be an integer from 1 to 100\");i.set(\"quality\",String(r.quality))}let o=i.size>0?`?${i}`:\"\",a=await this.requestResponse(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/screenshot${o}`,{},s),c=a.headers.get(\"content-type\")?.split(\";\",1)[0]?.trim().toLowerCase(),l=a.headers.get(\"x-opengeni-browser-frame\");if(c!==\"image/jpeg\"&&c!==\"image/png\"||!l||l.length>65536)throw await k(a,\"browser frame metadata is invalid\"),new g(502,\"browser frame metadata is invalid\");let d;try{d=et(JSON.parse(atob(l.replace(/-/gu,\"+\").replace(/_/gu,\"/\"))))}catch{throw await k(a,\"browser frame metadata is invalid\"),new g(502,\"browser frame metadata is invalid\")}let p=await K(a,25165824,null);if(d.browserSessionId!==t||d.targetId!==n||d.mediaType!==c)throw new g(502,\"browser frame evidence does not match its request\");return{...d,data:p}}async closeBrowserTarget(e,t,n,s={}){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}`,void 0,{},s)}async observeBrowserTarget(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/observation`,void 0,{},s)}async getBrowserTargetState(e,t,n,s={}){let r=await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/state`,void 0,{},s);if(r.browserSessionId!==t||r.targetId!==n)throw new g(502,\"browser target state belongs to another binding\");return r}async readBrowserDom(e,t,n,s,r={}){let i=await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/dom-read`,s,{},r);if(i.browserSessionId!==t||i.targetId!==n||i.kind!==s.kind||i.targetGeneration!==s.expectedTargetGeneration||i.documentGeneration!==s.expectedDocumentGeneration||i.frameId!==s.expectedFrameId)throw new g(502,\"browser DOM read belongs to another binding\");return i}async actInBrowser(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/actions`,n,{},s)}async getBrowserActionReceipt(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/operations/${encodeURIComponent(n)}`,void 0,{},s)}async listBrowserDiagnostics(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/diagnostics`,void 0,{...s.kinds?.length?{kinds:s.kinds.join(\",\")}:{},...s.after!==void 0?{after:String(s.after)}:{},...s.limit!==void 0?{limit:String(s.limit)}:{}},s.signal?{signal:s.signal}:{})}async attachBrowserSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/attachments`,n,{},s)}async heartbeatBrowserSession(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/heartbeat`,{},{},n)}async publishBrowserRevision(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/revisions`,n,{},s)}async suspendBrowserSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/suspend`,n,{},s)}async resumeBrowserSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/resume`,n,{},s)}async endBrowserSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/browser-sessions/${encodeURIComponent(t)}/end`,n,{},s)}async listComputerSessions(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions`,void 0,{},t)}async getComputerSession(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}`,void 0,{},n)}async readComputerClipboard(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/clipboard`,void 0,{},n)}async createComputerSession(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions`,t,{},n)}async listComputerTargets(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/targets`,void 0,{},n)}async observeComputerTarget(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/observation`,void 0,{},s)}async captureComputerTarget(e,t,n,s={}){let r=await this.requestResponse(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/targets/${encodeURIComponent(n)}/screenshot`,{},s),i=r.headers.get(\"content-type\")?.split(\";\",1)[0]?.trim().toLowerCase();if(i!==\"image/jpeg\"&&i!==\"image/png\")throw await k(r,\"computer frame media type is invalid\"),new g(502,\"computer frame media type is invalid\");let o=r.headers.get(\"x-opengeni-computer-frame\");if(!o||o.length>32768)throw await k(r,\"computer frame metadata is invalid\"),new g(502,\"computer frame metadata is invalid\");let a;try{a=tt(o)}catch{throw await k(r,\"computer frame metadata is invalid\"),new g(502,\"computer frame metadata is invalid\")}let c=await K(r,262144,null);if(Rn(a,{computerSessionId:t,targetId:n,mediaType:i,sha256:await St(c)}))throw new g(502,\"computer frame evidence does not match its request\");return{...a,data:c}}async actInComputer(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/actions`,n,{},s)}async getComputerActionReceipt(e,t,n,s={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/operations/${encodeURIComponent(n)}`,void 0,{},s)}async attachComputerSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/attachments`,n,{},s)}async heartbeatComputerSession(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/heartbeat`,{},{},n)}async endComputerSession(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/computer-sessions/${encodeURIComponent(t)}/end`,n,{},s)}async getClientConfig(e={}){let t=await this.requestJson(\"GET\",\"/v1/config/client\",void 0,{},e);if(t.apiContractRevision!==U)throw new j(U,String(t.apiContractRevision||\"(missing)\"));return t}async getWorkspaceModelCatalog(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/model-catalog`,void 0,{},t)}async listWorkspaceGatewayCustomModels(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/gateway-custom-models`)}async createWorkspaceGatewayCustomModel(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/gateway-custom-models`,t)}async deleteWorkspaceGatewayCustomModel(e,t,n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t))throw TypeError(\"customModelId must be a UUID\");await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/gateway-custom-models/${encodeURIComponent(t)}`,n)}async listWorkspaceOpenRouterCustomModels(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/openrouter-custom-models`)}async createWorkspaceOpenRouterCustomModel(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/openrouter-custom-models`,t)}async deleteWorkspaceOpenRouterCustomModel(e,t,n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t))throw TypeError(\"customModelId must be a UUID\");await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/openrouter-custom-models/${encodeURIComponent(t)}`,n)}async getOrganizationModelProviderConnection(e,t){return await this.requestJson(\"GET\",`/v1/organizations/${e}/model-providers/${t}`)}async upsertOrganizationModelProviderConnection(e,t,n){return await this.requestJson(\"PUT\",`/v1/organizations/${e}/model-providers/${t}`,n)}async revokeOrganizationModelProviderConnection(e,t,n){return await this.requestJson(\"DELETE\",`/v1/organizations/${e}/model-providers/${t}`,n)}async listOrganizationProviderCustomModels(e,t){return await this.requestJson(\"GET\",`/v1/organizations/${e}/model-providers/${t}/custom-models`)}async createOrganizationProviderCustomModel(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/model-providers/${t}/custom-models`,n)}async deleteOrganizationProviderCustomModel(e,t,n,s){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(n))throw TypeError(\"customModelId must be a UUID\");return await this.requestJson(\"DELETE\",`/v1/organizations/${e}/model-providers/${t}/custom-models/${encodeURIComponent(n)}`,s)}async getWorkspaceModelAccessPolicy(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/model-policy`)}async updateWorkspaceModelAccessPolicy(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/model-policy`,t)}async getWorkspaceRealtimeModelCatalog(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/realtime-model-catalog`,void 0,{},t)}async getAccessContext(){return await this.requestJson(\"GET\",\"/v1/access/me\")}async listOrganizationMemberships(){return await this.requestJson(\"GET\",\"/v1/organization-memberships\")}async listUserResourceAuthorities(e,t){let n=new URLSearchParams({scope:\"user\",resourceKind:t.resourceKind});if(t.cursor)n.set(\"cursor\",t.cursor);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));return await this.requestJson(\"GET\",`/v1/workspaces/${e}/user-resource-authorities?${n.toString()}`)}async revokeUserResourceGrant(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/user-resource-authorities/grants/${t}?scope=user`)}async createOrganization(e){return await this.requestJson(\"POST\",\"/v1/organizations\",e)}async createAdditionalOrganization(e){return await this.requestJson(\"POST\",\"/v1/organizations/additional\",e)}async listOrganizationInvitations(e={}){let t=new URLSearchParams;if(e.cursor)t.set(\"cursor\",e.cursor);if(e.limit!==void 0)t.set(\"limit\",String(e.limit));let n=t.size>0?`?${t.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/organization-invitations${n}`)}async listOrganizationInvitationsForOrganization(e,t={}){let n=new URLSearchParams;if(t.cursor)n.set(\"cursor\",t.cursor);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.size>0?`?${n.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/organizations/${e}/invitations${s}`)}async createOrganizationInvitation(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/invitations`,t)}async acceptOrganizationInvitation(e,t){return await this.requestJson(\"POST\",`/v1/organization-invitations/${e}/accept`,t)}async revokeOrganizationInvitation(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/invitations/${t}/revoke`,n)}async listOrganizationAdministrationMembers(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/members`)}async listOrganizationMembers(e){return await this.listOrganizationAdministrationMembers(e)}async getOrganizationAdministrationOverview(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/overview`)}async createOrganizationWorkspace(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/workspaces`,t)}async updateOrganizationWorkspace(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/workspaces/${t}`,n)}async updateOrganizationWorkspaceSettings(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/workspaces/${t}/settings`,n)}async deleteOrganizationWorkspace(e,t){await this.requestVoid(\"DELETE\",`/v1/organizations/${e}/workspaces/${t}`)}async putOrganizationWorkspaceMember(e,t,n,s){return await this.requestJson(\"PUT\",`/v1/organizations/${e}/workspaces/${t}/members/${n}`,s)}async revokeOrganizationWorkspaceMember(e,t,n,s){return await this.requestJson(\"POST\",`/v1/organizations/${e}/workspaces/${t}/members/${n}/revoke`,s)}async updateOrganizationName(e,t){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}`,t)}async updateOrganizationMember(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/members/${t}`,n)}async getOrganizationRetentionPolicy(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/retention-policy`)}async updateOrganizationRetentionPolicy(e,t){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/retention-policy`,t)}async getOrganizationRecovery(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/recovery`)}async configureOrganizationRecoveryPolicy(e,t){return await this.requestJson(\"PUT\",`/v1/organizations/${e}/recovery/policy`,t)}async acceptOrganizationRecoveryCustody(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/policy/accept`,t)}async disableOrganizationRecoveryPolicy(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/policy/disable`,t)}async startOrganizationRecoveryOperation(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/operations`,t)}async approveOrganizationRecoveryOperation(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/operations/${t}/approve`,n)}async cancelOrganizationRecoveryOperation(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/operations/${t}/cancel`,n)}async executeOrganizationRecoveryOperation(e,t,n){return await this.requestJson(\"POST\",`/v1/organizations/${e}/recovery/operations/${t}/execute`,n)}async searchPublicSkills(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/skills/search?q=${encodeURIComponent(t)}`)}async listWorkspaces(){return await this.requestJson(\"GET\",\"/v1/workspaces\")}connectTransport(){let e=(t)=>`/v1/workspaces/${encodeURIComponent(t)}/connect`;return{catalog:(t,n)=>this.requestJson(\"GET\",`${e(t)}/catalog`,void 0,void 0,n),accounts:(t,n)=>this.requestJson(\"GET\",`${e(t)}/accounts`,void 0,void 0,n),pending:(t,n)=>this.requestJson(\"GET\",`${e(t)}/attempts`,void 0,void 0,n),begin:(t,n,s)=>this.requestJson(\"POST\",`${e(t)}/attempts`,n,void 0,s),get:(t,n,s)=>this.requestJson(\"GET\",`${e(t)}/attempts/${encodeURIComponent(n)}`,void 0,void 0,s),advance:(t,n,s,r)=>this.requestJson(\"POST\",`${e(t)}/attempts/${encodeURIComponent(n)}/advance`,s,void 0,r),cancel:(t,n,s,r)=>this.requestJson(\"POST\",`${e(t)}/attempts/${encodeURIComponent(n)}/cancel`,s,void 0,r),disconnect:async(t,n,s)=>{if(n.startsWith(\"social:\")){let o=n.slice(7);if(!/^[0-9a-f-]{36}$/i.test(o))throw Error(\"Invalid social account ID\");await this.disconnectSocialConnection(t,o);return}if(n.startsWith(\"lens-registration:\")){let o=n.slice(18);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(o))throw Error(\"Invalid Lens registration ID\");await this.requestJson(\"DELETE\",`/v1/workspaces/${encodeURIComponent(t)}/pr-review/registrations/${o}`,void 0,void 0,s);return}if(n.startsWith(\"github-installation:\")){let o=n.slice(20);if(!/^[1-9][0-9]*$/.test(o)||!Number.isSafeInteger(Number(o)))throw Error(\"Invalid GitHub installation ID\");await this.requestJson(\"DELETE\",`/v1/workspaces/${encodeURIComponent(t)}/github/installations/${o}`,void 0,void 0,s);return}let r=s?.expectedVersion;if(r!==void 0&&(!Number.isSafeInteger(r)||r<1))throw Error(\"invalid expected connection version\");let i=r===void 0?\"\":`?expectedVersion=${r}`;await this.requestJson(\"DELETE\",`/v1/workspaces/${encodeURIComponent(t)}/connections/${encodeURIComponent(n)}${i}`,void 0,void 0,s)}}}async browseAtlassianSources(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/atlassian/${t}/browse`)}async saveAtlassianSources(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/atlassian/${t}/source`,n)}async setAtlassianLifecycle(e,t,n){return this.requestJson(\"PATCH\",`/v1/workspaces/${e}/connections/atlassian/${t}/lifecycle`,n)}async beginConnect(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/connect/attempts`,t)}async createWorkspace(e){return await this.requestJson(\"POST\",\"/v1/workspaces\",e)}async ensureWorkspace(e){return await this.requestJson(\"PUT\",\"/v1/workspaces/external\",e)}async getWorkspace(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}`)}async getWorkspaceState(e,t={}){let n=new URLSearchParams;if(t.attemptId)n.set(\"attemptId\",t.attemptId);let s=n.size>0?`?${n.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${e}/workspace-state${s}`)}async exportWorkspaceState(e,t={}){let n=new URLSearchParams;if(t.attemptId)n.set(\"attemptId\",t.attemptId);let s=n.size>0?`?${n.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${e}/workspace-state/export${s}`)}async updateWorkspace(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}`,t)}async listWorkspaceInstructionPolicies(e,t={}){let n=new URLSearchParams;if(t.kind!==void 0)n.set(\"kind\",t.kind);if(t.scope!==void 0)n.set(\"scope\",t.scope);if(t.roleKey!==void 0)n.set(\"roleKey\",t.roleKey);if(t.afterRevision!==void 0)n.set(\"afterRevision\",String(t.afterRevision));if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/instruction-policies${s?`?${s}`:\"\"}`)}async getWorkspaceLearningHistory(e,t={}){let n=new URLSearchParams;if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/learning${s?`?${s}`:\"\"}`)}async undoGovernedLearningActivation(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/learning/activations/${encodeURIComponent(t)}/undo`,n)}async getWorkspaceInstructionPolicyRevision(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/instruction-policies/${encodeURIComponent(t)}`)}async createWorkspaceInstructionPolicyDraft(e,t,n={}){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/instruction-policies/drafts`,t,n)}async listWorkspaceInstructionPolicyOnboardingProposals(e,t={}){let n=new URLSearchParams;if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/instruction-policies/onboarding-proposals${s?`?${s}`:\"\"}`)}async createWorkspaceInstructionPolicyOnboardingProposal(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/instruction-policies/onboarding-proposals`,t)}async importLegacyWorkspaceInstructionPolicyDraft(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/instruction-policies/import-legacy`,t)}async diffWorkspaceInstructionPolicyRevisions(e,t){let n=new URLSearchParams({fromRevisionId:t.fromRevisionId,toRevisionId:t.toRevisionId});return await this.requestJson(\"GET\",`/v1/workspaces/${e}/instruction-policies/diff?${n}`)}async activateWorkspaceInstructionPolicyRevision(e,t,n,s={}){return await this.requestSessionCommand(\"POST\",`/v1/workspaces/${e}/instruction-policies/${encodeURIComponent(t)}/activate`,n,s)}async rollbackWorkspaceInstructionPolicyRevision(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/instruction-policies/rollback`,t)}async listCompanyProfile(e,t={}){let n=new URLSearchParams;if(t.afterRevision!==void 0)n.set(\"afterRevision\",String(t.afterRevision));if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/company-profile${s?`?${s}`:\"\"}`)}async getCompanyProfileRevision(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/company-profile/revisions/${encodeURIComponent(t)}`)}async getCompanyProfileAgentPolicy(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/company-profile/agent-policy`)}async updateCompanyProfileAgentPolicy(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/company-profile/agent-policy`,t)}async updateCompanyProfile(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/company-profile`,t)}async diffCompanyProfileRevisions(e,t){let n=new URLSearchParams(t);return await this.requestJson(\"GET\",`/v1/workspaces/${e}/company-profile/diff?${n}`)}async activateCompanyProfileRevision(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/company-profile/revisions/${encodeURIComponent(t)}/activate`,n)}async rollbackCompanyProfile(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/company-profile/rollback`,t)}async listPreferenceRegistry(e,t={}){let n=new URLSearchParams;if(t.scope)n.set(\"scope\",t.scope);if(t.status)n.set(\"status\",t.status);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));let s=n.toString();return await this.requestJson(\"GET\",`/v1/workspaces/${e}/preferences${s?`?${s}`:\"\"}`)}async getPreferenceRegistry(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}`)}async createPreferenceRegistryProposal(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/proposals`,t)}async activatePreferenceRegistryRevision(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/activate`,n)}async correctPreferenceRegistry(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/correct`,n)}async changePreferenceRegistryScope(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/scope`,n)}async deactivatePreferenceRegistry(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/deactivate`,n)}async supersedePreferenceRegistry(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/supersede`,n)}async rejectPreferenceRegistryProposal(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/${encodeURIComponent(t)}/reject`,n)}async getPreferenceRegistrySummary(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/preferences/summary`)}async getPreferenceRegistryFullContent(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/preferences/full-content`,{retrievalHandle:t})}async deleteWorkspace(e){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}`)}async listWorkspaceMembers(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/members`)).members}async listWorkspaceMemberCandidates(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/member-candidates`)).members}async addWorkspaceMember(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/members`,t)}async updateWorkspaceMember(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/members/${encodeURIComponent(t)}`,n)}async removeWorkspaceMember(e,t){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/members/${encodeURIComponent(t)}`)}async prepareSlackUserLinkAccess(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/slack/user-link-intents`,t)}async getSlackUserLinkAccess(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/slack/user-link-intents/${t}`)}async requestSlackUserLinkWorkspaceAccess(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/slack/user-link-intents/${t}/request-access`,n)}async cancelSlackUserLinkAccess(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/slack/user-link-intents/${t}/cancel`,n)}async listSlackUserLinkAccessRequests(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/members/access-requests/slack`)).requests}async approveSlackUserLinkAccessRequest(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/members/access-requests/slack/${t}/approve`,n)}async denySlackUserLinkAccessRequest(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/members/access-requests/slack/${t}/deny`,n)}async createScheduledTask(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/scheduled-tasks`,bt(t))}async updateScheduledTask(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/scheduled-tasks/${t}`,bt(n))}async pauseScheduledTask(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/scheduled-tasks/${t}/pause`)}async resumeScheduledTask(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/scheduled-tasks/${t}/resume`)}async triggerScheduledTask(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/scheduled-tasks/${t}/trigger`,n.triggerId?{triggerId:n.triggerId}:void 0)}async deleteScheduledTask(e,t){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/scheduled-tasks/${t}`)}async listScheduledTaskRuns(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/scheduled-tasks/${t}/runs`,void 0,{...n.limit!==void 0?{limit:String(n.limit)}:{}})}async listVariableSets(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/variable-sets`)}async resolveVariableSetAttachments(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/variable-sets/resolve-attachments`,t)}async createVariableSet(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/variable-sets`,t)}async getVariableSet(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/variable-sets/${t}`)}async getVariableSetVariable(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/variable-sets/${t}/variables/${encodeURIComponent(n)}`)}async updateVariableSet(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/variable-sets/${t}`,n)}async deleteVariableSet(e,t){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/variable-sets/${t}`)}async setVariableSetVariable(e,t,n,s){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/variable-sets/${t}/variables/${encodeURIComponent(n)}`,{value:s})}async deleteVariableSetVariable(e,t,n){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/variable-sets/${t}/variables/${encodeURIComponent(n)}`)}async listChannels(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/channels`)}async createChannel(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/channels`,t)}async updateChannel(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/channels/${t}`,n)}async reorderChannels(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/channels/order`,t)}async deleteChannel(e,t){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/channels/${t}`)}async updateSessionChannel(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/sessions/${t}/channel`,n)}async listRigs(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs`)}async createRig(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs`,t)}async getRig(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs/${t}`)}async updateRig(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/rigs/${t}`,n)}async deleteRig(e,t){await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/rigs/${t}`)}async listRigVersions(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs/${t}/versions`)}async activateRigVersion(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/versions/${n}/activate`)}async listRigChanges(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs/${t}/changes`)}async proposeRigChange(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/changes`,n)}async getRigChange(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/rigs/${t}/changes/${n}`)}async verifyRigChange(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/changes/${n}/verify`)}async promoteRigChange(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/changes/${n}/promote`)}async verifyRig(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/rigs/${t}/verify`)}async listEnvironments(e){return await this.listVariableSets(e)}async createEnvironment(e,t){return await this.createVariableSet(e,t)}async getEnvironment(e,t){return await this.getVariableSet(e,t)}async updateEnvironment(e,t,n){return await this.updateVariableSet(e,t,n)}async deleteEnvironment(e,t){await this.deleteVariableSet(e,t)}async setEnvironmentVariable(e,t,n,s){return await this.setVariableSetVariable(e,t,n,s)}async deleteEnvironmentVariable(e,t,n){await this.deleteVariableSetVariable(e,t,n)}async beginFileUpload(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/files/uploads`,t,{},n)}async completeFileUpload(e,t,n={}){return(await this.requestJson(\"POST\",`/v1/workspaces/${e}/files/uploads/${t}/complete`,void 0,{},n)).file}async uploadFile(e,t){if(t.timeoutMs!==void 0&&(!Number.isFinite(t.timeoutMs)||t.timeoutMs<=0))throw Error(\"File upload timeout must be a positive number\");mn();let n=async(l,d)=>{let p=new AbortController,u,m=new Promise((b,y)=>{u=setTimeout(()=>{p.abort(),y(Error(\"File upload timed out. Retry the upload.\"))},l)});try{return await Promise.race([d(p.signal),m])}finally{if(u!==void 0)clearTimeout(u)}},s=t.data instanceof Uint8Array?new Blob([t.data.slice()]):t.data instanceof ArrayBuffer?t.data.slice(0):t.data,r=typeof s===\"string\"?new TextEncoder().encode(s).byteLength:s instanceof Blob?s.size:s.byteLength,i=t.sha256??await yn(s),o=await n(30000,async(l)=>await this.beginFileUpload(e,{filename:t.filename,contentType:t.contentType,...t.scope?{scope:t.scope}:{},sizeBytes:r,sha256:i},{signal:l})),a=t.timeoutMs??Math.max(120000,Math.ceil(r/262144)*1000),c=await n(a,async(l)=>await this.fetchImpl(o.putUrl,{method:\"PUT\",credentials:\"omit\",headers:{...o.requiredHeaders},body:s,signal:l}));if(!c.ok)throw await S(c,{method:\"PUT\"});return await n(30000,async(l)=>await this.completeFileUpload(e,o.uploadId,{signal:l}))}async listFiles(e,t={}){let n=new URLSearchParams;if(t.scope)n.set(\"scope\",t.scope);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));if(t.cursor)n.set(\"cursor\",t.cursor);return this.requestJson(\"GET\",`/v1/workspaces/${e}/files${n.size?`?${n}`:\"\"}`)}async getFile(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/files/${t}${n.sessionId?`?sessionId=${encodeURIComponent(n.sessionId)}`:\"\"}`,void 0,{},n)}async getRetainedArtifact(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/artifacts/${t}`)}async getRetainedArtifactContent(e,t,n={}){return await this.getRetainedArtifactContentAtPath(`/v1/workspaces/${e}/artifacts/${t}/content`,n)}async getSessionRetainedArtifact(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/artifacts/${n}`)}async getSessionRetainedArtifactContent(e,t,n,s={}){return await this.getRetainedArtifactContentAtPath(`/v1/workspaces/${e}/sessions/${t}/artifacts/${n}/content`,s)}async downloadRetainedArtifact(e,t,n={}){vt(e,t);let s=await this.downloadRetainedArtifactBytes(t,n);return{artifact:t,bytes:s}}async createRetainedArtifactDownloadUrl(e,t,n={}){vt(e,t);let s=await this.createFileDownloadUrl(e,t.artifactId,n);return It(s),s}async downloadRetainedScreenshot(e,t,n,s={}){let r=await this.getSessionRetainedArtifact(e,t,n);if(!r.available)return{metadata:r,bytes:null};if(!(r.kind===\"computer_screenshot\"&&r.contentType===\"image/png\"||r.kind===\"browser_screenshot\"&&[\"image/png\",\"image/jpeg\",\"image/webp\"].includes(r.contentType))||!r.dimensions||r.originalBytes<=0||r.originalBytes>ot)throw new g(502,\"retained screenshot metadata is invalid\");let o=await this.downloadRetainedArtifactBytes(r,s);return{metadata:r,bytes:o}}async downloadRetainedArtifactBytes(e,t){let n=t.maxRetries??2;if(!Number.isInteger(n)||n<0||n>3)throw RangeError(\"retained artifact maxRetries must be an integer from 0 to 3\");let s=new Uint8Array(e.originalBytes),r=Math.min(e.retrieval.maxRangeBytes,te);if(!Number.isSafeInteger(r)||r<=0)throw new g(502,\"retained artifact range metadata is invalid\");for(let i=0;i<s.byteLength;i+=r){t.signal?.throwIfAborted();let o=Math.min(i+r,s.byteLength)-1,a=null;for(let l=0;l<=n;l+=1)try{a=await this.getRetainedArtifactContentAtPath(e.retrieval.path,{range:`bytes=${i}-${o}`,...t.signal?{signal:t.signal}:{}});break}catch(d){if(t.signal?.throwIfAborted(),l>=n||d instanceof g&&d.status>=400&&d.status<500)throw d}if(!a)throw new g(502,\"retained artifact range retry exhausted\");let c=o-i+1;if(a.status!==206||a.contentType!==e.contentType||a.contentLength!==c||a.contentRange!==`bytes ${i}-${o}/${e.originalBytes}`)throw new g(502,\"retained artifact range response is invalid\");s.set(a.bytes,i)}if(await St(s)!==e.sha256)throw new g(502,\"retained artifact checksum mismatch\");return s}async getRetainedArtifactContentAtPath(e,t){if(t.range&&(t.range.length>128||/[^\\x20-\\x7e]/.test(t.range)))throw RangeError(\"retained artifact range must be at most 128 printable ASCII bytes\");let n=crypto.randomUUID(),s=await this.fetchImpl(this.url(e),{method:\"GET\",headers:{...this.headers(n),Accept:\"application/octet-stream\",...t.range?{Range:t.range}:{}},...t.signal?{signal:t.signal}:{}});try{v(s)}catch(o){throw await k(s,\"retained artifact API contract mismatch\"),o}if(!s.ok)throw await S(s,{method:\"GET\",correlationId:n});if(s.status!==200&&s.status!==206)throw await k(s,\"unexpected retained artifact response status\"),new g(s.status,\"unexpected retained artifact response status\");if(s.headers.get(\"accept-ranges\")!==\"bytes\")throw await k(s,\"retained artifact response omitted byte-range support\"),new g(502,\"retained artifact response omitted byte-range support\");let r;try{r=wn(s.headers.get(\"content-length\"))}catch(o){throw await k(s,\"invalid retained artifact content-length\"),o}let i=await K(s,te,r);return{bytes:i,status:s.status,contentType:s.headers.get(\"content-type\")??\"application/octet-stream\",contentLength:i.byteLength,contentRange:s.headers.get(\"content-range\"),acceptRanges:\"bytes\"}}async createFileDownloadUrl(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/files/${t}/download-url${n.sessionId?`?sessionId=${encodeURIComponent(n.sessionId)}`:\"\"}`,void 0,{},n)}async getVideoGenerationSettings(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/video-generation`,void 0,{},t)}async updateVideoGenerationPolicy(e,t,n={}){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/video-generation/policy`,t,{},n)}async getVideoGenerationOperation(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/video-generation/operations/${t}`,void 0,{},n)}async createVideoArtifactPlaybackSource(e,t,n={}){let s=await this.requestJson(\"POST\",`/v1/workspaces/${e}/artifacts/${t}/playback-source`,void 0,{},n);return fn(s,t),s}async createDocumentBase(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/document-bases`,t)}async getDocumentBase(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/document-bases/${t}`)}async addDocument(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/document-bases/${t}/documents`,n)}async listDocuments(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/document-bases/${t}/documents`)}async getDocumentOriginalFile(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/documents/${t}/original-file`)}async createKnowledgeDrop(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/drops`,t)}async moveDocument(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/documents/${t}/move`,n)}async deleteDocument(e,t,n){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/document-bases/${t}/documents/${n}`)}async listKnowledgeEntries(e,t={}){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/search`,t)}async getKnowledgeEntry(e,t,n={}){let s=new URLSearchParams;if(n.revisionId!==void 0)s.set(\"revisionId\",n.revisionId);if(n.view!==void 0)s.set(\"view\",n.view);let r=s.toString();return this.requestJson(\"GET\",`/v1/workspaces/${e}/knowledge/entries/${t}${r?`?${r}`:\"\"}`)}async createKnowledgeFileDownloadUrl(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/${t}/file/download-url`,n?{revisionId:n}:{})}async saveKnowledgeEntry(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries`,t)}async reviewKnowledgeEntry(e,t){let{entryId:n,...s}=t;return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/${n}/review`,s)}async listKnowledgeReviewBatches(e,t={}){let n=new URLSearchParams;for(let[s,r]of Object.entries(t))if(r!==void 0)n.set(s,String(r));return this.requestJson(\"GET\",`/v1/workspaces/${e}/knowledge/review-groups?${n}`)}async reviewKnowledgeEntries(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/review`,t)}async listKnowledgeEntryHistory(e,t,n){return this.requestJson(\"GET\",`/v1/workspaces/${e}/knowledge/entries/${t}/history${n?`?beforeRevision=${n}`:\"\"}`)}async restoreKnowledgeEntry(e,t){let{entryId:n,...s}=t;return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/${n}/restore`,s)}async archiveKnowledgeEntry(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/knowledge/entries/${t}/archive`,n)}async getAgentLearningSettings(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/agent-learning/read`,{scope:t,source:n})}async saveAgentLearningSettings(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/agent-learning`,t)}async listAgentLearningOverrides(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/agent-learning/overrides?scope=${t}`)}async reviewAgentInstruction(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/agent-learning/instructions/review`,t)}async listAgentInstructionReviews(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/agent-learning/instructions/reviews${t?`?cursor=${encodeURIComponent(t)}`:\"\"}`)}async updateWorkspaceSettings(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/settings`,t)}async setWorkspaceDefaultRig(e,t){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/default-rig`,t)}async listCapabilities(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/capabilities`)}async createCapability(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/capabilities`,t)}async getConnectorToolPermissions(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/capabilities/${encodeURIComponent(t)}/tool-permissions`,void 0,{},n)}async updateConnectorToolPermissions(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/capabilities/${encodeURIComponent(t)}/tool-permissions`,n,{},s)}async enableCapability(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/capabilities/${encodeURIComponent(t)}/enable`,n)}async disableCapability(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/capabilities/${encodeURIComponent(t)}/disable`)}async listArtifactCatalog(e,t={}){let n=new URLSearchParams;for(let r of[\"sourceSessionId\",\"q\",\"kind\",\"sort\",\"status\",\"limit\",\"cursor\"])if(t[r]!==void 0)n.set(r,String(t[r]));let s=n.size?`?${n.toString()}`:\"\";return this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/artifact-catalog${s}`,void 0,void 0,t)}async listWorkspaceArtifacts(e,t={}){let n=new URLSearchParams;if(t.limit!==void 0)n.set(\"limit\",String(t.limit));if(t.cursor)n.set(\"cursor\",t.cursor);if(t.status)n.set(\"status\",t.status);if(t.sourceSessionId)n.set(\"sourceSessionId\",t.sourceSessionId);let s=n.size>0?`?${n.toString()}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts${s}`,void 0,void 0,t)}async getWorkspaceArtifact(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts/${encodeURIComponent(t)}`,void 0,void 0,n)}async getWorkspaceArtifactHtml(e,t,n){return(await this.requestResponse(\"GET\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts/${encodeURIComponent(t)}/html`,{versionId:n.versionId},n)).text()}async rollbackWorkspaceArtifact(e,t,n,s={}){return await this.requestJson(\"POST\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts/${encodeURIComponent(t)}/rollback`,n,void 0,s)}async setWorkspaceArtifactStatus(e,t,n,s={}){return await this.requestJson(\"PATCH\",`/v1/workspaces/${encodeURIComponent(e)}/published-artifacts/${encodeURIComponent(t)}/status`,n,void 0,s)}async discoverMcpCapabilities(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/capabilities/discovery/mcp-registry`,void 0,{...t.query!==void 0?{query:t.query}:{},...t.limit!==void 0?{limit:String(t.limit)}:{}})}async discoverPlugins(e,t={}){return this.requestJson(\"GET\",\"/v1/workspaces/\"+e+\"/capabilities/discovery/plugins\",void 0,{...t.id?{id:t.id}:{},...t.query?{query:t.query}:{},...t.provider?{provider:t.provider}:{},...t.offset!==void 0?{offset:String(t.offset)}:{}})}async inspectMcpAuthentication(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/capabilities/discovery/mcp-auth`,{url:t})}async listApiIntegrations(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations`)}async listIntegrationDefinitions(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/definitions`)}async previewApiIntegration(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/preview`,t)}async startApiIntegrationOAuth(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/oauth/start`,t)}async installApiIntegration(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/install`,t)}async previewApiIntegrationUninstall(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/uninstall-preview`)}async uninstallApiIntegration(e,t,n,s){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}`,s)}async listIntegrationFacets(e,t,n){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets`)}async configureIntegrationFacet(e,t,n,s,r){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}`,r)}async browseGoogleDriveFacetSource(e,t,n,s,r={}){let i=new URLSearchParams;if(r.parentId)i.set(\"parentId\",r.parentId);if(r.pageToken)i.set(\"pageToken\",r.pageToken);let o=i.size>0?`?${i}`:\"\";return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}/browse${o}`)}async saveGoogleDriveFacetSource(e,t,n,s,r){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}/source`,r)}async pauseIntegrationFacet(e,t,n,s,r){return await this.mutateIntegrationFacetLifecycle(e,t,n,s,\"pause\",r)}async resumeIntegrationFacet(e,t,n,s,r){return await this.mutateIntegrationFacetLifecycle(e,t,n,s,\"resume\",r)}async removeIntegrationFacet(e,t,n,s,r){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}`,r)}async mutateIntegrationFacetLifecycle(e,t,n,s,r,i){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/integrations/${encodeURIComponent(t)}/instances/${encodeURIComponent(n)}/facets/${encodeURIComponent(s)}/${r}`,i)}async previewPlugin(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/plugins/preview`,t)}async getInstalledPluginDetails(e,t){return this.requestJson(\"GET\",`/v1/workspaces/${e}/plugins/details`,void 0,{pluginKey:t})}async listInstalledPlugins(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/plugins`)}async installPlugin(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/plugins/install`,t)}async previewPluginUninstall(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/plugins/${encodeURIComponent(t)}/uninstall-preview`)}async uninstallPlugin(e,t,n){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/plugins/${encodeURIComponent(t)}`,n)}async previewSkillImport(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/preview`,t)}async installSkill(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/install`,t)}async listInstalledSkills(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/skills`)}async listWorkspaceSkills(e,t={}){let n=new URLSearchParams;if(t.cursor!==void 0)n.set(\"cursor\",t.cursor);if(t.limit!==void 0)n.set(\"limit\",String(t.limit));if(t.sessionId!==void 0)n.set(\"sessionId\",t.sessionId);let s=n.size?`?${n.toString()}`:\"\";return this.requestJson(\"GET\",`/v1/workspaces/${e}/skills/content${s}`)}async readWorkspaceSkill(e,t,n){let s=n?`?revisionId=${encodeURIComponent(n)}`:\"\";return this.requestJson(\"GET\",`/v1/workspaces/${e}/skills/content/${encodeURIComponent(t)}${s}`)}async saveWorkspaceSkill(e,t){return this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/content/save`,t)}async approveWorkspaceSkill(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/content/${encodeURIComponent(t)}/approve`,n)}async restoreWorkspaceSkill(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/content/${encodeURIComponent(t)}/restore`,n)}async rejectWorkspaceSkill(e,t,n){return this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/content/${encodeURIComponent(t)}/reject`,n)}async installLibrarySkill(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/skills/library/${encodeURIComponent(t)}/install`,n)}async previewSkillUninstall(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/skills/${encodeURIComponent(t)}/uninstall-preview`)}async uninstallSkill(e,t,n){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/skills/${encodeURIComponent(t)}`,n)}async listOwnConnectionAccounts(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/accounts`)).connections}async listConnections(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections`)).connections}async personalGitHubStatus(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/github`)}async startPersonalGitHubOAuth(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/github/oauth/start`,t)}async reconnectPersonalGitHub(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/${t}/github/reconnect`,n)}async disconnectPersonalGitHub(e,t,n){return(await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/connections/${t}`,n)).connection}async listPersonalGitHubRepositories(e,t,n={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/${t}/github/repositories`,void 0,{...n.cursor!==void 0?{cursor:String(n.cursor)}:{},...n.limit!==void 0?{limit:String(n.limit)}:{}})}async replacePersonalGitHubRepositorySelections(e,t,n){return await this.requestJson(\"PUT\",`/v1/workspaces/${e}/connections/${t}/github/repositories`,n)}async verifyPersonalGitHubRepositorySelections(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/${t}/github/repositories/verify`,n)}async listSlackInstallationBindings(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/connections/slack-bot/bindings`)).bindings}async createConnection(e,t){return(await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections`,t)).connection}async installFikenConnection(e,t){return(await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/fiken/install`,t)).connection}async startFikenOAuth(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/fiken/oauth/start`,t)}async startOpenGeniSlackBotInstall(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/slack-bot/install`,t)}async listOpenGeniSlackReactionChannels(e,t,n){let s=new URLSearchParams({connectionId:t});if(n)s.set(\"cursor\",n);return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/slack/reaction-channels?${s}`)}async listOpenGeniSlackChannelRoutes(e,t){let n=new URLSearchParams({connectionId:t});return await this.requestJson(\"GET\",`/v1/workspaces/${e}/integrations/slack/channel-routes?${n}`)}async updateOpenGeniSlackChannelRoutes(e,t){await this.requestJson(\"PUT\",`/v1/workspaces/${e}/integrations/slack/channel-routes`,t)}async updateConnection(e,t,n){return(await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/connections/${t}`,n)).connection}async deleteConnection(e,t){return(await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/connections/${t}`)).connection}async disconnectGoogleDriveConnection(e,t,n){return(await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/connections/${t}`,n)).connection}async transitionGoogleDriveLifecycle(e,t,n){return(await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/connections/google-drive/${t}/lifecycle`,n)).connection}async startConnectionOAuth(e,t,n={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/connections/oauth/start`,t,{},n)}async startSocialOAuth(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/social/oauth/start`,t)}async listSocialConnections(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/social/connections`)}async disconnectSocialConnection(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/social/connections/${t}`)}catalogAssetUrl(e){return e?`${this.baseUrl}/v1/${e}`:null}async downloadCatalogAsset(e,t={}){if(!/^catalog-assets\\/[a-zA-Z0-9_./-]+$/.test(e)||e.split(\"/\").some((i)=>!i||i===\".\"||i===\"..\"))throw TypeError(\"A catalog asset path is required\");let n=await this.requestResponse(\"GET\",`/v1/${e}`,{},t),s=n.headers.get(\"content-type\")?.split(\";\")[0]??\"\";if(!s.startsWith(\"image/\"))throw await n.body?.cancel(),Error(\"The catalog asset is not an image\");let r=await K(n,2000000,null);return new Blob([Uint8Array.from(r)],{type:s})}async getGitHubApp(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/github/app`,void 0,t.returnPath?{returnPath:t.returnPath}:void 0)}githubConnectUrl(e,t){return this.url(`/v1/workspaces/${e}/github/connect`,{state:t})}async listGitHubRepositories(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/github/repositories`)}async getGitHubActionPolicies(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/github/action-policies`)}async updateGitHubActionPolicy(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/github/action-policies`,t)}async syncGitHubRepositories(e){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/github/repositories/sync`)}async unlinkGitHubInstallation(e,t){await this.requestVoid(\"DELETE\",`/v1/workspaces/${e}/github/installations/${t}`)}async createGitHubAppManifest(e,t={}){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/github/app-manifest`,t)}async listApiKeys(e){return(await this.requestJson(\"GET\",`/v1/workspaces/${e}/api-keys`)).apiKeys}async createApiKey(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/api-keys`,t)}async deleteApiKey(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/api-keys/${t}`)}async listOrganizationApiKeys(e){return(await this.requestJson(\"GET\",`/v1/organizations/${e}/api-keys`)).apiKeys}async createOrganizationApiKey(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/api-keys`,t)}async deleteOrganizationApiKey(e,t){return await this.requestJson(\"DELETE\",`/v1/organizations/${e}/api-keys/${t}`)}async listOrganizationSessions(e,t={}){return await this.requestJson(\"GET\",`/v1/organizations/${e}/sessions`,void 0,{...t.limit===void 0?{}:{limit:String(t.limit)},...t.cursor===void 0?{}:{cursor:t.cursor},...t.scopeSubjectId?{scopeSubjectId:t.scopeSubjectId}:{},...t.status===void 0?{}:{status:t.status}},{signal:t.signal})}async*iterateOrganizationSessions(e,t={}){let n;do{let s=await this.listOrganizationSessions(e,{...t,...n===void 0?{}:{cursor:n}});for(let r of s.sessions)yield r;n=s.nextCursor??void 0}while(n!==void 0)}async getBilling(e={}){return await this.requestJson(\"GET\",\"/v1/billing\",void 0,{...e.accountId!==void 0?{accountId:e.accountId}:{}})}async getOrganizationUsageSummary(e,t={}){return await this.requestJson(\"GET\",\"/v1/billing/usage-summary\",void 0,{accountId:e.accountId,period:e.period??\"month\"},t)}async getOrganizationUsageWorkspacePage(e,t={}){return await this.requestJson(\"GET\",\"/v1/billing/usage-workspaces\",void 0,{accountId:e.accountId,period:e.period??\"month\",until:e.until,...e.afterWorkspaceId?{afterWorkspaceId:e.afterWorkspaceId}:{}},t)}async getBillingUsage(e={}){return await this.requestJson(\"GET\",\"/v1/billing/usage\",void 0,{...e.accountId!==void 0?{accountId:e.accountId}:{},...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}})}async getWorkspaceInsights(e,t={}){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/insights`,void 0,{range:t.range??\"week\",...t.provider!==void 0?{provider:t.provider}:{},...t.model!==void 0?{model:t.model}:{}},{signal:t.signal})}async getBillingEntitlements(e={}){return await this.requestJson(\"GET\",\"/v1/billing/entitlements\",void 0,{...e.accountId!==void 0?{accountId:e.accountId}:{}})}async createBillingCheckout(e){return await this.requestJson(\"POST\",\"/v1/billing/checkout\",e)}async createBillingPortalSession(e={}){return await this.requestJson(\"POST\",\"/v1/billing/portal\",e)}headers(e){let t=typeof this.options.headers===\"function\"?this.options.headers():this.options.headers,n={...this.options.apiKey?{Authorization:`Bearer ${this.options.apiKey}`}:{},...t,[de]:U,...e?{[ee]:e}:{}};if(this.externalActorHeader){for(let s of Object.keys(n))if(s.toLowerCase()===\"x-opengeni-external-actor\")delete n[s];n[\"x-opengeni-external-actor\"]=this.externalActorHeader}return n}url(e,t={}){let n=new URLSearchParams(t).toString();return`${this.baseUrl}${e}${n?`?${n}`:\"\"}`}async codexStatus(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/status`)}async codexConnectStart(e){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/connect/start`)}async codexConnectPoll(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/connect/poll`,{state:t})}async codexUsage(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/usage`)}async codexAccountUsage(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/accounts/${t}/usage`)}async refreshCodexUsage(e){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/usage/refresh`)}async codexOverview(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/overview`)}async codexDisconnect(e){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/codex`)}async listCodexAccounts(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/codex/accounts`)}async listSessionCodexAccounts(e,t){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/sessions/${t}/codex-accounts`)}async activateCodexAccount(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/accounts/${t}/activate`)}async designateCodexAppsAccount(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/codex/apps`,{accountId:t,expectedVersion:n})}async clearCodexAppsAccount(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/codex/apps`,{expectedVersion:t})}async setCodexRotationSettings(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/codex/settings`,t)}async setCodexAccountAllocator(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/codex/accounts/${t}/allocator`,n)}async disconnectCodexAccount(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/codex/accounts/${t}`)}async renameCodexAccount(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/codex/accounts/${t}`,{label:n})}async pinSessionCodexAccount(e,t,n){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/sessions/${t}/codex-account`,{target:n})}async getModelConnectionAccess(e){return await this.requestJson(\"GET\",`/v1/${e.scope}/${encodeURIComponent(e.scopeId)}/model-connections/${e.kind}/${encodeURIComponent(e.connectionId)}/access`)}async updateModelConnectionAccess(e,t){return await this.requestJson(\"PUT\",`/v1/${e.scope}/${encodeURIComponent(e.scopeId)}/model-connections/${e.kind}/${encodeURIComponent(e.connectionId)}/access`,t)}async listOrganizationSuperGrokAccounts(e){return await this.requestJson(\"GET\",`/v1/organizations/${e}/supergrok/accounts`)}async organizationSupergrokConnectStart(e){return await this.requestJson(\"POST\",`/v1/organizations/${e}/supergrok/connect/start`,{})}async organizationSupergrokConnectPoll(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/supergrok/connect/poll`,{state:t})}async activateOrganizationSuperGrokAccount(e,t){return await this.requestJson(\"POST\",`/v1/organizations/${e}/supergrok/accounts/${t}/activate`,{})}async setOrganizationSuperGrokRotationSettings(e,t){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/supergrok/settings`,t)}async setOrganizationSuperGrokAccountAllocator(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/supergrok/accounts/${t}/allocator`,n)}async renameOrganizationSuperGrokAccount(e,t,n){return await this.requestJson(\"PATCH\",`/v1/organizations/${e}/supergrok/accounts/${t}`,{label:n})}async disconnectOrganizationSuperGrokAccount(e,t){return await this.requestJson(\"DELETE\",`/v1/organizations/${e}/supergrok/accounts/${t}`,{})}async supergrokStatus(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/supergrok/status`)}async supergrokConnectStart(e,t=\"workspace\"){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/supergrok/connect/start`,{scope:t})}async supergrokConnectPoll(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/supergrok/connect/poll`,{state:t})}async listSuperGrokAccounts(e){return await this.requestJson(\"GET\",`/v1/workspaces/${e}/supergrok/accounts`)}async activateSuperGrokAccount(e,t){return await this.requestJson(\"POST\",`/v1/workspaces/${e}/supergrok/accounts/${t}/activate`,{})}async setSuperGrokRotationSettings(e,t){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/supergrok/settings`,t)}async setSuperGrokAccountAllocator(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/supergrok/accounts/${t}/allocator`,n)}async renameSuperGrokAccount(e,t,n){return await this.requestJson(\"PATCH\",`/v1/workspaces/${e}/supergrok/accounts/${t}`,{label:n})}async disconnectSuperGrokAccount(e,t){return await this.requestJson(\"DELETE\",`/v1/workspaces/${e}/supergrok/accounts/${t}`,{})}async requestSessionCommand(e,t,n,s={}){return await this.requestJson(e,t,n,{},{signal:s.signal,timeoutMs:s.timeoutMs??this.sessionCommandTimeoutMs})}async requestJson(e,t,n,s={},r={}){let i=crypto.randomUUID(),o=pn(r);try{if(o.signal?.aborted)throw o.signal.reason??new DOMException(\"Request aborted\",\"AbortError\");let a;try{a=await V(this.fetchImpl(this.url(t,s),{method:e,headers:{...this.headers(i),Accept:\"application/json\",...n!==void 0?{\"Content-Type\":\"application/json\"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{},...o.signal?{signal:o.signal}:{}}),o.signal)}catch(c){if(r.signal?.aborted)throw c;if(L(e))throw D(i);throw c}v(a);try{if(!a.ok)throw await V(S(a,{method:e,correlationId:i}),o.signal);return await V(N(a,{method:e,correlationId:i}),o.signal),await V(a.json(),o.signal)}catch(c){if(r.signal?.aborted)throw c;if(c instanceof g)throw c;if(L(e))throw D(i);throw c}}finally{o.dispose()}}async requestResponse(e,t,n={},s={}){let r=crypto.randomUUID(),i;try{i=await this.fetchImpl(this.url(t,n),{method:e,headers:{...this.headers(r),Accept:\"application/octet-stream\"},...s.signal?{signal:s.signal}:{}})}catch(o){if(L(e))throw D(r);throw o}if(v(i),!i.ok)throw await S(i,{method:e,correlationId:r});return i}async requestVoid(e,t,n){let s=crypto.randomUUID(),r;try{r=await this.fetchImpl(this.url(t),{method:e,headers:{...this.headers(s),Accept:\"application/json\",...n!==void 0?{\"Content-Type\":\"application/json\"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}})}catch(i){if(L(e))throw D(s);throw i}if(v(r),!r.ok)throw await S(r,{method:e,correlationId:s})}}function v(e){let t=e.headers.get(de);if(t&&t!==U)throw new j(U,t)}function cn(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return!1;let t=e;return typeof t.text===\"string\"&&Array.isArray(t.languages)&&t.languages.every((n)=>typeof n===\"string\")}function un(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return!1;let t=e;if(!pe({recording:t.recording,segments:[]}))return!1;if(!t.chunk||typeof t.chunk!==\"object\"||Array.isArray(t.chunk))return!1;let n=t.chunk;return typeof n.chunkNumber===\"number\"&&typeof n.byteLength===\"number\"&&typeof n.sha256===\"string\"&&typeof n.startMilliseconds===\"number\"&&typeof n.durationMilliseconds===\"number\"&&typeof n.deduplicated===\"boolean\"}function pe(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return!1;let t=e;if(!t.recording||typeof t.recording!==\"object\"||Array.isArray(t.recording))return!1;let n=t.recording;return typeof n.id===\"string\"&&typeof n.workspaceId===\"string\"&&typeof n.mimeType===\"string\"&&typeof n.state===\"string\"&&typeof n.nextChunkNumber===\"number\"&&typeof n.chunkCount===\"number\"&&typeof n.totalBytes===\"number\"&&typeof n.totalDurationMilliseconds===\"number\"&&typeof n.segmentCount===\"number\"&&typeof n.completedSegmentCount===\"number\"&&(n.transcriptText===null||typeof n.transcriptText===\"string\")&&Array.isArray(n.languages)&&(n.errorCode===null||typeof n.errorCode===\"string\")&&typeof n.retryable===\"boolean\"&&typeof n.objectsCleaned===\"boolean\"&&typeof n.createdAt===\"string\"&&typeof n.updatedAt===\"string\"&&typeof n.expiresAt===\"string\"&&(t.retryAfterMilliseconds===void 0||typeof t.retryAfterMilliseconds===\"number\"&&Number.isInteger(t.retryAfterMilliseconds)&&t.retryAfterMilliseconds>0&&t.retryAfterMilliseconds<=60000)&&Array.isArray(t.segments)}function J(e){if(pe(e))return e;throw new g(502,\"Invalid transcription recording response.\",{code:\"invalid_response\"})}function dn(e){if(!e||typeof e!==\"object\"||Array.isArray(e))return!1;let t=e.recordings;return Array.isArray(t)&&t.length<=50&&t.every((n)=>pe({recording:n,segments:[]}))}function ln(e){switch(e.trim().toLowerCase().split(\";\")[0]??\"audio/webm\"){case\"audio/mp4\":case\"audio/m4a\":return\"audio.mp4\";case\"audio/ogg\":return\"audio.ogg\";case\"audio/mpeg\":case\"audio/mp3\":return\"audio.mp3\";case\"audio/wav\":case\"audio/x-wav\":return\"audio.wav\";case\"audio/webm\":default:return\"audio.webm\"}}var ht=16384;function pn(e){let t=e.timeoutMs??0;if(t<=0)return{signal:e.signal,dispose:()=>{return}};let n=new AbortController,s=()=>n.abort(e.signal?.reason);if(e.signal?.aborted)s();else e.signal?.addEventListener(\"abort\",s,{once:!0});let r=setTimeout(()=>n.abort(new DOMException(\"Request timed out\",\"TimeoutError\")),t);return{signal:n.signal,dispose:()=>{clearTimeout(r),e.signal?.removeEventListener(\"abort\",s)}}}async function V(e,t){if(!t)return await e;if(t.aborted)throw t.reason??new DOMException(\"Request aborted\",\"AbortError\");return await new Promise((n,s)=>{let r=()=>{i(),s(t.reason??new DOMException(\"Request aborted\",\"AbortError\"))},i=()=>t.removeEventListener(\"abort\",r);t.addEventListener(\"abort\",r,{once:!0}),e.then((o)=>{i(),n(o)},(o)=>{i(),s(o)})})}async function S(e,t){return new g(e.status,await gn(e),{correlationId:e.headers.get(ee)??t.correlationId,mutation:L(t.method)})}async function N(e,t){if(kt(e.headers.get(\"content-type\")))return;throw await k(e,\"unexpected non-JSON API response\"),new g(502,\"\",{code:\"upstream_unavailable\",retryable:!0,correlationId:e.headers.get(ee)??t.correlationId,outcomeUnknown:L(t.method),displayMessage:\"OpenGeni is temporarily unavailable \u2014 retry.\"})}async function gn(e){if(!kt(e.headers.get(\"content-type\")))return await k(e,\"discarding API error body\"),\"\";if(Number(e.headers.get(\"content-length\"))>ht)return await k(e,\"discarding API error body\"),\"\";try{return new TextDecoder().decode(await K(e,ht,null))}catch{return\"\"}}function kt(e){return/^(application\\/json|[^;]+\\+json)\\s*(;|$)/i.test(e??\"\")}function L(e){return e!==\"GET\"&&e!==\"HEAD\"&&e!==\"OPTIONS\"}function D(e){return new g(0,\"\",{code:\"network_error\",retryable:!0,correlationId:e,outcomeUnknown:!0,mutation:!0,displayMessage:\"OpenGeni could not confirm the request \u2014 reconcile before retrying.\"})}function mn(){let e=typeof window<\"u\"?window.isSecureContext:typeof globalThis.isSecureContext===\"boolean\"?globalThis.isSecureContext:void 0;if(e===void 0)return;if(!e)throw new H(\"insecure_context\");if(typeof globalThis.crypto>\"u\"||typeof globalThis.crypto.subtle?.digest!==\"function\")throw new H(\"web_crypto_unavailable\")}async function yn(e){let t=typeof e===\"string\"?new TextEncoder().encode(e):e instanceof Blob?new Uint8Array(await e.arrayBuffer()):new Uint8Array(e),n=await globalThis.crypto.subtle.digest(\"SHA-256\",t);return[...new Uint8Array(n)].map((s)=>s.toString(16).padStart(2,\"0\")).join(\"\")}async function St(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest(\"SHA-256\",t.buffer);return[...new Uint8Array(n)].map((s)=>s.toString(16).padStart(2,\"0\")).join(\"\")}function Rn(e,t){if(e.computerSessionId!==t.computerSessionId)return\"frame_session_mismatch\";if(e.targetId!==t.targetId)return\"frame_target_mismatch\";if(e.mediaType!==t.mediaType)return\"frame_media_mismatch\";if(e.sha256!==t.sha256)return\"frame_digest_mismatch\";return null}async function k(e,t){await e.body?.cancel(t).catch(()=>{return})}function vt(e,t){if(!pt(t,e)&&!lt(t,e))throw new g(502,\"retained workspace artifact receipt is invalid\")}function It(e){if(!e||typeof e.url!==\"string\"||typeof e.expiresAt!==\"string\"||!Number.isFinite(Date.parse(e.expiresAt)))throw new g(502,\"retained artifact download URL is invalid\");let t;try{t=new URL(e.url)}catch{throw new g(502,\"retained artifact download URL is invalid\")}if(![\"http:\",\"https:\"].includes(t.protocol)||t.username||t.password)throw new g(502,\"retained artifact download URL is unsafe\")}function fn(e,t){if(!e||e.schemaVersion!==1||e.artifactId!==t||e.contentType!==\"video/mp4\"||e.acceptRanges!==\"bytes\"||!Number.isSafeInteger(e.sizeBytes)||e.sizeBytes<=0||e.sizeBytes>at||!/^[0-9a-f]{64}$/.test(e.sha256))throw new g(502,\"generated-video playback source is invalid\");It({url:e.url,expiresAt:e.expiresAt})}function wn(e){if(e===null)return null;if(!/^\\d+$/.test(e))throw new g(502,\"invalid retained artifact content-length\");let t=Number(e);if(!Number.isSafeInteger(t)||t>te)throw new g(502,\"retained artifact response exceeds the SDK byte limit\");return t}async function K(e,t,n){if(!e.body){if(n!==null&&n!==0)throw new g(502,\"retained artifact response length mismatch\");return new Uint8Array}let s=e.body.getReader(),r=[],i=0;try{while(!0){let{done:c,value:l}=await s.read();if(c)break;if(i+=l.byteLength,i>t)throw await s.cancel(\"retained artifact response exceeded the SDK byte limit\").catch(()=>{return}),new g(502,\"retained artifact response exceeds the SDK byte limit\");r.push(l)}}finally{s.releaseLock()}if(n!==null&&i!==n)throw new g(502,\"retained artifact response length mismatch\");let o=new Uint8Array(i),a=0;for(let c of r)o.set(c,a),a+=c.byteLength;return o}var W=2,bn=\"opengeni.site.connect\",xt=\"opengeni.site.ready\",hn=\"opengeni.site.request\",Sn=\"opengeni.site.response\",vn=\"opengeni.site.cancel\",At=\"__opengeniSiteBridgeBootstrapV2\",kn=\"/__opengeni/site-tools\";class I extends Error{code;retryable;outcomeUnknown;constructor(e,t,n=!1,s=!1){super(t);this.code=e;this.retryable=n;this.outcomeUnknown=s;this.name=\"OpenGeniSiteBridgeError\"}}function qt(e={}){let t=In(e)?new Ot(e):new Tt(e);return{client:new le({baseUrl:\"https://site.opengeni.invalid\",fetch:(n,s)=>t.fetch(n,s)}),workspaceId:X,tools:new Z(t).forWorkspace(\"site-host\"),close:()=>t.close()}}class Ot{fetchImpl;basePath;constructor(e){this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis);let t=e.localCodemodePath;this.basePath=(typeof t===\"string\"?t:kn).replace(/\\/+$/u,\"\")}close(){}async fetch(e,t){let n=new Request(e,t),s=new URL(n.url),r=`${s.pathname}${s.search}`;return z(r,X,n.method),this.fetchImpl(`${this.basePath}/sdk${r}`,{method:n.method,headers:n.headers,signal:n.signal,...n.body?{body:await n.text()}:{}})}async requestJson(e,t,n,s,r={}){let i=Cn(e,t),o=await this.fetchImpl(`${this.basePath}${i}`,{method:e,...r.signal?{signal:r.signal}:{},...n===void 0?{}:{headers:{\"content-type\":\"application/json\"},body:JSON.stringify(n)}}),a=await o.json();if(o.ok)return a;let c=T(a)&&T(a.error)?a.error:{};throw new I(typeof c.code===\"string\"?c.code:\"local_codemode_error\",typeof c.message===\"string\"?c.message:`Local Site tool request failed with HTTP ${o.status}`,c.retryable===!0,c.outcomeUnknown===!0)}}function In(e){if(e.localCodemodePath===!1||e.bootstrapPort)return!1;if(typeof e.localCodemodePath===\"string\")return!0;let t=e.siteWindow??globalThis.window;return Boolean(t&&t.parent===t)}function Cn(e,t){if(e===\"GET\"&&t.endsWith(\"/tools/catalog\"))return\"/catalog\";if(e===\"GET\"&&t.endsWith(\"/tools/declarations\"))return\"/declarations\";if(e===\"POST\"&&t.endsWith(\"/tools/calls\"))return\"/calls\";throw new I(\"unsupported_request\",\"Unsupported Site tool request\")}function Pn(e){return{...e.operationId===void 0?{}:{operationId:e.operationId},catalogDigest:e.catalogDigest,identity:e.identity,arguments:e.arguments}}class Tt{options;bootstrap;port=null;connecting=null;closed=!1;constructor(e){this.options=e,this.bootstrap=xn(e)}async fetch(e,t){return fe(await this.connect(),e,t)}async requestJson(e,t,n,s,r={}){if(e===\"GET\"&&t.endsWith(\"/tools/catalog\"))return await this.request({method:\"catalog\"},r);if(e===\"GET\"&&t.endsWith(\"/tools/declarations\"))return await this.request({method:\"declarations\"},r);if(e===\"POST\"&&t.endsWith(\"/tools/calls\")){if(!T(n))throw TypeError(\"Site tool call payload is required\");return await this.request({method:\"call\",payload:Pn(n)},r)}throw new I(\"unsupported_request\",\"Unsupported Site bridge request\")}close(){if(this.closed)return;this.closed=!0,this.bootstrap.close(),this.port?.close(),this.port=null}async request(e,t){let n=await this.connect(),s=crypto.randomUUID(),r=Pt(t.timeoutMs??this.options.requestTimeoutMs??120000,\"requestTimeoutMs\");return await new Promise((i,o)=>{let a=setTimeout(()=>{d(),Ct(n,s),o(e.method===\"call\"?new I(\"timeout\",\"Site tool request timed out after execution may have started\",!1,!0):new I(\"timeout\",\"Site tool request timed out\",!0))},r),c=()=>{d(),Ct(n,s),o(t.signal?.reason??new DOMException(\"Request aborted\",\"AbortError\"))},l=(p)=>{let u=p.data;if(!T(u)||u.type!==Sn||u.version!==W||u.requestId!==s||typeof u.ok!==\"boolean\")return;if(d(),u.ok){i(u.value);return}let m=T(u.error)?u.error:{};o(new I(typeof m.code===\"string\"?m.code:\"bridge_error\",typeof m.message===\"string\"?m.message:\"Site tool request failed\",m.retryable===!0,m.outcomeUnknown===!0))},d=()=>{clearTimeout(a),t.signal?.removeEventListener(\"abort\",c),n.removeEventListener(\"message\",l)};if(t.signal?.aborted){c();return}t.signal?.addEventListener(\"abort\",c,{once:!0}),n.addEventListener(\"message\",l),n.postMessage({type:hn,version:W,requestId:s,...e})})}async connect(){if(this.closed)throw new I(\"closed\",\"Site bridge is closed\");if(this.port)return this.port;if(this.connecting)return await this.connecting;let e=(this.options.createMessageChannel??(()=>new MessageChannel))(),t=Pt(this.options.connectTimeoutMs??1e4,\"connectTimeoutMs\");return this.connecting=new Promise((n,s)=>{let r=!0,i=setTimeout(()=>{a(),e.port1.close(),s(new I(\"host_timeout\",\"OpenGeni Site host did not respond\"))},t),o=(c)=>{let l=c.data;if(!T(l)||l.type!==xt||l.version!==W)return;a(),this.port=e.port1,n(e.port1)},a=()=>{r=!1,clearTimeout(i),e.port1.removeEventListener(\"message\",o)};e.port1.addEventListener(\"message\",o),e.port1.start(),this.bootstrap.port().then((c)=>{if(!r)return;if(this.closed)throw new I(\"closed\",\"Site bridge is closed\");c.postMessage({type:bn,version:W},[e.port2])}).catch((c)=>{a(),e.port1.close(),s(c)})}).finally(()=>{this.connecting=null}),await this.connecting}}function xn(e){if(e.bootstrapPort)return{port:async()=>e.bootstrapPort,close:()=>e.bootstrapPort?.close()};let t=e.siteWindow??globalThis.window,n=e.parentWindow??t?.parent;if(!t||!n||n===t)return{port:async()=>{throw new I(\"host_unavailable\",\"OpenGeni Site client must run inside a hosted iframe\")},close:()=>{return}};let s=An(t);if(s)return{port:async()=>s,close:()=>{return}};let r=null,i=null,o=(d)=>{if(d.source!==n||!On(d.data)||d.ports.length!==1)return;c(),r=d.ports[0],r.start(),qn(t,r),a?.(r)},a=null,c=()=>t.removeEventListener(\"message\",o),l=new Promise((d,p)=>{a=d,i=p,t.addEventListener(\"message\",o)});return l.catch(()=>{return}),{port:async()=>await l,close:()=>{c(),i?.(new I(\"closed\",\"Site bridge is closed\")),a=null,i=null}}}function An(e){let t=e[At];if(!T(t))return null;let n=t.port;return n&&typeof n.postMessage===\"function\"&&typeof n.addEventListener===\"function\"&&typeof n.start===\"function\"?n:null}function qn(e,t){try{Object.defineProperty(e,At,{configurable:!0,value:{port:t}})}catch{}}function On(e){return T(e)&&e.type===xt&&e.version===W}function Ct(e,t){e.postMessage({type:vn,version:W,requestId:t})}function Pt(e,t){if(!Number.isFinite(e)||e<=0)throw RangeError(`${t} must be positive`);return e}function T(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}Object.defineProperty(globalThis,\"createOpenGeniSiteClient\",{configurable:!0,value:qt});})();\n";