@synlexa/studio 0.4.4 → 0.4.5

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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MolStarViewport-BEGb0UZJ.js","assets/MolStarViewport-BYVdqMR8.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MolStarViewport-DUHXlKIt.js","assets/MolStarViewport-BYVdqMR8.css"])))=>i.map(i=>d[i]);
2
2
  (function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const c of i)if(c.type==="childList")for(const d of c.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&s(d)}).observe(document,{childList:!0,subtree:!0});function n(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(i){if(i.ep)return;i.ep=!0;const c=n(i);fetch(i.href,c)}})();function GM(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Sb={exports:{}},nd={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.js
@@ -522,9 +522,9 @@ Error generating stack: `+u.message+`
522
522
  ${c.map(_=>_.error).join(`
523
523
  `)}
524
524
  ${d}
525
- ${g}`)}return d},U=s8(dT);var r_=(()=>{class e extends Ye{}return e._errorName="FileNotDownloadableError",e})(),i_=(()=>{class e extends Ye{}return e._errorName="StorageQuotaExceededError",e})(),o_=(()=>{class e extends Zc{}return e._errorName="FileExpiredError",e})(),Pk=(()=>{class e extends ye{list(n={},s){const{workspace_id:i,...c}=n??{};return this._client.getAPIList("/v1/files",Me,{query:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.files.list",s,{route:"/v1/files",queryParams:["ids","limit","page"]})})}delete(n,s={},i){const{workspace_id:c}=s??{};return this._client.delete(U`/v1/files/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.files.delete",i,{route:"/v1/files/{file_id}",attributes:{"anthropic.file.id":n}})})}download(n,s={},i){const{workspace_id:c}=s??{};return this._client.get(U`/v1/files/${n}/content`,{...i,headers:L([{Accept:"application/binary",...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__binaryResponse:!0,__span:N(this._client,"anthropic.files.download",i,{route:"/v1/files/{file_id}/content",attributes:{"anthropic.file.id":n}})})}retrieveMetadata(n,s={},i){const{workspace_id:c}=s??{};return this._client.get(U`/v1/files/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.files.retrieve_metadata",i,{route:"/v1/files/{file_id}",attributes:{"anthropic.file.id":n}})})}upload(n,s){const{workspace_id:i,...c}=n;return this._client.post("/v1/files",Kr({body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},uT(c.file),s?.headers]),__span:N(this._client,"anthropic.files.upload",s,{route:"/v1/files",createdIDAttribute:"anthropic.file.id"})},this._client))}}return e.FileNotDownloadableError=r_,e.StorageQuotaExceededError=i_,e.FileExpiredError=o_,e})(),hT=(()=>{class e extends Ye{}return e._errorName="ClaudeCodeKeyCreatorNotMemberError",e})(),mT=(()=>{class e extends Ye{}return e._errorName="ClaudeCodeVersionTooOldError",e})(),fT=(()=>{class e extends Ye{}return e._errorName="CMEKKeyDisabledError",e})(),pT=(()=>{class e extends Ye{}return e._errorName="CMEKKeyNetworkBlockedError",e})(),gT=(()=>{class e extends Ye{}return e._errorName="OrganizationOnHoldError",e})(),bT=(()=>{class e extends Ye{}return e._errorName="OrganizationTypeNotSupportedError",e})(),xT=(()=>{class e extends Ye{}return e._errorName="RequestBodyEncodingInvalidError",e})(),yT=(()=>{class e extends Ye{}return e._errorName="RequestBodyEncodingUnsupportedError",e})(),_T=(()=>{class e extends vs{}return e._errorName="SandboxEgressRestrictedError",e})(),vT=(()=>{class e extends qy{}return e._errorName="RequestBodyTooLargeAfterDecodingError",e})(),wT=(()=>{class e extends Hp{}return e._errorName="EnforcedSpendLimitReachedError",e})(),ST=(()=>{class e extends Hp{}return e._errorName="RampLimitExceededError",e})(),kT=(()=>{class e extends _h{}return e._errorName="CMEKContextUnavailableError",e})(),CT=(()=>{class e extends _h{}return e._errorName="CMEKKeyUnreachableError",e})();class $k extends ye{retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/deployment_runs/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployment_runs.retrieve",s,{route:"/v1/deployment_runs/{deployment_run_id}",attributes:{"anthropic.deployment_run.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/deployment_runs",Me,{query:c,...n,headers:L([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployment_runs.list",n,{route:"/v1/deployment_runs",queryParams:["created_at[gt]","created_at[gte]","created_at[lt]","created_at[lte]","deployment_id","has_error","limit","page","trigger_type"]})})}}class Ik extends ye{create(r,n){const{betas:s,workspace_id:i,...c}=r;return this._client.post("/v1/deployments",{body:c,...n,headers:L([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.create",n,{route:"/v1/deployments",createdIDAttribute:"anthropic.deployment.id"})})}retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/deployments/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.retrieve",s,{route:"/v1/deployments/{deployment_id}",attributes:{"anthropic.deployment.id":r}})})}update(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/deployments/${r}`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.update",s,{route:"/v1/deployments/{deployment_id}",attributes:{"anthropic.deployment.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/deployments",Me,{query:c,...n,headers:L([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.list",n,{route:"/v1/deployments",queryParams:["agent_id","created_at[gte]","created_at[lte]","include_archived","limit","page","status"]})})}archive(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/deployments/${r}/archive`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.archive",s,{route:"/v1/deployments/{deployment_id}/archive",attributes:{"anthropic.deployment.id":r}})})}pause(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/deployments/${r}/pause`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.pause",s,{route:"/v1/deployments/{deployment_id}/pause",attributes:{"anthropic.deployment.id":r}})})}run(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/deployments/${r}/run`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.run",s,{route:"/v1/deployments/{deployment_id}/run",attributes:{"anthropic.deployment.id":r}})})}unpause(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/deployments/${r}/unpause`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.unpause",s,{route:"/v1/deployments/{deployment_id}/unpause",attributes:{"anthropic.deployment.id":r}})})}}class Dk extends ye{create(r,n){const{betas:s,workspace_id:i,...c}=r;return this._client.post("/v1/dreams",{body:c,...n,headers:L([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.create",n,{route:"/v1/dreams",createdIDAttribute:"anthropic.dream.id"})})}retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/dreams/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.retrieve",s,{route:"/v1/dreams/{dream_id}",attributes:{"anthropic.dream.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/dreams",Me,{query:c,...n,headers:L([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.list",n,{route:"/v1/dreams",queryParams:["created_at[gt]","created_at[lt]","include_archived","limit","page","statuses"]})})}archive(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/dreams/${r}/archive`,{...s,headers:L([{"anthropic-beta":[...i??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.archive",s,{route:"/v1/dreams/{dream_id}/archive",attributes:{"anthropic.dream.id":r}})})}cancel(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/dreams/${r}/cancel`,{...s,headers:L([{"anthropic-beta":[...i??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.cancel",s,{route:"/v1/dreams/{dream_id}/cancel",attributes:{"anthropic.dream.id":r}})})}}class qk extends ye{list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/files",Me,{query:c,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.files.list",n,{route:"/v1/files",queryParams:["ids","limit","page","scope_id"]})})}delete(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.delete(U`/v1/files/${r}`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.files.delete",s,{route:"/v1/files/{file_id}",attributes:{"anthropic.file.id":r}})})}download(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/files/${r}/content`,{...s,headers:L([{Accept:"application/binary",...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__binaryResponse:!0,__span:N(this._client,"anthropic.files.download",s,{route:"/v1/files/{file_id}/content",attributes:{"anthropic.file.id":r}})})}retrieveMetadata(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/files/${r}`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.files.retrieve_metadata",s,{route:"/v1/files/{file_id}",attributes:{"anthropic.file.id":r}})})}upload(r,n){const{betas:s,workspace_id:i,...c}=r;return this._client.post("/v1/files",Kr({body:c,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},uT(c.file),n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.files.upload",n,{route:"/v1/files",createdIDAttribute:"anthropic.file.id"})},this._client))}}let Lk=class extends ye{retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/models/${r}`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.models.retrieve",s,{route:"/v1/models/{model_id}",attributes:{"anthropic.model.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/models",ns,{query:c,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.models.list",n,{route:"/v1/models",queryParams:["after_id","before_id","lifecycle","limit"]})})}};var Mo={},hs={},Uk;function a8(){if(Uk)return hs;Uk=1;var e=hs&&hs.__extends||(function(){var x=function(g,_){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,S){y.__proto__=S}||function(y,S){for(var k in S)S.hasOwnProperty(k)&&(y[k]=S[k])},x(g,_)};return function(g,_){x(g,_);function y(){this.constructor=g}g.prototype=_===null?Object.create(_):(y.prototype=_.prototype,new y)}})();Object.defineProperty(hs,"__esModule",{value:!0});var r=256,n=(function(){function x(g){g===void 0&&(g="="),this._paddingCharacter=g}return x.prototype.encodedLength=function(g){return this._paddingCharacter?(g+2)/3*4|0:(g*8+5)/6|0},x.prototype.encode=function(g){for(var _="",y=0;y<g.length-2;y+=3){var S=g[y]<<16|g[y+1]<<8|g[y+2];_+=this._encodeByte(S>>>18&63),_+=this._encodeByte(S>>>12&63),_+=this._encodeByte(S>>>6&63),_+=this._encodeByte(S>>>0&63)}var k=g.length-y;if(k>0){var S=g[y]<<16|(k===2?g[y+1]<<8:0);_+=this._encodeByte(S>>>18&63),_+=this._encodeByte(S>>>12&63),k===2?_+=this._encodeByte(S>>>6&63):_+=this._paddingCharacter||"",_+=this._paddingCharacter||""}return _},x.prototype.maxDecodedLength=function(g){return this._paddingCharacter?g/4*3|0:(g*6+7)/8|0},x.prototype.decodedLength=function(g){return this.maxDecodedLength(g.length-this._getPaddingLength(g))},x.prototype.decode=function(g){if(g.length===0)return new Uint8Array(0);for(var _=this._getPaddingLength(g),y=g.length-_,S=new Uint8Array(this.maxDecodedLength(y)),k=0,E=0,T=0,j=0,q=0,z=0,O=0;E<y-4;E+=4)j=this._decodeChar(g.charCodeAt(E+0)),q=this._decodeChar(g.charCodeAt(E+1)),z=this._decodeChar(g.charCodeAt(E+2)),O=this._decodeChar(g.charCodeAt(E+3)),S[k++]=j<<2|q>>>4,S[k++]=q<<4|z>>>2,S[k++]=z<<6|O,T|=j&r,T|=q&r,T|=z&r,T|=O&r;if(E<y-1&&(j=this._decodeChar(g.charCodeAt(E)),q=this._decodeChar(g.charCodeAt(E+1)),S[k++]=j<<2|q>>>4,T|=j&r,T|=q&r),E<y-2&&(z=this._decodeChar(g.charCodeAt(E+2)),S[k++]=q<<4|z>>>2,T|=z&r),E<y-3&&(O=this._decodeChar(g.charCodeAt(E+3)),S[k++]=z<<6|O,T|=O&r),T!==0)throw new Error("Base64Coder: incorrect characters for decoding");return S},x.prototype._encodeByte=function(g){var _=g;return _+=65,_+=25-g>>>8&6,_+=51-g>>>8&-75,_+=61-g>>>8&-15,_+=62-g>>>8&3,String.fromCharCode(_)},x.prototype._decodeChar=function(g){var _=r;return _+=(42-g&g-44)>>>8&-r+g-43+62,_+=(46-g&g-48)>>>8&-r+g-47+63,_+=(47-g&g-58)>>>8&-r+g-48+52,_+=(64-g&g-91)>>>8&-r+g-65+0,_+=(96-g&g-123)>>>8&-r+g-97+26,_},x.prototype._getPaddingLength=function(g){var _=0;if(this._paddingCharacter){for(var y=g.length-1;y>=0&&g[y]===this._paddingCharacter;y--)_++;if(g.length<4||_>2)throw new Error("Base64Coder: incorrect padding")}return _},x})();hs.Coder=n;var s=new n;function i(x){return s.encode(x)}hs.encode=i;function c(x){return s.decode(x)}hs.decode=c;var d=(function(x){e(g,x);function g(){return x!==null&&x.apply(this,arguments)||this}return g.prototype._encodeByte=function(_){var y=_;return y+=65,y+=25-_>>>8&6,y+=51-_>>>8&-75,y+=61-_>>>8&-13,y+=62-_>>>8&49,String.fromCharCode(y)},g.prototype._decodeChar=function(_){var y=r;return y+=(44-_&_-46)>>>8&-r+_-45+62,y+=(94-_&_-96)>>>8&-r+_-95+63,y+=(47-_&_-58)>>>8&-r+_-48+52,y+=(64-_&_-91)>>>8&-r+_-65+0,y+=(96-_&_-123)>>>8&-r+_-97+26,y},g})(n);hs.URLSafeCoder=d;var f=new d;function p(x){return f.encode(x)}hs.encodeURLSafe=p;function b(x){return f.decode(x)}return hs.decodeURLSafe=b,hs.encodedLength=function(x){return s.encodedLength(x)},hs.maxDecodedLength=function(x){return s.maxDecodedLength(x)},hs.decodedLength=function(x){return s.decodedLength(x)},hs}var ip={exports:{}},r8=ip.exports,Bk;function i8(){return Bk||(Bk=1,(function(e){(function(r,n){var s={};n(s);var i=s.default;for(var c in s)i[c]=s[c];e.exports=i})(r8,function(r){r.__esModule=!0,r.digestLength=32,r.blockSize=64;var n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function s(_,y,S,k,E){for(var T,j,q,z,O,V,P,$,H,Z,G,K,we;E>=64;){for(T=y[0],j=y[1],q=y[2],z=y[3],O=y[4],V=y[5],P=y[6],$=y[7],Z=0;Z<16;Z++)G=k+Z*4,_[Z]=(S[G]&255)<<24|(S[G+1]&255)<<16|(S[G+2]&255)<<8|S[G+3]&255;for(Z=16;Z<64;Z++)H=_[Z-2],K=(H>>>17|H<<15)^(H>>>19|H<<13)^H>>>10,H=_[Z-15],we=(H>>>7|H<<25)^(H>>>18|H<<14)^H>>>3,_[Z]=(K+_[Z-7]|0)+(we+_[Z-16]|0);for(Z=0;Z<64;Z++)K=(((O>>>6|O<<26)^(O>>>11|O<<21)^(O>>>25|O<<7))+(O&V^~O&P)|0)+($+(n[Z]+_[Z]|0)|0)|0,we=((T>>>2|T<<30)^(T>>>13|T<<19)^(T>>>22|T<<10))+(T&j^T&q^j&q)|0,$=P,P=V,V=O,O=z+K|0,z=q,q=j,j=T,T=K+we|0;y[0]+=T,y[1]+=j,y[2]+=q,y[3]+=z,y[4]+=O,y[5]+=V,y[6]+=P,y[7]+=$,k+=64,E-=64}return k}var i=(function(){function _(){this.digestLength=r.digestLength,this.blockSize=r.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return _.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},_.prototype.clean=function(){for(var y=0;y<this.buffer.length;y++)this.buffer[y]=0;for(var y=0;y<this.temp.length;y++)this.temp[y]=0;this.reset()},_.prototype.update=function(y,S){if(S===void 0&&(S=y.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var k=0;if(this.bytesHashed+=S,this.bufferLength>0){for(;this.bufferLength<64&&S>0;)this.buffer[this.bufferLength++]=y[k++],S--;this.bufferLength===64&&(s(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(S>=64&&(k=s(this.temp,this.state,y,k,S),S%=64);S>0;)this.buffer[this.bufferLength++]=y[k++],S--;return this},_.prototype.finish=function(y){if(!this.finished){var S=this.bytesHashed,k=this.bufferLength,E=S/536870912|0,T=S<<3,j=S%64<56?64:128;this.buffer[k]=128;for(var q=k+1;q<j-8;q++)this.buffer[q]=0;this.buffer[j-8]=E>>>24&255,this.buffer[j-7]=E>>>16&255,this.buffer[j-6]=E>>>8&255,this.buffer[j-5]=E>>>0&255,this.buffer[j-4]=T>>>24&255,this.buffer[j-3]=T>>>16&255,this.buffer[j-2]=T>>>8&255,this.buffer[j-1]=T>>>0&255,s(this.temp,this.state,this.buffer,0,j),this.finished=!0}for(var q=0;q<8;q++)y[q*4+0]=this.state[q]>>>24&255,y[q*4+1]=this.state[q]>>>16&255,y[q*4+2]=this.state[q]>>>8&255,y[q*4+3]=this.state[q]>>>0&255;return this},_.prototype.digest=function(){var y=new Uint8Array(this.digestLength);return this.finish(y),y},_.prototype._saveState=function(y){for(var S=0;S<this.state.length;S++)y[S]=this.state[S]},_.prototype._restoreState=function(y,S){for(var k=0;k<this.state.length;k++)this.state[k]=y[k];this.bytesHashed=S,this.finished=!1,this.bufferLength=0},_})();r.Hash=i;var c=(function(){function _(y){this.inner=new i,this.outer=new i,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var S=new Uint8Array(this.blockSize);if(y.length>this.blockSize)new i().update(y).finish(S).clean();else for(var k=0;k<y.length;k++)S[k]=y[k];for(var k=0;k<S.length;k++)S[k]^=54;this.inner.update(S);for(var k=0;k<S.length;k++)S[k]^=106;this.outer.update(S),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var k=0;k<S.length;k++)S[k]=0}return _.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},_.prototype.clean=function(){for(var y=0;y<this.istate.length;y++)this.ostate[y]=this.istate[y]=0;this.inner.clean(),this.outer.clean()},_.prototype.update=function(y){return this.inner.update(y),this},_.prototype.finish=function(y){return this.outer.finished?this.outer.finish(y):(this.inner.finish(y),this.outer.update(y,this.digestLength).finish(y)),this},_.prototype.digest=function(){var y=new Uint8Array(this.digestLength);return this.finish(y),y},_})();r.HMAC=c;function d(_){var y=new i().update(_),S=y.digest();return y.clean(),S}r.hash=d,r.default=d;function f(_,y){var S=new c(_).update(y),k=S.digest();return S.clean(),k}r.hmac=f;function p(_,y,S,k){var E=k[0];if(E===0)throw new Error("hkdf: cannot expand more");y.reset(),E>1&&y.update(_),S&&y.update(S),y.update(k),y.finish(_),k[0]++}var b=new Uint8Array(r.digestLength);function x(_,y,S,k){y===void 0&&(y=b),k===void 0&&(k=32);for(var E=new Uint8Array([1]),T=f(y,_),j=new c(T),q=new Uint8Array(j.digestLength),z=q.length,O=new Uint8Array(k),V=0;V<k;V++)z===q.length&&(p(q,j,S,E),z=0),O[V]=q[z++];return j.clean(),q.fill(0),E.fill(0),O}r.hkdf=x;function g(_,y,S,k){for(var E=new c(_),T=E.digestLength,j=new Uint8Array(4),q=new Uint8Array(T),z=new Uint8Array(T),O=new Uint8Array(k),V=0;V*T<k;V++){var P=V+1;j[0]=P>>>24&255,j[1]=P>>>16&255,j[2]=P>>>8&255,j[3]=P>>>0&255,E.reset(),E.update(y),E.update(j),E.finish(z);for(var $=0;$<T;$++)q[$]=z[$];for(var $=2;$<=S;$++){E.reset(),E.update(z).finish(z);for(var H=0;H<T;H++)q[H]^=z[H]}for(var $=0;$<T&&V*T+$<k;$++)O[V*T+$]=q[$]}for(var V=0;V<T;V++)q[V]=z[V]=0;for(var V=0;V<4;V++)j[V]=0;return E.clean(),O}r.pbkdf2=g})})(ip)),ip.exports}var af={},Gk;function o8(){if(Gk)return af;Gk=1,Object.defineProperty(af,"__esModule",{value:!0}),af.timingSafeEqual=r;function e(n,s=""){if(!n)throw new Error(s)}function r(n,s){if(n.byteLength!==s.byteLength)return!1;n instanceof DataView||(n=new DataView(ArrayBuffer.isView(n)?n.buffer:n)),s instanceof DataView||(s=new DataView(ArrayBuffer.isView(s)?s.buffer:s)),e(n instanceof DataView),e(s instanceof DataView);const i=n.byteLength;let c=0,d=-1;for(;++d<i;)c|=n.getUint8(d)^s.getUint8(d);return c===0}return af}var Hk;function l8(){if(Hk)return Mo;Hk=1,Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.Webhook=Mo.WebhookVerificationError=void 0;const e=a8(),r=i8(),n=o8(),s=300;class i extends Error{constructor(p){super(p),Object.setPrototypeOf(this,i.prototype),this.name="ExtendableError",this.stack=new Error(p).stack}}class c extends i{constructor(p){super(p),Object.setPrototypeOf(this,c.prototype),this.name="WebhookVerificationError"}}Mo.WebhookVerificationError=c;class d{constructor(p,b){if(b?.format==="raw")p instanceof Uint8Array?this.key=p:this.key=Uint8Array.from(p,x=>x.charCodeAt(0));else{if(typeof p!="string")throw new Error("Expected secret to be of type string");p.startsWith(d.prefix)&&(p=p.substring(d.prefix.length)),this.key=e.decode(p)}if(this.key.length===0)throw new Error("Secret can't be empty.")}verify(p,b,x){var g;const _=(g=x?.jsonParse)!==null&&g!==void 0?g:!0,y={};for(const V of Object.keys(b))y[V.toLowerCase()]=b[V];const S=y["webhook-id"],k=y["webhook-signature"],E=y["webhook-timestamp"];if(!k||!S||!E)throw new c("Missing required headers");const T=this.verifyTimestamp(E),q=this.sign(S,T,p).split(",")[1],z=k.split(" "),O=new globalThis.TextEncoder;for(const V of z){const[P,$]=V.split(",");if(P==="v1"&&(0,n.timingSafeEqual)(O.encode($),O.encode(q))){const H=p.toString();return H===""?void 0:_?JSON.parse(H):void 0}}throw new c("No matching signature found")}sign(p,b,x){if(typeof x!="string")if(x.constructor.name==="Buffer")x=x.toString();else throw new Error("Expected payload to be of type string or Buffer.");const g=new TextEncoder,_=Math.floor(b.getTime()/1e3),y=g.encode(`${p}.${_}.${x}`);return`v1,${e.encode(r.hmac(this.key,y))}`}verifyTimestamp(p){const b=Math.floor(Date.now()/1e3),x=parseInt(p,10);if(Number.isNaN(x))throw new c("Invalid Signature Headers");if(b-x>s)throw new c("Message timestamp too old");if(x>b+s)throw new c("Message timestamp too new");return new Date(x*1e3)}}return Mo.Webhook=d,d.prefix="whsec_",Mo}var c8=l8();let Fk=class extends ye{parseUnverified(r){return JSON.parse(r)}unwrap(r,n){const s=n?.headers;if(s==null)throw new Error("Webhook headers are required in order to verify the signature");const i=n.key===void 0?this._client.webhookKey:n.key;if(!i)throw new Error("Webhook key must not be null or empty in order to unwrap");return new c8.Webhook(i).verify(r,s),JSON.parse(r)}},Vk=class extends ye{list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/agents/${r}/versions`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.versions.list",s,{route:"/v1/agents/{agent_id}/versions",queryParams:["limit","page"],attributes:{"gen_ai.agent.id":r}})})}};var Kk=(()=>{class e extends ye{constructor(){super(...arguments),this.versions=new Vk(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/agents",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.create",s,{route:"/v1/agents",createdIDAttribute:"gen_ai.agent.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d,...f}=s??{};return this._client.get(U`/v1/agents/${n}`,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.retrieve",i,{route:"/v1/agents/{agent_id}",queryParams:["version"],attributes:{"gen_ai.agent.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/agents/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.update",i,{route:"/v1/agents/{agent_id}",attributes:{"gen_ai.agent.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/agents",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.list",s,{route:"/v1/agents",queryParams:["created_at[gte]","created_at[lte]","include_archived","limit","page"]})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/agents/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.archive",i,{route:"/v1/agents/{agent_id}/archive",attributes:{"gen_ai.agent.id":n}})})}}return e.Versions=Vk,e})();let Yx=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return Yx=e.randomUUID.bind(e),e.randomUUID();const r=new Uint8Array(1),n=e?()=>e.getRandomValues(r)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function uh(e,r){if(!e)return()=>{};if(e.aborted)return r.abort(),()=>{};const n=()=>r.abort();return e.addEventListener("abort",n),()=>e.removeEventListener("abort",n)}function $c(e,r){return e instanceof Gt&&e.status===r}function u8(e){return e instanceof Gt&&typeof e.status=="number"&&e.status>=400&&e.status<500}function wp(e){return u8(e)&&!$c(e,408)&&!$c(e,409)&&!$c(e,429)}function NT(e,r,n){return Math.min(r*2**e,n)}function d8(e,r){return e+Math.random()*(r-e)}function AT(e){return e*(1-Math.random()*.25)}function jT(e,{authToken:r,helper:n}){if(!r)throw new De(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(r)}`);const s=e._options.defaultHeaders,i=e._authState?.extraHeaders,c=i?Object.fromEntries(Object.entries(i).filter(([f])=>{const p=f.toLowerCase();return p!=="authorization"&&p!=="x-api-key"})):void 0,d=L([c,s,{[vh]:n}]);return d.values.delete("x-api-key"),d.values.delete("authorization"),d.nulls.delete("authorization"),e.withOptions({authToken:r,baseURL:e.baseURL,defaultHeaders:d})}var oc,rf,ms,of,lf,cf,cd,ud,lc,cc,uf,uc,dd;const h8=999,m8=1e3,f8=6e4,p8=3e5;var Wx=(()=>{class e{constructor(n){oc.set(this,void 0),rf.set(this,!1),ms.set(this,void 0),of.set(this,void 0),lf.set(this,void 0),cf.set(this,void 0),cd.set(this,void 0),ud.set(this,void 0),lc.set(this,void 0),this.client=n.client,this.environmentId=n.environmentId,this.environmentKey=n.environmentKey,this.workerId=n.workerId??x8(),se(this,oc,jT(n.client,{authToken:n.environmentKey,helper:"environments-work-poller"})),se(this,lf,n.autoStop??!0),se(this,cf,n.drain??!1),se(this,cd,n.blockMs===void 0?h8:n.blockMs),se(this,ud,n.reclaimOlderThanMs??null),se(this,lc,n.requestOptions),se(this,ms,new AbortController),se(this,of,uh(n.signal,v(this,ms,"f")))}get signal(){return v(this,ms,"f").signal}abort(){v(this,ms,"f").abort()}async*[(oc=new WeakMap,rf=new WeakMap,ms=new WeakMap,of=new WeakMap,lf=new WeakMap,cf=new WeakMap,cd=new WeakMap,ud=new WeakMap,lc=new WeakMap,Symbol.asyncIterator)](){if(v(this,rf,"f"))throw new De("Cannot iterate over a consumed WorkPoller");se(this,rf,!0);let n=Hs.active();const s=it(this.client);s.info("poller starting",{component:"work-poller",environment_id:this.environmentId});const i=new b8(s,this.environmentId);try{let c=0;for(;!v(this,ms,"f").signal.aborted;){let d;try{d=await v(this,oc,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...v(this,cd,"f")!==null?{block_ms:v(this,cd,"f")}:{},...v(this,ud,"f")!==null?{reclaim_older_than_ms:v(this,ud,"f")}:{}},{headers:L([v(this,lc,"f")?.headers]),signal:v(this,ms,"f").signal})}catch(f){if(v(this,ms,"f").signal.aborted)return;if(wp(f))throw s.error("poll failed permanently, stopping poller",{error:String(f)}),f;const p=AT(g8(c));s.warn("poll failed, backing off",{error:String(f),backoff_ms:p}),c++,await Ko(p,v(this,ms,"f").signal);continue}if(c=0,d==null){if(v(this,cf,"f"))return;i.onEmptyPoll(),await Ko(d8(1e3,3e3),v(this,ms,"f").signal);continue}i.onClaim(),this._workSpan=zt(this.client,()=>ZP(this.client,d,n)),s.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:d.id,work_type:d.data.type});try{await v(this,oc,"f").beta.environments.work.ack(d.id,{environment_id:d.environment_id},{headers:L([v(this,lc,"f")?.headers]),signal:v(this,ms,"f").signal})}catch(f){s.error("ack failed",{work_id:d.id,error:String(f)}),zt(this.client,()=>oT(this._workSpan,v(this,ms,"f").signal,f));continue}try{yield d,n=Hs.active()}finally{if(v(this,lf,"f"))try{await v(this,oc,"f").beta.environments.work.stop(d.id,{environment_id:d.environment_id},{headers:L([v(this,lc,"f")?.headers])})}catch(f){$c(f,409)||s.warn("stop failed",{work_id:d.id,error:String(f)})}zt(this.client,()=>iT(this._workSpan,v(this,ms,"f").signal))}}}finally{v(this,of,"f").call(this)}}}return e})();function g8(e){return NT(e,m8,f8)}var b8=(()=>{class e{constructor(n,s){cc.set(this,void 0),uf.set(this,void 0),uc.set(this,void 0),dd.set(this,0),se(this,cc,n),se(this,uf,s)}onEmptyPoll(){const n=Date.now(),s={component:"work-poller",environment_id:v(this,uf,"f")};v(this,uc,"f")===void 0?(se(this,uc,se(this,dd,n,"f")),v(this,cc,"f").info("idle; polling for work",s)):n-v(this,dd,"f")>=p8?(se(this,dd,n),v(this,cc,"f").info(`still polling; idle for ${Math.round((n-v(this,uc,"f"))/1e3)}s`,s)):v(this,cc,"f").debug("poll returned no work",s)}onClaim(){se(this,uc,void 0)}}return cc=new WeakMap,uf=new WeakMap,uc=new WeakMap,dd=new WeakMap,e})();function x8(){const r=globalThis.process?.env?.HOSTNAME;return r?`${r}-${Yx()}`:Yx()}const y8=e=>{if(typeof globalThis.Buffer<"u"){const r=globalThis.Buffer.from(e,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(typeof atob<"u"){const r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}throw new De("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};var dc,Ei,hc,_8=(()=>{class e{constructor(){dc.set(this,[]),Ei.set(this,[]),hc.set(this,!1)}push(n){if(v(this,hc,"f"))return!1;const s=v(this,Ei,"f").shift();return s?s({done:!1,value:n}):v(this,dc,"f").push(n),!0}close(){if(!v(this,hc,"f"))for(se(this,hc,!0);v(this,Ei,"f").length>0;)v(this,Ei,"f").shift()({done:!0,value:void 0})}next(n){return v(this,dc,"f").length>0?Promise.resolve({done:!1,value:v(this,dc,"f").shift()}):v(this,hc,"f")||n?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(s=>{const i=d=>{n?.removeEventListener("abort",c),s(d)},c=()=>{const d=v(this,Ei,"f").indexOf(i);d>=0&&v(this,Ei,"f").splice(d,1),s({done:!0,value:void 0})};v(this,Ei,"f").push(i),n?.addEventListener("abort",c,{once:!0})})}tryShift(){return v(this,dc,"f").shift()}}return dc=new WeakMap,Ei=new WeakMap,hc=new WeakMap,e})(),l_=(()=>{class e extends Error{constructor(n){const s=typeof n=="string"?n:n.map(i=>i.type==="text"?i.text:`[${i.type}]`).join(" ");super(s),this.name="ToolError",this.content=n}}return e})();const v8="\\x00-\\x1f\\x7f-\\x9f\\u061c\\u200e\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069",w8=new RegExp(`[${v8}]+`,"g"),S8=/[\uD800-\uDFFF]/gu;function Sp(e){return e.replace(S8,"�")}const TT=4096,k8=200;function C8(e,r=TT){return MT(Sp(e).replace(w8," ").trim(),r)}function N8(e){return C8(e,k8)}function Bi(e){return N8(e).replace(/[' ]+/g," ").trim()}function ET(e){return`Error: ${e instanceof Error?e.message:String(e)}`}function A8(e){return MT(Sp(ET(e)),TT)}function MT(e,r){if(e.length<=r)return e;let n=0,s=0;for(const i of e){if(s===r)break;s+=1,n+=i.length}return e.slice(0,n)}function j8(e){return typeof e=="string"?Sp(e):e.filter(r=>r.type==="text"&&r.text!=="").map(r=>({...r,text:Sp(r.text)}))}function Yk(e){return"name"in e?e.name:"mcp_server_name"in e?e.mcp_server_name:e.type}function T8(e){return e instanceof l_?e.content:ET(e)}async function RT(e,r,n){try{const s=e.parse?e.parse(r):r;return{content:await e.run(s,n),isError:!1}}catch(s){return{content:T8(s),isError:!0}}}var hd,df,mc,Ro,_a,Ft,hf,vn,mf,fc,ff,mn,pc,Os,gc,Mi,bc,Sr,pf,md,Ps,gf,fd,pd,bf,Wk,Xk,Qk,Bb,Jk,Gb,Zk,xf,yf,Hb,eC,tC;const nC=500,E8=1e4,M8=12e4,R8=3e4,z8=1e3,O8=3e4,P8=5*6e4,$8=6e4;function zT(e){return e.type!=="session.status_idle"?!1:e.stop_reason?.type!=="requires_action"}var I8=(()=>{class e{constructor(n,s){hd.set(this,void 0),df.set(this,void 0),mc.set(this,new Set),Ro.set(this,!1),_a.set(this,void 0),se(this,hd,n),se(this,df,s)}noteEvent(n){n.type!=="user.tool_confirmation"&&(zT(n)?this.arm():this.disarm())}block(n){v(this,mc,"f").add(n),v(this,_a,"f")!==void 0&&(se(this,Ro,!0),clearTimeout(v(this,_a,"f")),se(this,_a,void 0))}unblock(n){v(this,mc,"f").delete(n),v(this,mc,"f").size===0&&v(this,Ro,"f")&&this.arm()}arm(){if(!(v(this,hd,"f")<=0)){if(v(this,mc,"f").size>0){se(this,Ro,!0);return}se(this,Ro,!1),v(this,_a,"f")!==void 0&&clearTimeout(v(this,_a,"f")),se(this,_a,setTimeout(v(this,df,"f"),v(this,hd,"f")))}}disarm(){se(this,Ro,!1),v(this,_a,"f")!==void 0&&(clearTimeout(v(this,_a,"f")),se(this,_a,void 0))}}return hd=new WeakMap,df=new WeakMap,mc=new WeakMap,Ro=new WeakMap,_a=new WeakMap,e})(),Xx=(()=>{class e{constructor(n,s){Ft.add(this),hf.set(this,!1),vn.set(this,void 0),mf.set(this,void 0),fc.set(this,void 0),ff.set(this,void 0),mn.set(this,void 0),pc.set(this,new Set),Os.set(this,new Set),gc.set(this,new Map),Mi.set(this,new Map),bc.set(this,new _8),Sr.set(this,0),pf.set(this,P8),md.set(this,null),Ps.set(this,void 0),gf.set(this,void 0),fd.set(this,void 0),pd.set(this,!1),this.client=s.client,this.sessionId=n,this.tools=s.tools,this.maxIdleMs=s.maxIdleMs??$8,se(this,mn,it(s.client)),se(this,ff,new Map(s.tools.map(i=>[Yk(i),i]))),se(this,vn,new AbortController),se(this,mf,uh(s.signal,v(this,vn,"f"))),se(this,fc,s.requestOptions),se(this,Ps,new I8(this.maxIdleMs,()=>{v(this,mn,"f").info("session idle after its turn ended; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),v(this,vn,"f").abort()}))}get signal(){return v(this,vn,"f").signal}abort(){v(this,vn,"f").abort()}_setSendRetryWindow(n){se(this,pf,n)}async*[(hf=new WeakMap,vn=new WeakMap,mf=new WeakMap,fc=new WeakMap,ff=new WeakMap,mn=new WeakMap,pc=new WeakMap,Os=new WeakMap,gc=new WeakMap,Mi=new WeakMap,bc=new WeakMap,Sr=new WeakMap,pf=new WeakMap,md=new WeakMap,Ps=new WeakMap,gf=new WeakMap,fd=new WeakMap,pd=new WeakMap,Ft=new WeakSet,Symbol.asyncIterator)](){if(v(this,hf,"f"))throw new De("Cannot iterate over a consumed SessionToolRunner");se(this,hf,!0),se(this,gf,this.client._tracer?Hs.active():void 0),v(this,mn,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});const n=v(this,Ft,"m",Wk).call(this).catch(s=>{v(this,vn,"f").signal.aborted||v(this,mn,"f").error("stream loop failed",{error:String(s)}),v(this,vn,"f").abort()});try{for(;;){const i=await v(this,bc,"f").next(v(this,vn,"f").signal);if(i.done)break;yield i.value}await n;let s;for(;(s=v(this,bc,"f").tryShift())!==void 0;)yield s}finally{v(this,vn,"f").abort(),v(this,Ps,"f").disarm(),await n;try{await v(this,Ft,"m",tC).call(this)}catch(s){v(this,mn,"f").warn("drain failed",{error:String(s)})}v(this,bc,"f").close();for(const s of this.tools)try{await s.close?.()}catch(i){v(this,mn,"f").warn("tool.close failed",{tool:Yk(s),error:String(i)})}v(this,mf,"f").call(this)}}}return bf=function(){return{...v(this,fc,"f"),headers:L([s_("session-tool-runner"),v(this,fc,"f")?.headers]),signal:v(this,vn,"f").signal}},Wk=async function(){const n=v(this,vn,"f");let s=nC;for(;!n.signal.aborted;){try{const i=await this.client.beta.sessions.events.stream(this.sessionId,{},v(this,Ft,"m",bf).call(this));await v(this,Ft,"m",Xk).call(this);for await(const c of i)if(s=nC,await v(this,Ft,"m",Jk).call(this,c))return}catch(i){if(n.signal.throwIfAborted(),wp(i))throw v(this,mn,"f").error("permanent stream failure, shutting down",{error:String(i)}),n.abort(),i;v(this,mn,"f").warn("stream disconnected, reconnecting",{error:String(i),backoff_ms:s})}n.signal.throwIfAborted(),await Ko(s,n.signal),s=Math.min(s*2,E8)}},Xk=async function(){const n=v(this,vn,"f"),s=[];let i=!1;se(this,pd,!1);try{for await(const f of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},v(this,Ft,"m",bf).call(this)))v(this,Ft,"m",Qk).call(this,f,s),f.type!=="user.tool_confirmation"&&(i=zT(f))}catch(f){n.signal.throwIfAborted(),v(this,mn,"f").warn("reconcile list failed",{error:String(f)});for(const p of s)v(this,pc,"f").delete(p.id);return}se(this,pd,!0);const c=s.filter(f=>!v(this,Os,"f").has(f.id));v(this,Ps,"f").disarm();for(const f of c)await v(this,Ft,"m",Gb).call(this,f);for(const f of[...v(this,Mi,"f").values()]){const p=v(this,gc,"f").get(f.id);p!==void 0&&await v(this,Ft,"m",xf).call(this,f,p)}const d=c.filter(f=>!v(this,Os,"f").has(f.id)&&!v(this,Mi,"f").has(f.id));i&&d.length===0?v(this,Ps,"f").arm():v(this,Ps,"f").disarm()},Qk=function(n,s){v(this,Ft,"m",Bb).call(this,n),n.type==="agent.tool_use"||n.type==="agent.custom_tool_use"?(v(this,pc,"f").add(n.id),v(this,Os,"f").has(n.id)||s.push(n)):n.type==="user.tool_result"?v(this,Os,"f").add(n.tool_use_id):n.type==="user.custom_tool_result"?v(this,Os,"f").add(n.custom_tool_use_id):n.type==="user.tool_confirmation"&&(v(this,Os,"f").has(n.tool_use_id)||v(this,gc,"f").set(n.tool_use_id,n.result))},Bb=function(n){if(!(!this.client._tracer||v(this,fd,"f")!==void 0))switch(n.type){case"session.thread_status_running":case"session.thread_status_idle":case"session.thread_status_rescheduled":case"session.thread_status_terminated":se(this,fd,n.session_thread_id)}},Jk=async function(n){switch(v(this,Ps,"f").noteEvent(n),v(this,pd,"f")&&v(this,Ft,"m",Bb).call(this,n),n.type){case"agent.tool_use":case"agent.custom_tool_use":return v(this,pc,"f").has(n.id)||(v(this,pc,"f").add(n.id),await v(this,Ft,"m",Gb).call(this,n)),!1;case"user.tool_confirmation":return await v(this,Ft,"m",Zk).call(this,n),!1;case"user.tool_result":return v(this,Os,"f").add(n.tool_use_id),!1;case"user.custom_tool_result":return v(this,Os,"f").add(n.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return v(this,mn,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),v(this,vn,"f").abort(),!0;default:return!1}},Gb=async function(n){const s=n.evaluated_permission,i=s==="deny"?"deny":v(this,gc,"f").get(n.id);if(i===void 0){s===void 0||s==="allow"?await v(this,Ft,"m",Hb).call(this,n,void 0):v(this,Mi,"f").has(n.id)||(v(this,mn,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),v(this,Mi,"f").set(n.id,n),v(this,Ps,"f").block(n.id));return}await v(this,Ft,"m",xf).call(this,n,i)},Zk=async function(n){v(this,gc,"f").set(n.tool_use_id,n.result);const s=v(this,Mi,"f").get(n.tool_use_id);s!==void 0&&await v(this,Ft,"m",xf).call(this,s,n.result)},xf=async function(n,s){const i=v(this,Mi,"f").delete(n.id);if(s==="allow"){v(this,mn,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),i||v(this,Ps,"f").block(n.id);try{await v(this,Ft,"m",Hb).call(this,n,"allow")}finally{v(this,Ps,"f").unblock(n.id)}return}i&&v(this,Ps,"f").unblock(n.id),v(this,Os,"f").add(n.id),v(this,mn,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),v(this,Ft,"m",yf).call(this,{event:n,toolUseId:n.id,name:n.name,isError:!1,posted:!1,confirmation:"deny"})},yf=function(n){v(this,bc,"f").push(n)},Hb=async function(n,s){var i,c;if(!v(this,Os,"f").has(n.id)){v(this,mn,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),se(this,Sr,(i=v(this,Sr,"f"),i++,i));try{const d=v(this,ff,"f").get(n.name);if(!d){v(this,mn,"f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),s==="allow"&&v(this,Ps,"f").disarm(),v(this,Ft,"m",yf).call(this,{event:n,toolUseId:n.id,name:n.name,isError:!1,posted:!1,confirmation:s});return}let f,p;const b=v(this,fc,"f")?.openTelemetry?.conversationId??(n.session_thread_id||v(this,fd,"f")),x=new AbortController,g=uh(v(this,vn,"f").signal,x),_=setTimeout(()=>x.abort(),M8);try{const k={signal:v(this,vn,"f").signal,conversationId:b,sessionID:this.sessionId,parentContext:v(this,gf,"f")},E=await a_(this.client,d,n,k,async()=>{const T=await RT(d,n.input,{toolUse:n,toolUseBlock:n,signal:x.signal}),j=q8(T.content),q=this.client._tracer?j.map((z,O)=>{const V=typeof T.content=="string"?void 0:T.content[O];return V&&V.type!=="text"&&z.type==="text"?V:z}):j;return{sent:j,content:q,isError:T.isError}});f=E.sent,p=E.isError}finally{clearTimeout(_),g()}const y=D8(n,p,f),S=await v(this,Ft,"m",eC).call(this,y,n.id,b);v(this,Ft,"m",yf).call(this,{event:n,result:y,toolUseId:n.id,name:n.name,isError:p,posted:S,confirmation:s})}finally{se(this,Sr,(c=v(this,Sr,"f"),c--,c)),v(this,Sr,"f")===0&&v(this,md,"f")?.call(this)}}},eC=async function(n,s,i){const c=v(this,vn,"f"),d=Date.now();let f,p=0;for(;;){p++,c.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[n]},{...v(this,Ft,"m",bf).call(this),openTelemetry:{conversationId:i}}),v(this,Os,"f").add(s),!0}catch(b){if(f=b,wp(b))break;const x=v(this,pf,"f")-(Date.now()-d);if(x<=0)break;const g=Math.min(AT(NT(p-1,z8,O8)),x);v(this,mn,"f").warn("tool result send failed; retrying",{tool_use_id:s,attempt:p,backoff_ms:g,error:String(b)}),await Ko(g,c.signal)}}return v(this,mn,"f").error("failed to send tool result",{tool_use_id:s,attempts:p,error:String(f)}),!1},tC=async function(){v(this,Sr,"f")!==0&&(await Promise.race([new Promise(n=>se(this,md,n)),Ko(R8)]),se(this,md,null),v(this,Sr,"f")>0&&v(this,mn,"f").warn("drain timeout exceeded"))},e})();function D8(e,r,n){return e.type==="agent.custom_tool_use"?{type:"user.custom_tool_result",custom_tool_use_id:e.id,is_error:r,content:n}:{type:"user.tool_result",tool_use_id:e.id,is_error:r,content:n}}function q8(e){if(typeof e=="string")return[{type:"text",text:e||"(no output)"}];const r=e.map(n=>n.type==="text"?{type:"text",text:n.text||"(no output)"}:n.type==="image"||n.type==="document"?n:n.type==="search_result"?{type:"search_result",source:n.source,title:n.title,content:n.content.map(s=>({type:"text",text:s.text})),citations:{enabled:n.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(n)});return r.length>0?r:[{type:"text",text:"(no output)"}]}const eU=15e3,sC=5e3;function L8(e,r){if(!(e>=sC))throw new De(`${r} must be at least ${sC}ms (got ${e}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}var _f,gd,Fb,bd,zo;const aC=3e4,U8=9e4,B8="NO_HEARTBEAT";function G8(e){return e.resources.some(r=>r.type==="memory_store")}function H8(e){if(!e)return null;let r;try{const s=e.replace(/-/g,"+").replace(/_/g,"/"),i=s.padEnd(Math.ceil(s.length/4)*4,"=");r=JSON.parse(Ux(y8(i)))}catch{return null}if(r===null||typeof r!="object"||Array.isArray(r))return null;const n=r.sessions_token;return typeof n=="string"&&n!==""?n:null}var rC=(()=>{class e{constructor(n){if(_f.add(this),gd.set(this,void 0),n.unrestrictedPaths!==void 0)throw new De("The `unrestrictedPaths` option you passed to EnvironmentWorker (or client.beta.environments.work.worker()) is no longer supported. The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a `tools` factory.");this.client=n.client,this.environmentId=n.environmentId,this.environmentKey=n.environmentKey,this.tools=n.tools,this.workdir=n.workdir??process.cwd(),this.maxFileBytes=n.maxFileBytes,this.maxIdleMs=n.maxIdleMs,n.memorySyncIntervalMs!=null&&L8(n.memorySyncIntervalMs,"memorySyncIntervalMs"),this.memorySyncIntervalMs=n.memorySyncIntervalMs,this.memorySyncDeletions=n.memorySyncDeletions??"enabled",this.workerId=n.workerId,this.requestOptions=n.requestOptions,se(this,gd,n.signal)}async run(n){const{environmentId:s,environmentKey:i}=this;if(s===void 0||i===void 0)throw new De("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");const c=n??v(this,gd,"f"),d=new Wx({client:this.client,environmentId:s,environmentKey:i,...this.workerId!==void 0?{workerId:this.workerId}:{},...c?{signal:c}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(const f of d){const p=d._workSpan;try{await e8(this.client,p,d.signal,()=>v(this,_f,"m",Fb).call(this,f,i,d.signal,p))}catch(b){if(d.signal?.aborted)throw b;it(this.client).error("work item failed",{work_id:f.id,error:String(b)})}}}async handleItem(n){const s=n?.workId??ot("ANTHROPIC_WORK_ID"),i=n?.environmentId??ot("ANTHROPIC_ENVIRONMENT_ID"),c=n?.sessionId??ot("ANTHROPIC_SESSION_ID"),d=(n?.environmentKey??this.environmentKey??ot("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,f=n?.workSecret||ot("ANTHROPIC_WORK_SECRET")||null;if(!s)throw new De("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID");if(!i)throw new De("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!c)throw new De("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID");if(!d&&!f)throw new De("handleItem: environmentKey is required when there is no work secret — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");const p={id:s,environment_id:i,secret:f,data:{type:"session",id:c}};await v(this,_f,"m",Fb).call(this,p,d,n?.signal??v(this,gd,"f"))}}return gd=new WeakMap,_f=new WeakSet,Fb=async function(n,s,i,c){const d=it(this.client),f=H8(n.secret),p=f??s;if(p===void 0)throw new De("handleItem: the work item carried a secret payload but no sessions token could be extracted, and there is no environment key to fall back to; the poller must issue a secret whose payload carries `sessions_token`, or provide the environment key (pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY)");n.secret&&f===null&&d.warn("work item carried a secret payload but no sessions token could be extracted; falling back to the environment key",{work_id:n.id});const b=jT(this.client,{authToken:p,helper:"environments-worker"}),x=n.data.id,g=new AbortController,_=uh(i,g),y=new V8(g),S=await Aa(()=>import("./node.browser-BoI8HeAS.js"),[]);let k,E;const T=Y8(b,n,y,d,this.requestOptions,O=>{k=O,E?._setSendRetryWindow(O)}).catch(O=>{g.signal.aborted||d.error("heartbeat loop failed",{work_id:n.id,error:String(O)}),g.abort()});let j=async()=>{},q,z=!1;try{if(n.data.type!=="session"){d.debug("skipping non-session work item",{work_id:n.id,type:n.data.type});return}const O=await b.beta.sessions.retrieve(x);if(f===null&&this.memorySyncIntervalMs!==null&&G8(O))throw new S.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${n.id}, session_id=${x}); the memory endpoints reject the environment key, so the poller must issue a per-item \`secret\` carrying \`sessions_token\`, or set \`memorySyncIntervalMs: null\` to run without memory`);const V={workdir:this.workdir,client:b,session:O,...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}};try{j=await S.setupSkills(V)}catch($){d.warn("skill setup failed",{session_id:x,work_id:n.id,error:String($)})}f!==null&&this.memorySyncIntervalMs!==null?(q=new S.SessionMemoryStores(b,{workdir:this.workdir,...this.memorySyncIntervalMs!==void 0?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await q.download(O),V.allowedRoots=q.roots,V.readOnlyRoots=q.readOnlyRoots):d.debug("memory stores disabled for this item",{work_id:n.id});const P=typeof this.tools=="function"?this.tools(V):this.tools??S.betaAgentToolset20260401(V);E=new Xx(x,{client:b,tools:P,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:g.signal}),k!==void 0&&E._setSendRetryWindow(k);for await(const $ of E)q&&await q.syncIfDue();z=!g.signal.aborted}finally{try{await j().catch(O=>{d.warn("skill cleanup failed",{session_id:x,work_id:n.id,error:String(O)})})}finally{if(q){const O=S.MEMORY_FLUSH_TIMEOUT_MS;z&&await iC(q.finish(),O)&&d.warn(`final memory sync cut off after ${O}ms; the flush that follows still uploads changed files`,{session_id:x,work_id:n.id});const V=new AbortController;await iC(q.flushWrites(V.signal),O)&&(V.abort(),d.warn(`memory flush cut off after ${O}ms; changed files it had not uploaded yet are not saved`,{session_id:x,work_id:n.id})),await q.dispose().catch($=>{d.warn("memory store cleanup failed",{session_id:x,work_id:n.id,error:String($)})})}}y.finish("runner_done"),_(),await T,y.lost?d.info("lease lost; released without stopping it",{session_id:x,work_id:n.id}):await F8(b,n,d,this.requestOptions),(y.lost||y.rejected)&&zt(this.client,()=>c?.end())}},e})();async function iC(e,r){let n;try{return await Promise.race([e.then(()=>!1,()=>!1),new Promise(s=>{n=setTimeout(()=>s(!0),r)})])}finally{n!==void 0&&clearTimeout(n)}}async function F8(e,r,n,s){try{await e.beta.environments.work.stop(r.id,{environment_id:r.environment_id,force:!0},{...s,headers:L([s?.headers])})}catch(i){$c(i,409)||n.error("force-stop on exit failed",{work_id:r.id,error:String(i)})}}var V8=(()=>{class e{constructor(n){bd.set(this,void 0),zo.set(this,void 0),se(this,bd,n)}get signal(){return v(this,bd,"f").signal}finish(n){se(this,zo,v(this,zo,"f")??n),v(this,bd,"f").abort()}get lost(){return v(this,zo,"f")==="lease_lost"||v(this,zo,"f")==="assumed_lost"}get rejected(){return v(this,zo,"f")==="heartbeat_rejected"}}return bd=new WeakMap,zo=new WeakMap,e})();function K8(e){let r=e instanceof Gt?e.error:void 0;for(const n of["error","details","current_state"]){if(!Hn(r))return{};r=r[n]}return Hn(r)?r:{}}async function Y8(e,r,n,s,i,c){let d=aC,f=U8,p=Date.now(),b=B8;const x=async()=>{const g=new AbortController,_=uh(n.signal,g),y=setTimeout(()=>g.abort(),d);try{const S=await e.beta.environments.work.heartbeat(r.id,{environment_id:r.environment_id,expected_last_heartbeat:b},{...i,headers:L([i?.headers]),signal:g.signal});p=Date.now(),b=S.last_heartbeat,S.ttl_seconds>0&&(f=S.ttl_seconds*1e3,d=Math.max(1e3,Math.min(f/2,aC)),c?.(f)),(S.state==="stopping"||S.state==="stopped")&&(s.info("heartbeat signals shutdown",{work_id:r.id,state:S.state}),n.finish("heartbeat_stop")),S.lease_extended||(s.warn("lease not extended, shutting down",{work_id:r.id}),n.finish("heartbeat_stop"))}catch(S){if(n.signal.throwIfAborted(),$c(S,412)){const k=K8(S);s.error("lease lost: heartbeat precondition failed",{work_id:r.id,server_state:k.state,server_ttl_seconds:k.ttl_seconds,server_last_heartbeat:k.last_heartbeat}),n.finish("lease_lost");return}if(wp(S))throw s.error("permanent heartbeat failure",{work_id:r.id,error:String(S)}),n.finish("heartbeat_rejected"),S;if(Date.now()-p>f){s.error("lease assumed lost: no successful heartbeat in ttl",{work_id:r.id,ttl_ms:f,error:String(S)}),n.finish("assumed_lost");return}s.warn("transient heartbeat failure",{work_id:r.id,error:String(S)})}finally{clearTimeout(y),_()}};for(await x();!n.signal.aborted;)await Ko(d,n.signal),n.signal.throwIfAborted(),await x()}var c_=(()=>{class e extends Dy{}return e._errorName="BetaHeartbeatPreconditionFailedError",e})(),oC=(()=>{class e extends ye{retrieve(n,s,i){const{environment_id:c,betas:d,workspace_id:f}=s;return this._client.get(U`/v1/environments/${c}/work/${n}`,{...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.retrieve",i,{route:"/v1/environments/{environment_id}/work/{work_id}",attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}update(n,s,i){const{environment_id:c,betas:d,workspace_id:f,...p}=s;return this._client.post(U`/v1/environments/${c}/work/${n}`,{body:p,...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.update",i,{route:"/v1/environments/{environment_id}/work/{work_id}",attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}list(n,s={},i){const{betas:c,...d}=s??{};return this._client.getAPIList(U`/v1/environments/${n}/work`,Me,{query:d,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.list",i,{route:"/v1/environments/{environment_id}/work",queryParams:["limit","page"],attributes:{"anthropic.environment.id":n}})})}ack(n,s,i){const{environment_id:c,betas:d}=s;return this._client.post(U`/v1/environments/${c}/work/${n}/ack`,{...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.ack",i,{route:"/v1/environments/{environment_id}/work/{work_id}/ack",attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}heartbeat(n,s,i){const{environment_id:c,desired_ttl_seconds:d,expected_last_heartbeat:f,betas:p}=s;return this._client.post(U`/v1/environments/${c}/work/${n}/heartbeat`,{query:{desired_ttl_seconds:d,expected_last_heartbeat:f},...i,headers:L([{"anthropic-beta":[...p??[],"managed-agents-2026-04-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.heartbeat",i,{route:"/v1/environments/{environment_id}/work/{work_id}/heartbeat",queryParams:["desired_ttl_seconds","expected_last_heartbeat"],attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}poll(n,s={},i){const{betas:c,"Anthropic-Worker-ID":d,...f}=s??{};return this._client.get(U`/v1/environments/${n}/work/poll`,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"Anthropic-Worker-ID":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.poll",i,{route:"/v1/environments/{environment_id}/work/poll",queryParams:["block_ms","reclaim_older_than_ms"],attributes:{"anthropic.environment.id":n}})})}stats(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/environments/${n}/work/stats`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.stats",i,{route:"/v1/environments/{environment_id}/work/stats",attributes:{"anthropic.environment.id":n}})})}stop(n,s,i){const{environment_id:c,betas:d,workspace_id:f,...p}=s;return this._client.post(U`/v1/environments/${c}/work/${n}/stop`,{body:p,...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.stop",i,{route:"/v1/environments/{environment_id}/work/{work_id}/stop",attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}poller(n){return new Wx({...n,client:this._client})}worker(n){return new rC({...n,client:this._client})}}return e.BetaHeartbeatPreconditionFailedError=c_,e.WorkPoller=Wx,e.EnvironmentWorker=rC,e})(),u_=(()=>{class e extends Ye{}return e._errorName="BetaEnvironmentArchivedError",e})(),d_=(()=>{class e extends Ye{}return e._errorName="BetaInvalidConfigTypeChangeError",e})(),h_=(()=>{class e extends Ye{}return e._errorName="BetaInvalidMetadataError",e})(),m_=(()=>{class e extends vs{}return e._errorName="BetaEnvironmentCreateDisabledError",e})(),f_=(()=>{class e extends vs{}return e._errorName="BetaEnvironmentUpdateDisabledError",e})(),p_=(()=>{class e extends Zc{}return e._errorName="BetaEnvironmentNotFoundError",e})(),lC=(()=>{class e extends ye{constructor(){super(...arguments),this.work=new oC(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/environments",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.create",s,{route:"/v1/environments",createdIDAttribute:"anthropic.environment.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/environments/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.retrieve",i,{route:"/v1/environments/{environment_id}",attributes:{"anthropic.environment.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/environments/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.update",i,{route:"/v1/environments/{environment_id}",attributes:{"anthropic.environment.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/environments",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.list",s,{route:"/v1/environments",queryParams:["include_archived","limit","page"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/environments/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.delete",i,{route:"/v1/environments/{environment_id}",attributes:{"anthropic.environment.id":n}})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/environments/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.archive",i,{route:"/v1/environments/{environment_id}/archive",attributes:{"anthropic.environment.id":n}})})}}return e.BetaEnvironmentArchivedError=u_,e.BetaInvalidConfigTypeChangeError=d_,e.BetaInvalidMetadataError=h_,e.BetaEnvironmentCreateDisabledError=m_,e.BetaEnvironmentUpdateDisabledError=f_,e.BetaEnvironmentNotFoundError=p_,e.Work=oC,e.BetaHeartbeatPreconditionFailedError=c_,e})();class cC extends ye{create(r,n,s){const{view:i,betas:c,workspace_id:d,...f}=n;return this._client.post(U`/v1/memory_stores/${r}/memories`,{query:{view:i},body:f,...s,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.create",s,{route:"/v1/memory_stores/{memory_store_id}/memories",queryParams:["view"],attributes:{"gen_ai.memory.store.id":r},createdIDAttribute:"gen_ai.memory.record.id"})})}retrieve(r,n,s){const{memory_store_id:i,betas:c,workspace_id:d,...f}=n;return this._client.get(U`/v1/memory_stores/${i}/memories/${r}`,{query:f,...s,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.retrieve",s,{route:"/v1/memory_stores/{memory_store_id}/memories/{memory_id}",queryParams:["view"],attributes:{"gen_ai.memory.store.id":i,"gen_ai.memory.record.id":r}})})}update(r,n,s){const{memory_store_id:i,view:c,betas:d,workspace_id:f,...p}=n;return this._client.post(U`/v1/memory_stores/${i}/memories/${r}`,{query:{view:c},body:p,...s,headers:L([{"anthropic-beta":[...d??[],"agent-memory-2026-07-22"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.update",s,{route:"/v1/memory_stores/{memory_store_id}/memories/{memory_id}",queryParams:["view"],attributes:{"gen_ai.memory.store.id":i,"gen_ai.memory.record.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/memory_stores/${r}/memories`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.list",s,{route:"/v1/memory_stores/{memory_store_id}/memories",queryParams:["depth","limit","page","path_prefix","view"],contentQueryParams:["page"],attributes:{"gen_ai.memory.store.id":r}})})}delete(r,n,s){const{memory_store_id:i,expected_content_sha256:c,betas:d,workspace_id:f}=n;return this._client.delete(U`/v1/memory_stores/${i}/memories/${r}`,{query:{expected_content_sha256:c},...s,headers:L([{"anthropic-beta":[...d??[],"agent-memory-2026-07-22"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.delete",s,{route:"/v1/memory_stores/{memory_store_id}/memories/{memory_id}",queryParams:["expected_content_sha256"],attributes:{"gen_ai.memory.store.id":i,"gen_ai.memory.record.id":r}})})}}class uC extends ye{retrieve(r,n,s){const{memory_store_id:i,betas:c,workspace_id:d,...f}=n;return this._client.get(U`/v1/memory_stores/${i}/memory_versions/${r}`,{query:f,...s,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memory_versions.retrieve",s,{route:"/v1/memory_stores/{memory_store_id}/memory_versions/{memory_version_id}",queryParams:["view"],attributes:{"gen_ai.memory.store.id":i,"anthropic.memory_store.memory_version.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/memory_stores/${r}/memory_versions`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memory_versions.list",s,{route:"/v1/memory_stores/{memory_store_id}/memory_versions",queryParams:["api_key_id","created_at[gte]","created_at[lte]","limit","memory_id","operation","page","service_account_id","session_id","view"],attributes:{"gen_ai.memory.store.id":r}})})}redact(r,n,s){const{memory_store_id:i,betas:c,workspace_id:d}=n;return this._client.post(U`/v1/memory_stores/${i}/memory_versions/${r}/redact`,{...s,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memory_versions.redact",s,{route:"/v1/memory_stores/{memory_store_id}/memory_versions/{memory_version_id}/redact",attributes:{"gen_ai.memory.store.id":i,"anthropic.memory_store.memory_version.id":r}})})}}var dC=(()=>{class e extends ye{constructor(){super(...arguments),this.memories=new cC(this._client),this.memoryVersions=new uC(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/memory_stores",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.create",s,{route:"/v1/memory_stores",createdIDAttribute:"gen_ai.memory.store.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/memory_stores/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.retrieve",i,{route:"/v1/memory_stores/{memory_store_id}",attributes:{"gen_ai.memory.store.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/memory_stores/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.update",i,{route:"/v1/memory_stores/{memory_store_id}",attributes:{"gen_ai.memory.store.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/memory_stores",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.list",s,{route:"/v1/memory_stores",queryParams:["created_at[gte]","created_at[lte]","include_archived","limit","page"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/memory_stores/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.delete",i,{route:"/v1/memory_stores/{memory_store_id}",attributes:{"gen_ai.memory.store.id":n}})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/memory_stores/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.archive",i,{route:"/v1/memory_stores/{memory_store_id}/archive",attributes:{"gen_ai.memory.store.id":n}})})}}return e.Memories=cC,e.MemoryVersions=uC,e})(),OT=(()=>{class e{constructor(n,s,i){this.iterator=n,this.response=i,this.controller=s}async*decoder(){const n=this.iterator;if(!n)throw new De("Cannot iterate over a consumed stream.");this.iterator=void 0;const s=new Oj;for await(const i of n)for(const c of s.decode(i))yield JSON.parse(c);for(const i of s.flush())yield JSON.parse(i)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(n,s){if(!n.body)throw s.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new De("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new De("Attempted to iterate over a response with no body");return new e(By(n.body),s,n)}}return e})();let hC=class extends ye{create(r,n){const{betas:s,user_profile_id:i,workspace_id:c,...d}=r;return this._client.post("/v1/messages/batches",{body:d,...n,headers:L([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-user-profile-id":i}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.create",n,{route:"/v1/messages/batches",attributes:{"anthropic.message.batch.request_count":d.requests?.length},createdIDAttribute:"anthropic.message.batch.id"})})}retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/messages/batches/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.retrieve",s,{route:"/v1/messages/batches/{message_batch_id}",attributes:{"anthropic.message.batch.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/messages/batches",ns,{query:c,...n,headers:L([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.list",n,{route:"/v1/messages/batches",queryParams:["after_id","before_id","limit"]})})}delete(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.delete(U`/v1/messages/batches/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.delete",s,{route:"/v1/messages/batches/{message_batch_id}",attributes:{"anthropic.message.batch.id":r}})})}cancel(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/messages/batches/${r}/cancel`,{...s,headers:L([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.cancel",s,{route:"/v1/messages/batches/{message_batch_id}/cancel",attributes:{"anthropic.message.batch.id":r}})})}async results(r,n={},s){const i=await this.retrieve(r,n,s);if(!i.results_url)throw new De(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);const{betas:c,workspace_id:d}=n??{};return this._client.get(i.results_url,{...s,headers:L([{"anthropic-beta":[...c??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),stream:!0,__qualifiers:{beta:"true"},__binaryResponse:!0,__span:N(this._client,"anthropic.messages.batches.results",s,{route:"/v1/messages/batches/{message_batch_id}/results",attributes:{"anthropic.message.batch.id":r}})})._thenUnwrap((f,p)=>OT.fromResponse(p.response,p.controller))}};const PT={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function $T(e){return e?.output_format??e?.output_config?.format}function mC(e,r,n){const s=$T(r);return!r||!("parse"in(s??{}))?{...e,content:e.content.map(i=>{if(i.type==="text"){const c=Object.defineProperty({...i},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return i}),parsed_output:null}:g_(e,r,n)}function g_(e,r,n){let s=null;const i=e.content.map(c=>{if(c.type==="text"){const d=W8(r,c.text);s===null&&(s=d);const f=Object.defineProperty({...c},"parsed_output",{value:d,enumerable:!1});return Object.defineProperty(f,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),d},enumerable:!1})}return c});return{...e,content:i,parsed_output:s}}function W8(e,r){const n=$T(e);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(r):JSON.parse(r)}catch(s){throw new De(`Failed to parse structured output: ${s}`)}}function IT(e,r){const{betas:n,user_profile_id:s,workspace_id:i,tools:c,messages:d}=e;return L([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-user-profile-id":s}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},cT(c,d),r?.headers])}function X8(e,r,n){if(!e._tracer)return;const s=IT(r,n);return N(e,"anthropic.messages.create",n,Jp(e,{body:Qx(r),headers:s,stream:!0}))}function Qx(e){if(!e.output_format)return e;b_(e);const{output_format:r,...n}=e;return{...n,output_config:{...e.output_config,format:r}}}function b_(e){if(e.output_format&&e.output_config?.format)throw new De("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).")}const Q8=e=>{let r=0,n=[];for(;r<e.length;){let s=e[r];if(s==="\\"){r++;continue}if(s==="{"){n.push({type:"brace",value:"{"}),r++;continue}if(s==="}"){n.push({type:"brace",value:"}"}),r++;continue}if(s==="["){n.push({type:"paren",value:"["}),r++;continue}if(s==="]"){n.push({type:"paren",value:"]"}),r++;continue}if(s===":"){n.push({type:"separator",value:":"}),r++;continue}if(s===","){n.push({type:"delimiter",value:","}),r++;continue}if(s==='"'){const f=r+1;let p=f,b=!1;for(;;){if(p=e.indexOf('"',p),p===-1){b=!0;break}let x=0,g=p-1;for(;g>=f&&e[g]==="\\";)x++,g--;if(x%2===0)break;p++}b?r=e.length:(n.push({type:"string",value:e.slice(f,p)}),r=p+1);continue}if(s&&/\s/.test(s)){r++;continue}let c=/[0-9]/;if(s&&c.test(s)||s==="-"||s==="."){let f="";for(s==="-"&&(f+=s,s=e[++r]);s&&(c.test(s)||s==="."||s==="e"||s==="E"||(s==="-"||s==="+")&&(f[f.length-1]==="e"||f[f.length-1]==="E"));)f+=s,s=e[++r];n.push({type:"number",value:f,unterminated:r===e.length});continue}let d=/[a-z]/i;if(s&&d.test(s)){let f="";for(;s&&d.test(s)&&r!==e.length;)f+=s,s=e[++r];if(f=="true"||f=="false"||f==="null")n.push({type:"name",value:f});else{r++;continue}continue}r++}return n},J8=e=>{let r=[];for(const c of e)(c.type==="brace"||c.type==="paren")&&(c.value==="{"||c.value==="["?r.push(c.value):r.pop());let n=r[r.length-1],s=e.length,i=/^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;for(;s>0;){let c=e[s-1];switch(c.type){case"separator":s--;continue;case"number":if(c.unterminated||!i.test(c.value)){s--;continue}break;case"string":let d=e[s-2];if(n==="{"&&(d?.type==="delimiter"||d?.type==="brace"&&d.value==="{")){s--;continue}break;case"delimiter":s--;break}break}return e.slice(0,s)},Z8=e=>{let r=[];return e.map(n=>{n.type==="brace"&&(n.value==="{"?r.push("}"):r.splice(r.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?r.push("]"):r.splice(r.lastIndexOf("]"),1))}),r.length>0&&r.reverse().map(n=>{n==="}"?e.push({type:"brace",value:"}"}):n==="]"&&e.push({type:"paren",value:"]"})}),e},e$=e=>{let r="";return e.map(n=>{switch(n.type){case"string":r+='"'+n.value+'"';break;default:r+=n.value;break}}),r},t$=e=>JSON.parse(e$(Z8(J8(Q8(e))))),Ic="__json_buf";function DT(e,r){const n={};for(const c of Object.keys(e))c!=="input"&&(n[c]=e[c]);Object.defineProperty(n,Ic,{value:r,enumerable:!1,writable:!0});let s,i=!1;return Object.defineProperty(n,"input",{enumerable:!0,configurable:!0,get(){return i||(s=r?t$(r):{},i=!0),s}}),n}var fs,Ri,Ya,xd,vf,yd,_d,wf,vd,Wa,wd,Sf,kf,Oo,Cf,Nf,Af,Sd,Xa,Wn,kd,Vb,fC,Cd,Kb,Yb,Wb,pC,Xb;function Qb(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}var x_=(()=>{class e{constructor(n,s){fs.add(this),this.messages=[],this.receivedMessages=[],Ri.set(this,void 0),Ya.set(this,null),this.controller=new AbortController,xd.set(this,void 0),vf.set(this,()=>{}),yd.set(this,()=>{}),_d.set(this,void 0),wf.set(this,()=>{}),vd.set(this,()=>{}),Wa.set(this,{}),wd.set(this,!1),Sf.set(this,!1),kf.set(this,!1),Oo.set(this,!1),Cf.set(this,void 0),Nf.set(this,void 0),Af.set(this,void 0),Sd.set(this,void 0),Xa.set(this,void 0),Wn.set(this,void 0),kd.set(this,void 0),Cd.set(this,i=>{if(se(this,Sf,!0),v(this,Wn,"f")&&(v(this,Wn,"f").streamed=void 0),Jo(i)&&(i=new Ls),i instanceof Ls)return se(this,kf,!0),this._emit("abort",i);if(i instanceof De)return this._emit("error",i);if(i instanceof Error){const c=new De(i.message);return c.cause=i,this._emit("error",c)}return this._emit("error",new De(String(i)))}),se(this,xd,new Promise((i,c)=>{se(this,vf,i,"f"),se(this,yd,c,"f")})),se(this,_d,new Promise((i,c)=>{se(this,wf,i,"f"),se(this,vd,c,"f")})),v(this,xd,"f").catch(()=>{}),v(this,_d,"f").catch(()=>{}),se(this,Ya,n),se(this,Sd,s?.logger??console),se(this,Xa,s?.client)}get response(){return v(this,Cf,"f")}get request_id(){return v(this,Nf,"f")}get workspace_id(){return v(this,Af,"f")}async withResponse(){se(this,Oo,!0);const n=await v(this,xd,"f");if(!n)throw new Error("Could not resolve a `Response` object");return{data:this,response:n,request_id:n.headers.get("request-id"),workspace_id:n.headers.get("anthropic-workspace-id")}}static fromReadableStream(n){const s=new e(null);return s._run(()=>s._fromReadableStream(n)),s}static createMessage(n,s,i,{logger:c,client:d}={}){const f=new e(s,{logger:c,client:d});for(const p of s.messages)f._addMessageParam(p);return se(f,Ya,{...s,stream:!0}),f._run(()=>f._createMessage((p,b)=>n.create(p,b),{...s,stream:!0},{...i,headers:{...i?.headers,[n_]:"stream"}})),f}_start(n,s,i,c){for(const p of s.messages)this._addMessageParam(p);const d=v(this,Xa,"f");se(this,Xa,void 0);const f=(p,b)=>n(p,b)._thenUnwrap((x,{options:g})=>(se(this,Xa,d),se(this,Wn,g.__span),se(this,kd,g.body),x));this._run(()=>this._createMessage(f,{...s,stream:!0},i).finally(c))}_run(n){n().then(()=>{this._emitFinal(),this._emit("end")},v(this,Cd,"f"))}_addMessageParam(n){this.messages.push(n)}_addMessage(n,s=!0){this.receivedMessages.push(n),s&&this._emit("message",n)}async _createMessage(n,s,i){const c=i?.signal;let d;c&&(c.aborted&&this.controller.abort(),d=this.controller.abort.bind(this.controller),c.addEventListener("abort",d));try{v(this,fs,"m",Kb).call(this),se(this,Wn,i?.__span??(v(this,Xa,"f")&&X8(v(this,Xa,"f"),s,i)),"f");const{response:f,data:p}=await n({...s,stream:!0},{...i,__span:v(this,Wn,"f"),signal:this.controller.signal}).withResponse();try{this._connected(f)}catch(b){throw v(this,Wn,"f")&&(v(this,Wn,"f").failure=b),p.controller.abort(),b}for await(const b of p)try{v(this,fs,"m",Yb).call(this,b)}catch(x){throw v(this,Wn,"f")&&(v(this,Wn,"f").failure=x),x}if(p.controller.signal?.aborted)throw new Ls;v(this,fs,"m",Wb).call(this)}finally{c&&d&&c.removeEventListener("abort",d)}}_connected(n){this.ended||(se(this,Cf,n),se(this,Nf,n?.headers.get("request-id")),se(this,Af,n?.headers.get("anthropic-workspace-id")),v(this,vf,"f").call(this,n),this._emit("connect"))}get ended(){return v(this,wd,"f")}get errored(){return v(this,Sf,"f")}get aborted(){return v(this,kf,"f")}abort(){this.controller.abort()}on(n,s){return(v(this,Wa,"f")[n]||(v(this,Wa,"f")[n]=[])).push({listener:s}),this}off(n,s){const i=v(this,Wa,"f")[n];if(!i)return this;const c=i.findIndex(d=>d.listener===s);return c>=0&&i.splice(c,1),this}once(n,s){return(v(this,Wa,"f")[n]||(v(this,Wa,"f")[n]=[])).push({listener:s,once:!0}),this}emitted(n){return new Promise((s,i)=>{se(this,Oo,!0),n!=="error"&&this.once("error",i),this.once(n,s)})}async done(){se(this,Oo,!0),await v(this,_d,"f")}get currentMessage(){return v(this,Ri,"f")}async finalMessage(){return await this.done(),v(this,fs,"m",Vb).call(this)}async finalText(){return await this.done(),v(this,fs,"m",fC).call(this)}_emit(n,...s){if(v(this,wd,"f"))return;n==="end"&&(se(this,wd,!0),v(this,wf,"f").call(this));const i=v(this,Wa,"f")[n];if(i&&(v(this,Wa,"f")[n]=i.filter(c=>!c.once),i.forEach(({listener:c})=>c(...s))),n==="abort"){const c=s[0];!v(this,Oo,"f")&&!i?.length&&Promise.reject(c),v(this,yd,"f").call(this,c),v(this,vd,"f").call(this,c),this._emit("end");return}if(n==="error"){const c=s[0];!v(this,Oo,"f")&&!i?.length&&Promise.reject(c),v(this,yd,"f").call(this,c),v(this,vd,"f").call(this,c),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",v(this,fs,"m",Vb).call(this))}_deliverEvent(n,s){this._emit("_rawEvent",n),s&&this._emit("streamEvent",n,s)}async _fromReadableStream(n,s){const i=s?.signal;let c;i&&(i.aborted&&this.controller.abort(),c=this.controller.abort.bind(this.controller),i.addEventListener("abort",c));try{v(this,fs,"m",Kb).call(this),this._connected(null);const d=Hr.fromReadableStream(n,this.controller);for await(const f of d)v(this,fs,"m",Yb).call(this,f);if(d.controller.signal?.aborted)throw new Ls;v(this,fs,"m",Wb).call(this)}finally{i&&c&&i.removeEventListener("abort",c)}}[(Ri=new WeakMap,Ya=new WeakMap,xd=new WeakMap,vf=new WeakMap,yd=new WeakMap,_d=new WeakMap,wf=new WeakMap,vd=new WeakMap,Wa=new WeakMap,wd=new WeakMap,Sf=new WeakMap,kf=new WeakMap,Oo=new WeakMap,Cf=new WeakMap,Nf=new WeakMap,Af=new WeakMap,Sd=new WeakMap,Xa=new WeakMap,Wn=new WeakMap,kd=new WeakMap,Cd=new WeakMap,fs=new WeakSet,Vb=function(){if(this.receivedMessages.length===0)throw new De("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},fC=function(){if(this.receivedMessages.length===0)throw new De("stream ended without producing a Message with role=assistant");const s=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(s.length===0)throw new De("stream ended without producing a content block with type=text");return s.join(" ")},Kb=function(){this.ended||se(this,Ri,void 0)},Yb=function(s){if(this.ended)return;const i=v(this,fs,"m",pC).call(this,s);if(this._deliverEvent(s,i),!!i)switch(s.type){case"content_block_delta":{const c=i.content.at(-1);switch(s.delta.type){case"text_delta":{c.type==="text"&&this._emit("text",s.delta.text,c.text||"");break}case"citations_delta":{c.type==="text"&&this._emit("citation",s.delta.citation,c.citations??[]);break}case"input_json_delta":{if(Qb(c)&&v(this,Wa,"f").inputJson?.length){let d;try{d=c.input}catch(f){v(this,Cd,"f").call(this,v(this,fs,"m",Xb).call(this,c,f));break}this._emit("inputJson",s.delta.partial_json,d)}break}case"thinking_delta":{c.type==="thinking"&&this._emit("thinking",s.delta.thinking,c.thinking);break}case"signature_delta":{c.type==="thinking"&&this._emit("signature",c.signature);break}case"compaction_delta":{c.type==="compaction"&&c.content&&this._emit("compaction",c.content);break}default:s.delta}break}case"message_stop":{v(this,Xa,"f")&&v(this,Wn,"f")&&v(this,Ya,"f")&&t_(v(this,Xa,"f"),v(this,Wn,"f"),v(this,kd,"f")??v(this,Ya,"f"),i),this._addMessageParam(i),this._addMessage(mC(i,v(this,Ya,"f"),{logger:v(this,Sd,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{se(this,Ri,i),v(this,Wn,"f")&&v(this,Ya,"f")&&(v(this,Wn,"f").streamed={body:v(this,kd,"f")??v(this,Ya,"f"),message:i});break}}},Wb=function(){if(this.ended)throw new De("stream has ended, this shouldn't happen");const s=v(this,Ri,"f");if(!s)throw new De("request ended without sending any chunks");return se(this,Ri,void 0),mC(s,v(this,Ya,"f"),{logger:v(this,Sd,"f")})},pC=function(s){let i=v(this,Ri,"f");if(s.type==="message_start"){if(i)throw new De(`Unexpected event order, got ${s.type} before receiving "message_stop"`);return s.message}if(i)switch(s.type){case"message_stop":return i;case"message_delta":return i.stop_reason=s.delta.stop_reason,i.stop_sequence=s.delta.stop_sequence,i.stop_details=s.delta.stop_details,i.usage.output_tokens=s.usage.output_tokens,s.delta.container!=null&&(i.container=s.delta.container),s.context_management!=null&&(i.context_management=s.context_management),s.input_transformations!=null&&(i.input_transformations=s.input_transformations),s.usage.input_tokens!=null&&(i.usage.input_tokens=s.usage.input_tokens),s.usage.cache_creation_input_tokens!=null&&(i.usage.cache_creation_input_tokens=s.usage.cache_creation_input_tokens),s.usage.cache_read_input_tokens!=null&&(i.usage.cache_read_input_tokens=s.usage.cache_read_input_tokens),s.usage.server_tool_use!=null&&(i.usage.server_tool_use=s.usage.server_tool_use),s.usage.iterations!=null&&(i.usage.iterations=s.usage.iterations),s.usage.fallback_credit!=null&&(i.usage.fallback_credit=s.usage.fallback_credit),s.usage.output_tokens_details!=null&&(i.usage.output_tokens_details=s.usage.output_tokens_details),i;case"content_block_start":return i.content.push(s.content_block),s.content_block.type==="fallback"&&(i.model=s.content_block.to.model),i;case"content_block_delta":{const c=i.content.at(s.index);switch(s.delta.type){case"text_delta":{c?.type==="text"&&(i.content[s.index]={...c,text:(c.text||"")+s.delta.text});break}case"citations_delta":{c?.type==="text"&&(i.content[s.index]={...c,citations:[...c.citations??[],s.delta.citation]});break}case"input_json_delta":{if(c&&Qb(c)){const d=(c[Ic]||"")+s.delta.partial_json;i.content[s.index]=DT(c,d)}break}case"thinking_delta":{c?.type==="thinking"&&(i.content[s.index]={...c,thinking:c.thinking+s.delta.thinking});break}case"signature_delta":{c?.type==="thinking"&&(i.content[s.index]={...c,signature:s.delta.signature});break}case"compaction_delta":{if(c?.type==="compaction"){const d={...c,content:s.delta.content};"encrypted_content"in s.delta&&(d.encrypted_content=s.delta.encrypted_content),i.content[s.index]=d}break}default:s.delta}return i}case"content_block_stop":{const c=i.content.at(s.index);if(c&&Qb(c)&&Ic in c){let d;try{d=c.input}catch(f){d={},v(this,Cd,"f").call(this,v(this,fs,"m",Xb).call(this,c,f))}Object.defineProperty(c,"input",{value:d,enumerable:!0,configurable:!0,writable:!0})}return i}default:return i}},Xb=function(s,i){const c=s[Ic];return new De(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${i}. JSON: ${c}`)},Symbol.asyncIterator)](){const n=[],s=[];let i=!1;return this.on("_rawEvent",c=>{const d=s.shift();d?d.resolve(c):n.push(c)}),this.on("end",()=>{i=!0;for(const c of s)c.resolve(void 0);s.length=0}),this.on("abort",c=>{i=!0;for(const d of s)d.reject(c);s.length=0}),this.on("error",c=>{i=!0;for(const d of s)d.reject(c);s.length=0}),{next:async()=>n.length?{value:n.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((d,f)=>s.push({resolve:d,reject:f})).then(d=>d?{value:d,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Hr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})();const qT={browser_toolset_20260801:"browser",computer_toolset_20260801:"computer"};function Yc(e){return qT[e.type]}function dh(e){return"run"in e&&e.type!=null&&Object.prototype.hasOwnProperty.call(qT,e.type)}var LT=(()=>{class e extends De{constructor(n,s){super(n),s&&"cause"in s&&(this.cause=s.cause)}}return e._errorName="ToolsetUsageError",e})(),op=(()=>{class e extends LT{}return e._errorName="ToolsetContractError",e})();const UT="Not executed: an earlier action in this turn failed.",gC={browser:UT,computer:"Not executed: an earlier computer action in this turn failed."};function n$(e){return Object.prototype.hasOwnProperty.call(gC,e)?gC[e]:UT}function kp(e,r,n=!1){return n&&(r===""||Array.isArray(r)&&r.length===0)&&(r="The tool call failed with an empty error message."),{type:"tool_result",tool_use_id:e.id,toolset_name:e.toolset_name??null,content:r,...n?{is_error:!0}:{}}}function s$(e,r){if(e instanceof LT)throw e;a$(r.signal)}function a$(e){if(e?.aborted)throw new Ls}async function r$(e,r,n={}){const s=Yc(e);if(r.toolset_name!==s)throw new op(`tool_use ${JSON.stringify(r.id)} (toolset_name=${JSON.stringify(r.toolset_name??null)}, name=${JSON.stringify(r.name)}) is not a member call of the ${JSON.stringify(s)} toolset`);const i={...n,toolUse:r,toolUseBlock:r};try{return kp(r,await e.run(i,r))}catch(c){return s$(c,i),kp(r,j8(c instanceof l_?c.content:A8(c)),!0)}}let bC=class extends ye{retrieve(r,n){return this._client.get(U`/v1/organizations/api_keys/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.api_keys.retrieve",n,{route:"/v1/organizations/api_keys/{api_key_id}",attributes:{"anthropic.organization.api_key.id":r}})})}update(r,n,s){return this._client.post(U`/v1/organizations/api_keys/${r}`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.api_keys.update",s,{route:"/v1/organizations/api_keys/{api_key_id}",attributes:{"anthropic.organization.api_key.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/api_keys",ns,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.api_keys.list",n,{route:"/v1/organizations/api_keys",queryParams:["after_id","before_id","created_by_user_id","limit","status","workspace_id"]})})}},xC=class extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/artifacts",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.artifacts.list",n,{route:"/v1/organizations/analytics/artifacts",queryParams:["date","filter","group_by","limit","page"]})})}},yC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/connectors",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.connectors.list",n,{route:"/v1/organizations/analytics/connectors",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}};class _C extends ye{list(r,n){const{betas:s,...i}=r;return this._client.getAPIList("/v1/organizations/analytics/cost",tu,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"analytics-usage-cost-2026-08-24"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.cost.list",n,{route:"/v1/organizations/analytics/cost",queryParams:["actor_ids","actor_types","agent_ids","api_key_ids","claude_tag_categories","claude_tag_user_ids","context_windows","deployment_ids","ending_at","environment_ids","exclude_deleted_users","group_by","inference_geos","limit","models","order","order_by","organization_ids","page","products","rbac_group_ids","service_tiers","session_ids","slack_channel_ids","speeds","starting_at","time_bucket_width","user_profile_ids","workspace_ids"]})})}}class vC extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/cost_report",tu,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.cost_report.list",n,{route:"/v1/organizations/analytics/cost_report",queryParams:["bucket_width","claude_tag_categories","claude_tag_user_ids","context_windows","ending_at","group_by","inference_geos","limit","models","page","products","rbac_group_ids","slack_channel_ids","speeds","starting_at","user_ids"]})})}}let wC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/plugins",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.plugins.list",n,{route:"/v1/organizations/analytics/plugins",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}},SC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/skills",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.skills.list",n,{route:"/v1/organizations/analytics/skills",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}},kC=class extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/summaries",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.summaries.list",n,{route:"/v1/organizations/analytics/summaries",queryParams:["ending_date","filter","limit","page","starting_date"]})})}};class CC extends ye{list(r,n){const{betas:s,...i}=r;return this._client.getAPIList("/v1/organizations/analytics/usage",tu,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"analytics-usage-cost-2026-08-24"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.usage.list",n,{route:"/v1/organizations/analytics/usage",queryParams:["actor_ids","actor_types","agent_ids","api_key_ids","claude_tag_categories","claude_tag_user_ids","context_windows","deployment_ids","ending_at","environment_ids","exclude_deleted_users","group_by","inference_geos","limit","models","order","order_by","organization_ids","page","products","rbac_group_ids","service_tiers","session_ids","slack_channel_ids","speeds","starting_at","time_bucket_width","user_profile_ids","workspace_ids"]})})}}class NC extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/usage_report",tu,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.usage_report.list",n,{route:"/v1/organizations/analytics/usage_report",queryParams:["bucket_width","claude_tag_categories","claude_tag_user_ids","context_windows","ending_at","group_by","inference_geos","limit","models","page","products","rbac_group_ids","slack_channel_ids","speeds","starting_at","user_ids"]})})}}class AC extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/user_cost_report",tu,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.user_cost_report.list",n,{route:"/v1/organizations/analytics/user_cost_report",queryParams:["bucket_width","claude_tag_categories","claude_tag_user_ids","context_windows","ending_at","exclude_deleted_users","group_by","inference_geos","limit","models","order","order_by","page","products","rbac_group_ids","slack_channel_ids","speeds","starting_at","user_ids"]})})}}class jC extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/user_usage_report",tu,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.user_usage_report.list",n,{route:"/v1/organizations/analytics/user_usage_report",queryParams:["bucket_width","claude_tag_categories","claude_tag_user_ids","context_windows","ending_at","exclude_deleted_users","group_by","inference_geos","limit","models","order","order_by","page","products","rbac_group_ids","slack_channel_ids","speeds","starting_at","user_ids"]})})}}let TC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/users",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.users.list",n,{route:"/v1/organizations/analytics/users",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["page"]})})}},EC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/apps/chat/projects",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.apps.chat.projects.list",n,{route:"/v1/organizations/analytics/apps/chat/projects",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"]})})}};var MC=(()=>{class e extends ye{constructor(){super(...arguments),this.projects=new EC(this._client)}}return e.Projects=EC,e})(),RC=(()=>{class e extends ye{constructor(){super(...arguments),this.chat=new MC(this._client)}}return e.Chat=MC,e})(),zC=(()=>{class e extends ye{constructor(){super(...arguments),this.summaries=new kC(this._client),this.users=new TC(this._client),this.apps=new RC(this._client),this.connectors=new yC(this._client),this.plugins=new wC(this._client),this.skills=new SC(this._client),this.artifacts=new xC(this._client),this.usage=new CC(this._client),this.cost=new _C(this._client),this.usageReport=new NC(this._client),this.userUsageReport=new jC(this._client),this.costReport=new vC(this._client),this.userCostReport=new AC(this._client)}}return e.Summaries=kC,e.Users=TC,e.Apps=RC,e.Connectors=yC,e.Plugins=wC,e.Skills=SC,e.Artifacts=xC,e.Usage=CC,e.Cost=_C,e.UsageReport=NC,e.UserUsageReport=jC,e.CostReport=vC,e.UserCostReport=AC,e})(),y_=(()=>{class e extends Ye{}return e._errorName="BetaCannotSignOutPrimaryOwnerError",e})(),__=(()=>{class e extends Ye{}return e._errorName="BetaCannotSignOutSelfError",e})(),v_=(()=>{class e extends vs{}return e._errorName="BetaCannotSignOutManagedMemberError",e})(),w_=(()=>{class e extends vs{}return e._errorName="BetaCannotSignOutMembershipAdminError",e})(),S_=(()=>{class e extends vs{}return e._errorName="BetaCannotSignOutOwnerError",e})(),k_=(()=>{class e extends vs{}return e._errorName="BetaCannotSignOutPrivilegedMemberError",e})(),OC=(()=>{class e extends ye{retrieve(n,s){return this._client.get(U`/v1/organizations/users/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.retrieve",s,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/users/${n}`,{body:s,...i,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.update",i,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/users",ns,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.list",s,{route:"/v1/organizations/users",queryParams:["after_id","before_id","email","limit","roles"]})})}remove(n,s){return this._client.delete(U`/v1/organizations/users/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.remove",s,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}signOut(n,s={},i){const{betas:c}=s??{};return this._client.post(U`/v1/organizations/users/${n}/sign_out`,{...i,headers:L([{"anthropic-beta":[...c??[],"admin-user-sign-out-2026-10-08"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.sign_out",i,{route:"/v1/organizations/users/{user_id}/sign_out",attributes:{"anthropic.organization.user.id":n}})})}}return e.BetaCannotSignOutPrimaryOwnerError=y_,e.BetaCannotSignOutSelfError=__,e.BetaCannotSignOutManagedMemberError=v_,e.BetaCannotSignOutMembershipAdminError=w_,e.BetaCannotSignOutOwnerError=S_,e.BetaCannotSignOutPrivilegedMemberError=k_,e})();class PC extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/plugins/${r}/installation_settings`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.installation_settings.list",s,{route:"/v1/organizations/plugins/{plugin_id}/installation_settings",queryParams:["limit","organization_id","page","target_type"],attributes:{"anthropic.organization.plugin.id":r}})})}remove(r,n,s){const{plugin_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/plugins/${i}/installation_settings/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.installation_settings.remove",s,{route:"/v1/organizations/plugins/{plugin_id}/installation_settings/{target}",attributes:{"anthropic.organization.plugin.id":i,"anthropic.organization.plugin.installation_setting.id":r}})})}set(r,n,s){const{plugin_id:i,betas:c,...d}=n;return this._client.post(U`/v1/organizations/plugins/${i}/installation_settings/${r}`,{body:d,...s,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.installation_settings.set",s,{route:"/v1/organizations/plugins/{plugin_id}/installation_settings/{target}",attributes:{"anthropic.organization.plugin.id":i,"anthropic.organization.plugin.installation_setting.id":r}})})}}class $C extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/plugins/${r}/shares`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.shares.list",s,{route:"/v1/organizations/plugins/{plugin_id}/shares",queryParams:["limit","organization_id","page","target_type"],attributes:{"anthropic.organization.plugin.id":r}})})}}let IC=class extends ye{create(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/plugins/${r}/versions`,Kr({body:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.versions.create",s,{route:"/v1/organizations/plugins/{plugin_id}/versions",attributes:{"anthropic.organization.plugin.id":r},createdIDAttribute:"anthropic.organization.plugin.version.id"})},this._client))}retrieve(r,n,s){const{plugin_id:i,betas:c,...d}=n;return this._client.get(U`/v1/organizations/plugins/${i}/versions/${r}`,{query:d,...s,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.versions.retrieve",s,{route:"/v1/organizations/plugins/{plugin_id}/versions/{version}",queryParams:["organization_id"],attributes:{"anthropic.organization.plugin.id":i,"anthropic.organization.plugin.version.id":r}})})}list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/plugins/${r}/versions`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.versions.list",s,{route:"/v1/organizations/plugins/{plugin_id}/versions",queryParams:["limit","organization_id","page"],attributes:{"anthropic.organization.plugin.id":r}})})}download(r,n,s){const{plugin_id:i,betas:c,...d}=n;return this._client.get(U`/v1/organizations/plugins/${i}/versions/${r}/content`,{query:d,...s,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString(),Accept:"application/binary"},s?.headers]),__qualifiers:{beta:"true"},__binaryResponse:!0,__span:N(this._client,"anthropic.organization.plugins.versions.download",s,{route:"/v1/organizations/plugins/{plugin_id}/versions/{version}/content",queryParams:["organization_id"],attributes:{"anthropic.organization.plugin.id":i,"anthropic.organization.plugin.version.id":r}})})}};var C_=(()=>{class e extends Ye{}return e._errorName="BetaScanFailedError",e})(),N_=(()=>{class e extends Vr{}return e._errorName="BetaPluginNameTakenError",e})(),A_=(()=>{class e extends Vr{}return e._errorName="BetaScanPendingError",e})(),j_=(()=>{class e extends Vr{}return e._errorName="BetaSkillNameTakenError",e})(),T_=(()=>{class e extends _h{}return e._errorName="BetaRegistrationPendingError",e})(),DC=(()=>{class e extends ye{constructor(){super(...arguments),this.versions=new IC(this._client),this.installationSettings=new PC(this._client),this.shares=new $C(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/plugins",Kr({body:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.create",s,{route:"/v1/organizations/plugins",createdIDAttribute:"anthropic.organization.plugin.id"})},this._client))}retrieve(n,s={},i){const{betas:c,...d}=s??{};return this._client.get(U`/v1/organizations/plugins/${n}`,{query:d,...i,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.retrieve",i,{route:"/v1/organizations/plugins/{plugin_id}",queryParams:["organization_id"],attributes:{"anthropic.organization.plugin.id":n}})})}update(n,s,i){const{betas:c,...d}=s;return this._client.post(U`/v1/organizations/plugins/${n}`,{body:d,...i,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.update",i,{route:"/v1/organizations/plugins/{plugin_id}",attributes:{"anthropic.organization.plugin.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/plugins",Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.list",s,{route:"/v1/organizations/plugins",queryParams:["created_at[gt]","created_at[gte]","created_at[lt]","created_at[lte]","limit","marketplace_id","organization_id","owner_type","owner_user_id","page"]})})}delete(n,s={},i){const{betas:c}=s??{};return this._client.delete(U`/v1/organizations/plugins/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.delete",i,{route:"/v1/organizations/plugins/{plugin_id}",attributes:{"anthropic.organization.plugin.id":n}})})}}return e.BetaScanFailedError=C_,e.BetaPluginNameTakenError=N_,e.BetaScanPendingError=A_,e.BetaSkillNameTakenError=j_,e.BetaRegistrationPendingError=T_,e.Versions=IC,e.InstallationSettings=PC,e.Shares=$C,e})();class qC extends ye{create(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/claude_tag/slack_channels",{body:i,...n,headers:L([{"anthropic-beta":[...s??[],"experimental-claude-tag-2026-10-21"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.create",n,{route:"/v1/organizations/claude_tag/slack_channels",createdIDAttribute:"anthropic.organization.claude_tag.slack_channel.id"})})}retrieve(r,n={},s){const{betas:i,...c}=n??{};return this._client.get(U`/v1/organizations/claude_tag/slack_channels/${r}`,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.retrieve",s,{route:"/v1/organizations/claude_tag/slack_channels/{id}",queryParams:["include_inherited"],attributes:{"anthropic.organization.claude_tag.slack_channel.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/claude_tag/slack_channels/${r}`,{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.update",s,{route:"/v1/organizations/claude_tag/slack_channels/{id}",attributes:{"anthropic.organization.claude_tag.slack_channel.id":r}})})}list(r,n){const{betas:s,...i}=r;return this._client.getAPIList("/v1/organizations/claude_tag/slack_channels",Me,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"experimental-claude-tag-2026-10-21"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.list",n,{route:"/v1/organizations/claude_tag/slack_channels",queryParams:["include_inherited","limit","page","slack_channel_id","slack_workspace_id"]})})}delete(r,n={},s){const{betas:i}=n??{};return this._client.delete(U`/v1/organizations/claude_tag/slack_channels/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.delete",s,{route:"/v1/organizations/claude_tag/slack_channels/{id}",attributes:{"anthropic.organization.claude_tag.slack_channel.id":r}})})}}class LC extends ye{retrieve(r,n={},s){const{betas:i,...c}=n??{};return this._client.get(U`/v1/organizations/claude_tag/slack_workspaces/${r}`,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_workspaces.retrieve",s,{route:"/v1/organizations/claude_tag/slack_workspaces/{id}",queryParams:["include_inherited"],attributes:{"anthropic.organization.claude_tag.slack_workspace.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/claude_tag/slack_workspaces/${r}`,{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_workspaces.update",s,{route:"/v1/organizations/claude_tag/slack_workspaces/{id}",attributes:{"anthropic.organization.claude_tag.slack_workspace.id":r}})})}list(r={},n){const{betas:s,...i}=r??{};return this._client.getAPIList("/v1/organizations/claude_tag/slack_workspaces",Me,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"experimental-claude-tag-2026-10-21"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_workspaces.list",n,{route:"/v1/organizations/claude_tag/slack_workspaces",queryParams:["include_inherited","limit","page","slack_workspace_id"]})})}}class UC extends ye{create(r,n,s){const{target:i,betas:c}=n;return this._client.post(U`/v1/organizations/claude_tag/bundles/${r}/targets`,{body:i,...s,headers:L([{"anthropic-beta":[...c??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.targets.create",s,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}/targets",attributes:{"anthropic.organization.claude_tag.bundle.id":r}})})}retrieve(r,n,s){const{bundle_id:i,betas:c}=n;return this._client.get(U`/v1/organizations/claude_tag/bundles/${i}/targets/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.targets.retrieve",s,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}/targets/{target_id}",attributes:{"anthropic.organization.claude_tag.bundle.id":i,"anthropic.organization.claude_tag.bundle.target.id":r}})})}list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/claude_tag/bundles/${r}/targets`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.targets.list",s,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}/targets",queryParams:["limit","page"],attributes:{"anthropic.organization.claude_tag.bundle.id":r}})})}delete(r,n,s){const{bundle_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/claude_tag/bundles/${i}/targets/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.targets.delete",s,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}/targets/{target_id}",attributes:{"anthropic.organization.claude_tag.bundle.id":i,"anthropic.organization.claude_tag.bundle.target.id":r}})})}}var BC=(()=>{class e extends ye{constructor(){super(...arguments),this.targets=new UC(this._client)}retrieve(n,s={},i){const{betas:c}=s??{};return this._client.get(U`/v1/organizations/claude_tag/bundles/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"experimental-claude-tag-2026-10-21"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.retrieve",i,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}",attributes:{"anthropic.organization.claude_tag.bundle.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/claude_tag/bundles",Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.list",s,{route:"/v1/organizations/claude_tag/bundles",queryParams:["limit","page"]})})}}return e.Targets=UC,e})(),E_=(()=>{class e extends Ye{}return e._errorName="BetaSlackChannelSetUpSettingsRefusedError",e})(),M_=(()=>{class e extends vs{}return e._errorName="BetaAPIKeyScopeMissingError",e})(),R_=(()=>{class e extends vs{}return e._errorName="BetaClaudeTagWritesNotEnabledError",e})(),z_=(()=>{class e extends vs{}return e._errorName="BetaComplianceConfigurationRestrictedError",e})(),O_=(()=>{class e extends vs{}return e._errorName="BetaOrganizationLevelScopedAPIKeyRequiredError",e})(),P_=(()=>{class e extends Zc{}return e._errorName="BetaSlackChannelSetUpEnvironmentNotFoundError",e})(),$_=(()=>{class e extends Vr{}return e._errorName="BetaSlackChannelSetUpSettingsConflictError",e})(),GC=(()=>{class e extends ye{constructor(){super(...arguments),this.slackChannels=new qC(this._client),this.slackWorkspaces=new LC(this._client),this.bundles=new BC(this._client)}}return e.BetaSlackChannelSetUpSettingsRefusedError=E_,e.BetaAPIKeyScopeMissingError=M_,e.BetaClaudeTagWritesNotEnabledError=R_,e.BetaComplianceConfigurationRestrictedError=z_,e.BetaOrganizationLevelScopedAPIKeyRequiredError=O_,e.BetaSlackChannelSetUpEnvironmentNotFoundError=P_,e.BetaSlackChannelSetUpSettingsConflictError=$_,e.SlackChannels=qC,e.SlackWorkspaces=LC,e.Bundles=BC,e})();let HC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/spend_limits/effective",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.effective.list",n,{route:"/v1/organizations/spend_limits/effective",queryParams:["limit","page","period","user_ids"]})})}},FC=class extends ye{retrieve(r,n){return this._client.get(U`/v1/organizations/spend_limit_increase_requests/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.retrieve",n,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/spend_limit_increase_requests",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.list",n,{route:"/v1/organizations/spend_limit_increase_requests",queryParams:["actor_ids","limit","page","status"]})})}approve(r,n,s){return this._client.post(U`/v1/organizations/spend_limit_increase_requests/${r}/approve`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.approve",s,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}/approve",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}deny(r,n,s){return this._client.post(U`/v1/organizations/spend_limit_increase_requests/${r}/deny`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.deny",s,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}/deny",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}};var I_=(()=>{class e extends vs{}return e._errorName="BetaSpendLimitsAdminAPIWritesNotEnabledError",e})(),VC=(()=>{class e extends ye{constructor(){super(...arguments),this.effective=new HC(this._client),this.increaseRequests=new FC(this._client)}retrieve(n,s){return this._client.get(U`/v1/organizations/spend_limits/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.retrieve",s,{route:"/v1/organizations/spend_limits/{spend_limit_id}",attributes:{"anthropic.organization.spend_limit.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/spend_limits",Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"spend-limit-reads-2026-09-26"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.list",s,{route:"/v1/organizations/spend_limits",queryParams:["limit","page","scope_type","workspace_id"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/spend_limits/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.delete",s,{route:"/v1/organizations/spend_limits/{spend_limit_id}",attributes:{"anthropic.organization.spend_limit.id":n}})})}set(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/spend_limits",{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.set",s,{route:"/v1/organizations/spend_limits",createdIDAttribute:"anthropic.organization.spend_limit.id"})})}}return e.BetaSpendLimitsAdminAPIWritesNotEnabledError=I_,e.Effective=HC,e.IncreaseRequests=FC,e})();let KC=class extends ye{retrieve(r){return this._client.get("/v1/organizations/compliance_settings",{...r,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.compliance_settings.retrieve",r,{route:"/v1/organizations/compliance_settings"})})}update(r,n){return this._client.post("/v1/organizations/compliance_settings",{body:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.compliance_settings.update",n,{route:"/v1/organizations/compliance_settings"})})}},YC=class extends ye{create(r,n){return this._client.post("/v1/organizations/external_keys",{body:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.create",n,{route:"/v1/organizations/external_keys",createdIDAttribute:"anthropic.organization.external_key.id"})})}retrieve(r,n){return this._client.get(U`/v1/organizations/external_keys/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.retrieve",n,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":r}})})}update(r,n,s){return this._client.post(U`/v1/organizations/external_keys/${r}`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.update",s,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/external_keys",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.list",n,{route:"/v1/organizations/external_keys",queryParams:["limit","page"]})})}delete(r,n){return this._client.delete(U`/v1/organizations/external_keys/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.delete",n,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":r}})})}validate(r,n){return this._client.post(U`/v1/organizations/external_keys/${r}/validate`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.validate",n,{route:"/v1/organizations/external_keys/{external_key_id}/validate",attributes:{"anthropic.organization.external_key.id":r}})})}},WC=class extends ye{create(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/federation_issuers",{body:i,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.create",n,{route:"/v1/organizations/federation_issuers",createdIDAttribute:"anthropic.organization.federation_issuer.id"})})}retrieve(r,n={},s){const{betas:i}=n??{};return this._client.get(U`/v1/organizations/federation_issuers/${r}`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.retrieve",s,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}",attributes:{"anthropic.organization.federation_issuer.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/federation_issuers/${r}`,{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.update",s,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}",attributes:{"anthropic.organization.federation_issuer.id":r}})})}list(r={},n){const{betas:s,...i}=r??{};return this._client.getAPIList("/v1/organizations/federation_issuers",Me,{query:i,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.list",n,{route:"/v1/organizations/federation_issuers",queryParams:["include_archived","limit","page"]})})}archive(r,n={},s){const{betas:i}=n??{};return this._client.post(U`/v1/organizations/federation_issuers/${r}/archive`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.archive",s,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}/archive",attributes:{"anthropic.organization.federation_issuer.id":r}})})}},XC=class extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/federation_rules/${r}/workspaces`,Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.workspaces.list",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.federation_rule.id":r}})})}add(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/federation_rules/${r}/workspaces`,{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.workspaces.add",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces",attributes:{"anthropic.organization.federation_rule.id":r},createdIDAttribute:"anthropic.organization.federation_rule.workspace.id",createdIDField:"workspace_id"})})}remove(r,n,s){const{federation_rule_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/federation_rules/${i}/workspaces/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.workspaces.remove",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.federation_rule.id":i,"anthropic.organization.federation_rule.workspace.id":r}})})}};var QC=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new XC(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/federation_rules",{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.create",s,{route:"/v1/organizations/federation_rules",createdIDAttribute:"anthropic.organization.federation_rule.id"})})}retrieve(n,s={},i){const{betas:c}=s??{};return this._client.get(U`/v1/organizations/federation_rules/${n}`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.retrieve",i,{route:"/v1/organizations/federation_rules/{federation_rule_id}",attributes:{"anthropic.organization.federation_rule.id":n}})})}update(n,s,i){const{betas:c,...d}=s;return this._client.post(U`/v1/organizations/federation_rules/${n}`,{body:d,...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.update",i,{route:"/v1/organizations/federation_rules/{federation_rule_id}",attributes:{"anthropic.organization.federation_rule.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/federation_rules",Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.list",s,{route:"/v1/organizations/federation_rules",queryParams:["include_archived","issuer_id","limit","page"]})})}archive(n,s={},i){const{betas:c}=s??{};return this._client.post(U`/v1/organizations/federation_rules/${n}/archive`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.archive",i,{route:"/v1/organizations/federation_rules/{federation_rule_id}/archive",attributes:{"anthropic.organization.federation_rule.id":n}})})}}return e.Workspaces=XC,e})(),JC=(()=>{class e extends ye{constructor(){super(...arguments),this.issuers=new WC(this._client),this.rules=new QC(this._client)}}return e.Issuers=WC,e.Rules=QC,e})();let ZC=class extends ye{create(r,n){return this._client.post("/v1/organizations/invites",{body:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.invites.create",n,{route:"/v1/organizations/invites",createdIDAttribute:"anthropic.organization.invite.id"})})}retrieve(r,n){return this._client.get(U`/v1/organizations/invites/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.invites.retrieve",n,{route:"/v1/organizations/invites/{invite_id}",attributes:{"anthropic.organization.invite.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/invites",ns,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.invites.list",n,{route:"/v1/organizations/invites",queryParams:["after_id","before_id","email","limit","roles","statuses"]})})}delete(r,n){return this._client.delete(U`/v1/organizations/invites/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.invites.delete",n,{route:"/v1/organizations/invites/{invite_id}",attributes:{"anthropic.organization.invite.id":r}})})}};class eN extends ye{retrieve(r,n={},s){const{betas:i,...c}=n??{};return this._client.get(U`/v1/organizations/plugin_marketplaces/${r}`,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.retrieve",s,{route:"/v1/organizations/plugin_marketplaces/{marketplace_id}",queryParams:["organization_id"],attributes:{"anthropic.organization.plugin_marketplace.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/plugin_marketplaces/${r}`,{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.update",s,{route:"/v1/organizations/plugin_marketplaces/{marketplace_id}",attributes:{"anthropic.organization.plugin_marketplace.id":r}})})}list(r={},n){const{betas:s,...i}=r??{};return this._client.getAPIList("/v1/organizations/plugin_marketplaces",Me,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.list",n,{route:"/v1/organizations/plugin_marketplaces",queryParams:["limit","organization_id","owner_type","page","source"]})})}validateArchive(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/plugin_marketplaces/validate_archive",Kr({body:i,...n,headers:L([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.validate_archive",n,{route:"/v1/organizations/plugin_marketplaces/validate_archive"})},this._client))}validateRepository(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/plugin_marketplaces/validate_repository",{body:i,...n,headers:L([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.validate_repository",n,{route:"/v1/organizations/plugin_marketplaces/validate_repository"})})}}let tN=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/rate_limits",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rate_limits.list",n,{route:"/v1/organizations/rate_limits",queryParams:["group_type","limit","model","page"]})})}};class nN extends ye{create(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/webhooks",{body:i,...n,headers:L([{"anthropic-beta":[...s??[],"webhooks-2026-10-07"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.create",n,{route:"/v1/organizations/webhooks",createdIDAttribute:"anthropic.organization.webhook.id"})})}retrieve(r,n={},s){const{betas:i}=n??{};return this._client.get(U`/v1/organizations/webhooks/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"webhooks-2026-10-07"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.retrieve",s,{route:"/v1/organizations/webhooks/{webhook_endpoint_id}",attributes:{"anthropic.organization.webhook.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/webhooks/${r}`,{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"webhooks-2026-10-07"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.update",s,{route:"/v1/organizations/webhooks/{webhook_endpoint_id}",attributes:{"anthropic.organization.webhook.id":r}})})}list(r={},n){const{betas:s,...i}=r??{};return this._client.getAPIList("/v1/organizations/webhooks",ns,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"webhooks-2026-10-07"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.list",n,{route:"/v1/organizations/webhooks",queryParams:["after_id","before_id","limit","order"]})})}delete(r,n={},s){const{betas:i}=n??{};return this._client.delete(U`/v1/organizations/webhooks/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"webhooks-2026-10-07"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.delete",s,{route:"/v1/organizations/webhooks/{webhook_endpoint_id}",attributes:{"anthropic.organization.webhook.id":r}})})}regenerateSigningSecret(r,n={},s){const{betas:i}=n??{};return this._client.post(U`/v1/organizations/webhooks/${r}/regenerate_signing_secret`,{...s,headers:L([{"anthropic-beta":[...i??[],"webhooks-2026-10-07"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.regenerate_signing_secret",s,{route:"/v1/organizations/webhooks/{webhook_endpoint_id}/regenerate_signing_secret",attributes:{"anthropic.organization.webhook.id":r}})})}}let sN=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/rbac_groups/${r}/members`,Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.members.list",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members",queryParams:["limit","page"],attributes:{"anthropic.organization.rbac_group.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/rbac_groups/${r}/members`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.members.add",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members",attributes:{"anthropic.organization.rbac_group.id":r},createdIDAttribute:"anthropic.organization.rbac_group.member.id",createdIDField:"user_id"})})}remove(r,n,s){const{rbac_group_id:i}=n;return this._client.delete(U`/v1/organizations/rbac_groups/${i}/members/${r}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.members.remove",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members/{user_id}",attributes:{"anthropic.organization.rbac_group.id":i,"anthropic.organization.rbac_group.member.id":r}})})}};var aN=(()=>{class e extends ye{constructor(){super(...arguments),this.members=new sN(this._client)}create(n,s){return this._client.post("/v1/organizations/rbac_groups",{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.create",s,{route:"/v1/organizations/rbac_groups",createdIDAttribute:"anthropic.organization.rbac_group.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/rbac_groups/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.retrieve",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/rbac_groups/${n}`,{body:s,...i,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.update",i,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/rbac_groups",Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.list",s,{route:"/v1/organizations/rbac_groups",queryParams:["limit","page"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/rbac_groups/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.delete",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}}return e.Members=sN,e})();let rN=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/rbac_roles/${r}/permissions`,Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_roles.permissions.list",s,{route:"/v1/organizations/rbac_roles/{rbac_role_id}/permissions",queryParams:["limit","page"],attributes:{"anthropic.organization.rbac_role.id":r}})})}};var iN=(()=>{class e extends ye{constructor(){super(...arguments),this.permissions=new rN(this._client)}retrieve(n,s){return this._client.get(U`/v1/organizations/rbac_roles/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_roles.retrieve",s,{route:"/v1/organizations/rbac_roles/{rbac_role_id}",attributes:{"anthropic.organization.rbac_role.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/rbac_roles",Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_roles.list",s,{route:"/v1/organizations/rbac_roles",queryParams:["limit","page"]})})}}return e.Permissions=rN,e})();let oN=class extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/service_accounts/${r}/workspaces`,Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.workspaces.list",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.service_account.id":r}})})}add(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/service_accounts/${r}/workspaces`,{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.workspaces.add",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces",attributes:{"anthropic.organization.service_account.id":r},createdIDAttribute:"anthropic.organization.service_account.workspace.id",createdIDField:"workspace_id"})})}remove(r,n,s){const{service_account_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/service_accounts/${i}/workspaces/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.workspaces.remove",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.service_account.id":i,"anthropic.organization.service_account.workspace.id":r}})})}};var lN=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new oN(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/service_accounts",{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.create",s,{route:"/v1/organizations/service_accounts",createdIDAttribute:"anthropic.organization.service_account.id"})})}retrieve(n,s={},i){const{betas:c}=s??{};return this._client.get(U`/v1/organizations/service_accounts/${n}`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.retrieve",i,{route:"/v1/organizations/service_accounts/{service_account_id}",attributes:{"anthropic.organization.service_account.id":n}})})}update(n,s,i){const{betas:c,...d}=s;return this._client.post(U`/v1/organizations/service_accounts/${n}`,{body:d,...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.update",i,{route:"/v1/organizations/service_accounts/{service_account_id}",attributes:{"anthropic.organization.service_account.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/service_accounts",Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.list",s,{route:"/v1/organizations/service_accounts",queryParams:["include_archived","limit","page"]})})}archive(n,s={},i){const{betas:c}=s??{};return this._client.post(U`/v1/organizations/service_accounts/${n}/archive`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.archive",i,{route:"/v1/organizations/service_accounts/{service_account_id}/archive",attributes:{"anthropic.organization.service_account.id":n}})})}}return e.Workspaces=oN,e})();let cN=class extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/telemetry_destinations/${r}/workspaces`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.workspaces.list",s,{route:"/v1/organizations/telemetry_destinations/{destination_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.telemetry_destination.id":r}})})}add(r,n,s){const{destination_id:i,betas:c}=n;return this._client.post(U`/v1/organizations/telemetry_destinations/${i}/workspaces/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.workspaces.add",s,{route:"/v1/organizations/telemetry_destinations/{destination_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.telemetry_destination.id":i,"anthropic.organization.telemetry_destination.workspace.id":r}})})}remove(r,n,s){const{destination_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/telemetry_destinations/${i}/workspaces/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.workspaces.remove",s,{route:"/v1/organizations/telemetry_destinations/{destination_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.telemetry_destination.id":i,"anthropic.organization.telemetry_destination.workspace.id":r}})})}};var uN=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new cN(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/telemetry_destinations",{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.create",s,{route:"/v1/organizations/telemetry_destinations",createdIDAttribute:"anthropic.organization.telemetry_destination.id"})})}retrieve(n,s={},i){const{betas:c}=s??{};return this._client.get(U`/v1/organizations/telemetry_destinations/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.retrieve",i,{route:"/v1/organizations/telemetry_destinations/{destination_id}",attributes:{"anthropic.organization.telemetry_destination.id":n}})})}update(n,s,i){const{betas:c,...d}=s;return this._client.post(U`/v1/organizations/telemetry_destinations/${n}`,{body:d,...i,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.update",i,{route:"/v1/organizations/telemetry_destinations/{destination_id}",attributes:{"anthropic.organization.telemetry_destination.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/telemetry_destinations",Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.list",s,{route:"/v1/organizations/telemetry_destinations",queryParams:["limit","page","workspace_ids"]})})}delete(n,s={},i){const{betas:c}=s??{};return this._client.delete(U`/v1/organizations/telemetry_destinations/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.delete",i,{route:"/v1/organizations/telemetry_destinations/{destination_id}",attributes:{"anthropic.organization.telemetry_destination.id":n}})})}test(n,s={},i){const{betas:c}=s??{};return this._client.post(U`/v1/organizations/telemetry_destinations/${n}/test`,{...i,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.test",i,{route:"/v1/organizations/telemetry_destinations/{destination_id}/test",attributes:{"anthropic.organization.telemetry_destination.id":n}})})}}return e.Workspaces=cN,e})();let dN=class extends ye{retrieve(r,n,s){const{workspace_id:i}=n;return this._client.get(U`/v1/organizations/workspaces/${i}/members/${r}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/members/${r}`,{body:c,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/members`,ns,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/members",queryParams:["after_id","before_id","limit"],attributes:{"anthropic.organization.workspace.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/workspaces/${r}/members`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.add",s,{route:"/v1/organizations/workspaces/{workspace_id}/members",attributes:{"anthropic.organization.workspace.id":r},createdIDAttribute:"anthropic.organization.workspace.member.id",createdIDField:"user_id"})})}remove(r,n,s){const{workspace_id:i}=n;return this._client.delete(U`/v1/organizations/workspaces/${i}/members/${r}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.remove",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}},hN=class extends ye{update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/rate_limits/${r}`,{body:c,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.rate_limits.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/rate_limits/{rate_limit_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.rate_limit.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/rate_limits`,Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.rate_limits.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/rate_limits",queryParams:["group_type","include_inherited","limit","page"],attributes:{"anthropic.organization.workspace.id":r}})})}},mN=class extends ye{retrieve(r,n,s){const{workspace_id:i,betas:c}=n;return this._client.get(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}update(r,n,s){const{workspace_id:i,betas:c,...d}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{body:d,...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/service_accounts`,Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts",queryParams:["limit","page"],attributes:{"anthropic.organization.workspace.id":r}})})}add(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${r}/service_accounts`,{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.add",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts",attributes:{"anthropic.organization.workspace.id":r},createdIDAttribute:"anthropic.organization.workspace.service_account.id",createdIDField:"service_account_id"})})}remove(r,n,s){const{workspace_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.remove",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}};var fN=(()=>{class e extends ye{constructor(){super(...arguments),this.rateLimits=new hN(this._client),this.members=new dN(this._client),this.serviceAccounts=new mN(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/workspaces",{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.create",s,{route:"/v1/organizations/workspaces",createdIDAttribute:"anthropic.organization.workspace.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/workspaces/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}",attributes:{"anthropic.organization.workspace.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/workspaces/${n}`,{body:s,...i,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.update",i,{route:"/v1/organizations/workspaces/{workspace_id}",attributes:{"anthropic.organization.workspace.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/workspaces",ns,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.list",s,{route:"/v1/organizations/workspaces",queryParams:["after_id","before_id","ids","include_archived","include_default","limit"]})})}archive(n,s){return this._client.post(U`/v1/organizations/workspaces/${n}/archive`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.archive",s,{route:"/v1/organizations/workspaces/{workspace_id}/archive",attributes:{"anthropic.organization.workspace.id":n}})})}}return e.RateLimits=hN,e.Members=dN,e.ServiceAccounts=mN,e})(),pN=(()=>{class e extends ye{constructor(){super(...arguments),this.apiKeys=new bC(this._client),this.externalKeys=new YC(this._client),this.federation=new JC(this._client),this.invites=new ZC(this._client),this.serviceAccounts=new lN(this._client),this.users=new OC(this._client),this.workspaces=new fN(this._client),this.rateLimits=new tN(this._client),this.complianceSettings=new KC(this._client),this.analytics=new zC(this._client),this.spendLimits=new VC(this._client),this.rbacGroups=new aN(this._client),this.rbacRoles=new iN(this._client),this.plugins=new DC(this._client),this.pluginMarketplaces=new eN(this._client),this.telemetryDestinations=new uN(this._client),this.webhooks=new nN(this._client),this.claudeTag=new GC(this._client)}retrieve(n){return this._client.get("/v1/organizations/me",{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.retrieve",n,{route:"/v1/organizations/me"})})}}return e.APIKeys=bC,e.ExternalKeys=YC,e.Federation=JC,e.Invites=ZC,e.ServiceAccounts=lN,e.Users=OC,e.BetaCannotSignOutPrimaryOwnerError=y_,e.BetaCannotSignOutSelfError=__,e.BetaCannotSignOutManagedMemberError=v_,e.BetaCannotSignOutMembershipAdminError=w_,e.BetaCannotSignOutOwnerError=S_,e.BetaCannotSignOutPrivilegedMemberError=k_,e.Workspaces=fN,e.RateLimits=tN,e.ComplianceSettings=KC,e.Analytics=zC,e.SpendLimits=VC,e.BetaSpendLimitsAdminAPIWritesNotEnabledError=I_,e.RBACGroups=aN,e.RBACRoles=iN,e.Plugins=DC,e.BetaScanFailedError=C_,e.BetaPluginNameTakenError=N_,e.BetaScanPendingError=A_,e.BetaSkillNameTakenError=j_,e.BetaRegistrationPendingError=T_,e.PluginMarketplaces=eN,e.TelemetryDestinations=uN,e.Webhooks=nN,e.ClaudeTag=GC,e.BetaSlackChannelSetUpSettingsRefusedError=E_,e.BetaAPIKeyScopeMissingError=M_,e.BetaClaudeTagWritesNotEnabledError=R_,e.BetaComplianceConfigurationRestrictedError=z_,e.BetaOrganizationLevelScopedAPIKeyRequiredError=O_,e.BetaSlackChannelSetUpEnvironmentNotFoundError=P_,e.BetaSlackChannelSetUpSettingsConflictError=$_,e})(),gN=(()=>{class e extends ye{list(n,s={},i){const{betas:c,workspace_id:d,...f}=s??{};return this._client.getAPIList(U`/v1/sessions/${n}/events`,Me,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.events.list",i,{route:"/v1/sessions/{session_id}/events",queryParams:["created_at[gt]","created_at[gte]","created_at[lt]","created_at[lte]","limit","order","page","types"],attributes:{"anthropic.session.id":n}})})}send(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/sessions/${n}/events`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.events.send",i,{route:"/v1/sessions/{session_id}/events",attributes:{"anthropic.session.id":n}})})}stream(n,s={},i){const{betas:c,workspace_id:d,...f}=s??{};return this._client.get(U`/v1/sessions/${n}/events/stream`,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),stream:!0,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.events.stream",i,{route:"/v1/sessions/{session_id}/events/stream",queryParams:["event_deltas"],attributes:{"anthropic.session.id":n}})})}toolRunner(n,s){return new Xx(n,{...s,client:this._client})}}return e.SessionToolRunner=Xx,e})();class bN extends ye{retrieve(r,n,s){const{session_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/sessions/${i}/resources/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.retrieve",s,{route:"/v1/sessions/{session_id}/resources/{resource_id}",attributes:{"anthropic.session.id":i,"anthropic.session.resource.id":r}})})}update(r,n,s){const{session_id:i,betas:c,workspace_id:d,...f}=n;return this._client.post(U`/v1/sessions/${i}/resources/${r}`,{body:f,...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.update",s,{route:"/v1/sessions/{session_id}/resources/{resource_id}",attributes:{"anthropic.session.id":i,"anthropic.session.resource.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/sessions/${r}/resources`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.list",s,{route:"/v1/sessions/{session_id}/resources",queryParams:["limit","page"],attributes:{"anthropic.session.id":r}})})}delete(r,n,s){const{session_id:i,betas:c,workspace_id:d}=n;return this._client.delete(U`/v1/sessions/${i}/resources/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.delete",s,{route:"/v1/sessions/{session_id}/resources/{resource_id}",attributes:{"anthropic.session.id":i,"anthropic.session.resource.id":r}})})}add(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/sessions/${r}/resources`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.add",s,{route:"/v1/sessions/{session_id}/resources",attributes:{"anthropic.session.id":r},createdIDAttribute:"anthropic.session.resource.id"})})}}class xN extends ye{list(r,n,s){const{session_id:i,betas:c,workspace_id:d,...f}=n;return this._client.getAPIList(U`/v1/sessions/${i}/threads/${r}/events`,Me,{query:f,...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.events.list",s,{route:"/v1/sessions/{session_id}/threads/{thread_id}/events",queryParams:["limit","page"],attributes:{"anthropic.session.id":i,"anthropic.session.thread.id":r}})})}stream(r,n,s){const{session_id:i,betas:c,workspace_id:d,...f}=n;return this._client.get(U`/v1/sessions/${i}/threads/${r}/stream`,{query:f,...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),stream:!0,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.events.stream",s,{route:"/v1/sessions/{session_id}/threads/{thread_id}/stream",queryParams:["event_deltas"],attributes:{"anthropic.session.id":i,"anthropic.session.thread.id":r}})})}}var yN=(()=>{class e extends ye{constructor(){super(...arguments),this.events=new xN(this._client)}retrieve(n,s,i){const{session_id:c,betas:d,workspace_id:f}=s;return this._client.get(U`/v1/sessions/${c}/threads/${n}`,{...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.retrieve",i,{route:"/v1/sessions/{session_id}/threads/{thread_id}",attributes:{"anthropic.session.id":c,"anthropic.session.thread.id":n}})})}list(n,s={},i){const{betas:c,workspace_id:d,...f}=s??{};return this._client.getAPIList(U`/v1/sessions/${n}/threads`,Me,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.list",i,{route:"/v1/sessions/{session_id}/threads",queryParams:["limit","page","statuses"],attributes:{"anthropic.session.id":n}})})}archive(n,s,i){const{session_id:c,betas:d,workspace_id:f}=s;return this._client.post(U`/v1/sessions/${c}/threads/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.archive",i,{route:"/v1/sessions/{session_id}/threads/{thread_id}/archive",attributes:{"anthropic.session.id":c,"anthropic.session.thread.id":n}})})}}return e.Events=xN,e})(),_N=(()=>{class e extends ye{constructor(){super(...arguments),this.events=new gN(this._client),this.resources=new bN(this._client),this.threads=new yN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n,f={body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"}};return this._client.post("/v1/sessions",{...f,__span:N(this._client,"anthropic.sessions.create",s,{route:"/v1/sessions",attributes:VP(d),createdIDAttribute:"anthropic.session.id",request:f})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/sessions/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.retrieve",i,{route:"/v1/sessions/{session_id}",attributes:{"anthropic.session.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/sessions/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.update",i,{route:"/v1/sessions/{session_id}",attributes:{"anthropic.session.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/sessions",n8,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.list",s,{route:"/v1/sessions",queryParams:["agent_id","agent_version","created_at[gt]","created_at[gte]","created_at[lt]","created_at[lte]","deployment_id","include_archived","limit","memory_store_id","order","page","statuses"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/sessions/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.delete",i,{route:"/v1/sessions/{session_id}",attributes:{"anthropic.session.id":n}})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/sessions/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.archive",i,{route:"/v1/sessions/{session_id}/archive",attributes:{"anthropic.session.id":n}})})}}return e.Events=gN,e.Resources=bN,e.Threads=yN,e})();let vN=class extends ye{create(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/skills/${r}/versions`,Kr({body:d,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.versions.create",s,{route:"/v1/skills/{skill_id}/versions",attributes:{"anthropic.skill.id":r},createdIDAttribute:"anthropic.skill.version.id"})},this._client,!1))}retrieve(r,n,s){const{skill_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/skills/${i}/versions/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.versions.retrieve",s,{route:"/v1/skills/{skill_id}/versions/{version}",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/skills/${r}/versions`,Me,{query:d,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.versions.list",s,{route:"/v1/skills/{skill_id}/versions",queryParams:["limit","page"],attributes:{"anthropic.skill.id":r}})})}delete(r,n,s){const{skill_id:i,betas:c,workspace_id:d}=n;return this._client.delete(U`/v1/skills/${i}/versions/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.versions.delete",s,{route:"/v1/skills/{skill_id}/versions/{version}",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}download(r,n,s){const{skill_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/skills/${i}/versions/${r}/content`,{...s,headers:L([{Accept:"application/binary",...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__binaryResponse:!0,__span:N(this._client,"anthropic.skills.versions.download",s,{route:"/v1/skills/{skill_id}/versions/{version}/content",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}};var wN=(()=>{class e extends ye{constructor(){super(...arguments),this.versions=new vN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/skills",Kr({body:d,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.create",s,{route:"/v1/skills",createdIDAttribute:"anthropic.skill.id"})},this._client,!1))}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/skills/${n}`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.retrieve",i,{route:"/v1/skills/{skill_id}",attributes:{"anthropic.skill.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/skills",Me,{query:d,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.list",s,{route:"/v1/skills",queryParams:["limit","page","source"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/skills/${n}`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.delete",i,{route:"/v1/skills/{skill_id}",attributes:{"anthropic.skill.id":n}})})}}return e.Versions=vN,e})();class SN extends ye{create(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/tunnels/${r}/certificates`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.certificates.create",s,{route:"/v1/tunnels/{tunnel_id}/certificates",attributes:{"anthropic.tunnel.id":r},createdIDAttribute:"anthropic.tunnel.certificate.id"})})}retrieve(r,n,s){const{tunnel_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/tunnels/${i}/certificates/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.certificates.retrieve",s,{route:"/v1/tunnels/{tunnel_id}/certificates/{certificate_id}",attributes:{"anthropic.tunnel.id":i,"anthropic.tunnel.certificate.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/tunnels/${r}/certificates`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.certificates.list",s,{route:"/v1/tunnels/{tunnel_id}/certificates",queryParams:["include_archived","limit","page"],attributes:{"anthropic.tunnel.id":r}})})}archive(r,n,s){const{tunnel_id:i,betas:c,workspace_id:d}=n;return this._client.post(U`/v1/tunnels/${i}/certificates/${r}/archive`,{...s,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.certificates.archive",s,{route:"/v1/tunnels/{tunnel_id}/certificates/{certificate_id}/archive",attributes:{"anthropic.tunnel.id":i,"anthropic.tunnel.certificate.id":r}})})}}var kN=(()=>{class e extends ye{constructor(){super(...arguments),this.certificates=new SN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/tunnels",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.create",s,{route:"/v1/tunnels",createdIDAttribute:"anthropic.tunnel.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/tunnels/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.retrieve",i,{route:"/v1/tunnels/{tunnel_id}",attributes:{"anthropic.tunnel.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/tunnels",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.list",s,{route:"/v1/tunnels",queryParams:["include_archived","limit","page"]})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/tunnels/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.archive",i,{route:"/v1/tunnels/{tunnel_id}/archive",attributes:{"anthropic.tunnel.id":n}})})}revealToken(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/tunnels/${n}/reveal_token`,{...i,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.reveal_token",i,{route:"/v1/tunnels/{tunnel_id}/reveal_token",attributes:{"anthropic.tunnel.id":n}})})}rotateToken(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/tunnels/${n}/rotate_token`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.rotate_token",i,{route:"/v1/tunnels/{tunnel_id}/rotate_token",attributes:{"anthropic.tunnel.id":n}})})}}return e.Certificates=SN,e})();let CN=class extends ye{create(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/user_profiles/${r}/action_urls`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.action_urls.create",s,{route:"/v1/user_profiles/{user_profile_id}/action_urls",attributes:{"anthropic.user_profile.id":r}})})}};var NN=(()=>{class e extends ye{constructor(){super(...arguments),this.actionURLs=new CN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/user_profiles",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.create",s,{route:"/v1/user_profiles",createdIDAttribute:"anthropic.user_profile.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/user_profiles/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"user-profiles-2026-08-18"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.retrieve",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/user_profiles/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"user-profiles-2026-08-18"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.update",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/user_profiles",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.list",s,{route:"/v1/user_profiles",queryParams:["limit","order","order_by","page"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/user_profiles/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"user-profiles-2026-08-18"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.delete",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}createEnrollmentURL(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/user_profiles/${n}/enrollment_url`,{...i,headers:L([{"anthropic-beta":[...c??[],"user-profiles-2026-08-18"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.create_enrollment_url",i,{route:"/v1/user_profiles/{user_profile_id}/enrollment_url",attributes:{"anthropic.user_profile.id":n}})})}}return e.ActionURLs=CN,e})();class AN extends ye{create(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/vaults/${r}/credentials`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.create",s,{route:"/v1/vaults/{vault_id}/credentials",attributes:{"anthropic.vault.id":r},createdIDAttribute:"anthropic.vault.credential.id"})})}retrieve(r,n,s){const{vault_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/vaults/${i}/credentials/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.retrieve",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}update(r,n,s){const{vault_id:i,betas:c,workspace_id:d,...f}=n;return this._client.post(U`/v1/vaults/${i}/credentials/${r}`,{body:f,...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.update",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/vaults/${r}/credentials`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.list",s,{route:"/v1/vaults/{vault_id}/credentials",queryParams:["include_archived","limit","page"],attributes:{"anthropic.vault.id":r}})})}delete(r,n,s){const{vault_id:i,betas:c,workspace_id:d}=n;return this._client.delete(U`/v1/vaults/${i}/credentials/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.delete",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}archive(r,n,s){const{vault_id:i,betas:c,workspace_id:d}=n;return this._client.post(U`/v1/vaults/${i}/credentials/${r}/archive`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.archive",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}/archive",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}mcpOAuthValidate(r,n,s){const{vault_id:i,betas:c,workspace_id:d}=n;return this._client.post(U`/v1/vaults/${i}/credentials/${r}/mcp_oauth_validate`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.mcp_oauth_validate",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}/mcp_oauth_validate",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}}var jN=(()=>{class e extends ye{constructor(){super(...arguments),this.credentials=new AN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/vaults",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.create",s,{route:"/v1/vaults",createdIDAttribute:"anthropic.vault.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/vaults/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.retrieve",i,{route:"/v1/vaults/{vault_id}",attributes:{"anthropic.vault.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/vaults/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.update",i,{route:"/v1/vaults/{vault_id}",attributes:{"anthropic.vault.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/vaults",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.list",s,{route:"/v1/vaults",queryParams:["include_archived","limit","page"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/vaults/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.delete",i,{route:"/v1/vaults/{vault_id}",attributes:{"anthropic.vault.id":n}})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/vaults/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.archive",i,{route:"/v1/vaults/{vault_id}/archive",attributes:{"anthropic.vault.id":n}})})}}return e.Credentials=AN,e})(),kr,jf,Po,xc,Tf,$o,yc,Ef,TN,Mf,Rf,EN=(()=>{class e extends x_{constructor(n,s,i){super(n,{client:i}),kr.add(this),jf.set(this,void 0),Po.set(this,0),xc.set(this,[]),Tf.set(this,[]),$o.set(this,void 0),yc.set(this,[]),Ef.set(this,!1),se(this,jf,s)}get toolCalls(){return v(this,Tf,"f")}_deliverEvent(n,s){var i;se(this,Po,(i=v(this,Po,"f"),i++,i));const c=n.type==="content_block_stop"?s?.content[n.index]:void 0,d=c?.type==="tool_use"?c:void 0;d&&v(this,Tf,"f").push(d),super._deliverEvent(n,s),v(this,kr,"m",TN).call(this,n,d),v(this,kr,"m",Mf).call(this)}[(jf=new WeakMap,Po=new WeakMap,xc=new WeakMap,Tf=new WeakMap,$o=new WeakMap,yc=new WeakMap,Ef=new WeakMap,kr=new WeakSet,Symbol.asyncIterator)](){const n=super[Symbol.asyncIterator](),s={handled:v(this,Po,"f")};v(this,xc,"f").push(s);let i=!1;return{next:async()=>{i&&(i=!1,s.handled++,v(this,kr,"m",Mf).call(this));try{const c=await n.next();return i=!c.done,c.done&&v(this,kr,"m",Rf).call(this,s),c}catch(c){throw v(this,kr,"m",Rf).call(this,s),c}},return:async()=>{const c=n.return?.();return v(this,kr,"m",Rf).call(this,s),await c??{value:void 0,done:!0}}}}}return TN=function(n,s){if(v(this,Ef,"f"))return;if(n.type==="content_block_start"&&n.content_block.type==="fallback"){se(this,Ef,!0),se(this,$o,void 0);return}const i=n.type==="content_block_start"||n.type==="message_delta"&&n.delta.stop_reason==="tool_use";v(this,$o,"f")&&i&&(v(this,yc,"f").push({toolUse:v(this,$o,"f"),event:v(this,Po,"f")}),se(this,$o,void 0)),s&&se(this,$o,s)},Mf=function(){if(this.errored||this.controller.signal.aborted)return;const n=Math.min(v(this,Po,"f"),...v(this,xc,"f").map(s=>s.handled));for(;v(this,yc,"f")[0]&&v(this,yc,"f")[0].event<=n;)v(this,jf,"f").call(this,v(this,yc,"f").shift().toolUse)},Rf=function(n){const s=v(this,xc,"f").indexOf(n);s>=0&&(v(this,xc,"f").splice(s,1),v(this,kr,"m",Mf).call(this))},e})();function MN(){let e,r;return{promise:new Promise((s,i)=>{e=s,r=i}),resolve:e,reject:r}}var wn,Pn,rn,nn,Vt,Xt,zi,RN,Jb,Nd,zN,Zb,ex,ON,tx,PN;class i${constructor(r,n,s){this.fields=r,this.ownMessages=n,this.ownCreateOnly=s,this.deferredMessages=[],this.replacementHistory=null,this.createOnly=HT(r)}}var BT=(()=>{class e{constructor({params:n,options:s,threading:i,logger:c}){wn.add(this),Pn.set(this,void 0),rn.set(this,[]),nn.set(this,[]),Vt.set(this,void 0),Xt.set(this,null),zi.set(this,void 0);const{messages:d,unsupportedRequestBehavior:f,...p}=n;lp(p),this.options=s,this.unsupportedRequestBehavior=f??"error",se(this,Pn,p),se(this,Vt,i?{type:"create",replacesLostThread:!1}:{type:"never_threaded"}),se(this,zi,c),this.push(d??[])}get threading(){return v(this,Vt,"f").type==="create"||v(this,Vt,"f").type==="continue"}get previousMessageId(){return v(this,Vt,"f").type==="continue"?v(this,Vt,"f").previousMessageId:null}get messages(){const n=v(this,Xt,"f")?.replacementHistory?.slice()??[...v(this,rn,"f"),...v(this,nn,"f")].map(s=>s.param);return v(this,Xt,"f")&&n.push(...v(this,Xt,"f").deferredMessages.map(Ec)),n}get params(){const n=v(this,Vt,"f").type==="create"?v(this,Xt,"f")?.ownCreateOnly:void 0;return{...v(this,Pn,"f"),...n,messages:this.messages}}push(n){if(v(this,Xt,"f")){v(this,Xt,"f").deferredMessages.push(...n);return}for(const s of n)v(this,wn,"m",Jb).call(this,s)||v(this,nn,"f").push({param:Ec(s),reply:null})}update(n={},s={}){lp(n),se(this,Pn,{...v(this,Pn,"f"),...Go(n)}),this.options={...this.options,...Go(s)};for(const i of nx)n[i]!==void 0&&delete v(this,Xt,"f")?.ownCreateOnly[i]}fork(n=v(this,Pn,"f")){const s=new e({params:{...n,unsupportedRequestBehavior:this.unsupportedRequestBehavior},options:this.options,threading:v(this,Vt,"f").type!=="never_threaded",logger:v(this,zi,"f")});return this.threading||s.stopThreading(),v(this,Xt,"f")?.replacementHistory?se(s,nn,v(this,Xt,"f").replacementHistory.map(i=>({param:i,reply:null}))):(se(s,rn,[...v(this,rn,"f")]),se(s,nn,[...v(this,nn,"f")])),v(this,Xt,"f")&&s.push(v(this,Xt,"f").deferredMessages),s}setParams({messages:n,...s}){se(this,Pn,s),v(this,Xt,"f")&&(v(this,Xt,"f").ownCreateOnly={}),this.setMessages(n)}setMessages(n){const s=[...v(this,rn,"f"),...v(this,nn,"f")];if(v(this,Xt,"f")){const c=s.map(d=>d.param);$N(n,c)?(v(this,Xt,"f").replacementHistory=null,v(this,Xt,"f").deferredMessages=n.slice(c.length)):(v(this,Xt,"f").replacementHistory=n,v(this,Xt,"f").deferredMessages=[]);return}$N(n,v(this,rn,"f").map(c=>c.param))||(se(this,rn,[]),this.threading&&se(this,Vt,{type:"create",replacesLostThread:!1})),se(this,nn,[]);const i=new Map(s.filter(c=>c.reply).map(c=>[c.param.content,c]));for(const c of n.slice(v(this,rn,"f").length))v(this,wn,"m",Jb).call(this,c)||v(this,nn,"f").push({...i.get(c.content)??{reply:null},param:Ec(c)})}get hasTurnToSend(){return v(this,nn,"f").length>0||GT(v(this,rn,"f").at(-1)?.reply?.stop_reason)}startTurn(n,s){if(v(this,Xt,"f"))throw new De("Another `send()`, `parse()` or `stream()` is already in progress on this thread");lp(s);const i=v(this,nn,"f").length;this.push(n);const c=v(this,nn,"f").slice(i);v(this,wn,"m",zN).call(this);const d={};return s.system!==void 0&&(d.system=s.system),s.tools!==void 0&&(d.tools=s.tools),se(this,Xt,new i$({...v(this,Pn,"f"),...Go(s)},c,d))}endTurn(n){se(this,Xt,null),se(this,nn,v(this,nn,"f").filter(s=>!n.ownMessages.includes(s))),n.replacementHistory&&this.setMessages(n.replacementHistory),this.push(n.deferredMessages)}recoversFrom(n){if(!(n instanceof Gt))return!1;const s=this.unsupportedRequestBehavior==="continue_unthreaded",i=c$(n);if(i!==null&&v(this,Vt,"f").type==="continue")return i==="thread_not_found"&&v(this,Vt,"f").replacesLostThread&&s?(v(this,zi,"f").info(`The server lost the thread again right after a replay; continuing without a thread: previous_message_id=${v(this,Vt,"f").previousMessageId}`),this.stopThreading()):v(this,wn,"m",Nd).call(this,i),!0;const c=d$(n);return c!==null&&this.threading&&s?(v(this,zi,"f").info(`The server cannot thread this request; continuing without a thread: unsupported=${c.join(",")}`),this.stopThreading(),!0):!1}stopThreading(){this.threading&&se(this,Vt,{type:"unthreaded"})}recordPartialReply(n,s){v(this,wn,"m",Zb).call(this,n)||(v(this,wn,"m",ex).call(this,h$(n,s),{partial:!0}),this.previousMessageId!==null&&v(this,wn,"m",Nd).call(this,"stream_ended_before_message_stop"))}recordReply(n,s){v(this,wn,"m",Zb).call(this,s)||(v(this,wn,"m",ex).call(this,s,{partial:!1}),v(this,Vt,"f").type==="create"&&se(this,Pn,{...v(this,Pn,"f"),...n.ownCreateOnly}),this.threading&&(se(this,Vt,{type:"continue",previousMessageId:s.id,createdWith:n.createOnly,replacesLostThread:v(this,Vt,"f").type==="create"&&v(this,Vt,"f").replacesLostThread}),s.usage.iterations?.some(i=>i.type==="fallback_message")&&v(this,wn,"m",Nd).call(this,"fallback_message")),s.container&&v(this,wn,"m",ON).call(this,s.container.id))}buildCreateArguments(n,s,{stream:i}){v(this,wn,"m",tx).call(this,n.createOnly);const c=v(this,Vt,"f");let d=c.type==="continue"?[]:v(this,rn,"f").map(p=>p.param);if(c.type!=="never_threaded"){const p=v(this,rn,"f").map(b=>b.reply!==null).lastIndexOf(!0)+1;d=d.map((b,x)=>x<p?Zx(b):b)}const f={...n.fields,messages:[...d,...v(this,nn,"f").map(p=>p.param)]};if(this.threading&&!f.betas?.includes(Jx)&&(f.betas=[...f.betas??[],Jx]),c.type==="create")f.thread={type:"create"};else if(c.type==="continue"){f.thread={type:"continue",previous_message_id:c.previousMessageId};for(const p of nx)delete f[p]}return{params:f,options:v(this,wn,"m",PN).call(this,s,{stream:i})}}checkNextTurn(n){v(this,wn,"m",tx).call(this,HT({...v(this,Pn,"f"),...Go(n)}))}}return Pn=new WeakMap,rn=new WeakMap,nn=new WeakMap,Vt=new WeakMap,Xt=new WeakMap,zi=new WeakMap,wn=new WeakSet,RN=function(){for(const n of[v(this,nn,"f"),v(this,rn,"f")])for(let s=n.length-1;s>=0;s--)if(n[s].reply)return n[s].reply;return null},Jb=function(n){if("id"in n)return n.id===v(this,wn,"a",RN)?.id;const s=v(this,nn,"f").at(-1)??v(this,rn,"f").at(-1);return s?.reply!=null&&e0(n,s.param)},Nd=function(n){v(this,zi,"f").info(`Replaying the full message history under a new thread: reason=${n} previous_message_id=${this.previousMessageId}`),se(this,Vt,{type:"create",replacesLostThread:n==="thread_not_found"})},zN=function(){const n=v(this,rn,"f").at(-1);if(v(this,nn,"f").length||!n||n.reply&&!n.partial)return;n.reply&&v(this,rn,"f").pop();let s=v(this,rn,"f").length;for(;s>0&&!v(this,rn,"f")[s-1].reply;)s-=1;se(this,nn,v(this,rn,"f").splice(s)),v(this,zi,"f").info(`Re-sending the turn whose reply ended before \`message_stop\`: partial_reply_id=${n.reply?.id??null}`)},Zb=function(n){return n.stop_reason!=="refusal"||v(this,Vt,"f").type==="never_threaded"?!1:(this.previousMessageId!==null&&v(this,wn,"m",Nd).call(this,"refusal"),!0)},ex=function(n,{partial:s}){v(this,rn,"f").push(...v(this,nn,"f")),se(this,nn,[]),n&&v(this,rn,"f").push({param:Ec(n),reply:n,partial:s})},ON=function(n){const{container:s}=v(this,Pn,"f");s==null?se(this,Pn,{...v(this,Pn,"f"),container:n}):typeof s=="object"&&s.id==null&&se(this,Pn,{...v(this,Pn,"f"),container:{...s,id:n}})},tx=function(n){if(v(this,Vt,"f").type!=="continue")return;const{createdWith:s}=v(this,Vt,"f"),i=nx.filter(c=>n[c]!==s[c]);if(i.length){const c=i.map(d=>`\`${d}\``).join(" and ");throw new De(`Cannot change ${c} on a thread: the server keeps the \`system\` and \`tools\` the thread was created with. To change them, start a new thread from \`thread.params\`.`+(i.includes("tools")?" To add or remove tools on this thread, send `tool_addition` or `tool_removal` blocks in a `system` message.":""))}},PN=function(n,{stream:s}){const i={...this.options,...Go(n)};return s&&(i.headers=L([{[n_]:"stream"},i.headers])),v(this,Vt,"f").type!=="never_threaded"&&(i.headers=L([i.headers,s_("message-thread")])),this.threading&&(i.headers=l$(i.headers)),i},e})();const o$=["pause_turn","compaction"];function GT(e){return o$.some(r=>r===e)}const Jx="message-threads-2026-08-12",nx=["system","tools"];function HT(e){return{system:JSON.stringify(e.system),tools:JSON.stringify(e.tools)}}function l$(e){const r=L([e]).values.get("anthropic-beta");return r===null?e:L([e,{"anthropic-beta":Ij(r,Jx)}])}function c$(e){const r=FT(e)?.error_code;return u$.find(n=>n===r)??null}const u$=["thread_not_found","thread_already_continued","thread_continue_in_flight"];function d$(e){const r=FT(e);if(r?.error_code!=="thread_unsupported_request")return null;const n=r.unsupported;return Array.isArray(n)?n.map(String):[]}function FT(e){const n=e.error?.error?.details;return Hn(n)?n:null}function lp(e){if("thread"in e&&e.thread!==void 0)throw new TypeError("`thread` cannot be set here. The message thread sets it for each request itself.")}function Go(e){return Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))}function h$(e,r){const n=e.content.slice(0,r),s=e.content[r];return s?.type==="text"&&s.text&&n.push(s),n.length?{...e,content:n}:null}function Zx(e){if(!Hn(e))return e;const{cache_control:r,...n}=e;for(const s of["content","source","tool","definition","tool_references"]){const i=n[s];Array.isArray(i)?n[s]=i.map(Zx):Hn(i)&&(n[s]=Zx(i))}return n}function $N(e,r){return r.length<=e.length&&r.every((n,s)=>e0(n,e[s]))}function e0(e,r){const[n,s]=[Ec(e),Ec(r)];return Object.keys({...n,...s}).every(c=>n[c]===s[c]||JSON.stringify(n[c])===JSON.stringify(s[c]))}function Ec(e){return"id"in e?{role:e.role,content:e.content}:e}function IN(e){return e===void 0?[]:qx(e)?e:[e]}function VT(e){const{stream:r,max_iterations:n,runToolsEagerly:s,thread:i,...c}=e;if(i!==void 0&&i!==!1)throw new TypeError("`thread` cannot be set in the params of a tool runner. The runner sets it for each request itself. To run without a message thread, pass `thread: false`.");return{settings:{stream:r,max_iterations:n,runToolsEagerly:s},thread:i,threadParams:c}}var mt,_c,Io,nt,Cr,Xn,zf,va,ps,Nr,Qa,Oi,Ad,Ar,$s,Ja,vc,wc,Do,jd,sx,Of,DN,ax,rx,qN,Td,Pf,LN,UN,ix,$f,If,BN,ox;const GN="a tool runner's toolsets come only from its tools param; change them with setMessagesParams(), or build a new runner",m$="a tool runner's toolsets come only from its tools param; remove it there with setMessagesParams(), or build a new runner without it";var ey=(()=>{class e{constructor(n,s,i){mt.add(this),_c.set(this,!1),Io.set(this,!1),nt.set(this,void 0),Cr.set(this,void 0),Xn.set(this,void 0),zf.set(this,void 0),va.set(this,void 0),ps.set(this,void 0),Nr.set(this,void 0),Qa.set(this,void 0),Oi.set(this,void 0),Ad.set(this,0),Ar.set(this,void 0),$s.set(this,{status:"idle"}),Ja.set(this,void 0),vc.set(this,null),wc.set(this,new Map),Do.set(this,[]);const{thread:c,settings:d}="_state"in n?{thread:n,settings:s}:n.beta.messages._toolRunnerThread(s);HN(c._state.params),FN(d),se(this,nt,c),se(this,Cr,Go(d));const{tools:f,messages:p}=c._state.params,b=lT(f,p);"_state"in n||c._state.setMessages(JSON.parse(JSON.stringify(VN(p)))),se(this,Xn,{...i}),se(this,zf,L([s_("BetaToolRunner"),b.length?{[vh]:b.join(", ")}:void 0])),se(this,Oi,MN())}async*[(_c=new WeakMap,Io=new WeakMap,nt=new WeakMap,Cr=new WeakMap,Xn=new WeakMap,zf=new WeakMap,va=new WeakMap,ps=new WeakMap,Nr=new WeakMap,Qa=new WeakMap,Oi=new WeakMap,Ad=new WeakMap,Ar=new WeakMap,$s=new WeakMap,Ja=new WeakMap,vc=new WeakMap,wc=new WeakMap,Do=new WeakMap,mt=new WeakSet,jd=function(s){return v(this,Ar,"f")?Hs.with(v(this,Ar,"f"),s):s()},Symbol.asyncIterator)](){var n;if(v(this,_c,"f"))throw new De("Cannot iterate over a consumed stream");se(this,_c,!0),se(this,Io,!0),se(this,Qa,void 0);const s=zt(v(this,nt,"f")._client,()=>t8(v(this,nt,"f")._client,this.params,v(this,Xn,"f").openTelemetry?.conversationId));se(this,Ar,s&&ll.setSpan(Hs.active(),s));try{for(;;)try{if(v(this,Cr,"f").max_iterations&&v(this,Ad,"f")>=v(this,Cr,"f").max_iterations)break;if(v(this,mt,"m",BN).call(this),v(this,$s,"f").status==="scheduled"&&WN(v(this,vc,"f"))!=="resume"){yield*v(this,mt,"m",rx).call(this,v(this,$s,"f").config);continue}se(this,Io,!1,"f"),se(this,Qa,void 0,"f"),se(this,Ad,(n=v(this,Ad,"f"),n++,n),"f"),se(this,ps,void 0,"f"),yield*v(this,mt,"m",sx).call(this,v(this,nt,"f"));const i=v(this,va,"f");if(se(this,va,void 0,"f"),await v(this,mt,"m",jd).call(this,async()=>{let d;if(v(this,Io,"f"))se(this,vc,null,"f"),v(this,Nr,"f")?.abort(),v(this,nt,"f")._state.checkNextTurn(Ed(v(this,nt,"f"))),v(this,nt,"f")._state.setMessages(i),d=i.at(-1);else{const p=await v(this,ps,"f"),b=WN(p.stop_reason);if(se(this,vc,p.stop_reason,"f"),b==="stop")return"stop";if(b==="resume")return"continue";d=y$(v(this,nt,"f").messages)}KN(d)&&v(this,nt,"f")._state.checkNextTurn(Ed(v(this,nt,"f")));const f=await v(this,mt,"m",ix).call(this,d,v(this,Xn,"f").signal,v(this,Ar,"f"));if(f){const p=v(this,nt,"f").messages,b=p.map(x=>x.role).lastIndexOf("assistant")+1;v(this,nt,"f")._state.setMessages([...p.slice(0,b),f,...p.slice(b)])}else if(!v(this,Io,"f")&&!v(this,nt,"f")._state.hasTurnToSend)return"stop";return"continue"})==="stop"){yield*v(this,mt,"m",UN).call(this);break}}finally{v(this,Nr,"f")?.abort(),se(this,Nr,void 0,"f")}if(await v(this,mt,"m",ax).call(this),!v(this,ps,"f"))throw new De("ToolRunner concluded without a message from the server");v(this,Oi,"f").resolve(await v(this,ps,"f")),zt(v(this,nt,"f")._client,()=>s?.setStatus({code:ol.OK}))}catch(i){throw s&&zt(v(this,nt,"f")._client,()=>Ui(s,i)),se(this,_c,!1),se(this,va,void 0),v(this,Oi,"f").promise.catch(()=>{}),v(this,Oi,"f").reject(i),se(this,Oi,MN()),i}finally{zt(v(this,nt,"f")._client,()=>s?.end()),se(this,Ar,void 0)}}setMessagesParams(n){const s=typeof n=="function"?n(this.params):n;if(HN(s),v(this,$s,"f").status!=="idle"&&lx(s),v(this,$s,"f").status==="in_flight"&&!p$(s.messages,v(this,nt,"f").messages))throw new De(f$);const{settings:i,threadParams:c}=VT(s);FN(i),se(this,Cr,Go(i)),v(this,va,"f")?(se(this,va,c.messages),v(this,nt,"f")._state.setParams({...c,messages:v(this,nt,"f").messages})):v(this,nt,"f")._state.setParams(c),se(this,Io,!0),se(this,Qa,void 0)}setRequestOptions(n){typeof n=="function"?se(this,Xn,n(v(this,Xn,"f"))):se(this,Xn,{...v(this,Xn,"f"),...n})}async generateToolResponse(n=v(this,Xn,"f").signal){const s=v(this,nt,"f")._client._tracer?Hs.active():void 0,i=await v(this,ps,"f")??v(this,nt,"f").messages.at(-1);return i?v(this,mt,"m",ix).call(this,i,n,s):null}deferToolCall(n){const s=typeof n=="string"?n:n.id;v(this,Ja,"f")&&!v(this,Ja,"f").has(s)&&v(this,Ja,"f").set(s,{status:"held"})}get deferredToolCalls(){const n=v(this,Nr,"f"),s=v(this,Ja,"f");return!(n instanceof EN)||!s?[]:n.toolCalls.filter(i=>s.get(i.id)?.status==="held")}done(){return v(this,Oi,"f").promise}async runUntilDone(){if(!v(this,_c,"f"))for await(const n of this);return this.done()}get params(){return{...v(this,nt,"f")._state.params,...v(this,va,"f")&&{messages:[...v(this,va,"f")]},...v(this,Cr,"f")}}pushMessages(...n){this.setMessagesParams(s=>({...s,messages:[...s.messages,...n]}))}compactBeforeNextTurn(n){v(this,$s,"f").status!=="in_flight"&&(lx(this.params),se(this,$s,{status:"scheduled",config:n??{type:"summarize"}}))}addTools(...n){const s=v(this,mt,"m",$f).call(this);for(const i of n){if(dh(i))throw new op(`addTools() can't add the '${Bi(Yc(i))}' toolset: ${GN}`);const c=_$(i);if(s.has(c))throw new op(`addTools() can't replace the '${Bi(c)}' toolset: ${GN}`)}for(const i of n)"name"in i&&v(this,wc,"f").set(i.name,"run"in i?i:null),v(this,Do,"f").push({type:"addition",tool:i})}removeTools(...n){const s=v(this,mt,"m",$f).call(this);for(const i of n){const c=typeof i=="string"?i:i.name;if(s.has(c))throw new op(`removeTools() can't remove the '${Bi(c)}' toolset: ${m$}`)}for(const i of n){const c=typeof i=="string"?i:i.name;v(this,wc,"f").set(c,null),v(this,Do,"f").push({type:"removal",name:c})}}then(n,s){return this.runUntilDone().then(n,s)}}return sx=async function*(n){await v(this,mt,"m",ax).call(this),se(this,Ja,void 0);const s=n.messages;s.some(b$)&&v(this,mt,"m",jd).call(this,()=>n._state.setMessages(VN(s)));const{tools:i}=n._state.params;v(this,Cr,"f").stream?(se(this,Nr,v(this,mt,"m",jd).call(this,()=>v(this,Cr,"f").runToolsEagerly?v(this,mt,"m",DN).call(this,n):n.stream(void 0,Ed(n),v(this,mt,"m",Of).call(this,n)))),i&&n.update({tools:i}),n===v(this,nt,"f")&&se(this,va,n.messages),se(this,ps,v(this,Nr,"f").finalMessage()),v(this,ps,"f").catch(()=>{}),yield v(this,Nr,"f")):(se(this,ps,v(this,mt,"m",jd).call(this,()=>n.send(void 0,Ed(n),v(this,mt,"m",Of).call(this,n)))),i&&n.update({tools:i}),n===v(this,nt,"f")&&se(this,va,n.messages),yield v(this,ps,"f"))},Of=function(n){const{headers:s=n._state.options.headers}=v(this,Xn,"f");return{...v(this,Xn,"f"),headers:L([v(this,zf,"f"),s])}},DN=function(n){const s=new Map;se(this,Ja,s);const i=new Map,c=f=>{const p=s.has(f.id),b=!f.toolset_name&&v(this,mt,"m",$f).call(this).has(f.name),x=b?f.name:f.toolset_name;if(x){if(p||b||i.has(x)){i.set(x,"waiting");return}i.set(x,"running");const _=KT(v(this,mt,"m",If).call(this),x,f,v(this,Xn,"f"),v(this,nt,"f")._client,v(this,Ar,"f"));s.set(f.id,{status:"started",result:_}),_.then(({is_error:y})=>{y||i.get(x)==="waiting"?i.set(x,"waiting"):i.delete(x)},()=>i.set(x,"waiting"));return}if(p)return;const g=YT(v(this,mt,"m",Td).call(this),v(this,mt,"m",Pf).call(this),f,v(this,Xn,"f"),v(this,nt,"f")._client,v(this,Ar,"f"));g.catch(()=>{}),s.set(f.id,{status:"started",result:g})},d=new EN(n._state.params,c,n._client);return n._stream(d,void 0,Ed(n),v(this,mt,"m",Of).call(this,n)),d},ax=async function(){const n=[...v(this,Ja,"f")?.values()??[]].filter(s=>s.status==="started");await Promise.allSettled(n.map(s=>s.result))},rx=async function*(n){lx(this.params),se(this,$s,{status:"in_flight"}),se(this,Qa,void 0);const s=v(this,ps,"f"),i=v(this,mt,"m",qN).call(this,n),c=v(this,nt,"f").messages.length;try{yield*v(this,mt,"m",sx).call(this,i);const d=await v(this,ps,"f");if(d.content.some(f=>f.type==="compaction"&&f.content)){v(this,mt,"m",LN).call(this);const f={role:d.role,content:d.content},p=v(this,nt,"f").messages.slice(c).filter(b=>!e0(b,f));v(this,nt,"f")._state.setMessages([f,...p])}else it(v(this,nt,"f")._client).warn("Compaction produced no summary; keeping the conversation as it is."),se(this,ps,s,"f")}finally{se(this,$s,{status:"idle"}),i._state.threading||v(this,nt,"f")._state.stopThreading()}},qN=function(n){const{messages:s,...i}=g$(v(this,nt,"f")._state.params),c=v(this,nt,"f").fork();return c._state=v(this,nt,"f")._state.fork({...i,compaction:n}),c},Td=function(){const n=new Map;for(const s of v(this,nt,"f")._state.params.tools??[])"run"in s&&"name"in s&&n.set(s.name,s);for(const[s,i]of v(this,wc,"f"))i?n.set(s,i):n.delete(s);return n},Pf=function(){const n=new Set(v(this,mt,"m",Td).call(this).keys());for(const s of[...this.params.messages,v(this,mt,"m",ox).call(this)])if(Array.isArray(s.content)){for(const i of s.content)if(s.role==="system")YN(i,n);else if(s.role==="assistant"&&i.type==="compaction")for(const c of i.tool_changes??[])YN(c,n)}return n},LN=function(){const n=v(this,mt,"m",Pf).call(this);for(const s of v(this,mt,"m",Td).call(this).keys())n.has(s)||v(this,wc,"f").set(s,null)},UN=async function*(){if(v(this,$s,"f").status==="scheduled"){if(KN(v(this,nt,"f").messages.at(-1))){it(v(this,nt,"f")._client).warn("The pending compaction was skipped because the last turn ended with tool calls that were not run. Call `compactBeforeNextTurn()` again if you continue the conversation."),se(this,$s,{status:"idle"});return}yield*v(this,mt,"m",rx).call(this,v(this,$s,"f").config)}},ix=async function(n,s,i){return v(this,Qa,"f")!==void 0?v(this,Qa,"f"):(se(this,Qa,x$(v(this,mt,"m",If).call(this),v(this,mt,"m",Td).call(this),v(this,mt,"m",Pf).call(this),n,{...v(this,Xn,"f"),signal:s},v(this,Ja,"f"),v(this,nt,"f")._client,i)),v(this,Qa,"f"))},$f=function(){return new Set(v(this,mt,"m",If).call(this).tools.filter(dh).map(Yc))},If=function(){return{...this.params,tools:v(this,nt,"f")._state.params.tools??[]}},BN=function(){v(this,vc,"f")==="pause_turn"||v(this,Do,"f").length===0||(v(this,nt,"f").append(v(this,mt,"m",ox).call(this)),se(this,Do,[]))},ox=function(){const n=[];for(const s of v(this,Do,"f")){if(s.type==="removal"){n.push({type:"tool_removal",tool:{type:"tool_reference",name:s.name}});continue}const i=D_(s.tool);n.push({type:"tool_addition",tool:{type:"tool_definition",definition:i}})}return{role:"system",content:n}},e})();const f$="Message params can't be changed while the conversation is being compacted, because the compaction response is about to replace them. Change them after this iteration instead.";function p$(e,r){return e.length===r.length&&e.every((n,s)=>e0(n,r[s]))}function HN(e){if("compaction"in e&&e.compaction!=null)throw new De("`compaction` cannot be set on a tool runner: every request in the loop would compact again. Call `runner.compactBeforeNextTurn()` when the conversation should be compacted instead.")}function FN(e){if(e.runToolsEagerly&&!e.stream)throw new TypeError("`runToolsEagerly: true` needs `stream: true` in the tool runner's params, because a reply that isn't streamed arrives whole.")}function lx(e){if(e.context_management?.edits?.some(r=>r.type.startsWith("compact_")))throw new De("`compactBeforeNextTurn()` can't be used while `context_management` has a compaction edit, because the API doesn't accept a compaction block together with one. Remove the edit first.")}function g$(e){const{context_management:r,stop_sequences:n,output_format:s,...i}=e,c=({format:d,...f})=>f;return(i.tool_choice?.type==="any"||i.tool_choice?.type==="tool")&&delete i.tool_choice,i.output_config&&(i.output_config=c(i.output_config)),Array.isArray(i.fallbacks)&&(i.fallbacks=i.fallbacks.map(d=>d.output_config?{...d,output_config:c(d.output_config)}:d)),i}function D_(e){if(!("run"in e))return e;const r=A$,n="toJSON"in e&&typeof e.toJSON=="function"?e.toJSON():e;return{...Object.fromEntries(Object.entries(n).filter(([s])=>r.includes(s))),...Ho(e)&&{[Ir]:e[Ir]}}}function Ed(e){const{tools:r}=e._state.params;return r?{tools:r.map(D_)}:{}}function VN(e){return e.map(r=>{if(r.role!=="system"||!Array.isArray(r.content))return r;const n=r.content.map(s=>s.type==="tool_addition"&&s.tool.type==="tool_definition"?{...s,tool:{...s.tool,definition:D_(s.tool.definition)}}:s);return{...r,content:n}})}function b$(e){return e.role==="system"&&Array.isArray(e.content)&&e.content.some(r=>r.type==="tool_addition"&&r.tool.type==="tool_definition"&&"run"in r.tool.definition)}async function x$(e,r,n,s,i,c,d,f){if(!s||s.role!=="assistant"||!s.content||typeof s.content=="string")return null;const p=s.content.filter(g=>g.type==="tool_use");if(p.length===0)return null;const b=new Map;return{role:"user",content:await Promise.all(p.map(async g=>{const _=c?.get(g.id),y=_?.status==="started"?_.result:void 0;if(g.toolset_name){const E=g.toolset_name,T=b.get(E)??{tail:Promise.resolve(),failed:!1};b.set(E,T);const j=e.tools.some(z=>dh(z)&&Yc(z)===E),q=y??T.tail.then(()=>T.failed?kp(g,n$(E),!0):KT(e,E,g,i,d,f));return T.tail=q.then(({is_error:z})=>{z&&j&&(T.failed=!0)},()=>{T.failed=!0}),c?.set(g.id,{status:"started",result:q}),q}if(y)return y;if(!(n.has(g.name)?r.get(g.name):void 0)&&e.tools.some(E=>dh(E)&&Yc(E)===g.name)){const E=b.get(g.name)??{tail:Promise.resolve(),failed:!1};return b.set(g.name,E),E.tail=E.tail.then(()=>{E.failed=!0}),w$(g)}const k=YT(r,n,g,i,d,f);return c?.set(g.id,{status:"started",result:k}),k}))}}async function KT(e,r,n,s,i,c){const d=e.tools.find(b=>dh(b)&&Yc(b)===r);if(!d)return kp(n,`Error: Toolset '${Bi(r)}' member '${Bi(n.name)}' not found`,!0);const f={signal:s?.signal,conversationId:s?.openTelemetry?.conversationId,parentContext:c};return(await a_(i,d,n,f,async()=>{const b=await r$(d,n,{signal:s?.signal});return{block:b,content:b.content??[],isError:b.is_error===!0}})).block}async function YT(e,r,n,s,i,c){const d=r.has(n.name)?e.get(n.name):void 0;if(!d)return v$(n);const f={signal:s?.signal,conversationId:s?.openTelemetry?.conversationId,parentContext:c},p=await a_(i,d,n,f,()=>RT(d,n.input,{toolUse:n,toolUseBlock:n,signal:s?.signal}));return{type:"tool_result",tool_use_id:n.id,content:p.content,...p.isError?{is_error:!0}:void 0}}function y$(e){for(let r=e.length-1;r>=0;r--){const n=e[r];if(n.role==="assistant")return n;if(n.role==="user"&&Array.isArray(n.content)&&n.content.some(s=>s.type==="tool_result"))return}}function KN(e){return Array.isArray(e?.content)&&e.content.some(r=>r.type==="tool_use")}function _$(e){return(e.type??"custom").replace(/_\d{8}$/,"").replace(/_toolset$/,"")}function v$(e){return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool '${e.name}' not found`,is_error:!0}}function w$(e){return{type:"tool_result",tool_use_id:e.id,content:`Error: the '${Bi(e.name)}' toolset could not run this call${S$(e.input)}; nothing in the batch was executed`,is_error:!0}}function S$(e){const r=typeof e=="object"&&e!==null?e:{};if(!("actions"in r)){const c="action"in r?r.action:void 0;return typeof c=="string"?`: the call has no 'actions' list (action: '${Bi(c)}')`:": the call has no 'actions' list"}const{actions:n}=r;if(typeof n=="string")return": 'actions' is text, not a list of actions";if(!Array.isArray(n))return": 'actions' is not a list of actions";if(n.length===0)return": the 'actions' list is empty";const s=[];for(const[c,d]of n.entries()){const f=typeof d=="object"&&d!==null&&"action"in d?d.action:void 0;if(typeof f!="string")return`: action ${c} must be an object with a string 'action' field`;s.push(`'${Bi(f)}'`)}const i=s.length>10?`, and ${s.length-10} more`:"";return`: its actions could not be run as sent (actions: ${s.slice(0,10).join(", ")}${i})`}function YN(e,r){switch(e.type){case"tool_removal":case"tool_addition":k$(e,r);break}}function k$(e,r){const n=C$(e.tool);n!==void 0&&(e.type==="tool_removal"?r.delete(n):r.add(n))}function C$(e){switch(e.type){case"tool_reference":return e.name;case"tool_definition":return"name"in e.definition?e.definition.name:void 0;default:return}}function WN(e){if(e===null)return"stop";if(GT(e))return"resume";switch(e){case"tool_use":return"run_tools";case"end_turn":case"stop_sequence":case"max_tokens":case"model_context_window_exceeded":case"refusal":return"stop";default:return"stop"}}class hh{constructor(r,n,s){if(!r._supportsMessageThreads)throw new De("Message threads are not available on this client; use `client.beta.messages.create()` with the full `messages` instead");b_(n),this._client=r,this._state=new BT({params:n,options:s??{},threading:!0,logger:it(r)})}static _fromState(r,n){const s=Object.create(hh.prototype);return Object.assign(s,{_client:r,_state:n})}get messages(){return this._state.messages}get previousMessageId(){return this._state.previousMessageId}get params(){return{...this._state.params,unsupportedRequestBehavior:this._state.unsupportedRequestBehavior}}append(...r){this._state.push(r)}send(r,n={},s={}){return this._send(r,n,s,i=>i)}parse(r,n={},s={}){return this._send(r,n,s,i=>g_(i,this._state.params,{logger:it(this._client)}))}_send(r,n,s,i){const c=this._state.startTurn(IN(r),n),d=(async()=>{try{const{request:f,props:p}=await this._createWithRecovery(c,s,{stream:!1}),b=await f;return this._state.recordReply(c,b),{props:p,reply:b}}finally{this._state.endTurn(c)}})();return new ch(this._client,d.then(({props:f})=>f),async()=>{const{props:f,reply:p}=await d;return Xp(i(p),f.response)})}stream(r,n={},s={}){const i=new x_(this._state.params,{logger:it(this._client),client:this._client});return this._stream(i,r,n,s),i}_stream(r,n,s,i){const c=this._state.startTurn(IN(n),s);let d,f=0,p=!1;r.on("streamEvent",(g,_)=>{p||(d=_,g.type==="content_block_stop"&&(f+=1),g.type==="message_stop"&&(p=!0,this._state.recordReply(c,_),this._state.endTurn(c)))});const b=()=>{p||(p=!0,d&&this._state.recordPartialReply(d,f),this._state.endTurn(c))};r.controller.signal.addEventListener("abort",b,{once:!0});const x=(g,_)=>new ch(this._client,this._createWithRecovery(c,{...i,signal:_?.signal},{stream:!0}).then(({props:y})=>y));r._start(x,this._state.params,{signal:i.signal??this._state.options.signal},b)}update(r={},n={}){this._state.update(r,n)}toolRunner(r={},n={}){return lp(r),new ey(this,r,n)}fork(){return hh._fromState(this._client,this._state.fork())}async _createWithRecovery(r,n,{stream:s}){for(;;){const{params:i,options:c}=this._state.buildCreateArguments(r,n,{stream:s}),d=this._client.beta.messages.create({...i,stream:s},c);try{return{request:d,props:await d._responseProps()}}catch(f){if(!this._state.recoversFrom(f))throw f}}}}const XN={"claude-sonnet-4-5":"November 30th, 2026","claude-sonnet-4-5-20250929":"November 30th, 2026"},N$=["claude-mythos-preview","claude-opus-4-6"];var QN=(()=>{class e extends ye{constructor(){super(...arguments),this.batches=new hC(this._client)}create(n,s){const i=Qx(n),{betas:c,user_profile_id:d,workspace_id:f,...p}=i;p.model in XN&&console.warn(`The model '${p.model}' is deprecated and will reach end-of-life on ${XN[p.model]}
525
+ ${g}`)}return d},U=s8(dT);var r_=(()=>{class e extends Ye{}return e._errorName="FileNotDownloadableError",e})(),i_=(()=>{class e extends Ye{}return e._errorName="StorageQuotaExceededError",e})(),o_=(()=>{class e extends Zc{}return e._errorName="FileExpiredError",e})(),Pk=(()=>{class e extends ye{list(n={},s){const{workspace_id:i,...c}=n??{};return this._client.getAPIList("/v1/files",Me,{query:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.files.list",s,{route:"/v1/files",queryParams:["ids","limit","page"]})})}delete(n,s={},i){const{workspace_id:c}=s??{};return this._client.delete(U`/v1/files/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.files.delete",i,{route:"/v1/files/{file_id}",attributes:{"anthropic.file.id":n}})})}download(n,s={},i){const{workspace_id:c}=s??{};return this._client.get(U`/v1/files/${n}/content`,{...i,headers:L([{Accept:"application/binary",...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__binaryResponse:!0,__span:N(this._client,"anthropic.files.download",i,{route:"/v1/files/{file_id}/content",attributes:{"anthropic.file.id":n}})})}retrieveMetadata(n,s={},i){const{workspace_id:c}=s??{};return this._client.get(U`/v1/files/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.files.retrieve_metadata",i,{route:"/v1/files/{file_id}",attributes:{"anthropic.file.id":n}})})}upload(n,s){const{workspace_id:i,...c}=n;return this._client.post("/v1/files",Kr({body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},uT(c.file),s?.headers]),__span:N(this._client,"anthropic.files.upload",s,{route:"/v1/files",createdIDAttribute:"anthropic.file.id"})},this._client))}}return e.FileNotDownloadableError=r_,e.StorageQuotaExceededError=i_,e.FileExpiredError=o_,e})(),hT=(()=>{class e extends Ye{}return e._errorName="ClaudeCodeKeyCreatorNotMemberError",e})(),mT=(()=>{class e extends Ye{}return e._errorName="ClaudeCodeVersionTooOldError",e})(),fT=(()=>{class e extends Ye{}return e._errorName="CMEKKeyDisabledError",e})(),pT=(()=>{class e extends Ye{}return e._errorName="CMEKKeyNetworkBlockedError",e})(),gT=(()=>{class e extends Ye{}return e._errorName="OrganizationOnHoldError",e})(),bT=(()=>{class e extends Ye{}return e._errorName="OrganizationTypeNotSupportedError",e})(),xT=(()=>{class e extends Ye{}return e._errorName="RequestBodyEncodingInvalidError",e})(),yT=(()=>{class e extends Ye{}return e._errorName="RequestBodyEncodingUnsupportedError",e})(),_T=(()=>{class e extends vs{}return e._errorName="SandboxEgressRestrictedError",e})(),vT=(()=>{class e extends qy{}return e._errorName="RequestBodyTooLargeAfterDecodingError",e})(),wT=(()=>{class e extends Hp{}return e._errorName="EnforcedSpendLimitReachedError",e})(),ST=(()=>{class e extends Hp{}return e._errorName="RampLimitExceededError",e})(),kT=(()=>{class e extends _h{}return e._errorName="CMEKContextUnavailableError",e})(),CT=(()=>{class e extends _h{}return e._errorName="CMEKKeyUnreachableError",e})();class $k extends ye{retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/deployment_runs/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployment_runs.retrieve",s,{route:"/v1/deployment_runs/{deployment_run_id}",attributes:{"anthropic.deployment_run.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/deployment_runs",Me,{query:c,...n,headers:L([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployment_runs.list",n,{route:"/v1/deployment_runs",queryParams:["created_at[gt]","created_at[gte]","created_at[lt]","created_at[lte]","deployment_id","has_error","limit","page","trigger_type"]})})}}class Ik extends ye{create(r,n){const{betas:s,workspace_id:i,...c}=r;return this._client.post("/v1/deployments",{body:c,...n,headers:L([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.create",n,{route:"/v1/deployments",createdIDAttribute:"anthropic.deployment.id"})})}retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/deployments/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.retrieve",s,{route:"/v1/deployments/{deployment_id}",attributes:{"anthropic.deployment.id":r}})})}update(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/deployments/${r}`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.update",s,{route:"/v1/deployments/{deployment_id}",attributes:{"anthropic.deployment.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/deployments",Me,{query:c,...n,headers:L([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.list",n,{route:"/v1/deployments",queryParams:["agent_id","created_at[gte]","created_at[lte]","include_archived","limit","page","status"]})})}archive(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/deployments/${r}/archive`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.archive",s,{route:"/v1/deployments/{deployment_id}/archive",attributes:{"anthropic.deployment.id":r}})})}pause(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/deployments/${r}/pause`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.pause",s,{route:"/v1/deployments/{deployment_id}/pause",attributes:{"anthropic.deployment.id":r}})})}run(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/deployments/${r}/run`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.run",s,{route:"/v1/deployments/{deployment_id}/run",attributes:{"anthropic.deployment.id":r}})})}unpause(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/deployments/${r}/unpause`,{...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.deployments.unpause",s,{route:"/v1/deployments/{deployment_id}/unpause",attributes:{"anthropic.deployment.id":r}})})}}class Dk extends ye{create(r,n){const{betas:s,workspace_id:i,...c}=r;return this._client.post("/v1/dreams",{body:c,...n,headers:L([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.create",n,{route:"/v1/dreams",createdIDAttribute:"anthropic.dream.id"})})}retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/dreams/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.retrieve",s,{route:"/v1/dreams/{dream_id}",attributes:{"anthropic.dream.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/dreams",Me,{query:c,...n,headers:L([{"anthropic-beta":[...s??[],"dreaming-2026-04-21"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.list",n,{route:"/v1/dreams",queryParams:["created_at[gt]","created_at[lt]","include_archived","limit","page","statuses"]})})}archive(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/dreams/${r}/archive`,{...s,headers:L([{"anthropic-beta":[...i??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.archive",s,{route:"/v1/dreams/{dream_id}/archive",attributes:{"anthropic.dream.id":r}})})}cancel(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/dreams/${r}/cancel`,{...s,headers:L([{"anthropic-beta":[...i??[],"dreaming-2026-04-21"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.dreams.cancel",s,{route:"/v1/dreams/{dream_id}/cancel",attributes:{"anthropic.dream.id":r}})})}}class qk extends ye{list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/files",Me,{query:c,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.files.list",n,{route:"/v1/files",queryParams:["ids","limit","page","scope_id"]})})}delete(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.delete(U`/v1/files/${r}`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.files.delete",s,{route:"/v1/files/{file_id}",attributes:{"anthropic.file.id":r}})})}download(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/files/${r}/content`,{...s,headers:L([{Accept:"application/binary",...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__binaryResponse:!0,__span:N(this._client,"anthropic.files.download",s,{route:"/v1/files/{file_id}/content",attributes:{"anthropic.file.id":r}})})}retrieveMetadata(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/files/${r}`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.files.retrieve_metadata",s,{route:"/v1/files/{file_id}",attributes:{"anthropic.file.id":r}})})}upload(r,n){const{betas:s,workspace_id:i,...c}=r;return this._client.post("/v1/files",Kr({body:c,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},uT(c.file),n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.files.upload",n,{route:"/v1/files",createdIDAttribute:"anthropic.file.id"})},this._client))}}let Lk=class extends ye{retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/models/${r}`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.models.retrieve",s,{route:"/v1/models/{model_id}",attributes:{"anthropic.model.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/models",ns,{query:c,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.models.list",n,{route:"/v1/models",queryParams:["after_id","before_id","lifecycle","limit"]})})}};var Mo={},hs={},Uk;function a8(){if(Uk)return hs;Uk=1;var e=hs&&hs.__extends||(function(){var x=function(g,_){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,S){y.__proto__=S}||function(y,S){for(var k in S)S.hasOwnProperty(k)&&(y[k]=S[k])},x(g,_)};return function(g,_){x(g,_);function y(){this.constructor=g}g.prototype=_===null?Object.create(_):(y.prototype=_.prototype,new y)}})();Object.defineProperty(hs,"__esModule",{value:!0});var r=256,n=(function(){function x(g){g===void 0&&(g="="),this._paddingCharacter=g}return x.prototype.encodedLength=function(g){return this._paddingCharacter?(g+2)/3*4|0:(g*8+5)/6|0},x.prototype.encode=function(g){for(var _="",y=0;y<g.length-2;y+=3){var S=g[y]<<16|g[y+1]<<8|g[y+2];_+=this._encodeByte(S>>>18&63),_+=this._encodeByte(S>>>12&63),_+=this._encodeByte(S>>>6&63),_+=this._encodeByte(S>>>0&63)}var k=g.length-y;if(k>0){var S=g[y]<<16|(k===2?g[y+1]<<8:0);_+=this._encodeByte(S>>>18&63),_+=this._encodeByte(S>>>12&63),k===2?_+=this._encodeByte(S>>>6&63):_+=this._paddingCharacter||"",_+=this._paddingCharacter||""}return _},x.prototype.maxDecodedLength=function(g){return this._paddingCharacter?g/4*3|0:(g*6+7)/8|0},x.prototype.decodedLength=function(g){return this.maxDecodedLength(g.length-this._getPaddingLength(g))},x.prototype.decode=function(g){if(g.length===0)return new Uint8Array(0);for(var _=this._getPaddingLength(g),y=g.length-_,S=new Uint8Array(this.maxDecodedLength(y)),k=0,E=0,T=0,j=0,q=0,z=0,O=0;E<y-4;E+=4)j=this._decodeChar(g.charCodeAt(E+0)),q=this._decodeChar(g.charCodeAt(E+1)),z=this._decodeChar(g.charCodeAt(E+2)),O=this._decodeChar(g.charCodeAt(E+3)),S[k++]=j<<2|q>>>4,S[k++]=q<<4|z>>>2,S[k++]=z<<6|O,T|=j&r,T|=q&r,T|=z&r,T|=O&r;if(E<y-1&&(j=this._decodeChar(g.charCodeAt(E)),q=this._decodeChar(g.charCodeAt(E+1)),S[k++]=j<<2|q>>>4,T|=j&r,T|=q&r),E<y-2&&(z=this._decodeChar(g.charCodeAt(E+2)),S[k++]=q<<4|z>>>2,T|=z&r),E<y-3&&(O=this._decodeChar(g.charCodeAt(E+3)),S[k++]=z<<6|O,T|=O&r),T!==0)throw new Error("Base64Coder: incorrect characters for decoding");return S},x.prototype._encodeByte=function(g){var _=g;return _+=65,_+=25-g>>>8&6,_+=51-g>>>8&-75,_+=61-g>>>8&-15,_+=62-g>>>8&3,String.fromCharCode(_)},x.prototype._decodeChar=function(g){var _=r;return _+=(42-g&g-44)>>>8&-r+g-43+62,_+=(46-g&g-48)>>>8&-r+g-47+63,_+=(47-g&g-58)>>>8&-r+g-48+52,_+=(64-g&g-91)>>>8&-r+g-65+0,_+=(96-g&g-123)>>>8&-r+g-97+26,_},x.prototype._getPaddingLength=function(g){var _=0;if(this._paddingCharacter){for(var y=g.length-1;y>=0&&g[y]===this._paddingCharacter;y--)_++;if(g.length<4||_>2)throw new Error("Base64Coder: incorrect padding")}return _},x})();hs.Coder=n;var s=new n;function i(x){return s.encode(x)}hs.encode=i;function c(x){return s.decode(x)}hs.decode=c;var d=(function(x){e(g,x);function g(){return x!==null&&x.apply(this,arguments)||this}return g.prototype._encodeByte=function(_){var y=_;return y+=65,y+=25-_>>>8&6,y+=51-_>>>8&-75,y+=61-_>>>8&-13,y+=62-_>>>8&49,String.fromCharCode(y)},g.prototype._decodeChar=function(_){var y=r;return y+=(44-_&_-46)>>>8&-r+_-45+62,y+=(94-_&_-96)>>>8&-r+_-95+63,y+=(47-_&_-58)>>>8&-r+_-48+52,y+=(64-_&_-91)>>>8&-r+_-65+0,y+=(96-_&_-123)>>>8&-r+_-97+26,y},g})(n);hs.URLSafeCoder=d;var f=new d;function p(x){return f.encode(x)}hs.encodeURLSafe=p;function b(x){return f.decode(x)}return hs.decodeURLSafe=b,hs.encodedLength=function(x){return s.encodedLength(x)},hs.maxDecodedLength=function(x){return s.maxDecodedLength(x)},hs.decodedLength=function(x){return s.decodedLength(x)},hs}var ip={exports:{}},r8=ip.exports,Bk;function i8(){return Bk||(Bk=1,(function(e){(function(r,n){var s={};n(s);var i=s.default;for(var c in s)i[c]=s[c];e.exports=i})(r8,function(r){r.__esModule=!0,r.digestLength=32,r.blockSize=64;var n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function s(_,y,S,k,E){for(var T,j,q,z,O,V,P,$,H,Z,G,K,we;E>=64;){for(T=y[0],j=y[1],q=y[2],z=y[3],O=y[4],V=y[5],P=y[6],$=y[7],Z=0;Z<16;Z++)G=k+Z*4,_[Z]=(S[G]&255)<<24|(S[G+1]&255)<<16|(S[G+2]&255)<<8|S[G+3]&255;for(Z=16;Z<64;Z++)H=_[Z-2],K=(H>>>17|H<<15)^(H>>>19|H<<13)^H>>>10,H=_[Z-15],we=(H>>>7|H<<25)^(H>>>18|H<<14)^H>>>3,_[Z]=(K+_[Z-7]|0)+(we+_[Z-16]|0);for(Z=0;Z<64;Z++)K=(((O>>>6|O<<26)^(O>>>11|O<<21)^(O>>>25|O<<7))+(O&V^~O&P)|0)+($+(n[Z]+_[Z]|0)|0)|0,we=((T>>>2|T<<30)^(T>>>13|T<<19)^(T>>>22|T<<10))+(T&j^T&q^j&q)|0,$=P,P=V,V=O,O=z+K|0,z=q,q=j,j=T,T=K+we|0;y[0]+=T,y[1]+=j,y[2]+=q,y[3]+=z,y[4]+=O,y[5]+=V,y[6]+=P,y[7]+=$,k+=64,E-=64}return k}var i=(function(){function _(){this.digestLength=r.digestLength,this.blockSize=r.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return _.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},_.prototype.clean=function(){for(var y=0;y<this.buffer.length;y++)this.buffer[y]=0;for(var y=0;y<this.temp.length;y++)this.temp[y]=0;this.reset()},_.prototype.update=function(y,S){if(S===void 0&&(S=y.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var k=0;if(this.bytesHashed+=S,this.bufferLength>0){for(;this.bufferLength<64&&S>0;)this.buffer[this.bufferLength++]=y[k++],S--;this.bufferLength===64&&(s(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(S>=64&&(k=s(this.temp,this.state,y,k,S),S%=64);S>0;)this.buffer[this.bufferLength++]=y[k++],S--;return this},_.prototype.finish=function(y){if(!this.finished){var S=this.bytesHashed,k=this.bufferLength,E=S/536870912|0,T=S<<3,j=S%64<56?64:128;this.buffer[k]=128;for(var q=k+1;q<j-8;q++)this.buffer[q]=0;this.buffer[j-8]=E>>>24&255,this.buffer[j-7]=E>>>16&255,this.buffer[j-6]=E>>>8&255,this.buffer[j-5]=E>>>0&255,this.buffer[j-4]=T>>>24&255,this.buffer[j-3]=T>>>16&255,this.buffer[j-2]=T>>>8&255,this.buffer[j-1]=T>>>0&255,s(this.temp,this.state,this.buffer,0,j),this.finished=!0}for(var q=0;q<8;q++)y[q*4+0]=this.state[q]>>>24&255,y[q*4+1]=this.state[q]>>>16&255,y[q*4+2]=this.state[q]>>>8&255,y[q*4+3]=this.state[q]>>>0&255;return this},_.prototype.digest=function(){var y=new Uint8Array(this.digestLength);return this.finish(y),y},_.prototype._saveState=function(y){for(var S=0;S<this.state.length;S++)y[S]=this.state[S]},_.prototype._restoreState=function(y,S){for(var k=0;k<this.state.length;k++)this.state[k]=y[k];this.bytesHashed=S,this.finished=!1,this.bufferLength=0},_})();r.Hash=i;var c=(function(){function _(y){this.inner=new i,this.outer=new i,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var S=new Uint8Array(this.blockSize);if(y.length>this.blockSize)new i().update(y).finish(S).clean();else for(var k=0;k<y.length;k++)S[k]=y[k];for(var k=0;k<S.length;k++)S[k]^=54;this.inner.update(S);for(var k=0;k<S.length;k++)S[k]^=106;this.outer.update(S),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var k=0;k<S.length;k++)S[k]=0}return _.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},_.prototype.clean=function(){for(var y=0;y<this.istate.length;y++)this.ostate[y]=this.istate[y]=0;this.inner.clean(),this.outer.clean()},_.prototype.update=function(y){return this.inner.update(y),this},_.prototype.finish=function(y){return this.outer.finished?this.outer.finish(y):(this.inner.finish(y),this.outer.update(y,this.digestLength).finish(y)),this},_.prototype.digest=function(){var y=new Uint8Array(this.digestLength);return this.finish(y),y},_})();r.HMAC=c;function d(_){var y=new i().update(_),S=y.digest();return y.clean(),S}r.hash=d,r.default=d;function f(_,y){var S=new c(_).update(y),k=S.digest();return S.clean(),k}r.hmac=f;function p(_,y,S,k){var E=k[0];if(E===0)throw new Error("hkdf: cannot expand more");y.reset(),E>1&&y.update(_),S&&y.update(S),y.update(k),y.finish(_),k[0]++}var b=new Uint8Array(r.digestLength);function x(_,y,S,k){y===void 0&&(y=b),k===void 0&&(k=32);for(var E=new Uint8Array([1]),T=f(y,_),j=new c(T),q=new Uint8Array(j.digestLength),z=q.length,O=new Uint8Array(k),V=0;V<k;V++)z===q.length&&(p(q,j,S,E),z=0),O[V]=q[z++];return j.clean(),q.fill(0),E.fill(0),O}r.hkdf=x;function g(_,y,S,k){for(var E=new c(_),T=E.digestLength,j=new Uint8Array(4),q=new Uint8Array(T),z=new Uint8Array(T),O=new Uint8Array(k),V=0;V*T<k;V++){var P=V+1;j[0]=P>>>24&255,j[1]=P>>>16&255,j[2]=P>>>8&255,j[3]=P>>>0&255,E.reset(),E.update(y),E.update(j),E.finish(z);for(var $=0;$<T;$++)q[$]=z[$];for(var $=2;$<=S;$++){E.reset(),E.update(z).finish(z);for(var H=0;H<T;H++)q[H]^=z[H]}for(var $=0;$<T&&V*T+$<k;$++)O[V*T+$]=q[$]}for(var V=0;V<T;V++)q[V]=z[V]=0;for(var V=0;V<4;V++)j[V]=0;return E.clean(),O}r.pbkdf2=g})})(ip)),ip.exports}var af={},Gk;function o8(){if(Gk)return af;Gk=1,Object.defineProperty(af,"__esModule",{value:!0}),af.timingSafeEqual=r;function e(n,s=""){if(!n)throw new Error(s)}function r(n,s){if(n.byteLength!==s.byteLength)return!1;n instanceof DataView||(n=new DataView(ArrayBuffer.isView(n)?n.buffer:n)),s instanceof DataView||(s=new DataView(ArrayBuffer.isView(s)?s.buffer:s)),e(n instanceof DataView),e(s instanceof DataView);const i=n.byteLength;let c=0,d=-1;for(;++d<i;)c|=n.getUint8(d)^s.getUint8(d);return c===0}return af}var Hk;function l8(){if(Hk)return Mo;Hk=1,Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.Webhook=Mo.WebhookVerificationError=void 0;const e=a8(),r=i8(),n=o8(),s=300;class i extends Error{constructor(p){super(p),Object.setPrototypeOf(this,i.prototype),this.name="ExtendableError",this.stack=new Error(p).stack}}class c extends i{constructor(p){super(p),Object.setPrototypeOf(this,c.prototype),this.name="WebhookVerificationError"}}Mo.WebhookVerificationError=c;class d{constructor(p,b){if(b?.format==="raw")p instanceof Uint8Array?this.key=p:this.key=Uint8Array.from(p,x=>x.charCodeAt(0));else{if(typeof p!="string")throw new Error("Expected secret to be of type string");p.startsWith(d.prefix)&&(p=p.substring(d.prefix.length)),this.key=e.decode(p)}if(this.key.length===0)throw new Error("Secret can't be empty.")}verify(p,b,x){var g;const _=(g=x?.jsonParse)!==null&&g!==void 0?g:!0,y={};for(const V of Object.keys(b))y[V.toLowerCase()]=b[V];const S=y["webhook-id"],k=y["webhook-signature"],E=y["webhook-timestamp"];if(!k||!S||!E)throw new c("Missing required headers");const T=this.verifyTimestamp(E),q=this.sign(S,T,p).split(",")[1],z=k.split(" "),O=new globalThis.TextEncoder;for(const V of z){const[P,$]=V.split(",");if(P==="v1"&&(0,n.timingSafeEqual)(O.encode($),O.encode(q))){const H=p.toString();return H===""?void 0:_?JSON.parse(H):void 0}}throw new c("No matching signature found")}sign(p,b,x){if(typeof x!="string")if(x.constructor.name==="Buffer")x=x.toString();else throw new Error("Expected payload to be of type string or Buffer.");const g=new TextEncoder,_=Math.floor(b.getTime()/1e3),y=g.encode(`${p}.${_}.${x}`);return`v1,${e.encode(r.hmac(this.key,y))}`}verifyTimestamp(p){const b=Math.floor(Date.now()/1e3),x=parseInt(p,10);if(Number.isNaN(x))throw new c("Invalid Signature Headers");if(b-x>s)throw new c("Message timestamp too old");if(x>b+s)throw new c("Message timestamp too new");return new Date(x*1e3)}}return Mo.Webhook=d,d.prefix="whsec_",Mo}var c8=l8();let Fk=class extends ye{parseUnverified(r){return JSON.parse(r)}unwrap(r,n){const s=n?.headers;if(s==null)throw new Error("Webhook headers are required in order to verify the signature");const i=n.key===void 0?this._client.webhookKey:n.key;if(!i)throw new Error("Webhook key must not be null or empty in order to unwrap");return new c8.Webhook(i).verify(r,s),JSON.parse(r)}},Vk=class extends ye{list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/agents/${r}/versions`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.versions.list",s,{route:"/v1/agents/{agent_id}/versions",queryParams:["limit","page"],attributes:{"gen_ai.agent.id":r}})})}};var Kk=(()=>{class e extends ye{constructor(){super(...arguments),this.versions=new Vk(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/agents",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.create",s,{route:"/v1/agents",createdIDAttribute:"gen_ai.agent.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d,...f}=s??{};return this._client.get(U`/v1/agents/${n}`,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.retrieve",i,{route:"/v1/agents/{agent_id}",queryParams:["version"],attributes:{"gen_ai.agent.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/agents/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.update",i,{route:"/v1/agents/{agent_id}",attributes:{"gen_ai.agent.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/agents",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.list",s,{route:"/v1/agents",queryParams:["created_at[gte]","created_at[lte]","include_archived","limit","page"]})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/agents/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.agents.archive",i,{route:"/v1/agents/{agent_id}/archive",attributes:{"gen_ai.agent.id":n}})})}}return e.Versions=Vk,e})();let Yx=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return Yx=e.randomUUID.bind(e),e.randomUUID();const r=new Uint8Array(1),n=e?()=>e.getRandomValues(r)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function uh(e,r){if(!e)return()=>{};if(e.aborted)return r.abort(),()=>{};const n=()=>r.abort();return e.addEventListener("abort",n),()=>e.removeEventListener("abort",n)}function $c(e,r){return e instanceof Gt&&e.status===r}function u8(e){return e instanceof Gt&&typeof e.status=="number"&&e.status>=400&&e.status<500}function wp(e){return u8(e)&&!$c(e,408)&&!$c(e,409)&&!$c(e,429)}function NT(e,r,n){return Math.min(r*2**e,n)}function d8(e,r){return e+Math.random()*(r-e)}function AT(e){return e*(1-Math.random()*.25)}function jT(e,{authToken:r,helper:n}){if(!r)throw new De(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(r)}`);const s=e._options.defaultHeaders,i=e._authState?.extraHeaders,c=i?Object.fromEntries(Object.entries(i).filter(([f])=>{const p=f.toLowerCase();return p!=="authorization"&&p!=="x-api-key"})):void 0,d=L([c,s,{[vh]:n}]);return d.values.delete("x-api-key"),d.values.delete("authorization"),d.nulls.delete("authorization"),e.withOptions({authToken:r,baseURL:e.baseURL,defaultHeaders:d})}var oc,rf,ms,of,lf,cf,cd,ud,lc,cc,uf,uc,dd;const h8=999,m8=1e3,f8=6e4,p8=3e5;var Wx=(()=>{class e{constructor(n){oc.set(this,void 0),rf.set(this,!1),ms.set(this,void 0),of.set(this,void 0),lf.set(this,void 0),cf.set(this,void 0),cd.set(this,void 0),ud.set(this,void 0),lc.set(this,void 0),this.client=n.client,this.environmentId=n.environmentId,this.environmentKey=n.environmentKey,this.workerId=n.workerId??x8(),se(this,oc,jT(n.client,{authToken:n.environmentKey,helper:"environments-work-poller"})),se(this,lf,n.autoStop??!0),se(this,cf,n.drain??!1),se(this,cd,n.blockMs===void 0?h8:n.blockMs),se(this,ud,n.reclaimOlderThanMs??null),se(this,lc,n.requestOptions),se(this,ms,new AbortController),se(this,of,uh(n.signal,v(this,ms,"f")))}get signal(){return v(this,ms,"f").signal}abort(){v(this,ms,"f").abort()}async*[(oc=new WeakMap,rf=new WeakMap,ms=new WeakMap,of=new WeakMap,lf=new WeakMap,cf=new WeakMap,cd=new WeakMap,ud=new WeakMap,lc=new WeakMap,Symbol.asyncIterator)](){if(v(this,rf,"f"))throw new De("Cannot iterate over a consumed WorkPoller");se(this,rf,!0);let n=Hs.active();const s=it(this.client);s.info("poller starting",{component:"work-poller",environment_id:this.environmentId});const i=new b8(s,this.environmentId);try{let c=0;for(;!v(this,ms,"f").signal.aborted;){let d;try{d=await v(this,oc,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...v(this,cd,"f")!==null?{block_ms:v(this,cd,"f")}:{},...v(this,ud,"f")!==null?{reclaim_older_than_ms:v(this,ud,"f")}:{}},{headers:L([v(this,lc,"f")?.headers]),signal:v(this,ms,"f").signal})}catch(f){if(v(this,ms,"f").signal.aborted)return;if(wp(f))throw s.error("poll failed permanently, stopping poller",{error:String(f)}),f;const p=AT(g8(c));s.warn("poll failed, backing off",{error:String(f),backoff_ms:p}),c++,await Ko(p,v(this,ms,"f").signal);continue}if(c=0,d==null){if(v(this,cf,"f"))return;i.onEmptyPoll(),await Ko(d8(1e3,3e3),v(this,ms,"f").signal);continue}i.onClaim(),this._workSpan=zt(this.client,()=>ZP(this.client,d,n)),s.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:d.id,work_type:d.data.type});try{await v(this,oc,"f").beta.environments.work.ack(d.id,{environment_id:d.environment_id},{headers:L([v(this,lc,"f")?.headers]),signal:v(this,ms,"f").signal})}catch(f){s.error("ack failed",{work_id:d.id,error:String(f)}),zt(this.client,()=>oT(this._workSpan,v(this,ms,"f").signal,f));continue}try{yield d,n=Hs.active()}finally{if(v(this,lf,"f"))try{await v(this,oc,"f").beta.environments.work.stop(d.id,{environment_id:d.environment_id},{headers:L([v(this,lc,"f")?.headers])})}catch(f){$c(f,409)||s.warn("stop failed",{work_id:d.id,error:String(f)})}zt(this.client,()=>iT(this._workSpan,v(this,ms,"f").signal))}}}finally{v(this,of,"f").call(this)}}}return e})();function g8(e){return NT(e,m8,f8)}var b8=(()=>{class e{constructor(n,s){cc.set(this,void 0),uf.set(this,void 0),uc.set(this,void 0),dd.set(this,0),se(this,cc,n),se(this,uf,s)}onEmptyPoll(){const n=Date.now(),s={component:"work-poller",environment_id:v(this,uf,"f")};v(this,uc,"f")===void 0?(se(this,uc,se(this,dd,n,"f")),v(this,cc,"f").info("idle; polling for work",s)):n-v(this,dd,"f")>=p8?(se(this,dd,n),v(this,cc,"f").info(`still polling; idle for ${Math.round((n-v(this,uc,"f"))/1e3)}s`,s)):v(this,cc,"f").debug("poll returned no work",s)}onClaim(){se(this,uc,void 0)}}return cc=new WeakMap,uf=new WeakMap,uc=new WeakMap,dd=new WeakMap,e})();function x8(){const r=globalThis.process?.env?.HOSTNAME;return r?`${r}-${Yx()}`:Yx()}const y8=e=>{if(typeof globalThis.Buffer<"u"){const r=globalThis.Buffer.from(e,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(typeof atob<"u"){const r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}throw new De("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};var dc,Ei,hc,_8=(()=>{class e{constructor(){dc.set(this,[]),Ei.set(this,[]),hc.set(this,!1)}push(n){if(v(this,hc,"f"))return!1;const s=v(this,Ei,"f").shift();return s?s({done:!1,value:n}):v(this,dc,"f").push(n),!0}close(){if(!v(this,hc,"f"))for(se(this,hc,!0);v(this,Ei,"f").length>0;)v(this,Ei,"f").shift()({done:!0,value:void 0})}next(n){return v(this,dc,"f").length>0?Promise.resolve({done:!1,value:v(this,dc,"f").shift()}):v(this,hc,"f")||n?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(s=>{const i=d=>{n?.removeEventListener("abort",c),s(d)},c=()=>{const d=v(this,Ei,"f").indexOf(i);d>=0&&v(this,Ei,"f").splice(d,1),s({done:!0,value:void 0})};v(this,Ei,"f").push(i),n?.addEventListener("abort",c,{once:!0})})}tryShift(){return v(this,dc,"f").shift()}}return dc=new WeakMap,Ei=new WeakMap,hc=new WeakMap,e})(),l_=(()=>{class e extends Error{constructor(n){const s=typeof n=="string"?n:n.map(i=>i.type==="text"?i.text:`[${i.type}]`).join(" ");super(s),this.name="ToolError",this.content=n}}return e})();const v8="\\x00-\\x1f\\x7f-\\x9f\\u061c\\u200e\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069",w8=new RegExp(`[${v8}]+`,"g"),S8=/[\uD800-\uDFFF]/gu;function Sp(e){return e.replace(S8,"�")}const TT=4096,k8=200;function C8(e,r=TT){return MT(Sp(e).replace(w8," ").trim(),r)}function N8(e){return C8(e,k8)}function Bi(e){return N8(e).replace(/[' ]+/g," ").trim()}function ET(e){return`Error: ${e instanceof Error?e.message:String(e)}`}function A8(e){return MT(Sp(ET(e)),TT)}function MT(e,r){if(e.length<=r)return e;let n=0,s=0;for(const i of e){if(s===r)break;s+=1,n+=i.length}return e.slice(0,n)}function j8(e){return typeof e=="string"?Sp(e):e.filter(r=>r.type==="text"&&r.text!=="").map(r=>({...r,text:Sp(r.text)}))}function Yk(e){return"name"in e?e.name:"mcp_server_name"in e?e.mcp_server_name:e.type}function T8(e){return e instanceof l_?e.content:ET(e)}async function RT(e,r,n){try{const s=e.parse?e.parse(r):r;return{content:await e.run(s,n),isError:!1}}catch(s){return{content:T8(s),isError:!0}}}var hd,df,mc,Ro,_a,Ft,hf,vn,mf,fc,ff,mn,pc,Os,gc,Mi,bc,Sr,pf,md,Ps,gf,fd,pd,bf,Wk,Xk,Qk,Bb,Jk,Gb,Zk,xf,yf,Hb,eC,tC;const nC=500,E8=1e4,M8=12e4,R8=3e4,z8=1e3,O8=3e4,P8=5*6e4,$8=6e4;function zT(e){return e.type!=="session.status_idle"?!1:e.stop_reason?.type!=="requires_action"}var I8=(()=>{class e{constructor(n,s){hd.set(this,void 0),df.set(this,void 0),mc.set(this,new Set),Ro.set(this,!1),_a.set(this,void 0),se(this,hd,n),se(this,df,s)}noteEvent(n){n.type!=="user.tool_confirmation"&&(zT(n)?this.arm():this.disarm())}block(n){v(this,mc,"f").add(n),v(this,_a,"f")!==void 0&&(se(this,Ro,!0),clearTimeout(v(this,_a,"f")),se(this,_a,void 0))}unblock(n){v(this,mc,"f").delete(n),v(this,mc,"f").size===0&&v(this,Ro,"f")&&this.arm()}arm(){if(!(v(this,hd,"f")<=0)){if(v(this,mc,"f").size>0){se(this,Ro,!0);return}se(this,Ro,!1),v(this,_a,"f")!==void 0&&clearTimeout(v(this,_a,"f")),se(this,_a,setTimeout(v(this,df,"f"),v(this,hd,"f")))}}disarm(){se(this,Ro,!1),v(this,_a,"f")!==void 0&&(clearTimeout(v(this,_a,"f")),se(this,_a,void 0))}}return hd=new WeakMap,df=new WeakMap,mc=new WeakMap,Ro=new WeakMap,_a=new WeakMap,e})(),Xx=(()=>{class e{constructor(n,s){Ft.add(this),hf.set(this,!1),vn.set(this,void 0),mf.set(this,void 0),fc.set(this,void 0),ff.set(this,void 0),mn.set(this,void 0),pc.set(this,new Set),Os.set(this,new Set),gc.set(this,new Map),Mi.set(this,new Map),bc.set(this,new _8),Sr.set(this,0),pf.set(this,P8),md.set(this,null),Ps.set(this,void 0),gf.set(this,void 0),fd.set(this,void 0),pd.set(this,!1),this.client=s.client,this.sessionId=n,this.tools=s.tools,this.maxIdleMs=s.maxIdleMs??$8,se(this,mn,it(s.client)),se(this,ff,new Map(s.tools.map(i=>[Yk(i),i]))),se(this,vn,new AbortController),se(this,mf,uh(s.signal,v(this,vn,"f"))),se(this,fc,s.requestOptions),se(this,Ps,new I8(this.maxIdleMs,()=>{v(this,mn,"f").info("session idle after its turn ended; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),v(this,vn,"f").abort()}))}get signal(){return v(this,vn,"f").signal}abort(){v(this,vn,"f").abort()}_setSendRetryWindow(n){se(this,pf,n)}async*[(hf=new WeakMap,vn=new WeakMap,mf=new WeakMap,fc=new WeakMap,ff=new WeakMap,mn=new WeakMap,pc=new WeakMap,Os=new WeakMap,gc=new WeakMap,Mi=new WeakMap,bc=new WeakMap,Sr=new WeakMap,pf=new WeakMap,md=new WeakMap,Ps=new WeakMap,gf=new WeakMap,fd=new WeakMap,pd=new WeakMap,Ft=new WeakSet,Symbol.asyncIterator)](){if(v(this,hf,"f"))throw new De("Cannot iterate over a consumed SessionToolRunner");se(this,hf,!0),se(this,gf,this.client._tracer?Hs.active():void 0),v(this,mn,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});const n=v(this,Ft,"m",Wk).call(this).catch(s=>{v(this,vn,"f").signal.aborted||v(this,mn,"f").error("stream loop failed",{error:String(s)}),v(this,vn,"f").abort()});try{for(;;){const i=await v(this,bc,"f").next(v(this,vn,"f").signal);if(i.done)break;yield i.value}await n;let s;for(;(s=v(this,bc,"f").tryShift())!==void 0;)yield s}finally{v(this,vn,"f").abort(),v(this,Ps,"f").disarm(),await n;try{await v(this,Ft,"m",tC).call(this)}catch(s){v(this,mn,"f").warn("drain failed",{error:String(s)})}v(this,bc,"f").close();for(const s of this.tools)try{await s.close?.()}catch(i){v(this,mn,"f").warn("tool.close failed",{tool:Yk(s),error:String(i)})}v(this,mf,"f").call(this)}}}return bf=function(){return{...v(this,fc,"f"),headers:L([s_("session-tool-runner"),v(this,fc,"f")?.headers]),signal:v(this,vn,"f").signal}},Wk=async function(){const n=v(this,vn,"f");let s=nC;for(;!n.signal.aborted;){try{const i=await this.client.beta.sessions.events.stream(this.sessionId,{},v(this,Ft,"m",bf).call(this));await v(this,Ft,"m",Xk).call(this);for await(const c of i)if(s=nC,await v(this,Ft,"m",Jk).call(this,c))return}catch(i){if(n.signal.throwIfAborted(),wp(i))throw v(this,mn,"f").error("permanent stream failure, shutting down",{error:String(i)}),n.abort(),i;v(this,mn,"f").warn("stream disconnected, reconnecting",{error:String(i),backoff_ms:s})}n.signal.throwIfAborted(),await Ko(s,n.signal),s=Math.min(s*2,E8)}},Xk=async function(){const n=v(this,vn,"f"),s=[];let i=!1;se(this,pd,!1);try{for await(const f of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},v(this,Ft,"m",bf).call(this)))v(this,Ft,"m",Qk).call(this,f,s),f.type!=="user.tool_confirmation"&&(i=zT(f))}catch(f){n.signal.throwIfAborted(),v(this,mn,"f").warn("reconcile list failed",{error:String(f)});for(const p of s)v(this,pc,"f").delete(p.id);return}se(this,pd,!0);const c=s.filter(f=>!v(this,Os,"f").has(f.id));v(this,Ps,"f").disarm();for(const f of c)await v(this,Ft,"m",Gb).call(this,f);for(const f of[...v(this,Mi,"f").values()]){const p=v(this,gc,"f").get(f.id);p!==void 0&&await v(this,Ft,"m",xf).call(this,f,p)}const d=c.filter(f=>!v(this,Os,"f").has(f.id)&&!v(this,Mi,"f").has(f.id));i&&d.length===0?v(this,Ps,"f").arm():v(this,Ps,"f").disarm()},Qk=function(n,s){v(this,Ft,"m",Bb).call(this,n),n.type==="agent.tool_use"||n.type==="agent.custom_tool_use"?(v(this,pc,"f").add(n.id),v(this,Os,"f").has(n.id)||s.push(n)):n.type==="user.tool_result"?v(this,Os,"f").add(n.tool_use_id):n.type==="user.custom_tool_result"?v(this,Os,"f").add(n.custom_tool_use_id):n.type==="user.tool_confirmation"&&(v(this,Os,"f").has(n.tool_use_id)||v(this,gc,"f").set(n.tool_use_id,n.result))},Bb=function(n){if(!(!this.client._tracer||v(this,fd,"f")!==void 0))switch(n.type){case"session.thread_status_running":case"session.thread_status_idle":case"session.thread_status_rescheduled":case"session.thread_status_terminated":se(this,fd,n.session_thread_id)}},Jk=async function(n){switch(v(this,Ps,"f").noteEvent(n),v(this,pd,"f")&&v(this,Ft,"m",Bb).call(this,n),n.type){case"agent.tool_use":case"agent.custom_tool_use":return v(this,pc,"f").has(n.id)||(v(this,pc,"f").add(n.id),await v(this,Ft,"m",Gb).call(this,n)),!1;case"user.tool_confirmation":return await v(this,Ft,"m",Zk).call(this,n),!1;case"user.tool_result":return v(this,Os,"f").add(n.tool_use_id),!1;case"user.custom_tool_result":return v(this,Os,"f").add(n.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return v(this,mn,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),v(this,vn,"f").abort(),!0;default:return!1}},Gb=async function(n){const s=n.evaluated_permission,i=s==="deny"?"deny":v(this,gc,"f").get(n.id);if(i===void 0){s===void 0||s==="allow"?await v(this,Ft,"m",Hb).call(this,n,void 0):v(this,Mi,"f").has(n.id)||(v(this,mn,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),v(this,Mi,"f").set(n.id,n),v(this,Ps,"f").block(n.id));return}await v(this,Ft,"m",xf).call(this,n,i)},Zk=async function(n){v(this,gc,"f").set(n.tool_use_id,n.result);const s=v(this,Mi,"f").get(n.tool_use_id);s!==void 0&&await v(this,Ft,"m",xf).call(this,s,n.result)},xf=async function(n,s){const i=v(this,Mi,"f").delete(n.id);if(s==="allow"){v(this,mn,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),i||v(this,Ps,"f").block(n.id);try{await v(this,Ft,"m",Hb).call(this,n,"allow")}finally{v(this,Ps,"f").unblock(n.id)}return}i&&v(this,Ps,"f").unblock(n.id),v(this,Os,"f").add(n.id),v(this,mn,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),v(this,Ft,"m",yf).call(this,{event:n,toolUseId:n.id,name:n.name,isError:!1,posted:!1,confirmation:"deny"})},yf=function(n){v(this,bc,"f").push(n)},Hb=async function(n,s){var i,c;if(!v(this,Os,"f").has(n.id)){v(this,mn,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),se(this,Sr,(i=v(this,Sr,"f"),i++,i));try{const d=v(this,ff,"f").get(n.name);if(!d){v(this,mn,"f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner",{component:"session-tool-runner",session_id:this.sessionId,tool:n.name,tool_use_id:n.id}),s==="allow"&&v(this,Ps,"f").disarm(),v(this,Ft,"m",yf).call(this,{event:n,toolUseId:n.id,name:n.name,isError:!1,posted:!1,confirmation:s});return}let f,p;const b=v(this,fc,"f")?.openTelemetry?.conversationId??(n.session_thread_id||v(this,fd,"f")),x=new AbortController,g=uh(v(this,vn,"f").signal,x),_=setTimeout(()=>x.abort(),M8);try{const k={signal:v(this,vn,"f").signal,conversationId:b,sessionID:this.sessionId,parentContext:v(this,gf,"f")},E=await a_(this.client,d,n,k,async()=>{const T=await RT(d,n.input,{toolUse:n,toolUseBlock:n,signal:x.signal}),j=q8(T.content),q=this.client._tracer?j.map((z,O)=>{const V=typeof T.content=="string"?void 0:T.content[O];return V&&V.type!=="text"&&z.type==="text"?V:z}):j;return{sent:j,content:q,isError:T.isError}});f=E.sent,p=E.isError}finally{clearTimeout(_),g()}const y=D8(n,p,f),S=await v(this,Ft,"m",eC).call(this,y,n.id,b);v(this,Ft,"m",yf).call(this,{event:n,result:y,toolUseId:n.id,name:n.name,isError:p,posted:S,confirmation:s})}finally{se(this,Sr,(c=v(this,Sr,"f"),c--,c)),v(this,Sr,"f")===0&&v(this,md,"f")?.call(this)}}},eC=async function(n,s,i){const c=v(this,vn,"f"),d=Date.now();let f,p=0;for(;;){p++,c.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[n]},{...v(this,Ft,"m",bf).call(this),openTelemetry:{conversationId:i}}),v(this,Os,"f").add(s),!0}catch(b){if(f=b,wp(b))break;const x=v(this,pf,"f")-(Date.now()-d);if(x<=0)break;const g=Math.min(AT(NT(p-1,z8,O8)),x);v(this,mn,"f").warn("tool result send failed; retrying",{tool_use_id:s,attempt:p,backoff_ms:g,error:String(b)}),await Ko(g,c.signal)}}return v(this,mn,"f").error("failed to send tool result",{tool_use_id:s,attempts:p,error:String(f)}),!1},tC=async function(){v(this,Sr,"f")!==0&&(await Promise.race([new Promise(n=>se(this,md,n)),Ko(R8)]),se(this,md,null),v(this,Sr,"f")>0&&v(this,mn,"f").warn("drain timeout exceeded"))},e})();function D8(e,r,n){return e.type==="agent.custom_tool_use"?{type:"user.custom_tool_result",custom_tool_use_id:e.id,is_error:r,content:n}:{type:"user.tool_result",tool_use_id:e.id,is_error:r,content:n}}function q8(e){if(typeof e=="string")return[{type:"text",text:e||"(no output)"}];const r=e.map(n=>n.type==="text"?{type:"text",text:n.text||"(no output)"}:n.type==="image"||n.type==="document"?n:n.type==="search_result"?{type:"search_result",source:n.source,title:n.title,content:n.content.map(s=>({type:"text",text:s.text})),citations:{enabled:n.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(n)});return r.length>0?r:[{type:"text",text:"(no output)"}]}const eU=15e3,sC=5e3;function L8(e,r){if(!(e>=sC))throw new De(`${r} must be at least ${sC}ms (got ${e}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}var _f,gd,Fb,bd,zo;const aC=3e4,U8=9e4,B8="NO_HEARTBEAT";function G8(e){return e.resources.some(r=>r.type==="memory_store")}function H8(e){if(!e)return null;let r;try{const s=e.replace(/-/g,"+").replace(/_/g,"/"),i=s.padEnd(Math.ceil(s.length/4)*4,"=");r=JSON.parse(Ux(y8(i)))}catch{return null}if(r===null||typeof r!="object"||Array.isArray(r))return null;const n=r.sessions_token;return typeof n=="string"&&n!==""?n:null}var rC=(()=>{class e{constructor(n){if(_f.add(this),gd.set(this,void 0),n.unrestrictedPaths!==void 0)throw new De("The `unrestrictedPaths` option you passed to EnvironmentWorker (or client.beta.environments.work.worker()) is no longer supported. The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a `tools` factory.");this.client=n.client,this.environmentId=n.environmentId,this.environmentKey=n.environmentKey,this.tools=n.tools,this.workdir=n.workdir??process.cwd(),this.maxFileBytes=n.maxFileBytes,this.maxIdleMs=n.maxIdleMs,n.memorySyncIntervalMs!=null&&L8(n.memorySyncIntervalMs,"memorySyncIntervalMs"),this.memorySyncIntervalMs=n.memorySyncIntervalMs,this.memorySyncDeletions=n.memorySyncDeletions??"enabled",this.workerId=n.workerId,this.requestOptions=n.requestOptions,se(this,gd,n.signal)}async run(n){const{environmentId:s,environmentKey:i}=this;if(s===void 0||i===void 0)throw new De("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");const c=n??v(this,gd,"f"),d=new Wx({client:this.client,environmentId:s,environmentKey:i,...this.workerId!==void 0?{workerId:this.workerId}:{},...c?{signal:c}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(const f of d){const p=d._workSpan;try{await e8(this.client,p,d.signal,()=>v(this,_f,"m",Fb).call(this,f,i,d.signal,p))}catch(b){if(d.signal?.aborted)throw b;it(this.client).error("work item failed",{work_id:f.id,error:String(b)})}}}async handleItem(n){const s=n?.workId??ot("ANTHROPIC_WORK_ID"),i=n?.environmentId??ot("ANTHROPIC_ENVIRONMENT_ID"),c=n?.sessionId??ot("ANTHROPIC_SESSION_ID"),d=(n?.environmentKey??this.environmentKey??ot("ANTHROPIC_ENVIRONMENT_KEY"))||void 0,f=n?.workSecret||ot("ANTHROPIC_WORK_SECRET")||null;if(!s)throw new De("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID");if(!i)throw new De("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!c)throw new De("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID");if(!d&&!f)throw new De("handleItem: environmentKey is required when there is no work secret — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");const p={id:s,environment_id:i,secret:f,data:{type:"session",id:c}};await v(this,_f,"m",Fb).call(this,p,d,n?.signal??v(this,gd,"f"))}}return gd=new WeakMap,_f=new WeakSet,Fb=async function(n,s,i,c){const d=it(this.client),f=H8(n.secret),p=f??s;if(p===void 0)throw new De("handleItem: the work item carried a secret payload but no sessions token could be extracted, and there is no environment key to fall back to; the poller must issue a secret whose payload carries `sessions_token`, or provide the environment key (pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY)");n.secret&&f===null&&d.warn("work item carried a secret payload but no sessions token could be extracted; falling back to the environment key",{work_id:n.id});const b=jT(this.client,{authToken:p,helper:"environments-worker"}),x=n.data.id,g=new AbortController,_=uh(i,g),y=new V8(g),S=await Aa(()=>import("./node.browser-B0beh7xO.js"),[]);let k,E;const T=Y8(b,n,y,d,this.requestOptions,O=>{k=O,E?._setSendRetryWindow(O)}).catch(O=>{g.signal.aborted||d.error("heartbeat loop failed",{work_id:n.id,error:String(O)}),g.abort()});let j=async()=>{},q,z=!1;try{if(n.data.type!=="session"){d.debug("skipping non-session work item",{work_id:n.id,type:n.data.type});return}const O=await b.beta.sessions.retrieve(x);if(f===null&&this.memorySyncIntervalMs!==null&&G8(O))throw new S.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${n.id}, session_id=${x}); the memory endpoints reject the environment key, so the poller must issue a per-item \`secret\` carrying \`sessions_token\`, or set \`memorySyncIntervalMs: null\` to run without memory`);const V={workdir:this.workdir,client:b,session:O,...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}};try{j=await S.setupSkills(V)}catch($){d.warn("skill setup failed",{session_id:x,work_id:n.id,error:String($)})}f!==null&&this.memorySyncIntervalMs!==null?(q=new S.SessionMemoryStores(b,{workdir:this.workdir,...this.memorySyncIntervalMs!==void 0?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await q.download(O),V.allowedRoots=q.roots,V.readOnlyRoots=q.readOnlyRoots):d.debug("memory stores disabled for this item",{work_id:n.id});const P=typeof this.tools=="function"?this.tools(V):this.tools??S.betaAgentToolset20260401(V);E=new Xx(x,{client:b,tools:P,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:g.signal}),k!==void 0&&E._setSendRetryWindow(k);for await(const $ of E)q&&await q.syncIfDue();z=!g.signal.aborted}finally{try{await j().catch(O=>{d.warn("skill cleanup failed",{session_id:x,work_id:n.id,error:String(O)})})}finally{if(q){const O=S.MEMORY_FLUSH_TIMEOUT_MS;z&&await iC(q.finish(),O)&&d.warn(`final memory sync cut off after ${O}ms; the flush that follows still uploads changed files`,{session_id:x,work_id:n.id});const V=new AbortController;await iC(q.flushWrites(V.signal),O)&&(V.abort(),d.warn(`memory flush cut off after ${O}ms; changed files it had not uploaded yet are not saved`,{session_id:x,work_id:n.id})),await q.dispose().catch($=>{d.warn("memory store cleanup failed",{session_id:x,work_id:n.id,error:String($)})})}}y.finish("runner_done"),_(),await T,y.lost?d.info("lease lost; released without stopping it",{session_id:x,work_id:n.id}):await F8(b,n,d,this.requestOptions),(y.lost||y.rejected)&&zt(this.client,()=>c?.end())}},e})();async function iC(e,r){let n;try{return await Promise.race([e.then(()=>!1,()=>!1),new Promise(s=>{n=setTimeout(()=>s(!0),r)})])}finally{n!==void 0&&clearTimeout(n)}}async function F8(e,r,n,s){try{await e.beta.environments.work.stop(r.id,{environment_id:r.environment_id,force:!0},{...s,headers:L([s?.headers])})}catch(i){$c(i,409)||n.error("force-stop on exit failed",{work_id:r.id,error:String(i)})}}var V8=(()=>{class e{constructor(n){bd.set(this,void 0),zo.set(this,void 0),se(this,bd,n)}get signal(){return v(this,bd,"f").signal}finish(n){se(this,zo,v(this,zo,"f")??n),v(this,bd,"f").abort()}get lost(){return v(this,zo,"f")==="lease_lost"||v(this,zo,"f")==="assumed_lost"}get rejected(){return v(this,zo,"f")==="heartbeat_rejected"}}return bd=new WeakMap,zo=new WeakMap,e})();function K8(e){let r=e instanceof Gt?e.error:void 0;for(const n of["error","details","current_state"]){if(!Hn(r))return{};r=r[n]}return Hn(r)?r:{}}async function Y8(e,r,n,s,i,c){let d=aC,f=U8,p=Date.now(),b=B8;const x=async()=>{const g=new AbortController,_=uh(n.signal,g),y=setTimeout(()=>g.abort(),d);try{const S=await e.beta.environments.work.heartbeat(r.id,{environment_id:r.environment_id,expected_last_heartbeat:b},{...i,headers:L([i?.headers]),signal:g.signal});p=Date.now(),b=S.last_heartbeat,S.ttl_seconds>0&&(f=S.ttl_seconds*1e3,d=Math.max(1e3,Math.min(f/2,aC)),c?.(f)),(S.state==="stopping"||S.state==="stopped")&&(s.info("heartbeat signals shutdown",{work_id:r.id,state:S.state}),n.finish("heartbeat_stop")),S.lease_extended||(s.warn("lease not extended, shutting down",{work_id:r.id}),n.finish("heartbeat_stop"))}catch(S){if(n.signal.throwIfAborted(),$c(S,412)){const k=K8(S);s.error("lease lost: heartbeat precondition failed",{work_id:r.id,server_state:k.state,server_ttl_seconds:k.ttl_seconds,server_last_heartbeat:k.last_heartbeat}),n.finish("lease_lost");return}if(wp(S))throw s.error("permanent heartbeat failure",{work_id:r.id,error:String(S)}),n.finish("heartbeat_rejected"),S;if(Date.now()-p>f){s.error("lease assumed lost: no successful heartbeat in ttl",{work_id:r.id,ttl_ms:f,error:String(S)}),n.finish("assumed_lost");return}s.warn("transient heartbeat failure",{work_id:r.id,error:String(S)})}finally{clearTimeout(y),_()}};for(await x();!n.signal.aborted;)await Ko(d,n.signal),n.signal.throwIfAborted(),await x()}var c_=(()=>{class e extends Dy{}return e._errorName="BetaHeartbeatPreconditionFailedError",e})(),oC=(()=>{class e extends ye{retrieve(n,s,i){const{environment_id:c,betas:d,workspace_id:f}=s;return this._client.get(U`/v1/environments/${c}/work/${n}`,{...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.retrieve",i,{route:"/v1/environments/{environment_id}/work/{work_id}",attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}update(n,s,i){const{environment_id:c,betas:d,workspace_id:f,...p}=s;return this._client.post(U`/v1/environments/${c}/work/${n}`,{body:p,...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.update",i,{route:"/v1/environments/{environment_id}/work/{work_id}",attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}list(n,s={},i){const{betas:c,...d}=s??{};return this._client.getAPIList(U`/v1/environments/${n}/work`,Me,{query:d,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.list",i,{route:"/v1/environments/{environment_id}/work",queryParams:["limit","page"],attributes:{"anthropic.environment.id":n}})})}ack(n,s,i){const{environment_id:c,betas:d}=s;return this._client.post(U`/v1/environments/${c}/work/${n}/ack`,{...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.ack",i,{route:"/v1/environments/{environment_id}/work/{work_id}/ack",attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}heartbeat(n,s,i){const{environment_id:c,desired_ttl_seconds:d,expected_last_heartbeat:f,betas:p}=s;return this._client.post(U`/v1/environments/${c}/work/${n}/heartbeat`,{query:{desired_ttl_seconds:d,expected_last_heartbeat:f},...i,headers:L([{"anthropic-beta":[...p??[],"managed-agents-2026-04-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.heartbeat",i,{route:"/v1/environments/{environment_id}/work/{work_id}/heartbeat",queryParams:["desired_ttl_seconds","expected_last_heartbeat"],attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}poll(n,s={},i){const{betas:c,"Anthropic-Worker-ID":d,...f}=s??{};return this._client.get(U`/v1/environments/${n}/work/poll`,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"Anthropic-Worker-ID":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.poll",i,{route:"/v1/environments/{environment_id}/work/poll",queryParams:["block_ms","reclaim_older_than_ms"],attributes:{"anthropic.environment.id":n}})})}stats(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/environments/${n}/work/stats`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.stats",i,{route:"/v1/environments/{environment_id}/work/stats",attributes:{"anthropic.environment.id":n}})})}stop(n,s,i){const{environment_id:c,betas:d,workspace_id:f,...p}=s;return this._client.post(U`/v1/environments/${c}/work/${n}/stop`,{body:p,...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.work.stop",i,{route:"/v1/environments/{environment_id}/work/{work_id}/stop",attributes:{"anthropic.environment.id":c,"anthropic.environment.work.id":n}})})}poller(n){return new Wx({...n,client:this._client})}worker(n){return new rC({...n,client:this._client})}}return e.BetaHeartbeatPreconditionFailedError=c_,e.WorkPoller=Wx,e.EnvironmentWorker=rC,e})(),u_=(()=>{class e extends Ye{}return e._errorName="BetaEnvironmentArchivedError",e})(),d_=(()=>{class e extends Ye{}return e._errorName="BetaInvalidConfigTypeChangeError",e})(),h_=(()=>{class e extends Ye{}return e._errorName="BetaInvalidMetadataError",e})(),m_=(()=>{class e extends vs{}return e._errorName="BetaEnvironmentCreateDisabledError",e})(),f_=(()=>{class e extends vs{}return e._errorName="BetaEnvironmentUpdateDisabledError",e})(),p_=(()=>{class e extends Zc{}return e._errorName="BetaEnvironmentNotFoundError",e})(),lC=(()=>{class e extends ye{constructor(){super(...arguments),this.work=new oC(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/environments",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.create",s,{route:"/v1/environments",createdIDAttribute:"anthropic.environment.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/environments/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.retrieve",i,{route:"/v1/environments/{environment_id}",attributes:{"anthropic.environment.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/environments/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.update",i,{route:"/v1/environments/{environment_id}",attributes:{"anthropic.environment.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/environments",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.list",s,{route:"/v1/environments",queryParams:["include_archived","limit","page"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/environments/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.delete",i,{route:"/v1/environments/{environment_id}",attributes:{"anthropic.environment.id":n}})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/environments/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.environments.archive",i,{route:"/v1/environments/{environment_id}/archive",attributes:{"anthropic.environment.id":n}})})}}return e.BetaEnvironmentArchivedError=u_,e.BetaInvalidConfigTypeChangeError=d_,e.BetaInvalidMetadataError=h_,e.BetaEnvironmentCreateDisabledError=m_,e.BetaEnvironmentUpdateDisabledError=f_,e.BetaEnvironmentNotFoundError=p_,e.Work=oC,e.BetaHeartbeatPreconditionFailedError=c_,e})();class cC extends ye{create(r,n,s){const{view:i,betas:c,workspace_id:d,...f}=n;return this._client.post(U`/v1/memory_stores/${r}/memories`,{query:{view:i},body:f,...s,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.create",s,{route:"/v1/memory_stores/{memory_store_id}/memories",queryParams:["view"],attributes:{"gen_ai.memory.store.id":r},createdIDAttribute:"gen_ai.memory.record.id"})})}retrieve(r,n,s){const{memory_store_id:i,betas:c,workspace_id:d,...f}=n;return this._client.get(U`/v1/memory_stores/${i}/memories/${r}`,{query:f,...s,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.retrieve",s,{route:"/v1/memory_stores/{memory_store_id}/memories/{memory_id}",queryParams:["view"],attributes:{"gen_ai.memory.store.id":i,"gen_ai.memory.record.id":r}})})}update(r,n,s){const{memory_store_id:i,view:c,betas:d,workspace_id:f,...p}=n;return this._client.post(U`/v1/memory_stores/${i}/memories/${r}`,{query:{view:c},body:p,...s,headers:L([{"anthropic-beta":[...d??[],"agent-memory-2026-07-22"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.update",s,{route:"/v1/memory_stores/{memory_store_id}/memories/{memory_id}",queryParams:["view"],attributes:{"gen_ai.memory.store.id":i,"gen_ai.memory.record.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/memory_stores/${r}/memories`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.list",s,{route:"/v1/memory_stores/{memory_store_id}/memories",queryParams:["depth","limit","page","path_prefix","view"],contentQueryParams:["page"],attributes:{"gen_ai.memory.store.id":r}})})}delete(r,n,s){const{memory_store_id:i,expected_content_sha256:c,betas:d,workspace_id:f}=n;return this._client.delete(U`/v1/memory_stores/${i}/memories/${r}`,{query:{expected_content_sha256:c},...s,headers:L([{"anthropic-beta":[...d??[],"agent-memory-2026-07-22"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memories.delete",s,{route:"/v1/memory_stores/{memory_store_id}/memories/{memory_id}",queryParams:["expected_content_sha256"],attributes:{"gen_ai.memory.store.id":i,"gen_ai.memory.record.id":r}})})}}class uC extends ye{retrieve(r,n,s){const{memory_store_id:i,betas:c,workspace_id:d,...f}=n;return this._client.get(U`/v1/memory_stores/${i}/memory_versions/${r}`,{query:f,...s,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memory_versions.retrieve",s,{route:"/v1/memory_stores/{memory_store_id}/memory_versions/{memory_version_id}",queryParams:["view"],attributes:{"gen_ai.memory.store.id":i,"anthropic.memory_store.memory_version.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/memory_stores/${r}/memory_versions`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memory_versions.list",s,{route:"/v1/memory_stores/{memory_store_id}/memory_versions",queryParams:["api_key_id","created_at[gte]","created_at[lte]","limit","memory_id","operation","page","service_account_id","session_id","view"],attributes:{"gen_ai.memory.store.id":r}})})}redact(r,n,s){const{memory_store_id:i,betas:c,workspace_id:d}=n;return this._client.post(U`/v1/memory_stores/${i}/memory_versions/${r}/redact`,{...s,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.memory_versions.redact",s,{route:"/v1/memory_stores/{memory_store_id}/memory_versions/{memory_version_id}/redact",attributes:{"gen_ai.memory.store.id":i,"anthropic.memory_store.memory_version.id":r}})})}}var dC=(()=>{class e extends ye{constructor(){super(...arguments),this.memories=new cC(this._client),this.memoryVersions=new uC(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/memory_stores",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.create",s,{route:"/v1/memory_stores",createdIDAttribute:"gen_ai.memory.store.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/memory_stores/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.retrieve",i,{route:"/v1/memory_stores/{memory_store_id}",attributes:{"gen_ai.memory.store.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/memory_stores/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.update",i,{route:"/v1/memory_stores/{memory_store_id}",attributes:{"gen_ai.memory.store.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/memory_stores",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.list",s,{route:"/v1/memory_stores",queryParams:["created_at[gte]","created_at[lte]","include_archived","limit","page"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/memory_stores/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.delete",i,{route:"/v1/memory_stores/{memory_store_id}",attributes:{"gen_ai.memory.store.id":n}})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/memory_stores/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"agent-memory-2026-07-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.memory_stores.archive",i,{route:"/v1/memory_stores/{memory_store_id}/archive",attributes:{"gen_ai.memory.store.id":n}})})}}return e.Memories=cC,e.MemoryVersions=uC,e})(),OT=(()=>{class e{constructor(n,s,i){this.iterator=n,this.response=i,this.controller=s}async*decoder(){const n=this.iterator;if(!n)throw new De("Cannot iterate over a consumed stream.");this.iterator=void 0;const s=new Oj;for await(const i of n)for(const c of s.decode(i))yield JSON.parse(c);for(const i of s.flush())yield JSON.parse(i)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(n,s){if(!n.body)throw s.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new De("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new De("Attempted to iterate over a response with no body");return new e(By(n.body),s,n)}}return e})();let hC=class extends ye{create(r,n){const{betas:s,user_profile_id:i,workspace_id:c,...d}=r;return this._client.post("/v1/messages/batches",{body:d,...n,headers:L([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-user-profile-id":i}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.create",n,{route:"/v1/messages/batches",attributes:{"anthropic.message.batch.request_count":d.requests?.length},createdIDAttribute:"anthropic.message.batch.id"})})}retrieve(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.get(U`/v1/messages/batches/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.retrieve",s,{route:"/v1/messages/batches/{message_batch_id}",attributes:{"anthropic.message.batch.id":r}})})}list(r={},n){const{betas:s,workspace_id:i,...c}=r??{};return this._client.getAPIList("/v1/messages/batches",ns,{query:c,...n,headers:L([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.list",n,{route:"/v1/messages/batches",queryParams:["after_id","before_id","limit"]})})}delete(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.delete(U`/v1/messages/batches/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.delete",s,{route:"/v1/messages/batches/{message_batch_id}",attributes:{"anthropic.message.batch.id":r}})})}cancel(r,n={},s){const{betas:i,workspace_id:c}=n??{};return this._client.post(U`/v1/messages/batches/${r}/cancel`,{...s,headers:L([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.messages.batches.cancel",s,{route:"/v1/messages/batches/{message_batch_id}/cancel",attributes:{"anthropic.message.batch.id":r}})})}async results(r,n={},s){const i=await this.retrieve(r,n,s);if(!i.results_url)throw new De(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);const{betas:c,workspace_id:d}=n??{};return this._client.get(i.results_url,{...s,headers:L([{"anthropic-beta":[...c??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),stream:!0,__qualifiers:{beta:"true"},__binaryResponse:!0,__span:N(this._client,"anthropic.messages.batches.results",s,{route:"/v1/messages/batches/{message_batch_id}/results",attributes:{"anthropic.message.batch.id":r}})})._thenUnwrap((f,p)=>OT.fromResponse(p.response,p.controller))}};const PT={"claude-opus-4@20250514":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function $T(e){return e?.output_format??e?.output_config?.format}function mC(e,r,n){const s=$T(r);return!r||!("parse"in(s??{}))?{...e,content:e.content.map(i=>{if(i.type==="text"){const c=Object.defineProperty({...i},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return i}),parsed_output:null}:g_(e,r,n)}function g_(e,r,n){let s=null;const i=e.content.map(c=>{if(c.type==="text"){const d=W8(r,c.text);s===null&&(s=d);const f=Object.defineProperty({...c},"parsed_output",{value:d,enumerable:!1});return Object.defineProperty(f,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),d},enumerable:!1})}return c});return{...e,content:i,parsed_output:s}}function W8(e,r){const n=$T(e);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(r):JSON.parse(r)}catch(s){throw new De(`Failed to parse structured output: ${s}`)}}function IT(e,r){const{betas:n,user_profile_id:s,workspace_id:i,tools:c,messages:d}=e;return L([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...s!=null?{"anthropic-user-profile-id":s}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},cT(c,d),r?.headers])}function X8(e,r,n){if(!e._tracer)return;const s=IT(r,n);return N(e,"anthropic.messages.create",n,Jp(e,{body:Qx(r),headers:s,stream:!0}))}function Qx(e){if(!e.output_format)return e;b_(e);const{output_format:r,...n}=e;return{...n,output_config:{...e.output_config,format:r}}}function b_(e){if(e.output_format&&e.output_config?.format)throw new De("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).")}const Q8=e=>{let r=0,n=[];for(;r<e.length;){let s=e[r];if(s==="\\"){r++;continue}if(s==="{"){n.push({type:"brace",value:"{"}),r++;continue}if(s==="}"){n.push({type:"brace",value:"}"}),r++;continue}if(s==="["){n.push({type:"paren",value:"["}),r++;continue}if(s==="]"){n.push({type:"paren",value:"]"}),r++;continue}if(s===":"){n.push({type:"separator",value:":"}),r++;continue}if(s===","){n.push({type:"delimiter",value:","}),r++;continue}if(s==='"'){const f=r+1;let p=f,b=!1;for(;;){if(p=e.indexOf('"',p),p===-1){b=!0;break}let x=0,g=p-1;for(;g>=f&&e[g]==="\\";)x++,g--;if(x%2===0)break;p++}b?r=e.length:(n.push({type:"string",value:e.slice(f,p)}),r=p+1);continue}if(s&&/\s/.test(s)){r++;continue}let c=/[0-9]/;if(s&&c.test(s)||s==="-"||s==="."){let f="";for(s==="-"&&(f+=s,s=e[++r]);s&&(c.test(s)||s==="."||s==="e"||s==="E"||(s==="-"||s==="+")&&(f[f.length-1]==="e"||f[f.length-1]==="E"));)f+=s,s=e[++r];n.push({type:"number",value:f,unterminated:r===e.length});continue}let d=/[a-z]/i;if(s&&d.test(s)){let f="";for(;s&&d.test(s)&&r!==e.length;)f+=s,s=e[++r];if(f=="true"||f=="false"||f==="null")n.push({type:"name",value:f});else{r++;continue}continue}r++}return n},J8=e=>{let r=[];for(const c of e)(c.type==="brace"||c.type==="paren")&&(c.value==="{"||c.value==="["?r.push(c.value):r.pop());let n=r[r.length-1],s=e.length,i=/^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;for(;s>0;){let c=e[s-1];switch(c.type){case"separator":s--;continue;case"number":if(c.unterminated||!i.test(c.value)){s--;continue}break;case"string":let d=e[s-2];if(n==="{"&&(d?.type==="delimiter"||d?.type==="brace"&&d.value==="{")){s--;continue}break;case"delimiter":s--;break}break}return e.slice(0,s)},Z8=e=>{let r=[];return e.map(n=>{n.type==="brace"&&(n.value==="{"?r.push("}"):r.splice(r.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?r.push("]"):r.splice(r.lastIndexOf("]"),1))}),r.length>0&&r.reverse().map(n=>{n==="}"?e.push({type:"brace",value:"}"}):n==="]"&&e.push({type:"paren",value:"]"})}),e},e$=e=>{let r="";return e.map(n=>{switch(n.type){case"string":r+='"'+n.value+'"';break;default:r+=n.value;break}}),r},t$=e=>JSON.parse(e$(Z8(J8(Q8(e))))),Ic="__json_buf";function DT(e,r){const n={};for(const c of Object.keys(e))c!=="input"&&(n[c]=e[c]);Object.defineProperty(n,Ic,{value:r,enumerable:!1,writable:!0});let s,i=!1;return Object.defineProperty(n,"input",{enumerable:!0,configurable:!0,get(){return i||(s=r?t$(r):{},i=!0),s}}),n}var fs,Ri,Ya,xd,vf,yd,_d,wf,vd,Wa,wd,Sf,kf,Oo,Cf,Nf,Af,Sd,Xa,Wn,kd,Vb,fC,Cd,Kb,Yb,Wb,pC,Xb;function Qb(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}var x_=(()=>{class e{constructor(n,s){fs.add(this),this.messages=[],this.receivedMessages=[],Ri.set(this,void 0),Ya.set(this,null),this.controller=new AbortController,xd.set(this,void 0),vf.set(this,()=>{}),yd.set(this,()=>{}),_d.set(this,void 0),wf.set(this,()=>{}),vd.set(this,()=>{}),Wa.set(this,{}),wd.set(this,!1),Sf.set(this,!1),kf.set(this,!1),Oo.set(this,!1),Cf.set(this,void 0),Nf.set(this,void 0),Af.set(this,void 0),Sd.set(this,void 0),Xa.set(this,void 0),Wn.set(this,void 0),kd.set(this,void 0),Cd.set(this,i=>{if(se(this,Sf,!0),v(this,Wn,"f")&&(v(this,Wn,"f").streamed=void 0),Jo(i)&&(i=new Ls),i instanceof Ls)return se(this,kf,!0),this._emit("abort",i);if(i instanceof De)return this._emit("error",i);if(i instanceof Error){const c=new De(i.message);return c.cause=i,this._emit("error",c)}return this._emit("error",new De(String(i)))}),se(this,xd,new Promise((i,c)=>{se(this,vf,i,"f"),se(this,yd,c,"f")})),se(this,_d,new Promise((i,c)=>{se(this,wf,i,"f"),se(this,vd,c,"f")})),v(this,xd,"f").catch(()=>{}),v(this,_d,"f").catch(()=>{}),se(this,Ya,n),se(this,Sd,s?.logger??console),se(this,Xa,s?.client)}get response(){return v(this,Cf,"f")}get request_id(){return v(this,Nf,"f")}get workspace_id(){return v(this,Af,"f")}async withResponse(){se(this,Oo,!0);const n=await v(this,xd,"f");if(!n)throw new Error("Could not resolve a `Response` object");return{data:this,response:n,request_id:n.headers.get("request-id"),workspace_id:n.headers.get("anthropic-workspace-id")}}static fromReadableStream(n){const s=new e(null);return s._run(()=>s._fromReadableStream(n)),s}static createMessage(n,s,i,{logger:c,client:d}={}){const f=new e(s,{logger:c,client:d});for(const p of s.messages)f._addMessageParam(p);return se(f,Ya,{...s,stream:!0}),f._run(()=>f._createMessage((p,b)=>n.create(p,b),{...s,stream:!0},{...i,headers:{...i?.headers,[n_]:"stream"}})),f}_start(n,s,i,c){for(const p of s.messages)this._addMessageParam(p);const d=v(this,Xa,"f");se(this,Xa,void 0);const f=(p,b)=>n(p,b)._thenUnwrap((x,{options:g})=>(se(this,Xa,d),se(this,Wn,g.__span),se(this,kd,g.body),x));this._run(()=>this._createMessage(f,{...s,stream:!0},i).finally(c))}_run(n){n().then(()=>{this._emitFinal(),this._emit("end")},v(this,Cd,"f"))}_addMessageParam(n){this.messages.push(n)}_addMessage(n,s=!0){this.receivedMessages.push(n),s&&this._emit("message",n)}async _createMessage(n,s,i){const c=i?.signal;let d;c&&(c.aborted&&this.controller.abort(),d=this.controller.abort.bind(this.controller),c.addEventListener("abort",d));try{v(this,fs,"m",Kb).call(this),se(this,Wn,i?.__span??(v(this,Xa,"f")&&X8(v(this,Xa,"f"),s,i)),"f");const{response:f,data:p}=await n({...s,stream:!0},{...i,__span:v(this,Wn,"f"),signal:this.controller.signal}).withResponse();try{this._connected(f)}catch(b){throw v(this,Wn,"f")&&(v(this,Wn,"f").failure=b),p.controller.abort(),b}for await(const b of p)try{v(this,fs,"m",Yb).call(this,b)}catch(x){throw v(this,Wn,"f")&&(v(this,Wn,"f").failure=x),x}if(p.controller.signal?.aborted)throw new Ls;v(this,fs,"m",Wb).call(this)}finally{c&&d&&c.removeEventListener("abort",d)}}_connected(n){this.ended||(se(this,Cf,n),se(this,Nf,n?.headers.get("request-id")),se(this,Af,n?.headers.get("anthropic-workspace-id")),v(this,vf,"f").call(this,n),this._emit("connect"))}get ended(){return v(this,wd,"f")}get errored(){return v(this,Sf,"f")}get aborted(){return v(this,kf,"f")}abort(){this.controller.abort()}on(n,s){return(v(this,Wa,"f")[n]||(v(this,Wa,"f")[n]=[])).push({listener:s}),this}off(n,s){const i=v(this,Wa,"f")[n];if(!i)return this;const c=i.findIndex(d=>d.listener===s);return c>=0&&i.splice(c,1),this}once(n,s){return(v(this,Wa,"f")[n]||(v(this,Wa,"f")[n]=[])).push({listener:s,once:!0}),this}emitted(n){return new Promise((s,i)=>{se(this,Oo,!0),n!=="error"&&this.once("error",i),this.once(n,s)})}async done(){se(this,Oo,!0),await v(this,_d,"f")}get currentMessage(){return v(this,Ri,"f")}async finalMessage(){return await this.done(),v(this,fs,"m",Vb).call(this)}async finalText(){return await this.done(),v(this,fs,"m",fC).call(this)}_emit(n,...s){if(v(this,wd,"f"))return;n==="end"&&(se(this,wd,!0),v(this,wf,"f").call(this));const i=v(this,Wa,"f")[n];if(i&&(v(this,Wa,"f")[n]=i.filter(c=>!c.once),i.forEach(({listener:c})=>c(...s))),n==="abort"){const c=s[0];!v(this,Oo,"f")&&!i?.length&&Promise.reject(c),v(this,yd,"f").call(this,c),v(this,vd,"f").call(this,c),this._emit("end");return}if(n==="error"){const c=s[0];!v(this,Oo,"f")&&!i?.length&&Promise.reject(c),v(this,yd,"f").call(this,c),v(this,vd,"f").call(this,c),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",v(this,fs,"m",Vb).call(this))}_deliverEvent(n,s){this._emit("_rawEvent",n),s&&this._emit("streamEvent",n,s)}async _fromReadableStream(n,s){const i=s?.signal;let c;i&&(i.aborted&&this.controller.abort(),c=this.controller.abort.bind(this.controller),i.addEventListener("abort",c));try{v(this,fs,"m",Kb).call(this),this._connected(null);const d=Hr.fromReadableStream(n,this.controller);for await(const f of d)v(this,fs,"m",Yb).call(this,f);if(d.controller.signal?.aborted)throw new Ls;v(this,fs,"m",Wb).call(this)}finally{i&&c&&i.removeEventListener("abort",c)}}[(Ri=new WeakMap,Ya=new WeakMap,xd=new WeakMap,vf=new WeakMap,yd=new WeakMap,_d=new WeakMap,wf=new WeakMap,vd=new WeakMap,Wa=new WeakMap,wd=new WeakMap,Sf=new WeakMap,kf=new WeakMap,Oo=new WeakMap,Cf=new WeakMap,Nf=new WeakMap,Af=new WeakMap,Sd=new WeakMap,Xa=new WeakMap,Wn=new WeakMap,kd=new WeakMap,Cd=new WeakMap,fs=new WeakSet,Vb=function(){if(this.receivedMessages.length===0)throw new De("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},fC=function(){if(this.receivedMessages.length===0)throw new De("stream ended without producing a Message with role=assistant");const s=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(s.length===0)throw new De("stream ended without producing a content block with type=text");return s.join(" ")},Kb=function(){this.ended||se(this,Ri,void 0)},Yb=function(s){if(this.ended)return;const i=v(this,fs,"m",pC).call(this,s);if(this._deliverEvent(s,i),!!i)switch(s.type){case"content_block_delta":{const c=i.content.at(-1);switch(s.delta.type){case"text_delta":{c.type==="text"&&this._emit("text",s.delta.text,c.text||"");break}case"citations_delta":{c.type==="text"&&this._emit("citation",s.delta.citation,c.citations??[]);break}case"input_json_delta":{if(Qb(c)&&v(this,Wa,"f").inputJson?.length){let d;try{d=c.input}catch(f){v(this,Cd,"f").call(this,v(this,fs,"m",Xb).call(this,c,f));break}this._emit("inputJson",s.delta.partial_json,d)}break}case"thinking_delta":{c.type==="thinking"&&this._emit("thinking",s.delta.thinking,c.thinking);break}case"signature_delta":{c.type==="thinking"&&this._emit("signature",c.signature);break}case"compaction_delta":{c.type==="compaction"&&c.content&&this._emit("compaction",c.content);break}default:s.delta}break}case"message_stop":{v(this,Xa,"f")&&v(this,Wn,"f")&&v(this,Ya,"f")&&t_(v(this,Xa,"f"),v(this,Wn,"f"),v(this,kd,"f")??v(this,Ya,"f"),i),this._addMessageParam(i),this._addMessage(mC(i,v(this,Ya,"f"),{logger:v(this,Sd,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{se(this,Ri,i),v(this,Wn,"f")&&v(this,Ya,"f")&&(v(this,Wn,"f").streamed={body:v(this,kd,"f")??v(this,Ya,"f"),message:i});break}}},Wb=function(){if(this.ended)throw new De("stream has ended, this shouldn't happen");const s=v(this,Ri,"f");if(!s)throw new De("request ended without sending any chunks");return se(this,Ri,void 0),mC(s,v(this,Ya,"f"),{logger:v(this,Sd,"f")})},pC=function(s){let i=v(this,Ri,"f");if(s.type==="message_start"){if(i)throw new De(`Unexpected event order, got ${s.type} before receiving "message_stop"`);return s.message}if(i)switch(s.type){case"message_stop":return i;case"message_delta":return i.stop_reason=s.delta.stop_reason,i.stop_sequence=s.delta.stop_sequence,i.stop_details=s.delta.stop_details,i.usage.output_tokens=s.usage.output_tokens,s.delta.container!=null&&(i.container=s.delta.container),s.context_management!=null&&(i.context_management=s.context_management),s.input_transformations!=null&&(i.input_transformations=s.input_transformations),s.usage.input_tokens!=null&&(i.usage.input_tokens=s.usage.input_tokens),s.usage.cache_creation_input_tokens!=null&&(i.usage.cache_creation_input_tokens=s.usage.cache_creation_input_tokens),s.usage.cache_read_input_tokens!=null&&(i.usage.cache_read_input_tokens=s.usage.cache_read_input_tokens),s.usage.server_tool_use!=null&&(i.usage.server_tool_use=s.usage.server_tool_use),s.usage.iterations!=null&&(i.usage.iterations=s.usage.iterations),s.usage.fallback_credit!=null&&(i.usage.fallback_credit=s.usage.fallback_credit),s.usage.output_tokens_details!=null&&(i.usage.output_tokens_details=s.usage.output_tokens_details),i;case"content_block_start":return i.content.push(s.content_block),s.content_block.type==="fallback"&&(i.model=s.content_block.to.model),i;case"content_block_delta":{const c=i.content.at(s.index);switch(s.delta.type){case"text_delta":{c?.type==="text"&&(i.content[s.index]={...c,text:(c.text||"")+s.delta.text});break}case"citations_delta":{c?.type==="text"&&(i.content[s.index]={...c,citations:[...c.citations??[],s.delta.citation]});break}case"input_json_delta":{if(c&&Qb(c)){const d=(c[Ic]||"")+s.delta.partial_json;i.content[s.index]=DT(c,d)}break}case"thinking_delta":{c?.type==="thinking"&&(i.content[s.index]={...c,thinking:c.thinking+s.delta.thinking});break}case"signature_delta":{c?.type==="thinking"&&(i.content[s.index]={...c,signature:s.delta.signature});break}case"compaction_delta":{if(c?.type==="compaction"){const d={...c,content:s.delta.content};"encrypted_content"in s.delta&&(d.encrypted_content=s.delta.encrypted_content),i.content[s.index]=d}break}default:s.delta}return i}case"content_block_stop":{const c=i.content.at(s.index);if(c&&Qb(c)&&Ic in c){let d;try{d=c.input}catch(f){d={},v(this,Cd,"f").call(this,v(this,fs,"m",Xb).call(this,c,f))}Object.defineProperty(c,"input",{value:d,enumerable:!0,configurable:!0,writable:!0})}return i}default:return i}},Xb=function(s,i){const c=s[Ic];return new De(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${i}. JSON: ${c}`)},Symbol.asyncIterator)](){const n=[],s=[];let i=!1;return this.on("_rawEvent",c=>{const d=s.shift();d?d.resolve(c):n.push(c)}),this.on("end",()=>{i=!0;for(const c of s)c.resolve(void 0);s.length=0}),this.on("abort",c=>{i=!0;for(const d of s)d.reject(c);s.length=0}),this.on("error",c=>{i=!0;for(const d of s)d.reject(c);s.length=0}),{next:async()=>n.length?{value:n.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((d,f)=>s.push({resolve:d,reject:f})).then(d=>d?{value:d,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Hr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})();const qT={browser_toolset_20260801:"browser",computer_toolset_20260801:"computer"};function Yc(e){return qT[e.type]}function dh(e){return"run"in e&&e.type!=null&&Object.prototype.hasOwnProperty.call(qT,e.type)}var LT=(()=>{class e extends De{constructor(n,s){super(n),s&&"cause"in s&&(this.cause=s.cause)}}return e._errorName="ToolsetUsageError",e})(),op=(()=>{class e extends LT{}return e._errorName="ToolsetContractError",e})();const UT="Not executed: an earlier action in this turn failed.",gC={browser:UT,computer:"Not executed: an earlier computer action in this turn failed."};function n$(e){return Object.prototype.hasOwnProperty.call(gC,e)?gC[e]:UT}function kp(e,r,n=!1){return n&&(r===""||Array.isArray(r)&&r.length===0)&&(r="The tool call failed with an empty error message."),{type:"tool_result",tool_use_id:e.id,toolset_name:e.toolset_name??null,content:r,...n?{is_error:!0}:{}}}function s$(e,r){if(e instanceof LT)throw e;a$(r.signal)}function a$(e){if(e?.aborted)throw new Ls}async function r$(e,r,n={}){const s=Yc(e);if(r.toolset_name!==s)throw new op(`tool_use ${JSON.stringify(r.id)} (toolset_name=${JSON.stringify(r.toolset_name??null)}, name=${JSON.stringify(r.name)}) is not a member call of the ${JSON.stringify(s)} toolset`);const i={...n,toolUse:r,toolUseBlock:r};try{return kp(r,await e.run(i,r))}catch(c){return s$(c,i),kp(r,j8(c instanceof l_?c.content:A8(c)),!0)}}let bC=class extends ye{retrieve(r,n){return this._client.get(U`/v1/organizations/api_keys/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.api_keys.retrieve",n,{route:"/v1/organizations/api_keys/{api_key_id}",attributes:{"anthropic.organization.api_key.id":r}})})}update(r,n,s){return this._client.post(U`/v1/organizations/api_keys/${r}`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.api_keys.update",s,{route:"/v1/organizations/api_keys/{api_key_id}",attributes:{"anthropic.organization.api_key.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/api_keys",ns,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.api_keys.list",n,{route:"/v1/organizations/api_keys",queryParams:["after_id","before_id","created_by_user_id","limit","status","workspace_id"]})})}},xC=class extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/artifacts",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.artifacts.list",n,{route:"/v1/organizations/analytics/artifacts",queryParams:["date","filter","group_by","limit","page"]})})}},yC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/connectors",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.connectors.list",n,{route:"/v1/organizations/analytics/connectors",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}};class _C extends ye{list(r,n){const{betas:s,...i}=r;return this._client.getAPIList("/v1/organizations/analytics/cost",tu,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"analytics-usage-cost-2026-08-24"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.cost.list",n,{route:"/v1/organizations/analytics/cost",queryParams:["actor_ids","actor_types","agent_ids","api_key_ids","claude_tag_categories","claude_tag_user_ids","context_windows","deployment_ids","ending_at","environment_ids","exclude_deleted_users","group_by","inference_geos","limit","models","order","order_by","organization_ids","page","products","rbac_group_ids","service_tiers","session_ids","slack_channel_ids","speeds","starting_at","time_bucket_width","user_profile_ids","workspace_ids"]})})}}class vC extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/cost_report",tu,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.cost_report.list",n,{route:"/v1/organizations/analytics/cost_report",queryParams:["bucket_width","claude_tag_categories","claude_tag_user_ids","context_windows","ending_at","group_by","inference_geos","limit","models","page","products","rbac_group_ids","slack_channel_ids","speeds","starting_at","user_ids"]})})}}let wC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/plugins",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.plugins.list",n,{route:"/v1/organizations/analytics/plugins",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}},SC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/skills",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.skills.list",n,{route:"/v1/organizations/analytics/skills",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}},kC=class extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/summaries",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.summaries.list",n,{route:"/v1/organizations/analytics/summaries",queryParams:["ending_date","filter","limit","page","starting_date"]})})}};class CC extends ye{list(r,n){const{betas:s,...i}=r;return this._client.getAPIList("/v1/organizations/analytics/usage",tu,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"analytics-usage-cost-2026-08-24"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.usage.list",n,{route:"/v1/organizations/analytics/usage",queryParams:["actor_ids","actor_types","agent_ids","api_key_ids","claude_tag_categories","claude_tag_user_ids","context_windows","deployment_ids","ending_at","environment_ids","exclude_deleted_users","group_by","inference_geos","limit","models","order","order_by","organization_ids","page","products","rbac_group_ids","service_tiers","session_ids","slack_channel_ids","speeds","starting_at","time_bucket_width","user_profile_ids","workspace_ids"]})})}}class NC extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/usage_report",tu,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.usage_report.list",n,{route:"/v1/organizations/analytics/usage_report",queryParams:["bucket_width","claude_tag_categories","claude_tag_user_ids","context_windows","ending_at","group_by","inference_geos","limit","models","page","products","rbac_group_ids","slack_channel_ids","speeds","starting_at","user_ids"]})})}}class AC extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/user_cost_report",tu,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.user_cost_report.list",n,{route:"/v1/organizations/analytics/user_cost_report",queryParams:["bucket_width","claude_tag_categories","claude_tag_user_ids","context_windows","ending_at","exclude_deleted_users","group_by","inference_geos","limit","models","order","order_by","page","products","rbac_group_ids","slack_channel_ids","speeds","starting_at","user_ids"]})})}}class jC extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/user_usage_report",tu,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.user_usage_report.list",n,{route:"/v1/organizations/analytics/user_usage_report",queryParams:["bucket_width","claude_tag_categories","claude_tag_user_ids","context_windows","ending_at","exclude_deleted_users","group_by","inference_geos","limit","models","order","order_by","page","products","rbac_group_ids","slack_channel_ids","speeds","starting_at","user_ids"]})})}}let TC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/users",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.users.list",n,{route:"/v1/organizations/analytics/users",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["page"]})})}},EC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/apps/chat/projects",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.analytics.apps.chat.projects.list",n,{route:"/v1/organizations/analytics/apps/chat/projects",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"]})})}};var MC=(()=>{class e extends ye{constructor(){super(...arguments),this.projects=new EC(this._client)}}return e.Projects=EC,e})(),RC=(()=>{class e extends ye{constructor(){super(...arguments),this.chat=new MC(this._client)}}return e.Chat=MC,e})(),zC=(()=>{class e extends ye{constructor(){super(...arguments),this.summaries=new kC(this._client),this.users=new TC(this._client),this.apps=new RC(this._client),this.connectors=new yC(this._client),this.plugins=new wC(this._client),this.skills=new SC(this._client),this.artifacts=new xC(this._client),this.usage=new CC(this._client),this.cost=new _C(this._client),this.usageReport=new NC(this._client),this.userUsageReport=new jC(this._client),this.costReport=new vC(this._client),this.userCostReport=new AC(this._client)}}return e.Summaries=kC,e.Users=TC,e.Apps=RC,e.Connectors=yC,e.Plugins=wC,e.Skills=SC,e.Artifacts=xC,e.Usage=CC,e.Cost=_C,e.UsageReport=NC,e.UserUsageReport=jC,e.CostReport=vC,e.UserCostReport=AC,e})(),y_=(()=>{class e extends Ye{}return e._errorName="BetaCannotSignOutPrimaryOwnerError",e})(),__=(()=>{class e extends Ye{}return e._errorName="BetaCannotSignOutSelfError",e})(),v_=(()=>{class e extends vs{}return e._errorName="BetaCannotSignOutManagedMemberError",e})(),w_=(()=>{class e extends vs{}return e._errorName="BetaCannotSignOutMembershipAdminError",e})(),S_=(()=>{class e extends vs{}return e._errorName="BetaCannotSignOutOwnerError",e})(),k_=(()=>{class e extends vs{}return e._errorName="BetaCannotSignOutPrivilegedMemberError",e})(),OC=(()=>{class e extends ye{retrieve(n,s){return this._client.get(U`/v1/organizations/users/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.retrieve",s,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/users/${n}`,{body:s,...i,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.update",i,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/users",ns,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.list",s,{route:"/v1/organizations/users",queryParams:["after_id","before_id","email","limit","roles"]})})}remove(n,s){return this._client.delete(U`/v1/organizations/users/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.remove",s,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}signOut(n,s={},i){const{betas:c}=s??{};return this._client.post(U`/v1/organizations/users/${n}/sign_out`,{...i,headers:L([{"anthropic-beta":[...c??[],"admin-user-sign-out-2026-10-08"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.users.sign_out",i,{route:"/v1/organizations/users/{user_id}/sign_out",attributes:{"anthropic.organization.user.id":n}})})}}return e.BetaCannotSignOutPrimaryOwnerError=y_,e.BetaCannotSignOutSelfError=__,e.BetaCannotSignOutManagedMemberError=v_,e.BetaCannotSignOutMembershipAdminError=w_,e.BetaCannotSignOutOwnerError=S_,e.BetaCannotSignOutPrivilegedMemberError=k_,e})();class PC extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/plugins/${r}/installation_settings`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.installation_settings.list",s,{route:"/v1/organizations/plugins/{plugin_id}/installation_settings",queryParams:["limit","organization_id","page","target_type"],attributes:{"anthropic.organization.plugin.id":r}})})}remove(r,n,s){const{plugin_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/plugins/${i}/installation_settings/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.installation_settings.remove",s,{route:"/v1/organizations/plugins/{plugin_id}/installation_settings/{target}",attributes:{"anthropic.organization.plugin.id":i,"anthropic.organization.plugin.installation_setting.id":r}})})}set(r,n,s){const{plugin_id:i,betas:c,...d}=n;return this._client.post(U`/v1/organizations/plugins/${i}/installation_settings/${r}`,{body:d,...s,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.installation_settings.set",s,{route:"/v1/organizations/plugins/{plugin_id}/installation_settings/{target}",attributes:{"anthropic.organization.plugin.id":i,"anthropic.organization.plugin.installation_setting.id":r}})})}}class $C extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/plugins/${r}/shares`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.shares.list",s,{route:"/v1/organizations/plugins/{plugin_id}/shares",queryParams:["limit","organization_id","page","target_type"],attributes:{"anthropic.organization.plugin.id":r}})})}}let IC=class extends ye{create(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/plugins/${r}/versions`,Kr({body:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.versions.create",s,{route:"/v1/organizations/plugins/{plugin_id}/versions",attributes:{"anthropic.organization.plugin.id":r},createdIDAttribute:"anthropic.organization.plugin.version.id"})},this._client))}retrieve(r,n,s){const{plugin_id:i,betas:c,...d}=n;return this._client.get(U`/v1/organizations/plugins/${i}/versions/${r}`,{query:d,...s,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.versions.retrieve",s,{route:"/v1/organizations/plugins/{plugin_id}/versions/{version}",queryParams:["organization_id"],attributes:{"anthropic.organization.plugin.id":i,"anthropic.organization.plugin.version.id":r}})})}list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/plugins/${r}/versions`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.versions.list",s,{route:"/v1/organizations/plugins/{plugin_id}/versions",queryParams:["limit","organization_id","page"],attributes:{"anthropic.organization.plugin.id":r}})})}download(r,n,s){const{plugin_id:i,betas:c,...d}=n;return this._client.get(U`/v1/organizations/plugins/${i}/versions/${r}/content`,{query:d,...s,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString(),Accept:"application/binary"},s?.headers]),__qualifiers:{beta:"true"},__binaryResponse:!0,__span:N(this._client,"anthropic.organization.plugins.versions.download",s,{route:"/v1/organizations/plugins/{plugin_id}/versions/{version}/content",queryParams:["organization_id"],attributes:{"anthropic.organization.plugin.id":i,"anthropic.organization.plugin.version.id":r}})})}};var C_=(()=>{class e extends Ye{}return e._errorName="BetaScanFailedError",e})(),N_=(()=>{class e extends Vr{}return e._errorName="BetaPluginNameTakenError",e})(),A_=(()=>{class e extends Vr{}return e._errorName="BetaScanPendingError",e})(),j_=(()=>{class e extends Vr{}return e._errorName="BetaSkillNameTakenError",e})(),T_=(()=>{class e extends _h{}return e._errorName="BetaRegistrationPendingError",e})(),DC=(()=>{class e extends ye{constructor(){super(...arguments),this.versions=new IC(this._client),this.installationSettings=new PC(this._client),this.shares=new $C(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/plugins",Kr({body:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.create",s,{route:"/v1/organizations/plugins",createdIDAttribute:"anthropic.organization.plugin.id"})},this._client))}retrieve(n,s={},i){const{betas:c,...d}=s??{};return this._client.get(U`/v1/organizations/plugins/${n}`,{query:d,...i,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.retrieve",i,{route:"/v1/organizations/plugins/{plugin_id}",queryParams:["organization_id"],attributes:{"anthropic.organization.plugin.id":n}})})}update(n,s,i){const{betas:c,...d}=s;return this._client.post(U`/v1/organizations/plugins/${n}`,{body:d,...i,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.update",i,{route:"/v1/organizations/plugins/{plugin_id}",attributes:{"anthropic.organization.plugin.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/plugins",Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.list",s,{route:"/v1/organizations/plugins",queryParams:["created_at[gt]","created_at[gte]","created_at[lt]","created_at[lte]","limit","marketplace_id","organization_id","owner_type","owner_user_id","page"]})})}delete(n,s={},i){const{betas:c}=s??{};return this._client.delete(U`/v1/organizations/plugins/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"ce-plugins-2026-09-01"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugins.delete",i,{route:"/v1/organizations/plugins/{plugin_id}",attributes:{"anthropic.organization.plugin.id":n}})})}}return e.BetaScanFailedError=C_,e.BetaPluginNameTakenError=N_,e.BetaScanPendingError=A_,e.BetaSkillNameTakenError=j_,e.BetaRegistrationPendingError=T_,e.Versions=IC,e.InstallationSettings=PC,e.Shares=$C,e})();class qC extends ye{create(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/claude_tag/slack_channels",{body:i,...n,headers:L([{"anthropic-beta":[...s??[],"experimental-claude-tag-2026-10-21"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.create",n,{route:"/v1/organizations/claude_tag/slack_channels",createdIDAttribute:"anthropic.organization.claude_tag.slack_channel.id"})})}retrieve(r,n={},s){const{betas:i,...c}=n??{};return this._client.get(U`/v1/organizations/claude_tag/slack_channels/${r}`,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.retrieve",s,{route:"/v1/organizations/claude_tag/slack_channels/{id}",queryParams:["include_inherited"],attributes:{"anthropic.organization.claude_tag.slack_channel.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/claude_tag/slack_channels/${r}`,{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.update",s,{route:"/v1/organizations/claude_tag/slack_channels/{id}",attributes:{"anthropic.organization.claude_tag.slack_channel.id":r}})})}list(r,n){const{betas:s,...i}=r;return this._client.getAPIList("/v1/organizations/claude_tag/slack_channels",Me,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"experimental-claude-tag-2026-10-21"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.list",n,{route:"/v1/organizations/claude_tag/slack_channels",queryParams:["include_inherited","limit","page","slack_channel_id","slack_workspace_id"]})})}delete(r,n={},s){const{betas:i}=n??{};return this._client.delete(U`/v1/organizations/claude_tag/slack_channels/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_channels.delete",s,{route:"/v1/organizations/claude_tag/slack_channels/{id}",attributes:{"anthropic.organization.claude_tag.slack_channel.id":r}})})}}class LC extends ye{retrieve(r,n={},s){const{betas:i,...c}=n??{};return this._client.get(U`/v1/organizations/claude_tag/slack_workspaces/${r}`,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_workspaces.retrieve",s,{route:"/v1/organizations/claude_tag/slack_workspaces/{id}",queryParams:["include_inherited"],attributes:{"anthropic.organization.claude_tag.slack_workspace.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/claude_tag/slack_workspaces/${r}`,{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_workspaces.update",s,{route:"/v1/organizations/claude_tag/slack_workspaces/{id}",attributes:{"anthropic.organization.claude_tag.slack_workspace.id":r}})})}list(r={},n){const{betas:s,...i}=r??{};return this._client.getAPIList("/v1/organizations/claude_tag/slack_workspaces",Me,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"experimental-claude-tag-2026-10-21"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.slack_workspaces.list",n,{route:"/v1/organizations/claude_tag/slack_workspaces",queryParams:["include_inherited","limit","page","slack_workspace_id"]})})}}class UC extends ye{create(r,n,s){const{target:i,betas:c}=n;return this._client.post(U`/v1/organizations/claude_tag/bundles/${r}/targets`,{body:i,...s,headers:L([{"anthropic-beta":[...c??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.targets.create",s,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}/targets",attributes:{"anthropic.organization.claude_tag.bundle.id":r}})})}retrieve(r,n,s){const{bundle_id:i,betas:c}=n;return this._client.get(U`/v1/organizations/claude_tag/bundles/${i}/targets/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.targets.retrieve",s,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}/targets/{target_id}",attributes:{"anthropic.organization.claude_tag.bundle.id":i,"anthropic.organization.claude_tag.bundle.target.id":r}})})}list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/claude_tag/bundles/${r}/targets`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.targets.list",s,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}/targets",queryParams:["limit","page"],attributes:{"anthropic.organization.claude_tag.bundle.id":r}})})}delete(r,n,s){const{bundle_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/claude_tag/bundles/${i}/targets/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.targets.delete",s,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}/targets/{target_id}",attributes:{"anthropic.organization.claude_tag.bundle.id":i,"anthropic.organization.claude_tag.bundle.target.id":r}})})}}var BC=(()=>{class e extends ye{constructor(){super(...arguments),this.targets=new UC(this._client)}retrieve(n,s={},i){const{betas:c}=s??{};return this._client.get(U`/v1/organizations/claude_tag/bundles/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"experimental-claude-tag-2026-10-21"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.retrieve",i,{route:"/v1/organizations/claude_tag/bundles/{bundle_id}",attributes:{"anthropic.organization.claude_tag.bundle.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/claude_tag/bundles",Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"experimental-claude-tag-2026-10-21"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.claude_tag.bundles.list",s,{route:"/v1/organizations/claude_tag/bundles",queryParams:["limit","page"]})})}}return e.Targets=UC,e})(),E_=(()=>{class e extends Ye{}return e._errorName="BetaSlackChannelSetUpSettingsRefusedError",e})(),M_=(()=>{class e extends vs{}return e._errorName="BetaAPIKeyScopeMissingError",e})(),R_=(()=>{class e extends vs{}return e._errorName="BetaClaudeTagWritesNotEnabledError",e})(),z_=(()=>{class e extends vs{}return e._errorName="BetaComplianceConfigurationRestrictedError",e})(),O_=(()=>{class e extends vs{}return e._errorName="BetaOrganizationLevelScopedAPIKeyRequiredError",e})(),P_=(()=>{class e extends Zc{}return e._errorName="BetaSlackChannelSetUpEnvironmentNotFoundError",e})(),$_=(()=>{class e extends Vr{}return e._errorName="BetaSlackChannelSetUpSettingsConflictError",e})(),GC=(()=>{class e extends ye{constructor(){super(...arguments),this.slackChannels=new qC(this._client),this.slackWorkspaces=new LC(this._client),this.bundles=new BC(this._client)}}return e.BetaSlackChannelSetUpSettingsRefusedError=E_,e.BetaAPIKeyScopeMissingError=M_,e.BetaClaudeTagWritesNotEnabledError=R_,e.BetaComplianceConfigurationRestrictedError=z_,e.BetaOrganizationLevelScopedAPIKeyRequiredError=O_,e.BetaSlackChannelSetUpEnvironmentNotFoundError=P_,e.BetaSlackChannelSetUpSettingsConflictError=$_,e.SlackChannels=qC,e.SlackWorkspaces=LC,e.Bundles=BC,e})();let HC=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/spend_limits/effective",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.effective.list",n,{route:"/v1/organizations/spend_limits/effective",queryParams:["limit","page","period","user_ids"]})})}},FC=class extends ye{retrieve(r,n){return this._client.get(U`/v1/organizations/spend_limit_increase_requests/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.retrieve",n,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/spend_limit_increase_requests",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.list",n,{route:"/v1/organizations/spend_limit_increase_requests",queryParams:["actor_ids","limit","page","status"]})})}approve(r,n,s){return this._client.post(U`/v1/organizations/spend_limit_increase_requests/${r}/approve`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.approve",s,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}/approve",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}deny(r,n,s){return this._client.post(U`/v1/organizations/spend_limit_increase_requests/${r}/deny`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.deny",s,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}/deny",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}};var I_=(()=>{class e extends vs{}return e._errorName="BetaSpendLimitsAdminAPIWritesNotEnabledError",e})(),VC=(()=>{class e extends ye{constructor(){super(...arguments),this.effective=new HC(this._client),this.increaseRequests=new FC(this._client)}retrieve(n,s){return this._client.get(U`/v1/organizations/spend_limits/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.retrieve",s,{route:"/v1/organizations/spend_limits/{spend_limit_id}",attributes:{"anthropic.organization.spend_limit.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/spend_limits",Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"spend-limit-reads-2026-09-26"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.list",s,{route:"/v1/organizations/spend_limits",queryParams:["limit","page","scope_type","workspace_id"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/spend_limits/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.delete",s,{route:"/v1/organizations/spend_limits/{spend_limit_id}",attributes:{"anthropic.organization.spend_limit.id":n}})})}set(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/spend_limits",{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.spend_limits.set",s,{route:"/v1/organizations/spend_limits",createdIDAttribute:"anthropic.organization.spend_limit.id"})})}}return e.BetaSpendLimitsAdminAPIWritesNotEnabledError=I_,e.Effective=HC,e.IncreaseRequests=FC,e})();let KC=class extends ye{retrieve(r){return this._client.get("/v1/organizations/compliance_settings",{...r,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.compliance_settings.retrieve",r,{route:"/v1/organizations/compliance_settings"})})}update(r,n){return this._client.post("/v1/organizations/compliance_settings",{body:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.compliance_settings.update",n,{route:"/v1/organizations/compliance_settings"})})}},YC=class extends ye{create(r,n){return this._client.post("/v1/organizations/external_keys",{body:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.create",n,{route:"/v1/organizations/external_keys",createdIDAttribute:"anthropic.organization.external_key.id"})})}retrieve(r,n){return this._client.get(U`/v1/organizations/external_keys/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.retrieve",n,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":r}})})}update(r,n,s){return this._client.post(U`/v1/organizations/external_keys/${r}`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.update",s,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/external_keys",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.list",n,{route:"/v1/organizations/external_keys",queryParams:["limit","page"]})})}delete(r,n){return this._client.delete(U`/v1/organizations/external_keys/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.delete",n,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":r}})})}validate(r,n){return this._client.post(U`/v1/organizations/external_keys/${r}/validate`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.external_keys.validate",n,{route:"/v1/organizations/external_keys/{external_key_id}/validate",attributes:{"anthropic.organization.external_key.id":r}})})}},WC=class extends ye{create(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/federation_issuers",{body:i,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.create",n,{route:"/v1/organizations/federation_issuers",createdIDAttribute:"anthropic.organization.federation_issuer.id"})})}retrieve(r,n={},s){const{betas:i}=n??{};return this._client.get(U`/v1/organizations/federation_issuers/${r}`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.retrieve",s,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}",attributes:{"anthropic.organization.federation_issuer.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/federation_issuers/${r}`,{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.update",s,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}",attributes:{"anthropic.organization.federation_issuer.id":r}})})}list(r={},n){const{betas:s,...i}=r??{};return this._client.getAPIList("/v1/organizations/federation_issuers",Me,{query:i,...n,headers:L([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.list",n,{route:"/v1/organizations/federation_issuers",queryParams:["include_archived","limit","page"]})})}archive(r,n={},s){const{betas:i}=n??{};return this._client.post(U`/v1/organizations/federation_issuers/${r}/archive`,{...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.issuers.archive",s,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}/archive",attributes:{"anthropic.organization.federation_issuer.id":r}})})}},XC=class extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/federation_rules/${r}/workspaces`,Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.workspaces.list",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.federation_rule.id":r}})})}add(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/federation_rules/${r}/workspaces`,{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.workspaces.add",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces",attributes:{"anthropic.organization.federation_rule.id":r},createdIDAttribute:"anthropic.organization.federation_rule.workspace.id",createdIDField:"workspace_id"})})}remove(r,n,s){const{federation_rule_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/federation_rules/${i}/workspaces/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.workspaces.remove",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.federation_rule.id":i,"anthropic.organization.federation_rule.workspace.id":r}})})}};var QC=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new XC(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/federation_rules",{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.create",s,{route:"/v1/organizations/federation_rules",createdIDAttribute:"anthropic.organization.federation_rule.id"})})}retrieve(n,s={},i){const{betas:c}=s??{};return this._client.get(U`/v1/organizations/federation_rules/${n}`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.retrieve",i,{route:"/v1/organizations/federation_rules/{federation_rule_id}",attributes:{"anthropic.organization.federation_rule.id":n}})})}update(n,s,i){const{betas:c,...d}=s;return this._client.post(U`/v1/organizations/federation_rules/${n}`,{body:d,...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.update",i,{route:"/v1/organizations/federation_rules/{federation_rule_id}",attributes:{"anthropic.organization.federation_rule.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/federation_rules",Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.list",s,{route:"/v1/organizations/federation_rules",queryParams:["include_archived","issuer_id","limit","page"]})})}archive(n,s={},i){const{betas:c}=s??{};return this._client.post(U`/v1/organizations/federation_rules/${n}/archive`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.federation.rules.archive",i,{route:"/v1/organizations/federation_rules/{federation_rule_id}/archive",attributes:{"anthropic.organization.federation_rule.id":n}})})}}return e.Workspaces=XC,e})(),JC=(()=>{class e extends ye{constructor(){super(...arguments),this.issuers=new WC(this._client),this.rules=new QC(this._client)}}return e.Issuers=WC,e.Rules=QC,e})();let ZC=class extends ye{create(r,n){return this._client.post("/v1/organizations/invites",{body:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.invites.create",n,{route:"/v1/organizations/invites",createdIDAttribute:"anthropic.organization.invite.id"})})}retrieve(r,n){return this._client.get(U`/v1/organizations/invites/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.invites.retrieve",n,{route:"/v1/organizations/invites/{invite_id}",attributes:{"anthropic.organization.invite.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/invites",ns,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.invites.list",n,{route:"/v1/organizations/invites",queryParams:["after_id","before_id","email","limit","roles","statuses"]})})}delete(r,n){return this._client.delete(U`/v1/organizations/invites/${r}`,{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.invites.delete",n,{route:"/v1/organizations/invites/{invite_id}",attributes:{"anthropic.organization.invite.id":r}})})}};class eN extends ye{retrieve(r,n={},s){const{betas:i,...c}=n??{};return this._client.get(U`/v1/organizations/plugin_marketplaces/${r}`,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.retrieve",s,{route:"/v1/organizations/plugin_marketplaces/{marketplace_id}",queryParams:["organization_id"],attributes:{"anthropic.organization.plugin_marketplace.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/plugin_marketplaces/${r}`,{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"ce-plugins-2026-09-01"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.update",s,{route:"/v1/organizations/plugin_marketplaces/{marketplace_id}",attributes:{"anthropic.organization.plugin_marketplace.id":r}})})}list(r={},n){const{betas:s,...i}=r??{};return this._client.getAPIList("/v1/organizations/plugin_marketplaces",Me,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.list",n,{route:"/v1/organizations/plugin_marketplaces",queryParams:["limit","organization_id","owner_type","page","source"]})})}validateArchive(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/plugin_marketplaces/validate_archive",Kr({body:i,...n,headers:L([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.validate_archive",n,{route:"/v1/organizations/plugin_marketplaces/validate_archive"})},this._client))}validateRepository(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/plugin_marketplaces/validate_repository",{body:i,...n,headers:L([{"anthropic-beta":[...s??[],"ce-plugins-2026-09-01"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.plugin_marketplaces.validate_repository",n,{route:"/v1/organizations/plugin_marketplaces/validate_repository"})})}}let tN=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/rate_limits",Me,{query:r,...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rate_limits.list",n,{route:"/v1/organizations/rate_limits",queryParams:["group_type","limit","model","page"]})})}};class nN extends ye{create(r,n){const{betas:s,...i}=r;return this._client.post("/v1/organizations/webhooks",{body:i,...n,headers:L([{"anthropic-beta":[...s??[],"webhooks-2026-10-07"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.create",n,{route:"/v1/organizations/webhooks",createdIDAttribute:"anthropic.organization.webhook.id"})})}retrieve(r,n={},s){const{betas:i}=n??{};return this._client.get(U`/v1/organizations/webhooks/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"webhooks-2026-10-07"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.retrieve",s,{route:"/v1/organizations/webhooks/{webhook_endpoint_id}",attributes:{"anthropic.organization.webhook.id":r}})})}update(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/webhooks/${r}`,{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"webhooks-2026-10-07"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.update",s,{route:"/v1/organizations/webhooks/{webhook_endpoint_id}",attributes:{"anthropic.organization.webhook.id":r}})})}list(r={},n){const{betas:s,...i}=r??{};return this._client.getAPIList("/v1/organizations/webhooks",ns,{query:i,...n,headers:L([{"anthropic-beta":[...s??[],"webhooks-2026-10-07"].toString()},n?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.list",n,{route:"/v1/organizations/webhooks",queryParams:["after_id","before_id","limit","order"]})})}delete(r,n={},s){const{betas:i}=n??{};return this._client.delete(U`/v1/organizations/webhooks/${r}`,{...s,headers:L([{"anthropic-beta":[...i??[],"webhooks-2026-10-07"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.delete",s,{route:"/v1/organizations/webhooks/{webhook_endpoint_id}",attributes:{"anthropic.organization.webhook.id":r}})})}regenerateSigningSecret(r,n={},s){const{betas:i}=n??{};return this._client.post(U`/v1/organizations/webhooks/${r}/regenerate_signing_secret`,{...s,headers:L([{"anthropic-beta":[...i??[],"webhooks-2026-10-07"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.webhooks.regenerate_signing_secret",s,{route:"/v1/organizations/webhooks/{webhook_endpoint_id}/regenerate_signing_secret",attributes:{"anthropic.organization.webhook.id":r}})})}}let sN=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/rbac_groups/${r}/members`,Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.members.list",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members",queryParams:["limit","page"],attributes:{"anthropic.organization.rbac_group.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/rbac_groups/${r}/members`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.members.add",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members",attributes:{"anthropic.organization.rbac_group.id":r},createdIDAttribute:"anthropic.organization.rbac_group.member.id",createdIDField:"user_id"})})}remove(r,n,s){const{rbac_group_id:i}=n;return this._client.delete(U`/v1/organizations/rbac_groups/${i}/members/${r}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.members.remove",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members/{user_id}",attributes:{"anthropic.organization.rbac_group.id":i,"anthropic.organization.rbac_group.member.id":r}})})}};var aN=(()=>{class e extends ye{constructor(){super(...arguments),this.members=new sN(this._client)}create(n,s){return this._client.post("/v1/organizations/rbac_groups",{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.create",s,{route:"/v1/organizations/rbac_groups",createdIDAttribute:"anthropic.organization.rbac_group.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/rbac_groups/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.retrieve",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/rbac_groups/${n}`,{body:s,...i,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.update",i,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/rbac_groups",Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.list",s,{route:"/v1/organizations/rbac_groups",queryParams:["limit","page"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/rbac_groups/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_groups.delete",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}}return e.Members=sN,e})();let rN=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/rbac_roles/${r}/permissions`,Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_roles.permissions.list",s,{route:"/v1/organizations/rbac_roles/{rbac_role_id}/permissions",queryParams:["limit","page"],attributes:{"anthropic.organization.rbac_role.id":r}})})}};var iN=(()=>{class e extends ye{constructor(){super(...arguments),this.permissions=new rN(this._client)}retrieve(n,s){return this._client.get(U`/v1/organizations/rbac_roles/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_roles.retrieve",s,{route:"/v1/organizations/rbac_roles/{rbac_role_id}",attributes:{"anthropic.organization.rbac_role.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/rbac_roles",Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.rbac_roles.list",s,{route:"/v1/organizations/rbac_roles",queryParams:["limit","page"]})})}}return e.Permissions=rN,e})();let oN=class extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/service_accounts/${r}/workspaces`,Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.workspaces.list",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.service_account.id":r}})})}add(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/service_accounts/${r}/workspaces`,{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.workspaces.add",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces",attributes:{"anthropic.organization.service_account.id":r},createdIDAttribute:"anthropic.organization.service_account.workspace.id",createdIDField:"workspace_id"})})}remove(r,n,s){const{service_account_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/service_accounts/${i}/workspaces/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.workspaces.remove",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.service_account.id":i,"anthropic.organization.service_account.workspace.id":r}})})}};var lN=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new oN(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/service_accounts",{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.create",s,{route:"/v1/organizations/service_accounts",createdIDAttribute:"anthropic.organization.service_account.id"})})}retrieve(n,s={},i){const{betas:c}=s??{};return this._client.get(U`/v1/organizations/service_accounts/${n}`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.retrieve",i,{route:"/v1/organizations/service_accounts/{service_account_id}",attributes:{"anthropic.organization.service_account.id":n}})})}update(n,s,i){const{betas:c,...d}=s;return this._client.post(U`/v1/organizations/service_accounts/${n}`,{body:d,...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.update",i,{route:"/v1/organizations/service_accounts/{service_account_id}",attributes:{"anthropic.organization.service_account.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/service_accounts",Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.list",s,{route:"/v1/organizations/service_accounts",queryParams:["include_archived","limit","page"]})})}archive(n,s={},i){const{betas:c}=s??{};return this._client.post(U`/v1/organizations/service_accounts/${n}/archive`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.service_accounts.archive",i,{route:"/v1/organizations/service_accounts/{service_account_id}/archive",attributes:{"anthropic.organization.service_account.id":n}})})}}return e.Workspaces=oN,e})();let cN=class extends ye{list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/telemetry_destinations/${r}/workspaces`,Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.workspaces.list",s,{route:"/v1/organizations/telemetry_destinations/{destination_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.telemetry_destination.id":r}})})}add(r,n,s){const{destination_id:i,betas:c}=n;return this._client.post(U`/v1/organizations/telemetry_destinations/${i}/workspaces/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.workspaces.add",s,{route:"/v1/organizations/telemetry_destinations/{destination_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.telemetry_destination.id":i,"anthropic.organization.telemetry_destination.workspace.id":r}})})}remove(r,n,s){const{destination_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/telemetry_destinations/${i}/workspaces/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.workspaces.remove",s,{route:"/v1/organizations/telemetry_destinations/{destination_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.telemetry_destination.id":i,"anthropic.organization.telemetry_destination.workspace.id":r}})})}};var uN=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new cN(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/telemetry_destinations",{body:c,...s,headers:L([{"anthropic-beta":[...i??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.create",s,{route:"/v1/organizations/telemetry_destinations",createdIDAttribute:"anthropic.organization.telemetry_destination.id"})})}retrieve(n,s={},i){const{betas:c}=s??{};return this._client.get(U`/v1/organizations/telemetry_destinations/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.retrieve",i,{route:"/v1/organizations/telemetry_destinations/{destination_id}",attributes:{"anthropic.organization.telemetry_destination.id":n}})})}update(n,s,i){const{betas:c,...d}=s;return this._client.post(U`/v1/organizations/telemetry_destinations/${n}`,{body:d,...i,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.update",i,{route:"/v1/organizations/telemetry_destinations/{destination_id}",attributes:{"anthropic.organization.telemetry_destination.id":n}})})}list(n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList("/v1/organizations/telemetry_destinations",Me,{query:c,...s,headers:L([{"anthropic-beta":[...i??[],"telemetry-destinations-2026-08-11"].toString()},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.list",s,{route:"/v1/organizations/telemetry_destinations",queryParams:["limit","page","workspace_ids"]})})}delete(n,s={},i){const{betas:c}=s??{};return this._client.delete(U`/v1/organizations/telemetry_destinations/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.delete",i,{route:"/v1/organizations/telemetry_destinations/{destination_id}",attributes:{"anthropic.organization.telemetry_destination.id":n}})})}test(n,s={},i){const{betas:c}=s??{};return this._client.post(U`/v1/organizations/telemetry_destinations/${n}/test`,{...i,headers:L([{"anthropic-beta":[...c??[],"telemetry-destinations-2026-08-11"].toString()},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.telemetry_destinations.test",i,{route:"/v1/organizations/telemetry_destinations/{destination_id}/test",attributes:{"anthropic.organization.telemetry_destination.id":n}})})}}return e.Workspaces=cN,e})();let dN=class extends ye{retrieve(r,n,s){const{workspace_id:i}=n;return this._client.get(U`/v1/organizations/workspaces/${i}/members/${r}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/members/${r}`,{body:c,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/members`,ns,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/members",queryParams:["after_id","before_id","limit"],attributes:{"anthropic.organization.workspace.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/workspaces/${r}/members`,{body:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.add",s,{route:"/v1/organizations/workspaces/{workspace_id}/members",attributes:{"anthropic.organization.workspace.id":r},createdIDAttribute:"anthropic.organization.workspace.member.id",createdIDField:"user_id"})})}remove(r,n,s){const{workspace_id:i}=n;return this._client.delete(U`/v1/organizations/workspaces/${i}/members/${r}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.members.remove",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}},hN=class extends ye{update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/rate_limits/${r}`,{body:c,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.rate_limits.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/rate_limits/{rate_limit_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.rate_limit.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/rate_limits`,Me,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.rate_limits.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/rate_limits",queryParams:["group_type","include_inherited","limit","page"],attributes:{"anthropic.organization.workspace.id":r}})})}},mN=class extends ye{retrieve(r,n,s){const{workspace_id:i,betas:c}=n;return this._client.get(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}update(r,n,s){const{workspace_id:i,betas:c,...d}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{body:d,...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}list(r,n={},s){const{betas:i,...c}=n??{};return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/service_accounts`,Me,{query:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts",queryParams:["limit","page"],attributes:{"anthropic.organization.workspace.id":r}})})}add(r,n,s){const{betas:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${r}/service_accounts`,{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.add",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts",attributes:{"anthropic.organization.workspace.id":r},createdIDAttribute:"anthropic.organization.workspace.service_account.id",createdIDField:"service_account_id"})})}remove(r,n,s){const{workspace_id:i,betas:c}=n;return this._client.delete(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.service_accounts.remove",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}};var fN=(()=>{class e extends ye{constructor(){super(...arguments),this.rateLimits=new hN(this._client),this.members=new dN(this._client),this.serviceAccounts=new mN(this._client)}create(n,s){const{betas:i,...c}=n;return this._client.post("/v1/organizations/workspaces",{body:c,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.create",s,{route:"/v1/organizations/workspaces",createdIDAttribute:"anthropic.organization.workspace.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/workspaces/${n}`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}",attributes:{"anthropic.organization.workspace.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/workspaces/${n}`,{body:s,...i,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.update",i,{route:"/v1/organizations/workspaces/{workspace_id}",attributes:{"anthropic.organization.workspace.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/workspaces",ns,{query:n,...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.list",s,{route:"/v1/organizations/workspaces",queryParams:["after_id","before_id","ids","include_archived","include_default","limit"]})})}archive(n,s){return this._client.post(U`/v1/organizations/workspaces/${n}/archive`,{...s,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.workspaces.archive",s,{route:"/v1/organizations/workspaces/{workspace_id}/archive",attributes:{"anthropic.organization.workspace.id":n}})})}}return e.RateLimits=hN,e.Members=dN,e.ServiceAccounts=mN,e})(),pN=(()=>{class e extends ye{constructor(){super(...arguments),this.apiKeys=new bC(this._client),this.externalKeys=new YC(this._client),this.federation=new JC(this._client),this.invites=new ZC(this._client),this.serviceAccounts=new lN(this._client),this.users=new OC(this._client),this.workspaces=new fN(this._client),this.rateLimits=new tN(this._client),this.complianceSettings=new KC(this._client),this.analytics=new zC(this._client),this.spendLimits=new VC(this._client),this.rbacGroups=new aN(this._client),this.rbacRoles=new iN(this._client),this.plugins=new DC(this._client),this.pluginMarketplaces=new eN(this._client),this.telemetryDestinations=new uN(this._client),this.webhooks=new nN(this._client),this.claudeTag=new GC(this._client)}retrieve(n){return this._client.get("/v1/organizations/me",{...n,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.organization.retrieve",n,{route:"/v1/organizations/me"})})}}return e.APIKeys=bC,e.ExternalKeys=YC,e.Federation=JC,e.Invites=ZC,e.ServiceAccounts=lN,e.Users=OC,e.BetaCannotSignOutPrimaryOwnerError=y_,e.BetaCannotSignOutSelfError=__,e.BetaCannotSignOutManagedMemberError=v_,e.BetaCannotSignOutMembershipAdminError=w_,e.BetaCannotSignOutOwnerError=S_,e.BetaCannotSignOutPrivilegedMemberError=k_,e.Workspaces=fN,e.RateLimits=tN,e.ComplianceSettings=KC,e.Analytics=zC,e.SpendLimits=VC,e.BetaSpendLimitsAdminAPIWritesNotEnabledError=I_,e.RBACGroups=aN,e.RBACRoles=iN,e.Plugins=DC,e.BetaScanFailedError=C_,e.BetaPluginNameTakenError=N_,e.BetaScanPendingError=A_,e.BetaSkillNameTakenError=j_,e.BetaRegistrationPendingError=T_,e.PluginMarketplaces=eN,e.TelemetryDestinations=uN,e.Webhooks=nN,e.ClaudeTag=GC,e.BetaSlackChannelSetUpSettingsRefusedError=E_,e.BetaAPIKeyScopeMissingError=M_,e.BetaClaudeTagWritesNotEnabledError=R_,e.BetaComplianceConfigurationRestrictedError=z_,e.BetaOrganizationLevelScopedAPIKeyRequiredError=O_,e.BetaSlackChannelSetUpEnvironmentNotFoundError=P_,e.BetaSlackChannelSetUpSettingsConflictError=$_,e})(),gN=(()=>{class e extends ye{list(n,s={},i){const{betas:c,workspace_id:d,...f}=s??{};return this._client.getAPIList(U`/v1/sessions/${n}/events`,Me,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.events.list",i,{route:"/v1/sessions/{session_id}/events",queryParams:["created_at[gt]","created_at[gte]","created_at[lt]","created_at[lte]","limit","order","page","types"],attributes:{"anthropic.session.id":n}})})}send(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/sessions/${n}/events`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.events.send",i,{route:"/v1/sessions/{session_id}/events",attributes:{"anthropic.session.id":n}})})}stream(n,s={},i){const{betas:c,workspace_id:d,...f}=s??{};return this._client.get(U`/v1/sessions/${n}/events/stream`,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),stream:!0,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.events.stream",i,{route:"/v1/sessions/{session_id}/events/stream",queryParams:["event_deltas"],attributes:{"anthropic.session.id":n}})})}toolRunner(n,s){return new Xx(n,{...s,client:this._client})}}return e.SessionToolRunner=Xx,e})();class bN extends ye{retrieve(r,n,s){const{session_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/sessions/${i}/resources/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.retrieve",s,{route:"/v1/sessions/{session_id}/resources/{resource_id}",attributes:{"anthropic.session.id":i,"anthropic.session.resource.id":r}})})}update(r,n,s){const{session_id:i,betas:c,workspace_id:d,...f}=n;return this._client.post(U`/v1/sessions/${i}/resources/${r}`,{body:f,...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.update",s,{route:"/v1/sessions/{session_id}/resources/{resource_id}",attributes:{"anthropic.session.id":i,"anthropic.session.resource.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/sessions/${r}/resources`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.list",s,{route:"/v1/sessions/{session_id}/resources",queryParams:["limit","page"],attributes:{"anthropic.session.id":r}})})}delete(r,n,s){const{session_id:i,betas:c,workspace_id:d}=n;return this._client.delete(U`/v1/sessions/${i}/resources/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.delete",s,{route:"/v1/sessions/{session_id}/resources/{resource_id}",attributes:{"anthropic.session.id":i,"anthropic.session.resource.id":r}})})}add(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/sessions/${r}/resources`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.resources.add",s,{route:"/v1/sessions/{session_id}/resources",attributes:{"anthropic.session.id":r},createdIDAttribute:"anthropic.session.resource.id"})})}}class xN extends ye{list(r,n,s){const{session_id:i,betas:c,workspace_id:d,...f}=n;return this._client.getAPIList(U`/v1/sessions/${i}/threads/${r}/events`,Me,{query:f,...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.events.list",s,{route:"/v1/sessions/{session_id}/threads/{thread_id}/events",queryParams:["limit","page"],attributes:{"anthropic.session.id":i,"anthropic.session.thread.id":r}})})}stream(r,n,s){const{session_id:i,betas:c,workspace_id:d,...f}=n;return this._client.get(U`/v1/sessions/${i}/threads/${r}/stream`,{query:f,...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),stream:!0,__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.events.stream",s,{route:"/v1/sessions/{session_id}/threads/{thread_id}/stream",queryParams:["event_deltas"],attributes:{"anthropic.session.id":i,"anthropic.session.thread.id":r}})})}}var yN=(()=>{class e extends ye{constructor(){super(...arguments),this.events=new xN(this._client)}retrieve(n,s,i){const{session_id:c,betas:d,workspace_id:f}=s;return this._client.get(U`/v1/sessions/${c}/threads/${n}`,{...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.retrieve",i,{route:"/v1/sessions/{session_id}/threads/{thread_id}",attributes:{"anthropic.session.id":c,"anthropic.session.thread.id":n}})})}list(n,s={},i){const{betas:c,workspace_id:d,...f}=s??{};return this._client.getAPIList(U`/v1/sessions/${n}/threads`,Me,{query:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.list",i,{route:"/v1/sessions/{session_id}/threads",queryParams:["limit","page","statuses"],attributes:{"anthropic.session.id":n}})})}archive(n,s,i){const{session_id:c,betas:d,workspace_id:f}=s;return this._client.post(U`/v1/sessions/${c}/threads/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...d??[],"managed-agents-2026-04-01"].toString(),...f!=null?{"anthropic-workspace-id":f}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.threads.archive",i,{route:"/v1/sessions/{session_id}/threads/{thread_id}/archive",attributes:{"anthropic.session.id":c,"anthropic.session.thread.id":n}})})}}return e.Events=xN,e})(),_N=(()=>{class e extends ye{constructor(){super(...arguments),this.events=new gN(this._client),this.resources=new bN(this._client),this.threads=new yN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n,f={body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"}};return this._client.post("/v1/sessions",{...f,__span:N(this._client,"anthropic.sessions.create",s,{route:"/v1/sessions",attributes:VP(d),createdIDAttribute:"anthropic.session.id",request:f})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/sessions/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.retrieve",i,{route:"/v1/sessions/{session_id}",attributes:{"anthropic.session.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/sessions/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.update",i,{route:"/v1/sessions/{session_id}",attributes:{"anthropic.session.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/sessions",n8,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.list",s,{route:"/v1/sessions",queryParams:["agent_id","agent_version","created_at[gt]","created_at[gte]","created_at[lt]","created_at[lte]","deployment_id","include_archived","limit","memory_store_id","order","page","statuses"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/sessions/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.delete",i,{route:"/v1/sessions/{session_id}",attributes:{"anthropic.session.id":n}})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/sessions/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.sessions.archive",i,{route:"/v1/sessions/{session_id}/archive",attributes:{"anthropic.session.id":n}})})}}return e.Events=gN,e.Resources=bN,e.Threads=yN,e})();let vN=class extends ye{create(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/skills/${r}/versions`,Kr({body:d,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.versions.create",s,{route:"/v1/skills/{skill_id}/versions",attributes:{"anthropic.skill.id":r},createdIDAttribute:"anthropic.skill.version.id"})},this._client,!1))}retrieve(r,n,s){const{skill_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/skills/${i}/versions/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.versions.retrieve",s,{route:"/v1/skills/{skill_id}/versions/{version}",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/skills/${r}/versions`,Me,{query:d,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.versions.list",s,{route:"/v1/skills/{skill_id}/versions",queryParams:["limit","page"],attributes:{"anthropic.skill.id":r}})})}delete(r,n,s){const{skill_id:i,betas:c,workspace_id:d}=n;return this._client.delete(U`/v1/skills/${i}/versions/${r}`,{...s,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.versions.delete",s,{route:"/v1/skills/{skill_id}/versions/{version}",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}download(r,n,s){const{skill_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/skills/${i}/versions/${r}/content`,{...s,headers:L([{Accept:"application/binary",...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__binaryResponse:!0,__span:N(this._client,"anthropic.skills.versions.download",s,{route:"/v1/skills/{skill_id}/versions/{version}/content",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}};var wN=(()=>{class e extends ye{constructor(){super(...arguments),this.versions=new vN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/skills",Kr({body:d,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.create",s,{route:"/v1/skills",createdIDAttribute:"anthropic.skill.id"})},this._client,!1))}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/skills/${n}`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.retrieve",i,{route:"/v1/skills/{skill_id}",attributes:{"anthropic.skill.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/skills",Me,{query:d,...s,headers:L([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.list",s,{route:"/v1/skills",queryParams:["limit","page","source"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/skills/${n}`,{...i,headers:L([{...c?.toString()!=null?{"anthropic-beta":c?.toString()}:void 0,...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.skills.delete",i,{route:"/v1/skills/{skill_id}",attributes:{"anthropic.skill.id":n}})})}}return e.Versions=vN,e})();class SN extends ye{create(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/tunnels/${r}/certificates`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.certificates.create",s,{route:"/v1/tunnels/{tunnel_id}/certificates",attributes:{"anthropic.tunnel.id":r},createdIDAttribute:"anthropic.tunnel.certificate.id"})})}retrieve(r,n,s){const{tunnel_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/tunnels/${i}/certificates/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.certificates.retrieve",s,{route:"/v1/tunnels/{tunnel_id}/certificates/{certificate_id}",attributes:{"anthropic.tunnel.id":i,"anthropic.tunnel.certificate.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/tunnels/${r}/certificates`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.certificates.list",s,{route:"/v1/tunnels/{tunnel_id}/certificates",queryParams:["include_archived","limit","page"],attributes:{"anthropic.tunnel.id":r}})})}archive(r,n,s){const{tunnel_id:i,betas:c,workspace_id:d}=n;return this._client.post(U`/v1/tunnels/${i}/certificates/${r}/archive`,{...s,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.certificates.archive",s,{route:"/v1/tunnels/{tunnel_id}/certificates/{certificate_id}/archive",attributes:{"anthropic.tunnel.id":i,"anthropic.tunnel.certificate.id":r}})})}}var kN=(()=>{class e extends ye{constructor(){super(...arguments),this.certificates=new SN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/tunnels",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.create",s,{route:"/v1/tunnels",createdIDAttribute:"anthropic.tunnel.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/tunnels/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.retrieve",i,{route:"/v1/tunnels/{tunnel_id}",attributes:{"anthropic.tunnel.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/tunnels",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.list",s,{route:"/v1/tunnels",queryParams:["include_archived","limit","page"]})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/tunnels/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.archive",i,{route:"/v1/tunnels/{tunnel_id}/archive",attributes:{"anthropic.tunnel.id":n}})})}revealToken(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/tunnels/${n}/reveal_token`,{...i,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.reveal_token",i,{route:"/v1/tunnels/{tunnel_id}/reveal_token",attributes:{"anthropic.tunnel.id":n}})})}rotateToken(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/tunnels/${n}/rotate_token`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"mcp-tunnels-2026-06-22"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.tunnels.rotate_token",i,{route:"/v1/tunnels/{tunnel_id}/rotate_token",attributes:{"anthropic.tunnel.id":n}})})}}return e.Certificates=SN,e})();let CN=class extends ye{create(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/user_profiles/${r}/action_urls`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.action_urls.create",s,{route:"/v1/user_profiles/{user_profile_id}/action_urls",attributes:{"anthropic.user_profile.id":r}})})}};var NN=(()=>{class e extends ye{constructor(){super(...arguments),this.actionURLs=new CN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/user_profiles",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.create",s,{route:"/v1/user_profiles",createdIDAttribute:"anthropic.user_profile.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/user_profiles/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"user-profiles-2026-08-18"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.retrieve",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/user_profiles/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"user-profiles-2026-08-18"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.update",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/user_profiles",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"user-profiles-2026-08-18"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.list",s,{route:"/v1/user_profiles",queryParams:["limit","order","order_by","page"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/user_profiles/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"user-profiles-2026-08-18"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.delete",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}createEnrollmentURL(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/user_profiles/${n}/enrollment_url`,{...i,headers:L([{"anthropic-beta":[...c??[],"user-profiles-2026-08-18"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.user_profiles.create_enrollment_url",i,{route:"/v1/user_profiles/{user_profile_id}/enrollment_url",attributes:{"anthropic.user_profile.id":n}})})}}return e.ActionURLs=CN,e})();class AN extends ye{create(r,n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post(U`/v1/vaults/${r}/credentials`,{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.create",s,{route:"/v1/vaults/{vault_id}/credentials",attributes:{"anthropic.vault.id":r},createdIDAttribute:"anthropic.vault.credential.id"})})}retrieve(r,n,s){const{vault_id:i,betas:c,workspace_id:d}=n;return this._client.get(U`/v1/vaults/${i}/credentials/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.retrieve",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}update(r,n,s){const{vault_id:i,betas:c,workspace_id:d,...f}=n;return this._client.post(U`/v1/vaults/${i}/credentials/${r}`,{body:f,...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.update",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}list(r,n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList(U`/v1/vaults/${r}/credentials`,Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.list",s,{route:"/v1/vaults/{vault_id}/credentials",queryParams:["include_archived","limit","page"],attributes:{"anthropic.vault.id":r}})})}delete(r,n,s){const{vault_id:i,betas:c,workspace_id:d}=n;return this._client.delete(U`/v1/vaults/${i}/credentials/${r}`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.delete",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}archive(r,n,s){const{vault_id:i,betas:c,workspace_id:d}=n;return this._client.post(U`/v1/vaults/${i}/credentials/${r}/archive`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.archive",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}/archive",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}mcpOAuthValidate(r,n,s){const{vault_id:i,betas:c,workspace_id:d}=n;return this._client.post(U`/v1/vaults/${i}/credentials/${r}/mcp_oauth_validate`,{...s,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.credentials.mcp_oauth_validate",s,{route:"/v1/vaults/{vault_id}/credentials/{credential_id}/mcp_oauth_validate",attributes:{"anthropic.vault.id":i,"anthropic.vault.credential.id":r}})})}}var jN=(()=>{class e extends ye{constructor(){super(...arguments),this.credentials=new AN(this._client)}create(n,s){const{betas:i,workspace_id:c,...d}=n;return this._client.post("/v1/vaults",{body:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.create",s,{route:"/v1/vaults",createdIDAttribute:"anthropic.vault.id"})})}retrieve(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.get(U`/v1/vaults/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.retrieve",i,{route:"/v1/vaults/{vault_id}",attributes:{"anthropic.vault.id":n}})})}update(n,s,i){const{betas:c,workspace_id:d,...f}=s;return this._client.post(U`/v1/vaults/${n}`,{body:f,...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.update",i,{route:"/v1/vaults/{vault_id}",attributes:{"anthropic.vault.id":n}})})}list(n={},s){const{betas:i,workspace_id:c,...d}=n??{};return this._client.getAPIList("/v1/vaults",Me,{query:d,...s,headers:L([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString(),...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.list",s,{route:"/v1/vaults",queryParams:["include_archived","limit","page"]})})}delete(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.delete(U`/v1/vaults/${n}`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.delete",i,{route:"/v1/vaults/{vault_id}",attributes:{"anthropic.vault.id":n}})})}archive(n,s={},i){const{betas:c,workspace_id:d}=s??{};return this._client.post(U`/v1/vaults/${n}/archive`,{...i,headers:L([{"anthropic-beta":[...c??[],"managed-agents-2026-04-01"].toString(),...d!=null?{"anthropic-workspace-id":d}:void 0},i?.headers]),__qualifiers:{beta:"true"},__span:N(this._client,"anthropic.vaults.archive",i,{route:"/v1/vaults/{vault_id}/archive",attributes:{"anthropic.vault.id":n}})})}}return e.Credentials=AN,e})(),kr,jf,Po,xc,Tf,$o,yc,Ef,TN,Mf,Rf,EN=(()=>{class e extends x_{constructor(n,s,i){super(n,{client:i}),kr.add(this),jf.set(this,void 0),Po.set(this,0),xc.set(this,[]),Tf.set(this,[]),$o.set(this,void 0),yc.set(this,[]),Ef.set(this,!1),se(this,jf,s)}get toolCalls(){return v(this,Tf,"f")}_deliverEvent(n,s){var i;se(this,Po,(i=v(this,Po,"f"),i++,i));const c=n.type==="content_block_stop"?s?.content[n.index]:void 0,d=c?.type==="tool_use"?c:void 0;d&&v(this,Tf,"f").push(d),super._deliverEvent(n,s),v(this,kr,"m",TN).call(this,n,d),v(this,kr,"m",Mf).call(this)}[(jf=new WeakMap,Po=new WeakMap,xc=new WeakMap,Tf=new WeakMap,$o=new WeakMap,yc=new WeakMap,Ef=new WeakMap,kr=new WeakSet,Symbol.asyncIterator)](){const n=super[Symbol.asyncIterator](),s={handled:v(this,Po,"f")};v(this,xc,"f").push(s);let i=!1;return{next:async()=>{i&&(i=!1,s.handled++,v(this,kr,"m",Mf).call(this));try{const c=await n.next();return i=!c.done,c.done&&v(this,kr,"m",Rf).call(this,s),c}catch(c){throw v(this,kr,"m",Rf).call(this,s),c}},return:async()=>{const c=n.return?.();return v(this,kr,"m",Rf).call(this,s),await c??{value:void 0,done:!0}}}}}return TN=function(n,s){if(v(this,Ef,"f"))return;if(n.type==="content_block_start"&&n.content_block.type==="fallback"){se(this,Ef,!0),se(this,$o,void 0);return}const i=n.type==="content_block_start"||n.type==="message_delta"&&n.delta.stop_reason==="tool_use";v(this,$o,"f")&&i&&(v(this,yc,"f").push({toolUse:v(this,$o,"f"),event:v(this,Po,"f")}),se(this,$o,void 0)),s&&se(this,$o,s)},Mf=function(){if(this.errored||this.controller.signal.aborted)return;const n=Math.min(v(this,Po,"f"),...v(this,xc,"f").map(s=>s.handled));for(;v(this,yc,"f")[0]&&v(this,yc,"f")[0].event<=n;)v(this,jf,"f").call(this,v(this,yc,"f").shift().toolUse)},Rf=function(n){const s=v(this,xc,"f").indexOf(n);s>=0&&(v(this,xc,"f").splice(s,1),v(this,kr,"m",Mf).call(this))},e})();function MN(){let e,r;return{promise:new Promise((s,i)=>{e=s,r=i}),resolve:e,reject:r}}var wn,Pn,rn,nn,Vt,Xt,zi,RN,Jb,Nd,zN,Zb,ex,ON,tx,PN;class i${constructor(r,n,s){this.fields=r,this.ownMessages=n,this.ownCreateOnly=s,this.deferredMessages=[],this.replacementHistory=null,this.createOnly=HT(r)}}var BT=(()=>{class e{constructor({params:n,options:s,threading:i,logger:c}){wn.add(this),Pn.set(this,void 0),rn.set(this,[]),nn.set(this,[]),Vt.set(this,void 0),Xt.set(this,null),zi.set(this,void 0);const{messages:d,unsupportedRequestBehavior:f,...p}=n;lp(p),this.options=s,this.unsupportedRequestBehavior=f??"error",se(this,Pn,p),se(this,Vt,i?{type:"create",replacesLostThread:!1}:{type:"never_threaded"}),se(this,zi,c),this.push(d??[])}get threading(){return v(this,Vt,"f").type==="create"||v(this,Vt,"f").type==="continue"}get previousMessageId(){return v(this,Vt,"f").type==="continue"?v(this,Vt,"f").previousMessageId:null}get messages(){const n=v(this,Xt,"f")?.replacementHistory?.slice()??[...v(this,rn,"f"),...v(this,nn,"f")].map(s=>s.param);return v(this,Xt,"f")&&n.push(...v(this,Xt,"f").deferredMessages.map(Ec)),n}get params(){const n=v(this,Vt,"f").type==="create"?v(this,Xt,"f")?.ownCreateOnly:void 0;return{...v(this,Pn,"f"),...n,messages:this.messages}}push(n){if(v(this,Xt,"f")){v(this,Xt,"f").deferredMessages.push(...n);return}for(const s of n)v(this,wn,"m",Jb).call(this,s)||v(this,nn,"f").push({param:Ec(s),reply:null})}update(n={},s={}){lp(n),se(this,Pn,{...v(this,Pn,"f"),...Go(n)}),this.options={...this.options,...Go(s)};for(const i of nx)n[i]!==void 0&&delete v(this,Xt,"f")?.ownCreateOnly[i]}fork(n=v(this,Pn,"f")){const s=new e({params:{...n,unsupportedRequestBehavior:this.unsupportedRequestBehavior},options:this.options,threading:v(this,Vt,"f").type!=="never_threaded",logger:v(this,zi,"f")});return this.threading||s.stopThreading(),v(this,Xt,"f")?.replacementHistory?se(s,nn,v(this,Xt,"f").replacementHistory.map(i=>({param:i,reply:null}))):(se(s,rn,[...v(this,rn,"f")]),se(s,nn,[...v(this,nn,"f")])),v(this,Xt,"f")&&s.push(v(this,Xt,"f").deferredMessages),s}setParams({messages:n,...s}){se(this,Pn,s),v(this,Xt,"f")&&(v(this,Xt,"f").ownCreateOnly={}),this.setMessages(n)}setMessages(n){const s=[...v(this,rn,"f"),...v(this,nn,"f")];if(v(this,Xt,"f")){const c=s.map(d=>d.param);$N(n,c)?(v(this,Xt,"f").replacementHistory=null,v(this,Xt,"f").deferredMessages=n.slice(c.length)):(v(this,Xt,"f").replacementHistory=n,v(this,Xt,"f").deferredMessages=[]);return}$N(n,v(this,rn,"f").map(c=>c.param))||(se(this,rn,[]),this.threading&&se(this,Vt,{type:"create",replacesLostThread:!1})),se(this,nn,[]);const i=new Map(s.filter(c=>c.reply).map(c=>[c.param.content,c]));for(const c of n.slice(v(this,rn,"f").length))v(this,wn,"m",Jb).call(this,c)||v(this,nn,"f").push({...i.get(c.content)??{reply:null},param:Ec(c)})}get hasTurnToSend(){return v(this,nn,"f").length>0||GT(v(this,rn,"f").at(-1)?.reply?.stop_reason)}startTurn(n,s){if(v(this,Xt,"f"))throw new De("Another `send()`, `parse()` or `stream()` is already in progress on this thread");lp(s);const i=v(this,nn,"f").length;this.push(n);const c=v(this,nn,"f").slice(i);v(this,wn,"m",zN).call(this);const d={};return s.system!==void 0&&(d.system=s.system),s.tools!==void 0&&(d.tools=s.tools),se(this,Xt,new i$({...v(this,Pn,"f"),...Go(s)},c,d))}endTurn(n){se(this,Xt,null),se(this,nn,v(this,nn,"f").filter(s=>!n.ownMessages.includes(s))),n.replacementHistory&&this.setMessages(n.replacementHistory),this.push(n.deferredMessages)}recoversFrom(n){if(!(n instanceof Gt))return!1;const s=this.unsupportedRequestBehavior==="continue_unthreaded",i=c$(n);if(i!==null&&v(this,Vt,"f").type==="continue")return i==="thread_not_found"&&v(this,Vt,"f").replacesLostThread&&s?(v(this,zi,"f").info(`The server lost the thread again right after a replay; continuing without a thread: previous_message_id=${v(this,Vt,"f").previousMessageId}`),this.stopThreading()):v(this,wn,"m",Nd).call(this,i),!0;const c=d$(n);return c!==null&&this.threading&&s?(v(this,zi,"f").info(`The server cannot thread this request; continuing without a thread: unsupported=${c.join(",")}`),this.stopThreading(),!0):!1}stopThreading(){this.threading&&se(this,Vt,{type:"unthreaded"})}recordPartialReply(n,s){v(this,wn,"m",Zb).call(this,n)||(v(this,wn,"m",ex).call(this,h$(n,s),{partial:!0}),this.previousMessageId!==null&&v(this,wn,"m",Nd).call(this,"stream_ended_before_message_stop"))}recordReply(n,s){v(this,wn,"m",Zb).call(this,s)||(v(this,wn,"m",ex).call(this,s,{partial:!1}),v(this,Vt,"f").type==="create"&&se(this,Pn,{...v(this,Pn,"f"),...n.ownCreateOnly}),this.threading&&(se(this,Vt,{type:"continue",previousMessageId:s.id,createdWith:n.createOnly,replacesLostThread:v(this,Vt,"f").type==="create"&&v(this,Vt,"f").replacesLostThread}),s.usage.iterations?.some(i=>i.type==="fallback_message")&&v(this,wn,"m",Nd).call(this,"fallback_message")),s.container&&v(this,wn,"m",ON).call(this,s.container.id))}buildCreateArguments(n,s,{stream:i}){v(this,wn,"m",tx).call(this,n.createOnly);const c=v(this,Vt,"f");let d=c.type==="continue"?[]:v(this,rn,"f").map(p=>p.param);if(c.type!=="never_threaded"){const p=v(this,rn,"f").map(b=>b.reply!==null).lastIndexOf(!0)+1;d=d.map((b,x)=>x<p?Zx(b):b)}const f={...n.fields,messages:[...d,...v(this,nn,"f").map(p=>p.param)]};if(this.threading&&!f.betas?.includes(Jx)&&(f.betas=[...f.betas??[],Jx]),c.type==="create")f.thread={type:"create"};else if(c.type==="continue"){f.thread={type:"continue",previous_message_id:c.previousMessageId};for(const p of nx)delete f[p]}return{params:f,options:v(this,wn,"m",PN).call(this,s,{stream:i})}}checkNextTurn(n){v(this,wn,"m",tx).call(this,HT({...v(this,Pn,"f"),...Go(n)}))}}return Pn=new WeakMap,rn=new WeakMap,nn=new WeakMap,Vt=new WeakMap,Xt=new WeakMap,zi=new WeakMap,wn=new WeakSet,RN=function(){for(const n of[v(this,nn,"f"),v(this,rn,"f")])for(let s=n.length-1;s>=0;s--)if(n[s].reply)return n[s].reply;return null},Jb=function(n){if("id"in n)return n.id===v(this,wn,"a",RN)?.id;const s=v(this,nn,"f").at(-1)??v(this,rn,"f").at(-1);return s?.reply!=null&&e0(n,s.param)},Nd=function(n){v(this,zi,"f").info(`Replaying the full message history under a new thread: reason=${n} previous_message_id=${this.previousMessageId}`),se(this,Vt,{type:"create",replacesLostThread:n==="thread_not_found"})},zN=function(){const n=v(this,rn,"f").at(-1);if(v(this,nn,"f").length||!n||n.reply&&!n.partial)return;n.reply&&v(this,rn,"f").pop();let s=v(this,rn,"f").length;for(;s>0&&!v(this,rn,"f")[s-1].reply;)s-=1;se(this,nn,v(this,rn,"f").splice(s)),v(this,zi,"f").info(`Re-sending the turn whose reply ended before \`message_stop\`: partial_reply_id=${n.reply?.id??null}`)},Zb=function(n){return n.stop_reason!=="refusal"||v(this,Vt,"f").type==="never_threaded"?!1:(this.previousMessageId!==null&&v(this,wn,"m",Nd).call(this,"refusal"),!0)},ex=function(n,{partial:s}){v(this,rn,"f").push(...v(this,nn,"f")),se(this,nn,[]),n&&v(this,rn,"f").push({param:Ec(n),reply:n,partial:s})},ON=function(n){const{container:s}=v(this,Pn,"f");s==null?se(this,Pn,{...v(this,Pn,"f"),container:n}):typeof s=="object"&&s.id==null&&se(this,Pn,{...v(this,Pn,"f"),container:{...s,id:n}})},tx=function(n){if(v(this,Vt,"f").type!=="continue")return;const{createdWith:s}=v(this,Vt,"f"),i=nx.filter(c=>n[c]!==s[c]);if(i.length){const c=i.map(d=>`\`${d}\``).join(" and ");throw new De(`Cannot change ${c} on a thread: the server keeps the \`system\` and \`tools\` the thread was created with. To change them, start a new thread from \`thread.params\`.`+(i.includes("tools")?" To add or remove tools on this thread, send `tool_addition` or `tool_removal` blocks in a `system` message.":""))}},PN=function(n,{stream:s}){const i={...this.options,...Go(n)};return s&&(i.headers=L([{[n_]:"stream"},i.headers])),v(this,Vt,"f").type!=="never_threaded"&&(i.headers=L([i.headers,s_("message-thread")])),this.threading&&(i.headers=l$(i.headers)),i},e})();const o$=["pause_turn","compaction"];function GT(e){return o$.some(r=>r===e)}const Jx="message-threads-2026-08-12",nx=["system","tools"];function HT(e){return{system:JSON.stringify(e.system),tools:JSON.stringify(e.tools)}}function l$(e){const r=L([e]).values.get("anthropic-beta");return r===null?e:L([e,{"anthropic-beta":Ij(r,Jx)}])}function c$(e){const r=FT(e)?.error_code;return u$.find(n=>n===r)??null}const u$=["thread_not_found","thread_already_continued","thread_continue_in_flight"];function d$(e){const r=FT(e);if(r?.error_code!=="thread_unsupported_request")return null;const n=r.unsupported;return Array.isArray(n)?n.map(String):[]}function FT(e){const n=e.error?.error?.details;return Hn(n)?n:null}function lp(e){if("thread"in e&&e.thread!==void 0)throw new TypeError("`thread` cannot be set here. The message thread sets it for each request itself.")}function Go(e){return Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))}function h$(e,r){const n=e.content.slice(0,r),s=e.content[r];return s?.type==="text"&&s.text&&n.push(s),n.length?{...e,content:n}:null}function Zx(e){if(!Hn(e))return e;const{cache_control:r,...n}=e;for(const s of["content","source","tool","definition","tool_references"]){const i=n[s];Array.isArray(i)?n[s]=i.map(Zx):Hn(i)&&(n[s]=Zx(i))}return n}function $N(e,r){return r.length<=e.length&&r.every((n,s)=>e0(n,e[s]))}function e0(e,r){const[n,s]=[Ec(e),Ec(r)];return Object.keys({...n,...s}).every(c=>n[c]===s[c]||JSON.stringify(n[c])===JSON.stringify(s[c]))}function Ec(e){return"id"in e?{role:e.role,content:e.content}:e}function IN(e){return e===void 0?[]:qx(e)?e:[e]}function VT(e){const{stream:r,max_iterations:n,runToolsEagerly:s,thread:i,...c}=e;if(i!==void 0&&i!==!1)throw new TypeError("`thread` cannot be set in the params of a tool runner. The runner sets it for each request itself. To run without a message thread, pass `thread: false`.");return{settings:{stream:r,max_iterations:n,runToolsEagerly:s},thread:i,threadParams:c}}var mt,_c,Io,nt,Cr,Xn,zf,va,ps,Nr,Qa,Oi,Ad,Ar,$s,Ja,vc,wc,Do,jd,sx,Of,DN,ax,rx,qN,Td,Pf,LN,UN,ix,$f,If,BN,ox;const GN="a tool runner's toolsets come only from its tools param; change them with setMessagesParams(), or build a new runner",m$="a tool runner's toolsets come only from its tools param; remove it there with setMessagesParams(), or build a new runner without it";var ey=(()=>{class e{constructor(n,s,i){mt.add(this),_c.set(this,!1),Io.set(this,!1),nt.set(this,void 0),Cr.set(this,void 0),Xn.set(this,void 0),zf.set(this,void 0),va.set(this,void 0),ps.set(this,void 0),Nr.set(this,void 0),Qa.set(this,void 0),Oi.set(this,void 0),Ad.set(this,0),Ar.set(this,void 0),$s.set(this,{status:"idle"}),Ja.set(this,void 0),vc.set(this,null),wc.set(this,new Map),Do.set(this,[]);const{thread:c,settings:d}="_state"in n?{thread:n,settings:s}:n.beta.messages._toolRunnerThread(s);HN(c._state.params),FN(d),se(this,nt,c),se(this,Cr,Go(d));const{tools:f,messages:p}=c._state.params,b=lT(f,p);"_state"in n||c._state.setMessages(JSON.parse(JSON.stringify(VN(p)))),se(this,Xn,{...i}),se(this,zf,L([s_("BetaToolRunner"),b.length?{[vh]:b.join(", ")}:void 0])),se(this,Oi,MN())}async*[(_c=new WeakMap,Io=new WeakMap,nt=new WeakMap,Cr=new WeakMap,Xn=new WeakMap,zf=new WeakMap,va=new WeakMap,ps=new WeakMap,Nr=new WeakMap,Qa=new WeakMap,Oi=new WeakMap,Ad=new WeakMap,Ar=new WeakMap,$s=new WeakMap,Ja=new WeakMap,vc=new WeakMap,wc=new WeakMap,Do=new WeakMap,mt=new WeakSet,jd=function(s){return v(this,Ar,"f")?Hs.with(v(this,Ar,"f"),s):s()},Symbol.asyncIterator)](){var n;if(v(this,_c,"f"))throw new De("Cannot iterate over a consumed stream");se(this,_c,!0),se(this,Io,!0),se(this,Qa,void 0);const s=zt(v(this,nt,"f")._client,()=>t8(v(this,nt,"f")._client,this.params,v(this,Xn,"f").openTelemetry?.conversationId));se(this,Ar,s&&ll.setSpan(Hs.active(),s));try{for(;;)try{if(v(this,Cr,"f").max_iterations&&v(this,Ad,"f")>=v(this,Cr,"f").max_iterations)break;if(v(this,mt,"m",BN).call(this),v(this,$s,"f").status==="scheduled"&&WN(v(this,vc,"f"))!=="resume"){yield*v(this,mt,"m",rx).call(this,v(this,$s,"f").config);continue}se(this,Io,!1,"f"),se(this,Qa,void 0,"f"),se(this,Ad,(n=v(this,Ad,"f"),n++,n),"f"),se(this,ps,void 0,"f"),yield*v(this,mt,"m",sx).call(this,v(this,nt,"f"));const i=v(this,va,"f");if(se(this,va,void 0,"f"),await v(this,mt,"m",jd).call(this,async()=>{let d;if(v(this,Io,"f"))se(this,vc,null,"f"),v(this,Nr,"f")?.abort(),v(this,nt,"f")._state.checkNextTurn(Ed(v(this,nt,"f"))),v(this,nt,"f")._state.setMessages(i),d=i.at(-1);else{const p=await v(this,ps,"f"),b=WN(p.stop_reason);if(se(this,vc,p.stop_reason,"f"),b==="stop")return"stop";if(b==="resume")return"continue";d=y$(v(this,nt,"f").messages)}KN(d)&&v(this,nt,"f")._state.checkNextTurn(Ed(v(this,nt,"f")));const f=await v(this,mt,"m",ix).call(this,d,v(this,Xn,"f").signal,v(this,Ar,"f"));if(f){const p=v(this,nt,"f").messages,b=p.map(x=>x.role).lastIndexOf("assistant")+1;v(this,nt,"f")._state.setMessages([...p.slice(0,b),f,...p.slice(b)])}else if(!v(this,Io,"f")&&!v(this,nt,"f")._state.hasTurnToSend)return"stop";return"continue"})==="stop"){yield*v(this,mt,"m",UN).call(this);break}}finally{v(this,Nr,"f")?.abort(),se(this,Nr,void 0,"f")}if(await v(this,mt,"m",ax).call(this),!v(this,ps,"f"))throw new De("ToolRunner concluded without a message from the server");v(this,Oi,"f").resolve(await v(this,ps,"f")),zt(v(this,nt,"f")._client,()=>s?.setStatus({code:ol.OK}))}catch(i){throw s&&zt(v(this,nt,"f")._client,()=>Ui(s,i)),se(this,_c,!1),se(this,va,void 0),v(this,Oi,"f").promise.catch(()=>{}),v(this,Oi,"f").reject(i),se(this,Oi,MN()),i}finally{zt(v(this,nt,"f")._client,()=>s?.end()),se(this,Ar,void 0)}}setMessagesParams(n){const s=typeof n=="function"?n(this.params):n;if(HN(s),v(this,$s,"f").status!=="idle"&&lx(s),v(this,$s,"f").status==="in_flight"&&!p$(s.messages,v(this,nt,"f").messages))throw new De(f$);const{settings:i,threadParams:c}=VT(s);FN(i),se(this,Cr,Go(i)),v(this,va,"f")?(se(this,va,c.messages),v(this,nt,"f")._state.setParams({...c,messages:v(this,nt,"f").messages})):v(this,nt,"f")._state.setParams(c),se(this,Io,!0),se(this,Qa,void 0)}setRequestOptions(n){typeof n=="function"?se(this,Xn,n(v(this,Xn,"f"))):se(this,Xn,{...v(this,Xn,"f"),...n})}async generateToolResponse(n=v(this,Xn,"f").signal){const s=v(this,nt,"f")._client._tracer?Hs.active():void 0,i=await v(this,ps,"f")??v(this,nt,"f").messages.at(-1);return i?v(this,mt,"m",ix).call(this,i,n,s):null}deferToolCall(n){const s=typeof n=="string"?n:n.id;v(this,Ja,"f")&&!v(this,Ja,"f").has(s)&&v(this,Ja,"f").set(s,{status:"held"})}get deferredToolCalls(){const n=v(this,Nr,"f"),s=v(this,Ja,"f");return!(n instanceof EN)||!s?[]:n.toolCalls.filter(i=>s.get(i.id)?.status==="held")}done(){return v(this,Oi,"f").promise}async runUntilDone(){if(!v(this,_c,"f"))for await(const n of this);return this.done()}get params(){return{...v(this,nt,"f")._state.params,...v(this,va,"f")&&{messages:[...v(this,va,"f")]},...v(this,Cr,"f")}}pushMessages(...n){this.setMessagesParams(s=>({...s,messages:[...s.messages,...n]}))}compactBeforeNextTurn(n){v(this,$s,"f").status!=="in_flight"&&(lx(this.params),se(this,$s,{status:"scheduled",config:n??{type:"summarize"}}))}addTools(...n){const s=v(this,mt,"m",$f).call(this);for(const i of n){if(dh(i))throw new op(`addTools() can't add the '${Bi(Yc(i))}' toolset: ${GN}`);const c=_$(i);if(s.has(c))throw new op(`addTools() can't replace the '${Bi(c)}' toolset: ${GN}`)}for(const i of n)"name"in i&&v(this,wc,"f").set(i.name,"run"in i?i:null),v(this,Do,"f").push({type:"addition",tool:i})}removeTools(...n){const s=v(this,mt,"m",$f).call(this);for(const i of n){const c=typeof i=="string"?i:i.name;if(s.has(c))throw new op(`removeTools() can't remove the '${Bi(c)}' toolset: ${m$}`)}for(const i of n){const c=typeof i=="string"?i:i.name;v(this,wc,"f").set(c,null),v(this,Do,"f").push({type:"removal",name:c})}}then(n,s){return this.runUntilDone().then(n,s)}}return sx=async function*(n){await v(this,mt,"m",ax).call(this),se(this,Ja,void 0);const s=n.messages;s.some(b$)&&v(this,mt,"m",jd).call(this,()=>n._state.setMessages(VN(s)));const{tools:i}=n._state.params;v(this,Cr,"f").stream?(se(this,Nr,v(this,mt,"m",jd).call(this,()=>v(this,Cr,"f").runToolsEagerly?v(this,mt,"m",DN).call(this,n):n.stream(void 0,Ed(n),v(this,mt,"m",Of).call(this,n)))),i&&n.update({tools:i}),n===v(this,nt,"f")&&se(this,va,n.messages),se(this,ps,v(this,Nr,"f").finalMessage()),v(this,ps,"f").catch(()=>{}),yield v(this,Nr,"f")):(se(this,ps,v(this,mt,"m",jd).call(this,()=>n.send(void 0,Ed(n),v(this,mt,"m",Of).call(this,n)))),i&&n.update({tools:i}),n===v(this,nt,"f")&&se(this,va,n.messages),yield v(this,ps,"f"))},Of=function(n){const{headers:s=n._state.options.headers}=v(this,Xn,"f");return{...v(this,Xn,"f"),headers:L([v(this,zf,"f"),s])}},DN=function(n){const s=new Map;se(this,Ja,s);const i=new Map,c=f=>{const p=s.has(f.id),b=!f.toolset_name&&v(this,mt,"m",$f).call(this).has(f.name),x=b?f.name:f.toolset_name;if(x){if(p||b||i.has(x)){i.set(x,"waiting");return}i.set(x,"running");const _=KT(v(this,mt,"m",If).call(this),x,f,v(this,Xn,"f"),v(this,nt,"f")._client,v(this,Ar,"f"));s.set(f.id,{status:"started",result:_}),_.then(({is_error:y})=>{y||i.get(x)==="waiting"?i.set(x,"waiting"):i.delete(x)},()=>i.set(x,"waiting"));return}if(p)return;const g=YT(v(this,mt,"m",Td).call(this),v(this,mt,"m",Pf).call(this),f,v(this,Xn,"f"),v(this,nt,"f")._client,v(this,Ar,"f"));g.catch(()=>{}),s.set(f.id,{status:"started",result:g})},d=new EN(n._state.params,c,n._client);return n._stream(d,void 0,Ed(n),v(this,mt,"m",Of).call(this,n)),d},ax=async function(){const n=[...v(this,Ja,"f")?.values()??[]].filter(s=>s.status==="started");await Promise.allSettled(n.map(s=>s.result))},rx=async function*(n){lx(this.params),se(this,$s,{status:"in_flight"}),se(this,Qa,void 0);const s=v(this,ps,"f"),i=v(this,mt,"m",qN).call(this,n),c=v(this,nt,"f").messages.length;try{yield*v(this,mt,"m",sx).call(this,i);const d=await v(this,ps,"f");if(d.content.some(f=>f.type==="compaction"&&f.content)){v(this,mt,"m",LN).call(this);const f={role:d.role,content:d.content},p=v(this,nt,"f").messages.slice(c).filter(b=>!e0(b,f));v(this,nt,"f")._state.setMessages([f,...p])}else it(v(this,nt,"f")._client).warn("Compaction produced no summary; keeping the conversation as it is."),se(this,ps,s,"f")}finally{se(this,$s,{status:"idle"}),i._state.threading||v(this,nt,"f")._state.stopThreading()}},qN=function(n){const{messages:s,...i}=g$(v(this,nt,"f")._state.params),c=v(this,nt,"f").fork();return c._state=v(this,nt,"f")._state.fork({...i,compaction:n}),c},Td=function(){const n=new Map;for(const s of v(this,nt,"f")._state.params.tools??[])"run"in s&&"name"in s&&n.set(s.name,s);for(const[s,i]of v(this,wc,"f"))i?n.set(s,i):n.delete(s);return n},Pf=function(){const n=new Set(v(this,mt,"m",Td).call(this).keys());for(const s of[...this.params.messages,v(this,mt,"m",ox).call(this)])if(Array.isArray(s.content)){for(const i of s.content)if(s.role==="system")YN(i,n);else if(s.role==="assistant"&&i.type==="compaction")for(const c of i.tool_changes??[])YN(c,n)}return n},LN=function(){const n=v(this,mt,"m",Pf).call(this);for(const s of v(this,mt,"m",Td).call(this).keys())n.has(s)||v(this,wc,"f").set(s,null)},UN=async function*(){if(v(this,$s,"f").status==="scheduled"){if(KN(v(this,nt,"f").messages.at(-1))){it(v(this,nt,"f")._client).warn("The pending compaction was skipped because the last turn ended with tool calls that were not run. Call `compactBeforeNextTurn()` again if you continue the conversation."),se(this,$s,{status:"idle"});return}yield*v(this,mt,"m",rx).call(this,v(this,$s,"f").config)}},ix=async function(n,s,i){return v(this,Qa,"f")!==void 0?v(this,Qa,"f"):(se(this,Qa,x$(v(this,mt,"m",If).call(this),v(this,mt,"m",Td).call(this),v(this,mt,"m",Pf).call(this),n,{...v(this,Xn,"f"),signal:s},v(this,Ja,"f"),v(this,nt,"f")._client,i)),v(this,Qa,"f"))},$f=function(){return new Set(v(this,mt,"m",If).call(this).tools.filter(dh).map(Yc))},If=function(){return{...this.params,tools:v(this,nt,"f")._state.params.tools??[]}},BN=function(){v(this,vc,"f")==="pause_turn"||v(this,Do,"f").length===0||(v(this,nt,"f").append(v(this,mt,"m",ox).call(this)),se(this,Do,[]))},ox=function(){const n=[];for(const s of v(this,Do,"f")){if(s.type==="removal"){n.push({type:"tool_removal",tool:{type:"tool_reference",name:s.name}});continue}const i=D_(s.tool);n.push({type:"tool_addition",tool:{type:"tool_definition",definition:i}})}return{role:"system",content:n}},e})();const f$="Message params can't be changed while the conversation is being compacted, because the compaction response is about to replace them. Change them after this iteration instead.";function p$(e,r){return e.length===r.length&&e.every((n,s)=>e0(n,r[s]))}function HN(e){if("compaction"in e&&e.compaction!=null)throw new De("`compaction` cannot be set on a tool runner: every request in the loop would compact again. Call `runner.compactBeforeNextTurn()` when the conversation should be compacted instead.")}function FN(e){if(e.runToolsEagerly&&!e.stream)throw new TypeError("`runToolsEagerly: true` needs `stream: true` in the tool runner's params, because a reply that isn't streamed arrives whole.")}function lx(e){if(e.context_management?.edits?.some(r=>r.type.startsWith("compact_")))throw new De("`compactBeforeNextTurn()` can't be used while `context_management` has a compaction edit, because the API doesn't accept a compaction block together with one. Remove the edit first.")}function g$(e){const{context_management:r,stop_sequences:n,output_format:s,...i}=e,c=({format:d,...f})=>f;return(i.tool_choice?.type==="any"||i.tool_choice?.type==="tool")&&delete i.tool_choice,i.output_config&&(i.output_config=c(i.output_config)),Array.isArray(i.fallbacks)&&(i.fallbacks=i.fallbacks.map(d=>d.output_config?{...d,output_config:c(d.output_config)}:d)),i}function D_(e){if(!("run"in e))return e;const r=A$,n="toJSON"in e&&typeof e.toJSON=="function"?e.toJSON():e;return{...Object.fromEntries(Object.entries(n).filter(([s])=>r.includes(s))),...Ho(e)&&{[Ir]:e[Ir]}}}function Ed(e){const{tools:r}=e._state.params;return r?{tools:r.map(D_)}:{}}function VN(e){return e.map(r=>{if(r.role!=="system"||!Array.isArray(r.content))return r;const n=r.content.map(s=>s.type==="tool_addition"&&s.tool.type==="tool_definition"?{...s,tool:{...s.tool,definition:D_(s.tool.definition)}}:s);return{...r,content:n}})}function b$(e){return e.role==="system"&&Array.isArray(e.content)&&e.content.some(r=>r.type==="tool_addition"&&r.tool.type==="tool_definition"&&"run"in r.tool.definition)}async function x$(e,r,n,s,i,c,d,f){if(!s||s.role!=="assistant"||!s.content||typeof s.content=="string")return null;const p=s.content.filter(g=>g.type==="tool_use");if(p.length===0)return null;const b=new Map;return{role:"user",content:await Promise.all(p.map(async g=>{const _=c?.get(g.id),y=_?.status==="started"?_.result:void 0;if(g.toolset_name){const E=g.toolset_name,T=b.get(E)??{tail:Promise.resolve(),failed:!1};b.set(E,T);const j=e.tools.some(z=>dh(z)&&Yc(z)===E),q=y??T.tail.then(()=>T.failed?kp(g,n$(E),!0):KT(e,E,g,i,d,f));return T.tail=q.then(({is_error:z})=>{z&&j&&(T.failed=!0)},()=>{T.failed=!0}),c?.set(g.id,{status:"started",result:q}),q}if(y)return y;if(!(n.has(g.name)?r.get(g.name):void 0)&&e.tools.some(E=>dh(E)&&Yc(E)===g.name)){const E=b.get(g.name)??{tail:Promise.resolve(),failed:!1};return b.set(g.name,E),E.tail=E.tail.then(()=>{E.failed=!0}),w$(g)}const k=YT(r,n,g,i,d,f);return c?.set(g.id,{status:"started",result:k}),k}))}}async function KT(e,r,n,s,i,c){const d=e.tools.find(b=>dh(b)&&Yc(b)===r);if(!d)return kp(n,`Error: Toolset '${Bi(r)}' member '${Bi(n.name)}' not found`,!0);const f={signal:s?.signal,conversationId:s?.openTelemetry?.conversationId,parentContext:c};return(await a_(i,d,n,f,async()=>{const b=await r$(d,n,{signal:s?.signal});return{block:b,content:b.content??[],isError:b.is_error===!0}})).block}async function YT(e,r,n,s,i,c){const d=r.has(n.name)?e.get(n.name):void 0;if(!d)return v$(n);const f={signal:s?.signal,conversationId:s?.openTelemetry?.conversationId,parentContext:c},p=await a_(i,d,n,f,()=>RT(d,n.input,{toolUse:n,toolUseBlock:n,signal:s?.signal}));return{type:"tool_result",tool_use_id:n.id,content:p.content,...p.isError?{is_error:!0}:void 0}}function y$(e){for(let r=e.length-1;r>=0;r--){const n=e[r];if(n.role==="assistant")return n;if(n.role==="user"&&Array.isArray(n.content)&&n.content.some(s=>s.type==="tool_result"))return}}function KN(e){return Array.isArray(e?.content)&&e.content.some(r=>r.type==="tool_use")}function _$(e){return(e.type??"custom").replace(/_\d{8}$/,"").replace(/_toolset$/,"")}function v$(e){return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool '${e.name}' not found`,is_error:!0}}function w$(e){return{type:"tool_result",tool_use_id:e.id,content:`Error: the '${Bi(e.name)}' toolset could not run this call${S$(e.input)}; nothing in the batch was executed`,is_error:!0}}function S$(e){const r=typeof e=="object"&&e!==null?e:{};if(!("actions"in r)){const c="action"in r?r.action:void 0;return typeof c=="string"?`: the call has no 'actions' list (action: '${Bi(c)}')`:": the call has no 'actions' list"}const{actions:n}=r;if(typeof n=="string")return": 'actions' is text, not a list of actions";if(!Array.isArray(n))return": 'actions' is not a list of actions";if(n.length===0)return": the 'actions' list is empty";const s=[];for(const[c,d]of n.entries()){const f=typeof d=="object"&&d!==null&&"action"in d?d.action:void 0;if(typeof f!="string")return`: action ${c} must be an object with a string 'action' field`;s.push(`'${Bi(f)}'`)}const i=s.length>10?`, and ${s.length-10} more`:"";return`: its actions could not be run as sent (actions: ${s.slice(0,10).join(", ")}${i})`}function YN(e,r){switch(e.type){case"tool_removal":case"tool_addition":k$(e,r);break}}function k$(e,r){const n=C$(e.tool);n!==void 0&&(e.type==="tool_removal"?r.delete(n):r.add(n))}function C$(e){switch(e.type){case"tool_reference":return e.name;case"tool_definition":return"name"in e.definition?e.definition.name:void 0;default:return}}function WN(e){if(e===null)return"stop";if(GT(e))return"resume";switch(e){case"tool_use":return"run_tools";case"end_turn":case"stop_sequence":case"max_tokens":case"model_context_window_exceeded":case"refusal":return"stop";default:return"stop"}}class hh{constructor(r,n,s){if(!r._supportsMessageThreads)throw new De("Message threads are not available on this client; use `client.beta.messages.create()` with the full `messages` instead");b_(n),this._client=r,this._state=new BT({params:n,options:s??{},threading:!0,logger:it(r)})}static _fromState(r,n){const s=Object.create(hh.prototype);return Object.assign(s,{_client:r,_state:n})}get messages(){return this._state.messages}get previousMessageId(){return this._state.previousMessageId}get params(){return{...this._state.params,unsupportedRequestBehavior:this._state.unsupportedRequestBehavior}}append(...r){this._state.push(r)}send(r,n={},s={}){return this._send(r,n,s,i=>i)}parse(r,n={},s={}){return this._send(r,n,s,i=>g_(i,this._state.params,{logger:it(this._client)}))}_send(r,n,s,i){const c=this._state.startTurn(IN(r),n),d=(async()=>{try{const{request:f,props:p}=await this._createWithRecovery(c,s,{stream:!1}),b=await f;return this._state.recordReply(c,b),{props:p,reply:b}}finally{this._state.endTurn(c)}})();return new ch(this._client,d.then(({props:f})=>f),async()=>{const{props:f,reply:p}=await d;return Xp(i(p),f.response)})}stream(r,n={},s={}){const i=new x_(this._state.params,{logger:it(this._client),client:this._client});return this._stream(i,r,n,s),i}_stream(r,n,s,i){const c=this._state.startTurn(IN(n),s);let d,f=0,p=!1;r.on("streamEvent",(g,_)=>{p||(d=_,g.type==="content_block_stop"&&(f+=1),g.type==="message_stop"&&(p=!0,this._state.recordReply(c,_),this._state.endTurn(c)))});const b=()=>{p||(p=!0,d&&this._state.recordPartialReply(d,f),this._state.endTurn(c))};r.controller.signal.addEventListener("abort",b,{once:!0});const x=(g,_)=>new ch(this._client,this._createWithRecovery(c,{...i,signal:_?.signal},{stream:!0}).then(({props:y})=>y));r._start(x,this._state.params,{signal:i.signal??this._state.options.signal},b)}update(r={},n={}){this._state.update(r,n)}toolRunner(r={},n={}){return lp(r),new ey(this,r,n)}fork(){return hh._fromState(this._client,this._state.fork())}async _createWithRecovery(r,n,{stream:s}){for(;;){const{params:i,options:c}=this._state.buildCreateArguments(r,n,{stream:s}),d=this._client.beta.messages.create({...i,stream:s},c);try{return{request:d,props:await d._responseProps()}}catch(f){if(!this._state.recoversFrom(f))throw f}}}}const XN={"claude-sonnet-4-5":"November 30th, 2026","claude-sonnet-4-5-20250929":"November 30th, 2026"},N$=["claude-mythos-preview","claude-opus-4-6"];var QN=(()=>{class e extends ye{constructor(){super(...arguments),this.batches=new hC(this._client)}create(n,s){const i=Qx(n),{betas:c,user_profile_id:d,workspace_id:f,...p}=i;p.model in XN&&console.warn(`The model '${p.model}' is deprecated and will reach end-of-life on ${XN[p.model]}
526
526
  Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),N$.includes(p.model)&&p.thinking&&p.thinking.type==="enabled"&&console.warn(`Using Claude with ${p.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let b=s?.timeout??this._client._options.timeout;if(!p.stream&&b==null){const y=PT[p.model]??void 0;b=this._client.calculateNonstreamingTimeout(p.max_tokens,y)}const x={body:p,timeout:b??6e5,...s,headers:IT(i,s),stream:i.stream??!1,__qualifiers:{beta:"true"}},g=this._client._tracer&&N(this._client,"anthropic.messages.create",s,Jp(this._client,x));nT(this._client,g,p);const _=this._client.post("/v1/messages",{...x,__span:g});return g?_._thenUnwrap(y=>(sT(this._client,g,p,y),y)):_}parse(n,s){return s={...s,headers:L([{"anthropic-beta":[...n.betas??[],"structured-outputs-2025-12-15"].toString()},s?.headers])},this.create(n,s).then(i=>g_(i,n,{logger:this._client.logger??console}))}stream(n,s){return x_.createMessage(this,n,s,{client:this._client})}countTokens(n,s){const i=Qx(n),{betas:c,user_profile_id:d,workspace_id:f,...p}=i,b={body:p,...s,headers:L([{"anthropic-beta":[...c??[],"token-counting-2024-11-01"].toString(),...d!=null?{"anthropic-user-profile-id":d}:void 0,...f!=null?{"anthropic-workspace-id":f}:void 0},s?.headers]),__qualifiers:{beta:"true"}};return this._client.post("/v1/messages/count_tokens",{...b,__span:N(this._client,"anthropic.messages.count_tokens",s,{route:"/v1/messages/count_tokens",request:b})})}toolRunner(n,s){return new ey(this._client,n,s)}_toolRunnerThread(n){b_(n);const{settings:s,thread:i,threadParams:c}=VT(n),d=new BT({params:{...c,unsupportedRequestBehavior:"continue_unthreaded"},options:{},threading:i!==!1&&this._client._supportsMessageThreads,logger:it(this._client)});return{thread:hh._fromState(this._client,d),settings:s}}thread(n,s){return new hh(this._client,n,s)}}return e.Batches=hC,e.BetaToolRunner=ey,e.ToolError=l_,e})();const A$=["input_schema","name","allowed_callers","cache_control","defer_loading","description","eager_input_streaming","input_examples","strict","type","configs","display_height_px","display_width_px","display_number","enable_zoom","max_characters"];var q_=(()=>{class e extends Ye{}return e._errorName="BetaOrganizationNotEnrolledInBetaError",e})(),L_=(()=>{class e extends Ye{}return e._errorName="BetaUnsupportedCharsetError",e})(),JN=(()=>{class e extends ye{constructor(){super(...arguments),this.models=new Lk(this._client),this.messages=new QN(this._client),this.agents=new Kk(this._client),this.environments=new lC(this._client),this.sessions=new _N(this._client),this.deployments=new Ik(this._client),this.deploymentRuns=new $k(this._client),this.vaults=new jN(this._client),this.memoryStores=new dC(this._client),this.files=new qk(this._client),this.skills=new wN(this._client),this.webhooks=new Fk(this._client),this.userProfiles=new NN(this._client),this.dreams=new Dk(this._client),this.tunnels=new kN(this._client),this.organization=new pN(this._client)}}return e.BetaOrganizationNotEnrolledInBetaError=q_,e.BetaUnsupportedCharsetError=L_,e.Models=Lk,e.Messages=QN,e.Agents=Kk,e.Environments=lC,e.BetaEnvironmentArchivedError=u_,e.BetaInvalidConfigTypeChangeError=d_,e.BetaInvalidMetadataError=h_,e.BetaEnvironmentCreateDisabledError=m_,e.BetaEnvironmentUpdateDisabledError=f_,e.BetaEnvironmentNotFoundError=p_,e.Sessions=_N,e.Deployments=Ik,e.DeploymentRuns=$k,e.Vaults=jN,e.MemoryStores=dC,e.Files=qk,e.Skills=wN,e.Webhooks=Fk,e.UserProfiles=NN,e.Dreams=Dk,e.Tunnels=kN,e.Organization=pN,e})();function WT(e,r){const{user_profile_id:n,workspace_id:s,tools:i,messages:c}=e;return L([{...n!=null?{"anthropic-user-profile-id":n}:void 0,...s!=null?{"anthropic-workspace-id":s}:void 0},cT(i,c),r?.headers])}function j$(e,r,n){if(!e._tracer)return;const s=WT(r,n);return N(e,"anthropic.messages.create",n,Jp(e,{body:r,headers:s,stream:!0}))}function XT(e){return e?.output_config?.format}function ZN(e,r,n){const s=XT(r);return!r||!("parse"in(s??{}))?{...e,content:e.content.map(i=>i.type==="text"?Object.defineProperty({...i},"parsed_output",{value:null,enumerable:!1}):i),parsed_output:null}:QT(e,r)}function QT(e,r,n){let s=null;const i=e.content.map(c=>{if(c.type==="text"){const d=T$(r,c.text);return s===null&&(s=d),Object.defineProperty({...c},"parsed_output",{value:d,enumerable:!1})}return c});return{...e,content:i,parsed_output:s}}function T$(e,r){const n=XT(e);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(r):JSON.parse(r)}catch(s){throw new De(`Failed to parse structured output: ${s}`)}}var sa,Pi,Za,Md,Df,Rd,zd,qf,Od,er,Pd,Lf,Uf,qo,Bf,Gf,Hf,$d,Lo,gs,cx,e5,ux,dx,hx,mx,t5;function fx(e){return e.type==="tool_use"||e.type==="server_tool_use"}var E$=(()=>{class e{constructor(n,s){sa.add(this),this.messages=[],this.receivedMessages=[],Pi.set(this,void 0),Za.set(this,null),this.controller=new AbortController,Md.set(this,void 0),Df.set(this,()=>{}),Rd.set(this,()=>{}),zd.set(this,void 0),qf.set(this,()=>{}),Od.set(this,()=>{}),er.set(this,{}),Pd.set(this,!1),Lf.set(this,!1),Uf.set(this,!1),qo.set(this,!1),Bf.set(this,void 0),Gf.set(this,void 0),Hf.set(this,void 0),$d.set(this,void 0),Lo.set(this,void 0),gs.set(this,void 0),ux.set(this,i=>{if(se(this,Lf,!0),v(this,gs,"f")&&(v(this,gs,"f").streamed=void 0),Jo(i)&&(i=new Ls),i instanceof Ls)return se(this,Uf,!0),this._emit("abort",i);if(i instanceof De)return this._emit("error",i);if(i instanceof Error){const c=new De(i.message);return c.cause=i,this._emit("error",c)}return this._emit("error",new De(String(i)))}),se(this,Md,new Promise((i,c)=>{se(this,Df,i,"f"),se(this,Rd,c,"f")})),se(this,zd,new Promise((i,c)=>{se(this,qf,i,"f"),se(this,Od,c,"f")})),v(this,Md,"f").catch(()=>{}),v(this,zd,"f").catch(()=>{}),se(this,Za,n),se(this,$d,s?.logger??console),se(this,Lo,s?.client)}get response(){return v(this,Bf,"f")}get request_id(){return v(this,Gf,"f")}get workspace_id(){return v(this,Hf,"f")}async withResponse(){se(this,qo,!0);const n=await v(this,Md,"f");if(!n)throw new Error("Could not resolve a `Response` object");return{data:this,response:n,request_id:n.headers.get("request-id"),workspace_id:n.headers.get("anthropic-workspace-id")}}static fromReadableStream(n){const s=new e(null);return s._run(()=>s._fromReadableStream(n)),s}static createMessage(n,s,i,{logger:c,client:d}={}){const f=new e(s,{logger:c,client:d});for(const p of s.messages)f._addMessageParam(p);return se(f,Za,{...s,stream:!0}),f._run(()=>f._createMessage(n,{...s,stream:!0},{...i,headers:{...i?.headers,[n_]:"stream"}})),f}_run(n){n().then(()=>{this._emitFinal(),this._emit("end")},v(this,ux,"f"))}_addMessageParam(n){this.messages.push(n)}_addMessage(n,s=!0){this.receivedMessages.push(n),s&&this._emit("message",n)}async _createMessage(n,s,i){const c=i?.signal;let d;c&&(c.aborted&&this.controller.abort(),d=this.controller.abort.bind(this.controller),c.addEventListener("abort",d));try{v(this,sa,"m",dx).call(this),se(this,gs,i?.__span??(v(this,Lo,"f")&&j$(v(this,Lo,"f"),s,i)),"f");const{response:f,data:p}=await n.create({...s,stream:!0},{...i,__span:v(this,gs,"f"),signal:this.controller.signal}).withResponse();try{this._connected(f)}catch(b){throw v(this,gs,"f")&&(v(this,gs,"f").failure=b),p.controller.abort(),b}for await(const b of p)try{v(this,sa,"m",hx).call(this,b)}catch(x){throw v(this,gs,"f")&&(v(this,gs,"f").failure=x),x}if(p.controller.signal?.aborted)throw new Ls;v(this,sa,"m",mx).call(this)}finally{c&&d&&c.removeEventListener("abort",d)}}_connected(n){this.ended||(se(this,Bf,n),se(this,Gf,n?.headers.get("request-id")),se(this,Hf,n?.headers.get("anthropic-workspace-id")),v(this,Df,"f").call(this,n),this._emit("connect"))}get ended(){return v(this,Pd,"f")}get errored(){return v(this,Lf,"f")}get aborted(){return v(this,Uf,"f")}abort(){this.controller.abort()}on(n,s){return(v(this,er,"f")[n]||(v(this,er,"f")[n]=[])).push({listener:s}),this}off(n,s){const i=v(this,er,"f")[n];if(!i)return this;const c=i.findIndex(d=>d.listener===s);return c>=0&&i.splice(c,1),this}once(n,s){return(v(this,er,"f")[n]||(v(this,er,"f")[n]=[])).push({listener:s,once:!0}),this}emitted(n){return new Promise((s,i)=>{se(this,qo,!0),n!=="error"&&this.once("error",i),this.once(n,s)})}async done(){se(this,qo,!0),await v(this,zd,"f")}get currentMessage(){return v(this,Pi,"f")}async finalMessage(){return await this.done(),v(this,sa,"m",cx).call(this)}async finalText(){return await this.done(),v(this,sa,"m",e5).call(this)}_emit(n,...s){if(v(this,Pd,"f"))return;n==="end"&&(se(this,Pd,!0),v(this,qf,"f").call(this));const i=v(this,er,"f")[n];if(i&&(v(this,er,"f")[n]=i.filter(c=>!c.once),i.forEach(({listener:c})=>c(...s))),n==="abort"){const c=s[0];!v(this,qo,"f")&&!i?.length&&Promise.reject(c),v(this,Rd,"f").call(this,c),v(this,Od,"f").call(this,c),this._emit("end");return}if(n==="error"){const c=s[0];!v(this,qo,"f")&&!i?.length&&Promise.reject(c),v(this,Rd,"f").call(this,c),v(this,Od,"f").call(this,c),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",v(this,sa,"m",cx).call(this))}async _fromReadableStream(n,s){const i=s?.signal;let c;i&&(i.aborted&&this.controller.abort(),c=this.controller.abort.bind(this.controller),i.addEventListener("abort",c));try{v(this,sa,"m",dx).call(this),this._connected(null);const d=Hr.fromReadableStream(n,this.controller);for await(const f of d)v(this,sa,"m",hx).call(this,f);if(d.controller.signal?.aborted)throw new Ls;v(this,sa,"m",mx).call(this)}finally{i&&c&&i.removeEventListener("abort",c)}}[(Pi=new WeakMap,Za=new WeakMap,Md=new WeakMap,Df=new WeakMap,Rd=new WeakMap,zd=new WeakMap,qf=new WeakMap,Od=new WeakMap,er=new WeakMap,Pd=new WeakMap,Lf=new WeakMap,Uf=new WeakMap,qo=new WeakMap,Bf=new WeakMap,Gf=new WeakMap,Hf=new WeakMap,$d=new WeakMap,Lo=new WeakMap,gs=new WeakMap,ux=new WeakMap,sa=new WeakSet,cx=function(){if(this.receivedMessages.length===0)throw new De("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},e5=function(){if(this.receivedMessages.length===0)throw new De("stream ended without producing a Message with role=assistant");const s=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(s.length===0)throw new De("stream ended without producing a content block with type=text");return s.join(" ")},dx=function(){this.ended||se(this,Pi,void 0)},hx=function(s){if(this.ended)return;const i=v(this,sa,"m",t5).call(this,s);if(this._emit("_rawEvent",s),!!i)switch(this._emit("streamEvent",s,i),s.type){case"content_block_delta":{const c=i.content.at(-1);switch(s.delta.type){case"text_delta":{c.type==="text"&&this._emit("text",s.delta.text,c.text||"");break}case"citations_delta":{c.type==="text"&&this._emit("citation",s.delta.citation,c.citations??[]);break}case"input_json_delta":{fx(c)&&v(this,er,"f").inputJson?.length&&this._emit("inputJson",s.delta.partial_json,c.input);break}case"thinking_delta":{c.type==="thinking"&&this._emit("thinking",s.delta.thinking,c.thinking);break}case"signature_delta":{c.type==="thinking"&&this._emit("signature",c.signature);break}default:s.delta}break}case"message_stop":{v(this,Lo,"f")&&v(this,gs,"f")&&v(this,Za,"f")&&t_(v(this,Lo,"f"),v(this,gs,"f"),v(this,Za,"f"),i),this._addMessageParam(i),this._addMessage(ZN(i,v(this,Za,"f"),{logger:v(this,$d,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{se(this,Pi,i),v(this,gs,"f")&&v(this,Za,"f")&&(v(this,gs,"f").streamed={body:v(this,Za,"f"),message:i});break}}},mx=function(){if(this.ended)throw new De("stream has ended, this shouldn't happen");const s=v(this,Pi,"f");if(!s)throw new De("request ended without sending any chunks");return se(this,Pi,void 0),ZN(s,v(this,Za,"f"),{logger:v(this,$d,"f")})},t5=function(s){let i=v(this,Pi,"f");if(s.type==="message_start"){if(i)throw new De(`Unexpected event order, got ${s.type} before receiving "message_stop"`);return s.message}if(i)switch(s.type){case"message_stop":return i;case"message_delta":return i.stop_reason=s.delta.stop_reason,i.stop_sequence=s.delta.stop_sequence,i.stop_details=s.delta.stop_details,i.usage.output_tokens=s.usage.output_tokens,s.delta.container!=null&&(i.container=s.delta.container),s.usage.input_tokens!=null&&(i.usage.input_tokens=s.usage.input_tokens),s.usage.cache_creation_input_tokens!=null&&(i.usage.cache_creation_input_tokens=s.usage.cache_creation_input_tokens),s.usage.cache_read_input_tokens!=null&&(i.usage.cache_read_input_tokens=s.usage.cache_read_input_tokens),s.usage.server_tool_use!=null&&(i.usage.server_tool_use=s.usage.server_tool_use),s.usage.output_tokens_details!=null&&(i.usage.output_tokens_details=s.usage.output_tokens_details),i;case"content_block_start":return i.content.push({...s.content_block}),i;case"content_block_delta":{const c=i.content.at(s.index);switch(s.delta.type){case"text_delta":{c?.type==="text"&&(i.content[s.index]={...c,text:(c.text||"")+s.delta.text});break}case"citations_delta":{c?.type==="text"&&(i.content[s.index]={...c,citations:[...c.citations??[],s.delta.citation]});break}case"input_json_delta":{if(c&&fx(c)){const d=(c[Ic]||"")+s.delta.partial_json;i.content[s.index]=DT(c,d)}break}case"thinking_delta":{c?.type==="thinking"&&(i.content[s.index]={...c,thinking:c.thinking+s.delta.thinking});break}case"signature_delta":{c?.type==="thinking"&&(i.content[s.index]={...c,signature:s.delta.signature});break}default:s.delta}return i}case"content_block_stop":{const c=i.content.at(s.index);return c&&fx(c)&&Ic in c&&Object.defineProperty(c,"input",{value:c.input,enumerable:!0,configurable:!0,writable:!0}),i}default:return i}},Symbol.asyncIterator)](){const n=[],s=[];let i=!1;return this.on("_rawEvent",c=>{const d=s.shift();d?d.resolve(c):n.push(c)}),this.on("end",()=>{i=!0;for(const c of s)c.resolve(void 0);s.length=0}),this.on("abort",c=>{i=!0;for(const d of s)d.reject(c);s.length=0}),this.on("error",c=>{i=!0;for(const d of s)d.reject(c);s.length=0}),{next:async()=>n.length?{value:n.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((d,f)=>s.push({resolve:d,reject:f})).then(d=>d?{value:d,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Hr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}return e})();class n5 extends ye{create(r,n){const{user_profile_id:s,workspace_id:i,...c}=r;return this._client.post("/v1/messages/batches",{body:c,...n,headers:L([{...s!=null?{"anthropic-user-profile-id":s}:void 0,...i!=null?{"anthropic-workspace-id":i}:void 0},n?.headers]),__span:N(this._client,"anthropic.messages.batches.create",n,{route:"/v1/messages/batches",attributes:{"anthropic.message.batch.request_count":c.requests?.length},createdIDAttribute:"anthropic.message.batch.id"})})}retrieve(r,n={},s){const{workspace_id:i}=n??{};return this._client.get(U`/v1/messages/batches/${r}`,{...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.messages.batches.retrieve",s,{route:"/v1/messages/batches/{message_batch_id}",attributes:{"anthropic.message.batch.id":r}})})}list(r={},n){const{workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/messages/batches",ns,{query:i,...n,headers:L([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers]),__span:N(this._client,"anthropic.messages.batches.list",n,{route:"/v1/messages/batches",queryParams:["after_id","before_id","limit"]})})}delete(r,n={},s){const{workspace_id:i}=n??{};return this._client.delete(U`/v1/messages/batches/${r}`,{...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.messages.batches.delete",s,{route:"/v1/messages/batches/{message_batch_id}",attributes:{"anthropic.message.batch.id":r}})})}cancel(r,n={},s){const{workspace_id:i}=n??{};return this._client.post(U`/v1/messages/batches/${r}/cancel`,{...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.messages.batches.cancel",s,{route:"/v1/messages/batches/{message_batch_id}/cancel",attributes:{"anthropic.message.batch.id":r}})})}async results(r,n={},s){const i=await this.retrieve(r,n,s);if(!i.results_url)throw new De(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);const{workspace_id:c}=n??{};return this._client.get(i.results_url,{...s,headers:L([{Accept:"application/binary",...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),stream:!0,__binaryResponse:!0,__span:N(this._client,"anthropic.messages.batches.results",s,{route:"/v1/messages/batches/{message_batch_id}/results",attributes:{"anthropic.message.batch.id":r}})})._thenUnwrap((d,f)=>OT.fromResponse(f.response,f.controller))}}var U_=(()=>{class e extends Ye{}return e._errorName="AvailableToolsLimitExceededError",e})(),B_=(()=>{class e extends Ye{}return e._errorName="CompactionBlockAmbiguousError",e})(),G_=(()=>{class e extends Ye{}return e._errorName="CompactionBlockMisplacedError",e})(),H_=(()=>{class e extends Ye{}return e._errorName="CompactionContentMismatchError",e})(),F_=(()=>{class e extends Ye{}return e._errorName="CompactionIncompleteTurnError",e})(),V_=(()=>{class e extends Ye{}return e._errorName="CompactionNothingToSummarizeError",e})(),K_=(()=>{class e extends Ye{}return e._errorName="CompactionSignatureInvalidError",e})(),Y_=(()=>{class e extends Ye{}return e._errorName="CompactionTooManyToolReferencesError",e})(),W_=(()=>{class e extends Ye{}return e._errorName="CompactionToolChangesMismatchError",e})(),X_=(()=>{class e extends Ye{}return e._errorName="ThreadAlreadyContinuedError",e})(),Q_=(()=>{class e extends Ye{}return e._errorName="ThreadContinueInFlightError",e})(),J_=(()=>{class e extends Ye{}return e._errorName="ThreadFingerprintMismatchError",e})(),Z_=(()=>{class e extends Ye{}return e._errorName="ThreadUnsupportedRequestError",e})(),ev=(()=>{class e extends Ye{}return e._errorName="ToolNameConflictError",e})(),tv=(()=>{class e extends Ye{}return e._errorName="ToolReferenceUnresolvedError",e})(),nv=(()=>{class e extends Zc{}return e._errorName="ThreadNotFoundError",e})(),sv=(()=>{class e extends Ly{}return e._errorName="CompactionUnavailableError",e})(),s5=(()=>{class e extends ye{constructor(){super(...arguments),this.batches=new n5(this._client)}create(n,s){const{user_profile_id:i,workspace_id:c,...d}=n;d.model in a5&&console.warn(`The model '${d.model}' is deprecated and will reach end-of-life on ${a5[d.model]}
527
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),M$.includes(d.model)&&d.thinking&&d.thinking.type==="enabled"&&console.warn(`Using Claude with ${d.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let f=s?.timeout??this._client._options.timeout;if(!d.stream&&f==null){const g=PT[d.model]??void 0;f=this._client.calculateNonstreamingTimeout(d.max_tokens,g)}const p={body:d,timeout:f??6e5,...s,headers:WT(n,s),stream:n.stream??!1},b=this._client._tracer&&N(this._client,"anthropic.messages.create",s,Jp(this._client,p));nT(this._client,b,d);const x=this._client.post("/v1/messages",{...p,__span:b});return b?x._thenUnwrap(g=>(sT(this._client,b,d,g),g)):x}parse(n,s){return this.create(n,s).then(i=>QT(i,n,{logger:this._client.logger??console}))}stream(n,s){const i=n;return E$.createMessage(this,i,s,{logger:this._client.logger??console,client:this._client})}countTokens(n,s){const{user_profile_id:i,workspace_id:c,...d}=n,f={body:d,...s,headers:L([{...i!=null?{"anthropic-user-profile-id":i}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers])};return this._client.post("/v1/messages/count_tokens",{...f,__span:N(this._client,"anthropic.messages.count_tokens",s,{route:"/v1/messages/count_tokens",request:f})})}}return e.AvailableToolsLimitExceededError=U_,e.CompactionBlockAmbiguousError=B_,e.CompactionBlockMisplacedError=G_,e.CompactionContentMismatchError=H_,e.CompactionIncompleteTurnError=F_,e.CompactionNothingToSummarizeError=V_,e.CompactionSignatureInvalidError=K_,e.CompactionTooManyToolReferencesError=Y_,e.CompactionToolChangesMismatchError=W_,e.ThreadAlreadyContinuedError=X_,e.ThreadContinueInFlightError=Q_,e.ThreadFingerprintMismatchError=J_,e.ThreadUnsupportedRequestError=Z_,e.ToolNameConflictError=ev,e.ToolReferenceUnresolvedError=tv,e.ThreadNotFoundError=nv,e.CompactionUnavailableError=sv,e.Batches=n5,e})();const a5={"claude-sonnet-4-5":"November 30th, 2026","claude-sonnet-4-5-20250929":"November 30th, 2026"},M$=["claude-mythos-preview","claude-opus-4-6"];var av=(()=>{class e extends Ye{}return e._errorName="OrgAPIKeyLimitExceededError",e})(),rv=(()=>{class e extends Ye{}return e._errorName="WorkspaceAPIKeyLimitExceededError",e})(),r5=(()=>{class e extends ye{retrieve(n,s){return this._client.get(U`/v1/organizations/api_keys/${n}`,{...s,__span:N(this._client,"anthropic.organization.api_keys.retrieve",s,{route:"/v1/organizations/api_keys/{api_key_id}",attributes:{"anthropic.organization.api_key.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/api_keys/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.api_keys.update",i,{route:"/v1/organizations/api_keys/{api_key_id}",attributes:{"anthropic.organization.api_key.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/api_keys",ns,{query:n,...s,__span:N(this._client,"anthropic.organization.api_keys.list",s,{route:"/v1/organizations/api_keys",queryParams:["after_id","before_id","created_by_user_id","limit","status","workspace_id"]})})}}return e.OrgAPIKeyLimitExceededError=av,e.WorkspaceAPIKeyLimitExceededError=rv,e})(),iv=(()=>{class e extends Ye{}return e._errorName="ExternalKeyInWorkspacePolicyError",e})(),ov=(()=>{class e extends Ye{}return e._errorName="ExternalKeyValidationFailedError",e})(),lv=(()=>{class e extends Ye{}return e._errorName="ExternalKeyValidationTimedOutError",e})(),cv=(()=>{class e extends Vr{}return e._errorName="ExternalKeyChangedError",e})(),i5=(()=>{class e extends ye{create(n,s){return this._client.post("/v1/organizations/external_keys",{body:n,...s,__span:N(this._client,"anthropic.organization.external_keys.create",s,{route:"/v1/organizations/external_keys",createdIDAttribute:"anthropic.organization.external_key.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/external_keys/${n}`,{...s,__span:N(this._client,"anthropic.organization.external_keys.retrieve",s,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/external_keys/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.external_keys.update",i,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/external_keys",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.external_keys.list",s,{route:"/v1/organizations/external_keys",queryParams:["limit","page"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/external_keys/${n}`,{...s,__span:N(this._client,"anthropic.organization.external_keys.delete",s,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":n}})})}validate(n,s){return this._client.post(U`/v1/organizations/external_keys/${n}/validate`,{...s,__span:N(this._client,"anthropic.organization.external_keys.validate",s,{route:"/v1/organizations/external_keys/{external_key_id}/validate",attributes:{"anthropic.organization.external_key.id":n}})})}}return e.ExternalKeyInWorkspacePolicyError=iv,e.ExternalKeyValidationFailedError=ov,e.ExternalKeyValidationTimedOutError=lv,e.ExternalKeyChangedError=cv,e})(),uv=(()=>{class e extends Ye{}return e._errorName="AlreadyMemberError",e})(),dv=(()=>{class e extends Ye{}return e._errorName="CannotInviteEmailsWithUnverifiedDomainsError",e})(),hv=(()=>{class e extends Ye{}return e._errorName="EmailDomainNotAllowedError",e})(),mv=(()=>{class e extends Ye{}return e._errorName="InviteAlreadyExistsError",e})(),o5=(()=>{class e extends ye{create(n,s){return this._client.post("/v1/organizations/invites",{body:n,...s,__span:N(this._client,"anthropic.organization.invites.create",s,{route:"/v1/organizations/invites",createdIDAttribute:"anthropic.organization.invite.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/invites/${n}`,{...s,__span:N(this._client,"anthropic.organization.invites.retrieve",s,{route:"/v1/organizations/invites/{invite_id}",attributes:{"anthropic.organization.invite.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/invites",ns,{query:n,...s,__span:N(this._client,"anthropic.organization.invites.list",s,{route:"/v1/organizations/invites",queryParams:["after_id","before_id","email","limit","roles","statuses"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/invites/${n}`,{...s,__span:N(this._client,"anthropic.organization.invites.delete",s,{route:"/v1/organizations/invites/{invite_id}",attributes:{"anthropic.organization.invite.id":n}})})}}return e.AlreadyMemberError=uv,e.CannotInviteEmailsWithUnverifiedDomainsError=dv,e.EmailDomainNotAllowedError=hv,e.InviteAlreadyExistsError=mv,e})();class l5 extends ye{retrieve(r){return this._client.get("/v1/organizations/compliance_settings",{...r,__span:N(this._client,"anthropic.organization.compliance_settings.retrieve",r,{route:"/v1/organizations/compliance_settings"})})}update(r,n){return this._client.post("/v1/organizations/compliance_settings",{body:r,...n,__span:N(this._client,"anthropic.organization.compliance_settings.update",n,{route:"/v1/organizations/compliance_settings"})})}}let c5=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/rate_limits",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.rate_limits.list",n,{route:"/v1/organizations/rate_limits",queryParams:["group_type","limit","model","page"]})})}};var fv=(()=>{class e extends Ye{}return e._errorName="CannotRemoveLastMemberError",e})(),u5=(()=>{class e extends ye{retrieve(n,s){return this._client.get(U`/v1/organizations/users/${n}`,{...s,__span:N(this._client,"anthropic.organization.users.retrieve",s,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/users/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.users.update",i,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/users",ns,{query:n,...s,__span:N(this._client,"anthropic.organization.users.list",s,{route:"/v1/organizations/users",queryParams:["after_id","before_id","email","limit","roles"]})})}remove(n,s){return this._client.delete(U`/v1/organizations/users/${n}`,{...s,__span:N(this._client,"anthropic.organization.users.remove",s,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}}return e.CannotRemoveLastMemberError=fv,e})();class d5 extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/artifacts",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.artifacts.list",n,{route:"/v1/organizations/analytics/artifacts",queryParams:["date","filter","group_by","limit","page"]})})}}class h5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/connectors",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.connectors.list",n,{route:"/v1/organizations/analytics/connectors",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}}class m5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/plugins",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.plugins.list",n,{route:"/v1/organizations/analytics/plugins",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}}let f5=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/skills",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.skills.list",n,{route:"/v1/organizations/analytics/skills",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}};class p5 extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/summaries",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.summaries.list",n,{route:"/v1/organizations/analytics/summaries",queryParams:["ending_date","filter","limit","page","starting_date"]})})}}class g5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/users",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.users.list",n,{route:"/v1/organizations/analytics/users",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["page"]})})}}class b5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/apps/chat/projects",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.apps.chat.projects.list",n,{route:"/v1/organizations/analytics/apps/chat/projects",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"]})})}}var x5=(()=>{class e extends ye{constructor(){super(...arguments),this.projects=new b5(this._client)}}return e.Projects=b5,e})(),y5=(()=>{class e extends ye{constructor(){super(...arguments),this.chat=new x5(this._client)}}return e.Chat=x5,e})(),_5=(()=>{class e extends ye{constructor(){super(...arguments),this.summaries=new p5(this._client),this.users=new g5(this._client),this.apps=new y5(this._client),this.connectors=new h5(this._client),this.plugins=new m5(this._client),this.skills=new f5(this._client),this.artifacts=new d5(this._client)}}return e.Summaries=p5,e.Users=g5,e.Apps=y5,e.Connectors=h5,e.Plugins=m5,e.Skills=f5,e.Artifacts=d5,e})();class v5 extends ye{create(r,n){return this._client.post("/v1/organizations/federation_issuers",{body:r,...n,__span:N(this._client,"anthropic.organization.federation.issuers.create",n,{route:"/v1/organizations/federation_issuers",createdIDAttribute:"anthropic.organization.federation_issuer.id"})})}retrieve(r,n){return this._client.get(U`/v1/organizations/federation_issuers/${r}`,{...n,__span:N(this._client,"anthropic.organization.federation.issuers.retrieve",n,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}",attributes:{"anthropic.organization.federation_issuer.id":r}})})}update(r,n,s){return this._client.post(U`/v1/organizations/federation_issuers/${r}`,{body:n,...s,__span:N(this._client,"anthropic.organization.federation.issuers.update",s,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}",attributes:{"anthropic.organization.federation_issuer.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/federation_issuers",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.federation.issuers.list",n,{route:"/v1/organizations/federation_issuers",queryParams:["include_archived","limit","page"]})})}archive(r,n){return this._client.post(U`/v1/organizations/federation_issuers/${r}/archive`,{...n,__span:N(this._client,"anthropic.organization.federation.issuers.archive",n,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}/archive",attributes:{"anthropic.organization.federation_issuer.id":r}})})}}let w5=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/federation_rules/${r}/workspaces`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.federation.rules.workspaces.list",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.federation_rule.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/federation_rules/${r}/workspaces`,{body:n,...s,__span:N(this._client,"anthropic.organization.federation.rules.workspaces.add",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces",attributes:{"anthropic.organization.federation_rule.id":r},createdIDAttribute:"anthropic.organization.federation_rule.workspace.id",createdIDField:"workspace_id"})})}remove(r,n,s){const{federation_rule_id:i}=n;return this._client.delete(U`/v1/organizations/federation_rules/${i}/workspaces/${r}`,{...s,__span:N(this._client,"anthropic.organization.federation.rules.workspaces.remove",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.federation_rule.id":i,"anthropic.organization.federation_rule.workspace.id":r}})})}};var S5=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new w5(this._client)}create(n,s){return this._client.post("/v1/organizations/federation_rules",{body:n,...s,__span:N(this._client,"anthropic.organization.federation.rules.create",s,{route:"/v1/organizations/federation_rules",createdIDAttribute:"anthropic.organization.federation_rule.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/federation_rules/${n}`,{...s,__span:N(this._client,"anthropic.organization.federation.rules.retrieve",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}",attributes:{"anthropic.organization.federation_rule.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/federation_rules/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.federation.rules.update",i,{route:"/v1/organizations/federation_rules/{federation_rule_id}",attributes:{"anthropic.organization.federation_rule.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/federation_rules",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.federation.rules.list",s,{route:"/v1/organizations/federation_rules",queryParams:["include_archived","issuer_id","limit","page"]})})}archive(n,s){return this._client.post(U`/v1/organizations/federation_rules/${n}/archive`,{...s,__span:N(this._client,"anthropic.organization.federation.rules.archive",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/archive",attributes:{"anthropic.organization.federation_rule.id":n}})})}}return e.Workspaces=w5,e})(),k5=(()=>{class e extends ye{constructor(){super(...arguments),this.issuers=new v5(this._client),this.rules=new S5(this._client)}}return e.Issuers=v5,e.Rules=S5,e})();let C5=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/rbac_groups/${r}/members`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.rbac_groups.members.list",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members",queryParams:["limit","page"],attributes:{"anthropic.organization.rbac_group.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/rbac_groups/${r}/members`,{body:n,...s,__span:N(this._client,"anthropic.organization.rbac_groups.members.add",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members",attributes:{"anthropic.organization.rbac_group.id":r},createdIDAttribute:"anthropic.organization.rbac_group.member.id",createdIDField:"user_id"})})}remove(r,n,s){const{rbac_group_id:i}=n;return this._client.delete(U`/v1/organizations/rbac_groups/${i}/members/${r}`,{...s,__span:N(this._client,"anthropic.organization.rbac_groups.members.remove",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members/{user_id}",attributes:{"anthropic.organization.rbac_group.id":i,"anthropic.organization.rbac_group.member.id":r}})})}};var pv=(()=>{class e extends Ye{}return e._errorName="RBACGroupGrantsOwnerAccessError",e})(),gv=(()=>{class e extends Ye{}return e._errorName="RBACGroupOwnerAccessUnconfirmedError",e})(),N5=(()=>{class e extends ye{constructor(){super(...arguments),this.members=new C5(this._client)}create(n,s){return this._client.post("/v1/organizations/rbac_groups",{body:n,...s,__span:N(this._client,"anthropic.organization.rbac_groups.create",s,{route:"/v1/organizations/rbac_groups",createdIDAttribute:"anthropic.organization.rbac_group.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/rbac_groups/${n}`,{...s,__span:N(this._client,"anthropic.organization.rbac_groups.retrieve",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/rbac_groups/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.rbac_groups.update",i,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/rbac_groups",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.rbac_groups.list",s,{route:"/v1/organizations/rbac_groups",queryParams:["limit","page"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/rbac_groups/${n}`,{...s,__span:N(this._client,"anthropic.organization.rbac_groups.delete",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}}return e.RBACGroupGrantsOwnerAccessError=pv,e.RBACGroupOwnerAccessUnconfirmedError=gv,e.Members=C5,e})();class A5 extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/rbac_roles/${r}/permissions`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.rbac_roles.permissions.list",s,{route:"/v1/organizations/rbac_roles/{rbac_role_id}/permissions",queryParams:["limit","page"],attributes:{"anthropic.organization.rbac_role.id":r}})})}}var j5=(()=>{class e extends ye{constructor(){super(...arguments),this.permissions=new A5(this._client)}retrieve(n,s){return this._client.get(U`/v1/organizations/rbac_roles/${n}`,{...s,__span:N(this._client,"anthropic.organization.rbac_roles.retrieve",s,{route:"/v1/organizations/rbac_roles/{rbac_role_id}",attributes:{"anthropic.organization.rbac_role.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/rbac_roles",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.rbac_roles.list",s,{route:"/v1/organizations/rbac_roles",queryParams:["limit","page"]})})}}return e.Permissions=A5,e})();let T5=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/service_accounts/${r}/workspaces`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.service_accounts.workspaces.list",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.service_account.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/service_accounts/${r}/workspaces`,{body:n,...s,__span:N(this._client,"anthropic.organization.service_accounts.workspaces.add",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces",attributes:{"anthropic.organization.service_account.id":r},createdIDAttribute:"anthropic.organization.service_account.workspace.id",createdIDField:"workspace_id"})})}remove(r,n,s){const{service_account_id:i}=n;return this._client.delete(U`/v1/organizations/service_accounts/${i}/workspaces/${r}`,{...s,__span:N(this._client,"anthropic.organization.service_accounts.workspaces.remove",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.service_account.id":i,"anthropic.organization.service_account.workspace.id":r}})})}};var E5=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new T5(this._client)}create(n,s){return this._client.post("/v1/organizations/service_accounts",{body:n,...s,__span:N(this._client,"anthropic.organization.service_accounts.create",s,{route:"/v1/organizations/service_accounts",createdIDAttribute:"anthropic.organization.service_account.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/service_accounts/${n}`,{...s,__span:N(this._client,"anthropic.organization.service_accounts.retrieve",s,{route:"/v1/organizations/service_accounts/{service_account_id}",attributes:{"anthropic.organization.service_account.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/service_accounts/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.service_accounts.update",i,{route:"/v1/organizations/service_accounts/{service_account_id}",attributes:{"anthropic.organization.service_account.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/service_accounts",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.service_accounts.list",s,{route:"/v1/organizations/service_accounts",queryParams:["include_archived","limit","page"]})})}archive(n,s){return this._client.post(U`/v1/organizations/service_accounts/${n}/archive`,{...s,__span:N(this._client,"anthropic.organization.service_accounts.archive",s,{route:"/v1/organizations/service_accounts/{service_account_id}/archive",attributes:{"anthropic.organization.service_account.id":n}})})}}return e.Workspaces=T5,e})();class M5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/spend_limits/effective",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.spend_limits.effective.list",n,{route:"/v1/organizations/spend_limits/effective",queryParams:["limit","page","period","user_ids"]})})}}class R5 extends ye{retrieve(r,n){return this._client.get(U`/v1/organizations/spend_limit_increase_requests/${r}`,{...n,__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.retrieve",n,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/spend_limit_increase_requests",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.list",n,{route:"/v1/organizations/spend_limit_increase_requests",queryParams:["actor_ids","limit","page","status"]})})}approve(r,n,s){return this._client.post(U`/v1/organizations/spend_limit_increase_requests/${r}/approve`,{body:n,...s,__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.approve",s,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}/approve",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}deny(r,n,s){return this._client.post(U`/v1/organizations/spend_limit_increase_requests/${r}/deny`,{body:n,...s,__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.deny",s,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}/deny",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}}var z5=(()=>{class e extends ye{constructor(){super(...arguments),this.effective=new M5(this._client),this.increaseRequests=new R5(this._client)}}return e.Effective=M5,e.IncreaseRequests=R5,e})();class O5 extends ye{retrieve(r,n,s){const{workspace_id:i}=n;return this._client.get(U`/v1/organizations/workspaces/${i}/members/${r}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.members.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/members/${r}`,{body:c,...s,__span:N(this._client,"anthropic.organization.workspaces.members.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/members`,ns,{query:n,...s,__span:N(this._client,"anthropic.organization.workspaces.members.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/members",queryParams:["after_id","before_id","limit"],attributes:{"anthropic.organization.workspace.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/workspaces/${r}/members`,{body:n,...s,__span:N(this._client,"anthropic.organization.workspaces.members.add",s,{route:"/v1/organizations/workspaces/{workspace_id}/members",attributes:{"anthropic.organization.workspace.id":r},createdIDAttribute:"anthropic.organization.workspace.member.id",createdIDField:"user_id"})})}remove(r,n,s){const{workspace_id:i}=n;return this._client.delete(U`/v1/organizations/workspaces/${i}/members/${r}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.members.remove",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}}class P5 extends ye{update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/rate_limits/${r}`,{body:c,...s,__span:N(this._client,"anthropic.organization.workspaces.rate_limits.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/rate_limits/{rate_limit_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.rate_limit.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/rate_limits`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.workspaces.rate_limits.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/rate_limits",queryParams:["group_type","include_inherited","limit","page"],attributes:{"anthropic.organization.workspace.id":r}})})}}class $5 extends ye{retrieve(r,n,s){const{workspace_id:i}=n;return this._client.get(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{body:c,...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/service_accounts`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts",queryParams:["limit","page"],attributes:{"anthropic.organization.workspace.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/workspaces/${r}/service_accounts`,{body:n,...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.add",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts",attributes:{"anthropic.organization.workspace.id":r},createdIDAttribute:"anthropic.organization.workspace.service_account.id",createdIDField:"service_account_id"})})}remove(r,n,s){const{workspace_id:i}=n;return this._client.delete(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.remove",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}}var bv=(()=>{class e extends Ye{}return e._errorName="KeyProfileMismatchError",e})(),xv=(()=>{class e extends Ye{}return e._errorName="WorkspaceMemberLimitExceededError",e})(),yv=(()=>{class e extends Ye{}return e._errorName="WorkspacePolicyViolationError",e})(),I5=(()=>{class e extends ye{constructor(){super(...arguments),this.rateLimits=new P5(this._client),this.members=new O5(this._client),this.serviceAccounts=new $5(this._client)}create(n,s){return this._client.post("/v1/organizations/workspaces",{body:n,...s,__span:N(this._client,"anthropic.organization.workspaces.create",s,{route:"/v1/organizations/workspaces",createdIDAttribute:"anthropic.organization.workspace.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/workspaces/${n}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}",attributes:{"anthropic.organization.workspace.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/workspaces/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.workspaces.update",i,{route:"/v1/organizations/workspaces/{workspace_id}",attributes:{"anthropic.organization.workspace.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/workspaces",ns,{query:n,...s,__span:N(this._client,"anthropic.organization.workspaces.list",s,{route:"/v1/organizations/workspaces",queryParams:["after_id","before_id","ids","include_archived","include_default","limit"]})})}archive(n,s){return this._client.post(U`/v1/organizations/workspaces/${n}/archive`,{...s,__span:N(this._client,"anthropic.organization.workspaces.archive",s,{route:"/v1/organizations/workspaces/{workspace_id}/archive",attributes:{"anthropic.organization.workspace.id":n}})})}}return e.KeyProfileMismatchError=bv,e.WorkspaceMemberLimitExceededError=xv,e.WorkspacePolicyViolationError=yv,e.RateLimits=P5,e.Members=O5,e.ServiceAccounts=$5,e})(),_v=(()=>{class e extends Ye{}return e._errorName="OrgMemberLimitExceededError",e})(),vv=(()=>{class e extends Vr{}return e._errorName="ConcurrentMembershipChangeError",e})(),D5=(()=>{class e extends ye{constructor(){super(...arguments),this.apiKeys=new r5(this._client),this.externalKeys=new i5(this._client),this.federation=new k5(this._client),this.invites=new o5(this._client),this.serviceAccounts=new E5(this._client),this.users=new u5(this._client),this.workspaces=new I5(this._client),this.rateLimits=new c5(this._client),this.complianceSettings=new l5(this._client),this.analytics=new _5(this._client),this.spendLimits=new z5(this._client),this.rbacGroups=new N5(this._client),this.rbacRoles=new j5(this._client)}retrieve(n){return this._client.get("/v1/organizations/me",{...n,__span:N(this._client,"anthropic.organization.retrieve",n,{route:"/v1/organizations/me"})})}}return e.OrgMemberLimitExceededError=_v,e.ConcurrentMembershipChangeError=vv,e.APIKeys=r5,e.OrgAPIKeyLimitExceededError=av,e.WorkspaceAPIKeyLimitExceededError=rv,e.ExternalKeys=i5,e.ExternalKeyInWorkspacePolicyError=iv,e.ExternalKeyValidationFailedError=ov,e.ExternalKeyValidationTimedOutError=lv,e.ExternalKeyChangedError=cv,e.Federation=k5,e.Invites=o5,e.AlreadyMemberError=uv,e.CannotInviteEmailsWithUnverifiedDomainsError=dv,e.EmailDomainNotAllowedError=hv,e.InviteAlreadyExistsError=mv,e.ServiceAccounts=E5,e.Users=u5,e.CannotRemoveLastMemberError=fv,e.Workspaces=I5,e.KeyProfileMismatchError=bv,e.WorkspaceMemberLimitExceededError=xv,e.WorkspacePolicyViolationError=yv,e.RateLimits=c5,e.ComplianceSettings=l5,e.Analytics=_5,e.SpendLimits=z5,e.RBACGroups=N5,e.RBACGroupGrantsOwnerAccessError=pv,e.RBACGroupOwnerAccessUnconfirmedError=gv,e.RBACRoles=j5,e})();class q5 extends ye{create(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/skills/${r}/versions`,Kr({body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.versions.create",s,{route:"/v1/skills/{skill_id}/versions",attributes:{"anthropic.skill.id":r},createdIDAttribute:"anthropic.skill.version.id"})},this._client,!1))}retrieve(r,n,s){const{skill_id:i,workspace_id:c}=n;return this._client.get(U`/v1/skills/${i}/versions/${r}`,{...s,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.versions.retrieve",s,{route:"/v1/skills/{skill_id}/versions/{version}",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}list(r,n={},s){const{workspace_id:i,...c}=n??{};return this._client.getAPIList(U`/v1/skills/${r}/versions`,Me,{query:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.versions.list",s,{route:"/v1/skills/{skill_id}/versions",queryParams:["limit","page"],attributes:{"anthropic.skill.id":r}})})}delete(r,n,s){const{skill_id:i,workspace_id:c}=n;return this._client.delete(U`/v1/skills/${i}/versions/${r}`,{...s,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.versions.delete",s,{route:"/v1/skills/{skill_id}/versions/{version}",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}}var wv=(()=>{class e extends Vr{}return e._errorName="SkillReadBlockedUndecryptableError",e})(),L5=(()=>{class e extends ye{constructor(){super(...arguments),this.versions=new q5(this._client)}create(n,s){const{workspace_id:i,...c}=n;return this._client.post("/v1/skills",Kr({body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.create",s,{route:"/v1/skills",createdIDAttribute:"anthropic.skill.id"})},this._client,!1))}retrieve(n,s={},i){const{workspace_id:c}=s??{};return this._client.get(U`/v1/skills/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.skills.retrieve",i,{route:"/v1/skills/{skill_id}",attributes:{"anthropic.skill.id":n}})})}list(n={},s){const{workspace_id:i,...c}=n??{};return this._client.getAPIList("/v1/skills",Me,{query:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.list",s,{route:"/v1/skills",queryParams:["limit","page","source"]})})}delete(n,s={},i){const{workspace_id:c}=s??{};return this._client.delete(U`/v1/skills/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.skills.delete",i,{route:"/v1/skills/{skill_id}",attributes:{"anthropic.skill.id":n}})})}}return e.SkillReadBlockedUndecryptableError=wv,e.Versions=q5,e})();class U5 extends ye{create(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/user_profiles/${r}/action_urls`,{body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.user_profiles.action_urls.create",s,{route:"/v1/user_profiles/{user_profile_id}/action_urls",attributes:{"anthropic.user_profile.id":r}})})}}var Sv=(()=>{class e extends Ye{}return e._errorName="UserProfileNotFoundError",e})(),B5=(()=>{class e extends ye{constructor(){super(...arguments),this.actionURLs=new U5(this._client)}create(n,s){const{workspace_id:i,...c}=n;return this._client.post("/v1/user_profiles",{body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.user_profiles.create",s,{route:"/v1/user_profiles",createdIDAttribute:"anthropic.user_profile.id"})})}retrieve(n,s={},i){const{workspace_id:c}=s??{};return this._client.get(U`/v1/user_profiles/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.user_profiles.retrieve",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}update(n,s,i){const{workspace_id:c,...d}=s;return this._client.post(U`/v1/user_profiles/${n}`,{body:d,...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.user_profiles.update",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}list(n={},s){const{workspace_id:i,...c}=n??{};return this._client.getAPIList("/v1/user_profiles",Me,{query:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.user_profiles.list",s,{route:"/v1/user_profiles",queryParams:["enforcement_status","limit","order","order_by","page"]})})}delete(n,s={},i){const{workspace_id:c}=s??{};return this._client.delete(U`/v1/user_profiles/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.user_profiles.delete",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}}return e.UserProfileNotFoundError=Sv,e.ActionURLs=U5,e})();const R$=new Map([["400 already_member",uv],["400 available_tools_limit_exceeded",U_],["400 cannot_invite_emails_with_unverified_domains",dv],["400 cannot_remove_last_member",fv],["400 cannot_sign_out_primary_owner",y_],["400 cannot_sign_out_self",__],["400 claude_code_key_creator_not_member",hT],["400 claude_code_version_too_old",mT],["400 cmek_key_disabled",fT],["400 cmek_key_network_blocked",pT],["400 compaction_block_ambiguous",B_],["400 compaction_block_misplaced",G_],["400 compaction_content_mismatch",H_],["400 compaction_incomplete_turn",F_],["400 compaction_nothing_to_summarize",V_],["400 compaction_signature_invalid",K_],["400 compaction_too_many_tool_references",Y_],["400 compaction_tool_changes_mismatch",W_],["400 email_domain_not_allowed",hv],["400 environment_archived",u_],["400 external_key_in_workspace_policy",iv],["400 external_key_validation_failed",ov],["400 external_key_validation_timed_out",lv],["400 file_not_downloadable",r_],["400 invalid_config_type_change",d_],["400 invalid_metadata",h_],["400 invite_already_exists",mv],["400 key_profile_mismatch",bv],["400 org_api_key_limit_exceeded",av],["400 org_member_limit_exceeded",_v],["400 organization_not_enrolled_in_beta",q_],["400 organization_on_hold",gT],["400 organization_type_not_supported",bT],["400 rbac_group_grants_owner_access",pv],["400 rbac_group_owner_access_unconfirmed",gv],["400 request_body_encoding_invalid",xT],["400 request_body_encoding_unsupported",yT],["400 scan_failed",C_],["400 slack_channel_set_up_settings_refused",E_],["400 storage_quota_exceeded",i_],["400 thread_already_continued",X_],["400 thread_continue_in_flight",Q_],["400 thread_fingerprint_mismatch",J_],["400 thread_unsupported_request",Z_],["400 tool_name_conflict",ev],["400 tool_reference_unresolved",tv],["400 unsupported_charset",L_],["400 user_profile_not_found",Sv],["400 workspace_api_key_limit_exceeded",rv],["400 workspace_member_limit_exceeded",xv],["400 workspace_policy_violation",yv],["403 api_key_scope_missing",M_],["403 cannot_sign_out_managed_member",v_],["403 cannot_sign_out_membership_admin",w_],["403 cannot_sign_out_owner",S_],["403 cannot_sign_out_privileged_member",k_],["403 claude_tag_writes_not_enabled",R_],["403 compliance_configuration_restricted",z_],["403 environment_create_disabled",m_],["403 environment_update_disabled",f_],["403 organization_level_scoped_api_key_required",O_],["403 sandbox_egress_restricted",_T],["403 spend_limits_admin_api_writes_not_enabled",I_],["404 environment_not_found",p_],["404 file_expired",o_],["404 slack_channel_set_up_environment_not_found",P_],["404 thread_not_found",nv],["409 concurrent_membership_change",vv],["409 external_key_changed",cv],["409 plugin_name_taken",N_],["409 scan_pending",A_],["409 skill_name_taken",j_],["409 skill_read_blocked_undecryptable",wv],["409 slack_channel_set_up_settings_conflict",$_],["412 heartbeat_precondition_failed",c_],["413 request_body_too_large_after_decoding",vT],["429 enforced_spend_limit_reached",wT],["429 ramp_limit_exceeded",ST],["503 cmek_context_unavailable",kT],["503 cmek_key_unreachable",CT],["503 registration_pending",T_],["529 compaction_unavailable",sv]]),z$="urn:ietf:params:oauth:grant-type:jwt-bearer",O$="refresh_token",JT="/v1/oauth/token",Cp="oauth-2025-04-20",P$="oidc-federation-2026-04-01",$$=120,kv=30,I$=5,G5=1<<20;function ZT(e){if(!e)return;let r;try{r=new URL(e)}catch(s){throw new Bt(`Invalid token endpoint base URL "${e}": ${s}`)}if(r.protocol==="https:")return;const n=r.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(r.protocol==="http:"&&(n==="localhost"||n==="127.0.0.1"||n==="::1")))throw new Bt(`Refusing to send credential over non-https token endpoint "${e}"`)}async function e3(e,r){const n=await q$(e);let s;try{s=JSON.parse(n)}catch{throw new Bt(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,ra(n),r)}if(!s.access_token)throw new Bt(`Token endpoint response missing access_token: ${JSON.stringify(ra(s))}`,e.status,ra(s),r);if(s.token_type&&s.token_type.toLowerCase()!=="bearer")throw new Bt(`Token endpoint response: unsupported token_type "${s.token_type}" (want Bearer)`,e.status,ra(s),r);return s}const px=2e3,D$=new Set(["error","error_description","error_uri"]);function ra(e){if(e==null)return e;if(typeof e=="string"){let r;try{r=JSON.parse(e)}catch{return e.length<=px?e:e.slice(0,px)+`... <${e.length-px} more chars>`}return JSON.stringify(ra(r))}if(typeof e=="object"&&!Array.isArray(e)){const r={};for(const[n,s]of Object.entries(e))D$.has(n)&&(r[n]=s);return r}return null}async function t3(e,r=n=>console.warn(`anthropic-sdk: ${n}`)){if(typeof process>"u"||process.platform==="win32")return;const{fs:n}=await Aa(async()=>{const{fs:d}=await import("./node.browser-BFtyutLR.js");return{fs:d}},[]);let s=e,i;try{s=await n.promises.realpath(e),i=await n.promises.stat(s)}catch{return}const c=i.mode&511;if(c&18)throw new Bt(`Credentials file at ${s} is group/world-writable (mode 0o${c.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${s}\`.`);if(c&36)throw new Bt(`Credentials file at ${s} is group/world-readable (mode 0o${c.toString(8)}); run \`chmod 600 ${s}\` before retrying.`);typeof process.getuid=="function"&&i.uid!==process.getuid()&&r(`credentials file at ${s} is owned by uid ${i.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function n3(e,r){const{fs:n,path:s}=await Aa(async()=>{const{fs:d,path:f}=await import("./node.browser-BFtyutLR.js");return{fs:d,path:f}},[]),i=s.dirname(e);await n.promises.mkdir(i,{recursive:!0,mode:448});const c=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const d=await n.promises.open(c,"w",384);try{await d.writeFile(JSON.stringify(r,null,2)),await d.sync()}finally{await d.close()}await n.promises.rename(c,e)}catch(d){throw await n.promises.unlink(c).catch(()=>{}),d}try{const d=await n.promises.open(i,"r");try{await d.sync()}finally{await d.close()}}catch{}}async function q$(e){if(!e.body)return"";const r=e.body.getReader(),n=[];let s=0;for(;;){const{done:c,value:d}=await r.read();if(c)break;if(s+d.length>G5){const f=G5-s;f>0&&n.push(d.subarray(0,f)),await r.cancel();break}n.push(d),s+=d.length}let i;if(n.length===1)i=n[0];else{i=new Uint8Array(n.reduce((d,f)=>d+f.length,0));let c=0;for(const d of n)i.set(d,c),c+=d.length}return new TextDecoder("utf-8").decode(i)}var Bt=(()=>{class e extends De{constructor(n,s=null,i=null,c=null){super(n),this.statusCode=s,this.body=i,this.requestId=c}}return e._errorName="WorkloadIdentityError",e})();function Wo(){return Math.floor(Date.now()/1e3)}class L${constructor(r,n){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=r,this.onAdvisoryRefreshError=n}async getToken(){const r=this.nextForce;this.nextForce=!1;const n=this.cached;if(r||n==null)return(await this.refresh(r)).token;if(n.expiresAt==null)return n.token;const s=n.expiresAt-Wo();return s>$$?n.token:s>kv?(this.backgroundRefresh(),n.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(r=!1){return this.pendingRefresh&&!r?this.pendingRefresh:this.doRefresh(r)}backgroundRefresh(){this.pendingRefresh||Wo()-this.lastAdvisoryError<I$||this.doRefresh().catch(r=>{this.lastAdvisoryError=Wo(),this.onAdvisoryRefreshError?.(r)})}doRefresh(r=!1){return this.pendingRefresh=this.provider(r?{forceRefresh:!0}:void 0).then(n=>(this.cached=n,this.pendingRefresh=null,n),n=>{throw this.pendingRefresh=null,n}),this.pendingRefresh}}const s3="1.0",U$=/^[A-Za-z0-9_.-]+$/;function a3(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!U$.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}const B$=async e=>{var r,n;const s=await Cv();if(s===null)return null;const i=e==null&&ot("ANTHROPIC_PROFILE")!=null;let c=null;if(e==null&&!i){const y=ot("ANTHROPIC_ORGANIZATION_ID"),S=ot("ANTHROPIC_IDENTITY_TOKEN_FILE"),k=ot("ANTHROPIC_FEDERATION_RULE_ID");if(k&&y&&(c={fromFile:!1,config:{organization_id:y,workspace_id:ot("ANTHROPIC_WORKSPACE_ID"),base_url:ot("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:k,service_account_id:ot("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:S?{source:"file",path:S}:void 0,scope:ot("ANTHROPIC_SCOPE")}}},S||ot("ANTHROPIC_IDENTITY_TOKEN")))return c}const d=e??await r3();if(d===null)return null;a3(d);const{fs:f,path:p}=await Aa(async()=>{const{fs:y,path:S}=await import("./node.browser-BFtyutLR.js");return{fs:y,path:S}},[]),b=p.join(s,"configs",`${d}.json`);let x;try{x=await f.promises.readFile(b,"utf-8")}catch(y){if(y?.code!=="ENOENT")throw new Error(`failed to read config file ${b}: ${y}`);if(i)throw new De(`ANTHROPIC_PROFILE names the profile "${d}", but ${b} does not exist. Set ANTHROPIC_PROFILE to a profile that exists, or unset it.`,{cause:y});return c}let g;try{g=JSON.parse(x)}catch(y){throw new Error(`failed to parse config file ${b}: ${y}`)}if(!g.authentication)throw new Error(`config file ${b} is missing "authentication"`);const _=g.authentication.type;if(_!=="oidc_federation"&&_!=="user_oauth")throw new Error(`authentication.type "${_}" is not a known authentication type`);if(g.organization_id??(g.organization_id=ot("ANTHROPIC_ORGANIZATION_ID")),g.workspace_id??(g.workspace_id=ot("ANTHROPIC_WORKSPACE_ID")),g.base_url??(g.base_url=ot("ANTHROPIC_BASE_URL")),(r=g.authentication).scope??(r.scope=ot("ANTHROPIC_SCOPE")),g.authentication.type==="oidc_federation"){if(!g.authentication.identity_token){const y=ot("ANTHROPIC_IDENTITY_TOKEN_FILE");y&&(g.authentication.identity_token={source:"file",path:y})}g.authentication.federation_rule_id||(g.authentication.federation_rule_id=ot("ANTHROPIC_FEDERATION_RULE_ID")??""),(n=g.authentication).service_account_id??(n.service_account_id=ot("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:g,fromFile:!0}},G$=async(e,r)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const n=await Cv();if(!n)return null;const s=r??await r3();if(!s)return null;a3(s);const{path:i}=await Aa(async()=>{const{path:c}=await import("./node.browser-BFtyutLR.js");return{path:c}},[]);return i.join(n,"credentials",`${s}.json`)},Cv=async()=>{if(!H$())return null;const{path:e}=await Aa(async()=>{const{path:c}=await import("./node.browser-BFtyutLR.js");return{path:c}},[]),r=ot("ANTHROPIC_CONFIG_DIR");if(r)return r;if(Uy()["X-Stainless-OS"]==="Windows"){const c=ot("APPDATA");if(c)return e.join(c,"Anthropic");const d=ot("USERPROFILE");return d?e.join(d,"AppData","Roaming","Anthropic"):null}const s=ot("XDG_CONFIG_HOME");if(s)return e.join(s,"anthropic");const i=ot("HOME");return i?e.join(i,".config","anthropic"):null},H$=()=>{const e=Uy()["X-Stainless-Runtime"];return e==="node"||e==="deno"},r3=async()=>{const e=await Cv();if(!e)return null;const r=ot("ANTHROPIC_PROFILE");if(r)return r;const{fs:n,path:s}=await Aa(async()=>{const{fs:c,path:d}=await import("./node.browser-BFtyutLR.js");return{fs:c,path:d}},[]),i=s.join(e,"active_config");try{return(await n.promises.readFile(i,"utf-8")).trim()||"default"}catch(c){if(c?.code!=="ENOENT")throw new Error(`failed to read ${i}: ${c}`);return"default"}};function H5(e){if(!e)throw new De("Identity token file path is empty");return async()=>{const{fs:r}=await Aa(async()=>{const{fs:i}=await import("./node.browser-BFtyutLR.js");return{fs:i}},[]);let n;try{n=await r.promises.readFile(e,"utf-8")}catch(i){throw new De(`Failed to read identity token file at ${e}: ${i}`)}const s=n.trim();if(!s)throw new De(`Identity token file at ${e} is empty`);return s}}function F$(e){if(!e)throw new De("Identity token value is empty");return()=>e}function V$(e){return async()=>{ZT(e.baseURL);const r=await e.identityTokenProvider();if(r.length>16*1024)throw new Bt(`Identity token is ${Math.ceil(r.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const n={grant_type:z$,assertion:r,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(n.service_account_id=e.serviceAccountId),e.workspaceId&&(n.workspace_id=e.workspaceId);const s=`${e.baseURL}${JT}`;let i;try{i=await e.fetch(s,{method:"POST",redirect:"manual",headers:{"Content-Type":"application/json","anthropic-beta":`${Cp},${P$}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Pr} oidcFederationProvider`},body:JSON.stringify(n)})}catch(p){throw new Bt(`Failed to reach token endpoint ${s}: ${p}`)}const c=i.headers.get("Request-Id");if(!i.ok){const p=await i.text().catch(()=>""),b=ra(p);let x="";throw i.status===401&&(x=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new Bt(`Token exchange failed with status ${i.status}${c?` (request-id ${c})`:""}: ${b}${x}`,i.status,b,c)}const d=await e3(i,c),f=Number(d.expires_in);if(!Number.isFinite(f))throw new Bt(`Token endpoint response missing required fields: ${JSON.stringify(ra(d))}`,i.status,ra(d),c);return{token:d.access_token,expiresAt:Wo()+f}}}function K$(e){return async r=>{const{fs:n}=await Aa(async()=>{const{fs:E}=await import("./node.browser-BFtyutLR.js");return{fs:E}},[]);await t3(e.credentialsPath,e.onSafetyWarning);let s;try{s=await n.promises.readFile(e.credentialsPath,"utf-8")}catch(E){throw new Bt(`Credentials file not found at ${e.credentialsPath}: ${E}`)}let i;try{i=JSON.parse(s)}catch(E){throw new Bt(`Credentials file at ${e.credentialsPath} is not valid JSON: ${E}`)}const c=i.access_token;if(!c)throw new Bt(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const d=i.expires_at;if(!r?.forceRefresh&&(d==null||Wo()<d-kv))return{token:c,expiresAt:d??null};const f=i.refresh_token;if(!e.clientId||!f)throw new Bt(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${f?"set":"empty"})`);ZT(e.baseURL);const p={grant_type:O$,refresh_token:f,client_id:e.clientId},b=`${e.baseURL}${JT}`;let x;try{x=await e.fetch(b,{method:"POST",redirect:"manual",headers:{"Content-Type":"application/json","anthropic-beta":Cp,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Pr} userOAuthProvider`},body:JSON.stringify(p)})}catch(E){throw new Bt(`User OAuth refresh failed to reach token endpoint: ${E}`)}const g=x.headers.get("Request-Id");if(!x.ok){const E=await x.text().catch(()=>"");throw new Bt(`User OAuth refresh failed (HTTP ${x.status}): ${ra(E)}`,x.status,ra(E),g)}const _=await e3(x,g),y=Number(_.expires_in);if(!Number.isFinite(y))throw new Bt(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(ra(_))}`,x.status,ra(_),g);const S=Wo()+y,k=_.refresh_token||f;return await n3(e.credentialsPath,{...i,version:s3,type:"oauth_token",access_token:_.access_token,expires_at:S,refresh_token:k}),{token:_.access_token,expiresAt:S}}}function i3(e,r){const n=e.authentication.credentials_path??null,s=(e.base_url||r.baseURL).replace(/\/+$/,""),i=W$(e,n,s,r),c={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(c["anthropic-workspace-id"]=e.workspace_id),{provider:i,extraHeaders:c,baseURL:e.base_url||void 0}}async function Y$(e,r){const n=await B$(r);if(!n)return null;const{config:s,fromFile:i}=n,c=s.authentication.credentials_path||!i?s:{...s,authentication:{...s.authentication,credentials_path:await G$(s,r)??void 0}};return i3(c,e)}function W$(e,r,n,s){switch(e.authentication.type){case"oidc_federation":{const i=e.authentication,c=X$(i);if(!c)throw new Bt("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!i.federation_rule_id)throw new Bt("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new Bt("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const d=V$({identityTokenProvider:c,federationRuleId:i.federation_rule_id,organizationId:e.organization_id,serviceAccountId:i.service_account_id,workspaceId:e.workspace_id,baseURL:n,fetch:s.fetch,userAgent:s.userAgent});return r?Q$(d,r,s.onCacheWriteError,s.onSafetyWarning):d}case"user_oauth":{if(!r)throw new Bt("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return K$({credentialsPath:r,clientId:e.authentication.client_id,baseURL:n,fetch:s.fetch,userAgent:s.userAgent,onSafetyWarning:s.onSafetyWarning})}default:{const i=e.authentication.type;throw new Bt(`authentication.type "${i}" is not a known authentication type`)}}}function X$(e){if(e.identity_token){const s=e.identity_token.source;if(s!=="file")throw new Bt(`identity_token.source "${s}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Bt('identity_token.source "file" requires a non-empty path');return H5(e.identity_token.path)}const r=ot("ANTHROPIC_IDENTITY_TOKEN_FILE");if(r)return H5(r);const n=ot("ANTHROPIC_IDENTITY_TOKEN");return n?F$(n):null}function Q$(e,r,n,s){return async i=>{const{fs:c}=await Aa(async()=>{const{fs:p}=await import("./node.browser-BFtyutLR.js");return{fs:p}},[]);await t3(r,s);let d;try{const p=await c.promises.readFile(r,"utf-8");d=JSON.parse(p);const b=d?.access_token;if(b&&!i?.forceRefresh){const x=d?.expires_at;if(x==null||Wo()<x-kv)return{token:b,expiresAt:x??null}}}catch(p){p?.code!=="ENOENT"&&!(p instanceof SyntaxError)&&n?.(p)}const f=await e(i);try{await n3(r,{...d??{},version:s3,type:"oauth_token",access_token:f.token,expires_at:f.expiresAt})}catch(p){n?.(p)}return f}}const o3=new WeakSet;function l3(e){return typeof e=="object"&&e!==null&&o3.has(e)}function J$(e){const r=new Set;for(;typeof e=="object"&&e!==null&&!r.has(e);){if(r.add(e),l3(e)||Jo(e)||e instanceof Hc||e instanceof Iz)return!0;e=e.cause}return!1}function F5(e,r,n,s){return async(i,c={})=>{if(r.length===0)return e.call(void 0,i,c);const d=c.headers instanceof Headers?c.headers:new Headers(c.headers),f=await eI(e,r,n,s)({...c,headers:d,url:typeof i=="string"?i:i instanceof URL?i.href:i.url});if(f.bodyUsed||f.body?.locked)throw new De("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return f}}function Z$(e,r){const n=new WeakMap;return{options:e,logger:r?it(r):Pj(),parse(s){if(e?.stream&&s.ok)return V5(s,e,r);let i=n.get(s);return i||(i=V5(s,e,r),n.set(s,i)),i}}}async function V5(e,r,n){if(e.bodyUsed||e.body?.locked)throw new De("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(r?.stream&&e.ok)return Hr.fromSSEResponse(e.clone(),new AbortController,n);if(e.status===204)return null;if(r?.__binaryResponse)return e;const i=e.headers.get("content-type")?.split(";")[0]?.trim();return i?.includes("application/json")||i?.endsWith("+json")?e.headers.get("content-length")==="0"?void 0:Xp(await e.clone().json(),e):await e.clone().text()}function eI(e,r,n,s){let i=async({url:d,...f})=>{try{return await e.call(void 0,d,f)}catch(p){const b=Yd(p);throw o3.add(b),b}};const c=Z$(n,s);for(let d=r.length-1;d>=0;d--){const f=r[d],p=i;i=async b=>f(b,p,c)}return i}const c3=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",tI=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&c3(e),nI=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function sI(e,r,n){if(Yj(),e=await e,r||(r=e instanceof File?e.name:rp(e,!0)),tI(e))return e instanceof File&&r==null&&n==null?e:Pc([await e.arrayBuffer()],r??e.name,{type:e.type,lastModified:e.lastModified,...n});if(nI(e)){const i=await e.blob();return r||(r=new URL(e.url).pathname.split(/[\\/]/).pop()),Pc(await ty(i),r,n)}const s=await ty(e);if(!n?.type){const i=s.find(c=>typeof c=="object"&&"type"in c&&c.type);typeof i=="string"&&(n={...n,type:i})}return Pc(s,r,n)}async function ty(e){let r=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)r.push(e);else if(c3(e))r.push(e instanceof Blob?e:await e.arrayBuffer());else if(Zy(e))for await(const n of e)r.push(...await ty(n));else{const n=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${n?`; constructor: ${n}`:""}${aI(e)}`)}return r}function aI(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class K5 extends ye{retrieve(r,n={},s){const{workspace_id:i}=n??{};return this._client.get(U`/v1/models/${r}`,{...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.models.retrieve",s,{route:"/v1/models/{model_id}",attributes:{"anthropic.model.id":r}})})}list(r={},n){const{workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/models",ns,{query:i,...n,headers:L([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers]),__span:N(this._client,"anthropic.models.list",n,{route:"/v1/models",queryParams:["after_id","before_id","lifecycle","limit"]})})}}var gx,bx,Ff,Sc,Uo,Y5;let W5=!1;var rI=(()=>{class e{get credentials(){return this._authState.provider}get openTelemetry(){return v(this,Uo,"f")}_instrumentationScope(){return{version:Pr}}constructor({baseURL:n=ot("ANTHROPIC_BASE_URL"),apiKey:s,authToken:i,webhookKey:c=ot("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...d}={}){gx.add(this),this._requestAuthFlags=new WeakMap,Ff.set(this,void 0),Sc.set(this,void 0),Uo.set(this,void 0),this._genAIProviderName="anthropic",this._supportsMessageThreads=!1;const f={apiKey:s,authToken:i,...d},p=ic.filter(E=>f[E]!=null);if(p.length>1){const E=T=>T.map(j=>`\`${j}\``).join(", ");throw new TypeError(`Pass at most one of ${E(ic)}. Received ${E(p)}.`)}const[b]=p,x=b!=null?null:{apiKey:s===void 0?ot("ANTHROPIC_API_KEY"):void 0,authToken:i===void 0?ot("ANTHROPIC_AUTH_TOKEN"):void 0},g=b!=null?{type:b,value:f[b]}:x?.apiKey!=null?{type:"apiKey",value:x.apiKey}:x?.authToken!=null?{type:"authToken",value:x.authToken}:{type:"defaultChain"},_={apiKey:g.type==="apiKey"?g.value:null,authToken:g.type==="authToken"?g.value:null,webhookKey:c,...d,baseURL:n||"https://api.anthropic.com"};if(!_.dangerouslyAllowBrowser&&Bz())throw new De(`It looks like you're running in a browser-like environment.
527
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),M$.includes(d.model)&&d.thinking&&d.thinking.type==="enabled"&&console.warn(`Using Claude with ${d.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let f=s?.timeout??this._client._options.timeout;if(!d.stream&&f==null){const g=PT[d.model]??void 0;f=this._client.calculateNonstreamingTimeout(d.max_tokens,g)}const p={body:d,timeout:f??6e5,...s,headers:WT(n,s),stream:n.stream??!1},b=this._client._tracer&&N(this._client,"anthropic.messages.create",s,Jp(this._client,p));nT(this._client,b,d);const x=this._client.post("/v1/messages",{...p,__span:b});return b?x._thenUnwrap(g=>(sT(this._client,b,d,g),g)):x}parse(n,s){return this.create(n,s).then(i=>QT(i,n,{logger:this._client.logger??console}))}stream(n,s){const i=n;return E$.createMessage(this,i,s,{logger:this._client.logger??console,client:this._client})}countTokens(n,s){const{user_profile_id:i,workspace_id:c,...d}=n,f={body:d,...s,headers:L([{...i!=null?{"anthropic-user-profile-id":i}:void 0,...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers])};return this._client.post("/v1/messages/count_tokens",{...f,__span:N(this._client,"anthropic.messages.count_tokens",s,{route:"/v1/messages/count_tokens",request:f})})}}return e.AvailableToolsLimitExceededError=U_,e.CompactionBlockAmbiguousError=B_,e.CompactionBlockMisplacedError=G_,e.CompactionContentMismatchError=H_,e.CompactionIncompleteTurnError=F_,e.CompactionNothingToSummarizeError=V_,e.CompactionSignatureInvalidError=K_,e.CompactionTooManyToolReferencesError=Y_,e.CompactionToolChangesMismatchError=W_,e.ThreadAlreadyContinuedError=X_,e.ThreadContinueInFlightError=Q_,e.ThreadFingerprintMismatchError=J_,e.ThreadUnsupportedRequestError=Z_,e.ToolNameConflictError=ev,e.ToolReferenceUnresolvedError=tv,e.ThreadNotFoundError=nv,e.CompactionUnavailableError=sv,e.Batches=n5,e})();const a5={"claude-sonnet-4-5":"November 30th, 2026","claude-sonnet-4-5-20250929":"November 30th, 2026"},M$=["claude-mythos-preview","claude-opus-4-6"];var av=(()=>{class e extends Ye{}return e._errorName="OrgAPIKeyLimitExceededError",e})(),rv=(()=>{class e extends Ye{}return e._errorName="WorkspaceAPIKeyLimitExceededError",e})(),r5=(()=>{class e extends ye{retrieve(n,s){return this._client.get(U`/v1/organizations/api_keys/${n}`,{...s,__span:N(this._client,"anthropic.organization.api_keys.retrieve",s,{route:"/v1/organizations/api_keys/{api_key_id}",attributes:{"anthropic.organization.api_key.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/api_keys/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.api_keys.update",i,{route:"/v1/organizations/api_keys/{api_key_id}",attributes:{"anthropic.organization.api_key.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/api_keys",ns,{query:n,...s,__span:N(this._client,"anthropic.organization.api_keys.list",s,{route:"/v1/organizations/api_keys",queryParams:["after_id","before_id","created_by_user_id","limit","status","workspace_id"]})})}}return e.OrgAPIKeyLimitExceededError=av,e.WorkspaceAPIKeyLimitExceededError=rv,e})(),iv=(()=>{class e extends Ye{}return e._errorName="ExternalKeyInWorkspacePolicyError",e})(),ov=(()=>{class e extends Ye{}return e._errorName="ExternalKeyValidationFailedError",e})(),lv=(()=>{class e extends Ye{}return e._errorName="ExternalKeyValidationTimedOutError",e})(),cv=(()=>{class e extends Vr{}return e._errorName="ExternalKeyChangedError",e})(),i5=(()=>{class e extends ye{create(n,s){return this._client.post("/v1/organizations/external_keys",{body:n,...s,__span:N(this._client,"anthropic.organization.external_keys.create",s,{route:"/v1/organizations/external_keys",createdIDAttribute:"anthropic.organization.external_key.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/external_keys/${n}`,{...s,__span:N(this._client,"anthropic.organization.external_keys.retrieve",s,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/external_keys/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.external_keys.update",i,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/external_keys",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.external_keys.list",s,{route:"/v1/organizations/external_keys",queryParams:["limit","page"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/external_keys/${n}`,{...s,__span:N(this._client,"anthropic.organization.external_keys.delete",s,{route:"/v1/organizations/external_keys/{external_key_id}",attributes:{"anthropic.organization.external_key.id":n}})})}validate(n,s){return this._client.post(U`/v1/organizations/external_keys/${n}/validate`,{...s,__span:N(this._client,"anthropic.organization.external_keys.validate",s,{route:"/v1/organizations/external_keys/{external_key_id}/validate",attributes:{"anthropic.organization.external_key.id":n}})})}}return e.ExternalKeyInWorkspacePolicyError=iv,e.ExternalKeyValidationFailedError=ov,e.ExternalKeyValidationTimedOutError=lv,e.ExternalKeyChangedError=cv,e})(),uv=(()=>{class e extends Ye{}return e._errorName="AlreadyMemberError",e})(),dv=(()=>{class e extends Ye{}return e._errorName="CannotInviteEmailsWithUnverifiedDomainsError",e})(),hv=(()=>{class e extends Ye{}return e._errorName="EmailDomainNotAllowedError",e})(),mv=(()=>{class e extends Ye{}return e._errorName="InviteAlreadyExistsError",e})(),o5=(()=>{class e extends ye{create(n,s){return this._client.post("/v1/organizations/invites",{body:n,...s,__span:N(this._client,"anthropic.organization.invites.create",s,{route:"/v1/organizations/invites",createdIDAttribute:"anthropic.organization.invite.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/invites/${n}`,{...s,__span:N(this._client,"anthropic.organization.invites.retrieve",s,{route:"/v1/organizations/invites/{invite_id}",attributes:{"anthropic.organization.invite.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/invites",ns,{query:n,...s,__span:N(this._client,"anthropic.organization.invites.list",s,{route:"/v1/organizations/invites",queryParams:["after_id","before_id","email","limit","roles","statuses"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/invites/${n}`,{...s,__span:N(this._client,"anthropic.organization.invites.delete",s,{route:"/v1/organizations/invites/{invite_id}",attributes:{"anthropic.organization.invite.id":n}})})}}return e.AlreadyMemberError=uv,e.CannotInviteEmailsWithUnverifiedDomainsError=dv,e.EmailDomainNotAllowedError=hv,e.InviteAlreadyExistsError=mv,e})();class l5 extends ye{retrieve(r){return this._client.get("/v1/organizations/compliance_settings",{...r,__span:N(this._client,"anthropic.organization.compliance_settings.retrieve",r,{route:"/v1/organizations/compliance_settings"})})}update(r,n){return this._client.post("/v1/organizations/compliance_settings",{body:r,...n,__span:N(this._client,"anthropic.organization.compliance_settings.update",n,{route:"/v1/organizations/compliance_settings"})})}}let c5=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/rate_limits",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.rate_limits.list",n,{route:"/v1/organizations/rate_limits",queryParams:["group_type","limit","model","page"]})})}};var fv=(()=>{class e extends Ye{}return e._errorName="CannotRemoveLastMemberError",e})(),u5=(()=>{class e extends ye{retrieve(n,s){return this._client.get(U`/v1/organizations/users/${n}`,{...s,__span:N(this._client,"anthropic.organization.users.retrieve",s,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/users/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.users.update",i,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/users",ns,{query:n,...s,__span:N(this._client,"anthropic.organization.users.list",s,{route:"/v1/organizations/users",queryParams:["after_id","before_id","email","limit","roles"]})})}remove(n,s){return this._client.delete(U`/v1/organizations/users/${n}`,{...s,__span:N(this._client,"anthropic.organization.users.remove",s,{route:"/v1/organizations/users/{user_id}",attributes:{"anthropic.organization.user.id":n}})})}}return e.CannotRemoveLastMemberError=fv,e})();class d5 extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/artifacts",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.artifacts.list",n,{route:"/v1/organizations/analytics/artifacts",queryParams:["date","filter","group_by","limit","page"]})})}}class h5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/connectors",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.connectors.list",n,{route:"/v1/organizations/analytics/connectors",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}}class m5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/plugins",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.plugins.list",n,{route:"/v1/organizations/analytics/plugins",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}}let f5=class extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/skills",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.skills.list",n,{route:"/v1/organizations/analytics/skills",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["filter"]})})}};class p5 extends ye{list(r,n){return this._client.getAPIList("/v1/organizations/analytics/summaries",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.summaries.list",n,{route:"/v1/organizations/analytics/summaries",queryParams:["ending_date","filter","limit","page","starting_date"]})})}}class g5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/users",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.users.list",n,{route:"/v1/organizations/analytics/users",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"],contentQueryParams:["page"]})})}}class b5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/analytics/apps/chat/projects",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.analytics.apps.chat.projects.list",n,{route:"/v1/organizations/analytics/apps/chat/projects",queryParams:["date","ending_date","filter","group_by","limit","order","order_by","page","starting_date"]})})}}var x5=(()=>{class e extends ye{constructor(){super(...arguments),this.projects=new b5(this._client)}}return e.Projects=b5,e})(),y5=(()=>{class e extends ye{constructor(){super(...arguments),this.chat=new x5(this._client)}}return e.Chat=x5,e})(),_5=(()=>{class e extends ye{constructor(){super(...arguments),this.summaries=new p5(this._client),this.users=new g5(this._client),this.apps=new y5(this._client),this.connectors=new h5(this._client),this.plugins=new m5(this._client),this.skills=new f5(this._client),this.artifacts=new d5(this._client)}}return e.Summaries=p5,e.Users=g5,e.Apps=y5,e.Connectors=h5,e.Plugins=m5,e.Skills=f5,e.Artifacts=d5,e})();class v5 extends ye{create(r,n){return this._client.post("/v1/organizations/federation_issuers",{body:r,...n,__span:N(this._client,"anthropic.organization.federation.issuers.create",n,{route:"/v1/organizations/federation_issuers",createdIDAttribute:"anthropic.organization.federation_issuer.id"})})}retrieve(r,n){return this._client.get(U`/v1/organizations/federation_issuers/${r}`,{...n,__span:N(this._client,"anthropic.organization.federation.issuers.retrieve",n,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}",attributes:{"anthropic.organization.federation_issuer.id":r}})})}update(r,n,s){return this._client.post(U`/v1/organizations/federation_issuers/${r}`,{body:n,...s,__span:N(this._client,"anthropic.organization.federation.issuers.update",s,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}",attributes:{"anthropic.organization.federation_issuer.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/federation_issuers",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.federation.issuers.list",n,{route:"/v1/organizations/federation_issuers",queryParams:["include_archived","limit","page"]})})}archive(r,n){return this._client.post(U`/v1/organizations/federation_issuers/${r}/archive`,{...n,__span:N(this._client,"anthropic.organization.federation.issuers.archive",n,{route:"/v1/organizations/federation_issuers/{federation_issuer_id}/archive",attributes:{"anthropic.organization.federation_issuer.id":r}})})}}let w5=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/federation_rules/${r}/workspaces`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.federation.rules.workspaces.list",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.federation_rule.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/federation_rules/${r}/workspaces`,{body:n,...s,__span:N(this._client,"anthropic.organization.federation.rules.workspaces.add",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces",attributes:{"anthropic.organization.federation_rule.id":r},createdIDAttribute:"anthropic.organization.federation_rule.workspace.id",createdIDField:"workspace_id"})})}remove(r,n,s){const{federation_rule_id:i}=n;return this._client.delete(U`/v1/organizations/federation_rules/${i}/workspaces/${r}`,{...s,__span:N(this._client,"anthropic.organization.federation.rules.workspaces.remove",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.federation_rule.id":i,"anthropic.organization.federation_rule.workspace.id":r}})})}};var S5=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new w5(this._client)}create(n,s){return this._client.post("/v1/organizations/federation_rules",{body:n,...s,__span:N(this._client,"anthropic.organization.federation.rules.create",s,{route:"/v1/organizations/federation_rules",createdIDAttribute:"anthropic.organization.federation_rule.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/federation_rules/${n}`,{...s,__span:N(this._client,"anthropic.organization.federation.rules.retrieve",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}",attributes:{"anthropic.organization.federation_rule.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/federation_rules/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.federation.rules.update",i,{route:"/v1/organizations/federation_rules/{federation_rule_id}",attributes:{"anthropic.organization.federation_rule.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/federation_rules",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.federation.rules.list",s,{route:"/v1/organizations/federation_rules",queryParams:["include_archived","issuer_id","limit","page"]})})}archive(n,s){return this._client.post(U`/v1/organizations/federation_rules/${n}/archive`,{...s,__span:N(this._client,"anthropic.organization.federation.rules.archive",s,{route:"/v1/organizations/federation_rules/{federation_rule_id}/archive",attributes:{"anthropic.organization.federation_rule.id":n}})})}}return e.Workspaces=w5,e})(),k5=(()=>{class e extends ye{constructor(){super(...arguments),this.issuers=new v5(this._client),this.rules=new S5(this._client)}}return e.Issuers=v5,e.Rules=S5,e})();let C5=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/rbac_groups/${r}/members`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.rbac_groups.members.list",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members",queryParams:["limit","page"],attributes:{"anthropic.organization.rbac_group.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/rbac_groups/${r}/members`,{body:n,...s,__span:N(this._client,"anthropic.organization.rbac_groups.members.add",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members",attributes:{"anthropic.organization.rbac_group.id":r},createdIDAttribute:"anthropic.organization.rbac_group.member.id",createdIDField:"user_id"})})}remove(r,n,s){const{rbac_group_id:i}=n;return this._client.delete(U`/v1/organizations/rbac_groups/${i}/members/${r}`,{...s,__span:N(this._client,"anthropic.organization.rbac_groups.members.remove",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}/members/{user_id}",attributes:{"anthropic.organization.rbac_group.id":i,"anthropic.organization.rbac_group.member.id":r}})})}};var pv=(()=>{class e extends Ye{}return e._errorName="RBACGroupGrantsOwnerAccessError",e})(),gv=(()=>{class e extends Ye{}return e._errorName="RBACGroupOwnerAccessUnconfirmedError",e})(),N5=(()=>{class e extends ye{constructor(){super(...arguments),this.members=new C5(this._client)}create(n,s){return this._client.post("/v1/organizations/rbac_groups",{body:n,...s,__span:N(this._client,"anthropic.organization.rbac_groups.create",s,{route:"/v1/organizations/rbac_groups",createdIDAttribute:"anthropic.organization.rbac_group.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/rbac_groups/${n}`,{...s,__span:N(this._client,"anthropic.organization.rbac_groups.retrieve",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/rbac_groups/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.rbac_groups.update",i,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/rbac_groups",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.rbac_groups.list",s,{route:"/v1/organizations/rbac_groups",queryParams:["limit","page"]})})}delete(n,s){return this._client.delete(U`/v1/organizations/rbac_groups/${n}`,{...s,__span:N(this._client,"anthropic.organization.rbac_groups.delete",s,{route:"/v1/organizations/rbac_groups/{rbac_group_id}",attributes:{"anthropic.organization.rbac_group.id":n}})})}}return e.RBACGroupGrantsOwnerAccessError=pv,e.RBACGroupOwnerAccessUnconfirmedError=gv,e.Members=C5,e})();class A5 extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/rbac_roles/${r}/permissions`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.rbac_roles.permissions.list",s,{route:"/v1/organizations/rbac_roles/{rbac_role_id}/permissions",queryParams:["limit","page"],attributes:{"anthropic.organization.rbac_role.id":r}})})}}var j5=(()=>{class e extends ye{constructor(){super(...arguments),this.permissions=new A5(this._client)}retrieve(n,s){return this._client.get(U`/v1/organizations/rbac_roles/${n}`,{...s,__span:N(this._client,"anthropic.organization.rbac_roles.retrieve",s,{route:"/v1/organizations/rbac_roles/{rbac_role_id}",attributes:{"anthropic.organization.rbac_role.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/rbac_roles",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.rbac_roles.list",s,{route:"/v1/organizations/rbac_roles",queryParams:["limit","page"]})})}}return e.Permissions=A5,e})();let T5=class extends ye{list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/service_accounts/${r}/workspaces`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.service_accounts.workspaces.list",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces",queryParams:["limit","page"],attributes:{"anthropic.organization.service_account.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/service_accounts/${r}/workspaces`,{body:n,...s,__span:N(this._client,"anthropic.organization.service_accounts.workspaces.add",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces",attributes:{"anthropic.organization.service_account.id":r},createdIDAttribute:"anthropic.organization.service_account.workspace.id",createdIDField:"workspace_id"})})}remove(r,n,s){const{service_account_id:i}=n;return this._client.delete(U`/v1/organizations/service_accounts/${i}/workspaces/${r}`,{...s,__span:N(this._client,"anthropic.organization.service_accounts.workspaces.remove",s,{route:"/v1/organizations/service_accounts/{service_account_id}/workspaces/{workspace_id}",attributes:{"anthropic.organization.service_account.id":i,"anthropic.organization.service_account.workspace.id":r}})})}};var E5=(()=>{class e extends ye{constructor(){super(...arguments),this.workspaces=new T5(this._client)}create(n,s){return this._client.post("/v1/organizations/service_accounts",{body:n,...s,__span:N(this._client,"anthropic.organization.service_accounts.create",s,{route:"/v1/organizations/service_accounts",createdIDAttribute:"anthropic.organization.service_account.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/service_accounts/${n}`,{...s,__span:N(this._client,"anthropic.organization.service_accounts.retrieve",s,{route:"/v1/organizations/service_accounts/{service_account_id}",attributes:{"anthropic.organization.service_account.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/service_accounts/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.service_accounts.update",i,{route:"/v1/organizations/service_accounts/{service_account_id}",attributes:{"anthropic.organization.service_account.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/service_accounts",Me,{query:n,...s,__span:N(this._client,"anthropic.organization.service_accounts.list",s,{route:"/v1/organizations/service_accounts",queryParams:["include_archived","limit","page"]})})}archive(n,s){return this._client.post(U`/v1/organizations/service_accounts/${n}/archive`,{...s,__span:N(this._client,"anthropic.organization.service_accounts.archive",s,{route:"/v1/organizations/service_accounts/{service_account_id}/archive",attributes:{"anthropic.organization.service_account.id":n}})})}}return e.Workspaces=T5,e})();class M5 extends ye{list(r={},n){return this._client.getAPIList("/v1/organizations/spend_limits/effective",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.spend_limits.effective.list",n,{route:"/v1/organizations/spend_limits/effective",queryParams:["limit","page","period","user_ids"]})})}}class R5 extends ye{retrieve(r,n){return this._client.get(U`/v1/organizations/spend_limit_increase_requests/${r}`,{...n,__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.retrieve",n,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}list(r={},n){return this._client.getAPIList("/v1/organizations/spend_limit_increase_requests",Me,{query:r,...n,__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.list",n,{route:"/v1/organizations/spend_limit_increase_requests",queryParams:["actor_ids","limit","page","status"]})})}approve(r,n,s){return this._client.post(U`/v1/organizations/spend_limit_increase_requests/${r}/approve`,{body:n,...s,__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.approve",s,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}/approve",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}deny(r,n,s){return this._client.post(U`/v1/organizations/spend_limit_increase_requests/${r}/deny`,{body:n,...s,__span:N(this._client,"anthropic.organization.spend_limits.increase_requests.deny",s,{route:"/v1/organizations/spend_limit_increase_requests/{spend_limit_increase_request_id}/deny",attributes:{"anthropic.organization.spend_limit_increase_request.id":r}})})}}var z5=(()=>{class e extends ye{constructor(){super(...arguments),this.effective=new M5(this._client),this.increaseRequests=new R5(this._client)}}return e.Effective=M5,e.IncreaseRequests=R5,e})();class O5 extends ye{retrieve(r,n,s){const{workspace_id:i}=n;return this._client.get(U`/v1/organizations/workspaces/${i}/members/${r}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.members.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/members/${r}`,{body:c,...s,__span:N(this._client,"anthropic.organization.workspaces.members.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/members`,ns,{query:n,...s,__span:N(this._client,"anthropic.organization.workspaces.members.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/members",queryParams:["after_id","before_id","limit"],attributes:{"anthropic.organization.workspace.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/workspaces/${r}/members`,{body:n,...s,__span:N(this._client,"anthropic.organization.workspaces.members.add",s,{route:"/v1/organizations/workspaces/{workspace_id}/members",attributes:{"anthropic.organization.workspace.id":r},createdIDAttribute:"anthropic.organization.workspace.member.id",createdIDField:"user_id"})})}remove(r,n,s){const{workspace_id:i}=n;return this._client.delete(U`/v1/organizations/workspaces/${i}/members/${r}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.members.remove",s,{route:"/v1/organizations/workspaces/{workspace_id}/members/{user_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.member.id":r}})})}}class P5 extends ye{update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/rate_limits/${r}`,{body:c,...s,__span:N(this._client,"anthropic.organization.workspaces.rate_limits.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/rate_limits/{rate_limit_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.rate_limit.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/rate_limits`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.workspaces.rate_limits.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/rate_limits",queryParams:["group_type","include_inherited","limit","page"],attributes:{"anthropic.organization.workspace.id":r}})})}}class $5 extends ye{retrieve(r,n,s){const{workspace_id:i}=n;return this._client.get(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}update(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{body:c,...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.update",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}list(r,n={},s){return this._client.getAPIList(U`/v1/organizations/workspaces/${r}/service_accounts`,Me,{query:n,...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.list",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts",queryParams:["limit","page"],attributes:{"anthropic.organization.workspace.id":r}})})}add(r,n,s){return this._client.post(U`/v1/organizations/workspaces/${r}/service_accounts`,{body:n,...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.add",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts",attributes:{"anthropic.organization.workspace.id":r},createdIDAttribute:"anthropic.organization.workspace.service_account.id",createdIDField:"service_account_id"})})}remove(r,n,s){const{workspace_id:i}=n;return this._client.delete(U`/v1/organizations/workspaces/${i}/service_accounts/${r}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.service_accounts.remove",s,{route:"/v1/organizations/workspaces/{workspace_id}/service_accounts/{service_account_id}",attributes:{"anthropic.organization.workspace.id":i,"anthropic.organization.workspace.service_account.id":r}})})}}var bv=(()=>{class e extends Ye{}return e._errorName="KeyProfileMismatchError",e})(),xv=(()=>{class e extends Ye{}return e._errorName="WorkspaceMemberLimitExceededError",e})(),yv=(()=>{class e extends Ye{}return e._errorName="WorkspacePolicyViolationError",e})(),I5=(()=>{class e extends ye{constructor(){super(...arguments),this.rateLimits=new P5(this._client),this.members=new O5(this._client),this.serviceAccounts=new $5(this._client)}create(n,s){return this._client.post("/v1/organizations/workspaces",{body:n,...s,__span:N(this._client,"anthropic.organization.workspaces.create",s,{route:"/v1/organizations/workspaces",createdIDAttribute:"anthropic.organization.workspace.id"})})}retrieve(n,s){return this._client.get(U`/v1/organizations/workspaces/${n}`,{...s,__span:N(this._client,"anthropic.organization.workspaces.retrieve",s,{route:"/v1/organizations/workspaces/{workspace_id}",attributes:{"anthropic.organization.workspace.id":n}})})}update(n,s,i){return this._client.post(U`/v1/organizations/workspaces/${n}`,{body:s,...i,__span:N(this._client,"anthropic.organization.workspaces.update",i,{route:"/v1/organizations/workspaces/{workspace_id}",attributes:{"anthropic.organization.workspace.id":n}})})}list(n={},s){return this._client.getAPIList("/v1/organizations/workspaces",ns,{query:n,...s,__span:N(this._client,"anthropic.organization.workspaces.list",s,{route:"/v1/organizations/workspaces",queryParams:["after_id","before_id","ids","include_archived","include_default","limit"]})})}archive(n,s){return this._client.post(U`/v1/organizations/workspaces/${n}/archive`,{...s,__span:N(this._client,"anthropic.organization.workspaces.archive",s,{route:"/v1/organizations/workspaces/{workspace_id}/archive",attributes:{"anthropic.organization.workspace.id":n}})})}}return e.KeyProfileMismatchError=bv,e.WorkspaceMemberLimitExceededError=xv,e.WorkspacePolicyViolationError=yv,e.RateLimits=P5,e.Members=O5,e.ServiceAccounts=$5,e})(),_v=(()=>{class e extends Ye{}return e._errorName="OrgMemberLimitExceededError",e})(),vv=(()=>{class e extends Vr{}return e._errorName="ConcurrentMembershipChangeError",e})(),D5=(()=>{class e extends ye{constructor(){super(...arguments),this.apiKeys=new r5(this._client),this.externalKeys=new i5(this._client),this.federation=new k5(this._client),this.invites=new o5(this._client),this.serviceAccounts=new E5(this._client),this.users=new u5(this._client),this.workspaces=new I5(this._client),this.rateLimits=new c5(this._client),this.complianceSettings=new l5(this._client),this.analytics=new _5(this._client),this.spendLimits=new z5(this._client),this.rbacGroups=new N5(this._client),this.rbacRoles=new j5(this._client)}retrieve(n){return this._client.get("/v1/organizations/me",{...n,__span:N(this._client,"anthropic.organization.retrieve",n,{route:"/v1/organizations/me"})})}}return e.OrgMemberLimitExceededError=_v,e.ConcurrentMembershipChangeError=vv,e.APIKeys=r5,e.OrgAPIKeyLimitExceededError=av,e.WorkspaceAPIKeyLimitExceededError=rv,e.ExternalKeys=i5,e.ExternalKeyInWorkspacePolicyError=iv,e.ExternalKeyValidationFailedError=ov,e.ExternalKeyValidationTimedOutError=lv,e.ExternalKeyChangedError=cv,e.Federation=k5,e.Invites=o5,e.AlreadyMemberError=uv,e.CannotInviteEmailsWithUnverifiedDomainsError=dv,e.EmailDomainNotAllowedError=hv,e.InviteAlreadyExistsError=mv,e.ServiceAccounts=E5,e.Users=u5,e.CannotRemoveLastMemberError=fv,e.Workspaces=I5,e.KeyProfileMismatchError=bv,e.WorkspaceMemberLimitExceededError=xv,e.WorkspacePolicyViolationError=yv,e.RateLimits=c5,e.ComplianceSettings=l5,e.Analytics=_5,e.SpendLimits=z5,e.RBACGroups=N5,e.RBACGroupGrantsOwnerAccessError=pv,e.RBACGroupOwnerAccessUnconfirmedError=gv,e.RBACRoles=j5,e})();class q5 extends ye{create(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/skills/${r}/versions`,Kr({body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.versions.create",s,{route:"/v1/skills/{skill_id}/versions",attributes:{"anthropic.skill.id":r},createdIDAttribute:"anthropic.skill.version.id"})},this._client,!1))}retrieve(r,n,s){const{skill_id:i,workspace_id:c}=n;return this._client.get(U`/v1/skills/${i}/versions/${r}`,{...s,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.versions.retrieve",s,{route:"/v1/skills/{skill_id}/versions/{version}",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}list(r,n={},s){const{workspace_id:i,...c}=n??{};return this._client.getAPIList(U`/v1/skills/${r}/versions`,Me,{query:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.versions.list",s,{route:"/v1/skills/{skill_id}/versions",queryParams:["limit","page"],attributes:{"anthropic.skill.id":r}})})}delete(r,n,s){const{skill_id:i,workspace_id:c}=n;return this._client.delete(U`/v1/skills/${i}/versions/${r}`,{...s,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.versions.delete",s,{route:"/v1/skills/{skill_id}/versions/{version}",attributes:{"anthropic.skill.id":i,"anthropic.skill.version.id":r}})})}}var wv=(()=>{class e extends Vr{}return e._errorName="SkillReadBlockedUndecryptableError",e})(),L5=(()=>{class e extends ye{constructor(){super(...arguments),this.versions=new q5(this._client)}create(n,s){const{workspace_id:i,...c}=n;return this._client.post("/v1/skills",Kr({body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.create",s,{route:"/v1/skills",createdIDAttribute:"anthropic.skill.id"})},this._client,!1))}retrieve(n,s={},i){const{workspace_id:c}=s??{};return this._client.get(U`/v1/skills/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.skills.retrieve",i,{route:"/v1/skills/{skill_id}",attributes:{"anthropic.skill.id":n}})})}list(n={},s){const{workspace_id:i,...c}=n??{};return this._client.getAPIList("/v1/skills",Me,{query:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.skills.list",s,{route:"/v1/skills",queryParams:["limit","page","source"]})})}delete(n,s={},i){const{workspace_id:c}=s??{};return this._client.delete(U`/v1/skills/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.skills.delete",i,{route:"/v1/skills/{skill_id}",attributes:{"anthropic.skill.id":n}})})}}return e.SkillReadBlockedUndecryptableError=wv,e.Versions=q5,e})();class U5 extends ye{create(r,n,s){const{workspace_id:i,...c}=n;return this._client.post(U`/v1/user_profiles/${r}/action_urls`,{body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.user_profiles.action_urls.create",s,{route:"/v1/user_profiles/{user_profile_id}/action_urls",attributes:{"anthropic.user_profile.id":r}})})}}var Sv=(()=>{class e extends Ye{}return e._errorName="UserProfileNotFoundError",e})(),B5=(()=>{class e extends ye{constructor(){super(...arguments),this.actionURLs=new U5(this._client)}create(n,s){const{workspace_id:i,...c}=n;return this._client.post("/v1/user_profiles",{body:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.user_profiles.create",s,{route:"/v1/user_profiles",createdIDAttribute:"anthropic.user_profile.id"})})}retrieve(n,s={},i){const{workspace_id:c}=s??{};return this._client.get(U`/v1/user_profiles/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.user_profiles.retrieve",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}update(n,s,i){const{workspace_id:c,...d}=s;return this._client.post(U`/v1/user_profiles/${n}`,{body:d,...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.user_profiles.update",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}list(n={},s){const{workspace_id:i,...c}=n??{};return this._client.getAPIList("/v1/user_profiles",Me,{query:c,...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.user_profiles.list",s,{route:"/v1/user_profiles",queryParams:["enforcement_status","limit","order","order_by","page"]})})}delete(n,s={},i){const{workspace_id:c}=s??{};return this._client.delete(U`/v1/user_profiles/${n}`,{...i,headers:L([{...c!=null?{"anthropic-workspace-id":c}:void 0},i?.headers]),__span:N(this._client,"anthropic.user_profiles.delete",i,{route:"/v1/user_profiles/{user_profile_id}",attributes:{"anthropic.user_profile.id":n}})})}}return e.UserProfileNotFoundError=Sv,e.ActionURLs=U5,e})();const R$=new Map([["400 already_member",uv],["400 available_tools_limit_exceeded",U_],["400 cannot_invite_emails_with_unverified_domains",dv],["400 cannot_remove_last_member",fv],["400 cannot_sign_out_primary_owner",y_],["400 cannot_sign_out_self",__],["400 claude_code_key_creator_not_member",hT],["400 claude_code_version_too_old",mT],["400 cmek_key_disabled",fT],["400 cmek_key_network_blocked",pT],["400 compaction_block_ambiguous",B_],["400 compaction_block_misplaced",G_],["400 compaction_content_mismatch",H_],["400 compaction_incomplete_turn",F_],["400 compaction_nothing_to_summarize",V_],["400 compaction_signature_invalid",K_],["400 compaction_too_many_tool_references",Y_],["400 compaction_tool_changes_mismatch",W_],["400 email_domain_not_allowed",hv],["400 environment_archived",u_],["400 external_key_in_workspace_policy",iv],["400 external_key_validation_failed",ov],["400 external_key_validation_timed_out",lv],["400 file_not_downloadable",r_],["400 invalid_config_type_change",d_],["400 invalid_metadata",h_],["400 invite_already_exists",mv],["400 key_profile_mismatch",bv],["400 org_api_key_limit_exceeded",av],["400 org_member_limit_exceeded",_v],["400 organization_not_enrolled_in_beta",q_],["400 organization_on_hold",gT],["400 organization_type_not_supported",bT],["400 rbac_group_grants_owner_access",pv],["400 rbac_group_owner_access_unconfirmed",gv],["400 request_body_encoding_invalid",xT],["400 request_body_encoding_unsupported",yT],["400 scan_failed",C_],["400 slack_channel_set_up_settings_refused",E_],["400 storage_quota_exceeded",i_],["400 thread_already_continued",X_],["400 thread_continue_in_flight",Q_],["400 thread_fingerprint_mismatch",J_],["400 thread_unsupported_request",Z_],["400 tool_name_conflict",ev],["400 tool_reference_unresolved",tv],["400 unsupported_charset",L_],["400 user_profile_not_found",Sv],["400 workspace_api_key_limit_exceeded",rv],["400 workspace_member_limit_exceeded",xv],["400 workspace_policy_violation",yv],["403 api_key_scope_missing",M_],["403 cannot_sign_out_managed_member",v_],["403 cannot_sign_out_membership_admin",w_],["403 cannot_sign_out_owner",S_],["403 cannot_sign_out_privileged_member",k_],["403 claude_tag_writes_not_enabled",R_],["403 compliance_configuration_restricted",z_],["403 environment_create_disabled",m_],["403 environment_update_disabled",f_],["403 organization_level_scoped_api_key_required",O_],["403 sandbox_egress_restricted",_T],["403 spend_limits_admin_api_writes_not_enabled",I_],["404 environment_not_found",p_],["404 file_expired",o_],["404 slack_channel_set_up_environment_not_found",P_],["404 thread_not_found",nv],["409 concurrent_membership_change",vv],["409 external_key_changed",cv],["409 plugin_name_taken",N_],["409 scan_pending",A_],["409 skill_name_taken",j_],["409 skill_read_blocked_undecryptable",wv],["409 slack_channel_set_up_settings_conflict",$_],["412 heartbeat_precondition_failed",c_],["413 request_body_too_large_after_decoding",vT],["429 enforced_spend_limit_reached",wT],["429 ramp_limit_exceeded",ST],["503 cmek_context_unavailable",kT],["503 cmek_key_unreachable",CT],["503 registration_pending",T_],["529 compaction_unavailable",sv]]),z$="urn:ietf:params:oauth:grant-type:jwt-bearer",O$="refresh_token",JT="/v1/oauth/token",Cp="oauth-2025-04-20",P$="oidc-federation-2026-04-01",$$=120,kv=30,I$=5,G5=1<<20;function ZT(e){if(!e)return;let r;try{r=new URL(e)}catch(s){throw new Bt(`Invalid token endpoint base URL "${e}": ${s}`)}if(r.protocol==="https:")return;const n=r.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(r.protocol==="http:"&&(n==="localhost"||n==="127.0.0.1"||n==="::1")))throw new Bt(`Refusing to send credential over non-https token endpoint "${e}"`)}async function e3(e,r){const n=await q$(e);let s;try{s=JSON.parse(n)}catch{throw new Bt(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,ra(n),r)}if(!s.access_token)throw new Bt(`Token endpoint response missing access_token: ${JSON.stringify(ra(s))}`,e.status,ra(s),r);if(s.token_type&&s.token_type.toLowerCase()!=="bearer")throw new Bt(`Token endpoint response: unsupported token_type "${s.token_type}" (want Bearer)`,e.status,ra(s),r);return s}const px=2e3,D$=new Set(["error","error_description","error_uri"]);function ra(e){if(e==null)return e;if(typeof e=="string"){let r;try{r=JSON.parse(e)}catch{return e.length<=px?e:e.slice(0,px)+`... <${e.length-px} more chars>`}return JSON.stringify(ra(r))}if(typeof e=="object"&&!Array.isArray(e)){const r={};for(const[n,s]of Object.entries(e))D$.has(n)&&(r[n]=s);return r}return null}async function t3(e,r=n=>console.warn(`anthropic-sdk: ${n}`)){if(typeof process>"u"||process.platform==="win32")return;const{fs:n}=await Aa(async()=>{const{fs:d}=await import("./node.browser-DTsgp0ny.js");return{fs:d}},[]);let s=e,i;try{s=await n.promises.realpath(e),i=await n.promises.stat(s)}catch{return}const c=i.mode&511;if(c&18)throw new Bt(`Credentials file at ${s} is group/world-writable (mode 0o${c.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${s}\`.`);if(c&36)throw new Bt(`Credentials file at ${s} is group/world-readable (mode 0o${c.toString(8)}); run \`chmod 600 ${s}\` before retrying.`);typeof process.getuid=="function"&&i.uid!==process.getuid()&&r(`credentials file at ${s} is owned by uid ${i.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function n3(e,r){const{fs:n,path:s}=await Aa(async()=>{const{fs:d,path:f}=await import("./node.browser-DTsgp0ny.js");return{fs:d,path:f}},[]),i=s.dirname(e);await n.promises.mkdir(i,{recursive:!0,mode:448});const c=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const d=await n.promises.open(c,"w",384);try{await d.writeFile(JSON.stringify(r,null,2)),await d.sync()}finally{await d.close()}await n.promises.rename(c,e)}catch(d){throw await n.promises.unlink(c).catch(()=>{}),d}try{const d=await n.promises.open(i,"r");try{await d.sync()}finally{await d.close()}}catch{}}async function q$(e){if(!e.body)return"";const r=e.body.getReader(),n=[];let s=0;for(;;){const{done:c,value:d}=await r.read();if(c)break;if(s+d.length>G5){const f=G5-s;f>0&&n.push(d.subarray(0,f)),await r.cancel();break}n.push(d),s+=d.length}let i;if(n.length===1)i=n[0];else{i=new Uint8Array(n.reduce((d,f)=>d+f.length,0));let c=0;for(const d of n)i.set(d,c),c+=d.length}return new TextDecoder("utf-8").decode(i)}var Bt=(()=>{class e extends De{constructor(n,s=null,i=null,c=null){super(n),this.statusCode=s,this.body=i,this.requestId=c}}return e._errorName="WorkloadIdentityError",e})();function Wo(){return Math.floor(Date.now()/1e3)}class L${constructor(r,n){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=r,this.onAdvisoryRefreshError=n}async getToken(){const r=this.nextForce;this.nextForce=!1;const n=this.cached;if(r||n==null)return(await this.refresh(r)).token;if(n.expiresAt==null)return n.token;const s=n.expiresAt-Wo();return s>$$?n.token:s>kv?(this.backgroundRefresh(),n.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(r=!1){return this.pendingRefresh&&!r?this.pendingRefresh:this.doRefresh(r)}backgroundRefresh(){this.pendingRefresh||Wo()-this.lastAdvisoryError<I$||this.doRefresh().catch(r=>{this.lastAdvisoryError=Wo(),this.onAdvisoryRefreshError?.(r)})}doRefresh(r=!1){return this.pendingRefresh=this.provider(r?{forceRefresh:!0}:void 0).then(n=>(this.cached=n,this.pendingRefresh=null,n),n=>{throw this.pendingRefresh=null,n}),this.pendingRefresh}}const s3="1.0",U$=/^[A-Za-z0-9_.-]+$/;function a3(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!U$.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}const B$=async e=>{var r,n;const s=await Cv();if(s===null)return null;const i=e==null&&ot("ANTHROPIC_PROFILE")!=null;let c=null;if(e==null&&!i){const y=ot("ANTHROPIC_ORGANIZATION_ID"),S=ot("ANTHROPIC_IDENTITY_TOKEN_FILE"),k=ot("ANTHROPIC_FEDERATION_RULE_ID");if(k&&y&&(c={fromFile:!1,config:{organization_id:y,workspace_id:ot("ANTHROPIC_WORKSPACE_ID"),base_url:ot("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:k,service_account_id:ot("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:S?{source:"file",path:S}:void 0,scope:ot("ANTHROPIC_SCOPE")}}},S||ot("ANTHROPIC_IDENTITY_TOKEN")))return c}const d=e??await r3();if(d===null)return null;a3(d);const{fs:f,path:p}=await Aa(async()=>{const{fs:y,path:S}=await import("./node.browser-DTsgp0ny.js");return{fs:y,path:S}},[]),b=p.join(s,"configs",`${d}.json`);let x;try{x=await f.promises.readFile(b,"utf-8")}catch(y){if(y?.code!=="ENOENT")throw new Error(`failed to read config file ${b}: ${y}`);if(i)throw new De(`ANTHROPIC_PROFILE names the profile "${d}", but ${b} does not exist. Set ANTHROPIC_PROFILE to a profile that exists, or unset it.`,{cause:y});return c}let g;try{g=JSON.parse(x)}catch(y){throw new Error(`failed to parse config file ${b}: ${y}`)}if(!g.authentication)throw new Error(`config file ${b} is missing "authentication"`);const _=g.authentication.type;if(_!=="oidc_federation"&&_!=="user_oauth")throw new Error(`authentication.type "${_}" is not a known authentication type`);if(g.organization_id??(g.organization_id=ot("ANTHROPIC_ORGANIZATION_ID")),g.workspace_id??(g.workspace_id=ot("ANTHROPIC_WORKSPACE_ID")),g.base_url??(g.base_url=ot("ANTHROPIC_BASE_URL")),(r=g.authentication).scope??(r.scope=ot("ANTHROPIC_SCOPE")),g.authentication.type==="oidc_federation"){if(!g.authentication.identity_token){const y=ot("ANTHROPIC_IDENTITY_TOKEN_FILE");y&&(g.authentication.identity_token={source:"file",path:y})}g.authentication.federation_rule_id||(g.authentication.federation_rule_id=ot("ANTHROPIC_FEDERATION_RULE_ID")??""),(n=g.authentication).service_account_id??(n.service_account_id=ot("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:g,fromFile:!0}},G$=async(e,r)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const n=await Cv();if(!n)return null;const s=r??await r3();if(!s)return null;a3(s);const{path:i}=await Aa(async()=>{const{path:c}=await import("./node.browser-DTsgp0ny.js");return{path:c}},[]);return i.join(n,"credentials",`${s}.json`)},Cv=async()=>{if(!H$())return null;const{path:e}=await Aa(async()=>{const{path:c}=await import("./node.browser-DTsgp0ny.js");return{path:c}},[]),r=ot("ANTHROPIC_CONFIG_DIR");if(r)return r;if(Uy()["X-Stainless-OS"]==="Windows"){const c=ot("APPDATA");if(c)return e.join(c,"Anthropic");const d=ot("USERPROFILE");return d?e.join(d,"AppData","Roaming","Anthropic"):null}const s=ot("XDG_CONFIG_HOME");if(s)return e.join(s,"anthropic");const i=ot("HOME");return i?e.join(i,".config","anthropic"):null},H$=()=>{const e=Uy()["X-Stainless-Runtime"];return e==="node"||e==="deno"},r3=async()=>{const e=await Cv();if(!e)return null;const r=ot("ANTHROPIC_PROFILE");if(r)return r;const{fs:n,path:s}=await Aa(async()=>{const{fs:c,path:d}=await import("./node.browser-DTsgp0ny.js");return{fs:c,path:d}},[]),i=s.join(e,"active_config");try{return(await n.promises.readFile(i,"utf-8")).trim()||"default"}catch(c){if(c?.code!=="ENOENT")throw new Error(`failed to read ${i}: ${c}`);return"default"}};function H5(e){if(!e)throw new De("Identity token file path is empty");return async()=>{const{fs:r}=await Aa(async()=>{const{fs:i}=await import("./node.browser-DTsgp0ny.js");return{fs:i}},[]);let n;try{n=await r.promises.readFile(e,"utf-8")}catch(i){throw new De(`Failed to read identity token file at ${e}: ${i}`)}const s=n.trim();if(!s)throw new De(`Identity token file at ${e} is empty`);return s}}function F$(e){if(!e)throw new De("Identity token value is empty");return()=>e}function V$(e){return async()=>{ZT(e.baseURL);const r=await e.identityTokenProvider();if(r.length>16*1024)throw new Bt(`Identity token is ${Math.ceil(r.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const n={grant_type:z$,assertion:r,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(n.service_account_id=e.serviceAccountId),e.workspaceId&&(n.workspace_id=e.workspaceId);const s=`${e.baseURL}${JT}`;let i;try{i=await e.fetch(s,{method:"POST",redirect:"manual",headers:{"Content-Type":"application/json","anthropic-beta":`${Cp},${P$}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Pr} oidcFederationProvider`},body:JSON.stringify(n)})}catch(p){throw new Bt(`Failed to reach token endpoint ${s}: ${p}`)}const c=i.headers.get("Request-Id");if(!i.ok){const p=await i.text().catch(()=>""),b=ra(p);let x="";throw i.status===401&&(x=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new Bt(`Token exchange failed with status ${i.status}${c?` (request-id ${c})`:""}: ${b}${x}`,i.status,b,c)}const d=await e3(i,c),f=Number(d.expires_in);if(!Number.isFinite(f))throw new Bt(`Token endpoint response missing required fields: ${JSON.stringify(ra(d))}`,i.status,ra(d),c);return{token:d.access_token,expiresAt:Wo()+f}}}function K$(e){return async r=>{const{fs:n}=await Aa(async()=>{const{fs:E}=await import("./node.browser-DTsgp0ny.js");return{fs:E}},[]);await t3(e.credentialsPath,e.onSafetyWarning);let s;try{s=await n.promises.readFile(e.credentialsPath,"utf-8")}catch(E){throw new Bt(`Credentials file not found at ${e.credentialsPath}: ${E}`)}let i;try{i=JSON.parse(s)}catch(E){throw new Bt(`Credentials file at ${e.credentialsPath} is not valid JSON: ${E}`)}const c=i.access_token;if(!c)throw new Bt(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const d=i.expires_at;if(!r?.forceRefresh&&(d==null||Wo()<d-kv))return{token:c,expiresAt:d??null};const f=i.refresh_token;if(!e.clientId||!f)throw new Bt(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${f?"set":"empty"})`);ZT(e.baseURL);const p={grant_type:O$,refresh_token:f,client_id:e.clientId},b=`${e.baseURL}${JT}`;let x;try{x=await e.fetch(b,{method:"POST",redirect:"manual",headers:{"Content-Type":"application/json","anthropic-beta":Cp,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Pr} userOAuthProvider`},body:JSON.stringify(p)})}catch(E){throw new Bt(`User OAuth refresh failed to reach token endpoint: ${E}`)}const g=x.headers.get("Request-Id");if(!x.ok){const E=await x.text().catch(()=>"");throw new Bt(`User OAuth refresh failed (HTTP ${x.status}): ${ra(E)}`,x.status,ra(E),g)}const _=await e3(x,g),y=Number(_.expires_in);if(!Number.isFinite(y))throw new Bt(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(ra(_))}`,x.status,ra(_),g);const S=Wo()+y,k=_.refresh_token||f;return await n3(e.credentialsPath,{...i,version:s3,type:"oauth_token",access_token:_.access_token,expires_at:S,refresh_token:k}),{token:_.access_token,expiresAt:S}}}function i3(e,r){const n=e.authentication.credentials_path??null,s=(e.base_url||r.baseURL).replace(/\/+$/,""),i=W$(e,n,s,r),c={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(c["anthropic-workspace-id"]=e.workspace_id),{provider:i,extraHeaders:c,baseURL:e.base_url||void 0}}async function Y$(e,r){const n=await B$(r);if(!n)return null;const{config:s,fromFile:i}=n,c=s.authentication.credentials_path||!i?s:{...s,authentication:{...s.authentication,credentials_path:await G$(s,r)??void 0}};return i3(c,e)}function W$(e,r,n,s){switch(e.authentication.type){case"oidc_federation":{const i=e.authentication,c=X$(i);if(!c)throw new Bt("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!i.federation_rule_id)throw new Bt("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new Bt("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const d=V$({identityTokenProvider:c,federationRuleId:i.federation_rule_id,organizationId:e.organization_id,serviceAccountId:i.service_account_id,workspaceId:e.workspace_id,baseURL:n,fetch:s.fetch,userAgent:s.userAgent});return r?Q$(d,r,s.onCacheWriteError,s.onSafetyWarning):d}case"user_oauth":{if(!r)throw new Bt("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return K$({credentialsPath:r,clientId:e.authentication.client_id,baseURL:n,fetch:s.fetch,userAgent:s.userAgent,onSafetyWarning:s.onSafetyWarning})}default:{const i=e.authentication.type;throw new Bt(`authentication.type "${i}" is not a known authentication type`)}}}function X$(e){if(e.identity_token){const s=e.identity_token.source;if(s!=="file")throw new Bt(`identity_token.source "${s}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Bt('identity_token.source "file" requires a non-empty path');return H5(e.identity_token.path)}const r=ot("ANTHROPIC_IDENTITY_TOKEN_FILE");if(r)return H5(r);const n=ot("ANTHROPIC_IDENTITY_TOKEN");return n?F$(n):null}function Q$(e,r,n,s){return async i=>{const{fs:c}=await Aa(async()=>{const{fs:p}=await import("./node.browser-DTsgp0ny.js");return{fs:p}},[]);await t3(r,s);let d;try{const p=await c.promises.readFile(r,"utf-8");d=JSON.parse(p);const b=d?.access_token;if(b&&!i?.forceRefresh){const x=d?.expires_at;if(x==null||Wo()<x-kv)return{token:b,expiresAt:x??null}}}catch(p){p?.code!=="ENOENT"&&!(p instanceof SyntaxError)&&n?.(p)}const f=await e(i);try{await n3(r,{...d??{},version:s3,type:"oauth_token",access_token:f.token,expires_at:f.expiresAt})}catch(p){n?.(p)}return f}}const o3=new WeakSet;function l3(e){return typeof e=="object"&&e!==null&&o3.has(e)}function J$(e){const r=new Set;for(;typeof e=="object"&&e!==null&&!r.has(e);){if(r.add(e),l3(e)||Jo(e)||e instanceof Hc||e instanceof Iz)return!0;e=e.cause}return!1}function F5(e,r,n,s){return async(i,c={})=>{if(r.length===0)return e.call(void 0,i,c);const d=c.headers instanceof Headers?c.headers:new Headers(c.headers),f=await eI(e,r,n,s)({...c,headers:d,url:typeof i=="string"?i:i instanceof URL?i.href:i.url});if(f.bodyUsed||f.body?.locked)throw new De("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return f}}function Z$(e,r){const n=new WeakMap;return{options:e,logger:r?it(r):Pj(),parse(s){if(e?.stream&&s.ok)return V5(s,e,r);let i=n.get(s);return i||(i=V5(s,e,r),n.set(s,i)),i}}}async function V5(e,r,n){if(e.bodyUsed||e.body?.locked)throw new De("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(r?.stream&&e.ok)return Hr.fromSSEResponse(e.clone(),new AbortController,n);if(e.status===204)return null;if(r?.__binaryResponse)return e;const i=e.headers.get("content-type")?.split(";")[0]?.trim();return i?.includes("application/json")||i?.endsWith("+json")?e.headers.get("content-length")==="0"?void 0:Xp(await e.clone().json(),e):await e.clone().text()}function eI(e,r,n,s){let i=async({url:d,...f})=>{try{return await e.call(void 0,d,f)}catch(p){const b=Yd(p);throw o3.add(b),b}};const c=Z$(n,s);for(let d=r.length-1;d>=0;d--){const f=r[d],p=i;i=async b=>f(b,p,c)}return i}const c3=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",tI=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&c3(e),nI=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function sI(e,r,n){if(Yj(),e=await e,r||(r=e instanceof File?e.name:rp(e,!0)),tI(e))return e instanceof File&&r==null&&n==null?e:Pc([await e.arrayBuffer()],r??e.name,{type:e.type,lastModified:e.lastModified,...n});if(nI(e)){const i=await e.blob();return r||(r=new URL(e.url).pathname.split(/[\\/]/).pop()),Pc(await ty(i),r,n)}const s=await ty(e);if(!n?.type){const i=s.find(c=>typeof c=="object"&&"type"in c&&c.type);typeof i=="string"&&(n={...n,type:i})}return Pc(s,r,n)}async function ty(e){let r=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)r.push(e);else if(c3(e))r.push(e instanceof Blob?e:await e.arrayBuffer());else if(Zy(e))for await(const n of e)r.push(...await ty(n));else{const n=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${n?`; constructor: ${n}`:""}${aI(e)}`)}return r}function aI(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class K5 extends ye{retrieve(r,n={},s){const{workspace_id:i}=n??{};return this._client.get(U`/v1/models/${r}`,{...s,headers:L([{...i!=null?{"anthropic-workspace-id":i}:void 0},s?.headers]),__span:N(this._client,"anthropic.models.retrieve",s,{route:"/v1/models/{model_id}",attributes:{"anthropic.model.id":r}})})}list(r={},n){const{workspace_id:s,...i}=r??{};return this._client.getAPIList("/v1/models",ns,{query:i,...n,headers:L([{...s!=null?{"anthropic-workspace-id":s}:void 0},n?.headers]),__span:N(this._client,"anthropic.models.list",n,{route:"/v1/models",queryParams:["after_id","before_id","lifecycle","limit"]})})}}var gx,bx,Ff,Sc,Uo,Y5;let W5=!1;var rI=(()=>{class e{get credentials(){return this._authState.provider}get openTelemetry(){return v(this,Uo,"f")}_instrumentationScope(){return{version:Pr}}constructor({baseURL:n=ot("ANTHROPIC_BASE_URL"),apiKey:s,authToken:i,webhookKey:c=ot("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...d}={}){gx.add(this),this._requestAuthFlags=new WeakMap,Ff.set(this,void 0),Sc.set(this,void 0),Uo.set(this,void 0),this._genAIProviderName="anthropic",this._supportsMessageThreads=!1;const f={apiKey:s,authToken:i,...d},p=ic.filter(E=>f[E]!=null);if(p.length>1){const E=T=>T.map(j=>`\`${j}\``).join(", ");throw new TypeError(`Pass at most one of ${E(ic)}. Received ${E(p)}.`)}const[b]=p,x=b!=null?null:{apiKey:s===void 0?ot("ANTHROPIC_API_KEY"):void 0,authToken:i===void 0?ot("ANTHROPIC_AUTH_TOKEN"):void 0},g=b!=null?{type:b,value:f[b]}:x?.apiKey!=null?{type:"apiKey",value:x.apiKey}:x?.authToken!=null?{type:"authToken",value:x.authToken}:{type:"defaultChain"},_={apiKey:g.type==="apiKey"?g.value:null,authToken:g.type==="authToken"?g.value:null,webhookKey:c,...d,baseURL:n||"https://api.anthropic.com"};if(!_.dangerouslyAllowBrowser&&Bz())throw new De(`It looks like you're running in a browser-like environment.
528
528
 
529
529
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
530
530
  If you understand the risks and have appropriate mitigations in place,
@@ -679,7 +679,7 @@ Outlier residues: ${y.map(S=>`${S.resName3}${S.seqId} (φ=${S.phiDeg?.toFixed(1)
679
679
 
680
680
  _${Cn}_`,citations:r.comparison?[`resultId:${r.comparison.resultId}`]:[],actionTaken:"Inspected deterministic workspace telemetry",timestampUtc:i}}}if(s.includes("mcp"))return{actions:[{type:"switch_tab",tab:"mcp"}],reply:{id:c(),role:"assistant",command:"open_mcp_server",text:`Opened the In-App MCP Server panel. Studio exposes 11 JSON-RPC 2.0 tools, 8 live workspace resources, and 4 prompts for both the internal AI Assistant and external clients (Claude Desktop, Claude Code, OpenAI Codex CLI, Cursor). ${Cn}`,actionTaken:"Opened MCP Server workbench",timestampUtc:i}};if(s==="explain_result"||s.includes("explain")||s.includes("summary")||s.includes("metric")){if(!r.comparison)return{actions:[],reply:{id:c(),role:"assistant",command:"explain_result",text:"No active structural comparison result yet. Run `compare_structures` first.",timestampUtc:i}};const x=r.comparison,g=x.matchedResidues.reduce((y,S)=>S.distanceAngstrom>y.distanceAngstrom?S:y,x.matchedResidues[0]),_=x.refContacts?.length??0;return{actions:[],reply:{id:c(),role:"assistant",command:"explain_result",text:[`Verified Comparison Summary (${Cn}):`,`• Cα RMSD: ${x.metrics.rmsdAngstrom.toFixed(4)} Å across ${x.metrics.matchedCaCount} matched Cα residues (${x.engine.target}, ${x.engine.floatPrecision}).`,`• Reference Coverage: ${x.metrics.refCoverage.numerator}/${x.metrics.refCoverage.denominator} (${(x.metrics.refCoverage.ratio*100).toFixed(1)}%, ${x.metrics.refCoverage.denominatorKind}).`,`• Mobile Coverage: ${x.metrics.mobCoverage.numerator}/${x.metrics.mobCoverage.denominator} (${(x.metrics.mobCoverage.ratio*100).toFixed(1)}%, ${x.metrics.mobCoverage.denominatorKind}).`,`• Peak Residue Δd: ${g?`${g.resName3}${g.refSeqId} (${g.distanceAngstrom.toFixed(3)} Å)`:"n/a"} · PAE status: ${x.metrics.paeStatus}.`,`• Active-site ligand/metal contacts (≤4.5 Å): ${_} atom contacts recorded.`,`• Confidence Separation: Reference uses ${x.reference.confidenceKind} (Ų); Mobile uses ${x.mobile.confidenceKind}.`].join(`
681
681
  `),citations:[`resultId:${x.resultId}`,`ref:sha256:${x.reference.sha256}`,`mob:sha256:${x.mobile.sha256}`],actionTaken:"explain_result()",timestampUtc:i}}}return{actions:[],reply:{id:c(),role:"assistant",text:["Available deterministic commands (RUO):","• `list_artifacts` — Show loaded structures, SHA-256 digests, and confidence types","• `focus_residues 94, 96, 119` — Highlight residue(s) across 3D, Sequence, and PAE","• `compare_structures` — Re-run float64 Kabsch alignment in Wasm worker","• `explain_result` — Summarize verified RMSD, coverage, contacts, and provenance","• `which residues deviate most` — Inspect top Cα deviations and active-site contacts","• `ramachandran outliers` — Check backbone φ/ψ geometry & outliers","• `mutate H94A` — Apply point mutation in Peptide Engineering tab","• `crispr codon 94` — Jump to coding codon & scan Cas9/Cas12a PAMs","• `smiles CC(=O)Nc1nnc(S(N)(=O)=O)s1` — Depict & analyze SMILES ligand","• `mcp` — Open the In-App MCP Server & external client setup","• `request_report html` or `request_report json` — Export RUO report"].join(`
682
- `),timestampUtc:i}}}const h3="state.vscdb",cI=1,Us="ItemTable",Mc="VaultKeyStore",X5="synlexa.studio.master.aes256gcm",ny="secret://synlexa.studio.vault/",sy="secret://synlexa.studio.vault/custom/",m3={gemini:"synlexa.studio.gemini.apiKey",anthropic:"synlexa.studio.anthropic.apiKey",openai:"synlexa.studio.openai.apiKey"},Np=["anthropic","gemini","openai"],Gi=new Map,Dc=new Map,Ap=new Map,ay=new Set;let wa={initialized:!1,backend:"memory-fallback",dbName:h3,tableName:Us,dbPath:"IndexedDB://state.vscdb/ItemTable",encrypted:!0,cipher:"AES-256-GCM",storedProviders:[],entries:{},migratedLegacyCount:0},Vf=null,Kf=null;function Nv(){for(const e of ay)e()}function f3(e){return ay.add(e),()=>ay.delete(e)}function Zo(){return{...wa,storedProviders:Np.filter(e=>Gi.has(e)&&!!Gi.get(e)),entries:Object.fromEntries(Dc.entries())}}function xx(e){return Gi.get(e)??""}function uI(e){return Ap.get(e)??""}async function p3(e,r){const n=e.trim().replace(/[^a-zA-Z0-9._:-]/g,"_");if(!n)return;const s=r.trim(),i=new Date().toISOString();s?Ap.set(n,s):Ap.delete(n);const c=await Av();if(c){const d=await jv(c),f=`${sy}${n}`;if(s){const p=await g3(s,d),b=await jp(s),x={key:f,value:{v:1,alg:p.alg,iv:p.iv,ct:p.ct,fingerprint:b,updatedAtUtc:i}},g=c.transaction(Us,"readwrite");await el(g.objectStore(Us).put(x))}else{const p=c.transaction(Us,"readwrite");await el(p.objectStore(Us).delete(f))}}Nv()}function Yf(e){let r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);return btoa(r)}function Q5(e){const r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}function Av(){return Kf||(Kf=new Promise(e=>{if(typeof indexedDB>"u")return e(null);try{const r=indexedDB.open(h3,cI);r.onupgradeneeded=()=>{const n=r.result;n.objectStoreNames.contains(Us)||n.createObjectStore(Us,{keyPath:"key"}),n.objectStoreNames.contains(Mc)||n.createObjectStore(Mc,{keyPath:"id"})},r.onsuccess=()=>e(r.result),r.onerror=()=>e(null)}catch{e(null)}}),Kf)}function el(e){return new Promise((r,n)=>{e.onsuccess=()=>r(e.result),e.onerror=()=>n(e.error)})}async function jv(e){const r=globalThis.crypto?.subtle;if(!r)return null;try{const n=e.transaction(Mc,"readonly"),s=await el(n.objectStore(Mc).get(X5))??null;if(s?.key)return s.key;const i=await r.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),c=e.transaction(Mc,"readwrite");return await el(c.objectStore(Mc).put({id:X5,key:i})),i}catch{return null}}async function g3(e,r){const n=new TextEncoder().encode(e);if(r&&globalThis.crypto?.subtle&&globalThis.crypto?.getRandomValues){const c=globalThis.crypto.getRandomValues(new Uint8Array(12)),d=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:c},r,n);return{alg:"AES-GCM-256",iv:Yf(c),ct:Yf(new Uint8Array(d))}}const s=new Uint8Array(12);globalThis.crypto?.getRandomValues?.(s);const i=new Uint8Array(n.length);for(let c=0;c<n.length;c++)i[c]=n[c]^s[c%s.length]^90;return{alg:"LOCAL-OBF-V1",iv:Yf(s),ct:Yf(i)}}async function J5(e,r){try{const n=Q5(e.iv),s=Q5(e.ct);if(e.alg==="AES-GCM-256"){if(!r||!globalThis.crypto?.subtle)return null;const c=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:n},r,s);return new TextDecoder().decode(c)}const i=new Uint8Array(s.length);for(let c=0;c<s.length;c++)i[c]=s[c]^n[c%n.length]^90;return new TextDecoder().decode(i)}catch{return null}}async function jp(e){return(await Jc(`synlexa-vault-fp:${e}`)).slice(0,12)}function b3(){if(typeof window>"u")return!1;const e=window.location?.hostname??"";return e==="127.0.0.1"||e==="localhost"}async function dI(){if(!b3()||typeof fetch!="function")return{available:!1};try{const e=await fetch("/api/local-vault/keys",{method:"GET"});if(!e.ok)return{available:!1};if(!(e.headers.get("content-type")??"").includes("application/json"))return{available:!1};const n=await e.json();return n?.ok?{available:!0,dbPath:n.dbPath,keys:n.keys??{}}:{available:!1}}catch{return{available:!1}}}async function hI(e,r){if(!b3()||typeof fetch!="function")return null;try{const n=await fetch("/api/local-vault/keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,apiKey:r})});if(!n.ok)return null;const s=await n.json();return s?.ok?s.dbPath??"~/.synlexa-studio/state.vscdb":null}catch{return null}}function mI(){const e=[];try{if(typeof localStorage>"u")return e;for(const r of Np){const n=m3[r],s=localStorage.getItem(n)?.trim();s&&(e.push({provider:r,key:s}),localStorage.removeItem(n))}}catch{}return e}async function cp(e,r){const n=r.trim(),s=new Date().toISOString();try{typeof localStorage<"u"&&localStorage.removeItem(m3[e])}catch{}if(!n)Gi.delete(e),Dc.delete(e);else{Gi.set(e,n);const f=await jp(n);Dc.set(e,{provider:e,fingerprint:f,updatedAtUtc:s,cipher:wa.cipher})}const i=await Av();if(i){const f=await jv(i),p=`${ny}${e}`;if(n){const b=await g3(n,f),x=Dc.get(e)?.fingerprint??await jp(n),g={key:p,value:{v:1,alg:b.alg,iv:b.iv,ct:b.ct,fingerprint:x,updatedAtUtc:s}},_=i.transaction(Us,"readwrite");await el(_.objectStore(Us).put(g))}else{const b=i.transaction(Us,"readwrite");await el(b.objectStore(Us).delete(p))}}const c=await hI(e,n);return c?wa={...wa,backend:"sqlite-state.vscdb",dbPath:`${c} (ItemTable)`,cipher:"AES-256-GCM + vscdb-enc-v1"}:i&&(wa={...wa,backend:"indexeddb-state.vscdb-aes256gcm",dbPath:"IndexedDB://state.vscdb/ItemTable",cipher:globalThis.crypto?.subtle?"AES-256-GCM":"LOCAL-OBF-V1"}),wa={...Zo(),initialized:!0},Nv(),wa}async function fI(){return Vf||(Vf=(async()=>{const e=await Av();let r=null;if(e){r=await jv(e);try{const c=e.transaction(Us,"readonly"),d=await el(c.objectStore(Us).getAll())??[];for(const f of d){if(!f?.key?.startsWith(ny))continue;if(f.key.startsWith(sy)){const x=f.key.slice(sy.length),g=await J5(f.value,r);g&&x&&Ap.set(x,g);continue}const p=f.key.slice(ny.length);if(!Np.includes(p))continue;const b=await J5(f.value,r);b&&(Gi.set(p,b),Dc.set(p,{provider:p,fingerprint:f.value.fingerprint,updatedAtUtc:f.value.updatedAtUtc,cipher:f.value.alg}))}}catch{}}const n=await dI();if(n.available&&n.keys)for(const c of Np){const d=n.keys[c]?.trim();d&&!Gi.has(c)&&(Gi.set(c,d),Dc.set(c,{provider:c,fingerprint:await jp(d),updatedAtUtc:new Date().toISOString(),cipher:"vscdb-enc-v1"}))}const s=mI();for(const c of s)await cp(c.provider,c.key);wa={...wa,initialized:!0,backend:n.available?"sqlite-state.vscdb":e?"indexeddb-state.vscdb-aes256gcm":"memory-fallback",dbPath:n.available?`${n.dbPath??"~/.synlexa-studio/state.vscdb"} (ItemTable)`:e?"IndexedDB://state.vscdb/ItemTable":"memory://state.vscdb/ItemTable",cipher:n.available?"AES-256-GCM + SQLite state.vscdb":e&&r?"AES-256-GCM":"In-memory sealed session",migratedLegacyCount:s.length};const i={...Zo(),initialized:!0};return wa=i,Nv(),i})(),Vf)}const x3="synlexa.studio.aiPermissions.v1",Bo={safe_read:"always-allow",external_network:"ask",workspace_mutate:"always-allow",remote_compute:"ask"},Z5={safe_read:{label:"Workspace inspection & UI navigation",description:"Read loaded metrics, switch tabs/views, focus residues, and run offline RDKit/Wasm checks."},workspace_mutate:{label:"Project changes, plugins & exports",description:"Create/modify projects, split structures, toggle plugins, or download HTML/JSON reports."},external_network:{label:"External web & public databases",description:"Fetch structures/compounds from RCSB/AlphaFold/PubChem/ChEMBL or search Europe PMC & ClinicalTrials.gov."},remote_compute:{label:"External GPU / Colab & multi-step pipelines",description:"Dispatch jobs to connected GPU Compute Nodes (AutoDock Vina, OpenMM, Boltz-2, RFdiffusion, PySCF)."}};function pI(e,r={}){switch(e){case"fetch_from_database":return{category:"external_network",title:`Fetch from ${String(r.source??"public database").toUpperCase()}`,detail:`Query "${String(r.query??"")}"${r.autoImport!==!1?" and import into workspace":""}.`};case"search_scientific_web":return{category:"external_network",title:"Search scientific literature & trials",detail:`Query Europe PMC / ClinicalTrials.gov for "${String(r.query??"")}".`};case"run_compute_job":return{category:"remote_compute",title:`Dispatch GPU / Compute job (${String(r.toolId??"adapter")})`,detail:"Submit computation to the active connected Compute Node."};case"run_workflow_pipeline":return{category:"remote_compute",title:`Execute workflow pipeline (${String(r.templateId??"active")})`,detail:"Run multi-step DAG workflow across configured compute tiers."};case"export_ruo_report":return{category:"workspace_mutate",title:`Export RUO ${String(r.format??"html").toUpperCase()} artifact`,detail:"Generate and download report/manifest/bundle file."};case"manage_project":{const n=String(r.action??"list");return{category:n==="list"?"safe_read":"workspace_mutate",title:`Project action: ${n}`,detail:`Modify or split project assets (${String(r.name??r.projectId??"active project")}).`}}case"manage_plugins":{const n=String(r.action??"list");return{category:n==="list"?"safe_read":"workspace_mutate",title:`Plugin manager: ${n}`,detail:`Inspect or toggle plugin "${String(r.pluginId??"catalog")}".`}}default:return{category:"safe_read",title:`Run ${e}`,detail:"Deterministic local workspace / UI action."}}}function t0(e){let r=null;if(!r)try{r=typeof localStorage<"u"?localStorage:null}catch{r=null}if(!r)return{...Bo};try{const n=r.getItem(x3);if(!n)return{...Bo};const s=JSON.parse(n);return{safe_read:s.safe_read??Bo.safe_read,external_network:s.external_network??Bo.external_network,workspace_mutate:s.workspace_mutate??Bo.workspace_mutate,remote_compute:s.remote_compute??Bo.remote_compute}}catch{return{...Bo}}}function gI(e,r){const n={...t0(),...e};let s=null;if(!s)try{s=typeof localStorage<"u"?localStorage:null}catch{s=null}try{s?.setItem(x3,JSON.stringify(n))}catch{}return n}const ry="gemini-3.1-flash-lite",eA=[{id:"gemini-3.1-flash-lite",label:"Gemini 3.1 Flash-Lite",note:"Fastest · default for quick answers"},{id:"gemini-3-flash-preview",label:"Gemini 3 Flash",note:"Multi-step reasoning & tool use · preview"},{id:"gemini-3.1-pro-preview",label:"Gemini 3.1 Pro",note:"Deep reasoning, 1M-token context · preview"},{id:"gemini-4-hydrogen",label:"Gemini 4 Hydrogen",note:"Fast, efficient agentic workflows"},{id:"gemini-4-argon",label:"Gemini 4 Argon",note:"Efficient frontier reasoning for math & science"},{id:"gemini-4-carbon",label:"Gemini 4 Carbon",note:"Strongest reasoning · complex scientific work"}],y3="https://generativelanguage.googleapis.com/v1beta/models",_3="synlexa.studio.gemini.model",bI=[{name:"fetch_from_database",description:"Search or import a verified public structure or compound from RCSB PDB, AlphaFold DB, UniProtKB, or PubChem (or pinned local cache if offline).",parameters:{type:"OBJECT",properties:{source:{type:"STRING",description:"Public database source to query.",enum:["rcsb","alphafold","uniprot","pubchem"]},query:{type:"STRING",description:'PDB ID, UniProt accession, protein name, or compound name (e.g. "1UBQ", "P0CG48", "imatinib").'},role:{type:"STRING",description:"When importing a structure, whether to assign it as reference or mobile.",enum:["reference","mobile"]},autoImport:{type:"BOOLEAN",description:"If true, immediately import the top matching record into the IDE workspace."}},required:["source","query"]}},{name:"run_structure_superposition",description:"Run deterministic float64 Kabsch 3D rigid superposition between the currently loaded Reference and Mobile structures.",parameters:{type:"OBJECT",properties:{refChain:{type:"STRING",description:"Optional explicit polymer chain ID for the reference structure."},mobChain:{type:"STRING",description:"Optional explicit polymer chain ID for the mobile structure."}}}},{name:"focus_3d_residues",description:"Highlight and center one or more residue sequence numbers across the 3D viewport, sequence Δd track, PAE matrix, and Ramachandran plot.",parameters:{type:"OBJECT",properties:{seqIds:{type:"ARRAY",description:"Positive 1-based residue sequence IDs to focus.",items:{type:"INTEGER"}}},required:["seqIds"]}},{name:"engineer_peptide_mutation",description:"Apply one or more point mutations (e.g. H94A, T199V, E7V) in the Peptide Engineering workbench and compute deterministic biophysical deltas.",parameters:{type:"OBJECT",properties:{mutations:{type:"ARRAY",description:'Point mutations in <WT><pos><Mut> format, e.g. ["H94A"].',items:{type:"STRING"}},focusSeqId:{type:"INTEGER",description:"Optional residue ID for 5.0 Å local 3D contact shell inspection."}},required:["mutations"]}},{name:"design_crispr_edit",description:"Evaluate a coding-transcript nucleotide edit consequence (synonymous/missense/nonsense) and scan SpCas9, SaCas9, or Cas12a PAM sites.",parameters:{type:"OBJECT",properties:{transcriptId:{type:"STRING",description:"RefSeq transcript ID (NM_000067.3 CA2, NM_000518.5 HBB, NM_000546.6 TP53).",enum:["NM_000067.3","NM_000518.5","NM_000546.6"]},targetCodonIndex:{type:"INTEGER",description:"1-based target codon index in the CDS."},baseEditOffset:{type:"INTEGER",description:"Codon base offset (0, 1, or 2)."},newBase:{type:"STRING",description:"Substituted DNA nucleotide.",enum:["A","C","G","T"]},nuclease:{type:"STRING",description:"CRISPR nuclease PAM scanner.",enum:["SpCas9","SaCas9","Cas12a"]}},required:["targetCodonIndex"]}},{name:"inspect_chemical_smiles",description:"Parse a SMILES string in the deterministic Wasm chemistry engine to compute formula, MW, TPSA, cLogP, Lipinski/Veber metrics, and 2D layout.",parameters:{type:"OBJECT",properties:{smiles:{type:"STRING",description:"Canonical or isomeric SMILES string."},name:{type:"STRING",description:"Human-readable compound label."}},required:["smiles"]}},{name:"analyze_ramachandran",description:"Compute backbone (φ, ψ) dihedral angles, secondary structure counts (Helix/Sheet/Loop), Ramachandran favored/allowed/outlier counts, and Cα–Cα contacts.",parameters:{type:"OBJECT",properties:{target:{type:"STRING",description:"Which loaded structure to analyze.",enum:["reference","mobile"]},chainId:{type:"STRING",description:"Optional polymer chain ID."}}}},{name:"export_ruo_report",description:"Export a self-contained Research-Use-Only (RUO) HTML report, JSON provenance manifest, or versioned .synlexa.bundle.json project file.",parameters:{type:"OBJECT",properties:{format:{type:"STRING",description:"Export format.",enum:["html","json","bundle"]}},required:["format"]}}],xI=[{name:"get_workspace_state",description:"Inspect the complete live deterministic workspace state via the in-app MCP server: top deviating residues, ligand/metal active-site contacts, Ramachandran outliers, peptide deltas, CRISPR PAM sites, SMILES descriptors, and saved library items.",parameters:{type:"OBJECT",properties:{section:{type:"STRING",description:"Which slice of workspace telemetry to inspect.",enum:["all","comparison","contacts","peptide","crispr","chemistry","ramachandran","library"]},topN:{type:"INTEGER",description:"Maximum number of residue/contact/PAM rows to include (default 10)."}}}},{name:"search_scientific_web",description:"Search live peer-reviewed scientific literature (Europe PMC / PubMed) and trial registries (ClinicalTrials.gov API v2) with verified PMIDs, DOIs, NCT IDs, source URLs, and UTC timestamps.",parameters:{type:"OBJECT",properties:{query:{type:"STRING",description:'Scientific search query (e.g. "carbonic anhydrase II acetazolamide 3HS4", "hashimoto autoimmune thyroid biomarker").'},scope:{type:"STRING",description:"Sources to query.",enum:["all","literature","trials"]},limit:{type:"INTEGER",description:"Maximum results per source (1-8)."}},required:["query"]}},{name:"query_local_library",description:"List or filter saved structures, ligands, and sequences in the local IndexedDB molecule library with SHA-256 checksums and provenance.",parameters:{type:"OBJECT",properties:{kind:{type:"STRING",description:"Filter by item kind.",enum:["all","structure","compound","sequence"]},query:{type:"STRING",description:"Optional substring filter by name, accession, or tag."}}}},{name:"list_compute_nodes",description:"List paired external GPU / Colab / local Compute Nodes, detected GPUs/VRAM, and installed bioinformatics engines (Vina, OpenMM, Boltz-2, RFdiffusion, PySCF, GROMACS).",parameters:{type:"OBJECT",properties:{}}},{name:"run_compute_job",description:"Submit a scientific compute job (vina_docking, openmm_md, boltz_predict, rfdiffusion_design, pyscf_qm, rdkit_3d, gromacs_md) to the currently active connected Compute Node.",parameters:{type:"OBJECT",properties:{toolId:{type:"STRING",description:"Compute adapter ID on the connected node.",enum:["vina_docking","openmm_md","boltz_predict","rfdiffusion_design","pyscf_qm","rdkit_3d","gromacs_md"]},smiles:{type:"STRING",description:"Optional ligand SMILES (defaults to active Chemistry Workbench SMILES)."},steps:{type:"INTEGER",description:"Optional OpenMM MD steps (default 1000)."}},required:["toolId"]}},{name:"control_app_ui",description:'Navigate and control the Synlexa Studio UI ("octopus arms"): open/split any workbench tab, switch the 3D engine (Fast WebGL2 vs Mol* Pro), change 3D layout/style/colorMode/camera preset, switch sidebar view, or open the interactive Tutorial.',parameters:{type:"OBJECT",properties:{openTab:{type:"STRING",description:"Tab to open or focus.",enum:["home","viewer","results","sequence","ramachandran","peptide","crispr","chemistry","workflow","compute","plugins","assistant","mcp","library"]},toSide:{type:"BOOLEAN",description:"If true, open the tab in a split side pane."},viewportEngine:{type:"STRING",description:"Switch 3D engine between Fast WebGL2 and Mol* Pro.",enum:["webgl2","molstar"]},viewportLayout:{type:"STRING",description:"Set 3D comparison layout.",enum:["overlay","split","reference","mobile"]},renderStyle:{type:"STRING",description:"Set 3D representation style.",enum:["ribbon","trace","pocket"]},colorMode:{type:"STRING",description:"Set 3D coloring mode.",enum:["identity","plddt","bfactor","deviation"]},cameraPreset:{type:"STRING",description:"Move 3D camera to preset.",enum:["overview","active-site","n-terminus","reset"]},sidebarView:{type:"STRING",description:"Switch left sidebar view.",enum:["explorer","library","tools","history"]},openTutorial:{type:"BOOLEAN",description:"Open the interactive Studio guided tutorial."}}}},{name:"manage_project",description:"Create, list, or switch multi-asset research projects; save designed molecules/peptides; split multi-chain/ligand structures into individual parts; or bind a receptor and ligand for docking.",parameters:{type:"OBJECT",properties:{action:{type:"STRING",description:"Project action to perform.",enum:["list","create","switch","add_molecule","split_chains","stage_binding"]},projectId:{type:"STRING",description:"Target project ID when switching."},name:{type:"STRING",description:"Project or molecule name."},description:{type:"STRING",description:"Project description."},template:{type:"STRING",description:"Project starter template.",enum:["blank","structure-compare","ligand-docking","peptide-crispr"]},smiles:{type:"STRING",description:"SMILES string when adding a molecule."},target:{type:"STRING",description:"Which loaded structure to split (reference or mobile).",enum:["reference","mobile"]}},required:["action"]}},{name:"design_molecule_rdkit",description:"Analyze, validate, screen for PAINS/Brenk alerts, or run SMARTS substructure search on a molecule using the in-browser RDKit WASM engine, and optionally save it into the active project.",parameters:{type:"OBJECT",properties:{smiles:{type:"STRING",description:"SMILES or MOL block to analyze/design."},name:{type:"STRING",description:"Molecule label."},smartsQuery:{type:"STRING",description:"Optional SMARTS pattern for substructure matching/highlighting."},saveToProject:{type:"BOOLEAN",description:"Save molecule to the active project."}},required:["smiles"]}},{name:"run_workflow_pipeline",description:"Open Workflow Canvas and inspect, export (Nextflow/Snakemake), or execute a multi-step scientific DAG workflow template.",parameters:{type:"OBJECT",properties:{templateId:{type:"STRING",description:"Workflow template ID.",enum:["tpl-structure-audit","tpl-hit-to-lead","tpl-binder-design","tpl-quantum-ligand"]},action:{type:"STRING",description:"Whether to run, export Nextflow, or export Snakemake.",enum:["run","export_nextflow","export_snakemake"]}},required:["action"]}},{name:"manage_plugins",description:"List all open-source biochemistry plugins & license status, or enable/disable an add-on.",parameters:{type:"OBJECT",properties:{action:{type:"STRING",description:"Plugin action to perform.",enum:["list","enable","disable"]},pluginId:{type:"STRING",description:"Plugin ID (e.g. org.synlexa.autodock-vina)."}},required:["action"]}}],Tp=[...bI,...xI];function yI(e){return`${y3}/${encodeURIComponent(e)}:generateContent`}function Tv(e){const r=[`Active Reference: ${e.refLabel||"none"} (chain=${e.refChain||"unselected"}, sha256=${e.comparison?.reference.sha256??e.refInspect?.sha256??"none"}, confidence=${e.comparison?.reference.confidenceKind??e.refInspect?.confidenceKind??"none"})`,`Active Mobile: ${e.mobLabel||"none"} (chain=${e.mobChain||"unselected"}, sha256=${e.comparison?.mobile.sha256??e.mobInspect?.sha256??"none"}, confidence=${e.comparison?.mobile.confidenceKind??e.mobInspect?.confidenceKind??"none"})`];if(e.comparison){const n=e.comparison.metrics,s=e.comparison.matchedResidues.map(p=>p.mobPlddt).filter(p=>p!==null&&Number.isFinite(p)),i=s.length>0?s.reduce((p,b)=>p+b,0)/s.length:null,c=e.comparison.refDisplayAtoms?.ligands.map(p=>`${p.resName}(${p.chainId}:${p.seqId})`).join(", ")||"none";r.push(`Comparison (${e.comparison.resultId.slice(0,12)}): RMSD=${n.rmsdAngstrom.toFixed(4)} Å across ${n.matchedCaCount} Cα, refCov=${n.refCoverage.numerator}/${n.refCoverage.denominator} (${n.refCoverage.denominatorKind}), mobCov=${n.mobCoverage.numerator}/${n.mobCoverage.denominator}, meanPlddt=${i!==null?i.toFixed(1):"n/a"}, PAE=${n.paeStatus}, ligands=[${c}]`);const d=[...e.comparison.matchedResidues].sort((p,b)=>b.distanceAngstrom-p.distanceAngstrom).slice(0,6);d.length>0&&r.push(`Top Cα Deviations: ${d.map(p=>`${p.resName3}${p.refSeqId}=${p.distanceAngstrom.toFixed(3)}Å${p.mobPlddt!==null?`(pLDDT ${p.mobPlddt.toFixed(1)})`:""}`).join(", ")}`);const f=e.comparison.refContacts??[];if(f.length>0){const p=[...f].sort((b,x)=>b.distanceAngstrom-x.distanceAngstrom).slice(0,6).map(b=>`${b.ligandResName}.${b.ligandAtom}–${b.proteinResName3}${b.proteinSeqId}.${b.proteinAtom}(${b.distanceAngstrom.toFixed(2)}Å)`);r.push(`Active-Site Ligand/Metal Contacts (≤4.5 Å, total=${f.length}): ${p.join(", ")}`)}}if(e.peptide){const n=e.peptide;r.push(`Peptide: len=${n.engineered.length}, mutations=[${n.appliedMutations.map(s=>s.notation).join(",")||"none"}], WT_MW=${n.wildType.mwAverageDa.toFixed(1)} Da, ΔMW=${n.deltas.mwAverageDa.toFixed(2)} Da, pI=${n.engineered.pi.toFixed(2)} (Δ${n.deltas.pi.toFixed(2)}), charge@7.4=${n.engineered.chargeAtPh74.toFixed(2)}, GRAVY=${n.engineered.gravy.toFixed(3)}, 3D_contacts=${n.local3dContacts.slice(0,5).map(s=>`${s.resName3}${s.seqId}(${s.distanceAngstrom.toFixed(2)}Å)`).join(", ")||"none"}`)}if(e.crispr){const n=e.crispr,s=n.pamSites.slice(0,4).map(i=>`${i.nuclease}:${i.pam}(${i.strand},cut=${i.cutBp1},Δ=${i.distanceToTargetCodonBp}bp,GC=${i.gcPercent.toFixed(0)}%)`);r.push(`CRISPR: ${n.geneSymbol} (${n.transcriptId}, ${n.cdsLengthBp} bp), codon=${n.targetCodon.codonIndex1} (${n.targetCodon.wtCodon}/${n.targetCodon.wtAa} -> ${n.targetCodon.editedCodon}/${n.targetCodon.editedAa}, ${n.targetCodon.consequence}), PAMs=${n.pamSites.length} [${s.join("; ")}]`)}if(e.smiles){const n=e.smiles;r.push(`SMILES: ${n.name}, formula=${n.formula}, MW=${n.molecularWeight.toFixed(2)} Da, exactMass=${n.exactMass.toFixed(4)} Da, TPSA=${n.tpsa.toFixed(2)} Ų, cLogP=${n.crippenLogP.toFixed(2)}, HBD=${n.hbd}, HBA=${n.hba}, rotBonds=${n.rotatableBonds}, rings=${n.ringCount}, LipinskiViol=${n.lipinskiViolations}, Veber=${n.veberCompliant?"pass":"fail"}`)}if(e.ramachandran){const n=e.ramachandran,s=n.residues.filter(i=>i.region==="outlier").slice(0,5).map(i=>`${i.resName3}${i.seqId}(φ=${i.phiDeg?.toFixed(1)??"n/a"},ψ=${i.psiDeg?.toFixed(1)??"n/a"})`);r.push(`Ramachandran: chain=${n.chainId}, residues=${n.residueCount}, H/S/L=${n.secondaryCounts.helix}/${n.secondaryCounts.sheet}/${n.secondaryCounts.loop}, favored/allowed/outlier=${n.regionCounts.favored}/${n.regionCounts.allowed}/${n.regionCounts.outlier}, contacts=${n.contactPairs.length}${s.length?`, outliers=[${s.join(", ")}]`:""}`)}return r.join(`
682
+ `),timestampUtc:i}}}const h3="state.vscdb",cI=1,Us="ItemTable",Mc="VaultKeyStore",X5="synlexa.studio.master.aes256gcm.raw.v2",ny="secret://synlexa.studio.vault/",sy="secret://synlexa.studio.vault/custom/",m3={gemini:"synlexa.studio.gemini.apiKey",anthropic:"synlexa.studio.anthropic.apiKey",openai:"synlexa.studio.openai.apiKey"},Np=["anthropic","gemini","openai"],Gi=new Map,Dc=new Map,Ap=new Map,ay=new Set;let wa={initialized:!1,backend:"memory-fallback",dbName:h3,tableName:Us,dbPath:"IndexedDB://state.vscdb/ItemTable",encrypted:!0,cipher:"AES-256-GCM",storedProviders:[],entries:{},migratedLegacyCount:0},Vf=null,Kf=null;function Nv(){for(const e of ay)e()}function f3(e){return ay.add(e),()=>ay.delete(e)}function Zo(){return{...wa,storedProviders:Np.filter(e=>Gi.has(e)&&!!Gi.get(e)),entries:Object.fromEntries(Dc.entries())}}function xx(e){return Gi.get(e)??""}function uI(e){return Ap.get(e)??""}async function p3(e,r){const n=e.trim().replace(/[^a-zA-Z0-9._:-]/g,"_");if(!n)return;const s=r.trim(),i=new Date().toISOString();s?Ap.set(n,s):Ap.delete(n);const c=await Av();if(c){const d=await jv(c),f=`${sy}${n}`;if(s){const p=await g3(s,d),b=await jp(s),x={key:f,value:{v:1,alg:p.alg,iv:p.iv,ct:p.ct,fingerprint:b,updatedAtUtc:i}},g=c.transaction(Us,"readwrite");await el(g.objectStore(Us).put(x))}else{const p=c.transaction(Us,"readwrite");await el(p.objectStore(Us).delete(f))}}Nv()}function Yf(e){let r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);return btoa(r)}function Q5(e){const r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}function Av(){return Kf||(Kf=new Promise(e=>{if(typeof indexedDB>"u")return e(null);try{const r=indexedDB.open(h3,cI);r.onupgradeneeded=()=>{const n=r.result;n.objectStoreNames.contains(Us)||n.createObjectStore(Us,{keyPath:"key"}),n.objectStoreNames.contains(Mc)||n.createObjectStore(Mc,{keyPath:"id"})},r.onsuccess=()=>e(r.result),r.onerror=()=>e(null)}catch{e(null)}}),Kf)}function el(e){return new Promise((r,n)=>{e.onsuccess=()=>r(e.result),e.onerror=()=>n(e.error)})}async function jv(e){const r=globalThis.crypto?.subtle;if(!r)return null;try{const n=e.transaction(Mc,"readonly"),s=await el(n.objectStore(Mc).get(X5))??null;if(s?.raw){const f=Uint8Array.from(atob(s.raw),p=>p.charCodeAt(0));return await r.importKey("raw",f,{name:"AES-GCM"},!1,["encrypt","decrypt"])}const i=globalThis.crypto.getRandomValues(new Uint8Array(32));let c="";for(const f of i)c+=String.fromCharCode(f);const d=e.transaction(Mc,"readwrite");return await el(d.objectStore(Mc).put({id:X5,raw:btoa(c)})),await r.importKey("raw",i,{name:"AES-GCM"},!1,["encrypt","decrypt"])}catch{return null}}async function g3(e,r){const n=new TextEncoder().encode(e);if(r&&globalThis.crypto?.subtle&&globalThis.crypto?.getRandomValues){const c=globalThis.crypto.getRandomValues(new Uint8Array(12)),d=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:c},r,n);return{alg:"AES-GCM-256",iv:Yf(c),ct:Yf(new Uint8Array(d))}}const s=new Uint8Array(12);globalThis.crypto?.getRandomValues?.(s);const i=new Uint8Array(n.length);for(let c=0;c<n.length;c++)i[c]=n[c]^s[c%s.length]^90;return{alg:"LOCAL-OBF-V1",iv:Yf(s),ct:Yf(i)}}async function J5(e,r){try{const n=Q5(e.iv),s=Q5(e.ct);if(e.alg==="AES-GCM-256"){if(!r||!globalThis.crypto?.subtle)return null;const c=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:n},r,s);return new TextDecoder().decode(c)}const i=new Uint8Array(s.length);for(let c=0;c<s.length;c++)i[c]=s[c]^n[c%n.length]^90;return new TextDecoder().decode(i)}catch{return null}}async function jp(e){return(await Jc(`synlexa-vault-fp:${e}`)).slice(0,12)}function b3(){if(typeof window>"u")return!1;const e=window.location?.hostname??"";return e==="127.0.0.1"||e==="localhost"}async function dI(){if(!b3()||typeof fetch!="function")return{available:!1};try{const e=await fetch("/api/local-vault/keys",{method:"GET"});if(!e.ok)return{available:!1};if(!(e.headers.get("content-type")??"").includes("application/json"))return{available:!1};const n=await e.json();return n?.ok?{available:!0,dbPath:n.dbPath,keys:n.keys??{}}:{available:!1}}catch{return{available:!1}}}async function hI(e,r){if(!b3()||typeof fetch!="function")return null;try{const n=await fetch("/api/local-vault/keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,apiKey:r})});if(!n.ok)return null;const s=await n.json();return s?.ok?s.dbPath??"~/.synlexa-studio/state.vscdb":null}catch{return null}}function mI(){const e=[];try{if(typeof localStorage>"u")return e;for(const r of Np){const n=m3[r],s=localStorage.getItem(n)?.trim();s&&(e.push({provider:r,key:s}),localStorage.removeItem(n))}}catch{}return e}async function cp(e,r){const n=r.trim(),s=new Date().toISOString();try{typeof localStorage<"u"&&localStorage.removeItem(m3[e])}catch{}if(!n)Gi.delete(e),Dc.delete(e);else{Gi.set(e,n);const f=await jp(n);Dc.set(e,{provider:e,fingerprint:f,updatedAtUtc:s,cipher:wa.cipher})}const i=await Av();if(i){const f=await jv(i),p=`${ny}${e}`;if(n){const b=await g3(n,f),x=Dc.get(e)?.fingerprint??await jp(n),g={key:p,value:{v:1,alg:b.alg,iv:b.iv,ct:b.ct,fingerprint:x,updatedAtUtc:s}},_=i.transaction(Us,"readwrite");await el(_.objectStore(Us).put(g))}else{const b=i.transaction(Us,"readwrite");await el(b.objectStore(Us).delete(p))}}const c=await hI(e,n);return c?wa={...wa,backend:"sqlite-state.vscdb",dbPath:`${c} (ItemTable)`,cipher:"AES-256-GCM + vscdb-enc-v1"}:i&&(wa={...wa,backend:"indexeddb-state.vscdb-aes256gcm",dbPath:"IndexedDB://state.vscdb/ItemTable",cipher:globalThis.crypto?.subtle?"AES-256-GCM":"LOCAL-OBF-V1"}),wa={...Zo(),initialized:!0},Nv(),wa}async function fI(){return Vf||(Vf=(async()=>{const e=await Av();let r=null;if(e){r=await jv(e);try{const c=e.transaction(Us,"readonly"),d=await el(c.objectStore(Us).getAll())??[];for(const f of d){if(!f?.key?.startsWith(ny))continue;if(f.key.startsWith(sy)){const x=f.key.slice(sy.length),g=await J5(f.value,r);g&&x&&Ap.set(x,g);continue}const p=f.key.slice(ny.length);if(!Np.includes(p))continue;const b=await J5(f.value,r);b&&(Gi.set(p,b),Dc.set(p,{provider:p,fingerprint:f.value.fingerprint,updatedAtUtc:f.value.updatedAtUtc,cipher:f.value.alg}))}}catch{}}const n=await dI();if(n.available&&n.keys)for(const c of Np){const d=n.keys[c]?.trim();d&&!Gi.has(c)&&(Gi.set(c,d),Dc.set(c,{provider:c,fingerprint:await jp(d),updatedAtUtc:new Date().toISOString(),cipher:"vscdb-enc-v1"}))}const s=mI();for(const c of s)await cp(c.provider,c.key);wa={...wa,initialized:!0,backend:n.available?"sqlite-state.vscdb":e?"indexeddb-state.vscdb-aes256gcm":"memory-fallback",dbPath:n.available?`${n.dbPath??"~/.synlexa-studio/state.vscdb"} (ItemTable)`:e?"IndexedDB://state.vscdb/ItemTable":"memory://state.vscdb/ItemTable",cipher:n.available?"AES-256-GCM + SQLite state.vscdb":e&&r?"AES-256-GCM":"In-memory sealed session",migratedLegacyCount:s.length};const i={...Zo(),initialized:!0};return wa=i,Nv(),i})(),Vf)}const x3="synlexa.studio.aiPermissions.v1",Bo={safe_read:"always-allow",external_network:"ask",workspace_mutate:"always-allow",remote_compute:"ask"},Z5={safe_read:{label:"Workspace inspection & UI navigation",description:"Read loaded metrics, switch tabs/views, focus residues, and run offline RDKit/Wasm checks."},workspace_mutate:{label:"Project changes, plugins & exports",description:"Create/modify projects, split structures, toggle plugins, or download HTML/JSON reports."},external_network:{label:"External web & public databases",description:"Fetch structures/compounds from RCSB/AlphaFold/PubChem/ChEMBL or search Europe PMC & ClinicalTrials.gov."},remote_compute:{label:"External GPU / Colab & multi-step pipelines",description:"Dispatch jobs to connected GPU Compute Nodes (AutoDock Vina, OpenMM, Boltz-2, RFdiffusion, PySCF)."}};function pI(e,r={}){switch(e){case"fetch_from_database":return{category:"external_network",title:`Fetch from ${String(r.source??"public database").toUpperCase()}`,detail:`Query "${String(r.query??"")}"${r.autoImport!==!1?" and import into workspace":""}.`};case"search_scientific_web":return{category:"external_network",title:"Search scientific literature & trials",detail:`Query Europe PMC / ClinicalTrials.gov for "${String(r.query??"")}".`};case"run_compute_job":return{category:"remote_compute",title:`Dispatch GPU / Compute job (${String(r.toolId??"adapter")})`,detail:"Submit computation to the active connected Compute Node."};case"run_workflow_pipeline":return{category:"remote_compute",title:`Execute workflow pipeline (${String(r.templateId??"active")})`,detail:"Run multi-step DAG workflow across configured compute tiers."};case"export_ruo_report":return{category:"workspace_mutate",title:`Export RUO ${String(r.format??"html").toUpperCase()} artifact`,detail:"Generate and download report/manifest/bundle file."};case"manage_project":{const n=String(r.action??"list");return{category:n==="list"?"safe_read":"workspace_mutate",title:`Project action: ${n}`,detail:`Modify or split project assets (${String(r.name??r.projectId??"active project")}).`}}case"manage_plugins":{const n=String(r.action??"list");return{category:n==="list"?"safe_read":"workspace_mutate",title:`Plugin manager: ${n}`,detail:`Inspect or toggle plugin "${String(r.pluginId??"catalog")}".`}}default:return{category:"safe_read",title:`Run ${e}`,detail:"Deterministic local workspace / UI action."}}}function t0(e){let r=null;if(!r)try{r=typeof localStorage<"u"?localStorage:null}catch{r=null}if(!r)return{...Bo};try{const n=r.getItem(x3);if(!n)return{...Bo};const s=JSON.parse(n);return{safe_read:s.safe_read??Bo.safe_read,external_network:s.external_network??Bo.external_network,workspace_mutate:s.workspace_mutate??Bo.workspace_mutate,remote_compute:s.remote_compute??Bo.remote_compute}}catch{return{...Bo}}}function gI(e,r){const n={...t0(),...e};let s=null;if(!s)try{s=typeof localStorage<"u"?localStorage:null}catch{s=null}try{s?.setItem(x3,JSON.stringify(n))}catch{}return n}const ry="gemini-3.1-flash-lite",eA=[{id:"gemini-3.1-flash-lite",label:"Gemini 3.1 Flash-Lite",note:"Fastest · default for quick answers"},{id:"gemini-3-flash-preview",label:"Gemini 3 Flash",note:"Multi-step reasoning & tool use · preview"},{id:"gemini-3.1-pro-preview",label:"Gemini 3.1 Pro",note:"Deep reasoning, 1M-token context · preview"},{id:"gemini-4-hydrogen",label:"Gemini 4 Hydrogen",note:"Fast, efficient agentic workflows"},{id:"gemini-4-argon",label:"Gemini 4 Argon",note:"Efficient frontier reasoning for math & science"},{id:"gemini-4-carbon",label:"Gemini 4 Carbon",note:"Strongest reasoning · complex scientific work"}],y3="https://generativelanguage.googleapis.com/v1beta/models",_3="synlexa.studio.gemini.model",bI=[{name:"fetch_from_database",description:"Search or import a verified public structure or compound from RCSB PDB, AlphaFold DB, UniProtKB, or PubChem (or pinned local cache if offline).",parameters:{type:"OBJECT",properties:{source:{type:"STRING",description:"Public database source to query.",enum:["rcsb","alphafold","uniprot","pubchem"]},query:{type:"STRING",description:'PDB ID, UniProt accession, protein name, or compound name (e.g. "1UBQ", "P0CG48", "imatinib").'},role:{type:"STRING",description:"When importing a structure, whether to assign it as reference or mobile.",enum:["reference","mobile"]},autoImport:{type:"BOOLEAN",description:"If true, immediately import the top matching record into the IDE workspace."}},required:["source","query"]}},{name:"run_structure_superposition",description:"Run deterministic float64 Kabsch 3D rigid superposition between the currently loaded Reference and Mobile structures.",parameters:{type:"OBJECT",properties:{refChain:{type:"STRING",description:"Optional explicit polymer chain ID for the reference structure."},mobChain:{type:"STRING",description:"Optional explicit polymer chain ID for the mobile structure."}}}},{name:"focus_3d_residues",description:"Highlight and center one or more residue sequence numbers across the 3D viewport, sequence Δd track, PAE matrix, and Ramachandran plot.",parameters:{type:"OBJECT",properties:{seqIds:{type:"ARRAY",description:"Positive 1-based residue sequence IDs to focus.",items:{type:"INTEGER"}}},required:["seqIds"]}},{name:"engineer_peptide_mutation",description:"Apply one or more point mutations (e.g. H94A, T199V, E7V) in the Peptide Engineering workbench and compute deterministic biophysical deltas.",parameters:{type:"OBJECT",properties:{mutations:{type:"ARRAY",description:'Point mutations in <WT><pos><Mut> format, e.g. ["H94A"].',items:{type:"STRING"}},focusSeqId:{type:"INTEGER",description:"Optional residue ID for 5.0 Å local 3D contact shell inspection."}},required:["mutations"]}},{name:"design_crispr_edit",description:"Evaluate a coding-transcript nucleotide edit consequence (synonymous/missense/nonsense) and scan SpCas9, SaCas9, or Cas12a PAM sites.",parameters:{type:"OBJECT",properties:{transcriptId:{type:"STRING",description:"RefSeq transcript ID (NM_000067.3 CA2, NM_000518.5 HBB, NM_000546.6 TP53).",enum:["NM_000067.3","NM_000518.5","NM_000546.6"]},targetCodonIndex:{type:"INTEGER",description:"1-based target codon index in the CDS."},baseEditOffset:{type:"INTEGER",description:"Codon base offset (0, 1, or 2)."},newBase:{type:"STRING",description:"Substituted DNA nucleotide.",enum:["A","C","G","T"]},nuclease:{type:"STRING",description:"CRISPR nuclease PAM scanner.",enum:["SpCas9","SaCas9","Cas12a"]}},required:["targetCodonIndex"]}},{name:"inspect_chemical_smiles",description:"Parse a SMILES string in the deterministic Wasm chemistry engine to compute formula, MW, TPSA, cLogP, Lipinski/Veber metrics, and 2D layout.",parameters:{type:"OBJECT",properties:{smiles:{type:"STRING",description:"Canonical or isomeric SMILES string."},name:{type:"STRING",description:"Human-readable compound label."}},required:["smiles"]}},{name:"analyze_ramachandran",description:"Compute backbone (φ, ψ) dihedral angles, secondary structure counts (Helix/Sheet/Loop), Ramachandran favored/allowed/outlier counts, and Cα–Cα contacts.",parameters:{type:"OBJECT",properties:{target:{type:"STRING",description:"Which loaded structure to analyze.",enum:["reference","mobile"]},chainId:{type:"STRING",description:"Optional polymer chain ID."}}}},{name:"export_ruo_report",description:"Export a self-contained Research-Use-Only (RUO) HTML report, JSON provenance manifest, or versioned .synlexa.bundle.json project file.",parameters:{type:"OBJECT",properties:{format:{type:"STRING",description:"Export format.",enum:["html","json","bundle"]}},required:["format"]}}],xI=[{name:"get_workspace_state",description:"Inspect the complete live deterministic workspace state via the in-app MCP server: top deviating residues, ligand/metal active-site contacts, Ramachandran outliers, peptide deltas, CRISPR PAM sites, SMILES descriptors, and saved library items.",parameters:{type:"OBJECT",properties:{section:{type:"STRING",description:"Which slice of workspace telemetry to inspect.",enum:["all","comparison","contacts","peptide","crispr","chemistry","ramachandran","library"]},topN:{type:"INTEGER",description:"Maximum number of residue/contact/PAM rows to include (default 10)."}}}},{name:"search_scientific_web",description:"Search live peer-reviewed scientific literature (Europe PMC / PubMed) and trial registries (ClinicalTrials.gov API v2) with verified PMIDs, DOIs, NCT IDs, source URLs, and UTC timestamps.",parameters:{type:"OBJECT",properties:{query:{type:"STRING",description:'Scientific search query (e.g. "carbonic anhydrase II acetazolamide 3HS4", "hashimoto autoimmune thyroid biomarker").'},scope:{type:"STRING",description:"Sources to query.",enum:["all","literature","trials"]},limit:{type:"INTEGER",description:"Maximum results per source (1-8)."}},required:["query"]}},{name:"query_local_library",description:"List or filter saved structures, ligands, and sequences in the local IndexedDB molecule library with SHA-256 checksums and provenance.",parameters:{type:"OBJECT",properties:{kind:{type:"STRING",description:"Filter by item kind.",enum:["all","structure","compound","sequence"]},query:{type:"STRING",description:"Optional substring filter by name, accession, or tag."}}}},{name:"list_compute_nodes",description:"List paired external GPU / Colab / local Compute Nodes, detected GPUs/VRAM, and installed bioinformatics engines (Vina, OpenMM, Boltz-2, RFdiffusion, PySCF, GROMACS).",parameters:{type:"OBJECT",properties:{}}},{name:"run_compute_job",description:"Submit a scientific compute job (vina_docking, openmm_md, boltz_predict, rfdiffusion_design, pyscf_qm, rdkit_3d, gromacs_md) to the currently active connected Compute Node.",parameters:{type:"OBJECT",properties:{toolId:{type:"STRING",description:"Compute adapter ID on the connected node.",enum:["vina_docking","openmm_md","boltz_predict","rfdiffusion_design","pyscf_qm","rdkit_3d","gromacs_md"]},smiles:{type:"STRING",description:"Optional ligand SMILES (defaults to active Chemistry Workbench SMILES)."},steps:{type:"INTEGER",description:"Optional OpenMM MD steps (default 1000)."}},required:["toolId"]}},{name:"control_app_ui",description:'Navigate and control the Synlexa Studio UI ("octopus arms"): open/split any workbench tab, switch the 3D engine (Fast WebGL2 vs Mol* Pro), change 3D layout/style/colorMode/camera preset, switch sidebar view, or open the interactive Tutorial.',parameters:{type:"OBJECT",properties:{openTab:{type:"STRING",description:"Tab to open or focus.",enum:["home","viewer","results","sequence","ramachandran","peptide","crispr","chemistry","workflow","compute","plugins","assistant","mcp","library"]},toSide:{type:"BOOLEAN",description:"If true, open the tab in a split side pane."},viewportEngine:{type:"STRING",description:"Switch 3D engine between Fast WebGL2 and Mol* Pro.",enum:["webgl2","molstar"]},viewportLayout:{type:"STRING",description:"Set 3D comparison layout.",enum:["overlay","split","reference","mobile"]},renderStyle:{type:"STRING",description:"Set 3D representation style.",enum:["ribbon","trace","pocket"]},colorMode:{type:"STRING",description:"Set 3D coloring mode.",enum:["identity","plddt","bfactor","deviation"]},cameraPreset:{type:"STRING",description:"Move 3D camera to preset.",enum:["overview","active-site","n-terminus","reset"]},sidebarView:{type:"STRING",description:"Switch left sidebar view.",enum:["explorer","library","tools","history"]},openTutorial:{type:"BOOLEAN",description:"Open the interactive Studio guided tutorial."}}}},{name:"manage_project",description:"Create, list, or switch multi-asset research projects; save designed molecules/peptides; split multi-chain/ligand structures into individual parts; or bind a receptor and ligand for docking.",parameters:{type:"OBJECT",properties:{action:{type:"STRING",description:"Project action to perform.",enum:["list","create","switch","add_molecule","split_chains","stage_binding"]},projectId:{type:"STRING",description:"Target project ID when switching."},name:{type:"STRING",description:"Project or molecule name."},description:{type:"STRING",description:"Project description."},template:{type:"STRING",description:"Project starter template.",enum:["blank","structure-compare","ligand-docking","peptide-crispr"]},smiles:{type:"STRING",description:"SMILES string when adding a molecule."},target:{type:"STRING",description:"Which loaded structure to split (reference or mobile).",enum:["reference","mobile"]}},required:["action"]}},{name:"design_molecule_rdkit",description:"Analyze, validate, screen for PAINS/Brenk alerts, or run SMARTS substructure search on a molecule using the in-browser RDKit WASM engine, and optionally save it into the active project.",parameters:{type:"OBJECT",properties:{smiles:{type:"STRING",description:"SMILES or MOL block to analyze/design."},name:{type:"STRING",description:"Molecule label."},smartsQuery:{type:"STRING",description:"Optional SMARTS pattern for substructure matching/highlighting."},saveToProject:{type:"BOOLEAN",description:"Save molecule to the active project."}},required:["smiles"]}},{name:"run_workflow_pipeline",description:"Open Workflow Canvas and inspect, export (Nextflow/Snakemake), or execute a multi-step scientific DAG workflow template.",parameters:{type:"OBJECT",properties:{templateId:{type:"STRING",description:"Workflow template ID.",enum:["tpl-structure-audit","tpl-hit-to-lead","tpl-binder-design","tpl-quantum-ligand"]},action:{type:"STRING",description:"Whether to run, export Nextflow, or export Snakemake.",enum:["run","export_nextflow","export_snakemake"]}},required:["action"]}},{name:"manage_plugins",description:"List all open-source biochemistry plugins & license status, or enable/disable an add-on.",parameters:{type:"OBJECT",properties:{action:{type:"STRING",description:"Plugin action to perform.",enum:["list","enable","disable"]},pluginId:{type:"STRING",description:"Plugin ID (e.g. org.synlexa.autodock-vina)."}},required:["action"]}}],Tp=[...bI,...xI];function yI(e){return`${y3}/${encodeURIComponent(e)}:generateContent`}function Tv(e){const r=[`Active Reference: ${e.refLabel||"none"} (chain=${e.refChain||"unselected"}, sha256=${e.comparison?.reference.sha256??e.refInspect?.sha256??"none"}, confidence=${e.comparison?.reference.confidenceKind??e.refInspect?.confidenceKind??"none"})`,`Active Mobile: ${e.mobLabel||"none"} (chain=${e.mobChain||"unselected"}, sha256=${e.comparison?.mobile.sha256??e.mobInspect?.sha256??"none"}, confidence=${e.comparison?.mobile.confidenceKind??e.mobInspect?.confidenceKind??"none"})`];if(e.comparison){const n=e.comparison.metrics,s=e.comparison.matchedResidues.map(p=>p.mobPlddt).filter(p=>p!==null&&Number.isFinite(p)),i=s.length>0?s.reduce((p,b)=>p+b,0)/s.length:null,c=e.comparison.refDisplayAtoms?.ligands.map(p=>`${p.resName}(${p.chainId}:${p.seqId})`).join(", ")||"none";r.push(`Comparison (${e.comparison.resultId.slice(0,12)}): RMSD=${n.rmsdAngstrom.toFixed(4)} Å across ${n.matchedCaCount} Cα, refCov=${n.refCoverage.numerator}/${n.refCoverage.denominator} (${n.refCoverage.denominatorKind}), mobCov=${n.mobCoverage.numerator}/${n.mobCoverage.denominator}, meanPlddt=${i!==null?i.toFixed(1):"n/a"}, PAE=${n.paeStatus}, ligands=[${c}]`);const d=[...e.comparison.matchedResidues].sort((p,b)=>b.distanceAngstrom-p.distanceAngstrom).slice(0,6);d.length>0&&r.push(`Top Cα Deviations: ${d.map(p=>`${p.resName3}${p.refSeqId}=${p.distanceAngstrom.toFixed(3)}Å${p.mobPlddt!==null?`(pLDDT ${p.mobPlddt.toFixed(1)})`:""}`).join(", ")}`);const f=e.comparison.refContacts??[];if(f.length>0){const p=[...f].sort((b,x)=>b.distanceAngstrom-x.distanceAngstrom).slice(0,6).map(b=>`${b.ligandResName}.${b.ligandAtom}–${b.proteinResName3}${b.proteinSeqId}.${b.proteinAtom}(${b.distanceAngstrom.toFixed(2)}Å)`);r.push(`Active-Site Ligand/Metal Contacts (≤4.5 Å, total=${f.length}): ${p.join(", ")}`)}}if(e.peptide){const n=e.peptide;r.push(`Peptide: len=${n.engineered.length}, mutations=[${n.appliedMutations.map(s=>s.notation).join(",")||"none"}], WT_MW=${n.wildType.mwAverageDa.toFixed(1)} Da, ΔMW=${n.deltas.mwAverageDa.toFixed(2)} Da, pI=${n.engineered.pi.toFixed(2)} (Δ${n.deltas.pi.toFixed(2)}), charge@7.4=${n.engineered.chargeAtPh74.toFixed(2)}, GRAVY=${n.engineered.gravy.toFixed(3)}, 3D_contacts=${n.local3dContacts.slice(0,5).map(s=>`${s.resName3}${s.seqId}(${s.distanceAngstrom.toFixed(2)}Å)`).join(", ")||"none"}`)}if(e.crispr){const n=e.crispr,s=n.pamSites.slice(0,4).map(i=>`${i.nuclease}:${i.pam}(${i.strand},cut=${i.cutBp1},Δ=${i.distanceToTargetCodonBp}bp,GC=${i.gcPercent.toFixed(0)}%)`);r.push(`CRISPR: ${n.geneSymbol} (${n.transcriptId}, ${n.cdsLengthBp} bp), codon=${n.targetCodon.codonIndex1} (${n.targetCodon.wtCodon}/${n.targetCodon.wtAa} -> ${n.targetCodon.editedCodon}/${n.targetCodon.editedAa}, ${n.targetCodon.consequence}), PAMs=${n.pamSites.length} [${s.join("; ")}]`)}if(e.smiles){const n=e.smiles;r.push(`SMILES: ${n.name}, formula=${n.formula}, MW=${n.molecularWeight.toFixed(2)} Da, exactMass=${n.exactMass.toFixed(4)} Da, TPSA=${n.tpsa.toFixed(2)} Ų, cLogP=${n.crippenLogP.toFixed(2)}, HBD=${n.hbd}, HBA=${n.hba}, rotBonds=${n.rotatableBonds}, rings=${n.ringCount}, LipinskiViol=${n.lipinskiViolations}, Veber=${n.veberCompliant?"pass":"fail"}`)}if(e.ramachandran){const n=e.ramachandran,s=n.residues.filter(i=>i.region==="outlier").slice(0,5).map(i=>`${i.resName3}${i.seqId}(φ=${i.phiDeg?.toFixed(1)??"n/a"},ψ=${i.psiDeg?.toFixed(1)??"n/a"})`);r.push(`Ramachandran: chain=${n.chainId}, residues=${n.residueCount}, H/S/L=${n.secondaryCounts.helix}/${n.secondaryCounts.sheet}/${n.secondaryCounts.loop}, favored/allowed/outlier=${n.regionCounts.favored}/${n.regionCounts.allowed}/${n.regionCounts.outlier}, contacts=${n.contactPairs.length}${s.length?`, outliers=[${s.join(", ")}]`:""}`)}return r.join(`
683
683
  `)}const Ev=["You are the autonomous AI scientific assistant inside Synlexa Studio, a Research-Use-Only (RUO) computational biology and chemistry IDE powered by an in-app MCP server.","STRICT RULES:","1. NEVER make diagnostic, therapeutic, clinical-decision, drug-efficacy, or FDA-clearance claims.","2. NEVER fabricate or guess PMIDs, DOIs, ClinicalTrials.gov NCT IDs, p-values, cohorts, or structural numbers.","3. Ground every quantitative statement in the live workspace summary or MCP tool execution outputs (get_workspace_state, run_structure_superposition, analyze_ramachandran, engineer_peptide_mutation, design_crispr_edit, inspect_chemical_smiles, design_molecule_rdkit, manage_project, run_workflow_pipeline, query_local_library).","4. Use your tools like octopus arms: you can inspect the workspace, switch UI tabs/panels/compare modes (`control_app_ui`), organize multi-structure/ligand projects and split chains or stage binding (`manage_project`), design and score molecules (`design_molecule_rdkit`), manage plugins (`manage_plugins`), and run multi-step workflows (`run_workflow_pipeline`). Run tests across rounds to verify inside the UI.","5. Before calling tools, write a brief 1-2 sentence plan/reasoning note so the user sees your thinking process step-by-step.","6. If the user denies permission for an external fetch or remote GPU/workflow tool, respect the denial immediately and continue with local/offline tools or propose alternatives.","7. When the user asks for recent papers, literature context, citations, or registered studies, call `search_scientific_web` and include the exact returned PMID/DOI/NCT ID and sourceUrl.","8. Clearly distinguish source-observed facts, deterministic engine numbers, and model-generated synthesis.","9. Always end or annotate with a concise Research-Use-Only (RUO) reminder.","10. Format responses in clean, well-structured Markdown: use concise section headings (##/###), bullet or numbered lists, GFM pipe tables for multi-item comparisons or structural metrics, fenced code blocks for sequences/SMILES/commands, and [label](url) links for verified references."].join(`
684
684
  `);function Ds(e,r){e?.(r.map(n=>({...n})))}function Mv(e,r,n,s){const i=Date.now(),c={round:r,phase:"thinking",title:`Reasoning (round ${r})`,detail:`Analyzing request with ${n}…`,status:"running",startedAtMs:i};return e.push(c),Ds(s,e),{step:c,startedAtMs:i}}function Wc(e,r){const n=e.indexOf(r);n!==-1&&e.splice(n,1)}function Rv(e){let r=!1;for(const s of e.thoughts){const i=s.trim();i&&(e.thinkingTrace.push(i),e.stepTrace.push({round:e.round,phase:"thinking",title:`${e.thoughtTitle??"Model reasoning"} (round ${e.round})`,detail:i,status:"done",...!r&&e.roundDurationMs?{durationMs:e.roundDurationMs}:{}}),r=!0)}const n=e.preToolRationale?.trim();n&&(e.thinkingTrace.push(n),e.stepTrace.push({round:e.round,phase:"thinking",title:`Pre-tool rationale (round ${e.round})`,detail:n,status:"done",...!r&&e.roundDurationMs?{durationMs:e.roundDurationMs}:{}}))}async function zv(e,r,n){const s=pI(r,n);let i="auto";const d=(e.permissionPolicies??t0())[s.category]??"ask";if(e.sessionApprovedCategories?.has(s.category))i="allowed-session";else if(d==="deny"){i="denied";const g={ok:!1,summary:`Blocked by permission policy (${s.category})`,data:{denied:!0,category:s.category,reason:"Denied by Studio permission policy"}};return e.executedTools.push({name:r,args:n,ok:!1,summary:g.summary,result:g.data,durationMs:0,permissionStatus:i}),e.stepTrace.push({round:e.round,phase:"permission",title:`Blocked: ${s.title}`,detail:g.summary,toolName:r,args:n,ok:!1,status:"error"}),Ds(e.onProgress,e.stepTrace),g}else if(d==="ask"&&e.requestToolPermission){const g={round:e.round,phase:"permission",title:`Permission requested: ${s.title}`,detail:s.detail,toolName:r,args:n,status:"running",startedAtMs:Date.now()};e.stepTrace.push(g),Ds(e.onProgress,e.stepTrace);const _=await e.requestToolPermission({id:`perm-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,toolName:r,category:s.category,title:s.title,detail:s.detail,args:n});if(_==="deny"){i="denied",g.ok=!1,g.status="error",g.detail=`${s.detail} — Denied by user.`;const y={ok:!1,summary:`Permission denied by user for ${r}`,data:{denied:!0,category:s.category,reason:"User denied permission"}};return e.executedTools.push({name:r,args:n,ok:!1,summary:y.summary,result:y.data,durationMs:0,permissionStatus:i}),Ds(e.onProgress,e.stepTrace),y}_==="allow_session"?(i="allowed-session",e.sessionApprovedCategories?.add(s.category),g.ok=!0,g.status="done",g.detail=`${s.detail} — Allowed for this session.`):(i="allowed-once",g.ok=!0,g.status="done",g.detail=`${s.detail} — Allowed once.`),Ds(e.onProgress,e.stepTrace)}const f=Date.now(),p={round:e.round,phase:"tool",title:`${r} · running`,toolName:r,args:n,status:"running",startedAtMs:f};e.stepTrace.push(p),Ds(e.onProgress,e.stepTrace);let b;try{b=await e.executeTool(r,n)}catch(g){b={ok:!1,summary:g instanceof Error?g.message:String(g),data:{error:g instanceof Error?g.message:String(g)}}}const x=Math.max(1,Date.now()-f);return e.executedTools.push({name:r,args:n,ok:b.ok,summary:b.summary,result:b.data,durationMs:x,permissionStatus:i}),p.phase=b.ok?"tool":"error",p.title=`${r} · ${b.ok?"ok":"failed"}`,p.detail=b.summary,p.durationMs=x,p.ok=b.ok,p.status=b.ok?"done":"error",Ds(e.onProgress,e.stepTrace),b}function Ov(e=!0){return e?Tp:Tp.filter(r=>r.name!=="search_scientific_web")}async function tA(e){const r=new Date().toISOString(),n=`agent-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,s=(e.apiKey??"").trim(),i=e.model??ry,c=e.fetchImpl??globalThis.fetch,d=e.transport,f=d?"synlexa-cloud":"gemini-api",p=Ov(e.enableWebSearch!==!1),b=z=>{const O=d3(e.prompt,e.workspace);if(e.onFallbackAction)for(const H of O.actions)e.onFallbackAction(H);const V=z?`[${d?"Synlexa Cloud":"Gemini API"} unavailable: ${z} — using local deterministic Copilot]
685
685
  `:"",P=O.reply.actionTaken?[{name:O.reply.command??"copilot",args:{},ok:!0,summary:O.reply.actionTaken,result:null,permissionStatus:"auto"}]:[],$=P.map((H,Z)=>({round:Z+1,phase:"tool",title:`${H.name} · ok`,detail:H.summary,toolName:String(H.name),ok:!0}));return{id:n,role:"assistant",mode:"local-deterministic-fallback",model:"deterministic-copilot",providerLabel:"Local Deterministic Copilot",text:`${V}${O.reply.text}`,citations:O.reply.citations,thinkingTrace:O.reply.actionTaken?[`Matched local deterministic command: ${O.reply.actionTaken}`]:[],stepTrace:$,executedTools:P,timestampUtc:r,error:z}};if(!s&&!d||typeof c!="function")return b();const x=[];for(const z of e.history.slice(-8))x.push({role:z.role==="user"?"user":"model",parts:[{text:z.text}]});x.push({role:"user",parts:[{text:`[LIVE WORKSPACE STATE]
@@ -755,7 +755,7 @@ rule all:
755
755
  ${s.join(`
756
756
 
757
757
  `)}
758
- `}const zD="2024-11-05",py={name:"synlexa-studio-mcp",version:"0.4.4",description:"Deterministic computational biology, structural superposition, CRISPR, SMILES, and scientific web MCP server (RUO)."},eh=[],gy=new Set;function J3(){for(const e of gy)e()}function uA(){return[...eh]}function OD(){eh.length=0,J3()}function PD(e){return gy.add(e),()=>gy.delete(e)}function Z3(e){eh.unshift(e),eh.length>100&&(eh.length=100),J3()}function $D(e){const r={};for(const[n,s]of Object.entries(e.parameters.properties)){const i={type:s.type.toLowerCase(),description:s.description};s.enum&&(i.enum=s.enum),s.items&&(i.items={type:s.items.type.toLowerCase()}),r[n]=i}return{type:"object",properties:r,required:e.parameters.required??[]}}const Lc=Tp.map(e=>({name:e.name,description:e.description,inputSchema:$D(e)}));function by(){const e=[];for(const r of Jd())if(!(r.builtin||!r.enabled||!r.mcpTools))for(const n of r.mcpTools)e.push({name:n.name,description:`[Plugin: ${r.name}] ${n.description}`,inputSchema:n.inputSchema});return[...Lc,...e]}const Bd=[{uri:"synlexa://workspace/summary",name:"Live Workspace Summary",description:"Overview of loaded structures, RMSD, coverage, active-site contacts, and workbench state.",mimeType:"application/json"},{uri:"synlexa://workspace/comparison",name:"Kabsch Superposition Result",description:"Full ComparisonResultV1 metrics, 4x4 rigid transform matrix, and top deviating residues.",mimeType:"application/json"},{uri:"synlexa://workspace/peptide",name:"Peptide Engineering State",description:"Wild-type vs engineered biophysical descriptors, pH titration delta, and 5.0 Å 3D contacts.",mimeType:"application/json"},{uri:"synlexa://workspace/crispr",name:"CRISPR & Coding Transcript Analysis",description:"Codon translation consequence and SpCas9/SaCas9/Cas12a PAM site scan.",mimeType:"application/json"},{uri:"synlexa://workspace/chemistry",name:"Ligands & SMILES Descriptors",description:"Formula, molecular weight, TPSA, cLogP, Lipinski/Veber metrics, and 2D layout.",mimeType:"application/json"},{uri:"synlexa://workspace/ramachandran",name:"Ramachandran Geometry & Contacts",description:"Backbone (φ, ψ) angles, secondary structure fractions, and Cα–Cα contact pairs.",mimeType:"application/json"},{uri:"synlexa://library/catalog",name:"Local Molecule Library Catalog",description:"Structures, ligands, and sequences saved in IndexedDB with SHA-256 provenance.",mimeType:"application/json"},{uri:"synlexa://vault/status",name:"Encrypted BYOK Vault Status",description:"Non-secret metadata and backend status for local state.vscdb key storage.",mimeType:"application/json"}],dA=[{name:"structural-deviation-audit",description:"Audit Kabsch RMSD, coverage denominators, PAE uncertainty, and top deviating residues (RUO).",arguments:[{name:"focus_chain",description:"Chain ID to examine (e.g. A)",required:!1}]},{name:"active-site-mutation-scan",description:"Evaluate a point mutation in the active site along with 5.0 Å local 3D contacts.",arguments:[{name:"mutation",description:"Mutation notation such as H94A",required:!0}]},{name:"crispr-codon-pam-plan",description:"Inspect coding codon edit consequence and enumerate SpCas9/Cas12a PAM windows.",arguments:[{name:"transcript",description:"RefSeq transcript ID (e.g. NM_000067.3)",required:!0}]},{name:"literature-evidence-check",description:"Query Europe PMC and ClinicalTrials.gov via search_scientific_web with verified PMIDs/NCTs.",arguments:[{name:"topic",description:"Biomarker, protein, or ligand query",required:!0}]}];function Ii(e,r,n="all",s=10){const i=Math.max(1,Math.min(50,s)),c=f=>n==="all"||n===f,d={ruoNotice:"For research and development use. Not for diagnostic or treatment decisions.",capturedAtUtc:new Date().toISOString()};return c("comparison")&&(d.structures={refLabel:e.refLabel,refChain:e.refChain,refSha256:e.comparison?.reference.sha256??e.refInspect?.sha256??null,refConfidenceKind:e.comparison?.reference.confidenceKind??e.refInspect?.confidenceKind??null,mobLabel:e.mobLabel,mobChain:e.mobChain,mobSha256:e.comparison?.mobile.sha256??e.mobInspect?.sha256??null,mobConfidenceKind:e.comparison?.mobile.confidenceKind??e.mobInspect?.confidenceKind??null,comparison:e.comparison?{resultId:e.comparison.resultId,metrics:e.comparison.metrics,topDeviatingResidues:[...e.comparison.matchedResidues].sort((f,p)=>p.distanceAngstrom-f.distanceAngstrom).slice(0,i),ligands:e.comparison.refDisplayAtoms?.ligands.map(f=>({resName:f.resName,chainId:f.chainId,seqId:f.seqId,atomCount:f.atoms.length}))}:null}),c("contacts")&&(d.activeSiteContacts=(e.comparison?.refContacts??[]).slice(0,i)),c("peptide")&&(d.peptide=e.peptide?{appliedMutations:e.peptide.appliedMutations,wildType:e.peptide.wildType,engineered:e.peptide.engineered,deltas:e.peptide.deltas,local3dContacts:e.peptide.local3dContacts.slice(0,i)}:null),c("crispr")&&(d.crispr=e.crispr?{transcriptId:e.crispr.transcriptId,geneSymbol:e.crispr.geneSymbol,cdsLengthBp:e.crispr.cdsLengthBp,targetCodon:e.crispr.targetCodon,pamSitesCount:e.crispr.pamSites.length,topPamSites:e.crispr.pamSites.slice(0,i)}:null),c("chemistry")&&(d.chemistry=e.smiles?{name:e.smiles.name,smiles:e.smiles.smiles,formula:e.smiles.formula,molecularWeight:e.smiles.molecularWeight,exactMass:e.smiles.exactMass,tpsa:e.smiles.tpsa,crippenLogP:e.smiles.crippenLogP,hbd:e.smiles.hbd,hba:e.smiles.hba,rotatableBonds:e.smiles.rotatableBonds,ringCount:e.smiles.ringCount,lipinskiViolations:e.smiles.lipinskiViolations,veberCompliant:e.smiles.veberCompliant}:null),c("ramachandran")&&(d.ramachandran=e.ramachandran?{chainId:e.ramachandran.chainId,residueCount:e.ramachandran.residueCount,secondaryCounts:e.ramachandran.secondaryCounts,regionCounts:e.ramachandran.regionCounts,contactPairsCount:e.ramachandran.contactPairs.length,outliers:e.ramachandran.residues.filter(f=>f.region==="outlier").slice(0,i)}:null),c("library")&&(d.library=r.slice(0,i).map(f=>({id:f.id,kind:f.kind,name:f.name,format:f.format,sha256:f.sha256,sizeBytes:f.sizeBytes,source:f.source}))),d}function ID(e,r,n){let s;switch(e){case"synlexa://workspace/summary":s=Ii(r,n,"all",10);break;case"synlexa://workspace/comparison":s=Ii(r,n,"comparison",25);break;case"synlexa://workspace/peptide":s=Ii(r,n,"peptide",20);break;case"synlexa://workspace/crispr":s=Ii(r,n,"crispr",20);break;case"synlexa://workspace/chemistry":s=Ii(r,n,"chemistry",20);break;case"synlexa://workspace/ramachandran":s=Ii(r,n,"ramachandran",25);break;case"synlexa://library/catalog":s=Ii(r,n,"library",50);break;case"synlexa://vault/status":s=Zo();break;default:throw new Error(`Unknown MCP resource URI: ${e}`)}return{contents:[{uri:e,mimeType:"application/json",text:JSON.stringify(s,null,2)}]}}async function eE(e,r,n,s="internal-ai-agent"){const i=typeof performance<"u"?performance.now():Date.now();let c;try{c=await e.executeTool(r,n)}catch(f){const p=f instanceof Error?f.message:String(f);c={ok:!1,summary:p,data:{error:p}}}const d=typeof performance<"u"?performance.now():Date.now();return Z3({id:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,timestampUtc:new Date().toISOString(),caller:s,method:"tools/call",target:r,ok:c.ok,durationMs:Math.max(0,Math.round(d-i)),summary:c.summary,requestPayload:n,responsePreview:c.data}),c}async function hA(e,r,n="mcp-playground"){const s=e.id??null,i=typeof performance<"u"?performance.now():Date.now(),c=e.params??{};try{switch(e.method){case"initialize":return{jsonrpc:"2.0",id:s,result:{protocolVersion:zD,serverInfo:py,capabilities:{tools:{listChanged:!1},resources:{subscribe:!1,listChanged:!1},prompts:{listChanged:!1}}}};case"ping":return{jsonrpc:"2.0",id:s,result:{}};case"tools/list":return{jsonrpc:"2.0",id:s,result:{tools:by()}};case"tools/call":{const d=String(c.name??""),f=c.arguments&&typeof c.arguments=="object"?c.arguments:{};if(!by().some(b=>b.name===d))return{jsonrpc:"2.0",id:s,error:{code:-32601,message:`Unknown MCP tool: ${d}`}};const p=await eE(r,d,f,n);return{jsonrpc:"2.0",id:s,result:{isError:!p.ok,content:[{type:"text",text:JSON.stringify({summary:p.summary,data:p.data},null,2)}]}}}case"resources/list":return{jsonrpc:"2.0",id:s,result:{resources:Bd}};case"resources/read":{const d=String(c.uri??""),f=ID(d,r.workspace,r.libraryItems),p=typeof performance<"u"?performance.now():Date.now();return Z3({id:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,timestampUtc:new Date().toISOString(),caller:n,method:"resources/read",target:d,ok:!0,durationMs:Math.max(0,Math.round(p-i)),summary:`Read resource ${d}`,requestPayload:c}),{jsonrpc:"2.0",id:s,result:f}}case"prompts/list":return{jsonrpc:"2.0",id:s,result:{prompts:dA}};case"prompts/get":{const d=String(c.name??""),f=dA.find(b=>b.name===d);if(!f)return{jsonrpc:"2.0",id:s,error:{code:-32602,message:`Unknown MCP prompt: ${d}`}};const p=c.arguments&&typeof c.arguments=="object"?c.arguments:{};return{jsonrpc:"2.0",id:s,result:{description:f.description,messages:[{role:"user",content:{type:"text",text:`[Synlexa Studio RUO MCP Prompt: ${f.name}] Arguments: ${JSON.stringify(p)}. Inspect synlexa://workspace/summary first, use deterministic Studio MCP tools, and cite verified provenance only.`}}]}}}default:return{jsonrpc:"2.0",id:s,error:{code:-32601,message:`Method not found: ${e.method}`}}}}catch(d){return{jsonrpc:"2.0",id:s,error:{code:-32e3,message:d instanceof Error?d.message:String(d)}}}}function DD(e=4179){return{claudeDesktopJson:JSON.stringify({mcpServers:{"synlexa-studio":{command:"synlexa-studio",args:["mcp","--stdio"]}}},null,2),claudeCodeCmd:"claude mcp add synlexa-studio -- synlexa-studio mcp --stdio",codexCliCmd:"codex mcp add synlexa-studio -- synlexa-studio mcp --stdio",codexConfigToml:`[mcp_servers.synlexa_studio]
758
+ `}const zD="2024-11-05",py={name:"synlexa-studio-mcp",version:"0.4.5",description:"Deterministic computational biology, structural superposition, CRISPR, SMILES, and scientific web MCP server (RUO)."},eh=[],gy=new Set;function J3(){for(const e of gy)e()}function uA(){return[...eh]}function OD(){eh.length=0,J3()}function PD(e){return gy.add(e),()=>gy.delete(e)}function Z3(e){eh.unshift(e),eh.length>100&&(eh.length=100),J3()}function $D(e){const r={};for(const[n,s]of Object.entries(e.parameters.properties)){const i={type:s.type.toLowerCase(),description:s.description};s.enum&&(i.enum=s.enum),s.items&&(i.items={type:s.items.type.toLowerCase()}),r[n]=i}return{type:"object",properties:r,required:e.parameters.required??[]}}const Lc=Tp.map(e=>({name:e.name,description:e.description,inputSchema:$D(e)}));function by(){const e=[];for(const r of Jd())if(!(r.builtin||!r.enabled||!r.mcpTools))for(const n of r.mcpTools)e.push({name:n.name,description:`[Plugin: ${r.name}] ${n.description}`,inputSchema:n.inputSchema});return[...Lc,...e]}const Bd=[{uri:"synlexa://workspace/summary",name:"Live Workspace Summary",description:"Overview of loaded structures, RMSD, coverage, active-site contacts, and workbench state.",mimeType:"application/json"},{uri:"synlexa://workspace/comparison",name:"Kabsch Superposition Result",description:"Full ComparisonResultV1 metrics, 4x4 rigid transform matrix, and top deviating residues.",mimeType:"application/json"},{uri:"synlexa://workspace/peptide",name:"Peptide Engineering State",description:"Wild-type vs engineered biophysical descriptors, pH titration delta, and 5.0 Å 3D contacts.",mimeType:"application/json"},{uri:"synlexa://workspace/crispr",name:"CRISPR & Coding Transcript Analysis",description:"Codon translation consequence and SpCas9/SaCas9/Cas12a PAM site scan.",mimeType:"application/json"},{uri:"synlexa://workspace/chemistry",name:"Ligands & SMILES Descriptors",description:"Formula, molecular weight, TPSA, cLogP, Lipinski/Veber metrics, and 2D layout.",mimeType:"application/json"},{uri:"synlexa://workspace/ramachandran",name:"Ramachandran Geometry & Contacts",description:"Backbone (φ, ψ) angles, secondary structure fractions, and Cα–Cα contact pairs.",mimeType:"application/json"},{uri:"synlexa://library/catalog",name:"Local Molecule Library Catalog",description:"Structures, ligands, and sequences saved in IndexedDB with SHA-256 provenance.",mimeType:"application/json"},{uri:"synlexa://vault/status",name:"Encrypted BYOK Vault Status",description:"Non-secret metadata and backend status for local state.vscdb key storage.",mimeType:"application/json"}],dA=[{name:"structural-deviation-audit",description:"Audit Kabsch RMSD, coverage denominators, PAE uncertainty, and top deviating residues (RUO).",arguments:[{name:"focus_chain",description:"Chain ID to examine (e.g. A)",required:!1}]},{name:"active-site-mutation-scan",description:"Evaluate a point mutation in the active site along with 5.0 Å local 3D contacts.",arguments:[{name:"mutation",description:"Mutation notation such as H94A",required:!0}]},{name:"crispr-codon-pam-plan",description:"Inspect coding codon edit consequence and enumerate SpCas9/Cas12a PAM windows.",arguments:[{name:"transcript",description:"RefSeq transcript ID (e.g. NM_000067.3)",required:!0}]},{name:"literature-evidence-check",description:"Query Europe PMC and ClinicalTrials.gov via search_scientific_web with verified PMIDs/NCTs.",arguments:[{name:"topic",description:"Biomarker, protein, or ligand query",required:!0}]}];function Ii(e,r,n="all",s=10){const i=Math.max(1,Math.min(50,s)),c=f=>n==="all"||n===f,d={ruoNotice:"For research and development use. Not for diagnostic or treatment decisions.",capturedAtUtc:new Date().toISOString()};return c("comparison")&&(d.structures={refLabel:e.refLabel,refChain:e.refChain,refSha256:e.comparison?.reference.sha256??e.refInspect?.sha256??null,refConfidenceKind:e.comparison?.reference.confidenceKind??e.refInspect?.confidenceKind??null,mobLabel:e.mobLabel,mobChain:e.mobChain,mobSha256:e.comparison?.mobile.sha256??e.mobInspect?.sha256??null,mobConfidenceKind:e.comparison?.mobile.confidenceKind??e.mobInspect?.confidenceKind??null,comparison:e.comparison?{resultId:e.comparison.resultId,metrics:e.comparison.metrics,topDeviatingResidues:[...e.comparison.matchedResidues].sort((f,p)=>p.distanceAngstrom-f.distanceAngstrom).slice(0,i),ligands:e.comparison.refDisplayAtoms?.ligands.map(f=>({resName:f.resName,chainId:f.chainId,seqId:f.seqId,atomCount:f.atoms.length}))}:null}),c("contacts")&&(d.activeSiteContacts=(e.comparison?.refContacts??[]).slice(0,i)),c("peptide")&&(d.peptide=e.peptide?{appliedMutations:e.peptide.appliedMutations,wildType:e.peptide.wildType,engineered:e.peptide.engineered,deltas:e.peptide.deltas,local3dContacts:e.peptide.local3dContacts.slice(0,i)}:null),c("crispr")&&(d.crispr=e.crispr?{transcriptId:e.crispr.transcriptId,geneSymbol:e.crispr.geneSymbol,cdsLengthBp:e.crispr.cdsLengthBp,targetCodon:e.crispr.targetCodon,pamSitesCount:e.crispr.pamSites.length,topPamSites:e.crispr.pamSites.slice(0,i)}:null),c("chemistry")&&(d.chemistry=e.smiles?{name:e.smiles.name,smiles:e.smiles.smiles,formula:e.smiles.formula,molecularWeight:e.smiles.molecularWeight,exactMass:e.smiles.exactMass,tpsa:e.smiles.tpsa,crippenLogP:e.smiles.crippenLogP,hbd:e.smiles.hbd,hba:e.smiles.hba,rotatableBonds:e.smiles.rotatableBonds,ringCount:e.smiles.ringCount,lipinskiViolations:e.smiles.lipinskiViolations,veberCompliant:e.smiles.veberCompliant}:null),c("ramachandran")&&(d.ramachandran=e.ramachandran?{chainId:e.ramachandran.chainId,residueCount:e.ramachandran.residueCount,secondaryCounts:e.ramachandran.secondaryCounts,regionCounts:e.ramachandran.regionCounts,contactPairsCount:e.ramachandran.contactPairs.length,outliers:e.ramachandran.residues.filter(f=>f.region==="outlier").slice(0,i)}:null),c("library")&&(d.library=r.slice(0,i).map(f=>({id:f.id,kind:f.kind,name:f.name,format:f.format,sha256:f.sha256,sizeBytes:f.sizeBytes,source:f.source}))),d}function ID(e,r,n){let s;switch(e){case"synlexa://workspace/summary":s=Ii(r,n,"all",10);break;case"synlexa://workspace/comparison":s=Ii(r,n,"comparison",25);break;case"synlexa://workspace/peptide":s=Ii(r,n,"peptide",20);break;case"synlexa://workspace/crispr":s=Ii(r,n,"crispr",20);break;case"synlexa://workspace/chemistry":s=Ii(r,n,"chemistry",20);break;case"synlexa://workspace/ramachandran":s=Ii(r,n,"ramachandran",25);break;case"synlexa://library/catalog":s=Ii(r,n,"library",50);break;case"synlexa://vault/status":s=Zo();break;default:throw new Error(`Unknown MCP resource URI: ${e}`)}return{contents:[{uri:e,mimeType:"application/json",text:JSON.stringify(s,null,2)}]}}async function eE(e,r,n,s="internal-ai-agent"){const i=typeof performance<"u"?performance.now():Date.now();let c;try{c=await e.executeTool(r,n)}catch(f){const p=f instanceof Error?f.message:String(f);c={ok:!1,summary:p,data:{error:p}}}const d=typeof performance<"u"?performance.now():Date.now();return Z3({id:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,timestampUtc:new Date().toISOString(),caller:s,method:"tools/call",target:r,ok:c.ok,durationMs:Math.max(0,Math.round(d-i)),summary:c.summary,requestPayload:n,responsePreview:c.data}),c}async function hA(e,r,n="mcp-playground"){const s=e.id??null,i=typeof performance<"u"?performance.now():Date.now(),c=e.params??{};try{switch(e.method){case"initialize":return{jsonrpc:"2.0",id:s,result:{protocolVersion:zD,serverInfo:py,capabilities:{tools:{listChanged:!1},resources:{subscribe:!1,listChanged:!1},prompts:{listChanged:!1}}}};case"ping":return{jsonrpc:"2.0",id:s,result:{}};case"tools/list":return{jsonrpc:"2.0",id:s,result:{tools:by()}};case"tools/call":{const d=String(c.name??""),f=c.arguments&&typeof c.arguments=="object"?c.arguments:{};if(!by().some(b=>b.name===d))return{jsonrpc:"2.0",id:s,error:{code:-32601,message:`Unknown MCP tool: ${d}`}};const p=await eE(r,d,f,n);return{jsonrpc:"2.0",id:s,result:{isError:!p.ok,content:[{type:"text",text:JSON.stringify({summary:p.summary,data:p.data},null,2)}]}}}case"resources/list":return{jsonrpc:"2.0",id:s,result:{resources:Bd}};case"resources/read":{const d=String(c.uri??""),f=ID(d,r.workspace,r.libraryItems),p=typeof performance<"u"?performance.now():Date.now();return Z3({id:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,timestampUtc:new Date().toISOString(),caller:n,method:"resources/read",target:d,ok:!0,durationMs:Math.max(0,Math.round(p-i)),summary:`Read resource ${d}`,requestPayload:c}),{jsonrpc:"2.0",id:s,result:f}}case"prompts/list":return{jsonrpc:"2.0",id:s,result:{prompts:dA}};case"prompts/get":{const d=String(c.name??""),f=dA.find(b=>b.name===d);if(!f)return{jsonrpc:"2.0",id:s,error:{code:-32602,message:`Unknown MCP prompt: ${d}`}};const p=c.arguments&&typeof c.arguments=="object"?c.arguments:{};return{jsonrpc:"2.0",id:s,result:{description:f.description,messages:[{role:"user",content:{type:"text",text:`[Synlexa Studio RUO MCP Prompt: ${f.name}] Arguments: ${JSON.stringify(p)}. Inspect synlexa://workspace/summary first, use deterministic Studio MCP tools, and cite verified provenance only.`}}]}}}default:return{jsonrpc:"2.0",id:s,error:{code:-32601,message:`Method not found: ${e.method}`}}}}catch(d){return{jsonrpc:"2.0",id:s,error:{code:-32e3,message:d instanceof Error?d.message:String(d)}}}}function DD(e=4179){return{claudeDesktopJson:JSON.stringify({mcpServers:{"synlexa-studio":{command:"synlexa-studio",args:["mcp","--stdio"]}}},null,2),claudeCodeCmd:"claude mcp add synlexa-studio -- synlexa-studio mcp --stdio",codexCliCmd:"codex mcp add synlexa-studio -- synlexa-studio mcp --stdio",codexConfigToml:`[mcp_servers.synlexa_studio]
759
759
  command = "synlexa-studio"
760
760
  args = ["mcp", "--stdio"]`,httpEndpointJson:JSON.stringify({mcpServers:{"synlexa-studio-http":{url:`http://127.0.0.1:${e}/mcp`,transport:"http"}}},null,2)}}const mA=[{source:"pinned-reference",sourceType:"pinned_fixture_citation",identifier:"PDB:3HS4",pmid:null,pmcid:null,doi:"10.2210/pdb3HS4/pdb",nctId:null,title:"Crystal structure of human carbonic anhydrase II complexed with acetazolamide (1.10 Å, PDB 3HS4)",authorsOrSponsor:"Sjoblom et al.",journalOrStatus:"RCSB Protein Data Bank (CC0-1.0)",yearOrPhase:"2009 / rev 2025-09-25",snippet:"Bundled SHA-256 verified reference structure 3HS4.cif in Synlexa Studio local fixtures.",sourceUrl:"https://www.rcsb.org/structure/3HS4",extractionMethod:"pinned-manifest-record"},{source:"pinned-reference",sourceType:"pinned_fixture_citation",identifier:"AF-P00918-F1",pmid:null,pmcid:null,doi:null,nctId:null,title:"AlphaFold Protein Structure Database prediction for Human Carbonic Anhydrase 2 (UniProt P00918, v6)",authorsOrSponsor:"Jumper et al. / Varadi et al. (EMBL-EBI / Google DeepMind)",journalOrStatus:"AlphaFold DB v6 (CC-BY-4.0)",yearOrPhase:"2025-08-01",snippet:"Bundled SHA-256 verified model AF-P00918-F1-model_v6.cif and 260x260 PAE JSON.",sourceUrl:"https://alphafold.ebi.ac.uk/entry/P00918",extractionMethod:"pinned-manifest-record"}];function In(e){if(typeof e!="string")return null;const r=e.trim();return r.length>0?r:null}function tE(e,r=320){if(!e)return null;const n=e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return n.length<=r?n:`${n.slice(0,r-1)}…`}async function qD(e,r,n,s,i){const c=`https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=${encodeURIComponent(e)}&format=json&resultType=core&pageSize=${r}`,d=await n(c,{signal:i});if(!d.ok)throw new Error(`Europe PMC returned HTTP ${d.status}`);const f=await d.json();return(Array.isArray(f?.resultList?.result)?f.resultList.result:[]).map(b=>{const x=In(b.pmid),g=In(b.pmcid),_=In(b.doi),y=In(b.id)??x??g??_??"epmc-record",S=In(b.source)??"MED",k=S==="PPR",E=x?`https://pubmed.ncbi.nlm.nih.gov/${encodeURIComponent(x)}/`:g?`https://europepmc.org/article/PMC/${encodeURIComponent(g)}`:_?`https://doi.org/${_}`:`https://europepmc.org/article/${encodeURIComponent(S)}/${encodeURIComponent(y)}`;return{source:"europepmc",sourceType:k?"preprint":"peer_reviewed_literature",identifier:x?`PMID:${x}`:g?`PMCID:${g}`:_?`DOI:${_}`:y,pmid:x,pmcid:g,doi:_,nctId:null,title:In(b.title)??"Untitled Europe PMC record",authorsOrSponsor:In(b.authorString),journalOrStatus:In(b.journalTitle)??In(b.bookOrReportDetails?.toString?.()),yearOrPhase:In(b.pubYear),snippet:tE(In(b.abstractText)),sourceUrl:E,retrievedAtUtc:s,extractionMethod:"europepmc-rest-api"}})}async function LD(e,r,n,s,i){const c=`https://clinicaltrials.gov/api/v2/studies?query.term=${encodeURIComponent(e)}&pageSize=${r}`,d=await n(c,{signal:i});if(!d.ok)throw new Error(`ClinicalTrials.gov returned HTTP ${d.status}`);const f=await d.json();return(Array.isArray(f?.studies)?f.studies:[]).map(b=>{const x=b.protocolSection?.identificationModule,g=b.protocolSection?.statusModule,_=b.protocolSection?.designModule,y=b.protocolSection?.descriptionModule,S=In(x?.nctId)??"NCT_UNKNOWN",k=Array.isArray(_?.phases)&&_.phases.length>0?_.phases.join(", "):null,E=Array.isArray(b.protocolSection?.conditionsModule?.conditions)?b.protocolSection.conditionsModule.conditions.slice(0,3).join(", "):null;return{source:"clinicaltrials",sourceType:"trial_registry",identifier:S,pmid:null,pmcid:null,doi:null,nctId:S,title:In(x?.briefTitle)??`ClinicalTrials.gov study ${S}`,authorsOrSponsor:In(x?.organization?.fullName),journalOrStatus:In(g?.overallStatus),yearOrPhase:[k,In(g?.startDateStruct?.date)].filter(Boolean).join(" · ")||null,snippet:tE(In(y?.briefSummary)??E),sourceUrl:`https://clinicaltrials.gov/study/${encodeURIComponent(S)}`,retrievedAtUtc:s,extractionMethod:"clinicaltrials-gov-apiv2"}})}async function UD(e,r={}){const n=e.trim(),s=r.scope??"all",i=Math.max(1,Math.min(8,r.limit??5)),c=new Date().toISOString(),d=[];if(!n)throw new Error("Web search query must not be empty.");const f=r.fetchImpl??globalThis.fetch;if(!!r.offline||typeof navigator<"u"&&navigator.onLine===!1||typeof f!="function"){const g=n.toLowerCase().split(/\s+/).filter(Boolean),_=mA.filter(y=>{const S=`${y.identifier} ${y.title} ${y.snippet??""}`.toLowerCase();return g.some(k=>S.includes(k))}).map(y=>({...y,retrievedAtUtc:c}));return{query:n,scope:s,origin:"offline-fallback",retrievedAtUtc:c,hits:_,warnings:["Offline mode or unavailable network: returned pinned local citations only."]}}const b=[],x=[];if((s==="all"||s==="literature")&&x.push(qD(n,i,f,c,r.signal).then(g=>{b.push(...g)}).catch(g=>{d.push(g instanceof Error?g.message:String(g))})),(s==="all"||s==="trials")&&x.push(LD(n,Math.min(4,i),f,c,r.signal).then(g=>{b.push(...g)}).catch(g=>{d.push(g instanceof Error?g.message:String(g))})),await Promise.all(x),b.length===0&&d.length>0){const g=n.toLowerCase().split(/\s+/).filter(Boolean),_=mA.filter(y=>{const S=`${y.identifier} ${y.title} ${y.snippet??""}`.toLowerCase();return g.some(k=>S.includes(k))}).map(y=>({...y,retrievedAtUtc:c}));return{query:n,scope:s,origin:"offline-fallback",retrievedAtUtc:c,hits:_,warnings:d}}return{query:n,scope:s,origin:"live-network",retrievedAtUtc:c,hits:b,warnings:d}}const zc={uiScale:1,guidedMode:!0,restoreTabs:!0,autoSaveImports:!0,confirmDeletes:!0,loadDemoOnStart:!0,viewer:{defaultStyle:"ribbon",defaultColorMode:"identity",defaultLayout:"overlay",embedPngInReports:!0}},nE=.85,sE=1.35,aE=.05,rE="synlexa.studio.settings.v2",xy=new Set;function Wv(e){return Number.isFinite(e)?Math.round(Math.min(sE,Math.max(nE,e))*100)/100:1}function BD(){try{const e=localStorage.getItem(rE);if(!e)return zc;const r=JSON.parse(e);return{...zc,...r,uiScale:Wv(r.uiScale??1),viewer:{...zc.viewer,...r.viewer??{}}}}catch{return zc}}let th=typeof localStorage<"u"?BD():zc;function Xv(){return th}function Qv(e){const r=typeof e=="function"?e(th):{...th,...e};r.uiScale=Wv(r.uiScale),th=r;try{localStorage.setItem(rE,JSON.stringify(r))}catch{}Jv(r.uiScale);for(const n of xy)n(r);return r}function GD(){return Qv(zc)}function Jv(e){typeof document>"u"||(document.documentElement.style.fontSize=`${16*Wv(e)}px`)}function Cx(e){const r=Xv();Qv({uiScale:e===0?1:r.uiScale+e*aE})}function Zv(){const[e,r]=C.useState(th);C.useEffect(()=>(xy.add(r),()=>{xy.delete(r)}),[]);const n=C.useCallback(Qv,[]);return[e,n]}const HD="synlexa_studio_library",zp="items",Ah=new Map,yy=new Set;function jh(){for(const e of yy)e()}function r0(e){return yy.add(e),()=>yy.delete(e)}let Wf=null;function Th(){return Wf||(Wf=new Promise(e=>{if(typeof indexedDB>"u")return e(null);try{const r=indexedDB.open(HD,1);r.onupgradeneeded=()=>{const n=r.result;n.objectStoreNames.contains(zp)||n.createObjectStore(zp,{keyPath:"id"}).createIndex("sha256","sha256",{unique:!1})},r.onsuccess=()=>e(r.result),r.onerror=()=>e(null)}catch{e(null)}}),Wf)}function Eh(e,r,n){return new Promise((s,i)=>{const c=e.transaction(zp,r),d=n(c.objectStore(zp));d.onsuccess=()=>s(d.result),d.onerror=()=>i(d.error)})}function iE(){const e=new Uint8Array(8);return globalThis.crypto?.getRandomValues?.(e),`lib_${Date.now().toString(36)}_${Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}`}async function nu(){const e=await Th();return(e?await Eh(e,"readonly",n=>n.getAll()):Array.from(Ah.values())).sort((n,s)=>n.favorite!==s.favorite?n.favorite?-1:1:(s.lastOpenedAtUtc??s.updatedAtUtc).localeCompare(n.lastOpenedAtUtc??n.updatedAtUtc))}async function oE(e){const r=await Th();return r?await Eh(r,"readonly",n=>n.get(e))??null:Ah.get(e)??null}async function e1(e){const r=await Th();r?await Eh(r,"readwrite",n=>n.put(e)):Ah.set(e.id,e)}async function t1(e){const r=await Jc(e.content),n=(await nu()).find(c=>c.sha256===r&&c.kind===e.kind);if(n)return{item:n,duplicate:!0};const s=new Date().toISOString(),i={...e,id:iE(),sha256:r,sizeBytes:new TextEncoder().encode(e.content).byteLength,tags:e.tags??[],notes:e.notes??"",favorite:e.favorite??!1,createdAtUtc:s,updatedAtUtc:s,lastOpenedAtUtc:null};return await e1(i),jh(),{item:i,duplicate:!1}}async function n1(e,r){const n=await oE(e);if(!n)return null;const s={...n,...r};return r.content!==void 0&&r.content!==n.content&&(s.sha256=await Jc(r.content),s.sizeBytes=new TextEncoder().encode(r.content).byteLength,s.source={...n.source,origin:"manual"}),r.lastOpenedAtUtc===void 0&&(s.updatedAtUtc=new Date().toISOString()),await e1(s),jh(),s}async function FD(e){const r=await oE(e);if(!r)return null;const n=new Date().toISOString(),s={...r,id:iE(),name:`${r.name} (copy)`,favorite:!1,createdAtUtc:n,updatedAtUtc:n,lastOpenedAtUtc:null};return await e1(s),jh(),s}async function VD(e){const r=await Th();for(const n of e)r?await Eh(r,"readwrite",s=>s.delete(n)):Ah.delete(n);jh()}async function KD(){const e=await Th();e?await Eh(e,"readwrite",r=>r.clear()):Ah.clear(),jh()}async function lE(e,r){const n=await nu();return{format:"synlexa.library.v1",exportedAtUtc:new Date().toISOString(),disclaimer:e,items:r?n.filter(s=>r.includes(s.id)):n}}async function YD(e){const r=JSON.parse(e);if(r.format!=="synlexa.library.v1"||!Array.isArray(r.items))throw new Error('Not a Synlexa library export (expected format "synlexa.library.v1").');let n=0;for(const s of r.items){if(!s||typeof s.content!="string"||typeof s.name!="string")continue;const{duplicate:i}=await t1({kind:s.kind,name:s.name,format:s.format,content:s.content,paeJson:s.paeJson??null,tags:s.tags,notes:s.notes,favorite:s.favorite,source:s.source});i||n++}return n}function Uc(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function WD(e){const r=e.toLowerCase();return/\.(cif|mmcif)$/.test(r)?{kind:"structure",format:"cif"}:/\.(pdb|ent)$/.test(r)?{kind:"structure",format:"pdb"}:/\.smi$/.test(r)?{kind:"compound",format:"smiles"}:/\.(fasta|fa|faa)$/.test(r)?{kind:"sequence",format:"fasta"}:null}class kn extends Error{code;constructor(r,n){super(n),this.name="BundleValidationError",this.code=r}}const XD=new TextEncoder;async function hp(e){return Jc(XD.encode(e))}function QD(e){if(typeof e!="string"||e.length===0)throw new kn("ERR_BUNDLE_PATH_TRAVERSAL","Bundle file path must be a non-empty relative string.");if(e.includes("\0")||e.includes("\\"))throw new kn("ERR_BUNDLE_PATH_TRAVERSAL",`Invalid path characters in "${e}".`);if(/%2e|%2f|%5c/i.test(e))throw new kn("ERR_BUNDLE_PATH_TRAVERSAL",`Encoded traversal characters are not allowed in "${e}".`);if(e.startsWith("/")||/^[A-Za-z]:/.test(e))throw new kn("ERR_BUNDLE_PATH_TRAVERSAL",`Absolute paths are prohibited in bundle: "${e}".`);const r=e.split("/");for(const n of r){if(n===""||n==="."||n==="..")throw new kn("ERR_BUNDLE_PATH_TRAVERSAL",`Path traversal or empty segment rejected: "${e}".`);if(!/^[A-Za-z0-9._-]+$/.test(n))throw new kn("ERR_BUNDLE_PATH_TRAVERSAL",`Unsupported characters in path segment "${n}".`)}return e}async function JD(e){const[r,n]=await Promise.all([hp(e.refContent),hp(e.mobContent)]),s=[{path:"structures/reference.cif",role:"reference",label:e.refLabel,sha256:r,content:e.refContent},{path:"structures/mobile.cif",role:"mobile",label:e.mobLabel,sha256:n,content:e.mobContent}];return e.paeJson&&e.paeJson.trim().length>0&&s.push({path:"pae/predicted_aligned_error.json",role:"pae",label:"PAE Matrix",sha256:await hp(e.paeJson),content:e.paeJson}),{schemaVersion:"1.0.0",bundleFormat:"synlexa-studio-bundle-v1",ruoNotice:Cn,exportedAtUtc:new Date().toISOString(),files:s,state:e.state,comparisonResult:e.comparisonResult}}async function ZD(e){let r;try{r=JSON.parse(e)}catch(c){throw new kn("ERR_BUNDLE_PARSE",`Invalid bundle JSON: ${c instanceof Error?c.message:String(c)}`)}if(!r||typeof r!="object")throw new kn("ERR_BUNDLE_SCHEMA","Bundle root must be an object.");const n=r;if(n.bundleFormat!=="synlexa-studio-bundle-v1"||n.schemaVersion!=="1.0.0")throw new kn("ERR_BUNDLE_SCHEMA","Unsupported bundleFormat or schemaVersion (expected synlexa-studio-bundle-v1 / 1.0.0).");if(!Array.isArray(n.files)||n.files.length===0)throw new kn("ERR_BUNDLE_SCHEMA","Bundle must contain a non-empty files array.");if(!n.state||typeof n.state!="object")throw new kn("ERR_BUNDLE_SCHEMA","Bundle missing workspace state.");const s=new Set,i=new Map;for(const c of n.files){if(!c||typeof c!="object")throw new kn("ERR_BUNDLE_SCHEMA","Invalid file entry in bundle.");const d=QD(c.path);if(s.has(d))throw new kn("ERR_BUNDLE_DUPLICATE_PATH",`Duplicate bundle file path "${d}".`);if(s.add(d),typeof c.content!="string"||typeof c.sha256!="string")throw new kn("ERR_BUNDLE_SCHEMA",`File "${d}" missing string content or sha256.`);if(!/^[a-fA-F0-9]{64}$/.test(c.sha256))throw new kn("ERR_BUNDLE_HASH_MISMATCH",`Invalid SHA-256 format on "${d}".`);const f=await hp(c.content);if(f!==c.sha256.toLowerCase())throw new kn("ERR_BUNDLE_HASH_MISMATCH",`SHA-256 mismatch on "${d}": expected ${c.sha256}, computed ${f}.`);(c.role==="reference"||c.role==="mobile")&&i.set(c.role,f)}if(n.comparisonResult){const c=i.get("reference"),d=i.get("mobile");if(c&&n.comparisonResult.reference?.sha256&&n.comparisonResult.reference.sha256.toLowerCase()!==c)throw new kn("ERR_BUNDLE_HASH_MISMATCH","Bundled comparisonResult.reference.sha256 does not match reference file digest.");if(d&&n.comparisonResult.mobile?.sha256&&n.comparisonResult.mobile.sha256.toLowerCase()!==d)throw new kn("ERR_BUNDLE_HASH_MISMATCH","Bundled comparisonResult.mobile.sha256 does not match mobile file digest.")}return n}const eq="synlexa_studio_db",Yi="run_history",s1="synlexa.studio.runHistory.v1",a1=25;function r1(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise(e=>{try{const r=indexedDB.open(eq,1);r.onupgradeneeded=()=>{const n=r.result;n.objectStoreNames.contains(Yi)||n.createObjectStore(Yi,{keyPath:"id"})},r.onsuccess=()=>e(r.result),r.onerror=()=>e(null)}catch{e(null)}})}function Xf(){if(typeof localStorage>"u")return[];try{const e=localStorage.getItem(s1);if(!e)return[];const r=JSON.parse(e);return Array.isArray(r)?r:[]}catch{return[]}}function tq(e){if(!(typeof localStorage>"u"))try{localStorage.setItem(s1,JSON.stringify(e.slice(0,a1)))}catch{}}async function cE(){const e=await r1();return e?new Promise(r=>{try{const i=e.transaction(Yi,"readonly").objectStore(Yi).getAll();i.onsuccess=()=>{const c=i.result??[];c.sort((d,f)=>f.createdAtUtc.localeCompare(d.createdAtUtc)),e.close(),r(c.length>0?c.slice(0,a1):Xf())},i.onerror=()=>{e.close(),r(Xf())}}catch{e.close(),r(Xf())}}):Xf()}async function nq(e){const r=await cE(),n=[e,...r.filter(i=>i.id!==e.id)].slice(0,a1);tq(n);const s=await r1();return s&&await new Promise(i=>{try{const c=s.transaction(Yi,"readwrite");c.objectStore(Yi).put(e),c.oncomplete=()=>{s.close(),i()},c.onerror=()=>{s.close(),i()}}catch{s.close(),i()}}),n}async function uE(){typeof localStorage<"u"&&localStorage.removeItem(s1);const e=await r1();e&&await new Promise(r=>{try{const n=e.transaction(Yi,"readwrite");n.objectStore(Yi).clear(),n.oncomplete=()=>{e.close(),r()},n.onerror=()=>{e.close(),r()}}catch{e.close(),r()}})}const dE=[{id:"ca2-azm",kind:"protein-pair",title:"Carbonic Anhydrase II",subtitle:"3HS4 vs AF-P00918 + Acetazolamide",blurb:"Compare a 1.1 Å crystal structure with its AlphaFold prediction, inspect the Zn²⁺ active site, and profile the co-crystallised sulfonamide ligand.",tags:["Enzyme","Zn²⁺ pocket","Ligand","PAE"],reference:{fileName:"3HS4.cif",chainId:"A",label:"3HS4.cif"},mobile:{fileName:"AF-P00918-F1-model_v6.cif",chainId:"A",label:"AF-P00918-F1-model_v6.cif"},paeFileName:"AF-P00918-F1-predicted_aligned_error_v6.json",focusSeqId:94,peptideMutations:["H94A"],crispr:{transcriptId:"NM_000067.3",targetCodonIndex:94,baseEditOffset:0,newBase:"G",nuclease:"SpCas9",note:"CA2 codon 94 (His94, a Zn²⁺-coordinating residue in the pinned structure)."},smilesPresetId:"azm",openTab:"sequence"},{id:"ubiquitin",kind:"protein-pair",title:"Human Ubiquitin",subtitle:"1UBQ vs AF-P0CG48 (Polyubiquitin-C)",blurb:"Compare a 76-aa monomer crystal structure (1UBQ) against the 685-aa 9-repeat polyubiquitin-C AlphaFold precursor (AF-P0CG48), and inspect its β-grasp Ramachandran angles.",tags:["β-grasp","Repeat precursor","Ramachandran"],reference:{fileName:"1UBQ.cif",chainId:"A",label:"1UBQ.cif"},mobile:{fileName:"AF-P0CG48-F1-model_v6.cif",chainId:"A",label:"AF-P0CG48-F1-model_v6.cif"},focusSeqId:48,openTab:"ramachandran"},{id:"hbb-e6v",kind:"protein-pair",title:"Hemoglobin β",subtitle:"1A3N chain B vs AF-P68871 + HBB E6V edit",blurb:"Select the β subunit from a four-chain assembly, then explore the classic E6V nucleotide change (HGVS c.20A>T, p.Glu7Val with the initiator Met counted) in the CRISPR studio.",tags:["Multi-chain","CRISPR","Missense"],reference:{fileName:"1A3N.cif",chainId:"B",label:"1A3N.cif"},mobile:{fileName:"AF-P68871-F1-model_v6.cif",chainId:"A",label:"AF-P68871-F1-model_v6.cif"},focusSeqId:6,peptideMutations:["E7V"],crispr:{transcriptId:"NM_000518.5",targetCodonIndex:7,baseEditOffset:1,newBase:"T",nuclease:"SpCas9",note:'Legacy "E6V" (mature-protein numbering) = CDS codon 7, c.20A>T (GAG → GTG).'},openTab:"crispr"},{id:"lysozyme",kind:"protein-pair",title:"Human Lysozyme C",subtitle:"1LZ1 vs AF-P61626",blurb:"A mixed α/β enzyme. The prediction includes the signal peptide, so coverage shows how sequence-aware mapping handles extra residues.",tags:["α/β enzyme","Coverage","Signal peptide"],reference:{fileName:"1LZ1.cif",chainId:"A",label:"1LZ1.cif"},mobile:{fileName:"AF-P61626-F1-model_v6.cif",chainId:"A",label:"AF-P61626-F1-model_v6.cif"},focusSeqId:35,openTab:"sequence"},{id:"chem-panel",kind:"chemistry-panel",title:"Small-Molecule Chemistry Panel",subtitle:"Imatinib · Acetazolamide · Aspirin · Caffeine",blurb:"Parse SMILES deterministically, depict 2D graphs, and read TPSA, cLogP, H-bond counts, and rule-of-five flags with plain-English badges.",tags:["SMILES","TPSA","cLogP","Lipinski"],smilesPresetId:"imatinib",smilesPanelIds:["imatinib","azm","aspirin","caffeine"],openTab:"chemistry"}];function sq(e){return dE.find(r=>r.id===e)}function aq(e){return e.split(/[,\s;]+/).map(r=>r.trim().toUpperCase()).filter(r=>/^[ACDEFGHIKLMNPQRSTVWY]\d+[ACDEFGHIKLMNPQRSTVWY]$/.test(r))}function rq(e,r){switch(r.type){case"set_sequence":{const n=r.sequence.toUpperCase().replace(/[^ACDEFGHIKLMNPQRSTVWY]/g,"");return{...e,sequence:n,sliceStart:1,sliceEnd:Math.max(1,n.length)}}case"set_mutations_input":return{...e,mutationsInput:r.raw,mutations:aq(r.raw)};case"add_mutation":{const n=r.notation.trim().toUpperCase();if(!/^[ACDEFGHIKLMNPQRSTVWY]\d+[ACDEFGHIKLMNPQRSTVWY]$/.test(n)||e.mutations.includes(n))return e;const s=[...e.mutations,n];return{...e,mutations:s,mutationsInput:s.join(", ")}}case"remove_mutation":{const n=e.mutations.filter(s=>s!==r.notation);return{...e,mutations:n,mutationsInput:n.join(", ")}}case"set_slice":{const n=Math.max(1,e.sequence.length),s=Math.max(1,Math.min(n,Math.floor(r.start))),i=Math.max(s,Math.min(n,Math.floor(r.end)));return{...e,sliceStart:s,sliceEnd:i}}case"focus_residue":return{...e,focusSeqId:r.seqId};default:return e}}function iq(e,r){switch(r.type){case"select_transcript":return{...e,transcriptId:r.transcriptId,useCustomDna:!1,targetCodonIndex:Math.max(1,e.targetCodonIndex)};case"set_custom_dna":return{...e,customDna:r.dna.toUpperCase().replace(/[^ACGT]/g,""),useCustomDna:!0};case"toggle_custom_dna":return{...e,useCustomDna:r.enabled};case"set_target_codon":return{...e,targetCodonIndex:Math.max(1,Math.floor(r.codonIndex))};case"set_base_edit":return{...e,baseEditOffset:r.offset,newBase:r.newBase};case"set_nuclease":return{...e,nuclease:r.nuclease};default:return e}}const Xo=[{id:"azm",name:"Acetazolamide (AZM · 3HS4 ligand)",smiles:"CC(=O)Nc1nnc(S(N)(=O)=O)s1",note:"Co-crystallized carbonic anhydrase II inhibitor in PDB 3HS4"},{id:"dorzolamide",name:"Dorzolamide",smiles:"CCN[C@H]1C[C@@H](C)S(=O)(=O)c2sc(S(N)(=O)=O)cc12",note:"Thienothiopyran sulfonamide scaffold"},{id:"bsa",name:"Benzene sulfonamide",smiles:"NS(=O)(=O)c1ccccc1",note:"Minimal arylsulfonamide zinc-binding headgroup"},{id:"aspirin",name:"Aspirin",smiles:"CC(=O)Oc1ccccc1C(=O)O",note:"Reference small-molecule carboxylate ester"},{id:"caffeine",name:"Caffeine",smiles:"Cn1cnc2c1c(=O)n(C)c(=O)n2C",note:"Purine xanthine benchmark"},{id:"imatinib",name:"Imatinib",smiles:"CC1=C(C=C(C=C1)NC(=O)C2=CC=C(C=C2)CN3CCN(CC3)C)NC4=NC=CC(=N4)C5=CN=CC=C5",note:"Phenylaminopyrimidine kinase-inhibitor scaffold (PubChem CID 5291)"}];function oq(e,r){switch(r.type){case"select_preset":{const n=Xo.find(s=>s.id===r.presetId);return n?{selectedPresetId:n.id,name:n.name,smiles:n.smiles}:e}case"set_custom_smiles":return{selectedPresetId:"custom",name:r.name?.trim()||"Custom SMILES",smiles:r.smiles.trim()};default:return e}}const lq=["home","viewer","results","sequence","ramachandran","peptide","crispr","chemistry","workflow","compute","plugins","assistant","mcp","library"],Op=new Set(["viewer"]),mp={groups:[{tabs:["home","viewer"],active:"home"},{tabs:["assistant","results","sequence","mcp"],active:"assistant"}],focused:0,split:.62};function Id(e,r){return e.groups.findIndex(n=>n.tabs.includes(r))}function Gd(e){let r=e.groups.filter(n=>n.tabs.length>0);return r.length===0&&(r=[{tabs:["home","viewer"],active:"home"}]),r=r.map(n=>({tabs:n.tabs,active:n.active&&n.tabs.includes(n.active)?n.active:n.tabs[n.tabs.length-1]??null})),r.some(n=>n.tabs.includes("viewer"))||(r[0]={...r[0],tabs:[...r[0].tabs,"viewer"]}),{groups:r.slice(0,2),focused:Math.min(e.focused,r.length-1),split:Math.min(.8,Math.max(.2,e.split))}}function _y(e,r){switch(r.type){case"open":{const n=Id(e,r.tab);if(n>=0&&!r.toSide){const c=e.groups.map((d,f)=>f===n?{...d,active:r.tab}:d);return{...e,groups:c,focused:n}}if(r.toSide){const c=n>=0?n:e.focused,d=e.groups.length===1?1:1-c;return _y(e,{type:"move",tab:r.tab,toGroup:d})}const s=e.focused,i=e.groups.map((c,d)=>d===s?{tabs:[...c.tabs,r.tab],active:r.tab}:c);return{...e,groups:i}}case"activate":{const n=Id(e,r.tab);if(n<0)return _y(e,{type:"open",tab:r.tab});const s=e.groups.map((i,c)=>c===n?{...i,active:r.tab}:i);return{...e,groups:s,focused:n}}case"close":{if(Op.has(r.tab))return e;const n=Id(e,r.tab);if(n<0)return e;const s=e.groups.map((i,c)=>{if(c!==n)return i;const d=i.tabs.indexOf(r.tab),f=i.tabs.filter(b=>b!==r.tab),p=i.active===r.tab?f[Math.min(d,f.length-1)]??null:i.active;return{tabs:f,active:p}});return Gd({...e,groups:s})}case"close_others":{const n=Id(e,r.tab);if(n<0)return e;const s=e.groups.map((i,c)=>c===n?{tabs:i.tabs.filter(d=>d===r.tab||Op.has(d)),active:r.tab}:i);return Gd({...e,groups:s})}case"move":{const n=Id(e,r.tab);let s=e.groups.map(p=>({...p,tabs:[...p.tabs]}));if(r.toGroup>=s.length&&s.push({tabs:[],active:null}),n>=0){const p=s[n],b=p.tabs.indexOf(r.tab);p.tabs.splice(b,1),p.active===r.tab&&(p.active=p.tabs[Math.min(b,p.tabs.length-1)]??null)}const i=s[r.toGroup],c=r.index===void 0?i.tabs.length:Math.max(0,Math.min(r.index,i.tabs.length));i.tabs.splice(c,0,r.tab),i.active=r.tab;const d=n>=0&&s[n].tabs.length===0;s=s.filter(p=>p.tabs.length>0);const f=d&&n<r.toGroup?r.toGroup-1:r.toGroup;return Gd({...e,groups:s,focused:f})}case"focus_group":return{...e,focused:Math.min(r.group,e.groups.length-1)};case"set_split":return{...e,split:Math.min(.8,Math.max(.2,r.split))};case"merge_split":{if(e.groups.length<2)return e;const n=e.groups[e.focused]??e.groups[0],s=Array.from(new Set(e.groups.flatMap(i=>i.tabs)));return Gd({...e,groups:[{tabs:s,active:n.active??s[0]??null}],focused:0})}case"reset":return mp}}const hE="synlexa.studio.layout.v1";function cq(e){if(!e)return mp;try{const r=localStorage.getItem(hE);if(!r)return mp;const n=JSON.parse(r),s=new Set(lq),i=(n.groups??[]).map(c=>({tabs:Array.from(new Set((c.tabs??[]).filter(f=>s.has(f)))),active:c.active&&s.has(c.active)?c.active:null})).slice(0,2);return i.length===2&&(i[1].tabs=i[1].tabs.filter(c=>!i[0].tabs.includes(c))),Gd({groups:i,focused:n.focused??0,split:n.split??.6})}catch{return mp}}function uq(e){try{localStorage.setItem(hE,JSON.stringify(e))}catch{}}function dq(e){if(typeof document>"u")return()=>{};const r=d=>{(d.ctrlKey||d.metaKey)&&d.preventDefault()},n=d=>d.preventDefault(),s=d=>{d.touches.length>1&&d.preventDefault()},i=d=>{!(d.metaKey||d.ctrlKey)||d.altKey||(d.key==="="||d.key==="+"?(d.preventDefault(),e?.(1)):d.key==="-"||d.key==="_"?(d.preventDefault(),e?.(-1)):d.key==="0"&&(d.preventDefault(),e?.(0)))},c={passive:!1};return window.addEventListener("wheel",r,c),document.addEventListener("gesturestart",n,c),document.addEventListener("gesturechange",n,c),document.addEventListener("gestureend",n,c),document.addEventListener("touchmove",s,c),window.addEventListener("keydown",i),()=>{window.removeEventListener("wheel",r),document.removeEventListener("gesturestart",n),document.removeEventListener("gesturechange",n),document.removeEventListener("gestureend",n),document.removeEventListener("touchmove",s),window.removeEventListener("keydown",i)}}var hq=$A();function Ie(...e){return e.filter(Boolean).join(" ")}const mq={primary:"bg-sky-500 text-slate-950 hover:bg-sky-400 font-semibold shadow-sm shadow-sky-950/40",secondary:"border border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08] hover:border-white/20",ghost:"text-slate-300 hover:bg-white/[0.06] hover:text-white",danger:"border border-rose-500/30 bg-rose-500/10 text-rose-200 hover:bg-rose-500/20"},fq={sm:"h-7 px-2.5 text-xs gap-1.5 rounded-md",md:"h-9 px-3.5 text-sm gap-2 rounded-lg"};function Oe({variant:e="secondary",size:r="md",className:n,icon:s,children:i,...c}){return o.jsxs("button",{type:"button",...c,className:Ie("inline-flex shrink-0 items-center justify-center whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-sky-400/60 disabled:pointer-events-none disabled:opacity-40",mq[e],fq[r],n),children:[s,i]})}function sl({label:e,active:r,className:n,children:s,...i}){return o.jsx("button",{type:"button","aria-label":e,title:e,...i,className:Ie("inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition-colors outline-none focus-visible:ring-2 focus-visible:ring-sky-400/60 disabled:opacity-40",r?"bg-sky-500/15 text-sky-300":"text-slate-400 hover:bg-white/[0.07] hover:text-slate-100",n),children:s})}function Dn({className:e,...r}){return o.jsx("input",{...r,className:Ie("h-9 w-full rounded-lg border border-white/10 bg-black/30 px-3 text-sm text-slate-100 placeholder-slate-500 outline-none transition focus:border-sky-400/70 focus:ring-2 focus:ring-sky-400/20",e)})}function Pp({className:e,...r}){return o.jsx("textarea",{...r,className:Ie("w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-slate-100 placeholder-slate-500 outline-none transition focus:border-sky-400/70 focus:ring-2 focus:ring-sky-400/20",e)})}function Na({className:e,children:r,...n}){return o.jsx("select",{...n,className:Ie("h-9 w-full rounded-lg border border-white/10 bg-[#121722] px-2.5 text-sm text-slate-100 outline-none focus:border-sky-400/70",e),children:r})}function $r({checked:e,onChange:r,label:n}){return o.jsx("button",{type:"button",role:"switch","aria-checked":e,"aria-label":n,onClick:()=>r(!e),className:Ie("relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors outline-none focus-visible:ring-2 focus-visible:ring-sky-400/60",e?"bg-sky-500":"bg-slate-700"),children:o.jsx("span",{className:Ie("inline-block h-4 w-4 rounded-full bg-white shadow transition-transform",e?"translate-x-[1.125rem]":"translate-x-0.5")})})}function It({tone:e="neutral",children:r,className:n}){const s={neutral:"bg-white/[0.06] text-slate-300 border-white/10",accent:"bg-sky-500/10 text-sky-300 border-sky-500/25",good:"bg-emerald-500/10 text-emerald-300 border-emerald-500/25",warn:"bg-amber-500/10 text-amber-300 border-amber-500/25",bad:"bg-rose-500/10 text-rose-300 border-rose-500/25"};return o.jsx("span",{className:Ie("inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[0.6875rem] font-medium leading-none",s[e],n),children:r})}function Rr({children:e}){return o.jsx("kbd",{className:"rounded border border-white/15 bg-white/[0.04] px-1.5 py-0.5 font-mono text-[0.6875rem] text-slate-400",children:e})}function yt({title:e,description:r,actions:n,children:s,className:i}){return o.jsxs("section",{className:Ie("rounded-xl border border-white/[0.08] bg-white/[0.02]",i),children:[(e||n)&&o.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-white/[0.06] px-4 py-3",children:[o.jsxs("div",{className:"min-w-0",children:[e&&o.jsx("h3",{className:"text-sm font-semibold text-slate-100",children:e}),r&&o.jsx("p",{className:"mt-0.5 text-xs text-slate-400",children:r})]}),n&&o.jsx("div",{className:"flex shrink-0 items-center gap-2",children:n})]}),s&&o.jsx("div",{className:"p-4",children:s})]})}function Qt({label:e,hint:r,children:n}){return o.jsxs("div",{className:"flex flex-col gap-2 py-3 @xl:flex-row @xl:items-center @xl:justify-between @xl:gap-6",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-sm text-slate-200",children:e}),r&&o.jsx("div",{className:"mt-0.5 text-xs text-slate-500",children:r})]}),o.jsx("div",{className:"min-w-0 @xl:max-w-[60%] @xl:shrink-0",children:n})]})}function mE({icon:e,title:r,description:n,action:s}){return o.jsxs("div",{className:"flex h-full min-h-40 flex-col items-center justify-center gap-2 px-6 py-10 text-center",children:[e&&o.jsx("div",{className:"mb-1 text-slate-500",children:e}),o.jsx("div",{className:"text-sm font-medium text-slate-200",children:r}),n&&o.jsx("div",{className:"max-w-sm text-xs leading-relaxed text-slate-400",children:n}),s&&o.jsx("div",{className:"mt-3",children:s})]})}function fE({open:e,onClose:r,title:n,children:s,footer:i,width:c="max-w-lg"}){return C.useEffect(()=>{if(!e)return;const d=f=>{f.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e,r]),e?o.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",onMouseDown:d=>{d.target===d.currentTarget&&r()},children:o.jsxs("div",{className:Ie("w-full overflow-hidden rounded-2xl border border-white/10 bg-[#121722] shadow-2xl",c),children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-white/[0.06] px-5 py-3.5",children:[o.jsx("h2",{className:"text-base font-semibold text-slate-100",children:n}),o.jsx(sl,{label:"Close",onClick:r,children:o.jsx(Xi,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"max-h-[70vh] overflow-y-auto px-5 py-4",children:s}),i&&o.jsx("div",{className:"flex justify-end gap-2 border-t border-white/[0.06] px-5 py-3",children:i})]})}):null}const pE=C.createContext({toast:()=>{},confirm:async()=>!0});function cl(){return C.useContext(pE)}function pq({children:e}){const[r,n]=C.useState([]),[s,i]=C.useState(null),c=C.useRef(1),d=C.useCallback((x,g="info",_)=>{const y=c.current++;n(S=>[...S.slice(-3),{id:y,tone:g,message:x,action:_}]),setTimeout(()=>n(S=>S.filter(k=>k.id!==y)),g==="error"?7e3:4e3)},[]),f=C.useCallback(x=>new Promise(g=>i({...x,resolve:g})),[]),p=x=>{s?.resolve(x),i(null)},b={info:o.jsx(zy,{className:"h-4 w-4 text-sky-300"}),success:o.jsx(Gs,{className:"h-4 w-4 text-emerald-300"}),warn:o.jsx(Gc,{className:"h-4 w-4 text-amber-300"}),error:o.jsx(Bc,{className:"h-4 w-4 text-rose-300"})};return o.jsxs(pE.Provider,{value:{toast:d,confirm:f},children:[e,o.jsx("div",{className:"pointer-events-none fixed right-4 bottom-10 z-[90] flex w-80 flex-col gap-2",children:r.map(x=>o.jsxs("div",{className:"pointer-events-auto flex items-start gap-2.5 rounded-xl border border-white/10 bg-[#161c28]/95 px-3.5 py-3 text-sm text-slate-200 shadow-xl backdrop-blur",children:[o.jsx("span",{className:"mt-0.5 shrink-0",children:b[x.tone]}),o.jsx("div",{className:"min-w-0 flex-1 leading-snug",children:x.message}),x.action&&o.jsx("button",{type:"button",onClick:()=>{x.action.run(),n(g=>g.filter(_=>_.id!==x.id))},className:"shrink-0 text-xs font-semibold text-sky-300 hover:text-sky-200",children:x.action.label})]},x.id))}),o.jsx(fE,{open:!!s,onClose:()=>p(!1),title:s?.title??"",width:"max-w-md",footer:o.jsxs(o.Fragment,{children:[o.jsx(Oe,{variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),o.jsx(Oe,{variant:s?.danger?"danger":"primary",onClick:()=>p(!0),autoFocus:!0,children:s?.confirmLabel??"Confirm"})]}),children:o.jsx("div",{className:"text-sm leading-relaxed text-slate-300",children:s?.message})})]})}function i1({trigger:e,items:r,align:n="right"}){const[s,i]=C.useState(!1),[c,d]=C.useState(null),f=C.useRef(null),p=C.useRef(null);return C.useLayoutEffect(()=>{if(!s){d(null);return}const b=()=>{const x=f.current?.getBoundingClientRect(),g=p.current;if(!x||!g)return;const _=8,y=g.offsetWidth,S=n==="right"?x.right-y:x.left,k=Math.min(Math.max(_,S),window.innerWidth-y-_),E=x.bottom+4;d({top:E,left:k,maxHeight:Math.max(160,window.innerHeight-E-_)})};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[s,n]),C.useEffect(()=>{if(!s)return;const b=g=>{const _=g.target;f.current?.contains(_)||p.current?.contains(_)||i(!1)},x=g=>g.key==="Escape"&&i(!1);return window.addEventListener("mousedown",b),window.addEventListener("keydown",x),()=>{window.removeEventListener("mousedown",b),window.removeEventListener("keydown",x)}},[s]),o.jsxs("div",{ref:f,className:"relative",children:[e(s,()=>i(b=>!b)),s&&hq.createPortal(o.jsx("div",{ref:p,style:c?{position:"fixed",top:c.top,left:c.left,maxHeight:Math.min(c.maxHeight,480)}:{position:"fixed",top:0,left:0,visibility:"hidden"},className:"z-[90] max-w-[calc(100vw-1rem)] min-w-52 overflow-y-auto rounded-xl border border-white/10 bg-[#161c28] py-1 shadow-2xl",children:r.map((b,x)=>b==="divider"?o.jsx("div",{className:"my-1 h-px bg-white/[0.06]"},`d${x}`):"heading"in b?o.jsx("div",{className:"px-3 pt-2.5 pb-1 text-[0.6875rem] font-semibold tracking-wide text-slate-500 uppercase",children:b.heading},`h${x}`):o.jsxs("button",{type:"button",disabled:b.disabled,onClick:()=>{i(!1),b.onSelect()},className:Ie("flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm transition-colors disabled:opacity-40",b.danger?"text-rose-300 hover:bg-rose-500/10":"text-slate-200 hover:bg-white/[0.06]",b.selected&&"bg-white/[0.05]"),children:[b.icon&&o.jsx("span",{className:"shrink-0 text-slate-400",children:b.icon}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block",children:b.label}),b.description&&o.jsx("span",{className:"block truncate text-xs text-slate-500",children:b.description})]}),b.hint&&o.jsx("span",{className:"text-xs text-slate-500",children:b.hint})]},b.key??b.label))}),document.body)]})}const gq=new Set(["\\","`","*","_","{","}","[","]","(",")","#","+","-",".","!","|",">","~"]);function Nx(e){const r=e.trim().replace(/^<|>$/g,"");if(!r)return null;try{const n=new URL(r);return n.protocol==="http:"||n.protocol==="https:"?n.href:null}catch{return null}}function $p(e){let r=e.trim();r.startsWith("|")&&(r=r.slice(1)),r.endsWith("|")&&!r.endsWith("\\|")&&(r=r.slice(0,-1));const n=[];let s="",i=0,c=0;for(;i<r.length;){const d=r[i];if(d==="\\"&&i+1<r.length&&r[i+1]==="|"){s+="|",i+=2;continue}if(d==="`"){let f=0;for(;i+f<r.length&&r[i+f]==="`";)f++;c===0?c=f:c===f&&(c=0),s+=r.slice(i,i+f),i+=f;continue}if(d==="|"&&c===0){n.push(s.trim()),s="",i++;continue}s+=d,i++}return n.push(s.trim()),n}function gE(e,r){if(!e.includes("|")&&r<=1)return null;const n=e.trim();if(!n)return null;const s=$p(n);if(s.length===0||s.length<r&&r>1&&s.length===1)return null;const i=[];for(const c of s){if(!/^:?-{1,}:?$/.test(c))return null;const d=c.startsWith(":"),f=c.endsWith(":");d&&f?i.push("center"):f?i.push("right"):d?i.push("left"):i.push(null)}return i}function fp(e){const r=e.match(/^(\s*)([-*+•])\s+(.*)$/);if(r){const s=r[3],i=s.match(/^\[([ xX])\]\s+(.*)$/);return{indent:r[1].replace(/\t/g," ").length,ordered:!1,start:1,text:i?i[2]:s,...i?{checked:i[1].toLowerCase()==="x"}:{}}}const n=e.match(/^(\s*)(\d{1,9})[.)]\s+(.*)$/);if(n){const s=n[3],i=s.match(/^\[([ xX])\]\s+(.*)$/);return{indent:n[1].replace(/\t/g," ").length,ordered:!0,start:Number.parseInt(n[2],10)||1,text:i?i[2]:s,...i?{checked:i[1].toLowerCase()==="x"}:{}}}return null}function vy(e){return/^\s*([-*_])(?:\s*\1){2,}\s*$/.test(e)}function wy(e){const r=e.match(/^\s*(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);return r?{level:r[1].length,text:r[2].trim()}:null}function Sy(e){const r=e.match(/^\s*(`{3,}|~{3,})(.*)$/);if(!r)return null;const n=r[1],s=r[2].trim();return n[0]==="`"&&s.includes("`")?null:{char:n[0],len:n.length,lang:s.split(/\s+/)[0]??""}}function fA(e,r){const n=e[r];if(!n.trim()||Sy(n)||wy(n)||vy(n)||/^\s*>\s?/.test(n)||fp(n))return!0;if(r+1<e.length&&n.includes("|")){const s=$p(n);if(gE(e[r+1],s.length))return!0}return!1}function bE(e,r=0,n=e[0]?.indent??0){const s=e[r],i={type:"list",ordered:s.ordered,start:s.start,items:[]};let c=r;for(;c<e.length;){const d=e[c];if(d.indent<n||d.indent===n&&d.ordered!==i.ordered)break;if(d.indent>n){if(i.items.length===0){const p={lines:d.lines,checked:d.checked,children:[]};i.items.push(p),c++;continue}const f=bE(e,c,d.indent);i.items[i.items.length-1].children.push(f.list),c=f.nextIdx;continue}i.items.push({lines:d.lines,checked:d.checked,children:[]}),c++}return{list:i,nextIdx:c}}function xE(e){const n=e.replace(/\r\n?/g,`
761
761
  `).split(`
@@ -842,4 +842,4 @@ void main() {
842
842
  vec3 bg = vec3(0.035, 0.051, 0.078);
843
843
  outColor = vec4(mix(shaded, bg, fog), 1.0);
844
844
  }
845
- `;function Hd(e,r){return[e[0]-r[0],e[1]-r[1],e[2]-r[2]]}function Is(e,r){return[e[0]+r[0],e[1]+r[1],e[2]+r[2]]}function Sn(e,r){return[e[0]*r,e[1]*r,e[2]*r]}function zr(e,r){return[e[1]*r[2]-e[2]*r[1],e[2]*r[0]-e[0]*r[2],e[0]*r[1]-e[1]*r[0]]}function nr(e){const r=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);return r<1e-8?[0,1,0]:[e[0]/r,e[1]/r,e[2]/r]}function Fd(e,r){return Math.sqrt((e[0]-r[0])**2+(e[1]-r[1])**2+(e[2]-r[2])**2)}function aL(e){const r=Math.cos(e.pitch),n=Math.sin(e.pitch),s=Math.cos(e.yaw),i=Math.sin(e.yaw),c=[e.target[0]+e.distance*r*i,e.target[1]+e.distance*n,e.target[2]+e.distance*r*s],d=nr(Hd(e.target,c)),p=nr(zr(d,[0,1,0])),b=zr(p,d);return new Float32Array([p[0],b[0],-d[0],0,p[1],b[1],-d[1],0,p[2],b[2],-d[2],0,-(p[0]*c[0]+p[1]*c[1]+p[2]*c[2]),-(b[0]*c[0]+b[1]*c[1]+b[2]*c[2]),d[0]*c[0]+d[1]*c[1]+d[2]*c[2],1])}function AA(e,r,n,s){const i=1/Math.tan(e/2),c=1/(n-s);return new Float32Array([i/r,0,0,0,0,i,0,0,0,0,(s+n)*c,-1,0,0,2*s*n*c,0])}function jA(e,r){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[s*4+i]=e[0+i]*r[s*4+0]+e[4+i]*r[s*4+1]+e[8+i]*r[s*4+2]+e[12+i]*r[s*4+3];return n}function $n(e,r,n,s,i,c){const d=e[0]*r[0]+e[4]*r[1]+e[8]*r[2]+e[12],f=e[1]*r[0]+e[5]*r[1]+e[9]*r[2]+e[13],p=e[2]*r[0]+e[6]*r[1]+e[10]*r[2]+e[14],b=e[3]*r[0]+e[7]*r[1]+e[11]*r[2]+e[15];if(b<=.05)return{sx:-9999,sy:-9999,ndcZ:2,visible:!1};const x=d/b,g=f/b,_=p/b;return{sx:n+(x*.5+.5)*i,sy:s+(-g*.5+.5)*c,ndcZ:_,visible:_>=-1&&_<=1}}function rL(e,r,n,s,i){const c=i*i,d=c*i,f=[0,0,0];for(let p=0;p<3;p++)f[p]=.5*(2*r[p]+(-e[p]+n[p])*i+(2*e[p]-5*r[p]+4*n[p]-s[p])*c+(-e[p]+3*r[p]-3*n[p]+s[p])*d);return f}class iL{data=[];pushTri(r,n,s,i,c,d,f,p,b){this.data.push(r[0],r[1],r[2],n[0],n[1],n[2],s[0]/255,s[1]/255,s[2]/255,i[0],i[1],i[2],c[0],c[1],c[2],d[0]/255,d[1]/255,d[2]/255,f[0],f[1],f[2],p[0],p[1],p[2],b[0]/255,b[1]/255,b[2]/255)}addSphere(r,n,s,i=8,c=12){for(let d=0;d<i;d++){const f=d/i*Math.PI,p=(d+1)/i*Math.PI;for(let b=0;b<c;b++){const x=b/c*Math.PI*2,g=(b+1)/c*Math.PI*2,_=[Math.sin(f)*Math.cos(x),Math.cos(f),Math.sin(f)*Math.sin(x)],y=[Math.sin(p)*Math.cos(x),Math.cos(p),Math.sin(p)*Math.sin(x)],S=[Math.sin(p)*Math.cos(g),Math.cos(p),Math.sin(p)*Math.sin(g)],k=[Math.sin(f)*Math.cos(g),Math.cos(f),Math.sin(f)*Math.sin(g)],E=Is(r,Sn(_,n)),T=Is(r,Sn(y,n)),j=Is(r,Sn(S,n)),q=Is(r,Sn(k,n));d>0&&this.pushTri(E,_,s,q,k,s,j,S,s),d<i-1&&this.pushTri(E,_,s,j,S,s,T,y,s)}}}addCylinder(r,n,s,i,c,d=8){const f=Hd(n,r),p=Math.sqrt(f[0]**2+f[1]**2+f[2]**2);if(p<1e-4)return;const b=Sn(f,1/p),x=Math.abs(b[1])<.9?[0,1,0]:[1,0,0],g=nr(zr(b,x)),_=zr(b,g);for(let y=0;y<d;y++){const S=y/d*Math.PI*2,k=(y+1)/d*Math.PI*2,E=Is(Sn(g,Math.cos(S)),Sn(_,Math.sin(S))),T=Is(Sn(g,Math.cos(k)),Sn(_,Math.sin(k))),j=Is(r,Sn(E,s)),q=Is(r,Sn(T,s)),z=Is(n,Sn(E,s)),O=Is(n,Sn(T,s));this.pushTri(j,E,i,q,T,i,O,T,c),this.pushTri(j,E,i,O,T,c,z,E,c)}}addBackboneRibbon(r,n,s,i=4,c=8){if(r.length<2)return;const d=[];let f=[r[0]];for(let p=1;p<r.length;p++)Fd(r[p-1].xyz,r[p].xyz)>6.5?(f.length>=2&&d.push(f),f=[r[p]]):f.push(r[p]);f.length>=2&&d.push(f);for(const p of d){const b=[];for(let k=0;k<p.length-1;k++){const E=p[Math.max(0,k-1)].xyz,T=p[k].xyz,j=p[k+1].xyz,q=p[Math.min(p.length-1,k+2)].xyz,z=p[k].color,O=p[k+1].color,V=k===p.length-2?i+1:i;for(let P=0;P<V;P++){const $=P/i,H=rL(E,T,j,q,$),Z=[z[0]+(O[0]-z[0])*$,z[1]+(O[1]-z[1])*$,z[2]+(O[2]-z[2])*$];b.push({pos:H,col:Z})}}let x=nr(Hd(b[1].pos,b[0].pos));const g=Math.abs(x[1])<.9?[0,1,0]:[1,0,0];let _=nr(zr(x,g)),y=zr(x,_);const S=[];for(let k=0;k<b.length;k++){const E=k===b.length-1?nr(Hd(b[k].pos,b[k-1].pos)):k===0?x:nr(Hd(b[k+1].pos,b[k-1].pos)),T=zr(x,E),j=Math.sqrt(T[0]**2+T[1]**2+T[2]**2);if(j>1e-5){const O=Math.max(-1,Math.min(1,x[0]*E[0]+x[1]*E[1]+x[2]*E[2])),V=Math.acos(O),P=Sn(T,1/j),$=Math.cos(V),H=Math.sin(V),Z=P[0]*_[0]+P[1]*_[1]+P[2]*_[2],G=zr(P,_);_=nr([_[0]*$+G[0]*H+P[0]*Z*(1-$),_[1]*$+G[1]*H+P[1]*Z*(1-$),_[2]*$+G[2]*H+P[2]*Z*(1-$)])}y=nr(zr(E,_)),x=E;const q=[],z=[];for(let O=0;O<c;O++){const V=O/c*Math.PI*2,P=Math.cos(V),$=Math.sin(V),H=Is(Sn(_,P*n),Sn(y,$*s)),Z=nr(Is(Sn(_,P/n),Sn(y,$/s)));q.push(Is(b[k].pos,H)),z.push(Z)}S.push({pts:q,norms:z,col:b[k].col})}for(let k=0;k<S.length-1;k++){const E=S[k],T=S[k+1];for(let j=0;j<c;j++){const q=(j+1)%c;this.pushTri(E.pts[j],E.norms[j],E.col,E.pts[q],E.norms[q],E.col,T.pts[q],T.norms[q],T.col),this.pushTri(E.pts[j],E.norms[j],E.col,T.pts[q],T.norms[q],T.col,T.pts[j],T.norms[j],T.col)}}}}toFloat32Array(){return new Float32Array(this.data)}}class oL{constructor(r){this.glCanvas=r;const n=r.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});n&&this.initProgram(n)?(this.gl=n,this.mode="webgl2"):this.mode="canvas2d-fallback"}gl=null;program=null;vao=null;vbo=null;uViewProjLoc=null;uViewLoc=null;mode;initProgram(r){const n=r.createShader(r.VERTEX_SHADER),s=r.createShader(r.FRAGMENT_SHADER);if(!n||!s||(r.shaderSource(n,nL),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))||(r.shaderSource(s,sL),r.compileShader(s),!r.getShaderParameter(s,r.COMPILE_STATUS)))return!1;const i=r.createProgram();if(!i||(r.attachShader(i,n),r.attachShader(i,s),r.linkProgram(i),!r.getProgramParameter(i,r.LINK_STATUS)))return!1;this.program=i,this.uViewProjLoc=r.getUniformLocation(i,"uViewProj"),this.uViewLoc=r.getUniformLocation(i,"uView"),this.vao=r.createVertexArray(),this.vbo=r.createBuffer(),r.bindVertexArray(this.vao),r.bindBuffer(r.ARRAY_BUFFER,this.vbo);const c=36;return r.enableVertexAttribArray(0),r.vertexAttribPointer(0,3,r.FLOAT,!1,c,0),r.enableVertexAttribArray(1),r.vertexAttribPointer(1,3,r.FLOAT,!1,c,12),r.enableVertexAttribArray(2),r.vertexAttribPointer(2,3,r.FLOAT,!1,c,24),r.bindVertexArray(null),r.enable(r.DEPTH_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),!0}render(r,n,s,i,c,d){const f=[],p=Math.max(1,Math.floor(i*d)),b=Math.max(1,Math.floor(c*d));(this.glCanvas.width!==p||this.glCanvas.height!==b)&&(this.glCanvas.width=p,this.glCanvas.height=b),(s.width!==p||s.height!==b)&&(s.width=p,s.height=b);const x=s.getContext("2d");x&&(x.setTransform(d,0,0,d,0,0),x.clearRect(0,0,i,c));const g=n.layout==="split"?[{x:0,y:0,w:i/2,h:c,showRef:!0,showMob:!1,title:"REFERENCE (EXPERIMENTAL)"},{x:i/2,y:0,w:i/2,h:c,showRef:!1,showMob:!0,title:"PREDICTION (SUPERPOSED)"}]:[{x:0,y:0,w:i,h:c,showRef:n.layout==="overlay"||n.layout==="reference",showMob:n.layout==="overlay"||n.layout==="mobile"}],_=aL(n.camera);if(this.mode==="webgl2"&&this.gl&&this.program&&this.vao&&this.vbo){const y=this.gl;y.disable(y.SCISSOR_TEST),y.viewport(0,0,p,b),y.clearColor(.035,.051,.078,1),y.clear(y.COLOR_BUFFER_BIT|y.DEPTH_BUFFER_BIT),y.enable(y.SCISSOR_TEST),y.useProgram(this.program),y.bindVertexArray(this.vao);for(const S of g){const k=Math.max(.1,S.w/Math.max(1,S.h)),E=AA(38*Math.PI/180,k,.5,600),T=jA(E,_),q=this.buildPanelMesh(r,n,S.showRef,S.showMob).toFloat32Array(),z=Math.floor(S.x*d),O=Math.floor(S.w*d),V=Math.floor(S.h*d);y.viewport(z,0,O,V),y.scissor(z,0,O,V),y.bindBuffer(y.ARRAY_BUFFER,this.vbo),y.bufferData(y.ARRAY_BUFFER,q,y.DYNAMIC_DRAW),y.uniformMatrix4fv(this.uViewLoc,!1,_),y.uniformMatrix4fv(this.uViewProjLoc,!1,T),y.drawArrays(y.TRIANGLES,0,q.length/9),this.collectAndDrawHud(r,n,T,S,x,f)}y.disable(y.SCISSOR_TEST)}else{const y=this.glCanvas.getContext("2d");if(y){y.setTransform(d,0,0,d,0,0),y.fillStyle="#090d14",y.fillRect(0,0,i,c);for(const S of g){const k=Math.max(.1,S.w/Math.max(1,S.h)),E=AA(38*Math.PI/180,k,.5,600),T=jA(E,_);this.render2dPanel(y,r,n,T,S),this.collectAndDrawHud(r,n,T,S,x,f)}}}return n.layout==="split"&&x&&(x.strokeStyle="rgba(148, 163, 184, 0.25)",x.lineWidth=1,x.beginPath(),x.moveTo(i/2,0),x.lineTo(i/2,c),x.stroke()),f}buildPanelMesh(r,n,s,i){const c=new iL,d=n.style==="pocket";if(s&&r.refResidues.length>0)if(n.style==="trace"){for(let p=0;p<r.refResidues.length-1;p++){const b=r.refResidues[p],x=r.refResidues[p+1];Fd(b.xyz,x.xyz)<=6.5&&c.addCylinder(b.xyz,x.xyz,.24,b.color,x.color,6)}for(const p of r.refResidues)c.addSphere(p.xyz,.34,p.color,6,8)}else c.addBackboneRibbon(r.refResidues,d?.34:.44,d?.14:.18,4,8);if(i&&r.mobResidues.length>0)if(n.style==="trace"){for(let p=0;p<r.mobResidues.length-1;p++){const b=r.mobResidues[p],x=r.mobResidues[p+1];Fd(b.xyz,x.xyz)<=6.5&&c.addCylinder(b.xyz,x.xyz,.2,b.color,x.color,6)}for(const p of r.mobResidues)c.addSphere(p.xyz,.3,p.color,6,8)}else c.addBackboneRibbon(r.mobResidues,d?.26:.36,d?.11:.14,4,8);if(s){for(const p of r.ligandBonds)c.addCylinder(p.a,p.b,d?p.radius:p.radius*.75,p.colorA,p.colorB,7);for(const p of r.ligandAtoms)c.addSphere(p.xyz,d?p.radius:p.radius*.85,p.color,9,12);if(d){for(const p of r.pocketBonds)c.addCylinder(p.a,p.b,p.radius,p.colorA,p.colorB,6);for(const p of r.pocketAtoms)c.addSphere(p.xyz,p.radius,p.color,6,8)}}const f=[...s?r.refResidues:[],...i?r.mobResidues:[]];for(const p of f)n.focusedSeqId===p.seqId?c.addSphere(p.xyz,.92,[251,191,36],10,14):n.highlightedSeqIds.has(p.seqId)&&c.addSphere(p.xyz,.68,[244,114,182],8,10);if(n.paePair){const[p,b]=n.paePair,x=f.find(_=>_.seqId===p),g=f.find(_=>_.seqId===b);x&&c.addSphere(x.xyz,.85,[34,211,238],9,12),g&&c.addSphere(g.xyz,.85,[52,211,153],9,12)}return c}render2dPanel(r,n,s,i,c){r.save(),r.beginPath(),r.rect(c.x,c.y,c.w,c.h),r.clip();const d=[],f=(b,x)=>{for(let g=0;g<b.length-1;g++){const _=b[g],y=b[g+1];if(Fd(_.xyz,y.xyz)>6.5)continue;const S=$n(i,_.xyz,c.x,c.y,c.w,c.h),k=$n(i,y.xyz,c.x,c.y,c.w,c.h);if(!S.visible||!k.visible)continue;const E=(S.ndcZ+k.ndcZ)*.5;d.push({depth:E,draw:()=>{r.strokeStyle=`rgb(${_.color[0]},${_.color[1]},${_.color[2]})`,r.lineWidth=x,r.lineCap="round",r.beginPath(),r.moveTo(S.sx,S.sy),r.lineTo(k.sx,k.sy),r.stroke()}})}};c.showRef&&f(n.refResidues,s.style==="pocket"?3:4),c.showMob&&f(n.mobResidues,s.style==="pocket"?2.4:3.2);const p=(b,x)=>{for(const g of x){const _=$n(i,g.a,c.x,c.y,c.w,c.h),y=$n(i,g.b,c.x,c.y,c.w,c.h);!_.visible||!y.visible||d.push({depth:(_.ndcZ+y.ndcZ)*.5,draw:()=>{r.strokeStyle=`rgb(${g.colorA[0]},${g.colorA[1]},${g.colorA[2]})`,r.lineWidth=2,r.beginPath(),r.moveTo(_.sx,_.sy),r.lineTo(y.sx,y.sy),r.stroke()}})}for(const g of b){const _=$n(i,g.xyz,c.x,c.y,c.w,c.h);_.visible&&d.push({depth:_.ndcZ,draw:()=>{r.fillStyle=`rgb(${g.color[0]},${g.color[1]},${g.color[2]})`,r.beginPath(),r.arc(_.sx,_.sy,g.isMetal?6:3.5,0,Math.PI*2),r.fill()}})}};c.showRef&&(p(n.ligandAtoms,n.ligandBonds),s.style==="pocket"&&p(n.pocketAtoms,n.pocketBonds)),d.sort((b,x)=>x.depth-b.depth);for(const b of d)b.draw();r.restore()}collectAndDrawHud(r,n,s,i,c,d){const f=x=>{x.sx>=i.x&&x.sx<=i.x+i.w&&x.sy>=i.y&&x.sy<=i.y+i.h&&d.push(x)};if(i.showRef){for(const x of r.refResidues){const g=$n(s,x.xyz,i.x,i.y,i.w,i.h);g.visible&&f({sx:g.sx,sy:g.sy,depth:g.ndcZ,kind:"residue",seqId:x.seqId,label:`${x.resName3} ${x.seqId} (Ref)`,xyz:x.xyz,chainKind:"ref"})}for(const x of r.ligandAtoms){const g=$n(s,x.xyz,i.x,i.y,i.w,i.h);g.visible&&f({sx:g.sx,sy:g.sy,depth:g.ndcZ,kind:"atom",seqId:x.seqId,label:x.label,xyz:x.xyz,chainKind:"ref"})}}if(i.showMob)for(const x of r.mobResidues){const g=$n(s,x.xyz,i.x,i.y,i.w,i.h);g.visible&&f({sx:g.sx,sy:g.sy,depth:g.ndcZ,kind:"residue",seqId:x.seqId,label:`${x.resName3} ${x.seqId} (Mob)`,xyz:x.xyz,chainKind:"mob"})}if(!c)return;if(c.save(),c.beginPath(),c.rect(i.x,i.y,i.w,i.h),c.clip(),i.showRef&&n.style==="pocket")for(const x of r.coordinationBonds){const g=$n(s,x.a,i.x,i.y,i.w,i.h),_=$n(s,x.b,i.x,i.y,i.w,i.h);!g.visible||!_.visible||(c.save(),c.setLineDash([4,3]),c.strokeStyle="rgba(216, 180, 254, 0.85)",c.lineWidth=1.4,c.beginPath(),c.moveTo(g.sx,g.sy),c.lineTo(_.sx,_.sy),c.stroke(),c.restore())}if(i.showRef){const x=r.ligandAtoms.find(_=>_.element==="ZN");if(x){const _=$n(s,x.xyz,i.x,i.y,i.w,i.h);_.visible&&kc(c,_.sx+10,_.sy-8,"Zn²⁺","#d8b4fe")}const g=r.ligandAtoms.find(_=>_.resName==="AZM"&&_.atomName==="S1");if(g){const _=$n(s,g.xyz,i.x,i.y,i.w,i.h);_.visible&&kc(c,_.sx+10,_.sy+10,"AZM","#67e8f9")}if(n.style==="pocket")for(const _ of[94,96,119]){const y=r.refResidues.find(k=>k.seqId===_);if(!y)continue;const S=$n(s,y.xyz,i.x,i.y,i.w,i.h);S.visible&&kc(c,S.sx+8,S.sy-6,`${y.resName3}${y.seqId}`,"#94a3b8")}}if(n.focusedSeqId!=null){const x=i.showRef&&r.refResidues.find(g=>g.seqId===n.focusedSeqId)||i.showMob&&r.mobResidues.find(g=>g.seqId===n.focusedSeqId);if(x){const g=$n(s,x.xyz,i.x,i.y,i.w,i.h);g.visible&&(c.strokeStyle="#fbbf24",c.lineWidth=2,c.beginPath(),c.arc(g.sx,g.sy,10,0,Math.PI*2),c.stroke(),kc(c,g.sx+12,g.sy-12,`${x.resName3}${x.seqId}`,"#fbbf24"))}}const[p,b]=n.distancePair;if(p&&b){const x=$n(s,p.xyz,i.x,i.y,i.w,i.h),g=$n(s,b.xyz,i.x,i.y,i.w,i.h);if(x.visible&&g.visible){c.save(),c.setLineDash([5,4]),c.strokeStyle="#f43f5e",c.lineWidth=2,c.beginPath(),c.moveTo(x.sx,x.sy),c.lineTo(g.sx,g.sy),c.stroke(),c.restore();const _=Fd(p.xyz,b.xyz),y=(x.sx+g.sx)*.5,S=(x.sy+g.sy)*.5;kc(c,y,S,`${p.resName3}${p.seqId} ↔ ${b.resName3}${b.seqId}: ${_.toFixed(2)} Å`,"#fda4af")}}else if(p){const x=$n(s,p.xyz,i.x,i.y,i.w,i.h);x.visible&&(c.strokeStyle="#f43f5e",c.lineWidth=2,c.beginPath(),c.arc(x.sx,x.sy,9,0,Math.PI*2),c.stroke(),kc(c,x.sx+10,x.sy+10,`A: ${p.resName3}${p.seqId}`,"#fda4af"))}i.title&&(c.fillStyle="rgba(15, 23, 42, 0.78)",c.fillRect(i.x+10,i.y+44,178,20),c.strokeStyle="rgba(51, 65, 85, 0.8)",c.strokeRect(i.x+10,i.y+44,178,20),c.fillStyle="#cbd5e1",c.font="600 10px ui-monospace, monospace",c.fillText(i.title,i.x+16,i.y+57)),c.restore()}}function kc(e,r,n,s,i){e.font="600 10px ui-monospace, SFMono-Regular, Menlo, monospace";const c=e.measureText(s),d=5,f=c.width+d*2,p=16;e.fillStyle="rgba(9, 13, 20, 0.84)",e.fillRect(r,n-11,f,p),e.strokeStyle="rgba(148, 163, 184, 0.35)",e.lineWidth=1,e.strokeRect(r,n-11,f,p),e.fillStyle=i,e.fillText(s,r+d,n)}function ky(e){return e==null||!Number.isFinite(e)?[148,163,184]:e>=90?[38,132,255]:e>=70?[101,203,243]:e>=50?[255,219,19]:[255,125,69]}function Cy(e){if(e==null||!Number.isFinite(e))return[148,163,184];const r=Math.max(0,Math.min(1,(e-4)/46)),n=[[98,45,186],[156,47,148],[222,73,104],[254,159,109],[252,244,152]],s=r*(n.length-1),i=Math.min(n.length-2,Math.floor(s)),c=s-i,d=n[i],f=n[i+1];return[Math.round(d[0]+(f[0]-d[0])*c),Math.round(d[1]+(f[1]-d[1])*c),Math.round(d[2]+(f[2]-d[2])*c)]}function Vd(e){if(e==null||!Number.isFinite(e))return[148,163,184];const r=Math.max(0,Math.min(1,e/4));if(r<.4){const s=r/.4;return[Math.round(16+229*s),Math.round(185+-27*s),Math.round(129+-118*s)]}const n=(r-.4)/.6;return[Math.round(245+-1*n),Math.round(158+-95*n),Math.round(11+83*n)]}function TA(e){switch(e.trim().toUpperCase()){case"ZN":return[192,132,252];case"MG":return[74,222,128];case"FE":return[249,115,22];case"N":return[96,165,250];case"O":return[248,113,113];case"S":return[250,204,21];case"P":return[251,146,60];case"F":case"CL":return[52,211,153];case"BR":return[185,28,28];default:return[203,213,225]}}function lL(e,r=1){return r>=1?`rgb(${e[0]}, ${e[1]}, ${e[2]})`:`rgba(${e[0]}, ${e[1]}, ${e[2]}, ${r})`}function cL(e){const n=Math.max(0,Math.min(30,e))/30;if(n<.35){const i=n/.35;return[Math.round(16+29*i),Math.round(210+-70*i),Math.round(160+-25*i)]}const s=(n-.35)/.65;return[Math.round(45+-30*s),Math.round(140+-117*s),Math.round(135+-93*s)]}function Ny(e,r){const n=e[0]-r[0],s=e[1]-r[1],i=e[2]-r[2];return Math.sqrt(n*n+s*s+i*i)}function uL(e,r){return e.length!==16?r:[e[0]*r[0]+e[1]*r[1]+e[2]*r[2]+e[3],e[4]*r[0]+e[5]*r[1]+e[6]*r[2]+e[7],e[8]*r[0]+e[9]*r[1]+e[10]*r[2]+e[11]]}function EA(e,r,n){const s=[];for(let i=0;i<e.length;i++)for(let c=i+1;c<e.length;c++){const d=e[i],f=e[c];if(d.isMetal||f.isMetal||d.seqId!==f.seqId||d.resName!==f.resName)continue;const p=Ny(d.xyz,f.xyz),b=d.element==="S"||f.element==="S"?r+.35:r;p>.4&&p<=b&&s.push({a:d.xyz,b:f.xyz,colorA:d.color,colorB:f.color,radius:n})}return s}function dL(e){const{comparison:r,refInspect:n,mobInspect:s,refChainId:i,mobChainId:c,colorMode:d}=e,f=new Map,p=new Map,b=new Map,x=new Map;if(r)for(const I of r.matchedResidues)f.set(I.refSeqId,I.distanceAngstrom),p.set(I.mobSeqId,I.distanceAngstrom),b.set(I.refSeqId,I.refBFactor),x.set(I.mobSeqId,I.mobPlddt);const g=[],_=r?.refDisplayAtoms?.residues;if(_&&_.length>0)for(const I of _){const J=f.get(I.seqId)??null,ge=I.bFactor??b.get(I.seqId)??null;let le=[56,189,248];d==="bfactor"?le=Cy(ge):d==="plddt"?le=[100,116,139]:d==="deviation"&&(le=J!=null?Vd(J):[100,116,139]),g.push({kind:"ref",seqId:I.seqId,insCode:I.insCode,resName3:I.resName3,resCode1:I.resCode1,xyz:I.ca,bFactor:ge,plddt:null,deviationA:J,color:le})}else if(n){const I=n.chains.find(J=>J.chainId===i)??n.chains[0];if(I)for(const J of I.residues){if(!J.ca)continue;const ge=f.get(J.seqId)??null;let le=[56,189,248];d==="bfactor"?le=Cy(J.bOrPlddt):d==="plddt"?le=[100,116,139]:d==="deviation"&&(le=Vd(ge)),g.push({kind:"ref",seqId:J.seqId,insCode:J.insCode,resName3:J.resName3,resCode1:J.resCode1,xyz:J.ca,bFactor:J.bOrPlddt,plddt:null,deviationA:ge,color:le})}}const y=[];if(r?.mobTransformedResidues&&r.mobTransformedResidues.length>0)for(const I of r.mobTransformedResidues){const J=p.get(I.seqId)??null,ge=I.plddt??x.get(I.seqId)??null;let le=[52,211,153];d==="plddt"?le=ky(ge):d==="bfactor"?le=[100,116,139]:d==="deviation"&&(le=J!=null?Vd(J):[100,116,139]),y.push({kind:"mob",seqId:I.seqId,insCode:I.insCode,resName3:I.resName3,resCode1:I.resCode1,xyz:I.xyz,bFactor:null,plddt:ge,deviationA:J,color:le})}else if(s){const I=s.chains.find(ge=>ge.chainId===c)??s.chains[0],J=r?.transform.matrixRowMajor4x4;if(I)for(const ge of I.residues){if(!ge.ca)continue;const le=J?uL(J,ge.ca):ge.ca,D=p.get(ge.seqId)??null;let ae=[52,211,153];d==="plddt"?ae=ky(ge.bOrPlddt):d==="bfactor"?ae=[100,116,139]:d==="deviation"&&(ae=Vd(D)),y.push({kind:"mob",seqId:ge.seqId,insCode:ge.insCode,resName3:ge.resName3,resCode1:ge.resCode1,xyz:le,bFactor:null,plddt:ge.bOrPlddt,deviationA:D,color:ae})}}const S=r?.refDisplayAtoms?.ligands??n?.ligands??[],k=[];for(const I of S)for(const J of I.atoms){const ge=J.element.toUpperCase(),le=ge==="ZN"||ge==="MG"||ge==="FE"||ge==="CA"||ge==="MN";k.push({id:`lig-${I.chainId}-${I.seqId}-${I.resName}-${J.name}`,label:`${I.resName} ${I.seqId} · ${J.name}`,seqId:I.seqId,resName:I.resName,atomName:J.name,element:ge,xyz:J.xyz,radius:le?.85:.42,color:TA(ge),isLigand:!0,isMetal:le})}const E=EA(k,1.88,.22),j=(r?.refDisplayAtoms?.pocketAtoms??[]).map((I,J)=>({id:`pocket-${I.seqId}-${I.atomName}-${J}`,label:`${I.resName3}${I.seqId} · ${I.atomName}`,seqId:I.seqId,resName:I.resName3,atomName:I.atomName,element:I.element.toUpperCase(),xyz:I.xyz,radius:.3,color:I.element.toUpperCase()==="C"?[148,163,184]:TA(I.element),isLigand:!1,isMetal:!1})),q=EA(j,1.85,.16),z=[],O=r?.refContacts??[],V=new Map;for(const I of k)V.set(`${I.resName}:${I.seqId}:${I.atomName}`,I);const P=new Map;for(const I of j)P.set(`${I.seqId}:${I.atomName}`,I);const $=new Map;for(const I of g)$.set(I.seqId,I);for(const I of O){const J=V.get(`${I.ligandResName}:${I.ligandSeqId}:${I.ligandAtom}`);if(!J)continue;const le=(P.get(`${I.proteinSeqId}:${I.proteinAtom}`)??void 0)?.xyz??$.get(I.proteinSeqId)?.xyz;le&&(I.ligandResName==="ZN"||I.distanceAngstrom<=3.1)&&z.push({a:J.xyz,b:le,colorA:[216,180,254],colorB:[103,232,249],radius:.1,dashed:!0})}const H=k.find(I=>I.element==="ZN");if(H)for(const I of k)I!==H&&Ny(H.xyz,I.xyz)<=2.6&&z.push({a:H.xyz,b:I.xyz,colorA:[216,180,254],colorB:[96,165,250],radius:.11,dashed:!0});const Z=[...g.map(I=>I.xyz),...y.map(I=>I.xyz)];let G=0,K=0,we=0;for(const I of Z)G+=I[0],K+=I[1],we+=I[2];const Se=Math.max(1,Z.length),Q=[G/Se,K/Se,we/Se];let F=12;for(const I of Z){const J=Ny(I,Q);J>F&&(F=J)}let he=null;if(H)he=[...H.xyz];else{const I=g.filter(J=>J.seqId===94||J.seqId===96||J.seqId===119);if(I.length>0){const J=I.reduce((ge,le)=>[ge[0]+le.xyz[0],ge[1]+le.xyz[1],ge[2]+le.xyz[2]],[0,0,0]);he=[J[0]/I.length,J[1]/I.length,J[2]/I.length]}}const W=g.slice(0,6),me=W.length>0?[W.reduce((I,J)=>I+J.xyz[0],0)/W.length,W.reduce((I,J)=>I+J.xyz[1],0)/W.length,W.reduce((I,J)=>I+J.xyz[2],0)/W.length]:null;return{refResidues:g,mobResidues:y,pocketAtoms:j,pocketBonds:q,ligandAtoms:k,ligandBonds:E,coordinationBonds:z,center:Q,radius:F,activeSiteCenter:he,nTermCenter:me}}const hL=C.forwardRef(function({comparison:r,refInspect:n,mobInspect:s,refChainId:i,mobChainId:c,layout:d,onChangeLayout:f,style:p,onChangeStyle:b,colorMode:x,onChangeColorMode:g,focusedSeqId:_,focusCameraRequest:y,highlightedSeqIds:S,highlightSourceLabel:k,onClearHighlights:E,paePair:T,onPickResidue:j,onRendererModeDetected:q,simpleMode:z=!1},O){const V=C.useRef(null),P=C.useRef(null),$=C.useRef(null),H=C.useRef(null),Z=C.useRef([]),[G,K]=C.useState({width:800,height:420}),[we,Se]=C.useState(!1),[Q,F]=C.useState([null,null]),[he,W]=C.useState(null),me=C.useMemo(()=>dL({comparison:r,refInspect:n,mobInspect:s,refChainId:i,mobChainId:c,colorMode:x}),[r,n,s,i,c,x,S]),[I,J]=C.useState({yaw:.55,pitch:.25,distance:68,target:[0,0,0]}),ge=C.useRef("");C.useEffect(()=>{const ue=`${r?.reference.sha256??""}:${r?.mobile.sha256??""}:${me.refResidues.length}`;ue!==ge.current&&me.refResidues.length+me.mobResidues.length>0&&(ge.current=ue,J({yaw:.55,pitch:.25,distance:Math.max(36,me.radius*2.55),target:[...me.center]}))},[r,me]);const le=ue=>{const He=me.refResidues.find(Pe=>Pe.seqId===ue)??me.mobResidues.find(Pe=>Pe.seqId===ue);He&&J(Pe=>({...Pe,distance:Math.max(14,Math.min(Pe.distance,26)),target:[...He.xyz]}))};C.useEffect(()=>{y&&le(y.seqId)},[y?.nonce,y?.seqId]);const D=C.useMemo(()=>_===null?null:me.refResidues.find(ue=>ue.seqId===_)??me.mobResidues.find(ue=>ue.seqId===_)??null,[_,me.refResidues,me.mobResidues]),ae=ue=>{ue==="active-site"&&me.activeSiteCenter?(J({yaw:.9,pitch:.2,distance:20,target:[...me.activeSiteCenter]}),b("pocket")):ue==="n-terminus"&&me.nTermCenter?J({yaw:-.4,pitch:.3,distance:24,target:[...me.nTermCenter]}):J({yaw:.55,pitch:.25,distance:Math.max(36,me.radius*2.55),target:[...me.center]})},pe=()=>{const ue=P.current,He=$.current;if(!ue||!He)return null;const Pe=document.createElement("canvas");Pe.width=ue.width,Pe.height=ue.height;const ut=Pe.getContext("2d");if(!ut)return null;ut.drawImage(ue,0,0),ut.drawImage(He,0,0);const Je=window.devicePixelRatio||1;return ut.fillStyle="rgba(9, 13, 20, 0.85)",ut.fillRect(0,Pe.height-24*Je,Pe.width,24*Je),ut.fillStyle="#fbbf24",ut.font=`600 ${Math.round(11*Je)}px ui-monospace, monospace`,ut.fillText(`SYNLEXA STUDIO · RESEARCH USE ONLY (RUO) · ${r?`RMSD ${r.metrics.rmsdAngstrom.toFixed(3)} A (${r.metrics.matchedCaCount} Ca)`:"3D Structure View"}`,10*Je,Pe.height-8*Je),Pe.toDataURL("image/png")};C.useImperativeHandle(O,()=>({capturePngDataUrl:pe,applyPreset:ae}));const Ae=()=>{const ue=pe();if(!ue)return;const He=document.createElement("a");He.href=ue,He.download=`synlexa-studio-ruo-viewport-${Date.now()}.png`,He.click()};C.useEffect(()=>{const ue=V.current;if(!ue)return;const He=new ResizeObserver(Pe=>{for(const ut of Pe)K({width:Math.max(200,Math.floor(ut.contentRect.width)),height:Math.max(180,Math.floor(ut.contentRect.height))})});return He.observe(ue),()=>He.disconnect()},[]),C.useEffect(()=>{const ue=P.current;if(!ue||H.current)return;const He=new oL(ue);H.current=He,q?.(He.mode)},[q]),C.useEffect(()=>{const ue=H.current,He=$.current;if(!ue||!He)return;const Pe=Math.min(2,window.devicePixelRatio||1);Z.current=ue.render(me,{layout:d,style:p,camera:I,focusedSeqId:_,highlightedSeqIds:S,distancePair:Q,paePair:T},He,G.width,G.height,Pe)},[me,d,p,I,_,S,Q,T,G]);const Ne=C.useRef({active:!1,moved:!1,startX:0,startY:0,lastX:0,lastY:0,pan:!1}),Re=(ue,He)=>{let Pe=null,ut=1/0;for(const Je of Z.current){const re=Je.sx-ue,ve=Je.sy-He,Qe=re*re+ve*ve;if(Qe<=196){const Fe=Qe+(Je.depth+1)*15;Fe<ut&&(ut=Fe,Pe=Je)}}return Pe},$e=C.useRef(new Map),Ce=C.useRef(null),Ue=ue=>{J(He=>({...He,distance:Math.max(4,Math.min(320,He.distance*ue))}))},be=(ue,He)=>{J(Pe=>{const ut=Pe.distance*.0018,Je=Math.cos(Pe.yaw),re=Math.sin(Pe.yaw);return{...Pe,target:[Pe.target[0]-ue*ut*Je,Pe.target[1]+He*ut,Pe.target[2]+ue*ut*re]}})},bt=(ue,He)=>{J(Pe=>({...Pe,yaw:Pe.yaw-ue*.0085,pitch:Math.max(-1.45,Math.min(1.45,Pe.pitch+He*.0085))}))},Ot=()=>{const ue=Array.from($e.current.values());if(ue.length<2)return null;const[He,Pe]=ue;return{dist:Math.hypot(He.x-Pe.x,He.y-Pe.y),cx:(He.x+Pe.x)/2,cy:(He.y+Pe.y)/2}},St=ue=>{if(!ue.target.closest("[data-viewport-ui]")){if(ue.currentTarget.setPointerCapture(ue.pointerId),$e.current.set(ue.pointerId,{x:ue.clientX,y:ue.clientY}),$e.current.size===2){Ce.current=Ot(),Ne.current.moved=!0;return}Ne.current={active:!0,moved:!1,startX:ue.clientX,startY:ue.clientY,lastX:ue.clientX,lastY:ue.clientY,pan:ue.shiftKey||ue.button===2||ue.button===1}}},Ke=ue=>{const He=ue.currentTarget.getBoundingClientRect(),Pe=ue.clientX-He.left,ut=ue.clientY-He.top;if($e.current.has(ue.pointerId)&&$e.current.set(ue.pointerId,{x:ue.clientX,y:ue.clientY}),$e.current.size>=2&&Ce.current){const ve=Ot();ve&&ve.dist>0&&Ce.current.dist>0&&(Ue(Ce.current.dist/ve.dist),be(ve.cx-Ce.current.cx,ve.cy-Ce.current.cy),Ce.current=ve);return}if(!Ne.current.active){if(ue.pointerType==="mouse"){const ve=Re(Pe,ut);W(ve?ve.label:null)}return}const Je=ue.clientX-Ne.current.lastX,re=ue.clientY-Ne.current.lastY;(Math.abs(ue.clientX-Ne.current.startX)>3||Math.abs(ue.clientY-Ne.current.startY)>3)&&(Ne.current.moved=!0),Ne.current.lastX=ue.clientX,Ne.current.lastY=ue.clientY,Ne.current.pan?be(Je,re):bt(Je,re)},et=ue=>{const He=$e.current.size>=2;if($e.current.delete(ue.pointerId),$e.current.size<2&&(Ce.current=null),He){Ne.current.active=!1;return}if(!Ne.current.active)return;const Pe=Ne.current.moved;if(Ne.current.active=!1,Pe)return;const ut=ue.currentTarget.getBoundingClientRect(),Je=Re(ue.clientX-ut.left,ue.clientY-ut.top);if(Je)if(we){const re=me.refResidues.find(ve=>ve.seqId===Je.seqId)??me.mobResidues.find(ve=>ve.seqId===Je.seqId)??null;re&&F(([ve,Qe])=>!ve||ve&&Qe?[re,null]:[ve,re])}else j(Je.seqId)};return C.useEffect(()=>{const ue=V.current;if(!ue)return;const He=ve=>{if(ve.target.closest("[data-viewport-ui]"))return;ve.preventDefault();const Qe=ve.deltaMode===1?16:ve.deltaMode===2?400:1,Fe=ve.deltaY*Qe;ve.ctrlKey?Ue(Math.exp(Fe*.012)):ve.shiftKey?be(-ve.deltaX*Qe,-Fe):Ue(Math.exp(Fe*.0015))};let Pe=0;const ut=ve=>{ve.preventDefault(),J(Qe=>(Pe=Qe.distance,Qe))},Je=ve=>{ve.preventDefault();const Qe=ve.scale??1;Pe>0&&Qe>0&&J(Fe=>({...Fe,distance:Math.max(4,Math.min(320,Pe/Qe))}))},re=ve=>ve.preventDefault();return ue.addEventListener("wheel",He,{passive:!1}),ue.addEventListener("gesturestart",ut,{passive:!1}),ue.addEventListener("gesturechange",Je,{passive:!1}),ue.addEventListener("gestureend",re,{passive:!1}),()=>{ue.removeEventListener("wheel",He),ue.removeEventListener("gesturestart",ut),ue.removeEventListener("gesturechange",Je),ue.removeEventListener("gestureend",re)}},[]),o.jsxs("div",{ref:V,onContextMenu:ue=>ue.preventDefault(),onPointerDown:St,onPointerMove:Ke,onPointerUp:et,onPointerCancel:et,onPointerLeave:ue=>{ue.pointerType==="mouse"&&!Ne.current.active&&W(null)},style:{touchAction:"none"},className:"relative h-full w-full cursor-grab overflow-hidden bg-[#090d14] select-none overscroll-none active:cursor-grabbing",children:[o.jsx("canvas",{ref:P,className:"absolute inset-0 h-full w-full"}),o.jsx("canvas",{ref:$,className:"pointer-events-none absolute inset-0 h-full w-full"}),o.jsxs("div",{"data-viewport-ui":!0,className:"pointer-events-none absolute top-2.5 right-2.5 left-2.5 flex flex-wrap items-center justify-between gap-2",children:[o.jsx("div",{className:"pointer-events-auto flex flex-wrap items-center gap-1 rounded-xl border border-white/10 bg-[#0d121b]/85 p-1 shadow-xl backdrop-blur-md",children:[["overlay","Overlay","Superpose both structures on the same coordinates"],["split","Split","Show reference and comparison side-by-side"],["reference","Ref Only","Show only the experimental/reference structure"],["mobile","Pred Only","Show only the predicted/mobile structure"]].map(([ue,He,Pe])=>o.jsxs("button",{type:"button",title:Pe,onClick:()=>f(ue),className:`flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] font-medium transition ${d===ue?"bg-white/[0.12] text-white shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:[ue==="split"&&o.jsx(W6,{className:"h-3.5 w-3.5"}),o.jsx("span",{children:He})]},ue))}),o.jsx("div",{className:"pointer-events-auto flex flex-wrap items-center gap-1 rounded-xl border border-white/10 bg-[#0d121b]/85 p-1 shadow-xl backdrop-blur-md",children:[["ribbon","Ribbon","Smooth backbone ribbon representation"],["trace","Cα Trace","Minimal alpha-carbon wire trace"],["pocket","Active Pocket","Highlight co-crystal ligand, metal ion & pocket sidechains"]].map(([ue,He,Pe])=>o.jsx("button",{type:"button",title:Pe,onClick:()=>b(ue),className:`rounded-lg px-2.5 py-1 text-[0.75rem] font-medium transition ${p===ue?"bg-white/[0.12] text-white shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:He},ue))}),o.jsx("div",{className:"pointer-events-auto flex flex-wrap items-center gap-1 rounded-xl border border-white/10 bg-[#0d121b]/85 p-1 shadow-xl backdrop-blur-md",children:[["identity","Identity","Color by structure (blue = reference, green = prediction)"],["plddt","pLDDT","Color by AlphaFold confidence score (0–100)"],["bfactor","B-Factor (Ų)","Color by crystallographic B-factor flexibility"],["deviation","Δd (Å)","Color by per-residue Cα distance between structures"]].map(([ue,He,Pe])=>o.jsx("button",{type:"button",title:Pe,onClick:()=>g(ue),className:`rounded-lg px-2.5 py-1 text-[0.75rem] font-medium transition ${x===ue?"bg-white/[0.12] text-white shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:He},ue))})]}),(D||S.size>0)&&o.jsxs("div",{"data-viewport-ui":!0,className:"pointer-events-none absolute top-14 right-2.5 left-2.5 flex flex-wrap items-center gap-1.5",children:[D&&o.jsxs("button",{type:"button",onClick:()=>le(D.seqId),title:"Click to center 3D camera on this residue",className:"pointer-events-auto inline-flex items-center gap-1.5 rounded-lg border border-amber-400/40 bg-[#0d121b]/85 px-2.5 py-1 font-mono text-[0.6875rem] text-amber-200 shadow backdrop-blur-md hover:border-amber-300",children:[o.jsx(Ur,{className:"h-3 w-3 text-amber-300"}),o.jsxs("span",{children:[D.resName3," ",D.seqId,D.deviationA!=null?` · Δd ${D.deviationA.toFixed(2)} Å`:"",D.plddt!=null?` · pLDDT ${D.plddt.toFixed(0)}`:""]}),o.jsx("span",{className:"text-amber-300/75",children:"Center"})]}),S.size>0&&o.jsxs("span",{className:"pointer-events-auto inline-flex items-center gap-1.5 rounded-lg border border-pink-400/40 bg-[#0d121b]/85 px-2.5 py-1 font-mono text-[0.6875rem] text-pink-200 shadow backdrop-blur-md",children:[o.jsx("span",{className:"h-2 w-2 rounded-full bg-pink-400"}),o.jsxs("span",{children:[S.size," highlighted",k?` (${k})`:""]}),E&&o.jsx("button",{type:"button",onClick:E,title:"Clear 3D highlights",className:"rounded p-0.5 text-pink-300 hover:bg-white/10 hover:text-white",children:o.jsx(Xi,{className:"h-3 w-3"})})]})]}),o.jsxs("div",{"data-viewport-ui":!0,className:"pointer-events-none absolute right-2.5 bottom-2.5 left-2.5 flex flex-wrap items-end justify-between gap-2",children:[o.jsxs("div",{className:"pointer-events-auto flex flex-wrap items-center gap-1 rounded-xl border border-white/10 bg-[#0d121b]/85 p-1 shadow-xl backdrop-blur-md",children:[o.jsxs("button",{type:"button",onClick:()=>ae("overview"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-300 hover:bg-white/[0.07]",children:[o.jsx(Oy,{className:"h-3.5 w-3.5"})," Overview"]}),o.jsxs("button",{type:"button",onClick:()=>ae("active-site"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-200 hover:bg-white/[0.07]",children:[o.jsx(Ur,{className:"h-3.5 w-3.5"})," Active Site"]}),!z&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",onClick:()=>ae("n-terminus"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-300 hover:bg-white/[0.07]",children:[o.jsx(OR,{className:"h-3.5 w-3.5"})," N-Term"]}),o.jsx("button",{type:"button",onClick:()=>ae("reset"),className:"rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-400 hover:bg-white/[0.07] hover:text-slate-200",children:"Reset"}),o.jsx("span",{className:"mx-0.5 h-3.5 w-px bg-slate-800"}),o.jsxs("button",{type:"button",onClick:()=>{Se(ue=>!ue),we&&F([null,null])},className:`flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] transition ${we?"border border-rose-500/50 bg-rose-500/20 text-rose-200":"text-slate-300 hover:bg-white/[0.07]"}`,children:[o.jsx(q6,{className:"h-3.5 w-3.5"}),o.jsx("span",{children:we?"Pick 2 Residues":"Distance (Å)"})]})]}),o.jsxs("button",{type:"button",onClick:Ae,className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-200 hover:bg-white/[0.07]",children:[o.jsx(bR,{className:"h-3.5 w-3.5"})," PNG"]})]}),o.jsxs("div",{className:"pointer-events-auto flex items-center gap-2 rounded-xl border border-white/10 bg-[#0d121b]/85 px-3 py-1.5 font-mono text-[0.75rem] text-slate-300 shadow-lg backdrop-blur-md",children:[he&&o.jsx("span",{className:"border-r border-slate-700 pr-2 text-amber-300",children:he}),x==="identity"&&o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("i",{className:"inline-block h-2 w-2 rounded-full bg-sky-400"})," Ref"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("i",{className:"inline-block h-2 w-2 rounded-full bg-emerald-400"})," Pred"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("i",{className:"inline-block h-2 w-2 rounded-full bg-purple-400"})," Zn²⁺"]})]}),x==="plddt"&&o.jsxs("span",{className:"flex items-center gap-1.5",title:"AlphaFold pLDDT confidence (distinct from B-factor)",children:[o.jsx("span",{className:"text-slate-400",children:"pLDDT:"}),o.jsx("span",{className:"text-[#2684ff]",children:"■ ≥90"}),o.jsx("span",{className:"text-[#65cbf3]",children:"■ 70-90"}),o.jsx("span",{className:"text-[#ffdb13]",children:"■ 50-70"}),o.jsx("span",{className:"text-[#ff7d45]",children:"■ <50"})]}),x==="bfactor"&&o.jsxs("span",{className:"flex items-center gap-1.5",title:"Experimental B-factor in Angstrom^2 (Plasma scale, never conflated with pLDDT)",children:[o.jsx("span",{className:"text-slate-400",children:"Exp B (Ų):"}),o.jsx("span",{className:"inline-block h-2 w-16 rounded-xs bg-gradient-to-r from-[#622dba] via-[#de4968] to-[#fcf498]"}),o.jsx("span",{children:"4 → 50+"})]}),x==="deviation"&&o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"text-slate-400",children:"Δd (Å):"}),o.jsx("span",{className:"inline-block h-2 w-16 rounded-xs bg-gradient-to-r from-emerald-500 via-amber-500 to-rose-500"}),o.jsx("span",{children:"0 → 4+"})]})]})]})]})});function mL({state:e,dispatch:r,result:n,error:s,onFocusResidue:i,simpleMode:c=!1,bridge:d}){const[f,p]=C.useState(""),[b,x]=C.useState(!1),[g,_]=C.useState(!1),[y,S]=C.useState(e.sequence),[k,E]=C.useState(null),T=e.focusSeqId??d?.focusedSeqId??null,j=e.sequence.startsWith("MSHHWGYGKHNGPEHWHK"),q=()=>{const P=f.trim().toUpperCase();P&&(r({type:"add_mutation",notation:P}),p(""))},z=C.useMemo(()=>{if(!T||T<1||T>e.sequence.length)return[];const P=e.sequence[T-1];return P?["A","R","D","W"].filter(H=>H!==P).map(H=>({notation:`${P}${T}${H}`,label:H==="A"?"Ala Scan":H==="R"?"+Charge":H==="D"?"−Charge":"Bulky Trp"})):[]},[T,e.sequence]),O=C.useMemo(()=>{const P=e.sequence.length;if(P===0)return[];const $=T&&T>=1&&T<=P?T:Math.min(P,Math.max(1,e.sliceStart+10)),H=Math.max(1,$-10),Z=Math.min(P,H+20),G=new Map;for(const we of n?.appliedMutations??[])G.set(we.pos,we.to);const K=[];for(let we=H;we<=Z;we++){const Se=e.sequence[we-1]??"X",Q=G.get(we);K.push({pos:we,wt:Se,eng:Q??Se,mutated:!!Q})}return K},[e.sequence,e.sliceStart,T,n?.appliedMutations]),V=(P,$=!1)=>{r({type:"focus_residue",seqId:P}),i(P),$&&d?.focusIn3D(P,{centerCamera:!0})};return o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3 text-xs @xl:p-4",children:[o.jsx(ir,{bridge:d,title:"Peptide & Protein Engineering Workbench",subtitle:"Test point mutations and sequence slices, inspect pH 0–14 titration & Kyte-Doolittle shifts, and map 3D contact shells.",icon:o.jsx(ar,{className:"h-4 w-4"}),guideOpen:b,onToggleGuide:()=>x(P=>!P),actions:d&&o.jsxs("button",{type:"button",onClick:()=>{d.savePeptideToProject({name:e.mutations.length>0?e.mutations.join(", "):`Peptide (${e.sliceStart}–${e.sliceEnd})`,sequence:e.sequence,mutations:e.mutations}),E("Saved"),setTimeout(()=>E(null),1600)},className:"inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs font-medium text-slate-200 hover:border-sky-400/40",children:[o.jsx(Qc,{className:"h-3.5 w-3.5 text-sky-300"}),o.jsx("span",{children:k?"Saved!":"Save Variant"})]})}),o.jsx(Qi,{open:b,title:"How Peptide Engineering Works",summary:"Simulate amino-acid substitutions (e.g. H94A) or sequence truncations against the active protein chain in deterministic Rust/WASM. Side-by-side biophysical deltas compare Wild-Type (WT) vs Engineered sequences.",steps:["Click a residue on the sequence strip below (or pick any residue in the 3D Viewer) and click one of the dynamic mutation chips (e.g. Ala Scan) or type any mutation like H94A.","Adjust Slice Start/End to evaluate a cleaved domain or peptide fragment.","Hover the pH 0–14 Titration or Kyte-Doolittle charts to inspect exact shifts, and click any 3D < 5.0 Å neighbor to jump to it in 3D."],connectionTip:"Syncs directly with your loaded 3D structure's sequence and active pocket. Clicking 'Highlight Shell in 3D' illuminates every neighboring residue within 5.0 Å of the mutated site right on the 3D structure.",glossary:[{term:"pI (Isoelectric Point)",desc:"pH where net peptide charge is 0 (Henderson-Hasselbalch model). Shifts affect solubility & purification."},{term:"GRAVY",desc:"Grand Average of Hydropathy (Kyte-Doolittle). Positive = hydrophobic; negative = hydrophilic/soluble."},{term:"ε280 (M⁻¹cm⁻¹)",desc:"Molar extinction coefficient at 280 nm from Trp, Tyr, and cystine disulfide pairs."},{term:"Steric ΔV (ų)",desc:"Net side-chain volume change from substitutions; large positive/negative ΔV inside a packed core can introduce clashes or cavities."}]}),o.jsxs("div",{className:"space-y-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("input",{value:f,onChange:P=>p(P.target.value),onKeyDown:P=>{P.key==="Enter"&&q()},placeholder:"Mutation (e.g. H94A)",className:"h-8 w-36 rounded-lg border border-white/10 bg-slate-950 px-2.5 font-mono text-xs text-slate-100 placeholder-slate-500 outline-none focus:border-cyan-500"}),o.jsxs("button",{type:"button",onClick:q,className:"flex h-8 items-center gap-1 rounded-lg border border-cyan-500/40 bg-cyan-500/15 px-2.5 text-xs font-medium text-cyan-200 hover:bg-cyan-500/25",children:[o.jsx(gh,{className:"h-3.5 w-3.5"})," Add"]})]}),e.mutations.map(P=>o.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-emerald-500/40 bg-emerald-500/15 px-2 py-1 font-mono text-[0.75rem] text-emerald-200",children:[P,o.jsx("button",{type:"button",onClick:()=>r({type:"remove_mutation",notation:P}),className:"text-emerald-300 hover:text-white","aria-label":`Remove ${P}`,children:o.jsx(Xi,{className:"h-3 w-3"})})]},P)),e.mutations.length>0&&o.jsx("button",{type:"button",onClick:()=>r({type:"set_mutations_input",raw:""}),className:"rounded-md px-2 py-1 text-[0.6875rem] text-slate-400 hover:bg-white/[0.06] hover:text-slate-200",children:"Clear all"})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2 font-mono text-[0.75rem]",children:[o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/10 bg-slate-950/70 px-2 py-1",children:[o.jsx(ar,{className:"h-3 w-3 text-slate-400"}),o.jsx("span",{className:"text-slate-400",children:"Slice"}),o.jsx("input",{type:"number",min:1,max:Math.max(1,e.sequence.length),value:e.sliceStart,onChange:P=>r({type:"set_slice",start:Number(P.target.value)||1,end:e.sliceEnd}),className:"w-14 rounded border border-white/10 bg-slate-900 px-1.5 py-0.5 text-slate-200"}),o.jsx("span",{className:"text-slate-500",children:"–"}),o.jsx("input",{type:"number",min:e.sliceStart,max:Math.max(1,e.sequence.length),value:e.sliceEnd,onChange:P=>r({type:"set_slice",start:e.sliceStart,end:Number(P.target.value)||e.sequence.length}),className:"w-14 rounded border border-white/10 bg-slate-900 px-1.5 py-0.5 text-slate-200"}),o.jsxs("span",{className:"text-[0.6875rem] text-slate-500",children:["/ ",e.sequence.length," aa"]})]}),d&&o.jsxs("div",{className:"flex items-center gap-1 font-sans",children:[d.hasRef&&o.jsxs("button",{type:"button",onClick:()=>d.syncPeptideFromChain("reference"),title:"Load amino-acid sequence from active 3D Reference chain",className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-sky-300 hover:border-sky-400/40",children:[o.jsx(gp,{className:"h-3 w-3"})," Sync Ref"]}),d.hasMob&&o.jsxs("button",{type:"button",onClick:()=>d.syncPeptideFromChain("mobile"),title:"Load amino-acid sequence from active 3D Comparison chain",className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-emerald-300 hover:border-emerald-400/40",children:[o.jsx(gp,{className:"h-3 w-3"})," Sync Mob"]})]}),o.jsxs("button",{type:"button",onClick:()=>{S(e.sequence),_(P=>!P)},className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 font-sans text-[0.6875rem] text-slate-300 hover:border-white/25",children:[o.jsx(T6,{className:"h-3 w-3"})," ",g?"Hide Seq":"Edit Seq"]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-t border-white/[0.06] pt-2",children:[z.length>0&&T!==null&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-[0.6875rem] font-medium text-amber-300",children:["At #",T,":"]}),z.map(P=>o.jsxs("button",{type:"button",onClick:()=>r({type:"add_mutation",notation:P.notation}),className:"rounded-md border border-amber-400/30 bg-amber-500/10 px-2 py-0.5 font-mono text-[0.6875rem] text-amber-200 hover:bg-amber-500/20",children:["+",P.notation," ",o.jsxs("span",{className:"font-sans text-amber-300/75",children:["(",P.label,")"]})]},P.notation))]}),j&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ml-1 text-[0.6875rem] text-slate-500",children:"CA II Active Site:"}),["H94A","T199V","H96A","H119A"].map(P=>o.jsxs("button",{type:"button",onClick:()=>r({type:"add_mutation",notation:P}),className:"rounded-md border border-white/10 bg-slate-900 px-2 py-0.5 font-mono text-[0.6875rem] text-slate-300 hover:border-emerald-500/50 hover:text-emerald-200",children:["+",P]},P))]})]}),g&&o.jsxs("div",{className:"space-y-1.5 border-t border-white/[0.06] pt-2",children:[o.jsx("textarea",{rows:3,value:y,onChange:P=>S(P.target.value),placeholder:"Paste 1-letter protein/peptide sequence…",className:"w-full rounded-lg border border-white/10 bg-slate-950 p-2 font-mono text-xs text-slate-100 outline-none focus:border-sky-500"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{type:"button",onClick:()=>_(!1),className:"rounded-md px-2.5 py-1 text-xs text-slate-400 hover:text-white",children:"Cancel"}),o.jsx("button",{type:"button",onClick:()=>{r({type:"set_sequence",sequence:y}),_(!1)},className:"rounded-md bg-sky-500 px-3 py-1 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:"Apply Sequence"})]})]}),O.length>0&&o.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto border-t border-white/[0.06] pt-2 pb-0.5",children:[o.jsx("span",{className:"mr-1 shrink-0 font-mono text-[0.6875rem] text-slate-500",children:"Window:"}),O.map(P=>{const $=P.pos===T;return o.jsxs("button",{type:"button",onClick:()=>V(P.pos,!0),title:`Residue ${P.pos}: WT ${P.wt}${P.mutated?` → ${P.eng}`:""} (click to focus in 3D)`,className:`flex min-w-7 shrink-0 flex-col items-center rounded-md border px-1 py-0.5 font-mono transition ${$?"border-amber-400 bg-amber-500/20 text-amber-200":P.mutated?"border-emerald-400/50 bg-emerald-500/15 text-emerald-200":"border-white/[0.06] bg-black/25 text-slate-300 hover:border-sky-400/40"}`,children:[o.jsx("span",{className:"text-[0.5625rem] text-slate-500",children:P.pos}),o.jsx("span",{className:"text-[0.75rem] font-semibold",children:P.mutated?`${P.wt}→${P.eng}`:P.wt})]},P.pos)})]})]}),s&&o.jsx("div",{className:"rounded-xl border border-rose-500/40 bg-rose-500/10 px-3 py-2 font-mono text-xs text-rose-200",children:s}),n&&o.jsxs("div",{className:"grid grid-cols-1 gap-3 @4xl:grid-cols-2 @6xl:grid-cols-12",children:[o.jsxs("div",{className:"flex flex-col gap-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @6xl:col-span-4",children:[o.jsxs("div",{className:"flex items-center justify-between font-mono text-[0.75rem]",children:[o.jsx("span",{className:"font-semibold text-cyan-300",children:"WT vs ENGINEERED DELTAS"}),o.jsxs("span",{className:"text-slate-400",children:[n.engineered.length," aa"]})]}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full font-mono text-[0.75rem]",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-white/10 text-slate-500",children:[o.jsx("th",{className:"py-1.5 text-left",children:"Metric"}),o.jsx("th",{className:"py-1.5 text-right",children:"WT"}),o.jsx("th",{className:"py-1.5 text-right",children:"Eng"}),o.jsx("th",{className:"py-1.5 text-right",children:"Δ"})]})}),o.jsxs("tbody",{className:"divide-y divide-white/[0.06] text-slate-200",children:[o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"Avg MW (Da)"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.mwAverageDa.toFixed(1)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.mwAverageDa.toFixed(1)}),o.jsxs("td",{className:"py-1.5 text-right text-cyan-300",children:[n.deltas.mwAverageDa>=0?"+":"",n.deltas.mwAverageDa.toFixed(1)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"Mono MW (Da)"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.mwMonoisotopicDa.toFixed(1)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.mwMonoisotopicDa.toFixed(1)}),o.jsxs("td",{className:"py-1.5 text-right text-cyan-300",children:[n.deltas.mwMonoisotopicDa>=0?"+":"",n.deltas.mwMonoisotopicDa.toFixed(1)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"pI"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.pi.toFixed(2)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.pi.toFixed(2)}),o.jsxs("td",{className:"py-1.5 text-right text-amber-300",children:[n.deltas.pi>=0?"+":"",n.deltas.pi.toFixed(3)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"Charge pH 7.4"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.chargeAtPh74.toFixed(2)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.chargeAtPh74.toFixed(2)}),o.jsxs("td",{className:"py-1.5 text-right text-emerald-300",children:[n.deltas.chargeAtPh74>=0?"+":"",n.deltas.chargeAtPh74.toFixed(2)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"GRAVY"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.gravy.toFixed(3)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.gravy.toFixed(3)}),o.jsxs("td",{className:"py-1.5 text-right text-violet-300",children:[n.deltas.gravy>=0?"+":"",n.deltas.gravy.toFixed(3)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"ε280 (red/ox)"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.extinctionReduced}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.extinctionCystine}),o.jsx("td",{className:"py-1.5 text-right text-slate-400",children:"M⁻¹cm⁻¹"})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"Steric ΔV"}),o.jsx("td",{className:"py-1.5 text-right",children:"—"}),o.jsx("td",{className:"py-1.5 text-right",children:"—"}),o.jsxs("td",{className:"py-1.5 text-right text-amber-300",children:[n.deltas.stericVolumeDeltaA3>=0?"+":"",n.deltas.stericVolumeDeltaA3.toFixed(1)," ų"]})]})]})]})}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsx(bs,{label:"Aromatic Fraction",value:`${(n.engineered.aromaticFraction*100).toFixed(1)}%`,hint:"Trp + Tyr + Phe"}),o.jsx(bs,{label:"Hydrophobic",value:`${(n.engineered.hydrophobicFraction*100).toFixed(1)}%`,hint:"Nonpolar residues"})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx(Ca,{insight:yA(n.engineered.pi,n.engineered.chargeAtPh74),compact:!0}),o.jsx(Ca,{insight:_A(n.engineered.gravy),compact:!0})]}),o.jsxs("p",{className:"text-[0.6875rem] leading-relaxed text-slate-400",children:[yA(n.engineered.pi,n.engineered.chargeAtPh74).explanation,c?"":` ${_A(n.engineered.gravy).explanation}`]})]}),o.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @6xl:col-span-5",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 font-mono text-[0.75rem]",children:[o.jsx("span",{className:"font-semibold text-cyan-300",children:"pH 0–14 TITRATION & KYTE-DOOLITTLE PROFILE"}),o.jsxs("span",{className:"flex items-center gap-3 text-[0.6875rem]",children:[o.jsx("span",{className:"text-sky-400",children:"— WT"}),o.jsx("span",{className:"text-emerald-400",children:"-- Engineered"})]})]}),o.jsx(fL,{curve:n.titrationCurve}),o.jsx(pL,{profile:n.gravyProfile,focusedPos:T,onPickPos:P=>V(P,!0)})]}),o.jsxs("div",{className:"flex flex-col gap-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @4xl:col-span-2 @6xl:col-span-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("span",{className:"font-mono text-[0.75rem] font-semibold text-violet-300",children:["3D <5.0 Å CONTACT SHELL",T!=null?` (RES ${T})`:""]}),d&&n.local3dContacts.length>0&&o.jsxs("button",{type:"button",onClick:()=>d.highlightIn3D(n.local3dContacts.map(P=>P.seqId),`Peptide Shell #${T??""}`,{focusSeqId:T??void 0,style:"pocket"}),className:"inline-flex items-center gap-1 rounded-md border border-violet-400/40 bg-violet-500/15 px-2 py-0.5 text-[0.6875rem] font-medium text-violet-200 hover:bg-violet-500/25",children:[o.jsx(_s,{className:"h-3 w-3"})," Show in 3D"]})]}),n.local3dContacts.length===0?o.jsx("div",{className:"flex flex-1 flex-col justify-center gap-2 rounded-lg border border-white/[0.06] bg-black/20 p-3 text-slate-400",children:o.jsx("p",{children:"Select a residue (e.g. click in the 3D Viewer or sequence window above) or apply a mutation like H94A to inspect its 3D <5.0 Å neighbor shell."})}):o.jsx("div",{className:"max-h-60 space-y-1.5 overflow-y-auto pr-0.5 font-mono text-[0.75rem]",children:n.local3dContacts.map(P=>o.jsxs("button",{type:"button",onClick:()=>V(P.seqId,!0),className:`flex w-full items-center justify-between rounded-lg border px-2.5 py-1.5 text-left transition ${P.seqId===T?"border-amber-400/60 bg-amber-500/10":"border-white/[0.07] bg-black/30 hover:border-cyan-400/50"}`,children:[o.jsxs("span",{className:"text-slate-200",children:[P.resName3," ",P.seqId]}),o.jsxs("span",{className:"text-emerald-300",children:[P.distanceAngstrom.toFixed(2)," Å"]})]},`${P.seqId}-${P.resName3}`))}),d&&T!==null&&o.jsxs("div",{className:"mt-auto flex flex-wrap gap-1.5 border-t border-white/[0.06] pt-2",children:[o.jsxs("button",{type:"button",onClick:()=>d.focusIn3D(T,{centerCamera:!0,openViewer:"activate"}),className:"inline-flex items-center gap-1 rounded-md border border-sky-400/40 bg-sky-500/15 px-2 py-1 text-[0.6875rem] font-medium text-sky-200 hover:bg-sky-500/25",children:[o.jsx(Ur,{className:"h-3 w-3"})," Focus #",T," in 3D"]}),o.jsxs("button",{type:"button",onClick:()=>d.sendResidueToCrispr(T),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-emerald-400/40",children:[o.jsx(Fs,{className:"h-3 w-3 text-emerald-300"})," Codon #",T]})]})]})]})]})}function fL({curve:e}){const[r,n]=C.useState(null);if(e.length<2)return null;const s=360,i=110,c=Math.min(...e.flatMap(E=>[E.wtCharge,E.engCharge]),-10),d=Math.max(...e.flatMap(E=>[E.wtCharge,E.engCharge]),10),f=Math.max(1,d-c),p=E=>28+E/14*(s-40),b=E=>i-18-(E-c)/f*(i-28),x=e.map((E,T)=>`${T===0?"M":"L"}${p(E.ph).toFixed(1)},${b(E.wtCharge).toFixed(1)}`).join(" "),g=e.map((E,T)=>`${T===0?"M":"L"}${p(E.ph).toFixed(1)},${b(E.engCharge).toFixed(1)}`).join(" "),_=b(0),y=p(7.4),S=r!==null?e[r]:null,k=E=>{const T=E.currentTarget.getBoundingClientRect(),j=(E.clientX-T.left)/T.width*s,q=Math.max(0,Math.min(14,(j-28)/(s-40)*14));let z=0,O=1/0;e.forEach((V,P)=>{const $=Math.abs(V.ph-q);$<O&&(O=$,z=P)}),n(z)};return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between font-mono text-[0.6875rem] text-slate-400",children:[o.jsx("span",{children:"Net Charge vs pH (0–14)"}),S?o.jsxs("span",{className:"text-slate-200",children:["pH ",S.ph.toFixed(1)," · WT ",S.wtCharge.toFixed(2)," · Eng ",S.engCharge.toFixed(2)]}):o.jsx("span",{children:"Hover curve to inspect"})]}),o.jsxs("svg",{viewBox:`0 0 ${s} ${i}`,onMouseMove:k,onMouseLeave:()=>n(null),className:"w-full cursor-crosshair rounded-lg border border-white/[0.06] bg-black/35",children:[o.jsx("line",{x1:28,y1:_,x2:s-12,y2:_,stroke:"#334155",strokeDasharray:"3,3",strokeWidth:1}),o.jsx("line",{x1:y,y1:6,x2:y,y2:i-14,stroke:"#f59e0b",strokeDasharray:"2,2",strokeWidth:1}),o.jsx("path",{d:x,fill:"none",stroke:"#38bdf8",strokeWidth:1.8}),o.jsx("path",{d:g,fill:"none",stroke:"#34d399",strokeWidth:1.6,strokeDasharray:"4,2"}),S&&o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:p(S.ph),y1:6,x2:p(S.ph),y2:i-14,stroke:"rgba(148,163,184,0.45)",strokeWidth:1}),o.jsx("circle",{cx:p(S.ph),cy:b(S.wtCharge),r:3,fill:"#38bdf8"}),o.jsx("circle",{cx:p(S.ph),cy:b(S.engCharge),r:3,fill:"#34d399"})]}),o.jsx("text",{x:6,y:_+3,fill:"#64748b",fontSize:8,fontFamily:"monospace",children:"0"}),o.jsx("text",{x:y+3,y:13,fill:"#fbbf24",fontSize:8,fontFamily:"monospace",children:"pH 7.4"}),o.jsx("text",{x:28,y:i-4,fill:"#64748b",fontSize:8,fontFamily:"monospace",children:"0"}),o.jsx("text",{x:s/2,y:i-4,fill:"#64748b",fontSize:8,fontFamily:"monospace",children:"7"}),o.jsx("text",{x:s-20,y:i-4,fill:"#64748b",fontSize:8,fontFamily:"monospace",children:"14"})]})]})}function pL({profile:e,focusedPos:r,onPickPos:n}){const[s,i]=C.useState(null);if(e.length<2)return null;const c=360,d=88,f=S=>10+S/Math.max(1,e.length-1)*(c-20),p=S=>d/2-S/5*(d/2-10),b=e.map((S,k)=>`${k===0?"M":"L"}${f(k).toFixed(1)},${p(S.wtScore).toFixed(1)}`).join(" "),x=e.map((S,k)=>`${k===0?"M":"L"}${f(k).toFixed(1)},${p(S.engScore).toFixed(1)}`).join(" "),g=s!==null?e[s]:null,_=r!==null?e.findIndex(S=>S.index===r):-1,y=S=>{const k=S.currentTarget.getBoundingClientRect(),E=(S.clientX-k.left)/k.width*c,T=Math.max(0,Math.min(1,(E-10)/(c-20)));return Math.round(T*(e.length-1))};return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between font-mono text-[0.6875rem] text-slate-400",children:[o.jsx("span",{children:"Kyte-Doolittle Hydropathy"}),g?o.jsxs("span",{className:"text-slate-200",children:["Res ",g.index," (",g.res,") · WT ",g.wtScore.toFixed(2)," · Eng ",g.engScore.toFixed(2)]}):o.jsx("span",{children:"Click profile to focus 3D residue"})]}),o.jsxs("svg",{viewBox:`0 0 ${c} ${d}`,onMouseMove:S=>i(y(S)),onMouseLeave:()=>i(null),onClick:S=>{const k=y(S),E=e[k];E&&n(E.index)},className:"w-full cursor-pointer rounded-lg border border-white/[0.06] bg-black/35",children:[o.jsx("line",{x1:10,y1:d/2,x2:c-10,y2:d/2,stroke:"#1e293b",strokeWidth:1}),o.jsx("path",{d:b,fill:"none",stroke:"#38bdf8",strokeWidth:1.3,opacity:.85}),o.jsx("path",{d:x,fill:"none",stroke:"#34d399",strokeWidth:1.3,strokeDasharray:"3,2",opacity:.95}),_>=0&&o.jsx("line",{x1:f(_),y1:4,x2:f(_),y2:d-4,stroke:"#fbbf24",strokeWidth:1.4}),g&&s!==null&&o.jsx("circle",{cx:f(s),cy:p(g.engScore),r:3,fill:"#fbbf24"})]})]})}const gL={all:"All Tiers","tier0-core":"Tier 0 · Instant Wasm/Rust","tier1-wasm":"Tier 1 · Browser Engine","tier2-compute":"Tier 2 · External GPU/HPC",database:"Public Databases"},bL=JSON.stringify({schemaVersion:"1.0.0",id:"org.lab.custom-scorer",name:"Custom Scoring Adapter",version:"0.1.0",category:"Cheminformatics ML",tier:"tier2-compute",license:"MIT",commercialSafe:!0,ruoRequired:!0,description:"Example user add-on wrapping a custom scoring script on a connected Compute Node.",computeAdapterId:"ml_property",mcpTools:[{name:"run_custom_ml_scorer",description:"Score candidate SMILES with custom Chemprop/DeepChem checkpoint.",computeToolId:"ml_property",inputSchema:{type:"object",properties:{smiles:{type:"string",description:"Input SMILES"}},required:["smiles"]}}]},null,2);function xL({onOpenComputeNodes:e,onOpenMcpServer:r,onOpenToolTab:n}){const[s,i]=C.useState(()=>Jd()),[c,d]=C.useState(""),[f,p]=C.useState("all"),[b,x]=C.useState(!1),[g,_]=C.useState(bL),[y,S]=C.useState(null);C.useEffect(()=>(i(Jd()),gD(()=>i(Jd()))),[]);const k=C.useMemo(()=>{const T=c.trim().toLowerCase();return s.filter(j=>f!=="all"&&j.tier!==f?!1:T?`${j.name} ${j.category} ${j.license} ${j.description}`.toLowerCase().includes(T):!0)},[s,c,f]),E=()=>{S(null);try{yD(g),x(!1)}catch(T){S(T instanceof Error?T.message:String(T))}};return o.jsx("div",{className:"@container h-full min-h-0 overflow-y-auto p-3 text-xs @xl:p-4",children:o.jsxs("div",{className:"mx-auto max-w-6xl space-y-4",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsxs("h2",{className:"flex items-center gap-2 text-base font-semibold text-slate-100",children:[o.jsx(Lp,{className:"h-4 w-4 text-sky-400"}),"Biochemistry Plugins & Add-ons"]}),o.jsxs("p",{className:"mt-1 text-slate-400",children:["Manage built-in open-source engines, external GPU adapters, database connectors, and custom"," ",o.jsx("code",{className:"text-sky-300",children:"synlexa-plugin.v1"})," add-ons. Enabled plugin tools auto-wire into MCP and the AI Assistant."]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(Oe,{size:"sm",variant:"secondary",onClick:e,children:"Configure GPU Nodes"}),o.jsx(Oe,{size:"sm",variant:"secondary",onClick:r,children:"View Exposed MCP Tools"}),o.jsx(Oe,{size:"sm",variant:"primary",icon:o.jsx(gh,{className:"h-3.5 w-3.5"}),onClick:()=>x(T=>!T),children:"Install Custom Manifest"})]})]}),b&&o.jsxs(yt,{className:"space-y-2.5 p-3.5",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"font-semibold text-slate-200",children:"Install Custom Plugin (`synlexa-plugin.v1`)"}),o.jsx(Oe,{size:"sm",variant:"ghost",onClick:()=>x(!1),children:"Close"})]}),o.jsx(Pp,{rows:10,value:g,onChange:T=>_(T.target.value),className:"font-mono text-[0.6875rem]"}),y&&o.jsx("div",{className:"rounded border border-rose-500/40 bg-rose-500/10 px-2.5 py-1.5 text-rose-200",children:y}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"text-[0.6875rem] text-slate-500",children:["Enforces ",o.jsx("code",{className:"text-slate-300",children:"ruoRequired: true"})," and declarative schema validation."]}),o.jsx(Oe,{size:"sm",variant:"primary",onClick:E,children:"Validate & Install"})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("div",{className:"relative min-w-44 flex-1 @lg:max-w-xs",children:[o.jsx(Gr,{className:"pointer-events-none absolute top-2.5 left-2.5 h-3.5 w-3.5 text-slate-500"}),o.jsx(Dn,{value:c,onChange:T=>d(T.target.value),placeholder:"Filter tools, categories, licenses…",className:"pl-8"})]}),o.jsx("div",{className:"flex flex-wrap gap-1",children:["all","tier0-core","tier1-wasm","tier2-compute","database"].map(T=>o.jsx("button",{type:"button",onClick:()=>p(T),className:`rounded-lg border px-2.5 py-1.5 text-xs transition ${f===T?"border-sky-400/50 bg-sky-500/20 text-sky-200":"border-white/10 bg-white/[0.03] text-slate-300 hover:border-white/20"}`,children:gL[T]},T))})]}),o.jsx("div",{className:"grid grid-cols-1 gap-3 @2xl:grid-cols-2 @5xl:grid-cols-3",children:k.map(T=>o.jsxs(yt,{className:"flex flex-col justify-between gap-3 p-3.5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx("span",{className:"font-semibold text-slate-100",children:T.name}),T.topPick&&o.jsxs(It,{tone:"accent",children:[o.jsx(Gs,{className:"h-2.5 w-2.5"})," Top 8"]})]}),o.jsxs("div",{className:"mt-0.5 text-[0.6875rem] text-slate-400",children:[T.category," · v",T.version]})]}),o.jsx($r,{checked:T.enabled,onChange:j=>H3(T.id,j),label:`Toggle ${T.name}`})]}),o.jsx("p",{className:"text-slate-300 leading-relaxed",children:T.description}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs(It,{tone:T.commercialSafe?"good":"warn",children:[T.commercialSafe?o.jsx(Ki,{className:"h-3 w-3"}):o.jsx(Gc,{className:"h-3 w-3"}),T.license]}),o.jsx(It,{tone:"neutral",children:T.tier}),T.requiresGpu&&o.jsx(It,{tone:"warn",children:"GPU recommended"}),T.mcpTools&&T.mcpTools.length>0&&o.jsxs(It,{tone:"accent",children:[T.mcpTools.length," MCP tool"]})]}),T.installHint&&o.jsx("div",{className:"rounded border border-white/[0.06] bg-[#070b12] px-2 py-1 font-mono text-[0.6875rem] text-slate-400",children:T.installHint})]}),o.jsxs("div",{className:"flex items-center justify-between border-t border-white/[0.06] pt-2 text-[0.6875rem] text-slate-500",children:[o.jsx("span",{className:"truncate font-mono",children:T.id}),o.jsxs("div",{className:"flex items-center gap-2",children:[n&&T.id==="org.synlexa.molstar"&&o.jsx("button",{type:"button",onClick:()=>n("viewer"),className:"text-emerald-300 hover:text-emerald-200",children:"Open 3D"}),n&&T.id==="org.synlexa.rdkit-wasm"&&o.jsx("button",{type:"button",onClick:()=>n("chemistry"),className:"text-emerald-300 hover:text-emerald-200",children:"Open Ligands"}),n&&T.id==="org.synlexa.gemmi-core"&&o.jsx("button",{type:"button",onClick:()=>n("ramachandran"),className:"text-emerald-300 hover:text-emerald-200",children:"Open Tools"}),n&&T.id==="org.synlexa.workflows"&&o.jsx("button",{type:"button",onClick:()=>n("workflow"),className:"text-emerald-300 hover:text-emerald-200",children:"Open Canvas"}),n&&T.tier==="tier2-compute"&&T.id!=="org.synlexa.workflows"&&o.jsx("button",{type:"button",onClick:()=>n("compute"),className:"text-emerald-300 hover:text-emerald-200",children:"GPU Runner"}),T.homepage&&o.jsxs("a",{href:T.homepage,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-sky-300 hover:text-sky-200",children:["Source ",o.jsx(Kd,{className:"h-3 w-3"})]}),!T.builtin&&o.jsx("button",{type:"button",onClick:()=>_D(T.id),className:"text-rose-300 hover:text-rose-200",title:"Uninstall custom plugin",children:o.jsx(Wi,{className:"h-3.5 w-3.5"})})]})]})]},T.id))})]})})}const Er=260,Or=28,Ip=Er-Or*2,Jf=360;function Qn(e){return Or+(e+180)/360*Ip}function Jn(e){return Or+(180-e)/360*Ip}function yL(e){if(e.region==="outlier")return"#fb7185";switch(e.secondary){case"helix":return"#38bdf8";case"sheet":return"#34d399";default:return"#fbbf24"}}function _L({refLabel:e,refChain:r,mobLabel:n,mobChain:s,activeSource:i,onChangeSource:c,result:d,error:f,focusedSeqId:p,onFocusResidue:b,simpleMode:x=!1,bridge:g}){const[_,y]=C.useState(null),[S,k]=C.useState(null),[E,T]=C.useState("all"),[j,q]=C.useState(8),[z,O]=C.useState(!1),[V,P]=C.useState(!1),$=C.useRef(null),H=C.useMemo(()=>{const I=new Map;for(const J of d?.residues??[])I.set(J.seqId,J);return I},[d]),Z=C.useMemo(()=>{if(!d)return null;const I=Math.max(1,d.residueCount),{helix:J,sheet:ge,loop:le}=d.secondaryCounts,{favored:D,allowed:ae,outlier:pe}=d.regionCounts,Ae=Math.max(1,D+ae+pe);return{helixPct:J/I*100,sheetPct:ge/I*100,loopPct:le/I*100,favoredPct:D/Ae*100,allowedPct:ae/Ae*100,outlierPct:pe/Ae*100,classified:Ae}},[d]),G=C.useMemo(()=>(d?.residues??[]).filter(I=>I.phiDeg===null||I.psiDeg===null?!1:I.seqId===p||E==="all"?!0:E==="outlier"?I.region==="outlier":I.secondary===E),[d,E,p]),K=C.useMemo(()=>(d?.residues??[]).filter(I=>I.region==="outlier"),[d]),we=C.useMemo(()=>{if(!d)return[];const I=z?12:4;return d.contactPairs.filter(([J,ge,le])=>le<=j&&Math.abs(J-ge)>=I)},[d,j,z]),Se=C.useMemo(()=>p!==null?H.get(p)??null:null,[H,p]),Q=C.useMemo(()=>p===null?[]:we.filter(([I,J])=>I===p||J===p).sort((I,J)=>I[2]-J[2]),[we,p]),F=C.useMemo(()=>{if(!d||d.residues.length===0)return{min:1,max:1};let I=d.residues[0].seqId,J=d.residues[0].seqId;for(const ge of d.residues)ge.seqId<I&&(I=ge.seqId),ge.seqId>J&&(J=ge.seqId);return{min:I,max:Math.max(I+1,J)}},[d]);C.useEffect(()=>{const I=$.current;if(!I)return;const J=I.getContext("2d");if(!J)return;const ge=Jf;if(J.fillStyle="#070a10",J.fillRect(0,0,ge,ge),!d||d.residues.length===0)return;const le=12,D=F.max-F.min,ae=pe=>le+(pe-F.min)/D*(ge-le*2);J.strokeStyle="rgba(148, 163, 184, 0.08)",J.lineWidth=1;for(let pe=Math.ceil(F.min/50)*50;pe<=F.max;pe+=50){const Ae=ae(pe);J.beginPath(),J.moveTo(Ae,le),J.lineTo(Ae,ge-le),J.moveTo(le,Ae),J.lineTo(ge-le,Ae),J.stroke()}J.strokeStyle="rgba(148, 163, 184, 0.25)",J.lineWidth=1.25,J.beginPath(),J.moveTo(le,le),J.lineTo(ge-le,ge-le),J.stroke();for(const[pe,Ae,Ne]of we){const Re=ae(pe),$e=ae(Ae),Ce=Math.max(0,Math.min(1,(j-Ne)/Math.max(1,j-3.5)));J.fillStyle=Ne<=5.5?`rgba(52, 211, 153, ${.6+Ce*.4})`:`rgba(56, 189, 248, ${.4+Ce*.45})`,J.fillRect(Re-1.6,$e-1.6,3.4,3.4),J.fillRect($e-1.6,Re-1.6,3.4,3.4)}if(p!==null){const pe=ae(p);J.strokeStyle="rgba(251, 191, 36, 0.8)",J.lineWidth=1.5,J.beginPath(),J.moveTo(pe,0),J.lineTo(pe,ge),J.moveTo(0,pe),J.lineTo(ge,pe),J.stroke()}},[d,we,j,F,p]);const he=(I,J=!1)=>{b(I),J&&g?.focusIn3D(I,{centerCamera:!0})},W=(I,J)=>{if(!d||we.length===0)return;const ge=I.currentTarget.getBoundingClientRect(),le=ge.width,D=12/Jf,ae=le*D,pe=F.max-F.min,Ae=F.min+(I.clientX-ge.left-ae)/Math.max(1,le-ae*2)*pe,Ne=F.min+(I.clientY-ge.top-ae)/Math.max(1,le-ae*2)*pe;let Re=null,$e=160;for(const Ce of we){const Ue=(Ce[0]-Ae)**2+(Ce[1]-Ne)**2,be=(Ce[1]-Ae)**2+(Ce[0]-Ne)**2,bt=Math.min(Ue,be);bt<$e&&($e=bt,Re=Ce)}k(Re),J&&Re&&he(Re[0],!0)},me=!!(e||n);return o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3 text-xs @xl:p-4",children:[o.jsx(ir,{bridge:g,title:"Ramachandran Geometry & Cα Contact Map",subtitle:"Inspect backbone dihedral angles (φ, ψ), secondary structure packing, conformational outliers, and 3D tertiary contacts.",icon:o.jsx(Qo,{className:"h-4 w-4"}),guideOpen:V,onToggleGuide:()=>P(I=>!I)}),o.jsx(Qi,{open:V,title:"How Ramachandran & Cα Contact Analysis Works",summary:"Every protein residue’s backbone conformation is defined by two dihedral torsion angles: φ (N–Cα) and ψ (Cα–C). Plotting φ vs ψ reveals well-packed α-helices and β-sheets versus strained outliers.",steps:["Switch between Reference (experimental) and Mobile (predicted) structures in the toolbar below.","Filter the Ramachandran plot by Helix, Sheet, Loop, or Outliers Only; click any dot to inspect its φ/ψ angles and sync the 3D Viewer.","Use the Cα–Cα Contact Map to inspect folded tertiary contacts (distant residues in sequence that touch in 3D space). Adjust the Å cutoff or toggle Long-Range contacts."],connectionTip:"Every click on a Ramachandran dot, outlier chip, or contact neighbor synchronizes your focused residue across the 3D Viewer, Sequence Track, Peptide, and CRISPR tabs. Use 'Highlight Outliers in 3D' or 'Highlight Contacts in 3D' to light them up directly on the 3D model.",glossary:[{term:"Favored / Allowed / Outlier",desc:"Empirical backbone angle regions; well-refined proteins typically have ≥ 90% in favored zones (Gly and Pro can legitimately occupy broader regions)."},{term:"Cα–Cα Contact (≤ 8 Å)",desc:"Residues separated by at least 4 sequence positions whose alpha carbons sit within 8 Å in 3D — defining secondary & tertiary fold packing."},{term:"Long-Range (|i−j| ≥ 12)",desc:"Contacts between distant parts of the chain that reveal global domain folding rather than local helix turns."}]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-xl border border-white/[0.08] bg-[#0b1018] p-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 font-mono text-xs",children:[o.jsxs("button",{type:"button",disabled:!e,onClick:()=>c("reference"),className:`rounded-lg border px-2.5 py-1 transition disabled:opacity-40 ${i==="reference"?"border-sky-400/50 bg-sky-500/20 text-sky-200":"border-white/10 bg-slate-950 text-slate-400 hover:text-slate-200"}`,children:["Ref: ",e||"None"," (",r||"?",")"]}),o.jsxs("button",{type:"button",disabled:!n,onClick:()=>c("mobile"),className:`rounded-lg border px-2.5 py-1 transition disabled:opacity-40 ${i==="mobile"?"border-emerald-400/50 bg-emerald-500/20 text-emerald-200":"border-white/10 bg-slate-950 text-slate-400 hover:text-slate-200"}`,children:["Mob: ",n||"None"," (",s||"?",")"]})]}),o.jsx("div",{className:"flex flex-wrap items-center gap-1",children:[["all","All"],["helix","α-Helix"],["sheet","β-Sheet"],["loop","Loop"],["outlier",`Outliers (${K.length})`]].map(([I,J])=>o.jsx("button",{type:"button",onClick:()=>T(I),className:`rounded-md border px-2 py-1 font-mono text-[0.6875rem] transition ${E===I?"border-cyan-400/50 bg-cyan-500/20 text-cyan-200":"border-white/10 bg-slate-900/70 text-slate-400 hover:text-slate-200"}`,children:J},I))})]}),f&&o.jsx("div",{className:"rounded-xl border border-rose-500/40 bg-rose-500/10 px-3 py-2 font-mono text-xs text-rose-200",children:f}),!me&&!d&&!f&&o.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 rounded-xl border border-white/[0.08] bg-[#0b1018] p-6 text-center",children:[o.jsx(Qo,{className:"h-8 w-8 text-slate-500"}),o.jsx("div",{className:"text-sm font-medium text-slate-200",children:"No structure loaded for Ramachandran analysis"}),o.jsx("p",{className:"max-w-md text-xs text-slate-400",children:"Load a PDB or mmCIF structure to compute backbone φ/ψ dihedral angles and tertiary Cα–Cα contact maps."}),g&&o.jsxs("button",{type:"button",onClick:g.loadExample,className:"inline-flex items-center gap-1.5 rounded-lg bg-sky-500 px-3.5 py-2 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:[o.jsx(Br,{className:"h-3.5 w-3.5"})," Load Carbonic Anhydrase II Example"]})]}),me&&!d&&!f&&o.jsx("div",{className:"flex flex-1 items-center justify-center rounded-xl border border-white/[0.08] bg-[#0b1018] p-6 font-mono text-xs text-slate-500",children:"Computing backbone φ/ψ dihedral angles and Cα–Cα contact distances in Wasm…"}),d&&Z&&o.jsxs("div",{className:"grid grid-cols-1 gap-3 @3xl:grid-cols-2 @6xl:grid-cols-12",children:[o.jsxs("div",{className:"flex flex-col gap-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @6xl:col-span-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 font-mono text-[0.75rem]",children:[o.jsx("span",{className:"font-semibold text-cyan-300",children:"RAMACHANDRAN PLOT"}),o.jsx("span",{className:"text-slate-300",children:_?`${_.resName3}${_.seqId} (φ ${_.phiDeg?.toFixed(0)}°, ψ ${_.psiDeg?.toFixed(0)}°)`:Se&&Se.phiDeg!==null?`Sel: ${Se.resName3}${Se.seqId} · ${Se.region}`:"Click any dot to focus in 3D"})]}),o.jsx("div",{className:"flex w-full justify-center",children:o.jsxs("svg",{viewBox:`0 0 ${Er} ${Er}`,className:"aspect-square w-full max-w-[330px] rounded-lg border border-white/10 bg-[#070a10]",children:[o.jsx("rect",{x:Qn(-165),y:Jn(175),width:Qn(-65)-Qn(-165),height:Jn(85)-Jn(175),rx:6,fill:"rgba(52, 211, 153, 0.12)",stroke:"rgba(52, 211, 153, 0.35)",strokeWidth:.85}),o.jsx("rect",{x:Qn(-105),y:Jn(-5),width:Qn(-35)-Qn(-105),height:Jn(-70)-Jn(-5),rx:6,fill:"rgba(56, 189, 248, 0.14)",stroke:"rgba(56, 189, 248, 0.38)",strokeWidth:.85}),o.jsx("rect",{x:Qn(35),y:Jn(65),width:Qn(95)-Qn(35),height:Jn(5)-Jn(65),rx:5,fill:"rgba(56, 189, 248, 0.09)",stroke:"rgba(56, 189, 248, 0.25)",strokeWidth:.85}),o.jsx("line",{x1:Qn(0),y1:Or,x2:Qn(0),y2:Er-Or,stroke:"rgba(148,163,184,0.25)",strokeDasharray:"2 2"}),o.jsx("line",{x1:Or,y1:Jn(0),x2:Er-Or,y2:Jn(0),stroke:"rgba(148,163,184,0.25)",strokeDasharray:"2 2"}),o.jsx("rect",{x:Or,y:Or,width:Ip,height:Ip,fill:"none",stroke:"rgba(51,65,85,0.85)"}),o.jsx("text",{x:Er/2,y:Er-7,textAnchor:"middle",fill:"#64748b",fontSize:"9",fontFamily:"monospace",children:"φ (deg) [-180 … +180]"}),o.jsx("text",{x:10,y:Er/2,textAnchor:"middle",fill:"#64748b",fontSize:"9",fontFamily:"monospace",transform:`rotate(-90 10 ${Er/2})`,children:"ψ (deg)"}),o.jsx("text",{x:Qn(-115),y:Jn(135),textAnchor:"middle",fill:"rgba(52,211,153,0.65)",fontSize:"8",fontFamily:"monospace",children:"β-sheet"}),o.jsx("text",{x:Qn(-70),y:Jn(-38),textAnchor:"middle",fill:"rgba(56,189,248,0.75)",fontSize:"8",fontFamily:"monospace",children:"α-helix"}),o.jsx("text",{x:Qn(65),y:Jn(35),textAnchor:"middle",fill:"rgba(56,189,248,0.55)",fontSize:"7",fontFamily:"monospace",children:"L-helix"}),G.map(I=>{const J=Qn(I.phiDeg),ge=Jn(I.psiDeg),le=I.seqId===p;return o.jsxs("g",{children:[le&&o.jsx("circle",{cx:J,cy:ge,r:7.5,fill:"none",stroke:"#fbbf24",strokeWidth:1.8}),o.jsx("circle",{cx:J,cy:ge,r:le?4.2:I.region==="outlier"?3.5:2.5,fill:yL(I),fillOpacity:le?1:.85,className:"cursor-pointer",onMouseEnter:()=>y(I),onMouseLeave:()=>y(null),onClick:()=>he(I.seqId,!0)})]},`${I.seqId}-${I.insCode}`)})]})}),o.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-3 font-mono text-[0.6875rem] text-slate-400",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-sky-400"})," Helix"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-emerald-400"})," Sheet"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-amber-400"})," Loop"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-rose-400"})," Outlier"]})]})]}),o.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @6xl:col-span-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 font-mono text-[0.75rem]",children:[o.jsx("span",{className:"font-semibold text-cyan-300",children:"SECONDARY STRUCTURE & GEOMETRY"}),o.jsxs("span",{className:"text-slate-400",children:[d.residueCount," res"]})]}),o.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-cyan-500/25 bg-cyan-500/8 px-2.5 py-2 text-xs leading-relaxed text-cyan-100",children:[o.jsx(zy,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-cyan-300"}),o.jsxs("span",{children:[Z.favoredPct>=90?`${Z.favoredPct.toFixed(1)}% of dihedral pairs sit in favored Ramachandran zones — typical of well-packed backbone geometry.`:`${Z.favoredPct.toFixed(1)}% favored (${d.regionCounts.outlier} outlier${d.regionCounts.outlier===1?"":"s"}). Click rose dots or outlier chips to inspect strained residues in 3D.`,x?"":" Click any residue dot or outlier below to jump in 3D."]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex h-2.5 w-full overflow-hidden rounded-full bg-slate-900",children:[o.jsx("div",{style:{width:`${Z.helixPct}%`},className:"bg-sky-400",title:`α-Helix ${Z.helixPct.toFixed(1)}%`}),o.jsx("div",{style:{width:`${Z.sheetPct}%`},className:"bg-emerald-400",title:`β-Sheet ${Z.sheetPct.toFixed(1)}%`}),o.jsx("div",{style:{width:`${Z.loopPct}%`},className:"bg-amber-400",title:`Loop / Turn ${Z.loopPct.toFixed(1)}%`})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 font-mono text-xs",children:[o.jsxs("div",{className:"min-w-0 rounded-lg border border-white/[0.07] bg-black/25 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-sky-300",children:"α-Helix"}),o.jsxs("div",{className:"mt-0.5 font-bold text-slate-100",children:[Z.helixPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-500",children:[d.secondaryCounts.helix," res"]})]}),o.jsxs("div",{className:"min-w-0 rounded-lg border border-white/[0.07] bg-black/25 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-emerald-300",children:"β-Sheet"}),o.jsxs("div",{className:"mt-0.5 font-bold text-slate-100",children:[Z.sheetPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-500",children:[d.secondaryCounts.sheet," res"]})]}),o.jsxs("div",{className:"min-w-0 rounded-lg border border-white/[0.07] bg-black/25 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-amber-300",children:"Loop / Turn"}),o.jsxs("div",{className:"mt-0.5 font-bold text-slate-100",children:[Z.loopPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-500",children:[d.secondaryCounts.loop," res"]})]})]})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 font-mono text-xs",children:[o.jsxs("div",{className:"min-w-0 rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-emerald-300",children:"Favored"}),o.jsxs("div",{className:"mt-0.5 font-bold text-emerald-200",children:[Z.favoredPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-400",children:[d.regionCounts.favored," res"]})]}),o.jsxs("div",{className:"min-w-0 rounded-lg border border-sky-500/30 bg-sky-500/10 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-sky-300",children:"Allowed"}),o.jsxs("div",{className:"mt-0.5 font-bold text-sky-200",children:[Z.allowedPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-400",children:[d.regionCounts.allowed," res"]})]}),o.jsxs("div",{className:"min-w-0 rounded-lg border border-rose-500/30 bg-rose-500/10 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-rose-300",children:"Outliers"}),o.jsx("div",{className:"mt-0.5 font-bold text-rose-200",children:d.regionCounts.outlier}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-400",children:[Z.outlierPct.toFixed(1),"%"]})]})]}),K.length>0&&o.jsxs("div",{className:"space-y-1.5 rounded-lg border border-rose-500/20 bg-rose-500/[0.04] p-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("span",{className:"font-mono text-[0.6875rem] font-medium text-rose-300",children:["Outliers (",K.length,"):"]}),g&&o.jsxs("button",{type:"button",onClick:()=>g.highlightIn3D(K.map(I=>I.seqId),"Ramachandran Outliers",{focusSeqId:K[0]?.seqId}),className:"inline-flex items-center gap-1 rounded-md border border-rose-400/40 bg-rose-500/15 px-2 py-0.5 text-[0.6875rem] font-medium text-rose-200 hover:bg-rose-500/25",children:[o.jsx(_s,{className:"h-3 w-3"})," Highlight Outliers in 3D"]})]}),o.jsx("div",{className:"flex flex-wrap gap-1 font-mono text-[0.6875rem]",children:K.slice(0,14).map(I=>o.jsxs("button",{type:"button",onClick:()=>he(I.seqId,!0),className:`rounded-md border px-2 py-0.5 transition ${I.seqId===p?"border-amber-400 bg-amber-400/20 text-amber-200":"border-rose-500/40 bg-rose-500/10 text-rose-200 hover:bg-rose-500/20"}`,children:[I.resName3,I.seqId]},`${I.seqId}-${I.insCode}`))})]}),Se&&o.jsxs("div",{className:"mt-auto space-y-2 rounded-lg border border-amber-400/30 bg-amber-500/[0.05] p-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("span",{className:"font-mono text-xs font-semibold text-amber-200",children:[Se.resName3," ",Se.seqId," (",Se.resCode1,")"]}),o.jsxs("span",{className:"font-mono text-[0.6875rem] text-slate-300",children:[Se.secondary," · ",Se.region]})]}),o.jsxs("div",{className:"flex flex-wrap gap-3 font-mono text-[0.6875rem] text-slate-300",children:[o.jsxs("span",{children:["φ = ",Se.phiDeg!==null?`${Se.phiDeg.toFixed(1)}°`:"terminal"]}),o.jsxs("span",{children:["ψ = ",Se.psiDeg!==null?`${Se.psiDeg.toFixed(1)}°`:"terminal"]}),o.jsxs("span",{children:["Contacts: ",Q.length]})]}),g&&o.jsxs("div",{className:"flex flex-wrap gap-1.5 pt-0.5",children:[o.jsxs("button",{type:"button",onClick:()=>g.focusIn3D(Se.seqId,{centerCamera:!0,openViewer:"activate"}),className:"inline-flex items-center gap-1 rounded-md border border-sky-400/40 bg-sky-500/15 px-2 py-1 text-[0.6875rem] font-medium text-sky-200 hover:bg-sky-500/25",children:[o.jsx(Ur,{className:"h-3 w-3"})," Focus in 3D"]}),o.jsxs("button",{type:"button",onClick:()=>g.openTab("sequence"),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-sky-400/40",children:[o.jsx(Vo,{className:"h-3 w-3"})," Sequence Δd"]}),o.jsxs("button",{type:"button",onClick:()=>g.sendMutationToPeptide(`${Se.resCode1}${Se.seqId}A`,Se.seqId),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-emerald-400/40",children:[o.jsx(ar,{className:"h-3 w-3"})," Ala Scan in Peptide"]})]})]})]}),o.jsxs("div",{className:"@container flex flex-col gap-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @3xl:col-span-2 @6xl:col-span-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 font-mono text-[0.75rem]",children:[o.jsxs("span",{className:"font-semibold text-emerald-300",children:["Cα–Cα CONTACT MAP (|i−j|≥",z?12:4,", ≤",j.toFixed(1)," Å)"]}),o.jsx("span",{className:"text-slate-300",children:S?`${S[0]}–${S[1]}: ${S[2].toFixed(2)} Å`:`${we.length} pairs`})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border border-white/[0.06] bg-black/25 px-2.5 py-1.5 text-[0.6875rem]",children:[o.jsxs("label",{className:"flex items-center gap-2 font-mono text-slate-300",children:[o.jsxs("span",{children:["Cutoff: ",j.toFixed(1)," Å"]}),o.jsx("input",{type:"range",min:5,max:8,step:.2,value:j,onChange:I=>q(Number(I.target.value)),className:"w-24 accent-emerald-400"})]}),o.jsx("button",{type:"button",onClick:()=>O(I=>!I),className:`rounded-md border px-2 py-0.5 font-mono transition ${z?"border-emerald-400/50 bg-emerald-500/20 text-emerald-200":"border-white/10 bg-slate-900 text-slate-400 hover:text-slate-200"}`,children:z?"Long-Range |i−j|≥12":"All |i−j|≥4"})]}),o.jsxs("div",{className:"flex flex-col items-center gap-3 @lg:flex-row @lg:items-start",children:[o.jsx("canvas",{ref:$,width:Jf,height:Jf,onMouseMove:I=>W(I,!1),onClick:I=>W(I,!0),onMouseLeave:()=>k(null),className:"aspect-square w-full max-w-[280px] shrink-0 cursor-crosshair rounded-lg border border-white/10"}),o.jsxs("div",{className:"w-full min-w-0 flex-1 space-y-2 font-mono text-xs",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-1.5",children:[o.jsx("span",{className:"text-[0.6875rem] text-slate-300",children:p!==null?`Neighbors of ${Se?`${Se.resName3}${p}`:`Res ${p}`} (${Q.length})`:"Click plot or contact map to inspect tertiary neighbors."}),g&&Q.length>0&&o.jsx("button",{type:"button",onClick:()=>{const I=Q.map(([J,ge])=>J===p?ge:J);g.highlightIn3D(I,`Cα Contacts of #${p}`,{focusSeqId:p??void 0})},className:"rounded border border-emerald-400/40 bg-emerald-500/15 px-1.5 py-0.5 font-sans text-[0.6875rem] font-medium text-emerald-200 hover:bg-emerald-500/25",children:"Show in 3D"})]}),o.jsxs("div",{className:"grid max-h-56 grid-cols-1 gap-1 overflow-y-auto pr-0.5 @sm:grid-cols-2",children:[Q.slice(0,24).map(([I,J,ge],le)=>{const D=I===p?J:I,ae=H.get(D);return o.jsxs("button",{type:"button",onClick:()=>he(D,!0),className:"flex items-center justify-between gap-1.5 rounded-lg border border-white/[0.08] bg-black/30 px-2 py-1 text-left text-[0.6875rem] text-slate-200 hover:border-emerald-400/50 hover:text-emerald-200",children:[o.jsx("span",{className:"truncate",children:ae?`${ae.resName3} ${D}`:`Res ${D}`}),o.jsxs("span",{className:"shrink-0 text-emerald-300",children:[ge.toFixed(1)," Å"]})]},`${I}-${J}-${le}`)}),p!==null&&Q.length===0&&o.jsxs("span",{className:"col-span-full text-[0.6875rem] text-slate-500",children:["No non-local Cα contacts within ",j.toFixed(1)," Å."]})]})]})]})]})]})]})}function vL({comparison:e,paeJson:r,busy:n,guided:s,selectedPaePair:i,onSelectPaePair:c,includePng:d,onToggleIncludePng:f,onExportHtml:p,onExportJson:b,onExportBundle:x,bridge:g}){const[_,y]=C.useState(null),[S,k]=C.useState(!1),[E,T]=C.useState(!1),j=C.useMemo(()=>e?Rq(e.matchedResidues.map($=>$.mobPlddt)):null,[e]),q=C.useMemo(()=>zq(r),[r]),z=C.useMemo(()=>e?[...e.matchedResidues].sort(($,H)=>H.distanceAngstrom-$.distanceAngstrom).slice(0,8):[],[e]);if(!e)return o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col p-3 @xl:p-4",children:[o.jsx(ir,{bridge:g,title:"Comparison Results & Provenance",subtitle:"Quantitative RMSD, coverage, PAE matrix, top deviation hotspots, and RUO exports.",icon:o.jsx(qi,{className:"h-4 w-4"}),guideOpen:E,onToggleGuide:()=>T($=>!$)}),o.jsx("div",{className:"flex-1",children:o.jsx(mE,{icon:o.jsx(qi,{className:"h-8 w-8"}),title:n?"Running comparison…":"No comparison yet",description:"Load a reference and a comparison structure (from a file, your library, or a public database) to see RMSD, coverage, confidence, and provenance here."})})]});const O=e.metrics,V=$=>{navigator.clipboard?.writeText($),y($),setTimeout(()=>y(null),1500)},P=[{label:"Cα RMSD",value:`${O.rmsdAngstrom.toFixed(3)} Å`,sub:"after rigid superposition",tone:"text-emerald-300"},{label:"Matched Cα",value:String(O.matchedCaCount),sub:"aligned residue pairs"},{label:"Reference coverage",value:`${(O.refCoverage.ratio*100).toFixed(1)}%`,sub:`${O.refCoverage.numerator} / ${O.refCoverage.denominator}`},{label:"Comparison coverage",value:`${(O.mobCoverage.ratio*100).toFixed(1)}%`,sub:`${O.mobCoverage.numerator} / ${O.mobCoverage.denominator}`}];return j!==null&&P.push({label:"Mean pLDDT",value:j.toFixed(1),sub:"prediction confidence (0–100)"}),q!==null&&P.push({label:"Mean PAE",value:`${q.toFixed(1)} Å`,sub:"predicted aligned error"}),o.jsx("div",{className:"@container h-full min-h-0 overflow-y-auto",children:o.jsxs("div",{className:"mx-auto max-w-5xl space-y-4 p-3 @xl:px-5 @xl:py-5",children:[o.jsx(ir,{bridge:g,title:`${e.reference.label} (${e.reference.chainId}) vs ${e.mobile.label} (${e.mobile.chainId})`,subtitle:"Deterministic Kabsch rigid superposition metrics, PAE domain confidence, top deviation hotspots & RUO exports.",icon:o.jsx(qi,{className:"h-4 w-4"}),guideOpen:E,onToggleGuide:()=>T($=>!$),actions:g&&o.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.jsx("button",{type:"button",onClick:()=>{g.setColorMode3D("deviation"),g.openTab("viewer",!1)},className:"rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-sky-400/40",children:"Color 3D by Δd"}),o.jsx("button",{type:"button",onClick:()=>{g.setColorMode3D("plddt"),g.openTab("viewer",!1)},className:"rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-emerald-400/40",children:"Color 3D by pLDDT"})]})}),o.jsx(Qi,{open:E,title:"How to Read Comparison Results",summary:"Results summarize deterministic Cα Kabsch superposition between your reference and comparison structures, paired with AlphaFold PAE uncertainty when available.",steps:["Check Cα RMSD and Coverage cards to see global fold similarity and whether termini/loops were excluded.","Inspect Highest Deviation Residues below and click any residue to jump directly to it in 3D.","Click any cell on the PAE heatmap to verify inter-residue domain confidence and focus residue i in 3D."],connectionTip:"Use 'Color 3D by Δd' or click any residue in the deviation table or PAE heatmap to synchronize the 3D Viewer, Sequence Track, and Ramachandran plot."}),o.jsx("div",{className:"grid grid-cols-2 gap-3 @2xl:grid-cols-3",children:P.map($=>o.jsxs("div",{className:"min-w-0 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5",children:[o.jsx("div",{className:"truncate text-xs text-slate-400",children:$.label}),o.jsx("div",{className:`mt-1 truncate text-xl font-semibold tabular-nums @2xl:text-2xl ${$.tone??"text-slate-100"}`,children:$.value}),$.sub&&o.jsx("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:$.sub})]},$.label))}),o.jsx(yt,{title:"Plain-English Summary",description:"Deterministic metric interpretations (RUO heuristics).",children:o.jsxs("div",{className:"grid gap-2 @2xl:grid-cols-2",children:[o.jsx(Ca,{insight:Aq(O.rmsdAngstrom)}),o.jsx(Ca,{insight:jq(O.refCoverage.ratio,O.refCoverage.numerator,O.refCoverage.denominator)}),j!==null&&o.jsx(Ca,{insight:wE(j)}),q!==null&&o.jsx(Ca,{insight:Tq(q)})]})}),z.length>0&&o.jsx(yt,{title:"Highest Structural Deviations (Top Δd Residues)",description:"Residues with the largest Cα-to-Cα offset after rigid superposition — click any chip to inspect in 3D.",actions:g&&o.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.jsxs("button",{type:"button",onClick:()=>g.highlightIn3D(z.map($=>$.refSeqId),"Top Δd Hotspots",{focusSeqId:z[0]?.refSeqId}),className:"inline-flex items-center gap-1 rounded-md border border-rose-400/40 bg-rose-500/15 px-2 py-1 text-xs font-medium text-rose-200 hover:bg-rose-500/25",children:[o.jsx(_s,{className:"h-3 w-3"})," Highlight Top ",z.length," in 3D"]}),o.jsxs("button",{type:"button",onClick:()=>g.openTab("sequence"),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-xs text-slate-200 hover:border-sky-400/40",children:[o.jsx(Vo,{className:"h-3 w-3"})," Sequence Track"]}),o.jsxs("button",{type:"button",onClick:()=>g.openTab("ramachandran"),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-xs text-slate-200 hover:border-cyan-400/40",children:[o.jsx(Qo,{className:"h-3 w-3"})," Ramachandran"]})]}),children:o.jsx("div",{className:"grid grid-cols-2 gap-2 @xl:grid-cols-4",children:z.map($=>o.jsxs("button",{type:"button",onClick:()=>{c($.mobSeqId,$.mobSeqId),g?.focusIn3D($.refSeqId,{centerCamera:!0})},className:"flex items-center justify-between gap-2 rounded-lg border border-white/[0.08] bg-black/25 px-2.5 py-2 text-left font-mono text-xs transition hover:border-amber-400/50",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"truncate font-semibold text-slate-100",children:[$.resName3," ",$.refSeqId]}),o.jsx("div",{className:"truncate text-[0.6875rem] text-slate-500",children:$.mobPlddt!=null?`pLDDT ${$.mobPlddt.toFixed(0)}`:"Exp/Model"})]}),o.jsxs("span",{className:"shrink-0 font-semibold text-amber-300",children:[$.distanceAngstrom.toFixed(2)," Å"]})]},`${$.refSeqId}-${$.mobSeqId}`))})}),o.jsx(wL,{paeJson:r,selected:i,onSelect:($,H)=>{c($,H),g?.focusIn3D($,{centerCamera:!0})},status:O.paeStatus,onFocusIn3D:g?$=>g.focusIn3D($,{centerCamera:!0,openViewer:"activate"}):void 0}),o.jsx(yt,{title:"Provenance",description:"Exact inputs used for this result.",children:o.jsxs("div",{className:"space-y-2",children:[[{tag:"Reference",rec:e.reference,tone:"text-sky-300"},{tag:"Comparison",rec:e.mobile,tone:"text-emerald-300"}].map(({tag:$,rec:H,tone:Z})=>o.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-white/[0.06] bg-black/20 p-3",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[o.jsx("span",{className:`font-medium ${Z}`,children:$}),o.jsx("span",{className:"text-slate-200",children:H.label}),o.jsx(It,{children:H.confidenceKind}),o.jsx(It,{children:H.license??"license unknown"})]}),o.jsxs("div",{className:"mt-1 truncate font-mono text-xs text-slate-500",children:["sha256 ",H.sha256]})]}),o.jsx("button",{type:"button",onClick:()=>V(H.sha256),title:"Copy SHA-256",className:"rounded-md p-1.5 text-slate-500 hover:bg-white/[0.06] hover:text-slate-200",children:_===H.sha256?o.jsx(Fi,{className:"h-4 w-4 text-emerald-400"}):o.jsx(Lr,{className:"h-4 w-4"})})]},$)),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 pt-1 text-xs text-slate-500",children:[o.jsxs("span",{children:["Engine ",e.engine.target," · ",e.engine.floatPrecision]}),o.jsxs("span",{children:["Result ",e.resultId.slice(0,16),"…"]}),o.jsx("span",{children:new Date(e.createdAtUtc).toLocaleString()})]}),o.jsxs("button",{type:"button",onClick:()=>k($=>!$),className:"flex items-center gap-1 pt-1 text-xs text-slate-400 hover:text-slate-200",children:[S?o.jsx(ph,{className:"h-3.5 w-3.5"}):o.jsx(Ty,{className:"h-3.5 w-3.5"}),"4×4 transform (",e.transform.direction,")"]}),S&&o.jsx("div",{className:"grid grid-cols-4 gap-1 rounded-lg bg-black/30 p-3 font-mono text-xs text-slate-300",children:e.transform.matrixRowMajor4x4.map(($,H)=>o.jsx("div",{className:"text-right tabular-nums",children:$.toFixed(4)},H))})]})}),o.jsxs(yt,{title:"Export",description:"Every export carries provenance and the research-use-only notice.",children:[o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(Oe,{variant:"primary",icon:o.jsx(sr,{className:"h-4 w-4"}),onClick:p,children:"HTML report"}),o.jsx(Oe,{icon:o.jsx(BA,{className:"h-4 w-4"}),onClick:b,children:"JSON manifest"}),o.jsx(Oe,{icon:o.jsx(UA,{className:"h-4 w-4"}),onClick:x,children:"Project bundle"})]}),o.jsxs("label",{className:"mt-4 flex items-center gap-3 text-sm text-slate-300",children:[o.jsx($r,{checked:d,onChange:f,label:"Embed 3D image"}),"Embed the current 3D view in the HTML report"]})]}),o.jsx("p",{className:"text-xs text-slate-500",children:Cn})]})})}function wL({paeJson:e,selected:r,onSelect:n,status:s,onFocusIn3D:i}){const c=C.useRef(null),d=C.useRef(null),[f,p]=C.useState(null),b=C.useMemo(()=>{if(!e)return null;try{const g=JSON.parse(e),y=(Array.isArray(g)?g[0]:g)?.predicted_aligned_error;return Array.isArray(y)&&Array.isArray(y[0])?y:null}catch{return null}},[e]);C.useEffect(()=>{if(!b){d.current=null;return}const g=b.length,_=document.createElement("canvas");_.width=g,_.height=g;const y=_.getContext("2d");if(!y)return;const S=y.createImageData(g,g);for(let k=0;k<g;k++)for(let E=0;E<g;E++){const[T,j,q]=cL(Number(b[k][E]??30)),z=(k*g+E)*4;S.data[z]=T,S.data[z+1]=j,S.data[z+2]=q,S.data[z+3]=255}y.putImageData(S,0,0),d.current=_},[b]),C.useEffect(()=>{const g=c.current,_=d.current;if(!g||!_||!b)return;const y=g.getContext("2d");if(!y)return;const S=g.width;y.imageSmoothingEnabled=!1,y.drawImage(_,0,0,S,S);const k=S/b.length,E=(T,j,q)=>{y.strokeStyle=q,y.lineWidth=1.5,y.beginPath(),y.moveTo((j-.5)*k,0),y.lineTo((j-.5)*k,S),y.moveTo(0,(T-.5)*k),y.lineTo(S,(T-.5)*k),y.stroke()};r&&E(r[0],r[1],"rgba(251,191,36,0.9)"),f&&E(f.i,f.j,"rgba(125,211,252,0.75)")},[b,f,r]);const x=(g,_)=>{if(!b)return;const y=g.currentTarget.getBoundingClientRect(),S=b.length,k=Math.max(0,Math.min(S-1,Math.floor((g.clientX-y.left)/y.width*S))),E=Math.max(0,Math.min(S-1,Math.floor((g.clientY-y.top)/y.height*S)));p({i:E+1,j:k+1,val:Number(b[E][k]??0)}),_&&n(E+1,k+1)};return o.jsx(yt,{title:"Predicted aligned error (PAE)",description:b?`${b.length} × ${b.length} residues · click a cell to focus residue i in 3D`:`No PAE matrix loaded (${s}). AlphaFold DB imports include it automatically.`,actions:o.jsxs("div",{className:"flex items-center gap-2",children:[f?o.jsxs("span",{className:"font-mono text-xs text-slate-300 tabular-nums",children:["(",f.i,", ",f.j,") = ",f.val.toFixed(1)," Å"]}):r?o.jsxs("span",{className:"font-mono text-xs text-amber-300",children:["selected (",r[0],", ",r[1],")"]}):null,r&&i&&o.jsxs("button",{type:"button",onClick:()=>i(r[0]),className:"inline-flex items-center gap-1 rounded-md border border-sky-400/40 bg-sky-500/15 px-2 py-0.5 text-xs text-sky-200 hover:bg-sky-500/25",children:[o.jsx(Ur,{className:"h-3 w-3"})," View in 3D"]})]}),children:b?o.jsxs("div",{className:"flex flex-col items-center gap-3 @lg:flex-row @lg:items-end",children:[o.jsx("canvas",{ref:c,width:520,height:520,onMouseMove:g=>x(g,!1),onClick:g=>x(g,!0),onMouseLeave:()=>p(null),className:"aspect-square w-full max-w-[22rem] cursor-crosshair rounded-lg border border-white/[0.08]"}),o.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400 @lg:flex-col @lg:items-start",children:[o.jsx("span",{children:"0 Å · confident"}),o.jsx("span",{className:"inline-block h-2 w-28 rounded-sm bg-gradient-to-r from-[#10d2a0] via-[#2d8c87] to-[#0f172a] @lg:h-28 @lg:w-2 @lg:bg-gradient-to-b"}),o.jsx("span",{children:"30 Å · uncertain"})]})]}):null})}function SL({comparison:e,refInspect:r,mobInspect:n,refChainId:s,mobChainId:i,focusedSeqId:c,onFocusResidue:d,bridge:f}){const p=C.useRef(null),[b,x]=C.useState("deviation"),[g,_]=C.useState("all"),[y,S]=C.useState(""),[k,E]=C.useState(!1),T=C.useMemo(()=>{const P=r?.chains.find(K=>K.chainId===s)??r?.chains[0],$=n?.chains.find(K=>K.chainId===i)??n?.chains[0],H=new Map;if(e)for(const K of e.matchedResidues)H.set(K.mobSeqId,K);const Z=P?.sequence1Letter??"",G=new Map;for(const K of P?.residues??[])G.set(K.seqId,{code:K.resCode1,hasCa:K.ca!=null,b:K.bOrPlddt});return $&&$.residues.length>0?$.residues.map((K,we)=>{const Se=H.get(K.seqId),Q=G.get(K.seqId),F=we<Z.length?Z[we]:null;return Se?{posIndex:we+1,refSeqId:Se.refSeqId,refCode:Se.resCode1,mobSeqId:Se.mobSeqId,mobCode:K.resCode1,distanceA:Se.distanceAngstrom,refBFactor:Se.refBFactor,mobPlddt:Se.mobPlddt,isMissingRefCoord:!1}:{posIndex:we+1,refSeqId:Q?K.seqId:null,refCode:Q?.hasCa?Q.code:"-",mobSeqId:K.seqId,mobCode:K.resCode1,distanceA:null,refBFactor:Q?.b??null,mobPlddt:K.bOrPlddt,isMissingRefCoord:!Q?.hasCa&&F!=null}}):e?e.matchedResidues.map((K,we)=>({posIndex:we+1,refSeqId:K.refSeqId,refCode:K.resCode1,mobSeqId:K.mobSeqId,mobCode:K.resCode1,distanceA:K.distanceAngstrom,refBFactor:K.refBFactor,mobPlddt:K.mobPlddt,isMissingRefCoord:!1})):[]},[e,r,n,s,i]),j=C.useMemo(()=>{let P=0,$=0,H=0,Z=null,G=0,K=[],we=0,Se=0,Q=0,F=0;for(const he of T){const W=he.refSeqId??he.mobSeqId??he.posIndex;he.distanceA!=null?(P++,$+=he.distanceA,he.distanceA>H&&(H=he.distanceA,Z=W),he.distanceA>=2&&(G++,K.push(W))):Se++,he.mobPlddt!=null&&(Q+=he.mobPlddt,F++,he.mobPlddt<70&&we++)}return{matched:P,meanD:P>0?$/P:0,maxD:H,maxDSeqId:Z,highDevCount:G,highDevSeqIds:K,lowPlddtCount:we,gapCount:Se,meanPlddt:F>0?Q/F:null}},[T]),q=C.useMemo(()=>g==="all"?T:T.filter(P=>g==="high_dev"?P.distanceA!=null&&P.distanceA>=2:g==="low_plddt"?P.mobPlddt!=null&&P.mobPlddt<70:g==="gaps"?P.distanceA==null:!0),[T,g]),z=C.useMemo(()=>T.find(P=>P.refSeqId===c||P.mobSeqId===c)??null,[T,c]),O=C.useMemo(()=>{let P=2;for(const $ of T)$.distanceA!=null&&$.distanceA>P&&(P=$.distanceA);return P},[T]),V=P=>{d(P),f?.focusIn3D(P,{centerCamera:!0})};return T.length===0?o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 p-3 @xl:p-4",children:[o.jsx(ir,{bridge:f,title:"Sequence Alignment & Per-Residue Deviation Track",subtitle:"Compare aligned amino-acid sequences, Cα deviations (Δd), pLDDT confidence, and B-factors residue-by-residue.",icon:o.jsx(Vo,{className:"h-4 w-4"}),guideOpen:k,onToggleGuide:()=>E(P=>!P)}),o.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 rounded-xl border border-white/[0.08] bg-[#0b1018] p-6 text-center text-xs text-slate-400",children:[o.jsx(Vo,{className:"h-8 w-8 text-slate-500"}),o.jsx("div",{className:"text-sm font-medium text-slate-200",children:"No structure pair loaded"}),o.jsx("p",{className:"max-w-md",children:"Load reference and comparison structures to inspect aligned sequence columns and per-residue Cα Δd deviations."}),f&&o.jsxs("button",{type:"button",onClick:f.loadExample,className:"inline-flex items-center gap-1.5 rounded-lg bg-sky-500 px-3.5 py-2 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:[o.jsx(Br,{className:"h-3.5 w-3.5"})," Load CA II Example"]})]})]}):o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3 text-xs @xl:p-4",children:[o.jsx(ir,{bridge:f,title:"Sequence Alignment & Per-Residue Δd Track",subtitle:"Inspect aligned residue columns, structural deviation spikes (Δd), experimental B-factors, and AlphaFold pLDDT.",icon:o.jsx(Vo,{className:"h-4 w-4"}),guideOpen:k,onToggleGuide:()=>E(P=>!P)}),o.jsx(Qi,{open:k,title:"How Sequence Deviation Tracking Works",summary:"Each column aligns a reference residue (top letter, sky blue) to the corresponding comparison/predicted residue (bottom letter, emerald). The bar height and color visualize local structural or confidence differences.",steps:["Switch the bar chart metric between Δd (Å), AlphaFold pLDDT, and Experimental B-factor.","Use the Filter pills to isolate only High-Deviation hotspots (Δd ≥ 2.0 Å), Low-Confidence loops (pLDDT < 70), or Missing Coordinate gaps (-).",'Click any residue column to focus it in the 3D Viewer, or click "Highlight High Δd in 3D" to inspect flexible loops on the 3D model.'],connectionTip:"Every column is directly bound to the 3D scene. Focusing a residue here highlights it in the 3D Viewer, updates the Peptide & CRISPR workbenches, and allows 1-click navigation to Ramachandran angles."}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 @lg:grid-cols-4",children:[o.jsx(bs,{label:"Aligned / Total",value:`${j.matched} / ${T.length}`,hint:`${j.gapCount} missing coords (-)`}),o.jsx(bs,{label:"Mean Δd",value:`${j.meanD.toFixed(3)} Å`,hint:"Average Cα offset"}),o.jsxs("button",{type:"button",onClick:()=>j.maxDSeqId!==null&&V(j.maxDSeqId),disabled:j.maxDSeqId===null,className:"min-w-0 rounded-lg border border-amber-400/25 bg-amber-500/[0.06] px-2.5 py-2 text-left transition hover:border-amber-400/50 disabled:opacity-50",title:"Click to jump to the highest-deviating residue",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-amber-300",children:"Max Δd (Jump ↗)"}),o.jsxs("div",{className:"mt-0.5 truncate font-mono text-sm font-semibold text-amber-200 tabular-nums",children:[j.maxD.toFixed(2)," Å ",j.maxDSeqId!==null?`(#${j.maxDSeqId})`:""]}),o.jsxs("div",{className:"mt-0.5 truncate text-[0.625rem] text-slate-400",children:[j.highDevCount," res ≥ 2.0 Å"]})]}),o.jsx(bs,{label:"Mean pLDDT",value:j.meanPlddt!==null?j.meanPlddt.toFixed(1):"n/a",hint:j.meanPlddt!==null?`${j.lowPlddtCount} res < 70`:"No pLDDT"})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-xl border border-white/[0.08] bg-[#0b1018] p-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx("span",{className:"text-[0.6875rem] text-slate-400",children:"Bar Metric:"}),[["deviation","Δd (Å)"],["plddt","pLDDT"],["bfactor","B-Factor"]].map(([P,$])=>o.jsx("button",{type:"button",onClick:()=>{x(P),f?.setColorMode3D(P)},className:`rounded-md border px-2 py-1 font-mono text-[0.6875rem] transition ${b===P?"border-sky-400/50 bg-sky-500/20 text-sky-200":"border-white/10 bg-slate-900 text-slate-400 hover:text-slate-200"}`,children:$},P))]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[[["all",`All (${T.length})`],["high_dev",`Δd ≥ 2Å (${j.highDevCount})`],["low_plddt",`pLDDT < 70 (${j.lowPlddtCount})`],["gaps",`Gaps (${j.gapCount})`]].map(([P,$])=>o.jsx("button",{type:"button",onClick:()=>_(P),className:`rounded-md border px-2 py-1 text-[0.6875rem] transition ${g===P?"border-emerald-400/50 bg-emerald-500/20 text-emerald-200":"border-white/10 bg-slate-900 text-slate-400 hover:text-slate-200"}`,children:$},P)),f&&j.highDevSeqIds.length>0&&o.jsxs("button",{type:"button",onClick:()=>f.highlightIn3D(j.highDevSeqIds,"High Δd ≥ 2.0 Å",{focusSeqId:j.maxDSeqId??j.highDevSeqIds[0]}),className:"inline-flex items-center gap-1 rounded-md border border-rose-400/40 bg-rose-500/15 px-2 py-1 text-[0.6875rem] font-medium text-rose-200 hover:bg-rose-500/25",children:[o.jsx(_s,{className:"h-3 w-3"})," Highlight High Δd in 3D"]})]}),o.jsxs("form",{onSubmit:P=>{P.preventDefault();const $=Number.parseInt(y.trim(),10);Number.isFinite($)&&$>0&&V($)},className:"flex items-center gap-1",children:[o.jsx("input",{value:y,onChange:P=>S(P.target.value),placeholder:"Jump res #",className:"h-7 w-20 rounded-md border border-white/10 bg-slate-950 px-2 font-mono text-[0.6875rem] text-slate-200 outline-none focus:border-sky-400"}),o.jsx("button",{type:"submit",className:"h-7 rounded-md border border-white/10 bg-white/[0.04] px-2 text-[0.6875rem] text-slate-300 hover:text-white",children:"Go"})]})]}),o.jsx("div",{ref:p,className:"min-h-36 flex-1 overflow-x-auto overflow-y-hidden rounded-xl border border-white/[0.08] bg-[#070a10] p-3",children:q.length===0?o.jsx("div",{className:"flex h-full items-center justify-center text-slate-500",children:"No residues match this filter."}):o.jsx("div",{className:"inline-flex min-w-max items-end gap-[3px]",children:q.map(P=>{const $=P.refSeqId??P.mobSeqId??P.posIndex,H=c!=null&&(P.refSeqId===c||P.mobSeqId===c);let Z=3,G=[71,85,105],K=!1;return b==="deviation"&&P.distanceA!=null?(K=!0,Z=Math.max(4,Math.round(P.distanceA/O*56)),G=Vd(P.distanceA)):b==="plddt"&&P.mobPlddt!=null?(K=!0,Z=Math.max(4,Math.round(P.mobPlddt/100*56)),G=ky(P.mobPlddt)):b==="bfactor"&&P.refBFactor!=null&&(K=!0,Z=Math.max(4,Math.min(56,Math.round(P.refBFactor/60*56))),G=Cy(P.refBFactor)),o.jsxs("button",{type:"button",onClick:()=>V($),title:`Pos ${P.posIndex} | Ref: ${P.refCode}${P.refSeqId??"-"} | Mob: ${P.mobCode}${P.mobSeqId??"-"} | Δd=${P.distanceA!=null?`${P.distanceA.toFixed(3)} Å`:"missing"} | B=${P.refBFactor??"n/a"} | pLDDT=${P.mobPlddt??"n/a"}`,className:`group flex w-4.5 shrink-0 flex-col items-center rounded py-1 font-mono transition ${H?"bg-amber-500/25 ring-1 ring-amber-400":"hover:bg-slate-800/80"}`,children:[o.jsx("span",{className:"h-3.5 text-[0.5625rem] text-slate-500",children:P.posIndex%10===0||P.posIndex===1?P.posIndex:""}),o.jsx("div",{className:"flex h-15 w-full items-end justify-center pb-1",children:o.jsx("div",{className:"w-2.5 rounded-t-[2px] transition-all",style:{height:`${Z}px`,backgroundColor:lL(G),opacity:K?.94:.3}})}),o.jsx("span",{className:`text-[0.75rem] font-semibold leading-tight ${P.refCode==="-"?"text-amber-400":"text-sky-300"}`,children:P.refCode}),o.jsx("span",{className:"text-[0.75rem] leading-tight text-emerald-300",children:P.mobCode})]},`${P.posIndex}-${P.mobSeqId??""}`)})})}),z?o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-amber-400/35 bg-amber-500/[0.06] px-3 py-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3 font-mono text-xs text-amber-100",children:[o.jsxs("span",{className:"font-semibold text-amber-200",children:["Focus: ",z.mobCode,z.refSeqId??z.mobSeqId]}),o.jsxs("span",{children:["Δd=",z.distanceA!=null?`${z.distanceA.toFixed(3)} Å`:"gap (-)"]}),o.jsxs("span",{children:["B=",z.refBFactor!=null?`${z.refBFactor.toFixed(2)} Ų`:"n/a"]}),o.jsxs("span",{children:["pLDDT=",z.mobPlddt!=null?z.mobPlddt.toFixed(1):"n/a"]}),z.mobPlddt!==null&&o.jsx("span",{className:"font-sans",children:o.jsx(Ca,{insight:wE(z.mobPlddt),compact:!0})})]}),f&&o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs("button",{type:"button",onClick:()=>f.focusIn3D(z.refSeqId??z.mobSeqId??z.posIndex,{centerCamera:!0,openViewer:"activate"}),className:"inline-flex items-center gap-1 rounded-md border border-sky-400/40 bg-sky-500/15 px-2 py-1 text-[0.6875rem] font-medium text-sky-200 hover:bg-sky-500/25",children:[o.jsx(Ur,{className:"h-3 w-3"})," Focus in 3D"]}),o.jsxs("button",{type:"button",onClick:()=>f.sendResidueToRamachandran(z.refSeqId??z.mobSeqId??z.posIndex),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-cyan-400/40",children:[o.jsx(Qo,{className:"h-3 w-3 text-cyan-300"})," Ramachandran"]}),o.jsxs("button",{type:"button",onClick:()=>{const P=z.refSeqId??z.mobSeqId??z.posIndex,$=z.mobCode!=="-"?z.mobCode:z.refCode;f.sendMutationToPeptide(`${$}${P}A`,P)},className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-emerald-400/40",children:[o.jsx(ar,{className:"h-3 w-3 text-emerald-300"})," Ala Scan"]}),o.jsxs("button",{type:"button",onClick:()=>f.sendResidueToCrispr(z.refSeqId??z.mobSeqId??z.posIndex),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-violet-400/40",children:[o.jsx(Fs,{className:"h-3 w-3 text-violet-300"})," CRISPR Codon"]})]})]}):o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 font-mono text-[0.6875rem] text-slate-400",children:[o.jsx("span",{children:"Click any column to synchronize 3D Viewer, Peptide, CRISPR & Ramachandran."}),o.jsx("span",{className:"text-amber-300/90",children:"[-] = Missing coordinates in experimental structure"})]})]})}const SE=[[{id:"account",label:"Account",icon:o.jsx(ah,{className:"h-4 w-4"}),keywords:"sign in sign out profile email synlexa.com login"},{id:"usage",label:"Usage",icon:o.jsx(yR,{className:"h-4 w-4"}),keywords:"tokens requests cost history"}],[{id:"ai",label:"AI & API keys",icon:o.jsx(tp,{className:"h-4 w-4"}),keywords:"assistant claude anthropic gemini google model byok key synlexa cloud"}],[{id:"viewer",label:"3D viewer",icon:o.jsx(A6,{className:"h-4 w-4"}),keywords:"render style color cartoon surface layout png report"},{id:"workspace",label:"Workspace",icon:o.jsx(VA,{className:"h-4 w-4"}),keywords:"interface size scale zoom text tabs layout auto-save guided demo"}],[{id:"data",label:"Data & storage",icon:o.jsx(Vi,{className:"h-4 w-4"}),keywords:"library export import backup clear history storage"}]],pp={id:"about",label:"About",icon:o.jsx(zy,{className:"h-4 w-4"}),keywords:"version license engine keyboard shortcuts research use only"},Mx=[...SE.flat(),pp];function MA({item:e,active:r,onSelect:n}){return o.jsxs("button",{type:"button",onClick:n,"aria-current":r?"page":void 0,className:Ie("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-[0.4375rem] text-left text-sm transition-colors",r?"bg-white/[0.08] text-white":"text-slate-300 hover:bg-white/[0.04] hover:text-white"),children:[o.jsx("span",{className:r?"text-white":"text-slate-400",children:e.icon}),e.label]})}function kL(e){const{open:r,onClose:n,section:s,onSectionChange:i}=e,[c,d]=C.useState(""),f=C.useRef(null),p=C.useRef(null);C.useEffect(()=>{if(!r)return;d("");const k=E=>{E.key==="Escape"&&(E.stopPropagation(),n())};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[r,n]),C.useEffect(()=>{p.current?.scrollTo({top:0})},[s]);const b=c.trim().toLowerCase(),x=k=>!b||`${k.label} ${k.keywords}`.toLowerCase().includes(b),g=SE.map(k=>k.filter(x)).filter(k=>k.length>0),_=x(pp),y=g.length>0||_;if(!r)return null;const S=Mx.find(k=>k.id===s)??Mx[0];return o.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/55 p-3 backdrop-blur-[2px] sm:p-6",onMouseDown:k=>{k.target===k.currentTarget&&n()},children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Settings",className:"flex h-[min(46rem,100%)] w-[min(64rem,100%)] flex-col overflow-hidden rounded-2xl border border-white/10 bg-[#161a22] shadow-[0_24px_80px_-12px_rgba(0,0,0,0.7)]",children:[o.jsxs("div",{className:"flex h-12 shrink-0 items-center justify-between border-b border-white/[0.07] pr-2 pl-5",children:[o.jsx("h2",{className:"text-[0.9375rem] font-semibold text-slate-100",children:"Settings"}),o.jsx(sl,{label:"Close settings",onClick:n,children:o.jsx(Xi,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col md:flex-row",children:[o.jsxs("aside",{className:"hidden w-60 shrink-0 flex-col border-r border-white/[0.07] md:flex",children:[o.jsx("div",{className:"p-3 pb-2",children:o.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-white/[0.05] px-2.5 py-1.5 focus-within:ring-1 focus-within:ring-sky-400/50",children:[o.jsx(Gr,{className:"h-4 w-4 shrink-0 text-slate-500"}),o.jsx("input",{ref:f,value:c,onChange:k=>d(k.target.value),onKeyDown:k=>{if(k.key==="Enter"){const E=[...g.flat(),..._?[pp]:[]][0];E&&i(E.id)}},placeholder:"Search","aria-label":"Search settings",className:"min-w-0 flex-1 bg-transparent text-sm text-slate-100 placeholder:text-slate-500 focus:outline-none"})]})}),o.jsxs("nav",{className:"min-h-0 flex-1 overflow-y-auto px-3 pb-3",children:[g.map((k,E)=>o.jsx("div",{className:Ie("space-y-0.5 py-1.5",E>0&&"border-t border-white/[0.06]"),children:k.map(T=>o.jsx(MA,{item:T,active:s===T.id,onSelect:()=>i(T.id)},T.id))},k[0].id)),!y&&o.jsxs("p",{className:"px-2.5 py-2 text-sm text-slate-500",children:["No settings match “",c,"”."]})]}),_&&o.jsx("div",{className:"border-t border-white/[0.06] p-3",children:o.jsx(MA,{item:pp,active:s==="about",onSelect:()=>i("about")})})]}),o.jsx("div",{className:"flex shrink-0 gap-1 overflow-x-auto border-b border-white/[0.07] px-3 py-2 [scrollbar-width:none] md:hidden",children:Mx.map(k=>o.jsxs("button",{type:"button",onClick:()=>i(k.id),className:Ie("flex shrink-0 items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs whitespace-nowrap",s===k.id?"bg-white/[0.08] text-white":"text-slate-400 hover:bg-white/[0.04]"),children:[k.icon,k.label]},k.id))}),o.jsx("div",{ref:p,className:"@container min-w-0 flex-1 overflow-y-auto","aria-label":S.label,children:o.jsxs("div",{className:"mx-auto max-w-3xl space-y-5 px-5 py-6 @2xl:px-8",children:[s==="account"&&o.jsx(CL,{...e}),s==="ai"&&o.jsx(jL,{...e}),s==="usage"&&o.jsx(TL,{}),s==="viewer"&&o.jsx(EL,{}),s==="workspace"&&o.jsx(ML,{onResetLayout:e.onResetLayout}),s==="data"&&o.jsx(RL,{onClearedHistory:e.onClearedHistory}),s==="about"&&o.jsx(OL,{})]})})]})]})})}function ul({title:e,description:r}){return o.jsxs("div",{className:"pb-1",children:[o.jsx("h1",{className:"text-xl font-semibold text-slate-100",children:e}),r&&o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:r})]})}function CL({session:e,onSessionChange:r,onSignIn:n,onCancelSignIn:s,signInPending:i,aiConfig:c}){const{confirm:d,toast:f}=cl(),p=(e?.displayName??e?.email??"?").split(/[\s@.]+/).filter(Boolean).slice(0,2).map(b=>b[0]?.toUpperCase()).join("");return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"Account",description:"Your synlexa.com connection and how Studio uses it."}),o.jsx(yt,{children:e?o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-gradient-to-br from-sky-400 to-indigo-500 text-base font-semibold text-white",children:p||o.jsx(ah,{className:"h-5 w-5"})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"truncate text-base font-medium text-slate-100",children:e.displayName??e.email??"Signed in"}),o.jsx("div",{className:"truncate text-sm text-slate-400",children:e.email??"Email not shared"}),o.jsxs("div",{className:"mt-1.5 flex gap-1.5",children:[e.serverVerified?o.jsx(It,{tone:"good",children:"Verified by synlexa.com"}):o.jsx(It,{tone:"warn",children:"Not confirmed by synlexa.com"}),o.jsxs(It,{children:["Since ",new Date(e.establishedAtUtc).toLocaleDateString()]})]})]}),!e.serverVerified&&o.jsx(Oe,{variant:"primary",disabled:i,onClick:()=>n("signin"),children:i?"Waiting…":"Reconnect"}),o.jsx(Oe,{variant:"ghost",icon:o.jsx(k6,{className:"h-4 w-4"}),onClick:async()=>{await d({title:"Sign out?",message:"Your local library, settings, and API keys stay on this device.",confirmLabel:"Sign out"})&&(UI(),r(null),f("Signed out","success"))},children:"Sign out"})]}):i?o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-sky-400/10 text-sky-300",children:o.jsx(qs,{className:"h-5 w-5 animate-spin"})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-base font-medium text-slate-100",children:"Waiting for synlexa.com…"}),o.jsx("div",{className:"text-sm text-slate-400",children:"Finish signing in in the window that opened. Studio connects automatically."})]})]}),o.jsx(Oe,{variant:"ghost",onClick:s,children:"Cancel"})]}):o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-white/[0.06] text-slate-400",children:o.jsx(ah,{className:"h-5 w-5"})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-base font-medium text-slate-100",children:"Not signed in"}),o.jsx("div",{className:"text-sm text-slate-400",children:"Studio works fully offline. Sign in to use Synlexa Cloud and connect your organization."})]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Oe,{variant:"ghost",onClick:()=>n("signup"),children:"Create account"}),o.jsx(Oe,{variant:"primary",onClick:()=>n("signin"),children:"Sign in"})]})]})}),o.jsx(yt,{title:"Where your data lives",children:o.jsxs("ul",{className:"space-y-2 text-sm text-slate-300",children:[o.jsxs("li",{className:"flex gap-2",children:[o.jsx(Gs,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-400"}),"Structures, compounds, and your library are stored in this browser (IndexedDB) and never uploaded."]}),o.jsxs("li",{className:"flex gap-2",children:[o.jsx(Gs,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-400"}),"Calculations run locally in the WebAssembly engine."]}),o.jsxs("li",{className:"flex gap-2",children:[o.jsx(Gs,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-400"}),c[c.provider]?.apiKey?c.provider==="synlexa"?o.jsx(o.Fragment,{children:"AI requests go through synlexa.com to Google Gemini, with a summary of the loaded workspace. Synlexa does not store prompts or replies."}):o.jsxs(o.Fragment,{children:["AI requests go directly from this browser to"," ",c.provider==="anthropic"?"Anthropic":"Google"," using your own key, with a summary of the loaded workspace."]}):o.jsx(o.Fragment,{children:"Nothing is sent to an AI provider until you sign in for Synlexa Cloud or add your own key. The built-in assistant runs locally."})]})]})})]})}function NL({provider:e,value:r,onSave:n}){const[s,i]=C.useState(""),[c,d]=C.useState(!1),f=s.length>0;return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("div",{className:"relative min-w-0 flex-1",children:[o.jsx(Dn,{type:c?"text":"password",value:s,onChange:p=>i(p.target.value),placeholder:r?ZI(r):es[e].keyHint,autoComplete:"off",spellCheck:!1,className:"pr-9 font-mono text-[0.8125rem]",onKeyDown:p=>{p.key==="Enter"&&s.trim()&&(n(s.trim()),i(""))}}),o.jsx("button",{type:"button",onClick:()=>d(p=>!p),"aria-label":c?"Hide key":"Show key",className:"absolute top-1/2 right-2 -translate-y-1/2 text-slate-500 hover:text-slate-200",children:c?o.jsx(WR,{className:"h-4 w-4"}):o.jsx(LA,{className:"h-4 w-4"})})]}),f?o.jsx(Oe,{variant:"primary",onClick:()=>{n(s.trim()),i("")},children:"Save"}):r?o.jsx(Oe,{variant:"ghost",onClick:()=>n(""),children:"Remove"}):null]})}async function AL(e,r,n){if(e==="anthropic"){const c=new aa({apiKey:r,dangerouslyAllowBrowser:!0,maxRetries:0});try{const d=await c.models.retrieve(n);return`Connected · ${d.display_name??d.id}`}catch(d){throw d instanceof aa.AuthenticationError?new Error("Invalid API key"):d instanceof aa.NotFoundError?new Error(`Model "${n}" not available for this key`):d instanceof aa.APIConnectionError?new Error("Could not reach api.anthropic.com"):d instanceof Error?d:new Error(String(d))}}if(e==="openai"){const c=await fetch(`https://api.openai.com/v1/models/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`}}),d=await c.json().catch(()=>({}));if(!c.ok)throw new Error(d.error?.message??`HTTP ${c.status}`);return`Connected · ${d.id??n}`}const s=await fetch(`${y3}/${encodeURIComponent(n)}`,{headers:{"x-goog-api-key":r}}),i=await s.json().catch(()=>({}));if(!s.ok)throw new Error(i.error?.message??`HTTP ${s.status}`);return`Connected · ${i.displayName??n}`}function jL({aiConfig:e,onUpdateAiConfig:r,onPermissionsChange:n,session:s,onSignIn:i,signInPending:c}){const[d,f]=C.useState(null),[p,b]=C.useState({}),[x,g]=C.useState(()=>Zo()),[_,y]=C.useState(()=>t0());C.useEffect(()=>f3(()=>g(Zo())),[]);const S=Xc(e),k=e.routingPreference??"byok-first",E=(j,q)=>{const z=gI({..._,[j]:q});y(z),n?.(z)},T=async j=>{f(j);try{const q=e[j]??{apiKey:"",model:""},z=await AL(j,q.apiKey,q.model);b(O=>({...O,[j]:{ok:!0,msg:z}}))}catch(q){b(z=>({...z,[j]:{ok:!1,msg:q instanceof Error?q.message:String(q)}}))}finally{f(null)}};return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"AI & API keys",description:"Bring your own Anthropic, Gemini, or OpenAI/Codex key (BYOK), or choose Synlexa Cloud. When a BYOK key is entered in default mode, Studio routes directly to your provider instead of Synlexa Cloud."}),o.jsx(yt,{title:"Active AI routing & key priority",description:"Control whether your local BYOK keys always override Synlexa Cloud or whether you switch manually.",actions:o.jsx(It,{tone:S.isByok?"good":S.hasCloudToken?"accent":"neutral",children:S.isByok?`Using BYOK (${es[S.provider].label})`:S.provider==="synlexa"&&S.hasCloudToken?"Using Synlexa Cloud":"Local Deterministic Copilot"}),children:o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsx("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 text-xs",children:o.jsxs("div",{className:"flex items-center gap-2 text-slate-200",children:[o.jsx(Ki,{className:"h-4 w-4 shrink-0 text-emerald-400"}),S.isByok?o.jsxs("span",{children:["Requests go directly to ",o.jsx("strong",{children:es[S.provider].label})," using your encrypted BYOK key — Synlexa Cloud is bypassed."]}):S.provider==="synlexa"&&S.hasCloudToken?o.jsxs("span",{children:["Requests route through ",o.jsx("strong",{children:"Synlexa Cloud"})," (`synlexa.com` account).",S.hasByok?" (Manual override active; your BYOK keys are saved for instant switch.)":""]}):o.jsx("span",{children:"No BYOK key or Cloud token active — using offline deterministic Copilot."})]})}),o.jsx(Qt,{label:"Key routing priority",hint:"Prefer BYOK guarantees your personal API key is used instead of Synlexa Cloud whenever any key is saved.",children:o.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.jsx(Oe,{size:"sm",variant:k==="byok-first"?"primary":"secondary",onClick:()=>{const j=["anthropic","gemini","openai"].find(q=>!!e[q]?.apiKey?.trim());r({routingPreference:"byok-first",...j&&e.provider==="synlexa"?{provider:j}:{}})},children:"Prefer BYOK keys"}),o.jsx(Oe,{size:"sm",variant:k==="manual"?"primary":"secondary",onClick:()=>r({routingPreference:"manual"}),children:"Choose manually (BYOK / Cloud)"})]})})]})}),o.jsx(yt,{title:"Encrypted Local Key Vault (state.vscdb)",description:"BYOK keys are stored in the local ItemTable store and encrypted with a non-extractable key.",actions:o.jsx(It,{tone:"good",children:x.cipher}),children:o.jsxs("div",{className:"divide-y divide-white/[0.05] text-sm",children:[o.jsx(Qt,{label:"Storage backend",hint:"Never saved inside project files or plain-text localStorage.",children:o.jsx("span",{className:"font-mono text-xs text-sky-300",children:x.dbPath})}),o.jsx(Qt,{label:"Allow AI scientific web search",hint:"Lets the assistant query Europe PMC & ClinicalTrials.gov via MCP.",children:o.jsx($r,{checked:e.enableWebSearch!==!1,onChange:j=>r({enableWebSearch:j}),label:"Allow AI scientific web search"})})]})}),o.jsxs(yt,{title:"Default assistant",description:"Choose between your BYOK providers or Synlexa Cloud.",children:[o.jsx("div",{className:"grid gap-3 @lg:grid-cols-2",children:Uv.map(j=>{const q=S.provider===j,z=e[j]??{apiKey:"",model:es[j].models[0]?.id??""},O=!!z.apiKey,V=es[j].models.find(P=>P.id===z.model)?.label??z.model;return o.jsxs("button",{type:"button",onClick:()=>r({provider:j,...j==="synlexa"&&S.hasByok?{routingPreference:"manual"}:{}}),className:Ie("rounded-xl border p-4 text-left transition-colors",q?"border-sky-400/60 bg-sky-500/[0.07]":"border-white/10 hover:border-white/20 hover:bg-white/[0.02]"),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm font-semibold text-slate-100",children:es[j].label}),o.jsx("span",{className:Ie("h-4 w-4 rounded-full border-2",q?"border-sky-400 bg-sky-400 shadow-[inset_0_0_0_2px_#121722]":"border-slate-600")})]}),o.jsx("div",{className:"mt-1 text-xs text-slate-400",children:j==="synlexa"?O?`Signed in · ${V}`:"Sign in required":O?`BYOK key encrypted · ${V}`:"No key yet"})]},j)})}),!e[S.provider]?.apiKey&&o.jsx("p",{className:"mt-3 text-xs text-slate-400",children:"Until you add a BYOK key or sign in to Synlexa Cloud, the assistant answers with the built-in deterministic helper."})]}),o.jsxs(yt,{title:"Synlexa Cloud",description:"Gemini through your synlexa.com account. Used only when selected and no BYOK override is active.",children:[o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"Account",hint:e.synlexa.apiKey?"Connected":"Not connected",children:e.synlexa.apiKey?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-200",children:[o.jsx(Gs,{className:"h-4 w-4 text-emerald-400"}),s?.email??s?.displayName??"Signed in"]}):o.jsxs(Oe,{size:"sm",variant:"primary",disabled:c,onClick:()=>i("signin"),children:[c?o.jsx(qs,{className:"h-3.5 w-3.5 animate-spin"}):null,c?"Waiting for synlexa.com…":s?"Reconnect to synlexa.com":"Sign in to synlexa.com"]})}),o.jsx(Qt,{label:"Model",children:o.jsx("div",{className:"w-full @xl:w-80",children:o.jsx(Na,{value:e.synlexa.model,onChange:j=>r({synlexa:{model:j.target.value}}),children:es.synlexa.models.map(j=>o.jsxs("option",{value:j.id,children:[j.label," — ",j.note]},j.id))})})})]}),s&&!e.synlexa.apiKey&&o.jsx("p",{className:"mt-3 text-xs text-slate-400",children:"Your current sign-in was not confirmed by synlexa.com, so Studio has no account token. Sign in again to connect."})]}),["anthropic","gemini","openai"].map(j=>{const q=es[j],z=e[j]??{apiKey:"",model:q.models[0]?.id??""},O=q.models.some(P=>P.id===z.model),V=p[j];return o.jsxs(yt,{title:q.label,description:o.jsxs(o.Fragment,{children:["Get a key at"," ",o.jsx("a",{href:q.keyUrl,target:"_blank",rel:"noreferrer",className:"text-sky-300 hover:underline",children:new URL(q.keyUrl).host})]}),actions:o.jsxs(Oe,{size:"sm",disabled:!z.apiKey||d!==null,onClick:()=>void T(j),children:[d===j?o.jsx(qs,{className:"h-3.5 w-3.5 animate-spin"}):null,"Test connection"]}),children:[o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"API key",hint:z.apiKey?"Encrypted in state.vscdb · Active when saved":"Not set",children:o.jsx("div",{className:"w-full @xl:w-80",children:o.jsx(NL,{provider:j,value:z.apiKey,onSave:P=>{const $=P.trim();r({[j]:{apiKey:$},...$?{provider:j}:{}}),b(H=>({...H,[j]:void 0}))}})})}),o.jsx(Qt,{label:"Model",children:o.jsxs("div",{className:"w-full space-y-2 @xl:w-80",children:[o.jsxs(Na,{value:O?z.model:"__custom",onChange:P=>{P.target.value!=="__custom"?r({[j]:{model:P.target.value}}):r({[j]:{model:""}})},children:[q.models.map(P=>o.jsxs("option",{value:P.id,children:[P.label," — ",P.note]},P.id)),o.jsx("option",{value:"__custom",children:"Custom model ID…"})]}),!O&&o.jsx(Dn,{defaultValue:z.model,placeholder:"exact model ID",className:"font-mono text-[0.8125rem]",onBlur:P=>P.target.value.trim()&&r({[j]:{model:P.target.value.trim()}})})]})})]}),V&&o.jsx("div",{className:Ie("mt-3 rounded-lg px-3 py-2 text-sm",V.ok?"bg-emerald-500/10 text-emerald-200":"bg-rose-500/10 text-rose-200"),children:V.msg}),j==="anthropic"&&(z.model==="claude-opus-5-5"||z.model==="claude-sonnet-5-5")&&o.jsx("p",{className:"mt-3 text-xs text-slate-500",children:"If the selected model declines a request, the API automatically retries it on a fallback model (server-side fallback)."})]},j)}),o.jsx(yt,{title:"Agent Tool Permissions",description:"Control when the AI Assistant asks for interactive confirmation before acting across Studio tools.",children:o.jsx("div",{className:"divide-y divide-white/[0.05]",children:Object.keys(Z5).map(j=>{const q=Z5[j];return o.jsx(Qt,{label:q.label,hint:q.description,children:o.jsxs(Na,{value:_[j],onChange:z=>E(j,z.target.value),className:"w-44",children:[o.jsx("option",{value:"ask",children:"Ask before running"}),o.jsx("option",{value:"always-allow",children:"Always allow"}),o.jsx("option",{value:"deny",children:"Block (deny)"})]})},j)})})})]})}function TL(){const[e,r]=C.useState(iy),[n,s]=C.useState(30),{confirm:i}=cl();C.useEffect(()=>vI(()=>r(iy())),[]);const c=C.useMemo(()=>SI(e,n),[e,n]),d=Math.max(1,...c.days.map(p=>p.tokens)),f=new Intl.NumberFormat;return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"Usage",description:"AI requests and tokens made from this browser, as reported by each provider. Billing happens on your provider account."}),o.jsx("div",{className:"flex gap-1",children:[7,30].map(p=>o.jsxs("button",{type:"button",onClick:()=>s(p),className:Ie("rounded-lg px-3 py-1.5 text-sm",n===p?"bg-white/[0.1] text-white":"text-slate-400 hover:bg-white/[0.05]"),children:["Last ",p," days"]},p))}),o.jsx("div",{className:"grid grid-cols-2 gap-3 @2xl:grid-cols-4",children:[["Requests",c.totals.requests],["Input tokens",c.totals.inputTokens],["Output tokens",c.totals.outputTokens],["Tool calls",c.totals.toolCalls]].map(([p,b])=>o.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] p-4",children:[o.jsx("div",{className:"text-xs text-slate-400",children:p}),o.jsx("div",{className:"mt-1 text-2xl font-semibold text-slate-100 tabular-nums",children:f.format(b)})]},p))}),o.jsxs(yt,{title:"Tokens per day",children:[o.jsx("div",{className:"flex h-32 items-end gap-[3px]",children:c.days.map(p=>o.jsxs("div",{className:"group relative flex h-full flex-1 items-end",children:[o.jsx("div",{className:"w-full rounded-t-sm bg-sky-400/70 transition-colors group-hover:bg-sky-300",style:{height:`${p.tokens?Math.max(3,p.tokens/d*100):0}%`}}),o.jsxs("div",{className:"pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 hidden -translate-x-1/2 rounded-md bg-black/90 px-2 py-1 text-xs whitespace-nowrap text-slate-200 group-hover:block",children:[p.date,": ",f.format(p.tokens)," tokens · ",p.requests," req"]})]},p.date))}),o.jsxs("div",{className:"mt-2 flex justify-between text-xs text-slate-500",children:[o.jsx("span",{children:c.days[0]?.date}),o.jsx("span",{children:"Today"})]})]}),o.jsx(yt,{title:"By model",actions:o.jsx(Oe,{size:"sm",variant:"ghost",disabled:!e.length,onClick:async()=>{await i({title:"Clear usage history?",message:"This only resets the local counters.",confirmLabel:"Clear"})&&wI()},children:"Reset counters"}),children:c.byProvider.length===0?o.jsx("div",{className:"text-sm text-slate-400",children:"No AI requests in this period."}):o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"text-left text-xs text-slate-500",children:[o.jsx("th",{className:"pb-2 font-medium",children:"Model"}),o.jsx("th",{className:"pb-2 text-right font-medium",children:"Requests"}),o.jsx("th",{className:"pb-2 text-right font-medium",children:"Input"}),o.jsx("th",{className:"pb-2 text-right font-medium",children:"Output"}),o.jsx("th",{className:"pb-2 text-right font-medium",children:"Errors"})]})}),o.jsx("tbody",{className:"tabular-nums",children:c.byProvider.map(([p,b])=>{const[x,g]=p.split("::");return o.jsxs("tr",{className:"border-t border-white/[0.05]",children:[o.jsxs("td",{className:"py-2",children:[o.jsx("span",{className:"text-slate-200",children:g})," ",o.jsx("span",{className:"text-xs text-slate-500",children:x==="local"?"built-in":x})]}),o.jsx("td",{className:"py-2 text-right text-slate-300",children:f.format(b.requests)}),o.jsx("td",{className:"py-2 text-right text-slate-300",children:f.format(b.inputTokens)}),o.jsx("td",{className:"py-2 text-right text-slate-300",children:f.format(b.outputTokens)}),o.jsx("td",{className:Ie("py-2 text-right",b.errors?"text-rose-300":"text-slate-500"),children:b.errors})]},p)})})]})})]})}function EL(){const[e,r]=Zv(),n=e.viewer,s=i=>r(c=>({...c,viewer:{...c.viewer,...i}}));return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"3D viewer",description:"Defaults applied when Studio opens."}),o.jsx(yt,{children:o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"Representation",children:o.jsxs(Na,{className:"w-full @xl:w-56",value:n.defaultStyle,onChange:i=>s({defaultStyle:i.target.value}),children:[o.jsx("option",{value:"ribbon",children:"Ribbon"}),o.jsx("option",{value:"trace",children:"Cα trace"}),o.jsx("option",{value:"pocket",children:"Active pocket"})]})}),o.jsx(Qt,{label:"Color by",children:o.jsxs(Na,{className:"w-full @xl:w-56",value:n.defaultColorMode,onChange:i=>s({defaultColorMode:i.target.value}),children:[o.jsx("option",{value:"identity",children:"Structure identity"}),o.jsx("option",{value:"plddt",children:"pLDDT (predictions)"}),o.jsx("option",{value:"bfactor",children:"B-factor (experimental)"}),o.jsx("option",{value:"deviation",children:"Per-residue deviation Δd"})]})}),o.jsx(Qt,{label:"Layout",children:o.jsxs(Na,{className:"w-full @xl:w-56",value:n.defaultLayout,onChange:i=>s({defaultLayout:i.target.value}),children:[o.jsx("option",{value:"overlay",children:"Overlay"}),o.jsx("option",{value:"split",children:"Side by side"}),o.jsx("option",{value:"reference",children:"Reference only"}),o.jsx("option",{value:"mobile",children:"Comparison only"})]})}),o.jsx(Qt,{label:"Embed viewport image in HTML reports",children:o.jsx($r,{checked:n.embedPngInReports,onChange:i=>s({embedPngInReports:i})})})]})}),o.jsxs(yt,{title:"Controls",children:[o.jsxs("dl",{className:"grid grid-cols-[11rem_1fr] gap-y-2.5 text-sm",children:[o.jsx("dt",{className:"text-slate-400",children:"Rotate"}),o.jsx("dd",{className:"text-slate-200",children:"Drag · one-finger drag"}),o.jsx("dt",{className:"text-slate-400",children:"Zoom"}),o.jsx("dd",{className:"text-slate-200",children:"Scroll · trackpad pinch · two-finger pinch"}),o.jsx("dt",{className:"text-slate-400",children:"Pan"}),o.jsx("dd",{className:"text-slate-200",children:"Shift + drag · right-drag · two-finger drag"}),o.jsx("dt",{className:"text-slate-400",children:"Select residue"}),o.jsx("dd",{className:"text-slate-200",children:"Click"})]}),o.jsx("p",{className:"mt-3 text-xs text-slate-500",children:"Pinch and ctrl-scroll only zoom the 3D scene; the rest of the interface stays fixed."})]})]})}function ML({onResetLayout:e}){const[r,n]=Zv(),{toast:s}=cl();return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"Workspace",description:"Interface size, tabs, and behavior."}),o.jsx(yt,{children:o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"Interface size",hint:o.jsxs(o.Fragment,{children:["Also ",o.jsx(Rr,{children:"⌘"})," ",o.jsx(Rr,{children:"+"})," / ",o.jsx(Rr,{children:"⌘"})," ",o.jsx(Rr,{children:"−"})," / ",o.jsx(Rr,{children:"⌘"})," ",o.jsx(Rr,{children:"0"})]}),children:o.jsxs("div",{className:"flex w-full items-center gap-3 @xl:w-64",children:[o.jsx("input",{type:"range",min:nE,max:sE,step:aE,value:r.uiScale,onChange:i=>n({uiScale:Number(i.target.value)}),className:"flex-1 accent-sky-400","aria-label":"Interface size"}),o.jsxs("span",{className:"w-12 text-right text-sm text-slate-300 tabular-nums",children:[Math.round(r.uiScale*100),"%"]})]})}),o.jsx(Qt,{label:"Guided explanations",hint:"Plain-language notes next to metrics and in tools.",children:o.jsx($r,{checked:r.guidedMode,onChange:i=>n({guidedMode:i})})}),o.jsx(Qt,{label:"Reopen tabs on launch",children:o.jsx($r,{checked:r.restoreTabs,onChange:i=>n({restoreTabs:i})})}),o.jsx(Qt,{label:"Load example comparison on launch",hint:"Carbonic anhydrase II: crystal vs AlphaFold.",children:o.jsx($r,{checked:r.loadDemoOnStart,onChange:i=>n({loadDemoOnStart:i})})}),o.jsx(Qt,{label:"Save imports to library automatically",children:o.jsx($r,{checked:r.autoSaveImports,onChange:i=>n({autoSaveImports:i})})}),o.jsx(Qt,{label:"Confirm before deleting",children:o.jsx($r,{checked:r.confirmDeletes,onChange:i=>n({confirmDeletes:i})})}),o.jsx(Qt,{label:"Tab layout",children:o.jsx(Oe,{size:"sm",onClick:()=>{e(),s("Tab layout reset","success")},children:"Reset layout"})})]})}),o.jsx(yt,{title:"Keyboard shortcuts",actions:o.jsx(g6,{className:"h-4 w-4 text-slate-500"}),children:o.jsx("dl",{className:"grid grid-cols-[1fr_auto] gap-y-2.5 text-sm",children:[["Command palette",["⌘","K"]],["Open file",["⌘","O"]],["Search databases",["⌘","Shift","F"]],["Close tab",["Alt","W"]],["Toggle sidebar",["⌘","B"]],["Settings",["⌘",","]],["Interface size",["⌘","+ / −"]]].map(([i,c])=>o.jsxs("div",{className:"contents",children:[o.jsx("dt",{className:"text-slate-300",children:i}),o.jsx("dd",{className:"flex gap-1",children:c.map(d=>o.jsx(Rr,{children:d},d))})]},i))})})]})}function RL({onClearedHistory:e}){const{confirm:r,toast:n}=cl(),[s,i]=C.useState({count:0,bytes:0}),[c,d]=C.useState(null);return C.useEffect(()=>{const f=()=>nu().then(p=>i({count:p.length,bytes:p.reduce((b,x)=>b+x.sizeBytes,0)}));return f(),navigator.storage?.estimate?.().then(d).catch(()=>{}),r0(()=>void f())},[]),o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"Data & storage",description:"Everything here is stored on this device only."}),o.jsx(yt,{children:o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"Library",hint:`${s.count} items · ${Uc(s.bytes)}`,children:o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Oe,{size:"sm",disabled:!s.count,onClick:async()=>{const f=await lE(Cn),p=URL.createObjectURL(new Blob([JSON.stringify(f,null,2)],{type:"application/json"})),b=document.createElement("a");b.href=p,b.download=`synlexa-library-${new Date().toISOString().slice(0,10)}.json`,b.click(),setTimeout(()=>URL.revokeObjectURL(p),1e3)},children:"Export"}),o.jsx(Oe,{size:"sm",variant:"danger",disabled:!s.count,onClick:async()=>{await r({title:`Delete all ${s.count} library items?`,message:"This permanently removes every stored structure, compound, and sequence from this device. Export first if you want a backup.",confirmLabel:"Delete all",danger:!0})&&(await KD(),n("Library cleared","success"))},children:"Delete all"})]})}),o.jsx(Qt,{label:"Comparison run history",children:o.jsx(Oe,{size:"sm",variant:"danger",onClick:async()=>{await r({title:"Clear run history?",message:"Removes the list of past comparisons.",confirmLabel:"Clear",danger:!0})&&(await uE(),e(),n("Run history cleared","success"))},children:"Clear"})}),o.jsx(Qt,{label:"Settings",hint:"Restore every preference to its default.",children:o.jsx(Oe,{size:"sm",onClick:async()=>{await r({title:"Reset all settings?",message:"API keys and your library are not affected.",confirmLabel:"Reset"})&&(GD(),n("Settings reset","success"))},children:"Reset"})}),c?.usage!==void 0&&o.jsx(Qt,{label:"Browser storage used by Studio",children:o.jsxs("span",{className:"text-sm text-slate-300 tabular-nums",children:[Uc(c.usage??0),c.quota?` of ${Uc(c.quota)}`:""]})})]})})]})}const zL="0.4.4";function OL(){return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"About Synlexa Studio"}),o.jsx(yt,{children:o.jsxs("dl",{className:"grid grid-cols-[10rem_1fr] gap-y-2.5 text-sm",children:[o.jsx("dt",{className:"text-slate-400",children:"Version"}),o.jsx("dd",{className:"text-slate-200",children:zL}),o.jsx("dt",{className:"text-slate-400",children:"Compute engine"}),o.jsx("dd",{className:"text-slate-200",children:"synlexa-bio-core (Rust → WebAssembly), runs locally"}),o.jsx("dt",{className:"text-slate-400",children:"Storage"}),o.jsx("dd",{className:"text-slate-200",children:"On this device (IndexedDB + localStorage)"})]})}),o.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.06] p-4 text-sm leading-relaxed text-amber-100/90",children:[Cn," Computational outputs are exploratory and have not been clinically validated."]})]})}const Cc=[{id:1,title:"Start Page & Multi-Project Workspaces",subtitle:"Create isolated projects from templates and keep structures, ligands, and edits organized",icon:Qc,targetTab:"home",actionLabel:"Open Start Page",tryActionKey:"home",summary:"Synlexa Studio starts on the Start Page so you can create a new research project, launch starter benchmarks, or resume saved workspaces before diving into 3D inspection.",bullets:['Click "+ New project" on the Start Page or Workspace Explorer to create a dedicated project (Structure Compare, Ligand Design & Binding, or Peptide & CRISPR Test).',"Switch between projects anytime — all imported structures, designed SMILES molecules, peptides, and CRISPR targets stay organized inside each project.","Alt-click any tool in the Tools sidebar to open tabs side-by-side."]},{id:2,title:"Import Multiple Structures & Split Chains / Ligands",subtitle:"Load PDB/mmCIF files or fetch RCSB, AlphaFold, UniProt, and PubChem records",icon:Px,targetTab:"viewer",actionLabel:"Open 3D Viewer",tryActionKey:"viewer",summary:"Import multiple local structures by drag-and-drop or fetch public IDs directly. Split multi-chain complexes or co-crystallized ligands into standalone project assets.",bullets:["Load structures into Reference and Comparison slots from your disk or Public Databases.",'Click "Split Ref" or "Split Comp" in the Workspace Explorer (or ask the AI Assistant) to split polymer chains and non-water HETATM ligands into independent assets.',"Inspect deterministic float64 Kabsch RMSD, TM-score, GDT-TS, and per-residue Cα distances in 3D."]},{id:3,title:"Design Molecules in the 2D Sketcher & RDKit Engine",subtitle:"Edit ligands visually or by SMILES, score drug-likeness & PAINS alerts, and save to project",icon:ia,targetTab:"chemistry",actionLabel:"Open Ligands & 2D Sketcher",tryActionKey:"chemistry",summary:"Draw ring systems and bonds on the interactive 2D SVG canvas or enter SMILES strings directly. Studio runs RDKit in WebAssembly to compute deterministic descriptors offline.",bullets:["Check exact molecular formula, MW, cLogP, TPSA, HBD/HBA, rotatable bonds, SA score, and Lipinski/Veber checks.","Flag PAINS structural alerts locally before saving promising analogs into your active project.",'Click "Bind" next to any saved project molecule to stage docking/binding tests.']},{id:4,title:"Peptide Engineering & CRISPR / Base-Editing Workbenches",subtitle:"Mutate residues, check 3D active-site contacts, and score SpCas9/SaCas9/Cas12a guides",icon:Fs,targetTab:"peptide",actionLabel:"Open Peptide Workbench",tryActionKey:"peptide",summary:"Test point mutations in loaded protein sequences and inspect base-editing CRISPR targets with automatic PAM matching and codon delta computation.",bullets:["In Peptide Engineering, apply mutations (e.g. H94A), track isoelectric point / charge shifts, and focus those positions in Mol* 3D.","In Gene & CRISPR, switch nucleases (SpCas9 NGG, SaCas9, Cas12a), inspect guide RNAs, and preview amino-acid consequences."]},{id:5,title:"External GPU Nodes (Colab / SSH) & Workflow Canvas",subtitle:"Connect AutoDock Vina, OpenMM MD, Boltz-2, RFdiffusion, and PySCF backends",icon:al,targetTab:"compute",actionLabel:"Open GPU & Compute Nodes",tryActionKey:"compute",summary:"Light visualization and cheminformatics run in-browser via Rust WASM & RDKit. Heavy GPU jobs dispatch cleanly to a local sidecar, Google Colab, or cluster worker.",bullets:["Connect your Google Colab / FastAPI compute worker URL & bearer token in GPU & Compute Nodes.","Design multi-step pipelines in Workflow Canvas and export reproducible Nextflow (`main.nf`) or Snakemake (`Snakefile`) definitions."]},{id:6,title:"Autonomous AI Agent: Live Thinking, Octopus Tools & Permissions",subtitle:"Full UI + project control with interactive permission prompts",icon:qr,targetTab:"assistant",actionLabel:"Open AI Assistant",tryActionKey:"assistant",summary:'The AI Assistant uses Studio’s in-app MCP server as "octopus arms" to create projects, design molecules, split structures, run workflows, and switch UI tabs.',bullets:["Watch the live Thinking & Tool Trace accordion while the agent plans rounds and runs tools.","Sensitive categories (external web/database fetches and remote GPU/workflow execution) pause for your interactive Allow Once / Session / Deny approval.","Adjust per-category policies anytime in Settings → Agent Tool Permissions."]},{id:7,title:"BYOK Key Vault (state.vscdb) vs Synlexa Cloud & Exports",subtitle:"Keep your own Anthropic/Gemini/OpenAI keys encrypted locally with full control",icon:Ki,actionLabel:"Open AI & Key Settings",tryActionKey:"settings",summary:"When you enter your own API key (Anthropic, Gemini, or OpenAI), Studio encrypts it in local state.vscdb and routes directly to your provider instead of Synlexa Cloud.",bullets:['Use "Prefer BYOK keys" (default) so personal API keys always take priority, or switch to manual mode to choose Synlexa Cloud anytime.',"Export RUO-labeled HTML reports, JSON manifests, and reproducible `.synlexa.bundle.json` project archives."]}];function PL({open:e,onClose:r,onExecuteStepAction:n}){const[s,i]=C.useState(0);if(C.useEffect(()=>{if(!e)return;const f=p=>{p.key==="Escape"&&r()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,r]),!e)return null;const c=Cc[s]??Cc[0],d=c.icon;return o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 backdrop-blur-xs",role:"dialog","aria-modal":"true","aria-label":"Synlexa Studio Interactive Tutorial",onClick:f=>{f.target===f.currentTarget&&r()},children:o.jsxs("div",{className:"flex max-h-[88vh] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-white/15 bg-[#0e131c] shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-white/[0.08] px-5 py-3.5",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-sky-500/15 text-sky-300",children:o.jsx(jy,{className:"h-4 w-4"})}),o.jsxs("div",{children:[o.jsx("h2",{className:"text-sm font-semibold text-slate-100",children:"Synlexa Studio Interactive Guide"}),o.jsxs("p",{className:"text-xs text-slate-400",children:["Step ",c.id," of ",Cc.length," · Research-Use-Only (RUO)"]})]})]}),o.jsx("button",{type:"button",onClick:r,"aria-label":"Close guide",className:"rounded-lg p-1.5 text-slate-400 hover:bg-white/[0.06] hover:text-white",children:o.jsx(Xi,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"flex flex-wrap gap-1.5 border-b border-white/[0.06] bg-white/[0.015] px-5 py-2.5",children:Cc.map((f,p)=>{const b=p===s;return o.jsxs("button",{type:"button",onClick:()=>i(p),className:Ie("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",b?"border-sky-400/50 bg-sky-500/15 text-sky-200":"border-white/10 bg-white/[0.02] text-slate-400 hover:text-slate-200"),children:[o.jsx("span",{className:"font-mono text-[0.6875rem]",children:f.id}),o.jsx("span",{className:"hidden sm:inline",children:f.title.split("&")[0]?.trim()})]},f.id)})}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-5",children:[o.jsxs("div",{className:"flex items-start gap-4",children:[o.jsx("span",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-sky-400/30 bg-sky-500/10 text-sky-300",children:o.jsx(d,{className:"h-5 w-5"})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("h3",{className:"text-lg font-semibold text-slate-100",children:c.title}),o.jsxs(It,{tone:"accent",children:["Step ",c.id]})]}),o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:c.subtitle})]})]}),o.jsx("p",{className:"mt-4 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5 text-sm leading-relaxed text-slate-200",children:c.summary}),o.jsx("ul",{className:"mt-4 space-y-2.5",children:c.bullets.map((f,p)=>o.jsxs("li",{className:"flex items-start gap-2.5 text-sm text-slate-300",children:[o.jsx(Gs,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-400"}),o.jsx("span",{children:f})]},p))}),o.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-2 rounded-xl border border-sky-500/20 bg-sky-500/[0.06] px-4 py-3",children:[o.jsx("span",{className:"text-xs text-slate-300",children:"Try this feature directly inside the Studio workspace:"}),o.jsx(Oe,{size:"sm",variant:"primary",className:"ml-auto",onClick:()=>{n(c.tryActionKey),r()},children:c.actionLabel??"Try in Studio"})]})]}),o.jsxs("div",{className:"flex items-center justify-between border-t border-white/[0.08] px-5 py-3",children:[o.jsx(Oe,{size:"sm",variant:"ghost",disabled:s===0,icon:o.jsx(iR,{className:"h-3.5 w-3.5"}),onClick:()=>i(f=>Math.max(0,f-1)),children:"Previous"}),o.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500",children:[o.jsx(qi,{className:"h-3.5 w-3.5"}),o.jsx("span",{children:"Press Esc anytime · Reopen via Guide in the top bar"})]}),s<Cc.length-1?o.jsxs(Oe,{size:"sm",variant:"primary",onClick:()=>i(f=>Math.min(Cc.length-1,f+1)),children:["Next",o.jsx(DA,{className:"ml-1 h-3.5 w-3.5"})]}):o.jsx(Oe,{size:"sm",variant:"primary",onClick:r,children:"Done"})]})]})})}function $L({onExecuteNode:e,activeComputeLabel:r,onOpenComputeNodes:n,bridge:s}){const[i,c]=C.useState(()=>Zd[0]),[d,f]=C.useState(Zd[0].nodes[0]?.id??null),[p,b]=C.useState(null),[x,g]=C.useState({}),[_,y]=C.useState(!1),[S,k]=C.useState(null),[E,T]=C.useState(!1),j=C.useRef(null),q=C.useMemo(()=>new Map(i.nodes.map(W=>[W.id,W])),[i.nodes]),z=C.useMemo(()=>{let W=960,me=340;for(const I of i.nodes)I.x+230>W&&(W=I.x+230),I.y+130>me&&(me=I.y+130);return{width:W,height:me}},[i.nodes]),O=W=>{const me=Zn[W],I=`n${Date.now().toString(36).slice(-4)}`,J=i.nodes.length%4,ge=Math.floor(i.nodes.length/4);c(le=>({...le,nodes:[...le.nodes,{id:I,kind:W,x:40+J*235,y:45+ge*125,params:{...me.defaultParams}}]})),f(I)},V=W=>{c(me=>({...me,nodes:me.nodes.filter(I=>I.id!==W),edges:me.edges.filter(I=>I.from!==W&&I.to!==W)})),d===W&&f(null)},P=W=>{c(me=>({...me,edges:me.edges.filter(I=>I.id!==W)}))},$=W=>{if(!p||p===W){b(null);return}i.edges.some(I=>I.from===p&&I.to===W)||c(I=>({...I,edges:[...I.edges,{id:`e-${p}-${W}`,from:p,to:W}]})),b(null)},H=()=>{let W=i.nodes;try{W=fh(i)}catch{}const me=new Map;for(const J of W)me.set(J.id,0);for(const J of W){const ge=me.get(J.id)??0;for(const le of i.edges)le.from===J.id&&me.set(le.to,Math.max(me.get(le.to)??0,ge+1))}const I=new Map;for(const J of W){const ge=me.get(J.id)??0,le=I.get(ge)??[];le.push(J.id),I.set(ge,le)}c(J=>({...J,nodes:J.nodes.map(ge=>{const le=me.get(ge.id)??0,ae=(I.get(le)??[ge.id]).indexOf(ge.id);return{...ge,x:32+le*235,y:44+ae*124}})}))},Z=(W,me,I)=>{c(J=>({...J,nodes:J.nodes.map(ge=>ge.id===W?{...ge,params:{...ge.params,[me]:I}}:ge)}))},G=async()=>{k(null);let W;try{W=fh(i)}catch(I){k(I instanceof Error?I.message:String(I));return}y(!0);const me={};for(const I of W)me[I.id]={status:"idle"};g(me);try{for(const I of W){g(J=>({...J,[I.id]:{status:"running"}}));try{const J=await e(I.kind,I.params);g(ge=>({...ge,[I.id]:{status:"completed",summary:J.summary,metrics:J.metrics}}))}catch(J){const ge=J instanceof Error?J.message:String(J);g(le=>({...le,[I.id]:{status:"failed",error:ge}})),k(`Stopped at ${Zn[I.kind].label}: ${ge}`);break}}}finally{y(!1)}},K=(W,me)=>{const I=new Blob([me],{type:"text/plain;charset=utf-8"}),J=URL.createObjectURL(I),ge=document.createElement("a");ge.href=J,ge.download=W,ge.click(),setTimeout(()=>URL.revokeObjectURL(J),1e3)},we=(W,me,I,J)=>{W.target.closest("button")||(W.currentTarget.setPointerCapture(W.pointerId),j.current={id:me,startClientX:W.clientX,startClientY:W.clientY,origX:I,origY:J,moved:!1})},Se=W=>{const me=j.current;if(!me)return;const I=W.clientX-me.startClientX,J=W.clientY-me.startClientY;if((Math.abs(I)>4||Math.abs(J)>4)&&(me.moved=!0),!me.moved)return;const ge=Math.max(16,me.origX+I),le=Math.max(16,me.origY+J);c(D=>({...D,nodes:D.nodes.map(ae=>ae.id===me.id?{...ae,x:ge,y:le}:ae)}))},Q=W=>{const me=j.current;j.current=null,me&&!me.moved&&(p&&p!==W?$(W):f(W))},F=d?q.get(d)??null:null,he=F?i.edges.filter(W=>W.from===F.id||W.to===F.id):[];return o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3 text-xs @xl:p-4",children:[o.jsx(ir,{bridge:s,title:"Visual Workflow Canvas (DAG)",subtitle:"Chain local Wasm/RDKit steps and external GPU jobs using your active 3D structure & ligand, or export Nextflow / Snakemake.",icon:o.jsx(Dp,{className:"h-4 w-4"}),guideOpen:E,onToggleGuide:()=>T(W=>!W),actions:o.jsxs("button",{type:"button",onClick:n,className:"rounded-lg border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-300 hover:border-sky-500/40",children:["GPU Node: ",o.jsx("strong",{className:r?"text-emerald-300":"text-amber-300",children:r??"Not paired"})]})}),o.jsx(Qi,{open:E,title:"How the Visual Workflow Canvas Works",summary:"Design reproducible Directed Acyclic Graph (DAG) pipelines combining Tier-0/Tier-1 browser Wasm steps (Kabsch, RDKit, Reports) and Tier-2 GPU Compute Node workloads (Vina, OpenMM, Boltz-2, RFdiffusion, PySCF).",steps:["Pick a starter template or click + buttons to add processing nodes onto the canvas.","Drag nodes to organize them, click Link → on one node then click a target node to connect edges, and edit node parameters in the Inspector below.","Click Run DAG to execute topologically using your active 3D structures & ligand SMILES, or export a reproducible Nextflow / Snakemake script."],connectionTip:"The Workspace Inputs node automatically pulls your currently loaded 3D Reference/Comparison structures, active SMILES ligand, and 3D Vina pocket box."}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx(Oe,{size:"sm",variant:"secondary",icon:o.jsx(VA,{className:"h-3.5 w-3.5"}),onClick:H,children:"Auto-Layout"}),o.jsx(Oe,{size:"sm",variant:"secondary",icon:o.jsx(sr,{className:"h-3.5 w-3.5"}),onClick:()=>K("main.nf",X3(i)),children:"Nextflow"}),o.jsx(Oe,{size:"sm",variant:"secondary",icon:o.jsx(sr,{className:"h-3.5 w-3.5"}),onClick:()=>K("Snakefile",Q3(i)),children:"Snakemake"}),o.jsx(Oe,{size:"sm",variant:"secondary",icon:o.jsx(sr,{className:"h-3.5 w-3.5"}),onClick:()=>K(`${i.id}.synlexa-flow.json`,JSON.stringify(i,null,2)),children:"JSON"})]}),o.jsx(Oe,{size:"sm",variant:"primary",disabled:_,icon:_?o.jsx(qs,{className:"h-3.5 w-3.5 animate-spin"}):o.jsx(qp,{className:"h-3.5 w-3.5"}),onClick:()=>void G(),children:_?"Running Pipeline…":"Run DAG"})]}),o.jsxs("div",{className:"space-y-2 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx("span",{className:"text-[0.6875rem] font-semibold text-slate-400 uppercase",children:"Templates:"}),Zd.map(W=>o.jsx("button",{type:"button",onClick:()=>{c(W),f(W.nodes[0]?.id??null),g({}),k(null)},className:Ie("rounded-lg border px-2.5 py-1 text-xs transition",i.id===W.id?"border-sky-400/50 bg-sky-500/20 text-sky-200":"border-white/10 bg-slate-900 text-slate-300 hover:border-white/25"),children:W.name},W.id))]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-t border-white/[0.06] pt-2",children:[o.jsx("span",{className:"text-[0.6875rem] text-slate-400",children:"Add Node:"}),Object.keys(Zn).map(W=>{const me=Zn[W];return o.jsxs("button",{type:"button",onClick:()=>O(W),title:`${me.toolName} (${me.tier})`,className:"flex items-center gap-1 rounded-md border border-white/10 bg-slate-950 px-2 py-1 text-[0.6875rem] text-slate-300 hover:border-sky-500/40",children:[o.jsx(gh,{className:"h-3 w-3 text-sky-300"}),me.label]},W)})]})]}),S&&o.jsx("div",{className:"rounded-xl border border-rose-500/40 bg-rose-500/10 px-3 py-2 text-rose-200",children:S}),o.jsx("div",{className:"relative min-h-[300px] flex-1 overflow-auto rounded-xl border border-white/[0.08] bg-[#070b12]",children:o.jsxs("div",{className:"relative",style:{width:z.width,height:z.height},children:[o.jsxs("svg",{className:"pointer-events-none absolute inset-0 h-full w-full",children:[o.jsx("defs",{children:o.jsx("pattern",{id:"synlexa-dag-grid",width:"28",height:"28",patternUnits:"userSpaceOnUse",children:o.jsx("path",{d:"M 28 0 L 0 0 0 28",fill:"none",stroke:"rgba(148,163,184,0.05)",strokeWidth:"1"})})}),o.jsx("rect",{width:"100%",height:"100%",fill:"url(#synlexa-dag-grid)"}),i.edges.map(W=>{const me=q.get(W.from),I=q.get(W.to);if(!me||!I)return null;const J=me.x+196,ge=me.y+46,le=I.x,D=I.y+46,ae=(J+le)/2,pe=d===W.from||d===W.to;return o.jsx("path",{d:`M ${J} ${ge} C ${ae} ${ge}, ${ae} ${D}, ${le} ${D}`,fill:"none",stroke:pe?"rgba(56,189,248,0.85)":"rgba(56,189,248,0.4)",strokeWidth:pe?2.5:2},W.id)})]}),i.nodes.map(W=>{const me=Zn[W.kind],I=x[W.id],J=d===W.id;return o.jsxs("div",{style:{left:W.x,top:W.y,width:196},onPointerDown:ge=>we(ge,W.id,W.x,W.y),onPointerMove:Se,onPointerUp:()=>Q(W.id),className:Ie("absolute cursor-grab rounded-xl border bg-[#0d121b]/95 p-2.5 shadow-lg transition select-none active:cursor-grabbing",J?"border-sky-400/80 ring-1 ring-sky-400/35":"border-white/10 hover:border-white/25"),children:[o.jsxs("div",{className:"flex items-start justify-between gap-1",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate font-semibold text-slate-100",children:me.label}),o.jsx("div",{className:"truncate font-mono text-[0.6875rem] text-slate-400",children:me.toolName})]}),I?.status==="running"&&o.jsx(qs,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-sky-400"}),I?.status==="completed"&&o.jsx(Gs,{className:"h-3.5 w-3.5 shrink-0 text-emerald-400"}),I?.status==="failed"&&o.jsx(Bc,{className:"h-3.5 w-3.5 shrink-0 text-rose-400"})]}),o.jsxs("div",{className:"mt-2 flex items-center justify-between gap-1",children:[o.jsx(It,{tone:me.tier==="tier2-gpu"?"warn":me.tier==="tier1-wasm"?"accent":"good",children:me.tier}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{type:"button",onClick:ge=>{ge.stopPropagation(),b(p===W.id?null:W.id)},className:Ie("rounded border px-1.5 py-0.5 text-[0.625rem]",p===W.id?"border-sky-400 bg-sky-500/20 text-sky-200":"border-white/10 text-slate-400 hover:text-slate-200"),children:p===W.id?"Click target…":"Link →"}),o.jsx("button",{type:"button",onClick:ge=>{ge.stopPropagation(),V(W.id)},className:"rounded p-0.5 text-slate-500 hover:text-rose-300",title:"Delete node",children:o.jsx(Wi,{className:"h-3 w-3"})})]})]}),I?.summary&&o.jsx("div",{className:"mt-1.5 truncate font-mono text-[0.6875rem] text-emerald-300",title:I.summary,children:I.summary}),I?.error&&o.jsx("div",{className:"mt-1.5 truncate font-mono text-[0.6875rem] text-rose-300",title:I.error,children:I.error})]},W.id)})]})}),F&&o.jsxs(yt,{className:"space-y-3 p-3.5",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-semibold text-slate-100",children:Zn[F.kind].label}),o.jsxs("span",{className:"font-mono text-[0.6875rem] text-slate-500",children:["(",F.id,")"]}),o.jsx(It,{tone:Zn[F.kind].tier==="tier2-gpu"?"warn":"good",children:Zn[F.kind].tier})]}),o.jsxs("div",{className:"mt-0.5 text-[0.6875rem] text-slate-400",children:["Input: ",Zn[F.kind].inputPort," → Output: ",Zn[F.kind].outputPort]})]}),Zn[F.kind].tier==="tier2-gpu"&&!r&&o.jsx("button",{type:"button",onClick:n,className:"rounded-lg border border-amber-400/40 bg-amber-500/10 px-2.5 py-1 text-[0.6875rem] font-medium text-amber-200 hover:bg-amber-500/20",children:"Requires Online GPU Node — Pair Colab / Local →"})]}),Object.keys(F.params).length>0&&o.jsx("div",{className:"grid grid-cols-1 gap-2 @lg:grid-cols-2 @3xl:grid-cols-3",children:Object.entries(F.params).map(([W,me])=>o.jsxs("label",{className:"flex flex-col gap-1 rounded-lg border border-white/[0.07] bg-black/25 px-2.5 py-2",children:[o.jsx("span",{className:"font-mono text-[0.6875rem] text-slate-400",children:W}),typeof me=="boolean"?o.jsxs("span",{className:"flex items-center gap-2 text-xs text-slate-200",children:[o.jsx("input",{type:"checkbox",checked:me,onChange:I=>Z(F.id,W,I.target.checked),className:"accent-sky-400"}),me?"Enabled":"Disabled"]}):typeof me=="number"?o.jsx("input",{type:"number",value:me,onChange:I=>Z(F.id,W,Number(I.target.value)||0),className:"h-7 rounded border border-white/10 bg-slate-950 px-2 font-mono text-xs text-slate-100 outline-none focus:border-sky-400"}):o.jsx("input",{value:String(me),onChange:I=>Z(F.id,W,I.target.value),className:"h-7 rounded border border-white/10 bg-slate-950 px-2 font-mono text-xs text-slate-100 outline-none focus:border-sky-400"})]},W))}),he.length>0&&o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-t border-white/[0.06] pt-2",children:[o.jsx("span",{className:"text-[0.6875rem] text-slate-500",children:"Connections:"}),he.map(W=>{const me=Zn[q.get(W.from)?.kind??"load_structures"].label,I=Zn[q.get(W.to)?.kind??"load_structures"].label;return o.jsxs("button",{type:"button",onClick:()=>P(W.id),title:"Click to unlink edge",className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-black/30 px-2 py-0.5 text-[0.6875rem] text-slate-300 hover:border-rose-400/50 hover:text-rose-200",children:[o.jsxs("span",{children:[me," → ",I]}),o.jsx(sz,{className:"h-3 w-3"})]},W.id)})]})]})]})}const qd="application/x-synlexa-tab";function IL({layout:e,dispatch:r,meta:n,renderTab:s,keepAlive:i}){const c=C.useRef(null),[d,f]=C.useState(null),[p,b]=C.useState(null);C.useEffect(()=>{if(!p)return;const y=()=>b(null);return window.addEventListener("mousedown",y),window.addEventListener("blur",y),()=>{window.removeEventListener("mousedown",y),window.removeEventListener("blur",y)}},[p]);const x=y=>{y.preventDefault();const S=c.current;if(!S)return;const k=S.getBoundingClientRect(),E=j=>{r({type:"set_split",split:(j.clientX-k.left)/k.width})},T=()=>{window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",T),document.body.style.cursor=""};document.body.style.cursor="col-resize",window.addEventListener("pointermove",E),window.addEventListener("pointerup",T)},g=(y,S,k)=>{const E=y.dataTransfer.getData(qd);f(null),E&&(y.preventDefault(),r({type:"move",tab:E,toGroup:S,index:k}))},_=e.groups.length===2;return o.jsxs("div",{ref:c,className:"relative flex min-h-0 min-w-0 flex-1",children:[e.groups.map((y,S)=>o.jsxs("div",{style:_?{width:`${(S===0?e.split:1-e.split)*100}%`}:void 0,className:Ie("relative flex min-h-0 min-w-0 flex-col",!_&&"flex-1"),onMouseDownCapture:()=>e.focused!==S&&r({type:"focus_group",group:S}),children:[o.jsxs("div",{role:"tablist",className:Ie("flex h-10 shrink-0 items-stretch border-b border-white/[0.06] bg-[#0d1119]",e.focused===S&&_&&"shadow-[inset_0_-1px_0_0_rgba(56,189,248,0.25)]"),onDragOver:k=>{k.dataTransfer.types.includes(qd)&&k.preventDefault()},onDrop:k=>g(k,S),children:[o.jsx("div",{className:"flex min-w-0 flex-1 items-stretch overflow-x-auto [scrollbar-width:none]",children:y.tabs.map((k,E)=>{const T=n[k],j=y.active===k,q=!Op.has(k);return o.jsxs("div",{role:"tab","aria-selected":j,tabIndex:0,draggable:!0,onDragStart:z=>{z.dataTransfer.setData(qd,k),z.dataTransfer.effectAllowed="move",f(k)},onDragEnd:()=>f(null),onDragOver:z=>{z.dataTransfer.types.includes(qd)&&z.preventDefault()},onDrop:z=>{z.stopPropagation(),g(z,S,E)},onClick:()=>r({type:"activate",tab:k}),onAuxClick:z=>{z.button===1&&q&&r({type:"close",tab:k})},onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&r({type:"activate",tab:k})},onContextMenu:z=>{z.preventDefault(),b({tab:k,x:z.clientX,y:z.clientY})},className:Ie("group relative flex max-w-56 min-w-0 shrink-0 cursor-pointer items-center gap-2 border-r border-white/[0.05] pr-1.5 pl-3 text-[0.8125rem] transition-colors select-none",j?"bg-[#121722] text-slate-100":"text-slate-400 hover:bg-white/[0.03] hover:text-slate-200",d===k&&"opacity-40"),children:[j&&o.jsx("span",{className:Ie("absolute inset-x-0 top-0 h-0.5",e.focused===S?"bg-sky-400":"bg-slate-600")}),o.jsx("span",{className:Ie("shrink-0",j?"text-sky-300":"text-slate-500"),children:T.icon}),o.jsx("span",{className:"truncate",children:T.title}),T.badge,q?o.jsx("button",{type:"button","aria-label":`Close ${T.title}`,title:"Close (middle-click)",onClick:z=>{z.stopPropagation(),r({type:"close",tab:k})},className:Ie("flex h-5 w-5 items-center justify-center rounded text-slate-500 hover:bg-white/10 hover:text-slate-100",j?"opacity-100":"opacity-0 group-hover:opacity-100"),children:o.jsx(Xi,{className:"h-3.5 w-3.5"})}):o.jsx("span",{className:"w-1"})]},k)})}),o.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 px-1.5",children:[y.active&&o.jsx("button",{type:"button",title:_?"Move tab to the other side":"Split editor right","aria-label":"Split editor",onClick:()=>y.active&&r({type:"open",tab:y.active,toSide:!0}),disabled:!_&&y.tabs.length<2,className:"flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-white/[0.07] hover:text-slate-200 disabled:opacity-30",children:o.jsx(Ey,{className:"h-4 w-4"})}),_&&o.jsx("button",{type:"button",title:"Merge split panes into single full-width view","aria-label":"Merge split panes",onClick:()=>r({type:"merge_split"}),className:"flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-white/[0.07] hover:text-sky-300",children:o.jsx(Oy,{className:"h-3.5 w-3.5"})})]})]}),o.jsxs("div",{className:"relative min-h-0 flex-1 bg-[#0f131b]",onDragOver:k=>{k.dataTransfer.types.includes(qd)&&k.preventDefault()},onDrop:k=>g(k,S),children:[y.tabs.map(k=>{const E=y.active===k;return!E&&!i?.has(k)?null:o.jsx("div",{role:"tabpanel",className:Ie("absolute inset-0 overflow-hidden",!E&&"invisible"),"aria-hidden":!E,children:s(k)},k)}),d&&o.jsx("div",{className:"pointer-events-none absolute inset-2 rounded-xl border-2 border-dashed border-sky-400/30 bg-sky-400/[0.03]"})]})]},S)),_&&o.jsx("div",{onPointerDown:x,onDoubleClick:()=>r({type:"set_split",split:.6}),style:{left:`calc(${e.split*100}% - 3px)`},className:"absolute top-0 bottom-0 z-20 w-1.5 cursor-col-resize bg-transparent transition-colors hover:bg-sky-400/40",title:"Drag to resize · double-click to reset"}),_&&o.jsx("div",{style:{left:`${e.split*100}%`},className:"pointer-events-none absolute top-0 bottom-0 z-10 w-px bg-white/[0.08]"}),!_&&d&&o.jsx("div",{onDragOver:y=>y.preventDefault(),onDrop:y=>g(y,1),className:"absolute top-10 right-0 bottom-0 z-30 flex w-1/3 items-center justify-center rounded-l-xl border-2 border-dashed border-sky-400/50 bg-sky-400/10 text-sm font-medium text-sky-200",children:"Drop to open on the side"}),p&&o.jsx("div",{onMouseDown:y=>y.stopPropagation(),style:{left:p.x,top:p.y},className:"fixed z-[75] min-w-52 overflow-hidden rounded-xl border border-white/10 bg-[#161c28] py-1 text-sm shadow-2xl",children:[{label:_?"Move to other side":"Open to the side",run:()=>r({type:"open",tab:p.tab,toSide:!0}),disabled:!_&&e.groups[0].tabs.length<2},..._?[{label:"Merge split panes",run:()=>r({type:"merge_split"}),disabled:!1}]:[],{label:"Close",run:()=>r({type:"close",tab:p.tab}),disabled:Op.has(p.tab)},{label:"Close others",run:()=>r({type:"close_others",tab:p.tab})}].map(y=>o.jsx("button",{type:"button",disabled:y.disabled,onClick:()=>{y.run(),b(null)},className:"flex w-full px-3 py-2 text-left text-slate-200 hover:bg-white/[0.06] disabled:opacity-40",children:y.label},y.label))})]})}function DL({projectTitle:e,session:r,onOpenPalette:n,onOpenFile:s,onSearchDatabases:i,onOpenMcp:c,onOpenTutorial:d,onExportHtml:f,onExportJson:p,onExportBundle:b,canExport:x,onOpenAccount:g}){const _=(r?.displayName??r?.email??"").split(/[\s@.]+/).filter(Boolean).slice(0,2).map(y=>y[0]?.toUpperCase()).join("");return o.jsxs("header",{className:"relative flex h-12 shrink-0 items-center gap-3 border-b border-white/[0.06] bg-[#0a0d13] px-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[o.jsx("span",{className:"text-sm font-semibold tracking-tight text-slate-100",children:"Synlexa Studio"}),o.jsx("span",{className:"hidden text-slate-700 md:inline",children:"/"}),o.jsx("span",{className:"hidden max-w-[18rem] truncate text-sm text-slate-400 md:inline",title:e,children:e})]}),o.jsxs("button",{type:"button",onClick:n,className:"absolute left-1/2 hidden h-8 w-[min(25rem,30vw)] -translate-x-1/2 items-center gap-2 rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 text-sm text-slate-500 transition-colors hover:border-white/15 hover:text-slate-300 xl:flex",children:[o.jsx(Gr,{className:"h-4 w-4"}),o.jsx("span",{className:"flex-1 text-left",children:"Search commands, tools, MCP, settings…"}),o.jsx(Rr,{children:"⌘K"})]}),o.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[o.jsx(Oe,{size:"sm",variant:"ghost",icon:o.jsx(My,{className:"h-4 w-4"}),onClick:s,children:o.jsx("span",{className:"hidden sm:inline",children:"Open"})}),o.jsx(Oe,{size:"sm",variant:"ghost",icon:o.jsx(Vi,{className:"h-4 w-4"}),onClick:i,children:o.jsx("span",{className:"hidden sm:inline",children:"Databases"})}),d&&o.jsx(Oe,{size:"sm",variant:"ghost",icon:o.jsx(jy,{className:"h-4 w-4 text-emerald-400"}),onClick:d,children:o.jsx("span",{className:"hidden sm:inline",children:"Guide"})}),c&&o.jsx(Oe,{size:"sm",variant:"ghost",icon:o.jsx(rl,{className:"h-4 w-4 text-sky-400"}),onClick:c,children:o.jsx("span",{className:"hidden sm:inline",children:"MCP"})}),o.jsx(i1,{trigger:(y,S)=>o.jsxs(Oe,{size:"sm",variant:"secondary",onClick:S,icon:o.jsx(sr,{className:"h-4 w-4"}),children:[o.jsx("span",{className:"hidden sm:inline",children:"Export"}),o.jsx(ph,{className:Ie("h-3.5 w-3.5 transition-transform",y&&"rotate-180")})]}),items:[{label:"HTML report",icon:o.jsx(sr,{className:"h-4 w-4"}),onSelect:f,disabled:!x},{label:"JSON manifest",icon:o.jsx(BA,{className:"h-4 w-4"}),onSelect:p,disabled:!x},{label:"Project bundle",icon:o.jsx(UA,{className:"h-4 w-4"}),onSelect:b}]}),o.jsx("button",{type:"button",onClick:g,title:r?`Signed in as ${r.email??r.displayName??"user"}`:"Account & Settings",className:Ie("ml-1 flex h-8 w-8 items-center justify-center rounded-full text-xs font-semibold transition",r?"bg-gradient-to-br from-blue-500 to-blue-700 text-white":"border border-white/10 bg-white/[0.04] text-slate-400 hover:text-slate-200"),children:r?_||o.jsx(ah,{className:"h-4 w-4"}):o.jsx(ah,{className:"h-4 w-4"})})]})]})}function qL({view:e,sidebarOpen:r,onSelect:n,onOpenSettings:s,onOpenAssistant:i,onOpenMcp:c,libraryCount:d}){const f=[{id:"explorer",label:"Workspace",icon:o.jsx(qi,{className:"h-5 w-5"})},{id:"library",label:"Library",icon:o.jsx(sh,{className:"h-5 w-5"})},{id:"tools",label:"Tools",icon:o.jsx(Py,{className:"h-5 w-5"})},{id:"history",label:"History",icon:o.jsx(HA,{className:"h-5 w-5"})}];return o.jsxs("nav",{className:"flex w-14 shrink-0 flex-col items-center gap-1 border-r border-white/[0.06] bg-[#0a0d13] py-2",children:[f.map(p=>{const b=r&&e===p.id;return o.jsxs("button",{type:"button",title:p.label,"aria-label":p.label,onClick:()=>n(p.id),className:Ie("relative flex h-11 w-11 flex-col items-center justify-center rounded-xl transition-colors",b?"bg-white/[0.08] text-slate-100":"text-slate-500 hover:bg-white/[0.04] hover:text-slate-200"),children:[b&&o.jsx("span",{className:"absolute top-2 bottom-2 -left-1.5 w-0.5 rounded-full bg-sky-400"}),p.icon,p.id==="library"&&d>0&&o.jsx("span",{className:"absolute top-1 right-1 min-w-4 rounded-full bg-sky-500 px-1 text-[0.625rem] leading-4 font-semibold text-slate-950",children:d>99?"99+":d})]},p.id)}),o.jsx("div",{className:"flex-1"}),c&&o.jsx("button",{type:"button",title:"In-App MCP Server","aria-label":"In-App MCP Server",onClick:c,className:"flex h-11 w-11 items-center justify-center rounded-xl text-slate-500 hover:bg-white/[0.04] hover:text-sky-300",children:o.jsx(rl,{className:"h-5 w-5"})}),o.jsx("button",{type:"button",title:"AI Assistant","aria-label":"AI Assistant",onClick:i,className:"flex h-11 w-11 items-center justify-center rounded-xl text-slate-500 hover:bg-white/[0.04] hover:text-sky-300",children:o.jsx(qr,{className:"h-5 w-5"})}),o.jsx("button",{type:"button",title:"Settings (⌘,)","aria-label":"Settings",onClick:s,className:"flex h-11 w-11 items-center justify-center rounded-xl text-slate-500 hover:bg-white/[0.04] hover:text-slate-200",children:o.jsx(H6,{className:"h-5 w-5"})})]})}function LL({title:e,actions:r,children:n,width:s}){return o.jsxs("aside",{style:{width:s},className:"flex shrink-0 flex-col border-r border-white/[0.06] bg-[#0c1017]",children:[o.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between px-3",children:[o.jsx("span",{className:"text-xs font-semibold tracking-wide text-slate-400 uppercase",children:e}),o.jsx("div",{className:"flex items-center gap-0.5",children:r})]}),o.jsx("div",{className:"min-h-0 flex-1",children:n})]})}function RA({role:e,label:r,inspect:n,chain:s,onChangeChain:i,onReplace:c,onSaveToLibrary:d,hasContent:f}){const p=e==="reference",b=n&&n.chains.length>1&&!s;return o.jsxs("div",{className:Ie("rounded-xl border p-3",b?"border-amber-500/40 bg-amber-500/[0.04]":"border-white/[0.07] bg-white/[0.02]"),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:Ie("text-[0.6875rem] font-semibold tracking-wide uppercase",p?"text-sky-300":"text-emerald-300"),children:p?"Reference":"Comparison"}),o.jsxs("div",{className:"flex items-center",children:[f&&o.jsx(sl,{label:"Save to library",onClick:d,children:o.jsx(qA,{className:"h-4 w-4"})}),o.jsx(sl,{label:`Replace ${p?"reference":"comparison"} file`,onClick:c,children:o.jsx(Oc,{className:"h-4 w-4"})})]})]}),f?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mt-1 truncate text-sm font-medium text-slate-100",title:r,children:r}),o.jsx("div",{className:"mt-0.5 text-xs text-slate-500",children:n?`${n.format.toUpperCase()} · ${n.chains.length} chain${n.chains.length===1?"":"s"} · ${n.confidenceKind==="prediction_plddt"?"predicted":n.confidenceKind==="experimental_b_factor"?"experimental":"unknown confidence"}`:"Reading…"}),n&&n.chains.length>0&&o.jsx("div",{className:"mt-2.5 flex flex-wrap gap-1",children:n.chains.map(x=>o.jsx("button",{type:"button",onClick:()=>i(x.chainId),title:`${x.observedCaCount} observed Cα`,className:Ie("rounded-md border px-2 py-1 font-mono text-xs transition-colors",s===x.chainId?p?"border-sky-400/50 bg-sky-400/15 text-sky-200":"border-emerald-400/50 bg-emerald-400/15 text-emerald-200":"border-white/10 text-slate-400 hover:border-white/25 hover:text-slate-200"),children:x.chainId},x.chainId))}),b&&o.jsx("div",{className:"mt-2 text-xs text-amber-300",children:"Pick a chain to run the comparison."})]}):o.jsx("button",{type:"button",onClick:c,className:"mt-1.5 text-sm text-slate-400 hover:text-sky-300",children:"Load a structure…"})]})}function UL(e){const r=C.useRef(null),n=C.useRef("auto"),[s,i]=C.useState(!1),[c,d]=C.useState(!1),[f,p]=C.useState(""),[b,x]=C.useState("ligand-docking"),g=y=>{n.current=y,r.current?.click()},_=()=>{e.onCreateProject&&(e.onCreateProject({name:f.trim()||"Untitled Research Project",template:b}),p(""),d(!1))};return o.jsxs("div",{className:"relative flex h-full flex-col overflow-y-auto px-3 pb-4",onDragOver:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),i(!0))},onDragLeave:y=>y.currentTarget===y.target&&i(!1),onDrop:y=>{y.dataTransfer.files.length&&(y.preventDefault(),i(!1),e.onUploadFiles(y.dataTransfer.files,"auto"))},children:[o.jsx("input",{ref:r,type:"file",multiple:!0,accept:".cif,.mmcif,.pdb,.ent,.json,.fasta,.fa,.smi",className:"hidden",onChange:y=>{y.target.files?.length&&e.onUploadFiles(y.target.files,n.current),y.target.value=""}}),e.projects&&e.activeProject&&e.onSwitchProject&&o.jsxs("div",{className:"mb-3 rounded-xl border border-white/[0.08] bg-white/[0.02] p-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between gap-1.5",children:[o.jsx("span",{className:"text-[0.6875rem] font-semibold tracking-wide text-slate-400 uppercase",children:"Project"}),e.onCreateProject&&o.jsxs("button",{type:"button",onClick:()=>d(y=>!y),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[0.6875rem] text-sky-300 hover:bg-sky-500/10",children:[o.jsx(Qc,{className:"h-3 w-3"}),"New"]})]}),o.jsx(Na,{value:e.activeProject.id,onChange:y=>e.onSwitchProject?.(y.target.value),className:"mt-1.5 h-8 text-xs",children:e.projects.map(y=>o.jsx("option",{value:y.id,children:y.name},y.id))}),c&&o.jsxs("div",{className:"mt-2 space-y-1.5 border-t border-white/[0.06] pt-2",children:[o.jsx(Dn,{value:f,onChange:y=>p(y.target.value),placeholder:"Project name…",className:"h-7 text-xs"}),o.jsxs(Na,{value:b,onChange:y=>x(y.target.value),className:"h-7 text-xs",children:[o.jsx("option",{value:"structure-compare",children:"Structure Compare"}),o.jsx("option",{value:"ligand-docking",children:"Ligand Design & Binding"}),o.jsx("option",{value:"peptide-crispr",children:"Peptide & CRISPR Test"}),o.jsx("option",{value:"blank",children:"Blank Workspace"})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx(Oe,{size:"sm",variant:"primary",className:"flex-1",onClick:_,children:"Create"}),o.jsx(Oe,{size:"sm",variant:"ghost",onClick:()=>d(!1),children:"Cancel"})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(RA,{role:"reference",label:e.refLabel,inspect:e.refInspect,chain:e.refChain,onChangeChain:e.onChangeRefChain,onReplace:()=>g("reference"),onSaveToLibrary:()=>e.onSaveToLibrary("reference"),hasContent:e.hasRef}),o.jsx(RA,{role:"mobile",label:e.mobLabel,inspect:e.mobInspect,chain:e.mobChain,onChangeChain:e.onChangeMobChain,onReplace:()=>g("mobile"),onSaveToLibrary:()=>e.onSaveToLibrary("mobile"),hasContent:e.hasMob}),(e.hasRef||e.hasMob)&&e.onSplitStructure&&o.jsxs("div",{className:"flex gap-1.5",children:[e.hasRef&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"flex-1 text-[0.6875rem]",icon:o.jsx(Px,{className:"h-3 w-3"}),onClick:()=>e.onSplitStructure?.("reference"),title:"Split Reference chains & non-water HETATM ligands into project assets",children:"Split Ref"}),e.hasMob&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"flex-1 text-[0.6875rem]",icon:o.jsx(Px,{className:"h-3 w-3"}),onClick:()=>e.onSplitStructure?.("mobile"),title:"Split Comparison chains & non-water HETATM ligands into project assets",children:"Split Comp"})]}),o.jsxs("div",{className:"flex items-center gap-2 px-1 pt-1 text-xs text-slate-500",children:[o.jsx("span",{className:Ie("h-1.5 w-1.5 rounded-full",e.paePresent?"bg-emerald-400":"bg-slate-600")}),e.paePresent?"PAE matrix loaded":"No PAE matrix"]}),e.chainError&&o.jsxs("div",{className:"flex gap-2 rounded-lg border border-amber-500/30 bg-amber-500/[0.06] p-2.5 text-xs leading-relaxed text-amber-200",children:[o.jsx(Gc,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.chainError]})]}),o.jsxs("div",{className:"mt-3 space-y-1.5",children:[o.jsx(Oe,{className:"w-full",variant:"primary",size:"sm",icon:o.jsx(Oc,{className:"h-3.5 w-3.5"}),onClick:()=>g("auto"),children:"Import structures / files"}),o.jsx(Oe,{className:"w-full",size:"sm",icon:o.jsx(Vi,{className:"h-3.5 w-3.5"}),onClick:e.onSearchDatabases,children:"Search public databases"}),o.jsxs("div",{className:"grid grid-cols-3 gap-1 pt-0.5",children:[e.onOpenChemistry&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"text-[0.6875rem]",icon:o.jsx(gh,{className:"h-3 w-3"}),onClick:e.onOpenChemistry,children:"Mol"}),e.onOpenPeptide&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"text-[0.6875rem]",icon:o.jsx(ar,{className:"h-3 w-3"}),onClick:e.onOpenPeptide,children:"Pep"}),e.onOpenCrispr&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"text-[0.6875rem]",icon:o.jsx(Fs,{className:"h-3 w-3"}),onClick:e.onOpenCrispr,children:"CRISPR"})]})]}),e.activeProject&&(e.activeProject.structures.length>0||e.activeProject.molecules.length>0||e.activeProject.peptides.length>0||e.activeProject.crisprs.length>0)&&o.jsxs("div",{className:"mt-4 space-y-2 border-t border-white/[0.06] pt-3",children:[o.jsxs("div",{className:"text-[0.6875rem] font-semibold tracking-wide text-slate-400 uppercase",children:["Project Assets (",e.activeProject.structures.length+e.activeProject.molecules.length+e.activeProject.peptides.length+e.activeProject.crisprs.length,")"]}),e.activeProject.structures.map(y=>o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-2 py-1.5 text-xs",children:[o.jsx(_s,{className:"h-3.5 w-3.5 shrink-0 text-sky-300"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-slate-200",title:y.label,children:y.label}),e.onLoadProjectStructure&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>e.onLoadProjectStructure?.(y,"reference"),className:"rounded px-1 py-0.5 text-[0.625rem] text-sky-300 hover:bg-sky-500/15",title:"Load as Reference",children:"Ref"}),o.jsx("button",{type:"button",onClick:()=>e.onLoadProjectStructure?.(y,"mobile"),className:"rounded px-1 py-0.5 text-[0.625rem] text-emerald-300 hover:bg-emerald-500/15",title:"Load as Comparison",children:"Comp"})]})]},y.id)),e.activeProject.molecules.map(y=>o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-2 py-1.5 text-xs",children:[o.jsx(ia,{className:"h-3.5 w-3.5 shrink-0 text-violet-300"}),o.jsx("button",{type:"button",onClick:()=>e.onOpenProjectMolecule?.(y),className:"min-w-0 flex-1 truncate text-left text-slate-200 hover:text-sky-300",title:y.smiles,children:y.name}),e.onDockMolecule&&o.jsxs("button",{type:"button",onClick:()=>e.onDockMolecule?.(y),className:"inline-flex items-center gap-0.5 rounded bg-emerald-500/10 px-1.5 py-0.5 text-[0.625rem] text-emerald-300 hover:bg-emerald-500/20",title:"Test binding / AutoDock Vina against active protein",children:[o.jsx(Br,{className:"h-2.5 w-2.5"}),"Bind"]}),e.onRemoveProjectAsset&&o.jsx("button",{type:"button",onClick:()=>e.onRemoveProjectAsset?.("molecule",y.id),className:"text-slate-500 hover:text-rose-400","aria-label":`Remove ${y.name}`,children:"×"})]},y.id)),e.activeProject.peptides.map(y=>o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-2 py-1.5 text-xs",children:[o.jsx(ar,{className:"h-3.5 w-3.5 shrink-0 text-amber-300"}),o.jsx("button",{type:"button",onClick:()=>e.onOpenPeptide?.(),className:"min-w-0 flex-1 truncate text-left text-slate-200 hover:text-sky-300",children:y.name})]},y.id)),e.activeProject.crisprs.map(y=>o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-2 py-1.5 text-xs",children:[o.jsx(Fs,{className:"h-3.5 w-3.5 shrink-0 text-emerald-300"}),o.jsx("button",{type:"button",onClick:()=>e.onOpenCrispr?.(),className:"min-w-0 flex-1 truncate text-left text-slate-200 hover:text-sky-300",children:y.name})]},y.id))]}),o.jsx("div",{className:Ie("mt-4 rounded-xl border border-dashed px-3 py-4 text-center text-xs leading-relaxed transition-colors",s?"border-sky-400/70 bg-sky-400/10 text-sky-200":"border-white/10 text-slate-500"),children:"Drop .cif / .pdb / PAE .json / .fasta / .smi / .synlexa.bundle.json here"}),o.jsx("button",{type:"button",onClick:e.onLoadExample,className:"mt-3 text-xs text-slate-500 hover:text-sky-300",children:"Load example comparison (CA II)"})]})}const BL=[{id:"viewer",group:"Structures & 3D",label:"3D Viewer",desc:"Superposed structures, residue picking, distances",icon:o.jsx(_s,{className:"h-4 w-4"})},{id:"results",group:"Structures & 3D",label:"Results",desc:"RMSD, coverage, confidence, PAE, exports",icon:o.jsx(qi,{className:"h-4 w-4"})},{id:"sequence",group:"Structures & 3D",label:"Sequence deviation",desc:"Per-residue Δd along the alignment",icon:o.jsx(Vo,{className:"h-4 w-4"})},{id:"ramachandran",group:"Structures & 3D",label:"Ramachandran",desc:"Backbone φ/ψ and Cα contacts",icon:o.jsx(Qo,{className:"h-4 w-4"})},{id:"chemistry",group:"Design & Editing",label:"Ligands & 2D Sketcher",desc:"RDKit WASM, PAINS alerts, 2D editor",icon:o.jsx(ia,{className:"h-4 w-4"})},{id:"peptide",group:"Design & Editing",label:"Peptide engineering",desc:"Point mutations, pI, charge, 3D contacts",icon:o.jsx(ar,{className:"h-4 w-4"})},{id:"crispr",group:"Design & Editing",label:"Gene & CRISPR",desc:"Codon edits and PAM sites",icon:o.jsx(Fs,{className:"h-4 w-4"})},{id:"workflow",group:"Pipelines & GPU",label:"Workflow Canvas",desc:"DAG pipelines + Nextflow/Snakemake",icon:o.jsx(Dp,{className:"h-4 w-4"})},{id:"compute",group:"Pipelines & GPU",label:"GPU & Compute Nodes",desc:"Colab, Vina, OpenMM, Boltz-2, PySCF",icon:o.jsx(al,{className:"h-4 w-4"})},{id:"plugins",group:"Pipelines & GPU",label:"Plugins & Add-ons",desc:"Open-source tools & license ledger",icon:o.jsx(Lp,{className:"h-4 w-4"})},{id:"assistant",group:"Agent & Workspace",label:"AI Assistant",desc:"Reasoning trace, octopus tools, search",icon:o.jsx(qr,{className:"h-4 w-4"})},{id:"mcp",group:"Agent & Workspace",label:"MCP Server",desc:"In-app MCP & Claude/Codex bridge",icon:o.jsx(rl,{className:"h-4 w-4"})},{id:"library",group:"Agent & Workspace",label:"Library manager",desc:"Organize saved molecules",icon:o.jsx(sh,{className:"h-4 w-4"})},{id:"home",group:"Agent & Workspace",label:"Start page",desc:"Projects, tutorial, quick actions",icon:o.jsx(FA,{className:"h-4 w-4"})}],GL=["Structures & 3D","Design & Editing","Pipelines & GPU","Agent & Workspace"];function HL({openTabs:e,onOpen:r}){return o.jsxs("div",{className:"h-full overflow-y-auto px-2 pb-4",children:[o.jsx("p",{className:"px-2 pb-2 text-xs text-slate-500",children:"Click to open a tab, or use the split icon to open beside 3D."}),o.jsx("div",{className:"space-y-3",children:GL.map(n=>o.jsxs("div",{children:[o.jsx("div",{className:"px-2.5 pb-1 text-[0.6875rem] font-semibold tracking-wider text-slate-500 uppercase",children:n}),o.jsx("ul",{className:"space-y-0.5",children:BL.filter(s=>s.group===n).map(s=>o.jsxs("li",{className:"group flex items-center gap-1 rounded-lg pr-1 hover:bg-white/[0.04]",children:[o.jsxs("button",{type:"button",onClick:i=>r(s.id,i.altKey),className:"flex min-w-0 flex-1 items-start gap-3 px-2.5 py-2 text-left",children:[o.jsx("span",{className:"mt-0.5 text-slate-500 group-hover:text-sky-300",children:s.icon}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsxs("span",{className:"flex items-center gap-2 text-[0.8125rem] text-slate-200",children:[s.label,e.has(s.id)&&o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-sky-400",title:"Open"})]}),o.jsx("span",{className:"block truncate text-xs text-slate-500",children:s.desc})]})]}),o.jsx("button",{type:"button",title:`Open ${s.label} side-by-side`,"aria-label":`Open ${s.label} side-by-side`,onClick:()=>r(s.id,!0),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-slate-500 opacity-0 transition group-hover:opacity-100 hover:bg-white/[0.08] hover:text-sky-300",children:o.jsx(Ey,{className:"h-3.5 w-3.5"})})]},s.id))})]},n))})]})}function FL({runs:e,onClear:r}){return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:e.length===0?o.jsx("p",{className:"px-2 py-6 text-center text-xs text-slate-500",children:"Comparisons you run appear here."}):o.jsx("ul",{className:"space-y-1",children:e.map(n=>o.jsxs("li",{className:"rounded-lg px-2.5 py-2 hover:bg-white/[0.03]",children:[o.jsxs("div",{className:"truncate text-[0.8125rem] text-slate-200",children:[n.refLabel," ",o.jsx("span",{className:"text-slate-600",children:"vs"})," ",n.mobLabel]}),o.jsxs("div",{className:"mt-0.5 flex justify-between text-xs text-slate-500 tabular-nums",children:[o.jsxs("span",{children:[n.rmsdAngstrom.toFixed(3)," Å · ",n.matchedCaCount," Cα · ",n.refChain,"/",n.mobChain]}),o.jsx("span",{children:new Date(n.createdAtUtc).toLocaleDateString()})]})]},n.id))})}),e.length>0&&o.jsx("div",{className:"border-t border-white/[0.06] p-2",children:o.jsx(Oe,{size:"sm",variant:"ghost",className:"w-full",icon:o.jsx(Wi,{className:"h-3.5 w-3.5"}),onClick:r,children:"Clear history"})})]})}function VL({busyLabel:e,wasmReady:r,rendererMode:n,rmsd:s,focusedSeqId:i,computeNodeLabel:c,computeOnline:d,onOpenComputeNodes:f,aiLabel:p,aiReady:b,onOpenAiSettings:x}){return o.jsxs("footer",{className:"flex h-7 shrink-0 items-center gap-4 border-t border-white/[0.06] bg-[#0a0d13] px-3 text-[0.6875rem] text-slate-500",children:[o.jsx("span",{className:"flex items-center gap-1.5",children:e?o.jsxs(o.Fragment,{children:[o.jsx(qs,{className:"h-3 w-3 animate-spin text-sky-400"}),o.jsx("span",{className:"text-slate-300",children:e})]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:Ie("h-1.5 w-1.5 rounded-full",r?"bg-emerald-400":"bg-amber-400")}),r?"Engine ready":"Starting engine…"]})}),o.jsxs("span",{className:"hidden items-center gap-1 sm:flex",children:[o.jsx(al,{className:"h-3 w-3"})," ",n==="webgl2"?"WebGL2":"Canvas fallback"]}),f&&o.jsxs("button",{type:"button",onClick:f,className:"hidden items-center gap-1.5 hover:text-slate-300 md:flex",children:[o.jsx("span",{className:Ie("h-1.5 w-1.5 rounded-full",d?"bg-emerald-400":"bg-slate-600")}),c?`GPU: ${c}`:"Connect Colab / GPU"]}),s!==null&&o.jsxs("span",{className:"tabular-nums",children:["RMSD ",s.toFixed(3)," Å"]}),i!==null&&o.jsxs("span",{className:"tabular-nums",children:["Residue ",i]}),o.jsx("div",{className:"flex-1"}),o.jsxs("button",{type:"button",onClick:x,className:"flex items-center gap-1.5 hover:text-slate-300",children:[o.jsx(qr,{className:Ie("h-3 w-3",b?"text-sky-400":"text-slate-600")}),p]}),o.jsx("span",{className:"font-medium text-amber-400/80",children:"Research use only"})]})}const KL=C.lazy(()=>Aa(()=>import("./MolStarViewport-BEGb0UZJ.js"),__vite__mapDeps([0,1])).then(e=>({default:e.MolStarViewport}))),zA="MSHHWGYGKHNGPEHWHKDFPIAKGERQSPVDIDTHTAKYDPSLKPLSVSYDQATSLRILNNGHAFNVEFDDSQDKAVLKGGPLDGTYRLIQFHFHWGSLDGQGSEHTVDKKKYAAELHLVHWNTKYGDFGKAVQQPDGLAVLGIFLKVGSAKPGLQKVVDVLDSIKTKGKSADFTNFDPRGLLPESLDYWTYPGSLTTPPLLECVTWIVLKEPISVSSEQVLKFRKLNFNGEGEPEELMVDNWRPAQPLKNRQIKASFK",YL=new Set(["viewer"]);function Rx(e,r,n){const s=new Blob([r],{type:n}),i=URL.createObjectURL(s),c=document.createElement("a");c.href=i,c.download=e,c.click(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}function Zf(e){return e?{sourceTypeHint:e.confidenceKind==="experimental_b_factor"?"experimental":e.confidenceKind==="prediction_plddt"?"prediction":"auto",sourceUrl:e.sourceUrl,dataRevision:e.dataRevision,retrievedAtUtc:e.retrievedAtUtc,license:e.license}:{sourceTypeHint:"auto"}}function OA(e){if(!e)return null;try{const r=new URL(e).host;return r.includes("rcsb")?"RCSB PDB":r.includes("alphafold")?"AlphaFold DB":r.includes("uniprot")?"UniProtKB":r.includes("pubchem")||r.includes("ncbi")?"PubChem":r}catch{return null}}function ep(e){return e.replace(/\.(cif|mmcif|pdb|ent)$/i,"")}function WL(){const{toast:e}=cl(),[r,n]=Zv(),s=C.useRef(null);s.current||(s.current=new $y);const i=C.useRef(null),c=C.useRef(null),[d,f]=C.useState(!1),[p,b]=C.useState(null),[x,g]=C.useState(null),[_,y]=C.useState(null),[S,k]=C.useState("webgl2"),[E,T]=C.useReducer(_y,r.restoreTabs,cq),[j,q]=C.useState("explorer"),[z,O]=C.useState(!0),[V,P]=C.useState("account"),[$,H]=C.useState(!1),[Z,G]=C.useState(!1),[K,we]=C.useState(!1),[Se,Q]=C.useState(!1),F=C.useRef(null),[he,W]=C.useState(()=>rA()),[me,I]=C.useState(null),[J,ge]=C.useState([]),[le,D]=C.useState("webgl2"),[ae,pe]=C.useState(null),[Ae,Ne]=C.useState(null),[Re,$e]=C.useState(()=>Di()),[Ce,Ue]=C.useState(r.viewer.defaultLayout),[be,bt]=C.useState(r.viewer.defaultStyle),[Ot,St]=C.useState(r.viewer.defaultColorMode),[Ke,et]=C.useState(""),[ue,He]=C.useState(""),[Pe,ut]=C.useState({sourceTypeHint:"auto"}),[Je,re]=C.useState(null),[ve,Qe]=C.useState(""),[Fe,Fn]=C.useState(""),[We,Yr]=C.useState(""),[ss,su]=C.useState({sourceTypeHint:"auto"}),[qn,Wr]=C.useState(null),[_t,ja]=C.useState(""),[Nn,Ji]=C.useState(null),[tt,Mh]=C.useState(null),[Ln,dl]=C.useState(null),[Zi,Rh]=C.useState(null),[oa,hl]=C.useState(null),[zh,eo]=C.useState(null),[st,Lt]=C.useReducer(rq,{sequence:zA,mutationsInput:"H94A",mutations:["H94A"],sliceStart:1,sliceEnd:zA.length,focusSeqId:94}),[Ct,Oh]=C.useState(null),[i0,Ph]=C.useState(null),[Nt,An]=C.useReducer(iq,{transcriptId:"NM_000067.3",customDna:"",useCustomDna:!1,targetCodonIndex:94,baseEditOffset:0,newBase:"G",nuclease:"SpCas9"}),[as,Ta]=C.useState(null),[ml,Xr]=C.useState(null),[Mt,Un]=C.useReducer(oq,{selectedPresetId:Xo[0].id,name:Xo[0].name,smiles:Xo[0].smiles}),[Vs,to]=C.useState(null),[no,$h]=C.useState(null),[so,au]=C.useState("reference"),[Qr,fl]=C.useState(null),[ru,iu]=C.useState(null),[ou,rs]=C.useState([]),[Ut,on]=C.useState(()=>Ac()),[la,lu]=C.useState(!1),[cu,uu]=C.useState([]),[Ih,or]=C.useState([]),[pl,Jr]=C.useState(null),[Ea,Zr]=C.useState(()=>t0()),Ma=C.useRef(null),ei=C.useRef(new Set),[At,Dh]=C.useState(()=>dp()),[qh,lr]=C.useState(!1);C.useEffect(()=>(Jv(r.uiScale),dq(Cx)),[]),C.useEffect(()=>{r.restoreTabs&&uq(E)},[E,r.restoreTabs]),C.useEffect(()=>{const M=()=>nu().then(ge);return M(),r0(()=>void M())},[]),C.useEffect(()=>{x&&(e(x,"error"),g(null))},[x,e]);const je=C.useCallback((M,R=!1)=>{T({type:"open",tab:M,toSide:R})},[]),Jt=C.useCallback(M=>{M&&P(M),we(!0)},[]),Lh=C.useCallback(M=>new Promise(R=>{je("assistant"),Jr(M),Ma.current=R}),[je]),Uh=C.useCallback(M=>{const R=Ma.current;Ma.current=null,Jr(null),R?.(M)},[]),ti=C.useCallback(M=>{const R=SD(M);return M.template==="ligand-docking"?je("chemistry"):M.template==="peptide-crispr"?je("peptide"):M.template==="structure-compare"&&je("viewer"),e(`Created project "${R.name}"`,"success"),R},[je,e]),o0=C.useCallback(M=>{Un({type:"set_custom_smiles",smiles:M.smiles,name:M.name}),Ne({tool:"vina",nonce:Date.now()}),je("compute"),e(`Staged ${M.name} for receptor binding / Vina`,"info")},[je,e]),ct=C.useMemo(()=>{if(oa&&oa.seqIds.length>0)return new Set(oa.seqIds);const M=new Set;if(Ct?.local3dContacts)for(const R of Ct.local3dContacts)M.add(R.seqId);return M},[oa,Ct]),ao=C.useMemo(()=>oa&&oa.seqIds.length>0?oa.source:Ct?.local3dContacts&&Ct.local3dContacts.length>0?"Peptide <5 Å shell":null,[oa,Ct]),ca=C.useCallback(async(M,R={})=>{try{const{item:X,duplicate:oe}=await t1(M);return R.silent||e(oe?`${X.name} is already in your library`:`Saved ${X.name} to library`,oe?"info":"success"),X}catch(X){return e(`Could not save to library: ${X instanceof Error?X.message:String(X)}`,"error"),null}},[e]),ws=C.useCallback(M=>{r.autoSaveImports&&ca(M,{silent:!0})},[ca,r.autoSaveImports]),Pt=C.useCallback(async M=>{if(!M.rContent||!M.mContent)return null;if(!M.rChain||!M.mChain)return y("Select a chain for both the reference and the comparison structure."),null;b("Superposing structures…"),y(null);try{const R=await s.current.compareStructures({refLabel:M.rLabel,refContent:M.rContent,refChain:M.rChain,refMeta:M.rMeta,mobLabel:M.mLabel,mobContent:M.mContent,mobChain:M.mChain,mobMeta:M.mMeta,paeJson:M.pae??void 0});Mh(R),f(!0);const X=await nq({id:`${R.reference.sha256.slice(0,8)}-${R.mobile.sha256.slice(0,8)}-${R.reference.chainId}-${R.mobile.chainId}`,createdAtUtc:R.createdAtUtc,refLabel:R.reference.label,refChain:R.reference.chainId,refSha256:R.reference.sha256,mobLabel:R.mobile.label,mobChain:R.mobile.chainId,mobSha256:R.mobile.sha256,rmsdAngstrom:R.metrics.rmsdAngstrom,matchedCaCount:R.metrics.matchedCaCount,paeStatus:R.metrics.paeStatus});return rs(X),R}catch(R){return R instanceof Tr||(R instanceof XA&&R.code==="ERR_AMBIGUOUS_CHAIN"?y(R.message):g(R instanceof Error?R.message:String(R))),null}finally{b(null)}},[]),fn=()=>({rLabel:Ke,rContent:ue,rChain:ve,rMeta:Pe,mLabel:Fe,mContent:We,mChain:_t,mMeta:ss,pae:Nn}),ua=C.useCallback(async M=>{y(null),I(null),b(`Reading ${M.label}…`);try{const R=await s.current.inspectStructure(M.role==="reference"?"inspect-ref":"inspect-mob",{label:M.label,content:M.content,...M.meta});f(!0);const X=R.chains.length===1?R.chains[0].chainId:"";if(!X&&R.chains.length>1&&(q("explorer"),O(!0),y(`${M.label} has ${R.chains.length} chains (${R.chains.map(oe=>oe.chainId).join(", ")}). Pick one in the Workspace panel.`)),M.role==="reference")et(M.label),He(M.content),ut(M.meta),re(R),Qe(X),wx({label:M.label,role:"reference",content:M.content,paeJson:M.pae,sourceUrl:M.meta.sourceUrl??null,license:M.meta.license??null}),X&&We&&_t&&await Pt({rLabel:M.label,rContent:M.content,rChain:X,rMeta:M.meta,mLabel:Fe,mContent:We,mChain:_t,mMeta:ss,pae:Nn});else{const oe=M.pae!==void 0?M.pae:Nn;Fn(M.label),Yr(M.content),su(M.meta),Wr(R),ja(X),Ji(oe),wx({label:M.label,role:"mobile",content:M.content,paeJson:oe,sourceUrl:M.meta.sourceUrl??null,license:M.meta.license??null});const fe=(R.chains.find(ke=>ke.chainId===X)??R.chains[0])?.sequence1Letter;fe&&(Lt({type:"set_sequence",sequence:fe}),Lt({type:"set_mutations_input",raw:""})),X&&ue&&ve&&await Pt({rLabel:Ke,rContent:ue,rChain:ve,rMeta:Pe,mLabel:M.label,mContent:M.content,mChain:X,mMeta:M.meta,pae:oe})}return T({type:"activate",tab:"viewer"}),R}catch(R){return R instanceof Tr||g(R instanceof Error?R.message:String(R)),null}finally{b(null)}},[We,_t,Fe,ss,ue,ve,Ke,Pe,Nn,Pt]),gl=C.useCallback(M=>{const R=M==="reference"?ue:We,X=M==="reference"?Ke:Fe;if(!R)return e(`No ${M} structure loaded to split`,"error"),[];const oe=ND(R,X||M);for(const fe of oe)wx({label:fe.label,role:"extra",content:fe.pdbContent});return q("explorer"),O(!0),e(`Split ${X||M} into ${oe.length} chain/ligand part(s)`,"success"),oe},[ue,Ke,We,Fe,e]),du=C.useCallback((M,R)=>{ua({role:R,label:M.label,content:M.content,meta:{sourceTypeHint:"auto",sourceUrl:M.sourceUrl??void 0,license:M.license??void 0},pae:M.paeJson??void 0})},[ua]),bl=C.useRef(null),cr=C.useCallback(async()=>{b("Loading example…"),y(null),I("ca2-azm");try{const M=await uz(),R=Zf(M.manifest.fixtures.find(Be=>Be.fileName==="3HS4.cif")),X=Zf(M.manifest.fixtures.find(Be=>Be.fileName==="AF-P00918-F1-model_v6.cif"));et("3HS4.cif"),He(M.refCif),ut(R),Fn("AF-P00918-F1-model_v6.cif"),Yr(M.mobCif),su(X),Ji(M.paeJson);const[oe,fe]=await Promise.all([s.current.inspectStructure("inspect-ref",{label:"3HS4.cif",content:M.refCif,...R}),s.current.inspectStructure("inspect-mob",{label:"AF-P00918-F1-model_v6.cif",content:M.mobCif,...X})]);f(!0),re(oe),Wr(fe);const ke=oe.chains.length===1?oe.chains[0].chainId:"",Le=fe.chains.length===1?fe.chains[0].chainId:"";Qe(ke),ja(Le),dl(94),fe.chains[0]?.sequence1Letter&&(Lt({type:"set_sequence",sequence:fe.chains[0].sequence1Letter}),Lt({type:"add_mutation",notation:"H94A"})),ke&&Le&&await Pt({rLabel:"3HS4.cif",rContent:M.refCif,rChain:ke,rMeta:R,mLabel:"AF-P00918-F1-model_v6.cif",mContent:M.mobCif,mChain:Le,mMeta:X,pae:M.paeJson})}catch(M){if(M instanceof Tr)return;g(M instanceof Error?M.message:String(M))}finally{b(null)}},[Pt]);C.useEffect(()=>{fI().then(()=>on(Ac())),iD(),bD(),wD();const M=vD(()=>Dh(dp())),R=L3(()=>$e(Di()));return cE().then(rs).catch(()=>{}),r.loadDemoOnStart&&cr(),()=>{M(),R(),s.current?.dispose()}},[]),C.useEffect(()=>{const M=()=>{cy();try{F.current?.close()}catch{}F.current=null},R=(Le,Be)=>{Be||M(),qI(Le).then(ft=>{W(ft),on(Ac()),Be&&window.history.replaceState({},"",`${window.location.pathname}${window.location.hash}`||"/");const vt=ft.displayName??ft.email;e(ft.serverVerified?`Signed in${vt?` as ${vt}`:""}`:"Signed in, but synlexa.com could not confirm the session. Synlexa Cloud stays off until you reconnect.",ft.serverVerified?"success":"warn")}).catch(ft=>e(ft instanceof Error?ft.message:String(ft),"error")).finally(()=>{Q(!1),M()})},X=j3(window.location.href);X&&R(X,!0);const oe=WI(Le=>R(Le,!1)),fe=HI(Le=>R(Le,!1)),ke=Le=>{Le.key===n0&&(W(rA()),on(Ac()),Q(!1))};return window.addEventListener("storage",ke),()=>{oe(),fe(),window.removeEventListener("storage",ke)}},[e]),C.useEffect(()=>{if(!Se||!F.current)return;const M=window.setInterval(()=>{const R=F.current;R&&R.closed&&(window.clearInterval(M),window.setTimeout(()=>{F.current===R&&(F.current=null,Q(!1))},1500))},500);return()=>window.clearInterval(M)},[Se]);const Bn=C.useCallback(M=>{const R=VI(),X=R?null:KI("about:blank");PI(M,{platform:R?"desktop":"web"}).then(async({url:oe})=>{if(R){if(!await FI(oe))throw new Error("Could not open your browser.");Q(!0);return}X&&!X.closed?(X.location.href=oe,X.focus(),F.current=X,Q(!0)):window.location.assign(oe)}).catch(oe=>{X?.close(),e(oe instanceof Error?oe.message:String(oe),"error")})},[e]),hu=C.useCallback(()=>{cy();try{F.current?.close()}catch{}F.current=null,up(),Q(!1)},[]);C.useEffect(()=>{if(!st.sequence)return;let M=!0;return Ph(null),s.current?.analyzePeptide({sequence:st.sequence,mutations:st.mutations,sliceStart:st.sliceStart,sliceEnd:st.sliceEnd,structureContent:ue||void 0,chainId:ve||void 0,focusSeqId:st.focusSeqId??void 0}).then(R=>{M&&(f(!0),Oh(R))}).catch(R=>{R instanceof Tr||!M||Ph(R instanceof Error?R.message:String(R))}),()=>{M=!1}},[st.sequence,st.mutations,st.sliceStart,st.sliceEnd,st.focusSeqId,ue,ve]),C.useEffect(()=>{let M=!0;return Xr(null),s.current?.analyzeGeneCrispr({transcriptId:Nt.useCustomDna?void 0:Nt.transcriptId,codingDna:Nt.useCustomDna?Nt.customDna:void 0,targetCodonIndex:Nt.targetCodonIndex,baseEditIndex:(Nt.targetCodonIndex-1)*3+Nt.baseEditOffset+1,newBase:Nt.newBase,nuclease:Nt.nuclease}).then(R=>{M&&(f(!0),Ta(R))}).catch(R=>{R instanceof Tr||!M||Xr(R instanceof Error?R.message:String(R))}),()=>{M=!1}},[Nt]),C.useEffect(()=>{if(!Mt.smiles)return;let M=!0;return $h(null),s.current?.analyzeMoleculeSmiles({name:Mt.name,smiles:Mt.smiles}).then(R=>{M&&(f(!0),to(R))}).catch(R=>{R instanceof Tr||!M||$h(R instanceof Error?R.message:String(R))}),()=>{M=!1}},[Mt]),C.useEffect(()=>{const M=so==="reference"?ue:We,R=so==="reference"?ve:_t;if(!M)return;let X=!0;return iu(null),s.current?.analyzeRamachandran({content:M,chainId:R||void 0}).then(oe=>{X&&(f(!0),fl(oe))}).catch(oe=>{oe instanceof Tr||!X||iu(oe instanceof Error?oe.message:String(oe))}),()=>{X=!1}},[so,ue,ve,We,_t]);const Yt=C.useCallback(M=>{dl(M),Lt({type:"focus_residue",seqId:M}),An({type:"set_target_codon",codonIndex:M})},[]),mu=C.useCallback(async M=>{if(I(M.id),y(null),M.kind==="chemistry-panel"){M.smilesPresetId&&Un({type:"select_preset",presetId:M.smilesPresetId}),je("chemistry");return}if(!(!M.reference||!M.mobile)){b(`Loading ${M.title}…`);try{const[R,X,oe,fe]=await Promise.all([cz(),Rb(M.reference.fileName),Rb(M.mobile.fileName),M.paeFileName?Rb(M.paeFileName).catch(()=>null):Promise.resolve(null)]),ke=Zf(R.fixtures.find(Zt=>Zt.fileName===M.reference.fileName)),Le=Zf(R.fixtures.find(Zt=>Zt.fileName===M.mobile.fileName));et(M.reference.label),He(X),ut(ke),Fn(M.mobile.label),Yr(oe),su(Le),Ji(fe);const[Be,ft]=await Promise.all([s.current.inspectStructure("inspect-ref",{label:M.reference.label,content:X,...ke}),s.current.inspectStructure("inspect-mob",{label:M.mobile.label,content:oe,...Le})]);f(!0),re(Be),Wr(ft),Qe(M.reference.chainId),ja(M.mobile.chainId);const vt=ft.chains.find(Zt=>Zt.chainId===M.mobile.chainId)??ft.chains[0];vt?.sequence1Letter&&(Lt({type:"set_sequence",sequence:vt.sequence1Letter}),Lt({type:"set_mutations_input",raw:(M.peptideMutations??[]).join(", ")})),M.crispr&&(An({type:"select_transcript",transcriptId:M.crispr.transcriptId}),An({type:"set_target_codon",codonIndex:M.crispr.targetCodonIndex}),An({type:"set_base_edit",offset:M.crispr.baseEditOffset,newBase:M.crispr.newBase}),An({type:"set_nuclease",nuclease:M.crispr.nuclease})),M.smilesPresetId&&Un({type:"select_preset",presetId:M.smilesPresetId}),M.focusSeqId&&(dl(M.focusSeqId),Lt({type:"focus_residue",seqId:M.focusSeqId})),await Pt({rLabel:M.reference.label,rContent:X,rChain:M.reference.chainId,rMeta:ke,mLabel:M.mobile.label,mContent:oe,mChain:M.mobile.chainId,mMeta:Le,pae:fe}),T({type:"activate",tab:"viewer"}),M.openTab&&M.openTab!=="sequence"&&je(M.openTab)}catch(R){R instanceof Tr||g(R instanceof Error?R.message:String(R))}finally{b(null)}}},[Pt,je]),Ra=C.useCallback(async(M,R)=>{const X={sourceTypeHint:M.sourceTypeHint,sourceUrl:M.sourceUrl,dataRevision:M.dataRevision??void 0,retrievedAtUtc:M.retrievedAtUtc,license:M.license};await ua({role:R,label:M.label,content:M.content,meta:X,pae:R==="mobile"?M.paeJson??null:void 0}),ws({kind:"structure",format:/\.pdb$/i.test(M.label)?"pdb":"cif",name:ep(M.label),content:M.content,paeJson:M.paeJson,source:{database:OA(M.sourceUrl),accession:M.uniprotAccession??ep(M.label),sourceUrl:M.sourceUrl,license:M.license,retrievedAtUtc:M.retrievedAtUtc,origin:M.origin,sourceTypeHint:M.sourceTypeHint,dataRevision:M.dataRevision}})},[ua,ws]),xl=C.useCallback(M=>{Un({type:"set_custom_smiles",smiles:M.smiles,name:M.name}),je("chemistry"),ws({kind:"compound",format:"smiles",name:M.name,content:M.smiles,source:{database:"PubChem",accession:M.cid!==null?`CID ${M.cid}`:null,sourceUrl:M.sourceUrl,license:M.license,retrievedAtUtc:M.retrievedAtUtc,origin:M.origin}})},[je,ws]),fu=C.useCallback(async(M,R="auto")=>{I(null);const X=()=>({database:null,accession:null,sourceUrl:null,license:null,retrievedAtUtc:null,origin:"local-file"});let oe=!!ue,fe=!!We;for(const ke of Array.from(M)){const Le=ke.name.toLowerCase(),Be=await ke.text();if(Le.endsWith(".synlexa.bundle.json")){try{const vt=await ZD(Be),Zt=vt.files.find($a=>$a.role==="reference"),ks=vt.files.find($a=>$a.role==="mobile"),ri=vt.files.find($a=>$a.role==="pae");if(Zt&&ks){et(Zt.label),He(Zt.content),Fn(ks.label),Yr(ks.content),Ji(ri?.content??null);const[$a,u0]=await Promise.all([s.current.inspectStructure("inspect-ref",{label:Zt.label,content:Zt.content}),s.current.inspectStructure("inspect-mob",{label:ks.label,content:ks.content})]);re($a),Wr(u0),Qe(vt.state.refChain),ja(vt.state.mobChain),vt.comparisonResult&&Mh(vt.comparisonResult),e(`Opened project ${ke.name}`,"success")}}catch(vt){g(vt instanceof Error?vt.message:String(vt))}continue}if(/\.(fasta|fa|faa)$/.test(Le)){const vt=Be.split(/\r?\n/).filter(Zt=>!Zt.startsWith(">")).join("").trim().toUpperCase();/^[ACGTU\s]+$/i.test(vt)&&vt.length>=9?(An({type:"set_custom_dna",dna:vt.replace(/U/g,"T")}),je("crispr")):(Lt({type:"set_sequence",sequence:vt}),je("peptide")),ws({kind:"sequence",format:"fasta",name:ke.name.replace(/\.[^.]+$/,""),content:vt,source:X()});continue}if(Le.endsWith(".smi")){const vt=Be.split(/\r?\n/).find(ri=>ri.trim().length>0)??"",[Zt,...ks]=vt.trim().split(/\s+/);if(Zt){const ri=ks.join(" ")||ke.name.replace(/\.[^.]+$/,"");Un({type:"set_custom_smiles",smiles:Zt,name:ri}),je("chemistry"),ws({kind:"compound",format:"smiles",name:ri,content:Zt,source:X()})}continue}if(Le.endsWith(".json")){Ji(Be),e("PAE matrix loaded","success"),ue&&We&&ve&&_t&&await Pt({...fn(),pae:Be});continue}if(!/\.(cif|mmcif|pdb|ent)$/.test(Le)){e(`${ke.name}: unsupported file type`,"warn");continue}const ft=R!=="auto"?R:oe&&(Le.includes("af-")||Le.includes("model")||!fe)?"mobile":"reference";ft==="reference"?oe=!0:fe=!0,await ua({role:ft,label:ke.name,content:Be,meta:{sourceTypeHint:"auto"}}),ws({kind:"structure",format:/\.(pdb|ent)$/.test(Le)?"pdb":"cif",name:ep(ke.name),content:Be,source:X()})}},[Ke,ue,ve,Pe,Fe,We,_t,ss,Nn,Pt,ua,je,ws,e]),za=C.useCallback(async(M,R)=>{if(n1(M.id,{lastOpenedAtUtc:new Date().toISOString()}),M.kind==="compound"){Un({type:"set_custom_smiles",smiles:M.content,name:M.name}),je("chemistry");return}if(M.kind==="sequence"){/^[ACGT]+$/.test(M.content)&&M.content.length>=9?(An({type:"set_custom_dna",dna:M.content}),je("crispr")):(Lt({type:"set_sequence",sequence:M.content}),je("peptide"));return}const X=R!=="auto"?R:ue&&(M.source.sourceTypeHint==="prediction"||!We)?"mobile":"reference";await ua({role:X,label:`${M.name}.${M.format==="pdb"?"pdb":"cif"}`,content:M.content,meta:{sourceTypeHint:M.source.sourceTypeHint??"auto",sourceUrl:M.source.sourceUrl??void 0,license:M.source.license??void 0,retrievedAtUtc:M.source.retrievedAtUtc??void 0,dataRevision:M.source.dataRevision??void 0},pae:X==="mobile"?M.paeJson??null:void 0}),e(`${M.name} loaded as ${X==="reference"?"reference":"comparison"}`,"success")},[ue,We,ua,je,e]),l0=C.useCallback(M=>{const R=M==="reference"?Ke:Fe,X=M==="reference"?ue:We,oe=M==="reference"?Pe:ss;X&&ca({kind:"structure",format:/\.(pdb|ent)$/i.test(R)?"pdb":"cif",name:ep(R),content:X,paeJson:M==="mobile"?Nn:null,source:{database:OA(oe.sourceUrl),accession:null,sourceUrl:oe.sourceUrl??null,license:oe.license??null,retrievedAtUtc:oe.retrievedAtUtc??null,origin:oe.sourceUrl?"pinned-local-cache":"local-file",sourceTypeHint:oe.sourceTypeHint,dataRevision:oe.dataRevision??null}})},[Ke,Fe,ue,We,Pe,ss,Nn,ca]),ni=r.viewer.embedPngInReports,da=C.useCallback(()=>{if(!tt){e("Run a comparison first","warn");return}const M=lI({comparison:tt,peptide:Ct,crispr:as,smiles:Vs,viewportPngDataUrl:ni?i.current?.capturePngDataUrl()??null:null});Rx(`synlexa-ruo-report-${tt.resultId.slice(0,12)}.html`,M,"text/html;charset=utf-8")},[tt,Ct,as,Vs,ni,e]),is=C.useCallback(()=>{if(!tt){e("Run a comparison first","warn");return}const M=oI({comparison:tt,peptide:Ct,crispr:as,smiles:Vs,viewportPngDataUrl:ni?i.current?.capturePngDataUrl()??null:null});Rx(`synlexa-ruo-manifest-${tt.resultId.slice(0,12)}.json`,M,"application/json;charset=utf-8")},[tt,Ct,as,Vs,ni,e]),si=C.useCallback(async()=>{if(!ue||!We){e("Load a reference and a comparison structure first","warn");return}const M=await JD({refLabel:Ke,refContent:ue,mobLabel:Fe,mobContent:We,paeJson:Nn,comparisonResult:tt,state:{refChain:ve,mobChain:_t,focusedSeqId:Ln,peptide:{sequence:st.sequence,mutations:st.mutations,sliceStart:st.sliceStart,sliceEnd:st.sliceEnd},crispr:{transcriptId:Nt.transcriptId,customDna:Nt.customDna,targetCodonIndex:Nt.targetCodonIndex,baseEditIndex:Nt.baseEditOffset,newBase:Nt.newBase,nuclease:Nt.nuclease},smiles:{name:Mt.name,smiles:Mt.smiles}}});Rx(`synlexa-project-${Date.now()}.synlexa.bundle.json`,JSON.stringify(M,null,2),"application/json;charset=utf-8")},[Ke,ue,Fe,We,Nn,tt,ve,_t,Ln,st,Nt,Mt,e]),Bh=C.useCallback(M=>{M.type==="focus_residues"&&M.seqIds.length>0?Yt(M.seqIds[0]):M.type==="compare_structures"?Pt(fn()):M.type==="request_report"?M.format==="json"?is():da():M.type==="switch_tab"?je(M.tab):M.type==="apply_peptide_mutation"?Lt({type:"add_mutation",notation:M.notation}):M.type==="analyze_smiles"?Un({type:"set_custom_smiles",smiles:M.smiles,name:M.name}):M.type==="focus_crispr_codon"&&Yt(M.codonIndex)},[Yt,Pt,Ke,ue,ve,Pe,Fe,We,_t,ss,Nn,is,da,je]),ro=C.useCallback(async(M,R)=>{switch(M){case"fetch_from_database":{const X=String(R.source||"rcsb"),oe=String(R.query||""),fe=await Iy(X,oe);if(fe.records.length===0)return{ok:!1,summary:`No matches in ${X} for "${oe}"`,data:{origin:fe.origin,records:[]}};const ke=fe.records[0];if(R.autoImport!==!1){if(ke.source==="pubchem"){const ft=dj(ke);return xl(ft),{ok:!0,summary:`Imported ${ft.name} (${ft.origin})`,data:ft}}const Le=R.role==="reference"?"reference":R.role==="mobile"?"mobile":ke.source==="rcsb"?"reference":"mobile",Be=await uj(ke);return await Ra(Be,Le),{ok:!0,summary:`Imported ${Be.label} as ${Le}`,data:{label:Be.label,role:Le,sha256:Be.sha256,origin:Be.origin,sourceUrl:Be.sourceUrl,license:Be.license}}}return{ok:!0,summary:`Found ${fe.records.length} record(s) in ${X}`,data:{origin:fe.origin,records:fe.records.slice(0,5)}}}case"run_structure_superposition":{const X=typeof R.refChain=="string"&&R.refChain?R.refChain:ve,oe=typeof R.mobChain=="string"&&R.mobChain?R.mobChain:_t;X!==ve&&Qe(X),oe!==_t&&ja(oe);const fe=await Pt({...fn(),rChain:X,mChain:oe});return fe?(je("results"),{ok:!0,summary:`RMSD ${fe.metrics.rmsdAngstrom.toFixed(4)} Å (${fe.metrics.matchedCaCount} Cα)`,data:{resultId:fe.resultId,metrics:fe.metrics,refSha256:fe.reference.sha256,mobSha256:fe.mobile.sha256}}):{ok:!1,summary:"Superposition did not complete (check chains)",data:null}}case"focus_3d_residues":{const X=(Array.isArray(R.seqIds)?R.seqIds:[]).map(Number).filter(fe=>Number.isFinite(fe)&&fe>0);if(X.length===0)return{ok:!1,summary:"No positive residue IDs supplied",data:null};Yt(X[0]);const oe=X.map(fe=>tt?.matchedResidues.find(ke=>ke.refSeqId===fe)??{refSeqId:fe,note:"not in matched Cα set"});return{ok:!0,summary:`Focused residue(s) ${X.join(", ")}`,data:{seqIds:X,matched:oe}}}case"engineer_peptide_mutation":{const X=Array.isArray(R.mutations)?R.mutations.map(ke=>String(ke).trim().toUpperCase()).filter(Boolean):[],oe=typeof R.focusSeqId=="number"&&Number.isFinite(R.focusSeqId)?R.focusSeqId:st.focusSeqId??void 0;je("peptide");for(const ke of X)Lt({type:"add_mutation",notation:ke});oe&&Yt(oe);const fe=await s.current.analyzePeptide({sequence:st.sequence,mutations:Array.from(new Set([...st.mutations,...X])),sliceStart:st.sliceStart,sliceEnd:st.sliceEnd,structureContent:ue||void 0,chainId:ve||void 0,focusSeqId:oe});return Oh(fe),lA({name:X.join(", ")||`Peptide (${fe.engineered.length} aa)`,sequence:st.sequence,mutations:Array.from(new Set([...st.mutations,...X]))}),{ok:!0,summary:`Applied ${X.join(", ")||"peptide analysis"} (ΔMW ${fe.deltas.mwAverageDa.toFixed(1)} Da, pI ${fe.engineered.pi.toFixed(2)})`,data:fe}}case"design_crispr_edit":{const X=typeof R.transcriptId=="string"&&R.transcriptId?R.transcriptId:Nt.transcriptId,oe=Math.max(1,Number(R.targetCodonIndex)||Nt.targetCodonIndex),fe=[0,1,2].includes(Number(R.baseEditOffset))?Number(R.baseEditOffset):Nt.baseEditOffset,ke=["A","C","G","T"].includes(String(R.newBase).toUpperCase())?String(R.newBase).toUpperCase():Nt.newBase,Le=["SpCas9","SaCas9","Cas12a"].includes(String(R.nuclease))?String(R.nuclease):Nt.nuclease;je("crispr"),An({type:"select_transcript",transcriptId:X}),An({type:"set_target_codon",codonIndex:oe}),An({type:"set_base_edit",offset:fe,newBase:ke}),An({type:"set_nuclease",nuclease:Le});const Be=await s.current.analyzeGeneCrispr({transcriptId:X,targetCodonIndex:oe,baseEditIndex:(oe-1)*3+fe+1,newBase:ke,nuclease:Le});return Ta(Be),cA({name:`${Be.geneSymbol} codon ${oe} (${Be.targetCodon.wtCodon}→${Be.targetCodon.editedCodon})`,transcriptId:X,targetCodonIndex:oe,baseEditOffset:fe,newBase:ke,nuclease:Le}),{ok:!0,summary:`${Be.geneSymbol} codon ${oe}: ${Be.targetCodon.wtCodon}→${Be.targetCodon.editedCodon} (${Be.targetCodon.consequence}), ${Be.pamSites.length} PAMs`,data:{...Be,pamSites:Be.pamSites.slice(0,8)}}}case"inspect_chemical_smiles":{const X=String(R.smiles||"").trim(),oe=typeof R.name=="string"&&R.name.trim()?R.name.trim():"Assistant SMILES";je("chemistry"),Un({type:"set_custom_smiles",smiles:X,name:oe});const fe=await s.current.analyzeMoleculeSmiles({name:oe,smiles:X});return to(fe),{ok:!0,summary:`${fe.formula}, MW ${fe.molecularWeight.toFixed(2)} Da, TPSA ${fe.tpsa.toFixed(1)} Ų`,data:fe}}case"analyze_ramachandran":{const X=R.target==="mobile"?"mobile":"reference",oe=X==="reference"?ue:We,fe=typeof R.chainId=="string"&&R.chainId?R.chainId:X==="reference"?ve:_t;au(X),je("ramachandran");const ke=await s.current.analyzeRamachandran({content:oe,chainId:fe||void 0});return fl(ke),{ok:!0,summary:`${X} (${ke.chainId}): ${ke.regionCounts.favored}/${ke.residueCount} favored, ${ke.contactPairs.length} contacts`,data:{chainId:ke.chainId,residueCount:ke.residueCount,secondaryCounts:ke.secondaryCounts,regionCounts:ke.regionCounts,contactCount:ke.contactPairs.length,outliers:ke.residues.filter(Le=>Le.region==="outlier").slice(0,10)}}}case"export_ruo_report":{const X=String(R.format||"html");return X==="json"?is():X==="bundle"?await si():da(),{ok:!0,summary:`Started ${X.toUpperCase()} download`,data:{exported:X}}}case"get_workspace_state":{const X=typeof R.section=="string"?R.section:"all",oe=typeof R.topN=="number"&&Number.isFinite(R.topN)?R.topN:10,ke=Ii({refLabel:Ke,mobLabel:Fe,refChain:ve,mobChain:_t,refInspect:Je,mobInspect:qn,comparison:tt,peptide:Ct,crispr:as,smiles:Vs,ramachandran:Qr},J,X,oe);return{ok:!0,summary:`Inspected workspace (${X}, ${tt?`RMSD ${tt.metrics.rmsdAngstrom.toFixed(3)} Å`:"no comparison"})`,data:ke}}case"search_scientific_web":{const X=String(R.query||"").trim(),oe=["all","literature","trials"].includes(String(R.scope))?String(R.scope):"all",fe=typeof R.limit=="number"&&Number.isFinite(R.limit)?R.limit:5,ke=await UD(X,{scope:oe,limit:fe});return{ok:!0,summary:`Web search "${X}": ${ke.hits.length} record(s) (${ke.origin})`,data:ke}}case"query_local_library":{const X=typeof R.kind=="string"?R.kind:"all",oe=typeof R.query=="string"?R.query.trim().toLowerCase():"",fe=J.filter(ke=>X==="all"?!0:ke.kind===X).filter(ke=>oe?`${ke.name} ${ke.source.accession??""} ${ke.tags.join(" ")}`.toLowerCase().includes(oe):!0).slice(0,20).map(ke=>({id:ke.id,kind:ke.kind,name:ke.name,format:ke.format,sha256:ke.sha256,source:ke.source}));return{ok:!0,summary:`Found ${fe.length} local library item(s)`,data:{count:fe.length,items:fe}}}case"list_compute_nodes":{const X=Di();return{ok:!0,summary:`${X.nodes.length} paired node(s); active=${X.activeNode?.label??"none"}`,data:{activeNodeId:X.activeNodeId,nodes:X.nodes.map(oe=>({id:oe.id,label:oe.label,kind:oe.kind,online:oe.online,gpus:oe.capabilities?.gpus??[],installedTools:oe.capabilities?.tools.filter(fe=>fe.installed).map(fe=>fe.id)??[]}))}}}case"run_compute_job":{const oe=Di().activeNode;if(!oe||!oe.online)return{ok:!1,summary:"No online Compute Node connected. Open Compute Nodes tab to pair Colab or a local GPU daemon.",data:null};const fe=String(R.toolId||"vina_docking"),ke=typeof R.smiles=="string"&&R.smiles.trim()?R.smiles.trim():Mt.smiles,Le=oA(tt,Ln),Be=fe==="vina_docking"?{ligandSmiles:ke,receptorPdb:ue,center:Le?.center??[0,0,0],size:Le?.size??[22,22,22]}:fe==="openmm_md"?{pdbContent:ue,steps:Number(R.steps??1e3)}:fe==="pyscf_qm"?{smiles:ke}:fe==="boltz_predict"?{sequences:[{id:"A",sequence:st.sequence}]}:{...R};je("compute");const ft=await dy(oe.id,fe,Be);return hy(oe.id,ft.job_id),{ok:!0,summary:`Dispatched ${fe} (${ft.job_id}) to ${oe.label}`,data:ft}}case"control_app_ui":{const X=["home","viewer","results","sequence","ramachandran","peptide","crispr","chemistry","workflow","compute","plugins","assistant","mcp","library"],oe=typeof R.tab=="string"&&X.includes(R.tab)?R.tab:null;oe&&je(oe,!!R.toSide),typeof R.sidebarView=="string"&&["explorer","library","tools","history"].includes(R.sidebarView)&&q(R.sidebarView),typeof R.sidebarOpen=="boolean"&&O(R.sidebarOpen),(R.viewportEngine==="webgl2"||R.viewportEngine==="molstar")&&D(R.viewportEngine),(R.viewportLayout==="overlay"||R.viewportLayout==="split"||R.viewportLayout==="reference"||R.viewportLayout==="mobile")&&Ue(R.viewportLayout),(R.renderStyle==="ribbon"||R.renderStyle==="trace"||R.renderStyle==="pocket")&&bt(R.renderStyle),(R.colorMode==="plddt"||R.colorMode==="bfactor"||R.colorMode==="deviation"||R.colorMode==="identity")&&St(R.colorMode);const fe=R.cameraPreset??R.applyPreset;return(fe==="overview"||fe==="active-site"||fe==="n-terminus"||fe==="reset")&&i.current?.applyPreset(fe),R.openTutorial===!0||R.openModal==="tutorial"?lr(!0):R.openModal==="databases"?G(!0):R.openModal==="settings"?Jt("ai"):R.openModal==="palette"?H(!0):R.openModal==="close"&&(lr(!1),G(!1),we(!1),H(!1)),R.resetLayout===!0&&T({type:"reset"}),{ok:!0,summary:`Updated UI (${[oe?`tab=${oe}`:null,R.sidebarView?`sidebar=${String(R.sidebarView)}`:null,R.openModal?`modal=${String(R.openModal)}`:null].filter(Boolean).join(", ")||"applied state"})`,data:{tab:oe,sidebarView:R.sidebarView??null,viewportEngine:R.viewportEngine??null}}}case"manage_project":{const X=String(R.action||"list");if(X==="list"){const oe=dp();return{ok:!0,summary:`${oe.projects.length} project(s); active="${oe.activeProject?.name??"none"}"`,data:{activeProjectId:oe.activeProject?.id??null,projects:oe.projects.map(fe=>({id:fe.id,name:fe.name,template:fe.template,structures:fe.structures.map(ke=>ke.label),molecules:fe.molecules.map(ke=>({name:ke.name,smiles:ke.smiles})),peptides:fe.peptides.length,crisprs:fe.crisprs.length}))}}}if(X==="create"){const oe=["blank","structure-compare","ligand-docking","peptide-crispr"].includes(String(R.template))?String(R.template):"ligand-docking",fe=ti({name:String(R.name||"AI Research Project"),description:typeof R.description=="string"?R.description:void 0,template:oe});return{ok:!0,summary:`Created project "${fe.name}" (${fe.id})`,data:fe}}if(X==="switch"){const oe=vx(String(R.projectId||""));return oe?{ok:!0,summary:`Switched active project to "${oe.name}"`,data:oe}:{ok:!1,summary:`Project "${String(R.projectId)}" not found`,data:null}}if(X==="add_molecule"){const oe=String(R.smiles||Mt.smiles).trim(),fe=String(R.name||"Designed Ligand").trim(),ke=Sx({name:fe,smiles:oe,note:typeof R.note=="string"?R.note:void 0});return Un({type:"set_custom_smiles",smiles:oe,name:fe}),je("chemistry"),{ok:!0,summary:`Saved "${fe}" (${oe}) into active project`,data:ke}}if(X==="split_chains"){const oe=(R.target??R.role)==="mobile"?"mobile":"reference",fe=gl(oe);return fe.length===0?{ok:!1,summary:`No ${oe} structure loaded or no chains found`,data:[]}:{ok:!0,summary:`Split ${oe} into ${fe.length} chain/ligand assets`,data:fe.map(ke=>({label:ke.label,kind:ke.kind,chainId:ke.chainId,atomCount:ke.atomCount}))}}if(X==="stage_binding"){const oe=typeof R.smiles=="string"&&R.smiles.trim()?R.smiles.trim():Mt.smiles,fe=typeof R.name=="string"&&R.name.trim()?R.name.trim():Mt.name;return Un({type:"set_custom_smiles",smiles:oe,name:fe}),Ne({tool:"vina",nonce:Date.now()}),je("compute"),{ok:!0,summary:`Staged "${fe}" + "${Ke||"active receptor"}" for binding`,data:{smiles:oe,name:fe,receptor:Ke}}}return{ok:!1,summary:`Unknown project action: ${X}`,data:null}}case"design_molecule_rdkit":{let X=String(R.smiles||Mt.smiles).trim();const oe=String(R.name||"Designed Analog").trim(),fe=typeof R.modifyAction=="string"?R.modifyAction:"";fe==="add_fluoro"&&!X.includes("F")?X=`${X}F`:fe==="add_methyl"?X=`${X}C`:fe==="add_hydroxyl"&&(X=`${X}O`),je("chemistry"),Un({type:"set_custom_smiles",smiles:X,name:oe});const ke=await s.current.analyzeMoleculeSmiles({name:oe,smiles:X});to(ke);let Le=[],Be=X,ft=null;if(typeof Worker<"u")try{const Zt=await Fo().analyzeMolecule(X);Be=Zt.canonicalSmiles||X,Le=Zt.alerts.map(ks=>`${ks.family}: ${ks.label}`),typeof R.smartsQuery=="string"&&R.smartsQuery.trim()&&(ft=!!(await Fo().searchLibrary(R.smartsQuery.trim(),[{id:oe,name:oe,smiles:Be}]))[0]?.substructureMatch)}catch{}const vt=R.saveToProject===!1?null:Sx({name:oe,smiles:Be,note:Le.length?`Alerts: ${Le.join("; ")}`:"Clean PAINS/Brenk"});return{ok:!0,summary:`Designed "${oe}" (${ke.formula}, MW ${ke.molecularWeight.toFixed(1)}, cLogP ${ke.crippenLogP.toFixed(2)}, TPSA ${ke.tpsa.toFixed(1)})`,data:{name:oe,canonicalSmiles:Be,descriptors:ke,alerts:Le,smartsMatched:ft,savedProjectAssetId:vt?.id??null}}}case"run_workflow_pipeline":{const X=Zd.find(Be=>Be.id===R.templateId)??Zd[0],oe=String(R.action||"run");if(je("workflow"),oe==="export_nextflow"){const Be=X3(X);return{ok:!0,summary:`Exported Nextflow DSL2 for "${X.name}"`,data:{templateId:X.id,nextflow:Be}}}if(oe==="export_snakemake"){const Be=Q3(X);return{ok:!0,summary:`Exported Snakemake Snakefile for "${X.name}"`,data:{templateId:X.id,snakefile:Be}}}const fe=fh(X);je("workflow");const ke=[];for(const Be of fe){if(!bl.current)break;try{const ft=await bl.current(Be.kind,Be.params);ke.push({id:Be.id,kind:Be.kind,ok:!0,summary:ft.summary})}catch(ft){const vt=ft instanceof Error?ft.message:String(ft);ke.push({id:Be.id,kind:Be.kind,ok:!1,summary:vt});break}}return{ok:ke.length===fe.length&&ke.every(Be=>Be.ok),summary:`${X.name}: completed ${ke.filter(Be=>Be.ok).length}/${fe.length} workflow step(s)`,data:{templateId:X.id,templateName:X.name,steps:ke}}}case"manage_plugins":{const X=String(R.action||"list");if(X==="list"){const ke=Jd();return{ok:!0,summary:`${ke.filter(Le=>Le.enabled).length}/${ke.length} plugin(s) enabled`,data:ke.map(Le=>({id:Le.id,name:Le.name,category:Le.category,tier:Le.tier,license:Le.license,commercialSafe:Le.commercialSafe,enabled:Le.enabled}))}}const oe=String(R.pluginId||"").trim();if(!oe)return{ok:!1,summary:"pluginId required",data:null};const fe=X==="enable";return H3(oe,fe),je("plugins"),{ok:!0,summary:`${fe?"Enabled":"Disabled"} plugin ${oe}`,data:{pluginId:oe,enabled:fe}}}}},[Ke,ue,ve,Pe,Je,Fe,We,_t,ss,qn,Nn,tt,st,Ct,Nt,as,Mt.smiles,Mt.name,Vs,Qr,J,Ln,Pt,Yt,Ra,xl,da,is,si,je,Jt,ti,gl]),jn=C.useMemo(()=>oA(tt,Ln),[tt,Ln]),yl=C.useMemo(()=>(tt?.refDisplayAtoms?.ligands??Je?.ligands??[]).filter(R=>R.resName.toUpperCase()!=="HOH"&&R.atoms.length>0).map(R=>{let X=0,oe=0,fe=0;for(const Le of R.atoms)X+=Le.xyz[0],oe+=Le.xyz[1],fe+=Le.xyz[2];const ke=Math.max(1,R.atoms.length);return{resName:R.resName,chainId:R.chainId,seqId:R.seqId,atomCount:R.atoms.length,centroid:[X/ke,oe/ke,fe/ke]}}),[tt,Je]),Ks=C.useMemo(()=>({activeProjectName:At.activeProject?.name??null,refLabel:Ke,refChain:ve,mobLabel:Fe,mobChain:_t,hasRef:!!ue,hasMob:!!We,hasComparison:!!tt,focusedSeqId:Ln,activeHighlight:ct.size>0?{source:ao??"Selection",seqIds:Array.from(ct)}:null,projectMolecules:At.activeProject?.molecules??[],projectStructures:At.activeProject?.structures??[],coCrystalLigands:yl,dockingBox:jn,focusIn3D:(M,R)=>{Yt(M),R?.style&&bt(R.style),R?.centerCamera!==!1&&Rh({seqId:M,nonce:Date.now()}),R?.openViewer==="activate"?je("viewer",!1):R?.openViewer==="side"&&je("viewer",!0)},highlightIn3D:(M,R,X)=>{const oe=Array.from(new Set(M.filter(fe=>Number.isFinite(fe)&&fe>0)));hl(oe.length>0?{source:R,seqIds:oe}:null),X?.focusSeqId!==void 0&&(Yt(X.focusSeqId),Rh({seqId:X.focusSeqId,nonce:Date.now()})),X?.style&&bt(X.style),X?.openViewer==="activate"?je("viewer",!1):X?.openViewer==="side"&&je("viewer",!0),oe.length>0&&e(`Highlighted ${oe.length} residue(s) in 3D (${R})`,"info")},clearHighlights3D:()=>hl(null),setStyle3D:M=>bt(M),setColorMode3D:M=>St(M),openTab:je,openDatabases:()=>G(!0),loadExample:()=>void cr(),saveMoleculeToProject:M=>{Sx(M),e(`Saved ${M.name} to active project`,"success")},saveMoleculeToLibrary:M=>{ca({kind:"compound",format:"smiles",name:M.name,content:M.smiles,source:{database:null,accession:null,sourceUrl:null,license:null,retrievedAtUtc:new Date().toISOString(),origin:"manual"}})},savePeptideToProject:M=>{lA(M),e(`Saved peptide "${M.name}" to active project`,"success")},saveCrisprToProject:M=>{cA(M),e(`Saved CRISPR edit "${M.name}" to active project`,"success")},syncPeptideFromChain:M=>{const R=M==="reference"?Je:qn,X=M==="reference"?ve:_t,oe=R?.chains.find(fe=>fe.chainId===X)??R?.chains[0];if(!oe?.sequence1Letter){e(`No amino-acid sequence found on ${M} chain`,"warn");return}Lt({type:"set_sequence",sequence:oe.sequence1Letter}),e(`Synced ${oe.sequence1Letter.length} aa from ${M} chain ${oe.chainId}`,"success")},sendMutationToPeptide:(M,R)=>{Lt({type:"add_mutation",notation:M}),R&&Yt(R),je("peptide"),e(`Applied ${M} in Peptide Workbench`,"info")},sendResidueToCrispr:M=>{Yt(M),je("crispr")},sendResidueToRamachandran:M=>{Yt(M),je("ramachandran")}}),[At.activeProject,Ke,ve,Fe,_t,ue,We,tt,Ln,ct,ao,yl,jn,Je,qn,Yt,je,cr,ca,e]),ur=C.useCallback(async(M,R)=>{switch(M){case"load_structures":if(!ue&&!Mt.smiles)throw new Error("Load a structure or SMILES first.");return{summary:`${Ke||"No structure"} · ${Mt.name}`};case"kabsch_compare":{const X=await Pt({rLabel:Ke,rContent:ue,rChain:ve,rMeta:Pe,mLabel:Fe,mContent:We,mChain:_t,mMeta:ss,pae:Nn});if(!X)throw new Error("Superposition failed; verify reference & mobile chains.");return{summary:`RMSD ${X.metrics.rmsdAngstrom.toFixed(3)} Å (${X.metrics.matchedCaCount} Cα)`,metrics:X.metrics}}case"rdkit_prep":{if(typeof Worker>"u")return{summary:`Wasm SMILES (${Mt.smiles})`};const X=await Fo().analyzeMolecule(Mt.smiles);return{summary:`${X.canonicalSmiles} · ${X.alerts.length} alerts`,metrics:X.descriptors}}case"export_report":return is(),{summary:"Exported RUO JSON provenance manifest"};default:{const oe=Di().activeNode;if(!oe||!oe.online)throw new Error(`Node "${M}" requires an online Tier-2 GPU/Compute Node (pair Colab or local worker).`);const fe={...R,smiles:Mt.smiles,ligandSmiles:Mt.smiles,pdbContent:ue,receptorPdb:ue,targetPdb:ue,center:jn?.center??[0,0,0],size:jn?.size??[22,22,22],sequences:[{id:"A",sequence:st.sequence}]},ke=await dy(oe.id,M,fe),Le=await hy(oe.id,ke.job_id);if(Le.status!=="completed")throw new Error(Le.error_message||`Remote job ${Le.status}`);return{summary:`${M} complete on ${oe.label}`,metrics:Le.metrics}}}},[Ke,ue,ve,Pe,Fe,We,_t,ss,Nn,Mt.name,Mt.smiles,st.sequence,jn,Pt,is]);bl.current=ur;const ha=C.useMemo(()=>({refLabel:Ke,mobLabel:Fe,refChain:ve,mobChain:_t,refInspect:Je,mobInspect:qn,comparison:tt,peptide:Ct,crispr:as,smiles:Vs,ramachandran:Qr}),[Ke,Fe,ve,_t,Je,qn,tt,Ct,as,Vs,Qr]),_l=C.useMemo(()=>({workspace:ha,libraryItems:J,executeTool:ro}),[ha,J,ro]),pu=C.useCallback(async M=>{const R=M.trim();if(!R||la)return;const X={id:`u-${Date.now()}`,role:"user",text:R,timestampUtc:new Date().toISOString()},oe=cu;uu(fe=>[...fe,X]),or([]),lu(!0);try{const fe=await rD({prompt:R,history:oe,workspace:ha,executeTool:(ke,Le)=>eE(_l,ke,Le,"internal-ai-agent"),onFallbackAction:Bh,onProgress:or,requestToolPermission:Lh,sessionApprovedCategories:ei.current,permissionPolicies:Ea,config:Ut});uu(ke=>[...ke,fe])}finally{or([]),Ma.current=null,Jr(null),lu(!1)}},[la,cu,ha,_l,Bh,Lh,Ea,Ut]),vl=C.useCallback(M=>on(JI(M)),[]),io=C.useCallback(M=>{W(M),on(Ac())},[]),Ss=E.groups[E.focused]?.active??null;C.useEffect(()=>{const M=R=>{const X=R.metaKey||R.ctrlKey,oe=R.key.toLowerCase();X&&oe==="k"?(R.preventDefault(),H(fe=>!fe)):X&&oe==="o"?(R.preventDefault(),c.current?.click()):X&&R.shiftKey&&oe==="f"?(R.preventDefault(),G(!0)):X&&oe==="b"?(R.preventDefault(),O(fe=>!fe)):X&&R.key===","?(R.preventDefault(),Jt()):R.altKey&&R.code==="KeyW"&&Ss&&(R.preventDefault(),T({type:"close",tab:Ss}))};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[Ss,Jt]);const gu=C.useMemo(()=>[{id:"tutorial",category:"Help",label:"Open Interactive Studio Tutorial & Guide",run:()=>lr(!0)},{id:"new-project",category:"Project",label:"Create New Research Project",run:()=>{ti({name:`Project ${(At.projects.length||0)+1}`,template:"ligand-docking"})}},{id:"split-ref",category:"Project",label:"Split Reference Chains & HETATM Ligands",run:()=>{gl("reference")}},{id:"open-file",category:"File",label:"Open file…",shortcut:"⌘O",run:()=>c.current?.click()},{id:"db",category:"File",label:"Search public databases",shortcut:"⌘⇧F",run:()=>G(!0)},{id:"example",category:"File",label:"Load example comparison (carbonic anhydrase II)",run:()=>void cr()},{id:"tab-viewer",category:"Open tab",label:"3D Viewer",run:()=>je("viewer")},{id:"tab-results",category:"Open tab",label:"Results",run:()=>je("results")},{id:"tab-seq",category:"Open tab",label:"Sequence deviation",run:()=>je("sequence")},{id:"tab-rama",category:"Open tab",label:"Ramachandran plot",run:()=>je("ramachandran")},{id:"tab-pep",category:"Open tab",label:"Peptide engineering",run:()=>je("peptide")},{id:"tab-crispr",category:"Open tab",label:"Gene & CRISPR",run:()=>je("crispr")},{id:"tab-chem",category:"Open tab",label:"Ligands & 2D Sketcher",run:()=>je("chemistry")},{id:"tab-workflow",category:"Open tab",label:"Workflow Canvas",run:()=>je("workflow")},{id:"tab-compute",category:"Open tab",label:"GPU & Compute Nodes",run:()=>je("compute")},{id:"tab-plugins",category:"Open tab",label:"Plugins & Add-ons",run:()=>je("plugins")},{id:"toggle-molstar",category:"3D view",label:`Switch 3D Engine (${le==="molstar"?"Fast WebGL2":"Mol* Pro"})`,run:()=>D(M=>M==="molstar"?"webgl2":"molstar")},{id:"tab-ai",category:"Open tab",label:"AI Assistant",run:()=>je("assistant")},{id:"tab-mcp",category:"Open tab",label:"MCP Server",run:()=>je("mcp")},{id:"tab-lib",category:"Open tab",label:"Library",run:()=>je("library")},{id:"tab-home",category:"Open tab",label:"Start page",run:()=>je("home")},{id:"cam-site",category:"3D view",label:"Focus active site",run:()=>i.current?.applyPreset("active-site")},{id:"cam-reset",category:"3D view",label:"Reset camera",run:()=>i.current?.applyPreset("overview")},{id:"color-plddt",category:"3D view",label:"Color by pLDDT",run:()=>St("plddt")},{id:"color-b",category:"3D view",label:"Color by B-factor",run:()=>St("bfactor")},{id:"color-dev",category:"3D view",label:"Color by deviation Δd",run:()=>St("deviation")},{id:"color-id",category:"3D view",label:"Color by structure",run:()=>St("identity")},{id:"export-html",category:"Export",label:"HTML report",run:da},{id:"export-json",category:"Export",label:"JSON manifest",run:is},{id:"export-bundle",category:"Export",label:"Project bundle",run:()=>void si()},{id:"settings",category:"Settings",label:"Open settings",shortcut:"⌘,",run:()=>Jt()},{id:"settings-ai",category:"Settings",label:"AI & API keys",run:()=>Jt("ai")},{id:"settings-usage",category:"Settings",label:"Usage",run:()=>Jt("usage")},{id:"settings-account",category:"Settings",label:he?"Account":"Sign in",run:()=>he?Jt("account"):Bn("signin")},{id:"ui-bigger",category:"View",label:"Increase interface size",shortcut:"⌘+",run:()=>Cx(1)},{id:"ui-smaller",category:"View",label:"Decrease interface size",shortcut:"⌘−",run:()=>Cx(-1)},{id:"sidebar",category:"View",label:"Toggle sidebar",shortcut:"⌘B",run:()=>O(M=>!M)},{id:"layout-reset",category:"View",label:"Reset tab layout",run:()=>T({type:"reset"})}],[cr,je,da,is,si,Jt,he,Bn]),oo=C.useMemo(()=>new Set(E.groups.flatMap(M=>M.tabs)),[E]),ma=C.useMemo(()=>{const M=new Set;return Je&&M.add(Je.sha256),qn&&M.add(qn.sha256),M},[Je,qn]),bn="h-4 w-4",wl={home:{title:"Start",icon:o.jsx(FA,{className:bn})},viewer:{title:"3D Viewer",icon:o.jsx(_s,{className:bn})},results:{title:"Results",icon:o.jsx(qi,{className:bn})},sequence:{title:"Sequence",icon:o.jsx(Vo,{className:bn})},ramachandran:{title:"Ramachandran",icon:o.jsx(Qo,{className:bn})},peptide:{title:"Peptide",icon:o.jsx(ar,{className:bn})},crispr:{title:"CRISPR",icon:o.jsx(Fs,{className:bn})},chemistry:{title:"Ligands",icon:o.jsx(ia,{className:bn})},workflow:{title:"Workflows",icon:o.jsx(Dp,{className:bn})},compute:{title:"GPU Nodes",icon:o.jsx(al,{className:bn}),badge:Re.activeNode?.online?o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400"}):void 0},plugins:{title:"Plugins",icon:o.jsx(Lp,{className:bn})},assistant:{title:"Assistant",icon:o.jsx(qr,{className:bn}),badge:la?o.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-sky-400"}):void 0},mcp:{title:"MCP Server",icon:o.jsx(rl,{className:bn})},library:{title:"Library",icon:o.jsx(sh,{className:bn})}},ai=r.guidedMode,Oa=M=>o.jsx("div",{className:"h-full min-h-0",children:M}),Sl=M=>{switch(M){case"home":return o.jsx(Jq,{activeStarterId:me,runHistory:ou,projects:At.projects,activeProject:At.activeProject,onCreateProject:ti,onSwitchProject:R=>{vx(R),e("Switched active project","info")},onDeleteProject:R=>{kD(R),e("Deleted project","info")},onOpenTutorial:()=>lr(!0),onImportFile:()=>c.current?.click(),onSearchDatabases:()=>G(!0),onOpenLibrary:()=>je("library"),onOpenAssistant:()=>je("assistant"),onOpenChemistry:()=>je("chemistry"),onOpenPeptide:()=>je("peptide"),onOpenCrispr:()=>je("crispr"),onOpenWorkflows:()=>je("workflow"),onOpenComputeNodes:()=>je("compute"),onOpenPlugins:()=>je("plugins"),onLaunchStarter:R=>void mu(R),onOpenLibraryItem:R=>void za(R,"auto")});case"viewer":return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"flex h-8 shrink-0 items-center justify-between border-b border-white/[0.06] bg-[#0a0d13] px-2.5 text-[0.75rem]",children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"mr-1 text-slate-500",children:"3D Engine:"}),o.jsx("button",{type:"button",onClick:()=>D("webgl2"),className:`rounded-md px-2 py-0.5 font-medium transition ${le==="webgl2"?"bg-sky-500/20 text-sky-200":"text-slate-400 hover:text-slate-200"}`,children:"Fast WebGL2"}),o.jsx("button",{type:"button",onClick:()=>D("molstar"),className:`rounded-md px-2 py-0.5 font-medium transition ${le==="molstar"?"bg-sky-500/20 text-sky-200":"text-slate-400 hover:text-slate-200"}`,children:"Mol* Pro"})]}),ae&&o.jsxs("div",{className:"flex items-center gap-2 font-mono text-[0.6875rem] text-emerald-300",children:[o.jsxs("span",{children:["Overlay: ",ae.label]}),o.jsx("button",{type:"button",onClick:()=>pe(null),className:"text-slate-400 hover:text-slate-200",children:"Clear"})]})]}),o.jsxs("div",{className:"relative min-h-0 flex-1",children:[le==="molstar"?o.jsx(C.Suspense,{fallback:o.jsx("div",{className:"flex h-full items-center justify-center bg-[#070b12] text-xs text-slate-400",children:"Loading Mol* Pro 3D engine…"}),children:o.jsx(KL,{ref:i,refLabel:Ke,refContent:ue,mobLabel:Fe,mobContent:We,comparison:tt,layout:Ce,style:be,colorMode:Ot,focusedSeqId:Ln,focusCameraRequest:Zi,highlightSourceLabel:ao,highlightCount:ct.size,onClearHighlights:()=>hl(null),extraOverlay:ae,onPickResidue:Yt,onSendPocketToDocking:()=>{Ne({tool:"vina",nonce:Date.now()}),je("compute")}})}):o.jsx(hL,{ref:i,comparison:tt,refInspect:Je,mobInspect:qn,refChainId:ve,mobChainId:_t,layout:Ce,onChangeLayout:Ue,style:be,onChangeStyle:bt,colorMode:Ot,onChangeColorMode:St,focusedSeqId:Ln,focusCameraRequest:Zi,highlightedSeqIds:ct,highlightSourceLabel:ao,onClearHighlights:()=>hl(null),paePair:zh,onPickResidue:Yt,onRendererModeDetected:k,simpleMode:!1}),!ue&&!We&&!p&&o.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center p-6",children:o.jsxs("div",{className:"pointer-events-auto max-w-sm rounded-2xl border border-white/10 bg-[#121722]/95 p-6 text-center shadow-2xl backdrop-blur",children:[o.jsx(_s,{className:"mx-auto h-8 w-8 text-slate-500"}),o.jsx("div",{className:"mt-3 text-base font-medium text-slate-100",children:"No structure loaded"}),o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"Open a file, pick one from your library, or search a public database."}),o.jsxs("div",{className:"mt-4 flex flex-wrap justify-center gap-2",children:[o.jsx("button",{type:"button",onClick:()=>c.current?.click(),className:"rounded-lg bg-sky-500 px-3.5 py-2 text-sm font-semibold text-slate-950 hover:bg-sky-400",children:"Open file"}),o.jsx("button",{type:"button",onClick:()=>G(!0),className:"rounded-lg border border-white/10 px-3.5 py-2 text-sm text-slate-200 hover:bg-white/[0.06]",children:"Search databases"})]}),o.jsx("button",{type:"button",onClick:()=>void cr(),className:"mt-3 text-xs text-slate-500 hover:text-sky-300",children:"or load the example comparison"})]})})]})]});case"results":return o.jsx(vL,{comparison:tt,paeJson:Nn,busy:!!p,guided:ai,selectedPaePair:zh,onSelectPaePair:(R,X)=>{eo([R,X]),Yt(R)},includePng:ni,onToggleIncludePng:R=>n(X=>({...X,viewer:{...X.viewer,embedPngInReports:R}})),onExportHtml:da,onExportJson:is,onExportBundle:()=>void si(),bridge:Ks});case"sequence":return Oa(o.jsx(SL,{comparison:tt,refInspect:Je,mobInspect:qn,refChainId:ve,mobChainId:_t,focusedSeqId:Ln,onFocusResidue:Yt,bridge:Ks}));case"ramachandran":return Oa(o.jsx(_L,{refLabel:Ke,refChain:ve,mobLabel:Fe,mobChain:_t,activeSource:so,onChangeSource:au,result:Qr,error:ru,focusedSeqId:Ln,onFocusResidue:Yt,simpleMode:ai,bridge:Ks}));case"peptide":return Oa(o.jsx(mL,{state:st,dispatch:Lt,result:Ct,error:i0,onFocusResidue:Yt,simpleMode:ai,bridge:Ks}));case"crispr":return Oa(o.jsx(Yq,{state:Nt,dispatch:An,result:as,error:ml,onFocusResidue:Yt,simpleMode:ai,bridge:Ks}));case"chemistry":return Oa(o.jsx(Bq,{state:Mt,dispatch:Un,result:Vs,comparison:tt,error:no,onFocusResidue:Yt,onStageForCompute:(R,X)=>{Un({type:"set_custom_smiles",smiles:X.smiles,name:X.name}),Ne({tool:R,nonce:Date.now()}),je("compute")},libraryCompounds:J.filter(R=>R.kind==="compound").map(R=>({id:R.id,name:R.name,smiles:R.content})),simpleMode:ai,bridge:Ks}));case"workflow":return o.jsx($L,{onExecuteNode:ur,activeComputeLabel:Re.activeNode?.online?Re.activeNode.label:null,onOpenComputeNodes:()=>je("compute"),bridge:Ks});case"compute":return o.jsx(Fq,{activeSmiles:Mt.smiles,activeSmilesName:Mt.name,activeRefPdbOrCif:ue,activeRefLabel:Ke,pocketBox:jn,stagedComputeTarget:Ae,onImportArtifactToViewer:R=>{pe({id:`art-${Date.now()}`,...R}),D("molstar"),je("viewer")},bridge:Ks});case"plugins":return o.jsx(xL,{onOpenComputeNodes:()=>je("compute"),onOpenMcpServer:()=>je("mcp"),onOpenToolTab:R=>je(R)});case"assistant":return o.jsx(Nq,{messages:cu,busy:la,config:Ut,liveSteps:Ih,pendingPermission:pl,onResolvePermission:Uh,onSelectProvider:(R,X)=>vl({provider:R,...R==="synlexa"&&Xc(Ut).hasByok?{routingPreference:"manual"}:{},...X?{[R]:{model:X}}:{}}),onToggleWebSearch:R=>vl({enableWebSearch:R}),onSend:R=>void pu(R),onClear:()=>uu([]),onOpenKeySettings:()=>Jt("ai"),onOpenMcpServer:()=>je("mcp")});case"mcp":return o.jsx(tL,{runtime:_l,onOpenAiAssistant:()=>je("assistant"),onOpenVaultSettings:()=>Jt("ai")});case"library":return o.jsx(CA,{onOpenItem:(R,X)=>void za(R,X),loadedShas:ma})}},lo=Xc(Ut),ln=Ut[lo.provider]??{apiKey:"",model:""},Pa=es[lo.provider].models.find(M=>M.id===ln.model)?.label??ln.model,kl=ln.apiKey?`${lo.isByok?"BYOK":"Cloud"}: ${Pa}`:lo.provider==="synlexa"?"AI: sign in or add BYOK":"AI: no key",co=At.activeProject?.name??(me?sq(me)?.title:null)??(Ke||Fe?[Ke,Fe].filter(Boolean).join(" vs "):"Untitled workspace"),c0=M=>{M==="settings"?Jt("ai"):je(M)},bu={explorer:"Workspace",library:"Library",tools:"Tools",history:"History"};return o.jsxs("div",{className:"flex h-dvh w-screen flex-col overflow-hidden bg-[#0b0e14] text-slate-100",children:[o.jsx("input",{ref:c,type:"file",multiple:!0,accept:".cif,.mmcif,.pdb,.ent,.json,.fasta,.fa,.faa,.smi",className:"hidden",onChange:M=>{M.target.files?.length&&fu(M.target.files,"auto"),M.target.value=""}}),o.jsx(DL,{projectTitle:co,session:he,onOpenPalette:()=>H(!0),onOpenFile:()=>c.current?.click(),onSearchDatabases:()=>G(!0),onOpenMcp:()=>je("mcp"),onOpenTutorial:()=>lr(!0),onExportHtml:da,onExportJson:is,onExportBundle:()=>void si(),canExport:!!tt,onOpenAccount:()=>Jt("account")}),o.jsxs("div",{className:"flex min-h-0 flex-1",children:[o.jsx(qL,{view:j,sidebarOpen:z,onSelect:M=>{z&&M===j?O(!1):(q(M),O(!0))},onOpenSettings:()=>Jt(),onOpenAssistant:()=>je("assistant"),onOpenMcp:()=>je("mcp"),libraryCount:J.length}),z&&o.jsxs(LL,{title:bu[j],width:j==="library"?304:276,actions:j==="library"?o.jsx(sl,{label:"Open full library manager",onClick:()=>je("library"),children:o.jsx(Oy,{className:"h-3.5 w-3.5"})}):void 0,children:[j==="explorer"&&o.jsx(UL,{refLabel:Ke,mobLabel:Fe,refInspect:Je,mobInspect:qn,refChain:ve,mobChain:_t,hasRef:!!ue,hasMob:!!We,paePresent:!!Nn,chainError:_,onChangeRefChain:M=>{Qe(M),Pt({...fn(),rChain:M})},onChangeMobChain:M=>{ja(M);const R=qn?.chains.find(X=>X.chainId===M)?.sequence1Letter;R&&Lt({type:"set_sequence",sequence:R}),Pt({...fn(),mChain:M})},onUploadFiles:(M,R)=>void fu(M,R),onSaveToLibrary:l0,onSearchDatabases:()=>G(!0),onLoadExample:()=>void cr(),projects:At.projects,activeProject:At.activeProject,onCreateProject:ti,onSwitchProject:M=>vx(M),onSplitStructure:M=>gl(M),onLoadProjectStructure:du,onOpenProjectMolecule:M=>{Un({type:"set_custom_smiles",smiles:M.smiles,name:M.name}),je("chemistry")},onDockMolecule:o0,onRemoveProjectAsset:(M,R)=>CD(M,R),onOpenChemistry:()=>je("chemistry"),onOpenPeptide:()=>je("peptide"),onOpenCrispr:()=>je("crispr")}),j==="library"&&o.jsx(CA,{compact:!0,onOpenItem:(M,R)=>void za(M,R),loadedShas:ma}),j==="tools"&&o.jsx(HL,{openTabs:oo,onOpen:(M,R)=>je(M,R)}),j==="history"&&o.jsx(FL,{runs:ou,onClear:()=>void uE().then(()=>rs([]))})]}),o.jsx("main",{className:"flex min-w-0 flex-1 flex-col",children:o.jsx(IL,{layout:E,dispatch:T,meta:wl,renderTab:Sl,keepAlive:YL})})]}),o.jsx(VL,{busyLabel:p,wasmReady:d,rendererMode:S,rmsd:tt?.metrics.rmsdAngstrom??null,focusedSeqId:Ln,computeNodeLabel:Re.activeNode?.label??null,computeOnline:!!Re.activeNode?.online,onOpenComputeNodes:()=>je("compute"),aiLabel:kl,aiReady:!!ln.apiKey,onOpenAiSettings:()=>Jt("ai")}),o.jsx(Hq,{open:$,onClose:()=>H(!1),commands:gu}),o.jsx(Xq,{open:Z,onClose:()=>G(!1),onImportStructure:Ra,onImportCompound:xl}),o.jsx(kL,{open:K,onClose:()=>we(!1),section:V,onSectionChange:P,aiConfig:Ut,onUpdateAiConfig:vl,onPermissionsChange:Zr,session:he,onSessionChange:io,onSignIn:Bn,onCancelSignIn:hu,signInPending:Se,onResetLayout:()=>T({type:"reset"}),onClearedHistory:()=>rs([])}),o.jsx(PL,{open:qh,onClose:()=>lr(!1),onExecuteStepAction:c0})]})}Jv(Xv().uiScale);const PA=JM.createRoot(document.getElementById("root"));if(YI(window.location.href)){window.history.replaceState({},"",window.location.pathname||"/");try{window.close()}catch{}PA.render(o.jsx("div",{className:"flex h-full items-center justify-center bg-[#0d1117] p-6 text-center",children:o.jsxs("div",{children:[o.jsx("div",{className:"text-base font-medium text-slate-100",children:"You're signed in"}),o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"Closing sign-in window and returning to Synlexa Studio…"}),o.jsx("button",{type:"button",onClick:()=>window.close(),className:"mt-4 rounded-md border border-slate-700 bg-slate-800 px-3 py-1.5 text-xs font-medium text-slate-200 hover:bg-slate-700",children:"Close window"})]})})),window.setTimeout(()=>{try{window.close()}catch{}},80),window.setTimeout(()=>{try{window.close()}catch{}},350)}else PA.render(o.jsx(C.StrictMode,{children:o.jsx(pq,{children:o.jsx(WL,{})})}));export{De as A,_s as B,OR as C,eU as D,sC as M,XL as R,Ur as a,bR as b,oA as c,JM as d,GM as g,o as j,C as r};
845
+ `;function Hd(e,r){return[e[0]-r[0],e[1]-r[1],e[2]-r[2]]}function Is(e,r){return[e[0]+r[0],e[1]+r[1],e[2]+r[2]]}function Sn(e,r){return[e[0]*r,e[1]*r,e[2]*r]}function zr(e,r){return[e[1]*r[2]-e[2]*r[1],e[2]*r[0]-e[0]*r[2],e[0]*r[1]-e[1]*r[0]]}function nr(e){const r=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);return r<1e-8?[0,1,0]:[e[0]/r,e[1]/r,e[2]/r]}function Fd(e,r){return Math.sqrt((e[0]-r[0])**2+(e[1]-r[1])**2+(e[2]-r[2])**2)}function aL(e){const r=Math.cos(e.pitch),n=Math.sin(e.pitch),s=Math.cos(e.yaw),i=Math.sin(e.yaw),c=[e.target[0]+e.distance*r*i,e.target[1]+e.distance*n,e.target[2]+e.distance*r*s],d=nr(Hd(e.target,c)),p=nr(zr(d,[0,1,0])),b=zr(p,d);return new Float32Array([p[0],b[0],-d[0],0,p[1],b[1],-d[1],0,p[2],b[2],-d[2],0,-(p[0]*c[0]+p[1]*c[1]+p[2]*c[2]),-(b[0]*c[0]+b[1]*c[1]+b[2]*c[2]),d[0]*c[0]+d[1]*c[1]+d[2]*c[2],1])}function AA(e,r,n,s){const i=1/Math.tan(e/2),c=1/(n-s);return new Float32Array([i/r,0,0,0,0,i,0,0,0,0,(s+n)*c,-1,0,0,2*s*n*c,0])}function jA(e,r){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[s*4+i]=e[0+i]*r[s*4+0]+e[4+i]*r[s*4+1]+e[8+i]*r[s*4+2]+e[12+i]*r[s*4+3];return n}function $n(e,r,n,s,i,c){const d=e[0]*r[0]+e[4]*r[1]+e[8]*r[2]+e[12],f=e[1]*r[0]+e[5]*r[1]+e[9]*r[2]+e[13],p=e[2]*r[0]+e[6]*r[1]+e[10]*r[2]+e[14],b=e[3]*r[0]+e[7]*r[1]+e[11]*r[2]+e[15];if(b<=.05)return{sx:-9999,sy:-9999,ndcZ:2,visible:!1};const x=d/b,g=f/b,_=p/b;return{sx:n+(x*.5+.5)*i,sy:s+(-g*.5+.5)*c,ndcZ:_,visible:_>=-1&&_<=1}}function rL(e,r,n,s,i){const c=i*i,d=c*i,f=[0,0,0];for(let p=0;p<3;p++)f[p]=.5*(2*r[p]+(-e[p]+n[p])*i+(2*e[p]-5*r[p]+4*n[p]-s[p])*c+(-e[p]+3*r[p]-3*n[p]+s[p])*d);return f}class iL{data=[];pushTri(r,n,s,i,c,d,f,p,b){this.data.push(r[0],r[1],r[2],n[0],n[1],n[2],s[0]/255,s[1]/255,s[2]/255,i[0],i[1],i[2],c[0],c[1],c[2],d[0]/255,d[1]/255,d[2]/255,f[0],f[1],f[2],p[0],p[1],p[2],b[0]/255,b[1]/255,b[2]/255)}addSphere(r,n,s,i=8,c=12){for(let d=0;d<i;d++){const f=d/i*Math.PI,p=(d+1)/i*Math.PI;for(let b=0;b<c;b++){const x=b/c*Math.PI*2,g=(b+1)/c*Math.PI*2,_=[Math.sin(f)*Math.cos(x),Math.cos(f),Math.sin(f)*Math.sin(x)],y=[Math.sin(p)*Math.cos(x),Math.cos(p),Math.sin(p)*Math.sin(x)],S=[Math.sin(p)*Math.cos(g),Math.cos(p),Math.sin(p)*Math.sin(g)],k=[Math.sin(f)*Math.cos(g),Math.cos(f),Math.sin(f)*Math.sin(g)],E=Is(r,Sn(_,n)),T=Is(r,Sn(y,n)),j=Is(r,Sn(S,n)),q=Is(r,Sn(k,n));d>0&&this.pushTri(E,_,s,q,k,s,j,S,s),d<i-1&&this.pushTri(E,_,s,j,S,s,T,y,s)}}}addCylinder(r,n,s,i,c,d=8){const f=Hd(n,r),p=Math.sqrt(f[0]**2+f[1]**2+f[2]**2);if(p<1e-4)return;const b=Sn(f,1/p),x=Math.abs(b[1])<.9?[0,1,0]:[1,0,0],g=nr(zr(b,x)),_=zr(b,g);for(let y=0;y<d;y++){const S=y/d*Math.PI*2,k=(y+1)/d*Math.PI*2,E=Is(Sn(g,Math.cos(S)),Sn(_,Math.sin(S))),T=Is(Sn(g,Math.cos(k)),Sn(_,Math.sin(k))),j=Is(r,Sn(E,s)),q=Is(r,Sn(T,s)),z=Is(n,Sn(E,s)),O=Is(n,Sn(T,s));this.pushTri(j,E,i,q,T,i,O,T,c),this.pushTri(j,E,i,O,T,c,z,E,c)}}addBackboneRibbon(r,n,s,i=4,c=8){if(r.length<2)return;const d=[];let f=[r[0]];for(let p=1;p<r.length;p++)Fd(r[p-1].xyz,r[p].xyz)>6.5?(f.length>=2&&d.push(f),f=[r[p]]):f.push(r[p]);f.length>=2&&d.push(f);for(const p of d){const b=[];for(let k=0;k<p.length-1;k++){const E=p[Math.max(0,k-1)].xyz,T=p[k].xyz,j=p[k+1].xyz,q=p[Math.min(p.length-1,k+2)].xyz,z=p[k].color,O=p[k+1].color,V=k===p.length-2?i+1:i;for(let P=0;P<V;P++){const $=P/i,H=rL(E,T,j,q,$),Z=[z[0]+(O[0]-z[0])*$,z[1]+(O[1]-z[1])*$,z[2]+(O[2]-z[2])*$];b.push({pos:H,col:Z})}}let x=nr(Hd(b[1].pos,b[0].pos));const g=Math.abs(x[1])<.9?[0,1,0]:[1,0,0];let _=nr(zr(x,g)),y=zr(x,_);const S=[];for(let k=0;k<b.length;k++){const E=k===b.length-1?nr(Hd(b[k].pos,b[k-1].pos)):k===0?x:nr(Hd(b[k+1].pos,b[k-1].pos)),T=zr(x,E),j=Math.sqrt(T[0]**2+T[1]**2+T[2]**2);if(j>1e-5){const O=Math.max(-1,Math.min(1,x[0]*E[0]+x[1]*E[1]+x[2]*E[2])),V=Math.acos(O),P=Sn(T,1/j),$=Math.cos(V),H=Math.sin(V),Z=P[0]*_[0]+P[1]*_[1]+P[2]*_[2],G=zr(P,_);_=nr([_[0]*$+G[0]*H+P[0]*Z*(1-$),_[1]*$+G[1]*H+P[1]*Z*(1-$),_[2]*$+G[2]*H+P[2]*Z*(1-$)])}y=nr(zr(E,_)),x=E;const q=[],z=[];for(let O=0;O<c;O++){const V=O/c*Math.PI*2,P=Math.cos(V),$=Math.sin(V),H=Is(Sn(_,P*n),Sn(y,$*s)),Z=nr(Is(Sn(_,P/n),Sn(y,$/s)));q.push(Is(b[k].pos,H)),z.push(Z)}S.push({pts:q,norms:z,col:b[k].col})}for(let k=0;k<S.length-1;k++){const E=S[k],T=S[k+1];for(let j=0;j<c;j++){const q=(j+1)%c;this.pushTri(E.pts[j],E.norms[j],E.col,E.pts[q],E.norms[q],E.col,T.pts[q],T.norms[q],T.col),this.pushTri(E.pts[j],E.norms[j],E.col,T.pts[q],T.norms[q],T.col,T.pts[j],T.norms[j],T.col)}}}}toFloat32Array(){return new Float32Array(this.data)}}class oL{constructor(r){this.glCanvas=r;const n=r.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});n&&this.initProgram(n)?(this.gl=n,this.mode="webgl2"):this.mode="canvas2d-fallback"}gl=null;program=null;vao=null;vbo=null;uViewProjLoc=null;uViewLoc=null;mode;initProgram(r){const n=r.createShader(r.VERTEX_SHADER),s=r.createShader(r.FRAGMENT_SHADER);if(!n||!s||(r.shaderSource(n,nL),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))||(r.shaderSource(s,sL),r.compileShader(s),!r.getShaderParameter(s,r.COMPILE_STATUS)))return!1;const i=r.createProgram();if(!i||(r.attachShader(i,n),r.attachShader(i,s),r.linkProgram(i),!r.getProgramParameter(i,r.LINK_STATUS)))return!1;this.program=i,this.uViewProjLoc=r.getUniformLocation(i,"uViewProj"),this.uViewLoc=r.getUniformLocation(i,"uView"),this.vao=r.createVertexArray(),this.vbo=r.createBuffer(),r.bindVertexArray(this.vao),r.bindBuffer(r.ARRAY_BUFFER,this.vbo);const c=36;return r.enableVertexAttribArray(0),r.vertexAttribPointer(0,3,r.FLOAT,!1,c,0),r.enableVertexAttribArray(1),r.vertexAttribPointer(1,3,r.FLOAT,!1,c,12),r.enableVertexAttribArray(2),r.vertexAttribPointer(2,3,r.FLOAT,!1,c,24),r.bindVertexArray(null),r.enable(r.DEPTH_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),!0}render(r,n,s,i,c,d){const f=[],p=Math.max(1,Math.floor(i*d)),b=Math.max(1,Math.floor(c*d));(this.glCanvas.width!==p||this.glCanvas.height!==b)&&(this.glCanvas.width=p,this.glCanvas.height=b),(s.width!==p||s.height!==b)&&(s.width=p,s.height=b);const x=s.getContext("2d");x&&(x.setTransform(d,0,0,d,0,0),x.clearRect(0,0,i,c));const g=n.layout==="split"?[{x:0,y:0,w:i/2,h:c,showRef:!0,showMob:!1,title:"REFERENCE (EXPERIMENTAL)"},{x:i/2,y:0,w:i/2,h:c,showRef:!1,showMob:!0,title:"PREDICTION (SUPERPOSED)"}]:[{x:0,y:0,w:i,h:c,showRef:n.layout==="overlay"||n.layout==="reference",showMob:n.layout==="overlay"||n.layout==="mobile"}],_=aL(n.camera);if(this.mode==="webgl2"&&this.gl&&this.program&&this.vao&&this.vbo){const y=this.gl;y.disable(y.SCISSOR_TEST),y.viewport(0,0,p,b),y.clearColor(.035,.051,.078,1),y.clear(y.COLOR_BUFFER_BIT|y.DEPTH_BUFFER_BIT),y.enable(y.SCISSOR_TEST),y.useProgram(this.program),y.bindVertexArray(this.vao);for(const S of g){const k=Math.max(.1,S.w/Math.max(1,S.h)),E=AA(38*Math.PI/180,k,.5,600),T=jA(E,_),q=this.buildPanelMesh(r,n,S.showRef,S.showMob).toFloat32Array(),z=Math.floor(S.x*d),O=Math.floor(S.w*d),V=Math.floor(S.h*d);y.viewport(z,0,O,V),y.scissor(z,0,O,V),y.bindBuffer(y.ARRAY_BUFFER,this.vbo),y.bufferData(y.ARRAY_BUFFER,q,y.DYNAMIC_DRAW),y.uniformMatrix4fv(this.uViewLoc,!1,_),y.uniformMatrix4fv(this.uViewProjLoc,!1,T),y.drawArrays(y.TRIANGLES,0,q.length/9),this.collectAndDrawHud(r,n,T,S,x,f)}y.disable(y.SCISSOR_TEST)}else{const y=this.glCanvas.getContext("2d");if(y){y.setTransform(d,0,0,d,0,0),y.fillStyle="#090d14",y.fillRect(0,0,i,c);for(const S of g){const k=Math.max(.1,S.w/Math.max(1,S.h)),E=AA(38*Math.PI/180,k,.5,600),T=jA(E,_);this.render2dPanel(y,r,n,T,S),this.collectAndDrawHud(r,n,T,S,x,f)}}}return n.layout==="split"&&x&&(x.strokeStyle="rgba(148, 163, 184, 0.25)",x.lineWidth=1,x.beginPath(),x.moveTo(i/2,0),x.lineTo(i/2,c),x.stroke()),f}buildPanelMesh(r,n,s,i){const c=new iL,d=n.style==="pocket";if(s&&r.refResidues.length>0)if(n.style==="trace"){for(let p=0;p<r.refResidues.length-1;p++){const b=r.refResidues[p],x=r.refResidues[p+1];Fd(b.xyz,x.xyz)<=6.5&&c.addCylinder(b.xyz,x.xyz,.24,b.color,x.color,6)}for(const p of r.refResidues)c.addSphere(p.xyz,.34,p.color,6,8)}else c.addBackboneRibbon(r.refResidues,d?.34:.44,d?.14:.18,4,8);if(i&&r.mobResidues.length>0)if(n.style==="trace"){for(let p=0;p<r.mobResidues.length-1;p++){const b=r.mobResidues[p],x=r.mobResidues[p+1];Fd(b.xyz,x.xyz)<=6.5&&c.addCylinder(b.xyz,x.xyz,.2,b.color,x.color,6)}for(const p of r.mobResidues)c.addSphere(p.xyz,.3,p.color,6,8)}else c.addBackboneRibbon(r.mobResidues,d?.26:.36,d?.11:.14,4,8);if(s){for(const p of r.ligandBonds)c.addCylinder(p.a,p.b,d?p.radius:p.radius*.75,p.colorA,p.colorB,7);for(const p of r.ligandAtoms)c.addSphere(p.xyz,d?p.radius:p.radius*.85,p.color,9,12);if(d){for(const p of r.pocketBonds)c.addCylinder(p.a,p.b,p.radius,p.colorA,p.colorB,6);for(const p of r.pocketAtoms)c.addSphere(p.xyz,p.radius,p.color,6,8)}}const f=[...s?r.refResidues:[],...i?r.mobResidues:[]];for(const p of f)n.focusedSeqId===p.seqId?c.addSphere(p.xyz,.92,[251,191,36],10,14):n.highlightedSeqIds.has(p.seqId)&&c.addSphere(p.xyz,.68,[244,114,182],8,10);if(n.paePair){const[p,b]=n.paePair,x=f.find(_=>_.seqId===p),g=f.find(_=>_.seqId===b);x&&c.addSphere(x.xyz,.85,[34,211,238],9,12),g&&c.addSphere(g.xyz,.85,[52,211,153],9,12)}return c}render2dPanel(r,n,s,i,c){r.save(),r.beginPath(),r.rect(c.x,c.y,c.w,c.h),r.clip();const d=[],f=(b,x)=>{for(let g=0;g<b.length-1;g++){const _=b[g],y=b[g+1];if(Fd(_.xyz,y.xyz)>6.5)continue;const S=$n(i,_.xyz,c.x,c.y,c.w,c.h),k=$n(i,y.xyz,c.x,c.y,c.w,c.h);if(!S.visible||!k.visible)continue;const E=(S.ndcZ+k.ndcZ)*.5;d.push({depth:E,draw:()=>{r.strokeStyle=`rgb(${_.color[0]},${_.color[1]},${_.color[2]})`,r.lineWidth=x,r.lineCap="round",r.beginPath(),r.moveTo(S.sx,S.sy),r.lineTo(k.sx,k.sy),r.stroke()}})}};c.showRef&&f(n.refResidues,s.style==="pocket"?3:4),c.showMob&&f(n.mobResidues,s.style==="pocket"?2.4:3.2);const p=(b,x)=>{for(const g of x){const _=$n(i,g.a,c.x,c.y,c.w,c.h),y=$n(i,g.b,c.x,c.y,c.w,c.h);!_.visible||!y.visible||d.push({depth:(_.ndcZ+y.ndcZ)*.5,draw:()=>{r.strokeStyle=`rgb(${g.colorA[0]},${g.colorA[1]},${g.colorA[2]})`,r.lineWidth=2,r.beginPath(),r.moveTo(_.sx,_.sy),r.lineTo(y.sx,y.sy),r.stroke()}})}for(const g of b){const _=$n(i,g.xyz,c.x,c.y,c.w,c.h);_.visible&&d.push({depth:_.ndcZ,draw:()=>{r.fillStyle=`rgb(${g.color[0]},${g.color[1]},${g.color[2]})`,r.beginPath(),r.arc(_.sx,_.sy,g.isMetal?6:3.5,0,Math.PI*2),r.fill()}})}};c.showRef&&(p(n.ligandAtoms,n.ligandBonds),s.style==="pocket"&&p(n.pocketAtoms,n.pocketBonds)),d.sort((b,x)=>x.depth-b.depth);for(const b of d)b.draw();r.restore()}collectAndDrawHud(r,n,s,i,c,d){const f=x=>{x.sx>=i.x&&x.sx<=i.x+i.w&&x.sy>=i.y&&x.sy<=i.y+i.h&&d.push(x)};if(i.showRef){for(const x of r.refResidues){const g=$n(s,x.xyz,i.x,i.y,i.w,i.h);g.visible&&f({sx:g.sx,sy:g.sy,depth:g.ndcZ,kind:"residue",seqId:x.seqId,label:`${x.resName3} ${x.seqId} (Ref)`,xyz:x.xyz,chainKind:"ref"})}for(const x of r.ligandAtoms){const g=$n(s,x.xyz,i.x,i.y,i.w,i.h);g.visible&&f({sx:g.sx,sy:g.sy,depth:g.ndcZ,kind:"atom",seqId:x.seqId,label:x.label,xyz:x.xyz,chainKind:"ref"})}}if(i.showMob)for(const x of r.mobResidues){const g=$n(s,x.xyz,i.x,i.y,i.w,i.h);g.visible&&f({sx:g.sx,sy:g.sy,depth:g.ndcZ,kind:"residue",seqId:x.seqId,label:`${x.resName3} ${x.seqId} (Mob)`,xyz:x.xyz,chainKind:"mob"})}if(!c)return;if(c.save(),c.beginPath(),c.rect(i.x,i.y,i.w,i.h),c.clip(),i.showRef&&n.style==="pocket")for(const x of r.coordinationBonds){const g=$n(s,x.a,i.x,i.y,i.w,i.h),_=$n(s,x.b,i.x,i.y,i.w,i.h);!g.visible||!_.visible||(c.save(),c.setLineDash([4,3]),c.strokeStyle="rgba(216, 180, 254, 0.85)",c.lineWidth=1.4,c.beginPath(),c.moveTo(g.sx,g.sy),c.lineTo(_.sx,_.sy),c.stroke(),c.restore())}if(i.showRef){const x=r.ligandAtoms.find(_=>_.element==="ZN");if(x){const _=$n(s,x.xyz,i.x,i.y,i.w,i.h);_.visible&&kc(c,_.sx+10,_.sy-8,"Zn²⁺","#d8b4fe")}const g=r.ligandAtoms.find(_=>_.resName==="AZM"&&_.atomName==="S1");if(g){const _=$n(s,g.xyz,i.x,i.y,i.w,i.h);_.visible&&kc(c,_.sx+10,_.sy+10,"AZM","#67e8f9")}if(n.style==="pocket")for(const _ of[94,96,119]){const y=r.refResidues.find(k=>k.seqId===_);if(!y)continue;const S=$n(s,y.xyz,i.x,i.y,i.w,i.h);S.visible&&kc(c,S.sx+8,S.sy-6,`${y.resName3}${y.seqId}`,"#94a3b8")}}if(n.focusedSeqId!=null){const x=i.showRef&&r.refResidues.find(g=>g.seqId===n.focusedSeqId)||i.showMob&&r.mobResidues.find(g=>g.seqId===n.focusedSeqId);if(x){const g=$n(s,x.xyz,i.x,i.y,i.w,i.h);g.visible&&(c.strokeStyle="#fbbf24",c.lineWidth=2,c.beginPath(),c.arc(g.sx,g.sy,10,0,Math.PI*2),c.stroke(),kc(c,g.sx+12,g.sy-12,`${x.resName3}${x.seqId}`,"#fbbf24"))}}const[p,b]=n.distancePair;if(p&&b){const x=$n(s,p.xyz,i.x,i.y,i.w,i.h),g=$n(s,b.xyz,i.x,i.y,i.w,i.h);if(x.visible&&g.visible){c.save(),c.setLineDash([5,4]),c.strokeStyle="#f43f5e",c.lineWidth=2,c.beginPath(),c.moveTo(x.sx,x.sy),c.lineTo(g.sx,g.sy),c.stroke(),c.restore();const _=Fd(p.xyz,b.xyz),y=(x.sx+g.sx)*.5,S=(x.sy+g.sy)*.5;kc(c,y,S,`${p.resName3}${p.seqId} ↔ ${b.resName3}${b.seqId}: ${_.toFixed(2)} Å`,"#fda4af")}}else if(p){const x=$n(s,p.xyz,i.x,i.y,i.w,i.h);x.visible&&(c.strokeStyle="#f43f5e",c.lineWidth=2,c.beginPath(),c.arc(x.sx,x.sy,9,0,Math.PI*2),c.stroke(),kc(c,x.sx+10,x.sy+10,`A: ${p.resName3}${p.seqId}`,"#fda4af"))}i.title&&(c.fillStyle="rgba(15, 23, 42, 0.78)",c.fillRect(i.x+10,i.y+44,178,20),c.strokeStyle="rgba(51, 65, 85, 0.8)",c.strokeRect(i.x+10,i.y+44,178,20),c.fillStyle="#cbd5e1",c.font="600 10px ui-monospace, monospace",c.fillText(i.title,i.x+16,i.y+57)),c.restore()}}function kc(e,r,n,s,i){e.font="600 10px ui-monospace, SFMono-Regular, Menlo, monospace";const c=e.measureText(s),d=5,f=c.width+d*2,p=16;e.fillStyle="rgba(9, 13, 20, 0.84)",e.fillRect(r,n-11,f,p),e.strokeStyle="rgba(148, 163, 184, 0.35)",e.lineWidth=1,e.strokeRect(r,n-11,f,p),e.fillStyle=i,e.fillText(s,r+d,n)}function ky(e){return e==null||!Number.isFinite(e)?[148,163,184]:e>=90?[38,132,255]:e>=70?[101,203,243]:e>=50?[255,219,19]:[255,125,69]}function Cy(e){if(e==null||!Number.isFinite(e))return[148,163,184];const r=Math.max(0,Math.min(1,(e-4)/46)),n=[[98,45,186],[156,47,148],[222,73,104],[254,159,109],[252,244,152]],s=r*(n.length-1),i=Math.min(n.length-2,Math.floor(s)),c=s-i,d=n[i],f=n[i+1];return[Math.round(d[0]+(f[0]-d[0])*c),Math.round(d[1]+(f[1]-d[1])*c),Math.round(d[2]+(f[2]-d[2])*c)]}function Vd(e){if(e==null||!Number.isFinite(e))return[148,163,184];const r=Math.max(0,Math.min(1,e/4));if(r<.4){const s=r/.4;return[Math.round(16+229*s),Math.round(185+-27*s),Math.round(129+-118*s)]}const n=(r-.4)/.6;return[Math.round(245+-1*n),Math.round(158+-95*n),Math.round(11+83*n)]}function TA(e){switch(e.trim().toUpperCase()){case"ZN":return[192,132,252];case"MG":return[74,222,128];case"FE":return[249,115,22];case"N":return[96,165,250];case"O":return[248,113,113];case"S":return[250,204,21];case"P":return[251,146,60];case"F":case"CL":return[52,211,153];case"BR":return[185,28,28];default:return[203,213,225]}}function lL(e,r=1){return r>=1?`rgb(${e[0]}, ${e[1]}, ${e[2]})`:`rgba(${e[0]}, ${e[1]}, ${e[2]}, ${r})`}function cL(e){const n=Math.max(0,Math.min(30,e))/30;if(n<.35){const i=n/.35;return[Math.round(16+29*i),Math.round(210+-70*i),Math.round(160+-25*i)]}const s=(n-.35)/.65;return[Math.round(45+-30*s),Math.round(140+-117*s),Math.round(135+-93*s)]}function Ny(e,r){const n=e[0]-r[0],s=e[1]-r[1],i=e[2]-r[2];return Math.sqrt(n*n+s*s+i*i)}function uL(e,r){return e.length!==16?r:[e[0]*r[0]+e[1]*r[1]+e[2]*r[2]+e[3],e[4]*r[0]+e[5]*r[1]+e[6]*r[2]+e[7],e[8]*r[0]+e[9]*r[1]+e[10]*r[2]+e[11]]}function EA(e,r,n){const s=[];for(let i=0;i<e.length;i++)for(let c=i+1;c<e.length;c++){const d=e[i],f=e[c];if(d.isMetal||f.isMetal||d.seqId!==f.seqId||d.resName!==f.resName)continue;const p=Ny(d.xyz,f.xyz),b=d.element==="S"||f.element==="S"?r+.35:r;p>.4&&p<=b&&s.push({a:d.xyz,b:f.xyz,colorA:d.color,colorB:f.color,radius:n})}return s}function dL(e){const{comparison:r,refInspect:n,mobInspect:s,refChainId:i,mobChainId:c,colorMode:d}=e,f=new Map,p=new Map,b=new Map,x=new Map;if(r)for(const I of r.matchedResidues)f.set(I.refSeqId,I.distanceAngstrom),p.set(I.mobSeqId,I.distanceAngstrom),b.set(I.refSeqId,I.refBFactor),x.set(I.mobSeqId,I.mobPlddt);const g=[],_=r?.refDisplayAtoms?.residues;if(_&&_.length>0)for(const I of _){const J=f.get(I.seqId)??null,ge=I.bFactor??b.get(I.seqId)??null;let le=[56,189,248];d==="bfactor"?le=Cy(ge):d==="plddt"?le=[100,116,139]:d==="deviation"&&(le=J!=null?Vd(J):[100,116,139]),g.push({kind:"ref",seqId:I.seqId,insCode:I.insCode,resName3:I.resName3,resCode1:I.resCode1,xyz:I.ca,bFactor:ge,plddt:null,deviationA:J,color:le})}else if(n){const I=n.chains.find(J=>J.chainId===i)??n.chains[0];if(I)for(const J of I.residues){if(!J.ca)continue;const ge=f.get(J.seqId)??null;let le=[56,189,248];d==="bfactor"?le=Cy(J.bOrPlddt):d==="plddt"?le=[100,116,139]:d==="deviation"&&(le=Vd(ge)),g.push({kind:"ref",seqId:J.seqId,insCode:J.insCode,resName3:J.resName3,resCode1:J.resCode1,xyz:J.ca,bFactor:J.bOrPlddt,plddt:null,deviationA:ge,color:le})}}const y=[];if(r?.mobTransformedResidues&&r.mobTransformedResidues.length>0)for(const I of r.mobTransformedResidues){const J=p.get(I.seqId)??null,ge=I.plddt??x.get(I.seqId)??null;let le=[52,211,153];d==="plddt"?le=ky(ge):d==="bfactor"?le=[100,116,139]:d==="deviation"&&(le=J!=null?Vd(J):[100,116,139]),y.push({kind:"mob",seqId:I.seqId,insCode:I.insCode,resName3:I.resName3,resCode1:I.resCode1,xyz:I.xyz,bFactor:null,plddt:ge,deviationA:J,color:le})}else if(s){const I=s.chains.find(ge=>ge.chainId===c)??s.chains[0],J=r?.transform.matrixRowMajor4x4;if(I)for(const ge of I.residues){if(!ge.ca)continue;const le=J?uL(J,ge.ca):ge.ca,D=p.get(ge.seqId)??null;let ae=[52,211,153];d==="plddt"?ae=ky(ge.bOrPlddt):d==="bfactor"?ae=[100,116,139]:d==="deviation"&&(ae=Vd(D)),y.push({kind:"mob",seqId:ge.seqId,insCode:ge.insCode,resName3:ge.resName3,resCode1:ge.resCode1,xyz:le,bFactor:null,plddt:ge.bOrPlddt,deviationA:D,color:ae})}}const S=r?.refDisplayAtoms?.ligands??n?.ligands??[],k=[];for(const I of S)for(const J of I.atoms){const ge=J.element.toUpperCase(),le=ge==="ZN"||ge==="MG"||ge==="FE"||ge==="CA"||ge==="MN";k.push({id:`lig-${I.chainId}-${I.seqId}-${I.resName}-${J.name}`,label:`${I.resName} ${I.seqId} · ${J.name}`,seqId:I.seqId,resName:I.resName,atomName:J.name,element:ge,xyz:J.xyz,radius:le?.85:.42,color:TA(ge),isLigand:!0,isMetal:le})}const E=EA(k,1.88,.22),j=(r?.refDisplayAtoms?.pocketAtoms??[]).map((I,J)=>({id:`pocket-${I.seqId}-${I.atomName}-${J}`,label:`${I.resName3}${I.seqId} · ${I.atomName}`,seqId:I.seqId,resName:I.resName3,atomName:I.atomName,element:I.element.toUpperCase(),xyz:I.xyz,radius:.3,color:I.element.toUpperCase()==="C"?[148,163,184]:TA(I.element),isLigand:!1,isMetal:!1})),q=EA(j,1.85,.16),z=[],O=r?.refContacts??[],V=new Map;for(const I of k)V.set(`${I.resName}:${I.seqId}:${I.atomName}`,I);const P=new Map;for(const I of j)P.set(`${I.seqId}:${I.atomName}`,I);const $=new Map;for(const I of g)$.set(I.seqId,I);for(const I of O){const J=V.get(`${I.ligandResName}:${I.ligandSeqId}:${I.ligandAtom}`);if(!J)continue;const le=(P.get(`${I.proteinSeqId}:${I.proteinAtom}`)??void 0)?.xyz??$.get(I.proteinSeqId)?.xyz;le&&(I.ligandResName==="ZN"||I.distanceAngstrom<=3.1)&&z.push({a:J.xyz,b:le,colorA:[216,180,254],colorB:[103,232,249],radius:.1,dashed:!0})}const H=k.find(I=>I.element==="ZN");if(H)for(const I of k)I!==H&&Ny(H.xyz,I.xyz)<=2.6&&z.push({a:H.xyz,b:I.xyz,colorA:[216,180,254],colorB:[96,165,250],radius:.11,dashed:!0});const Z=[...g.map(I=>I.xyz),...y.map(I=>I.xyz)];let G=0,K=0,we=0;for(const I of Z)G+=I[0],K+=I[1],we+=I[2];const Se=Math.max(1,Z.length),Q=[G/Se,K/Se,we/Se];let F=12;for(const I of Z){const J=Ny(I,Q);J>F&&(F=J)}let he=null;if(H)he=[...H.xyz];else{const I=g.filter(J=>J.seqId===94||J.seqId===96||J.seqId===119);if(I.length>0){const J=I.reduce((ge,le)=>[ge[0]+le.xyz[0],ge[1]+le.xyz[1],ge[2]+le.xyz[2]],[0,0,0]);he=[J[0]/I.length,J[1]/I.length,J[2]/I.length]}}const W=g.slice(0,6),me=W.length>0?[W.reduce((I,J)=>I+J.xyz[0],0)/W.length,W.reduce((I,J)=>I+J.xyz[1],0)/W.length,W.reduce((I,J)=>I+J.xyz[2],0)/W.length]:null;return{refResidues:g,mobResidues:y,pocketAtoms:j,pocketBonds:q,ligandAtoms:k,ligandBonds:E,coordinationBonds:z,center:Q,radius:F,activeSiteCenter:he,nTermCenter:me}}const hL=C.forwardRef(function({comparison:r,refInspect:n,mobInspect:s,refChainId:i,mobChainId:c,layout:d,onChangeLayout:f,style:p,onChangeStyle:b,colorMode:x,onChangeColorMode:g,focusedSeqId:_,focusCameraRequest:y,highlightedSeqIds:S,highlightSourceLabel:k,onClearHighlights:E,paePair:T,onPickResidue:j,onRendererModeDetected:q,simpleMode:z=!1},O){const V=C.useRef(null),P=C.useRef(null),$=C.useRef(null),H=C.useRef(null),Z=C.useRef([]),[G,K]=C.useState({width:800,height:420}),[we,Se]=C.useState(!1),[Q,F]=C.useState([null,null]),[he,W]=C.useState(null),me=C.useMemo(()=>dL({comparison:r,refInspect:n,mobInspect:s,refChainId:i,mobChainId:c,colorMode:x}),[r,n,s,i,c,x,S]),[I,J]=C.useState({yaw:.55,pitch:.25,distance:68,target:[0,0,0]}),ge=C.useRef("");C.useEffect(()=>{const ue=`${r?.reference.sha256??""}:${r?.mobile.sha256??""}:${me.refResidues.length}`;ue!==ge.current&&me.refResidues.length+me.mobResidues.length>0&&(ge.current=ue,J({yaw:.55,pitch:.25,distance:Math.max(36,me.radius*2.55),target:[...me.center]}))},[r,me]);const le=ue=>{const He=me.refResidues.find(Pe=>Pe.seqId===ue)??me.mobResidues.find(Pe=>Pe.seqId===ue);He&&J(Pe=>({...Pe,distance:Math.max(14,Math.min(Pe.distance,26)),target:[...He.xyz]}))};C.useEffect(()=>{y&&le(y.seqId)},[y?.nonce,y?.seqId]);const D=C.useMemo(()=>_===null?null:me.refResidues.find(ue=>ue.seqId===_)??me.mobResidues.find(ue=>ue.seqId===_)??null,[_,me.refResidues,me.mobResidues]),ae=ue=>{ue==="active-site"&&me.activeSiteCenter?(J({yaw:.9,pitch:.2,distance:20,target:[...me.activeSiteCenter]}),b("pocket")):ue==="n-terminus"&&me.nTermCenter?J({yaw:-.4,pitch:.3,distance:24,target:[...me.nTermCenter]}):J({yaw:.55,pitch:.25,distance:Math.max(36,me.radius*2.55),target:[...me.center]})},pe=()=>{const ue=P.current,He=$.current;if(!ue||!He)return null;const Pe=document.createElement("canvas");Pe.width=ue.width,Pe.height=ue.height;const ut=Pe.getContext("2d");if(!ut)return null;ut.drawImage(ue,0,0),ut.drawImage(He,0,0);const Je=window.devicePixelRatio||1;return ut.fillStyle="rgba(9, 13, 20, 0.85)",ut.fillRect(0,Pe.height-24*Je,Pe.width,24*Je),ut.fillStyle="#fbbf24",ut.font=`600 ${Math.round(11*Je)}px ui-monospace, monospace`,ut.fillText(`SYNLEXA STUDIO · RESEARCH USE ONLY (RUO) · ${r?`RMSD ${r.metrics.rmsdAngstrom.toFixed(3)} A (${r.metrics.matchedCaCount} Ca)`:"3D Structure View"}`,10*Je,Pe.height-8*Je),Pe.toDataURL("image/png")};C.useImperativeHandle(O,()=>({capturePngDataUrl:pe,applyPreset:ae}));const Ae=()=>{const ue=pe();if(!ue)return;const He=document.createElement("a");He.href=ue,He.download=`synlexa-studio-ruo-viewport-${Date.now()}.png`,He.click()};C.useEffect(()=>{const ue=V.current;if(!ue)return;const He=new ResizeObserver(Pe=>{for(const ut of Pe)K({width:Math.max(200,Math.floor(ut.contentRect.width)),height:Math.max(180,Math.floor(ut.contentRect.height))})});return He.observe(ue),()=>He.disconnect()},[]),C.useEffect(()=>{const ue=P.current;if(!ue||H.current)return;const He=new oL(ue);H.current=He,q?.(He.mode)},[q]),C.useEffect(()=>{const ue=H.current,He=$.current;if(!ue||!He)return;const Pe=Math.min(2,window.devicePixelRatio||1);Z.current=ue.render(me,{layout:d,style:p,camera:I,focusedSeqId:_,highlightedSeqIds:S,distancePair:Q,paePair:T},He,G.width,G.height,Pe)},[me,d,p,I,_,S,Q,T,G]);const Ne=C.useRef({active:!1,moved:!1,startX:0,startY:0,lastX:0,lastY:0,pan:!1}),Re=(ue,He)=>{let Pe=null,ut=1/0;for(const Je of Z.current){const re=Je.sx-ue,ve=Je.sy-He,Qe=re*re+ve*ve;if(Qe<=196){const Fe=Qe+(Je.depth+1)*15;Fe<ut&&(ut=Fe,Pe=Je)}}return Pe},$e=C.useRef(new Map),Ce=C.useRef(null),Ue=ue=>{J(He=>({...He,distance:Math.max(4,Math.min(320,He.distance*ue))}))},be=(ue,He)=>{J(Pe=>{const ut=Pe.distance*.0018,Je=Math.cos(Pe.yaw),re=Math.sin(Pe.yaw);return{...Pe,target:[Pe.target[0]-ue*ut*Je,Pe.target[1]+He*ut,Pe.target[2]+ue*ut*re]}})},bt=(ue,He)=>{J(Pe=>({...Pe,yaw:Pe.yaw-ue*.0085,pitch:Math.max(-1.45,Math.min(1.45,Pe.pitch+He*.0085))}))},Ot=()=>{const ue=Array.from($e.current.values());if(ue.length<2)return null;const[He,Pe]=ue;return{dist:Math.hypot(He.x-Pe.x,He.y-Pe.y),cx:(He.x+Pe.x)/2,cy:(He.y+Pe.y)/2}},St=ue=>{if(!ue.target.closest("[data-viewport-ui]")){if(ue.currentTarget.setPointerCapture(ue.pointerId),$e.current.set(ue.pointerId,{x:ue.clientX,y:ue.clientY}),$e.current.size===2){Ce.current=Ot(),Ne.current.moved=!0;return}Ne.current={active:!0,moved:!1,startX:ue.clientX,startY:ue.clientY,lastX:ue.clientX,lastY:ue.clientY,pan:ue.shiftKey||ue.button===2||ue.button===1}}},Ke=ue=>{const He=ue.currentTarget.getBoundingClientRect(),Pe=ue.clientX-He.left,ut=ue.clientY-He.top;if($e.current.has(ue.pointerId)&&$e.current.set(ue.pointerId,{x:ue.clientX,y:ue.clientY}),$e.current.size>=2&&Ce.current){const ve=Ot();ve&&ve.dist>0&&Ce.current.dist>0&&(Ue(Ce.current.dist/ve.dist),be(ve.cx-Ce.current.cx,ve.cy-Ce.current.cy),Ce.current=ve);return}if(!Ne.current.active){if(ue.pointerType==="mouse"){const ve=Re(Pe,ut);W(ve?ve.label:null)}return}const Je=ue.clientX-Ne.current.lastX,re=ue.clientY-Ne.current.lastY;(Math.abs(ue.clientX-Ne.current.startX)>3||Math.abs(ue.clientY-Ne.current.startY)>3)&&(Ne.current.moved=!0),Ne.current.lastX=ue.clientX,Ne.current.lastY=ue.clientY,Ne.current.pan?be(Je,re):bt(Je,re)},et=ue=>{const He=$e.current.size>=2;if($e.current.delete(ue.pointerId),$e.current.size<2&&(Ce.current=null),He){Ne.current.active=!1;return}if(!Ne.current.active)return;const Pe=Ne.current.moved;if(Ne.current.active=!1,Pe)return;const ut=ue.currentTarget.getBoundingClientRect(),Je=Re(ue.clientX-ut.left,ue.clientY-ut.top);if(Je)if(we){const re=me.refResidues.find(ve=>ve.seqId===Je.seqId)??me.mobResidues.find(ve=>ve.seqId===Je.seqId)??null;re&&F(([ve,Qe])=>!ve||ve&&Qe?[re,null]:[ve,re])}else j(Je.seqId)};return C.useEffect(()=>{const ue=V.current;if(!ue)return;const He=ve=>{if(ve.target.closest("[data-viewport-ui]"))return;ve.preventDefault();const Qe=ve.deltaMode===1?16:ve.deltaMode===2?400:1,Fe=ve.deltaY*Qe;ve.ctrlKey?Ue(Math.exp(Fe*.012)):ve.shiftKey?be(-ve.deltaX*Qe,-Fe):Ue(Math.exp(Fe*.0015))};let Pe=0;const ut=ve=>{ve.preventDefault(),J(Qe=>(Pe=Qe.distance,Qe))},Je=ve=>{ve.preventDefault();const Qe=ve.scale??1;Pe>0&&Qe>0&&J(Fe=>({...Fe,distance:Math.max(4,Math.min(320,Pe/Qe))}))},re=ve=>ve.preventDefault();return ue.addEventListener("wheel",He,{passive:!1}),ue.addEventListener("gesturestart",ut,{passive:!1}),ue.addEventListener("gesturechange",Je,{passive:!1}),ue.addEventListener("gestureend",re,{passive:!1}),()=>{ue.removeEventListener("wheel",He),ue.removeEventListener("gesturestart",ut),ue.removeEventListener("gesturechange",Je),ue.removeEventListener("gestureend",re)}},[]),o.jsxs("div",{ref:V,onContextMenu:ue=>ue.preventDefault(),onPointerDown:St,onPointerMove:Ke,onPointerUp:et,onPointerCancel:et,onPointerLeave:ue=>{ue.pointerType==="mouse"&&!Ne.current.active&&W(null)},style:{touchAction:"none"},className:"relative h-full w-full cursor-grab overflow-hidden bg-[#090d14] select-none overscroll-none active:cursor-grabbing",children:[o.jsx("canvas",{ref:P,className:"absolute inset-0 h-full w-full"}),o.jsx("canvas",{ref:$,className:"pointer-events-none absolute inset-0 h-full w-full"}),o.jsxs("div",{"data-viewport-ui":!0,className:"pointer-events-none absolute top-2.5 right-2.5 left-2.5 flex flex-wrap items-center justify-between gap-2",children:[o.jsx("div",{className:"pointer-events-auto flex flex-wrap items-center gap-1 rounded-xl border border-white/10 bg-[#0d121b]/85 p-1 shadow-xl backdrop-blur-md",children:[["overlay","Overlay","Superpose both structures on the same coordinates"],["split","Split","Show reference and comparison side-by-side"],["reference","Ref Only","Show only the experimental/reference structure"],["mobile","Pred Only","Show only the predicted/mobile structure"]].map(([ue,He,Pe])=>o.jsxs("button",{type:"button",title:Pe,onClick:()=>f(ue),className:`flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] font-medium transition ${d===ue?"bg-white/[0.12] text-white shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:[ue==="split"&&o.jsx(W6,{className:"h-3.5 w-3.5"}),o.jsx("span",{children:He})]},ue))}),o.jsx("div",{className:"pointer-events-auto flex flex-wrap items-center gap-1 rounded-xl border border-white/10 bg-[#0d121b]/85 p-1 shadow-xl backdrop-blur-md",children:[["ribbon","Ribbon","Smooth backbone ribbon representation"],["trace","Cα Trace","Minimal alpha-carbon wire trace"],["pocket","Active Pocket","Highlight co-crystal ligand, metal ion & pocket sidechains"]].map(([ue,He,Pe])=>o.jsx("button",{type:"button",title:Pe,onClick:()=>b(ue),className:`rounded-lg px-2.5 py-1 text-[0.75rem] font-medium transition ${p===ue?"bg-white/[0.12] text-white shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:He},ue))}),o.jsx("div",{className:"pointer-events-auto flex flex-wrap items-center gap-1 rounded-xl border border-white/10 bg-[#0d121b]/85 p-1 shadow-xl backdrop-blur-md",children:[["identity","Identity","Color by structure (blue = reference, green = prediction)"],["plddt","pLDDT","Color by AlphaFold confidence score (0–100)"],["bfactor","B-Factor (Ų)","Color by crystallographic B-factor flexibility"],["deviation","Δd (Å)","Color by per-residue Cα distance between structures"]].map(([ue,He,Pe])=>o.jsx("button",{type:"button",title:Pe,onClick:()=>g(ue),className:`rounded-lg px-2.5 py-1 text-[0.75rem] font-medium transition ${x===ue?"bg-white/[0.12] text-white shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:He},ue))})]}),(D||S.size>0)&&o.jsxs("div",{"data-viewport-ui":!0,className:"pointer-events-none absolute top-14 right-2.5 left-2.5 flex flex-wrap items-center gap-1.5",children:[D&&o.jsxs("button",{type:"button",onClick:()=>le(D.seqId),title:"Click to center 3D camera on this residue",className:"pointer-events-auto inline-flex items-center gap-1.5 rounded-lg border border-amber-400/40 bg-[#0d121b]/85 px-2.5 py-1 font-mono text-[0.6875rem] text-amber-200 shadow backdrop-blur-md hover:border-amber-300",children:[o.jsx(Ur,{className:"h-3 w-3 text-amber-300"}),o.jsxs("span",{children:[D.resName3," ",D.seqId,D.deviationA!=null?` · Δd ${D.deviationA.toFixed(2)} Å`:"",D.plddt!=null?` · pLDDT ${D.plddt.toFixed(0)}`:""]}),o.jsx("span",{className:"text-amber-300/75",children:"Center"})]}),S.size>0&&o.jsxs("span",{className:"pointer-events-auto inline-flex items-center gap-1.5 rounded-lg border border-pink-400/40 bg-[#0d121b]/85 px-2.5 py-1 font-mono text-[0.6875rem] text-pink-200 shadow backdrop-blur-md",children:[o.jsx("span",{className:"h-2 w-2 rounded-full bg-pink-400"}),o.jsxs("span",{children:[S.size," highlighted",k?` (${k})`:""]}),E&&o.jsx("button",{type:"button",onClick:E,title:"Clear 3D highlights",className:"rounded p-0.5 text-pink-300 hover:bg-white/10 hover:text-white",children:o.jsx(Xi,{className:"h-3 w-3"})})]})]}),o.jsxs("div",{"data-viewport-ui":!0,className:"pointer-events-none absolute right-2.5 bottom-2.5 left-2.5 flex flex-wrap items-end justify-between gap-2",children:[o.jsxs("div",{className:"pointer-events-auto flex flex-wrap items-center gap-1 rounded-xl border border-white/10 bg-[#0d121b]/85 p-1 shadow-xl backdrop-blur-md",children:[o.jsxs("button",{type:"button",onClick:()=>ae("overview"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-300 hover:bg-white/[0.07]",children:[o.jsx(Oy,{className:"h-3.5 w-3.5"})," Overview"]}),o.jsxs("button",{type:"button",onClick:()=>ae("active-site"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-200 hover:bg-white/[0.07]",children:[o.jsx(Ur,{className:"h-3.5 w-3.5"})," Active Site"]}),!z&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",onClick:()=>ae("n-terminus"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-300 hover:bg-white/[0.07]",children:[o.jsx(OR,{className:"h-3.5 w-3.5"})," N-Term"]}),o.jsx("button",{type:"button",onClick:()=>ae("reset"),className:"rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-400 hover:bg-white/[0.07] hover:text-slate-200",children:"Reset"}),o.jsx("span",{className:"mx-0.5 h-3.5 w-px bg-slate-800"}),o.jsxs("button",{type:"button",onClick:()=>{Se(ue=>!ue),we&&F([null,null])},className:`flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] transition ${we?"border border-rose-500/50 bg-rose-500/20 text-rose-200":"text-slate-300 hover:bg-white/[0.07]"}`,children:[o.jsx(q6,{className:"h-3.5 w-3.5"}),o.jsx("span",{children:we?"Pick 2 Residues":"Distance (Å)"})]})]}),o.jsxs("button",{type:"button",onClick:Ae,className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[0.75rem] text-slate-200 hover:bg-white/[0.07]",children:[o.jsx(bR,{className:"h-3.5 w-3.5"})," PNG"]})]}),o.jsxs("div",{className:"pointer-events-auto flex items-center gap-2 rounded-xl border border-white/10 bg-[#0d121b]/85 px-3 py-1.5 font-mono text-[0.75rem] text-slate-300 shadow-lg backdrop-blur-md",children:[he&&o.jsx("span",{className:"border-r border-slate-700 pr-2 text-amber-300",children:he}),x==="identity"&&o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("i",{className:"inline-block h-2 w-2 rounded-full bg-sky-400"})," Ref"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("i",{className:"inline-block h-2 w-2 rounded-full bg-emerald-400"})," Pred"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("i",{className:"inline-block h-2 w-2 rounded-full bg-purple-400"})," Zn²⁺"]})]}),x==="plddt"&&o.jsxs("span",{className:"flex items-center gap-1.5",title:"AlphaFold pLDDT confidence (distinct from B-factor)",children:[o.jsx("span",{className:"text-slate-400",children:"pLDDT:"}),o.jsx("span",{className:"text-[#2684ff]",children:"■ ≥90"}),o.jsx("span",{className:"text-[#65cbf3]",children:"■ 70-90"}),o.jsx("span",{className:"text-[#ffdb13]",children:"■ 50-70"}),o.jsx("span",{className:"text-[#ff7d45]",children:"■ <50"})]}),x==="bfactor"&&o.jsxs("span",{className:"flex items-center gap-1.5",title:"Experimental B-factor in Angstrom^2 (Plasma scale, never conflated with pLDDT)",children:[o.jsx("span",{className:"text-slate-400",children:"Exp B (Ų):"}),o.jsx("span",{className:"inline-block h-2 w-16 rounded-xs bg-gradient-to-r from-[#622dba] via-[#de4968] to-[#fcf498]"}),o.jsx("span",{children:"4 → 50+"})]}),x==="deviation"&&o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"text-slate-400",children:"Δd (Å):"}),o.jsx("span",{className:"inline-block h-2 w-16 rounded-xs bg-gradient-to-r from-emerald-500 via-amber-500 to-rose-500"}),o.jsx("span",{children:"0 → 4+"})]})]})]})]})});function mL({state:e,dispatch:r,result:n,error:s,onFocusResidue:i,simpleMode:c=!1,bridge:d}){const[f,p]=C.useState(""),[b,x]=C.useState(!1),[g,_]=C.useState(!1),[y,S]=C.useState(e.sequence),[k,E]=C.useState(null),T=e.focusSeqId??d?.focusedSeqId??null,j=e.sequence.startsWith("MSHHWGYGKHNGPEHWHK"),q=()=>{const P=f.trim().toUpperCase();P&&(r({type:"add_mutation",notation:P}),p(""))},z=C.useMemo(()=>{if(!T||T<1||T>e.sequence.length)return[];const P=e.sequence[T-1];return P?["A","R","D","W"].filter(H=>H!==P).map(H=>({notation:`${P}${T}${H}`,label:H==="A"?"Ala Scan":H==="R"?"+Charge":H==="D"?"−Charge":"Bulky Trp"})):[]},[T,e.sequence]),O=C.useMemo(()=>{const P=e.sequence.length;if(P===0)return[];const $=T&&T>=1&&T<=P?T:Math.min(P,Math.max(1,e.sliceStart+10)),H=Math.max(1,$-10),Z=Math.min(P,H+20),G=new Map;for(const we of n?.appliedMutations??[])G.set(we.pos,we.to);const K=[];for(let we=H;we<=Z;we++){const Se=e.sequence[we-1]??"X",Q=G.get(we);K.push({pos:we,wt:Se,eng:Q??Se,mutated:!!Q})}return K},[e.sequence,e.sliceStart,T,n?.appliedMutations]),V=(P,$=!1)=>{r({type:"focus_residue",seqId:P}),i(P),$&&d?.focusIn3D(P,{centerCamera:!0})};return o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3 text-xs @xl:p-4",children:[o.jsx(ir,{bridge:d,title:"Peptide & Protein Engineering Workbench",subtitle:"Test point mutations and sequence slices, inspect pH 0–14 titration & Kyte-Doolittle shifts, and map 3D contact shells.",icon:o.jsx(ar,{className:"h-4 w-4"}),guideOpen:b,onToggleGuide:()=>x(P=>!P),actions:d&&o.jsxs("button",{type:"button",onClick:()=>{d.savePeptideToProject({name:e.mutations.length>0?e.mutations.join(", "):`Peptide (${e.sliceStart}–${e.sliceEnd})`,sequence:e.sequence,mutations:e.mutations}),E("Saved"),setTimeout(()=>E(null),1600)},className:"inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs font-medium text-slate-200 hover:border-sky-400/40",children:[o.jsx(Qc,{className:"h-3.5 w-3.5 text-sky-300"}),o.jsx("span",{children:k?"Saved!":"Save Variant"})]})}),o.jsx(Qi,{open:b,title:"How Peptide Engineering Works",summary:"Simulate amino-acid substitutions (e.g. H94A) or sequence truncations against the active protein chain in deterministic Rust/WASM. Side-by-side biophysical deltas compare Wild-Type (WT) vs Engineered sequences.",steps:["Click a residue on the sequence strip below (or pick any residue in the 3D Viewer) and click one of the dynamic mutation chips (e.g. Ala Scan) or type any mutation like H94A.","Adjust Slice Start/End to evaluate a cleaved domain or peptide fragment.","Hover the pH 0–14 Titration or Kyte-Doolittle charts to inspect exact shifts, and click any 3D < 5.0 Å neighbor to jump to it in 3D."],connectionTip:"Syncs directly with your loaded 3D structure's sequence and active pocket. Clicking 'Highlight Shell in 3D' illuminates every neighboring residue within 5.0 Å of the mutated site right on the 3D structure.",glossary:[{term:"pI (Isoelectric Point)",desc:"pH where net peptide charge is 0 (Henderson-Hasselbalch model). Shifts affect solubility & purification."},{term:"GRAVY",desc:"Grand Average of Hydropathy (Kyte-Doolittle). Positive = hydrophobic; negative = hydrophilic/soluble."},{term:"ε280 (M⁻¹cm⁻¹)",desc:"Molar extinction coefficient at 280 nm from Trp, Tyr, and cystine disulfide pairs."},{term:"Steric ΔV (ų)",desc:"Net side-chain volume change from substitutions; large positive/negative ΔV inside a packed core can introduce clashes or cavities."}]}),o.jsxs("div",{className:"space-y-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("input",{value:f,onChange:P=>p(P.target.value),onKeyDown:P=>{P.key==="Enter"&&q()},placeholder:"Mutation (e.g. H94A)",className:"h-8 w-36 rounded-lg border border-white/10 bg-slate-950 px-2.5 font-mono text-xs text-slate-100 placeholder-slate-500 outline-none focus:border-cyan-500"}),o.jsxs("button",{type:"button",onClick:q,className:"flex h-8 items-center gap-1 rounded-lg border border-cyan-500/40 bg-cyan-500/15 px-2.5 text-xs font-medium text-cyan-200 hover:bg-cyan-500/25",children:[o.jsx(gh,{className:"h-3.5 w-3.5"})," Add"]})]}),e.mutations.map(P=>o.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-emerald-500/40 bg-emerald-500/15 px-2 py-1 font-mono text-[0.75rem] text-emerald-200",children:[P,o.jsx("button",{type:"button",onClick:()=>r({type:"remove_mutation",notation:P}),className:"text-emerald-300 hover:text-white","aria-label":`Remove ${P}`,children:o.jsx(Xi,{className:"h-3 w-3"})})]},P)),e.mutations.length>0&&o.jsx("button",{type:"button",onClick:()=>r({type:"set_mutations_input",raw:""}),className:"rounded-md px-2 py-1 text-[0.6875rem] text-slate-400 hover:bg-white/[0.06] hover:text-slate-200",children:"Clear all"})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2 font-mono text-[0.75rem]",children:[o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/10 bg-slate-950/70 px-2 py-1",children:[o.jsx(ar,{className:"h-3 w-3 text-slate-400"}),o.jsx("span",{className:"text-slate-400",children:"Slice"}),o.jsx("input",{type:"number",min:1,max:Math.max(1,e.sequence.length),value:e.sliceStart,onChange:P=>r({type:"set_slice",start:Number(P.target.value)||1,end:e.sliceEnd}),className:"w-14 rounded border border-white/10 bg-slate-900 px-1.5 py-0.5 text-slate-200"}),o.jsx("span",{className:"text-slate-500",children:"–"}),o.jsx("input",{type:"number",min:e.sliceStart,max:Math.max(1,e.sequence.length),value:e.sliceEnd,onChange:P=>r({type:"set_slice",start:e.sliceStart,end:Number(P.target.value)||e.sequence.length}),className:"w-14 rounded border border-white/10 bg-slate-900 px-1.5 py-0.5 text-slate-200"}),o.jsxs("span",{className:"text-[0.6875rem] text-slate-500",children:["/ ",e.sequence.length," aa"]})]}),d&&o.jsxs("div",{className:"flex items-center gap-1 font-sans",children:[d.hasRef&&o.jsxs("button",{type:"button",onClick:()=>d.syncPeptideFromChain("reference"),title:"Load amino-acid sequence from active 3D Reference chain",className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-sky-300 hover:border-sky-400/40",children:[o.jsx(gp,{className:"h-3 w-3"})," Sync Ref"]}),d.hasMob&&o.jsxs("button",{type:"button",onClick:()=>d.syncPeptideFromChain("mobile"),title:"Load amino-acid sequence from active 3D Comparison chain",className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-emerald-300 hover:border-emerald-400/40",children:[o.jsx(gp,{className:"h-3 w-3"})," Sync Mob"]})]}),o.jsxs("button",{type:"button",onClick:()=>{S(e.sequence),_(P=>!P)},className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 font-sans text-[0.6875rem] text-slate-300 hover:border-white/25",children:[o.jsx(T6,{className:"h-3 w-3"})," ",g?"Hide Seq":"Edit Seq"]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-t border-white/[0.06] pt-2",children:[z.length>0&&T!==null&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-[0.6875rem] font-medium text-amber-300",children:["At #",T,":"]}),z.map(P=>o.jsxs("button",{type:"button",onClick:()=>r({type:"add_mutation",notation:P.notation}),className:"rounded-md border border-amber-400/30 bg-amber-500/10 px-2 py-0.5 font-mono text-[0.6875rem] text-amber-200 hover:bg-amber-500/20",children:["+",P.notation," ",o.jsxs("span",{className:"font-sans text-amber-300/75",children:["(",P.label,")"]})]},P.notation))]}),j&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ml-1 text-[0.6875rem] text-slate-500",children:"CA II Active Site:"}),["H94A","T199V","H96A","H119A"].map(P=>o.jsxs("button",{type:"button",onClick:()=>r({type:"add_mutation",notation:P}),className:"rounded-md border border-white/10 bg-slate-900 px-2 py-0.5 font-mono text-[0.6875rem] text-slate-300 hover:border-emerald-500/50 hover:text-emerald-200",children:["+",P]},P))]})]}),g&&o.jsxs("div",{className:"space-y-1.5 border-t border-white/[0.06] pt-2",children:[o.jsx("textarea",{rows:3,value:y,onChange:P=>S(P.target.value),placeholder:"Paste 1-letter protein/peptide sequence…",className:"w-full rounded-lg border border-white/10 bg-slate-950 p-2 font-mono text-xs text-slate-100 outline-none focus:border-sky-500"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{type:"button",onClick:()=>_(!1),className:"rounded-md px-2.5 py-1 text-xs text-slate-400 hover:text-white",children:"Cancel"}),o.jsx("button",{type:"button",onClick:()=>{r({type:"set_sequence",sequence:y}),_(!1)},className:"rounded-md bg-sky-500 px-3 py-1 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:"Apply Sequence"})]})]}),O.length>0&&o.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto border-t border-white/[0.06] pt-2 pb-0.5",children:[o.jsx("span",{className:"mr-1 shrink-0 font-mono text-[0.6875rem] text-slate-500",children:"Window:"}),O.map(P=>{const $=P.pos===T;return o.jsxs("button",{type:"button",onClick:()=>V(P.pos,!0),title:`Residue ${P.pos}: WT ${P.wt}${P.mutated?` → ${P.eng}`:""} (click to focus in 3D)`,className:`flex min-w-7 shrink-0 flex-col items-center rounded-md border px-1 py-0.5 font-mono transition ${$?"border-amber-400 bg-amber-500/20 text-amber-200":P.mutated?"border-emerald-400/50 bg-emerald-500/15 text-emerald-200":"border-white/[0.06] bg-black/25 text-slate-300 hover:border-sky-400/40"}`,children:[o.jsx("span",{className:"text-[0.5625rem] text-slate-500",children:P.pos}),o.jsx("span",{className:"text-[0.75rem] font-semibold",children:P.mutated?`${P.wt}→${P.eng}`:P.wt})]},P.pos)})]})]}),s&&o.jsx("div",{className:"rounded-xl border border-rose-500/40 bg-rose-500/10 px-3 py-2 font-mono text-xs text-rose-200",children:s}),n&&o.jsxs("div",{className:"grid grid-cols-1 gap-3 @4xl:grid-cols-2 @6xl:grid-cols-12",children:[o.jsxs("div",{className:"flex flex-col gap-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @6xl:col-span-4",children:[o.jsxs("div",{className:"flex items-center justify-between font-mono text-[0.75rem]",children:[o.jsx("span",{className:"font-semibold text-cyan-300",children:"WT vs ENGINEERED DELTAS"}),o.jsxs("span",{className:"text-slate-400",children:[n.engineered.length," aa"]})]}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full font-mono text-[0.75rem]",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-white/10 text-slate-500",children:[o.jsx("th",{className:"py-1.5 text-left",children:"Metric"}),o.jsx("th",{className:"py-1.5 text-right",children:"WT"}),o.jsx("th",{className:"py-1.5 text-right",children:"Eng"}),o.jsx("th",{className:"py-1.5 text-right",children:"Δ"})]})}),o.jsxs("tbody",{className:"divide-y divide-white/[0.06] text-slate-200",children:[o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"Avg MW (Da)"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.mwAverageDa.toFixed(1)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.mwAverageDa.toFixed(1)}),o.jsxs("td",{className:"py-1.5 text-right text-cyan-300",children:[n.deltas.mwAverageDa>=0?"+":"",n.deltas.mwAverageDa.toFixed(1)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"Mono MW (Da)"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.mwMonoisotopicDa.toFixed(1)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.mwMonoisotopicDa.toFixed(1)}),o.jsxs("td",{className:"py-1.5 text-right text-cyan-300",children:[n.deltas.mwMonoisotopicDa>=0?"+":"",n.deltas.mwMonoisotopicDa.toFixed(1)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"pI"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.pi.toFixed(2)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.pi.toFixed(2)}),o.jsxs("td",{className:"py-1.5 text-right text-amber-300",children:[n.deltas.pi>=0?"+":"",n.deltas.pi.toFixed(3)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"Charge pH 7.4"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.chargeAtPh74.toFixed(2)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.chargeAtPh74.toFixed(2)}),o.jsxs("td",{className:"py-1.5 text-right text-emerald-300",children:[n.deltas.chargeAtPh74>=0?"+":"",n.deltas.chargeAtPh74.toFixed(2)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"GRAVY"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.gravy.toFixed(3)}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.gravy.toFixed(3)}),o.jsxs("td",{className:"py-1.5 text-right text-violet-300",children:[n.deltas.gravy>=0?"+":"",n.deltas.gravy.toFixed(3)]})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"ε280 (red/ox)"}),o.jsx("td",{className:"py-1.5 text-right",children:n.wildType.extinctionReduced}),o.jsx("td",{className:"py-1.5 text-right",children:n.engineered.extinctionCystine}),o.jsx("td",{className:"py-1.5 text-right text-slate-400",children:"M⁻¹cm⁻¹"})]}),o.jsxs("tr",{children:[o.jsx("td",{className:"py-1.5 text-slate-400",children:"Steric ΔV"}),o.jsx("td",{className:"py-1.5 text-right",children:"—"}),o.jsx("td",{className:"py-1.5 text-right",children:"—"}),o.jsxs("td",{className:"py-1.5 text-right text-amber-300",children:[n.deltas.stericVolumeDeltaA3>=0?"+":"",n.deltas.stericVolumeDeltaA3.toFixed(1)," ų"]})]})]})]})}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsx(bs,{label:"Aromatic Fraction",value:`${(n.engineered.aromaticFraction*100).toFixed(1)}%`,hint:"Trp + Tyr + Phe"}),o.jsx(bs,{label:"Hydrophobic",value:`${(n.engineered.hydrophobicFraction*100).toFixed(1)}%`,hint:"Nonpolar residues"})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx(Ca,{insight:yA(n.engineered.pi,n.engineered.chargeAtPh74),compact:!0}),o.jsx(Ca,{insight:_A(n.engineered.gravy),compact:!0})]}),o.jsxs("p",{className:"text-[0.6875rem] leading-relaxed text-slate-400",children:[yA(n.engineered.pi,n.engineered.chargeAtPh74).explanation,c?"":` ${_A(n.engineered.gravy).explanation}`]})]}),o.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @6xl:col-span-5",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 font-mono text-[0.75rem]",children:[o.jsx("span",{className:"font-semibold text-cyan-300",children:"pH 0–14 TITRATION & KYTE-DOOLITTLE PROFILE"}),o.jsxs("span",{className:"flex items-center gap-3 text-[0.6875rem]",children:[o.jsx("span",{className:"text-sky-400",children:"— WT"}),o.jsx("span",{className:"text-emerald-400",children:"-- Engineered"})]})]}),o.jsx(fL,{curve:n.titrationCurve}),o.jsx(pL,{profile:n.gravyProfile,focusedPos:T,onPickPos:P=>V(P,!0)})]}),o.jsxs("div",{className:"flex flex-col gap-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @4xl:col-span-2 @6xl:col-span-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("span",{className:"font-mono text-[0.75rem] font-semibold text-violet-300",children:["3D <5.0 Å CONTACT SHELL",T!=null?` (RES ${T})`:""]}),d&&n.local3dContacts.length>0&&o.jsxs("button",{type:"button",onClick:()=>d.highlightIn3D(n.local3dContacts.map(P=>P.seqId),`Peptide Shell #${T??""}`,{focusSeqId:T??void 0,style:"pocket"}),className:"inline-flex items-center gap-1 rounded-md border border-violet-400/40 bg-violet-500/15 px-2 py-0.5 text-[0.6875rem] font-medium text-violet-200 hover:bg-violet-500/25",children:[o.jsx(_s,{className:"h-3 w-3"})," Show in 3D"]})]}),n.local3dContacts.length===0?o.jsx("div",{className:"flex flex-1 flex-col justify-center gap-2 rounded-lg border border-white/[0.06] bg-black/20 p-3 text-slate-400",children:o.jsx("p",{children:"Select a residue (e.g. click in the 3D Viewer or sequence window above) or apply a mutation like H94A to inspect its 3D <5.0 Å neighbor shell."})}):o.jsx("div",{className:"max-h-60 space-y-1.5 overflow-y-auto pr-0.5 font-mono text-[0.75rem]",children:n.local3dContacts.map(P=>o.jsxs("button",{type:"button",onClick:()=>V(P.seqId,!0),className:`flex w-full items-center justify-between rounded-lg border px-2.5 py-1.5 text-left transition ${P.seqId===T?"border-amber-400/60 bg-amber-500/10":"border-white/[0.07] bg-black/30 hover:border-cyan-400/50"}`,children:[o.jsxs("span",{className:"text-slate-200",children:[P.resName3," ",P.seqId]}),o.jsxs("span",{className:"text-emerald-300",children:[P.distanceAngstrom.toFixed(2)," Å"]})]},`${P.seqId}-${P.resName3}`))}),d&&T!==null&&o.jsxs("div",{className:"mt-auto flex flex-wrap gap-1.5 border-t border-white/[0.06] pt-2",children:[o.jsxs("button",{type:"button",onClick:()=>d.focusIn3D(T,{centerCamera:!0,openViewer:"activate"}),className:"inline-flex items-center gap-1 rounded-md border border-sky-400/40 bg-sky-500/15 px-2 py-1 text-[0.6875rem] font-medium text-sky-200 hover:bg-sky-500/25",children:[o.jsx(Ur,{className:"h-3 w-3"})," Focus #",T," in 3D"]}),o.jsxs("button",{type:"button",onClick:()=>d.sendResidueToCrispr(T),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-emerald-400/40",children:[o.jsx(Fs,{className:"h-3 w-3 text-emerald-300"})," Codon #",T]})]})]})]})]})}function fL({curve:e}){const[r,n]=C.useState(null);if(e.length<2)return null;const s=360,i=110,c=Math.min(...e.flatMap(E=>[E.wtCharge,E.engCharge]),-10),d=Math.max(...e.flatMap(E=>[E.wtCharge,E.engCharge]),10),f=Math.max(1,d-c),p=E=>28+E/14*(s-40),b=E=>i-18-(E-c)/f*(i-28),x=e.map((E,T)=>`${T===0?"M":"L"}${p(E.ph).toFixed(1)},${b(E.wtCharge).toFixed(1)}`).join(" "),g=e.map((E,T)=>`${T===0?"M":"L"}${p(E.ph).toFixed(1)},${b(E.engCharge).toFixed(1)}`).join(" "),_=b(0),y=p(7.4),S=r!==null?e[r]:null,k=E=>{const T=E.currentTarget.getBoundingClientRect(),j=(E.clientX-T.left)/T.width*s,q=Math.max(0,Math.min(14,(j-28)/(s-40)*14));let z=0,O=1/0;e.forEach((V,P)=>{const $=Math.abs(V.ph-q);$<O&&(O=$,z=P)}),n(z)};return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between font-mono text-[0.6875rem] text-slate-400",children:[o.jsx("span",{children:"Net Charge vs pH (0–14)"}),S?o.jsxs("span",{className:"text-slate-200",children:["pH ",S.ph.toFixed(1)," · WT ",S.wtCharge.toFixed(2)," · Eng ",S.engCharge.toFixed(2)]}):o.jsx("span",{children:"Hover curve to inspect"})]}),o.jsxs("svg",{viewBox:`0 0 ${s} ${i}`,onMouseMove:k,onMouseLeave:()=>n(null),className:"w-full cursor-crosshair rounded-lg border border-white/[0.06] bg-black/35",children:[o.jsx("line",{x1:28,y1:_,x2:s-12,y2:_,stroke:"#334155",strokeDasharray:"3,3",strokeWidth:1}),o.jsx("line",{x1:y,y1:6,x2:y,y2:i-14,stroke:"#f59e0b",strokeDasharray:"2,2",strokeWidth:1}),o.jsx("path",{d:x,fill:"none",stroke:"#38bdf8",strokeWidth:1.8}),o.jsx("path",{d:g,fill:"none",stroke:"#34d399",strokeWidth:1.6,strokeDasharray:"4,2"}),S&&o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:p(S.ph),y1:6,x2:p(S.ph),y2:i-14,stroke:"rgba(148,163,184,0.45)",strokeWidth:1}),o.jsx("circle",{cx:p(S.ph),cy:b(S.wtCharge),r:3,fill:"#38bdf8"}),o.jsx("circle",{cx:p(S.ph),cy:b(S.engCharge),r:3,fill:"#34d399"})]}),o.jsx("text",{x:6,y:_+3,fill:"#64748b",fontSize:8,fontFamily:"monospace",children:"0"}),o.jsx("text",{x:y+3,y:13,fill:"#fbbf24",fontSize:8,fontFamily:"monospace",children:"pH 7.4"}),o.jsx("text",{x:28,y:i-4,fill:"#64748b",fontSize:8,fontFamily:"monospace",children:"0"}),o.jsx("text",{x:s/2,y:i-4,fill:"#64748b",fontSize:8,fontFamily:"monospace",children:"7"}),o.jsx("text",{x:s-20,y:i-4,fill:"#64748b",fontSize:8,fontFamily:"monospace",children:"14"})]})]})}function pL({profile:e,focusedPos:r,onPickPos:n}){const[s,i]=C.useState(null);if(e.length<2)return null;const c=360,d=88,f=S=>10+S/Math.max(1,e.length-1)*(c-20),p=S=>d/2-S/5*(d/2-10),b=e.map((S,k)=>`${k===0?"M":"L"}${f(k).toFixed(1)},${p(S.wtScore).toFixed(1)}`).join(" "),x=e.map((S,k)=>`${k===0?"M":"L"}${f(k).toFixed(1)},${p(S.engScore).toFixed(1)}`).join(" "),g=s!==null?e[s]:null,_=r!==null?e.findIndex(S=>S.index===r):-1,y=S=>{const k=S.currentTarget.getBoundingClientRect(),E=(S.clientX-k.left)/k.width*c,T=Math.max(0,Math.min(1,(E-10)/(c-20)));return Math.round(T*(e.length-1))};return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between font-mono text-[0.6875rem] text-slate-400",children:[o.jsx("span",{children:"Kyte-Doolittle Hydropathy"}),g?o.jsxs("span",{className:"text-slate-200",children:["Res ",g.index," (",g.res,") · WT ",g.wtScore.toFixed(2)," · Eng ",g.engScore.toFixed(2)]}):o.jsx("span",{children:"Click profile to focus 3D residue"})]}),o.jsxs("svg",{viewBox:`0 0 ${c} ${d}`,onMouseMove:S=>i(y(S)),onMouseLeave:()=>i(null),onClick:S=>{const k=y(S),E=e[k];E&&n(E.index)},className:"w-full cursor-pointer rounded-lg border border-white/[0.06] bg-black/35",children:[o.jsx("line",{x1:10,y1:d/2,x2:c-10,y2:d/2,stroke:"#1e293b",strokeWidth:1}),o.jsx("path",{d:b,fill:"none",stroke:"#38bdf8",strokeWidth:1.3,opacity:.85}),o.jsx("path",{d:x,fill:"none",stroke:"#34d399",strokeWidth:1.3,strokeDasharray:"3,2",opacity:.95}),_>=0&&o.jsx("line",{x1:f(_),y1:4,x2:f(_),y2:d-4,stroke:"#fbbf24",strokeWidth:1.4}),g&&s!==null&&o.jsx("circle",{cx:f(s),cy:p(g.engScore),r:3,fill:"#fbbf24"})]})]})}const gL={all:"All Tiers","tier0-core":"Tier 0 · Instant Wasm/Rust","tier1-wasm":"Tier 1 · Browser Engine","tier2-compute":"Tier 2 · External GPU/HPC",database:"Public Databases"},bL=JSON.stringify({schemaVersion:"1.0.0",id:"org.lab.custom-scorer",name:"Custom Scoring Adapter",version:"0.1.0",category:"Cheminformatics ML",tier:"tier2-compute",license:"MIT",commercialSafe:!0,ruoRequired:!0,description:"Example user add-on wrapping a custom scoring script on a connected Compute Node.",computeAdapterId:"ml_property",mcpTools:[{name:"run_custom_ml_scorer",description:"Score candidate SMILES with custom Chemprop/DeepChem checkpoint.",computeToolId:"ml_property",inputSchema:{type:"object",properties:{smiles:{type:"string",description:"Input SMILES"}},required:["smiles"]}}]},null,2);function xL({onOpenComputeNodes:e,onOpenMcpServer:r,onOpenToolTab:n}){const[s,i]=C.useState(()=>Jd()),[c,d]=C.useState(""),[f,p]=C.useState("all"),[b,x]=C.useState(!1),[g,_]=C.useState(bL),[y,S]=C.useState(null);C.useEffect(()=>(i(Jd()),gD(()=>i(Jd()))),[]);const k=C.useMemo(()=>{const T=c.trim().toLowerCase();return s.filter(j=>f!=="all"&&j.tier!==f?!1:T?`${j.name} ${j.category} ${j.license} ${j.description}`.toLowerCase().includes(T):!0)},[s,c,f]),E=()=>{S(null);try{yD(g),x(!1)}catch(T){S(T instanceof Error?T.message:String(T))}};return o.jsx("div",{className:"@container h-full min-h-0 overflow-y-auto p-3 text-xs @xl:p-4",children:o.jsxs("div",{className:"mx-auto max-w-6xl space-y-4",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsxs("h2",{className:"flex items-center gap-2 text-base font-semibold text-slate-100",children:[o.jsx(Lp,{className:"h-4 w-4 text-sky-400"}),"Biochemistry Plugins & Add-ons"]}),o.jsxs("p",{className:"mt-1 text-slate-400",children:["Manage built-in open-source engines, external GPU adapters, database connectors, and custom"," ",o.jsx("code",{className:"text-sky-300",children:"synlexa-plugin.v1"})," add-ons. Enabled plugin tools auto-wire into MCP and the AI Assistant."]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(Oe,{size:"sm",variant:"secondary",onClick:e,children:"Configure GPU Nodes"}),o.jsx(Oe,{size:"sm",variant:"secondary",onClick:r,children:"View Exposed MCP Tools"}),o.jsx(Oe,{size:"sm",variant:"primary",icon:o.jsx(gh,{className:"h-3.5 w-3.5"}),onClick:()=>x(T=>!T),children:"Install Custom Manifest"})]})]}),b&&o.jsxs(yt,{className:"space-y-2.5 p-3.5",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"font-semibold text-slate-200",children:"Install Custom Plugin (`synlexa-plugin.v1`)"}),o.jsx(Oe,{size:"sm",variant:"ghost",onClick:()=>x(!1),children:"Close"})]}),o.jsx(Pp,{rows:10,value:g,onChange:T=>_(T.target.value),className:"font-mono text-[0.6875rem]"}),y&&o.jsx("div",{className:"rounded border border-rose-500/40 bg-rose-500/10 px-2.5 py-1.5 text-rose-200",children:y}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"text-[0.6875rem] text-slate-500",children:["Enforces ",o.jsx("code",{className:"text-slate-300",children:"ruoRequired: true"})," and declarative schema validation."]}),o.jsx(Oe,{size:"sm",variant:"primary",onClick:E,children:"Validate & Install"})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("div",{className:"relative min-w-44 flex-1 @lg:max-w-xs",children:[o.jsx(Gr,{className:"pointer-events-none absolute top-2.5 left-2.5 h-3.5 w-3.5 text-slate-500"}),o.jsx(Dn,{value:c,onChange:T=>d(T.target.value),placeholder:"Filter tools, categories, licenses…",className:"pl-8"})]}),o.jsx("div",{className:"flex flex-wrap gap-1",children:["all","tier0-core","tier1-wasm","tier2-compute","database"].map(T=>o.jsx("button",{type:"button",onClick:()=>p(T),className:`rounded-lg border px-2.5 py-1.5 text-xs transition ${f===T?"border-sky-400/50 bg-sky-500/20 text-sky-200":"border-white/10 bg-white/[0.03] text-slate-300 hover:border-white/20"}`,children:gL[T]},T))})]}),o.jsx("div",{className:"grid grid-cols-1 gap-3 @2xl:grid-cols-2 @5xl:grid-cols-3",children:k.map(T=>o.jsxs(yt,{className:"flex flex-col justify-between gap-3 p-3.5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx("span",{className:"font-semibold text-slate-100",children:T.name}),T.topPick&&o.jsxs(It,{tone:"accent",children:[o.jsx(Gs,{className:"h-2.5 w-2.5"})," Top 8"]})]}),o.jsxs("div",{className:"mt-0.5 text-[0.6875rem] text-slate-400",children:[T.category," · v",T.version]})]}),o.jsx($r,{checked:T.enabled,onChange:j=>H3(T.id,j),label:`Toggle ${T.name}`})]}),o.jsx("p",{className:"text-slate-300 leading-relaxed",children:T.description}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs(It,{tone:T.commercialSafe?"good":"warn",children:[T.commercialSafe?o.jsx(Ki,{className:"h-3 w-3"}):o.jsx(Gc,{className:"h-3 w-3"}),T.license]}),o.jsx(It,{tone:"neutral",children:T.tier}),T.requiresGpu&&o.jsx(It,{tone:"warn",children:"GPU recommended"}),T.mcpTools&&T.mcpTools.length>0&&o.jsxs(It,{tone:"accent",children:[T.mcpTools.length," MCP tool"]})]}),T.installHint&&o.jsx("div",{className:"rounded border border-white/[0.06] bg-[#070b12] px-2 py-1 font-mono text-[0.6875rem] text-slate-400",children:T.installHint})]}),o.jsxs("div",{className:"flex items-center justify-between border-t border-white/[0.06] pt-2 text-[0.6875rem] text-slate-500",children:[o.jsx("span",{className:"truncate font-mono",children:T.id}),o.jsxs("div",{className:"flex items-center gap-2",children:[n&&T.id==="org.synlexa.molstar"&&o.jsx("button",{type:"button",onClick:()=>n("viewer"),className:"text-emerald-300 hover:text-emerald-200",children:"Open 3D"}),n&&T.id==="org.synlexa.rdkit-wasm"&&o.jsx("button",{type:"button",onClick:()=>n("chemistry"),className:"text-emerald-300 hover:text-emerald-200",children:"Open Ligands"}),n&&T.id==="org.synlexa.gemmi-core"&&o.jsx("button",{type:"button",onClick:()=>n("ramachandran"),className:"text-emerald-300 hover:text-emerald-200",children:"Open Tools"}),n&&T.id==="org.synlexa.workflows"&&o.jsx("button",{type:"button",onClick:()=>n("workflow"),className:"text-emerald-300 hover:text-emerald-200",children:"Open Canvas"}),n&&T.tier==="tier2-compute"&&T.id!=="org.synlexa.workflows"&&o.jsx("button",{type:"button",onClick:()=>n("compute"),className:"text-emerald-300 hover:text-emerald-200",children:"GPU Runner"}),T.homepage&&o.jsxs("a",{href:T.homepage,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-sky-300 hover:text-sky-200",children:["Source ",o.jsx(Kd,{className:"h-3 w-3"})]}),!T.builtin&&o.jsx("button",{type:"button",onClick:()=>_D(T.id),className:"text-rose-300 hover:text-rose-200",title:"Uninstall custom plugin",children:o.jsx(Wi,{className:"h-3.5 w-3.5"})})]})]})]},T.id))})]})})}const Er=260,Or=28,Ip=Er-Or*2,Jf=360;function Qn(e){return Or+(e+180)/360*Ip}function Jn(e){return Or+(180-e)/360*Ip}function yL(e){if(e.region==="outlier")return"#fb7185";switch(e.secondary){case"helix":return"#38bdf8";case"sheet":return"#34d399";default:return"#fbbf24"}}function _L({refLabel:e,refChain:r,mobLabel:n,mobChain:s,activeSource:i,onChangeSource:c,result:d,error:f,focusedSeqId:p,onFocusResidue:b,simpleMode:x=!1,bridge:g}){const[_,y]=C.useState(null),[S,k]=C.useState(null),[E,T]=C.useState("all"),[j,q]=C.useState(8),[z,O]=C.useState(!1),[V,P]=C.useState(!1),$=C.useRef(null),H=C.useMemo(()=>{const I=new Map;for(const J of d?.residues??[])I.set(J.seqId,J);return I},[d]),Z=C.useMemo(()=>{if(!d)return null;const I=Math.max(1,d.residueCount),{helix:J,sheet:ge,loop:le}=d.secondaryCounts,{favored:D,allowed:ae,outlier:pe}=d.regionCounts,Ae=Math.max(1,D+ae+pe);return{helixPct:J/I*100,sheetPct:ge/I*100,loopPct:le/I*100,favoredPct:D/Ae*100,allowedPct:ae/Ae*100,outlierPct:pe/Ae*100,classified:Ae}},[d]),G=C.useMemo(()=>(d?.residues??[]).filter(I=>I.phiDeg===null||I.psiDeg===null?!1:I.seqId===p||E==="all"?!0:E==="outlier"?I.region==="outlier":I.secondary===E),[d,E,p]),K=C.useMemo(()=>(d?.residues??[]).filter(I=>I.region==="outlier"),[d]),we=C.useMemo(()=>{if(!d)return[];const I=z?12:4;return d.contactPairs.filter(([J,ge,le])=>le<=j&&Math.abs(J-ge)>=I)},[d,j,z]),Se=C.useMemo(()=>p!==null?H.get(p)??null:null,[H,p]),Q=C.useMemo(()=>p===null?[]:we.filter(([I,J])=>I===p||J===p).sort((I,J)=>I[2]-J[2]),[we,p]),F=C.useMemo(()=>{if(!d||d.residues.length===0)return{min:1,max:1};let I=d.residues[0].seqId,J=d.residues[0].seqId;for(const ge of d.residues)ge.seqId<I&&(I=ge.seqId),ge.seqId>J&&(J=ge.seqId);return{min:I,max:Math.max(I+1,J)}},[d]);C.useEffect(()=>{const I=$.current;if(!I)return;const J=I.getContext("2d");if(!J)return;const ge=Jf;if(J.fillStyle="#070a10",J.fillRect(0,0,ge,ge),!d||d.residues.length===0)return;const le=12,D=F.max-F.min,ae=pe=>le+(pe-F.min)/D*(ge-le*2);J.strokeStyle="rgba(148, 163, 184, 0.08)",J.lineWidth=1;for(let pe=Math.ceil(F.min/50)*50;pe<=F.max;pe+=50){const Ae=ae(pe);J.beginPath(),J.moveTo(Ae,le),J.lineTo(Ae,ge-le),J.moveTo(le,Ae),J.lineTo(ge-le,Ae),J.stroke()}J.strokeStyle="rgba(148, 163, 184, 0.25)",J.lineWidth=1.25,J.beginPath(),J.moveTo(le,le),J.lineTo(ge-le,ge-le),J.stroke();for(const[pe,Ae,Ne]of we){const Re=ae(pe),$e=ae(Ae),Ce=Math.max(0,Math.min(1,(j-Ne)/Math.max(1,j-3.5)));J.fillStyle=Ne<=5.5?`rgba(52, 211, 153, ${.6+Ce*.4})`:`rgba(56, 189, 248, ${.4+Ce*.45})`,J.fillRect(Re-1.6,$e-1.6,3.4,3.4),J.fillRect($e-1.6,Re-1.6,3.4,3.4)}if(p!==null){const pe=ae(p);J.strokeStyle="rgba(251, 191, 36, 0.8)",J.lineWidth=1.5,J.beginPath(),J.moveTo(pe,0),J.lineTo(pe,ge),J.moveTo(0,pe),J.lineTo(ge,pe),J.stroke()}},[d,we,j,F,p]);const he=(I,J=!1)=>{b(I),J&&g?.focusIn3D(I,{centerCamera:!0})},W=(I,J)=>{if(!d||we.length===0)return;const ge=I.currentTarget.getBoundingClientRect(),le=ge.width,D=12/Jf,ae=le*D,pe=F.max-F.min,Ae=F.min+(I.clientX-ge.left-ae)/Math.max(1,le-ae*2)*pe,Ne=F.min+(I.clientY-ge.top-ae)/Math.max(1,le-ae*2)*pe;let Re=null,$e=160;for(const Ce of we){const Ue=(Ce[0]-Ae)**2+(Ce[1]-Ne)**2,be=(Ce[1]-Ae)**2+(Ce[0]-Ne)**2,bt=Math.min(Ue,be);bt<$e&&($e=bt,Re=Ce)}k(Re),J&&Re&&he(Re[0],!0)},me=!!(e||n);return o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3 text-xs @xl:p-4",children:[o.jsx(ir,{bridge:g,title:"Ramachandran Geometry & Cα Contact Map",subtitle:"Inspect backbone dihedral angles (φ, ψ), secondary structure packing, conformational outliers, and 3D tertiary contacts.",icon:o.jsx(Qo,{className:"h-4 w-4"}),guideOpen:V,onToggleGuide:()=>P(I=>!I)}),o.jsx(Qi,{open:V,title:"How Ramachandran & Cα Contact Analysis Works",summary:"Every protein residue’s backbone conformation is defined by two dihedral torsion angles: φ (N–Cα) and ψ (Cα–C). Plotting φ vs ψ reveals well-packed α-helices and β-sheets versus strained outliers.",steps:["Switch between Reference (experimental) and Mobile (predicted) structures in the toolbar below.","Filter the Ramachandran plot by Helix, Sheet, Loop, or Outliers Only; click any dot to inspect its φ/ψ angles and sync the 3D Viewer.","Use the Cα–Cα Contact Map to inspect folded tertiary contacts (distant residues in sequence that touch in 3D space). Adjust the Å cutoff or toggle Long-Range contacts."],connectionTip:"Every click on a Ramachandran dot, outlier chip, or contact neighbor synchronizes your focused residue across the 3D Viewer, Sequence Track, Peptide, and CRISPR tabs. Use 'Highlight Outliers in 3D' or 'Highlight Contacts in 3D' to light them up directly on the 3D model.",glossary:[{term:"Favored / Allowed / Outlier",desc:"Empirical backbone angle regions; well-refined proteins typically have ≥ 90% in favored zones (Gly and Pro can legitimately occupy broader regions)."},{term:"Cα–Cα Contact (≤ 8 Å)",desc:"Residues separated by at least 4 sequence positions whose alpha carbons sit within 8 Å in 3D — defining secondary & tertiary fold packing."},{term:"Long-Range (|i−j| ≥ 12)",desc:"Contacts between distant parts of the chain that reveal global domain folding rather than local helix turns."}]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-xl border border-white/[0.08] bg-[#0b1018] p-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 font-mono text-xs",children:[o.jsxs("button",{type:"button",disabled:!e,onClick:()=>c("reference"),className:`rounded-lg border px-2.5 py-1 transition disabled:opacity-40 ${i==="reference"?"border-sky-400/50 bg-sky-500/20 text-sky-200":"border-white/10 bg-slate-950 text-slate-400 hover:text-slate-200"}`,children:["Ref: ",e||"None"," (",r||"?",")"]}),o.jsxs("button",{type:"button",disabled:!n,onClick:()=>c("mobile"),className:`rounded-lg border px-2.5 py-1 transition disabled:opacity-40 ${i==="mobile"?"border-emerald-400/50 bg-emerald-500/20 text-emerald-200":"border-white/10 bg-slate-950 text-slate-400 hover:text-slate-200"}`,children:["Mob: ",n||"None"," (",s||"?",")"]})]}),o.jsx("div",{className:"flex flex-wrap items-center gap-1",children:[["all","All"],["helix","α-Helix"],["sheet","β-Sheet"],["loop","Loop"],["outlier",`Outliers (${K.length})`]].map(([I,J])=>o.jsx("button",{type:"button",onClick:()=>T(I),className:`rounded-md border px-2 py-1 font-mono text-[0.6875rem] transition ${E===I?"border-cyan-400/50 bg-cyan-500/20 text-cyan-200":"border-white/10 bg-slate-900/70 text-slate-400 hover:text-slate-200"}`,children:J},I))})]}),f&&o.jsx("div",{className:"rounded-xl border border-rose-500/40 bg-rose-500/10 px-3 py-2 font-mono text-xs text-rose-200",children:f}),!me&&!d&&!f&&o.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 rounded-xl border border-white/[0.08] bg-[#0b1018] p-6 text-center",children:[o.jsx(Qo,{className:"h-8 w-8 text-slate-500"}),o.jsx("div",{className:"text-sm font-medium text-slate-200",children:"No structure loaded for Ramachandran analysis"}),o.jsx("p",{className:"max-w-md text-xs text-slate-400",children:"Load a PDB or mmCIF structure to compute backbone φ/ψ dihedral angles and tertiary Cα–Cα contact maps."}),g&&o.jsxs("button",{type:"button",onClick:g.loadExample,className:"inline-flex items-center gap-1.5 rounded-lg bg-sky-500 px-3.5 py-2 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:[o.jsx(Br,{className:"h-3.5 w-3.5"})," Load Carbonic Anhydrase II Example"]})]}),me&&!d&&!f&&o.jsx("div",{className:"flex flex-1 items-center justify-center rounded-xl border border-white/[0.08] bg-[#0b1018] p-6 font-mono text-xs text-slate-500",children:"Computing backbone φ/ψ dihedral angles and Cα–Cα contact distances in Wasm…"}),d&&Z&&o.jsxs("div",{className:"grid grid-cols-1 gap-3 @3xl:grid-cols-2 @6xl:grid-cols-12",children:[o.jsxs("div",{className:"flex flex-col gap-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @6xl:col-span-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 font-mono text-[0.75rem]",children:[o.jsx("span",{className:"font-semibold text-cyan-300",children:"RAMACHANDRAN PLOT"}),o.jsx("span",{className:"text-slate-300",children:_?`${_.resName3}${_.seqId} (φ ${_.phiDeg?.toFixed(0)}°, ψ ${_.psiDeg?.toFixed(0)}°)`:Se&&Se.phiDeg!==null?`Sel: ${Se.resName3}${Se.seqId} · ${Se.region}`:"Click any dot to focus in 3D"})]}),o.jsx("div",{className:"flex w-full justify-center",children:o.jsxs("svg",{viewBox:`0 0 ${Er} ${Er}`,className:"aspect-square w-full max-w-[330px] rounded-lg border border-white/10 bg-[#070a10]",children:[o.jsx("rect",{x:Qn(-165),y:Jn(175),width:Qn(-65)-Qn(-165),height:Jn(85)-Jn(175),rx:6,fill:"rgba(52, 211, 153, 0.12)",stroke:"rgba(52, 211, 153, 0.35)",strokeWidth:.85}),o.jsx("rect",{x:Qn(-105),y:Jn(-5),width:Qn(-35)-Qn(-105),height:Jn(-70)-Jn(-5),rx:6,fill:"rgba(56, 189, 248, 0.14)",stroke:"rgba(56, 189, 248, 0.38)",strokeWidth:.85}),o.jsx("rect",{x:Qn(35),y:Jn(65),width:Qn(95)-Qn(35),height:Jn(5)-Jn(65),rx:5,fill:"rgba(56, 189, 248, 0.09)",stroke:"rgba(56, 189, 248, 0.25)",strokeWidth:.85}),o.jsx("line",{x1:Qn(0),y1:Or,x2:Qn(0),y2:Er-Or,stroke:"rgba(148,163,184,0.25)",strokeDasharray:"2 2"}),o.jsx("line",{x1:Or,y1:Jn(0),x2:Er-Or,y2:Jn(0),stroke:"rgba(148,163,184,0.25)",strokeDasharray:"2 2"}),o.jsx("rect",{x:Or,y:Or,width:Ip,height:Ip,fill:"none",stroke:"rgba(51,65,85,0.85)"}),o.jsx("text",{x:Er/2,y:Er-7,textAnchor:"middle",fill:"#64748b",fontSize:"9",fontFamily:"monospace",children:"φ (deg) [-180 … +180]"}),o.jsx("text",{x:10,y:Er/2,textAnchor:"middle",fill:"#64748b",fontSize:"9",fontFamily:"monospace",transform:`rotate(-90 10 ${Er/2})`,children:"ψ (deg)"}),o.jsx("text",{x:Qn(-115),y:Jn(135),textAnchor:"middle",fill:"rgba(52,211,153,0.65)",fontSize:"8",fontFamily:"monospace",children:"β-sheet"}),o.jsx("text",{x:Qn(-70),y:Jn(-38),textAnchor:"middle",fill:"rgba(56,189,248,0.75)",fontSize:"8",fontFamily:"monospace",children:"α-helix"}),o.jsx("text",{x:Qn(65),y:Jn(35),textAnchor:"middle",fill:"rgba(56,189,248,0.55)",fontSize:"7",fontFamily:"monospace",children:"L-helix"}),G.map(I=>{const J=Qn(I.phiDeg),ge=Jn(I.psiDeg),le=I.seqId===p;return o.jsxs("g",{children:[le&&o.jsx("circle",{cx:J,cy:ge,r:7.5,fill:"none",stroke:"#fbbf24",strokeWidth:1.8}),o.jsx("circle",{cx:J,cy:ge,r:le?4.2:I.region==="outlier"?3.5:2.5,fill:yL(I),fillOpacity:le?1:.85,className:"cursor-pointer",onMouseEnter:()=>y(I),onMouseLeave:()=>y(null),onClick:()=>he(I.seqId,!0)})]},`${I.seqId}-${I.insCode}`)})]})}),o.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-3 font-mono text-[0.6875rem] text-slate-400",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-sky-400"})," Helix"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-emerald-400"})," Sheet"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-amber-400"})," Loop"]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-rose-400"})," Outlier"]})]})]}),o.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @6xl:col-span-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 font-mono text-[0.75rem]",children:[o.jsx("span",{className:"font-semibold text-cyan-300",children:"SECONDARY STRUCTURE & GEOMETRY"}),o.jsxs("span",{className:"text-slate-400",children:[d.residueCount," res"]})]}),o.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-cyan-500/25 bg-cyan-500/8 px-2.5 py-2 text-xs leading-relaxed text-cyan-100",children:[o.jsx(zy,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-cyan-300"}),o.jsxs("span",{children:[Z.favoredPct>=90?`${Z.favoredPct.toFixed(1)}% of dihedral pairs sit in favored Ramachandran zones — typical of well-packed backbone geometry.`:`${Z.favoredPct.toFixed(1)}% favored (${d.regionCounts.outlier} outlier${d.regionCounts.outlier===1?"":"s"}). Click rose dots or outlier chips to inspect strained residues in 3D.`,x?"":" Click any residue dot or outlier below to jump in 3D."]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex h-2.5 w-full overflow-hidden rounded-full bg-slate-900",children:[o.jsx("div",{style:{width:`${Z.helixPct}%`},className:"bg-sky-400",title:`α-Helix ${Z.helixPct.toFixed(1)}%`}),o.jsx("div",{style:{width:`${Z.sheetPct}%`},className:"bg-emerald-400",title:`β-Sheet ${Z.sheetPct.toFixed(1)}%`}),o.jsx("div",{style:{width:`${Z.loopPct}%`},className:"bg-amber-400",title:`Loop / Turn ${Z.loopPct.toFixed(1)}%`})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 font-mono text-xs",children:[o.jsxs("div",{className:"min-w-0 rounded-lg border border-white/[0.07] bg-black/25 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-sky-300",children:"α-Helix"}),o.jsxs("div",{className:"mt-0.5 font-bold text-slate-100",children:[Z.helixPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-500",children:[d.secondaryCounts.helix," res"]})]}),o.jsxs("div",{className:"min-w-0 rounded-lg border border-white/[0.07] bg-black/25 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-emerald-300",children:"β-Sheet"}),o.jsxs("div",{className:"mt-0.5 font-bold text-slate-100",children:[Z.sheetPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-500",children:[d.secondaryCounts.sheet," res"]})]}),o.jsxs("div",{className:"min-w-0 rounded-lg border border-white/[0.07] bg-black/25 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-amber-300",children:"Loop / Turn"}),o.jsxs("div",{className:"mt-0.5 font-bold text-slate-100",children:[Z.loopPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-500",children:[d.secondaryCounts.loop," res"]})]})]})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 font-mono text-xs",children:[o.jsxs("div",{className:"min-w-0 rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-emerald-300",children:"Favored"}),o.jsxs("div",{className:"mt-0.5 font-bold text-emerald-200",children:[Z.favoredPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-400",children:[d.regionCounts.favored," res"]})]}),o.jsxs("div",{className:"min-w-0 rounded-lg border border-sky-500/30 bg-sky-500/10 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-sky-300",children:"Allowed"}),o.jsxs("div",{className:"mt-0.5 font-bold text-sky-200",children:[Z.allowedPct.toFixed(1),"%"]}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-400",children:[d.regionCounts.allowed," res"]})]}),o.jsxs("div",{className:"min-w-0 rounded-lg border border-rose-500/30 bg-rose-500/10 p-2",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-rose-300",children:"Outliers"}),o.jsx("div",{className:"mt-0.5 font-bold text-rose-200",children:d.regionCounts.outlier}),o.jsxs("div",{className:"text-[0.6875rem] text-slate-400",children:[Z.outlierPct.toFixed(1),"%"]})]})]}),K.length>0&&o.jsxs("div",{className:"space-y-1.5 rounded-lg border border-rose-500/20 bg-rose-500/[0.04] p-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("span",{className:"font-mono text-[0.6875rem] font-medium text-rose-300",children:["Outliers (",K.length,"):"]}),g&&o.jsxs("button",{type:"button",onClick:()=>g.highlightIn3D(K.map(I=>I.seqId),"Ramachandran Outliers",{focusSeqId:K[0]?.seqId}),className:"inline-flex items-center gap-1 rounded-md border border-rose-400/40 bg-rose-500/15 px-2 py-0.5 text-[0.6875rem] font-medium text-rose-200 hover:bg-rose-500/25",children:[o.jsx(_s,{className:"h-3 w-3"})," Highlight Outliers in 3D"]})]}),o.jsx("div",{className:"flex flex-wrap gap-1 font-mono text-[0.6875rem]",children:K.slice(0,14).map(I=>o.jsxs("button",{type:"button",onClick:()=>he(I.seqId,!0),className:`rounded-md border px-2 py-0.5 transition ${I.seqId===p?"border-amber-400 bg-amber-400/20 text-amber-200":"border-rose-500/40 bg-rose-500/10 text-rose-200 hover:bg-rose-500/20"}`,children:[I.resName3,I.seqId]},`${I.seqId}-${I.insCode}`))})]}),Se&&o.jsxs("div",{className:"mt-auto space-y-2 rounded-lg border border-amber-400/30 bg-amber-500/[0.05] p-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("span",{className:"font-mono text-xs font-semibold text-amber-200",children:[Se.resName3," ",Se.seqId," (",Se.resCode1,")"]}),o.jsxs("span",{className:"font-mono text-[0.6875rem] text-slate-300",children:[Se.secondary," · ",Se.region]})]}),o.jsxs("div",{className:"flex flex-wrap gap-3 font-mono text-[0.6875rem] text-slate-300",children:[o.jsxs("span",{children:["φ = ",Se.phiDeg!==null?`${Se.phiDeg.toFixed(1)}°`:"terminal"]}),o.jsxs("span",{children:["ψ = ",Se.psiDeg!==null?`${Se.psiDeg.toFixed(1)}°`:"terminal"]}),o.jsxs("span",{children:["Contacts: ",Q.length]})]}),g&&o.jsxs("div",{className:"flex flex-wrap gap-1.5 pt-0.5",children:[o.jsxs("button",{type:"button",onClick:()=>g.focusIn3D(Se.seqId,{centerCamera:!0,openViewer:"activate"}),className:"inline-flex items-center gap-1 rounded-md border border-sky-400/40 bg-sky-500/15 px-2 py-1 text-[0.6875rem] font-medium text-sky-200 hover:bg-sky-500/25",children:[o.jsx(Ur,{className:"h-3 w-3"})," Focus in 3D"]}),o.jsxs("button",{type:"button",onClick:()=>g.openTab("sequence"),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-sky-400/40",children:[o.jsx(Vo,{className:"h-3 w-3"})," Sequence Δd"]}),o.jsxs("button",{type:"button",onClick:()=>g.sendMutationToPeptide(`${Se.resCode1}${Se.seqId}A`,Se.seqId),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-emerald-400/40",children:[o.jsx(ar,{className:"h-3 w-3"})," Ala Scan in Peptide"]})]})]})]}),o.jsxs("div",{className:"@container flex flex-col gap-2.5 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3 @3xl:col-span-2 @6xl:col-span-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 font-mono text-[0.75rem]",children:[o.jsxs("span",{className:"font-semibold text-emerald-300",children:["Cα–Cα CONTACT MAP (|i−j|≥",z?12:4,", ≤",j.toFixed(1)," Å)"]}),o.jsx("span",{className:"text-slate-300",children:S?`${S[0]}–${S[1]}: ${S[2].toFixed(2)} Å`:`${we.length} pairs`})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border border-white/[0.06] bg-black/25 px-2.5 py-1.5 text-[0.6875rem]",children:[o.jsxs("label",{className:"flex items-center gap-2 font-mono text-slate-300",children:[o.jsxs("span",{children:["Cutoff: ",j.toFixed(1)," Å"]}),o.jsx("input",{type:"range",min:5,max:8,step:.2,value:j,onChange:I=>q(Number(I.target.value)),className:"w-24 accent-emerald-400"})]}),o.jsx("button",{type:"button",onClick:()=>O(I=>!I),className:`rounded-md border px-2 py-0.5 font-mono transition ${z?"border-emerald-400/50 bg-emerald-500/20 text-emerald-200":"border-white/10 bg-slate-900 text-slate-400 hover:text-slate-200"}`,children:z?"Long-Range |i−j|≥12":"All |i−j|≥4"})]}),o.jsxs("div",{className:"flex flex-col items-center gap-3 @lg:flex-row @lg:items-start",children:[o.jsx("canvas",{ref:$,width:Jf,height:Jf,onMouseMove:I=>W(I,!1),onClick:I=>W(I,!0),onMouseLeave:()=>k(null),className:"aspect-square w-full max-w-[280px] shrink-0 cursor-crosshair rounded-lg border border-white/10"}),o.jsxs("div",{className:"w-full min-w-0 flex-1 space-y-2 font-mono text-xs",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-1.5",children:[o.jsx("span",{className:"text-[0.6875rem] text-slate-300",children:p!==null?`Neighbors of ${Se?`${Se.resName3}${p}`:`Res ${p}`} (${Q.length})`:"Click plot or contact map to inspect tertiary neighbors."}),g&&Q.length>0&&o.jsx("button",{type:"button",onClick:()=>{const I=Q.map(([J,ge])=>J===p?ge:J);g.highlightIn3D(I,`Cα Contacts of #${p}`,{focusSeqId:p??void 0})},className:"rounded border border-emerald-400/40 bg-emerald-500/15 px-1.5 py-0.5 font-sans text-[0.6875rem] font-medium text-emerald-200 hover:bg-emerald-500/25",children:"Show in 3D"})]}),o.jsxs("div",{className:"grid max-h-56 grid-cols-1 gap-1 overflow-y-auto pr-0.5 @sm:grid-cols-2",children:[Q.slice(0,24).map(([I,J,ge],le)=>{const D=I===p?J:I,ae=H.get(D);return o.jsxs("button",{type:"button",onClick:()=>he(D,!0),className:"flex items-center justify-between gap-1.5 rounded-lg border border-white/[0.08] bg-black/30 px-2 py-1 text-left text-[0.6875rem] text-slate-200 hover:border-emerald-400/50 hover:text-emerald-200",children:[o.jsx("span",{className:"truncate",children:ae?`${ae.resName3} ${D}`:`Res ${D}`}),o.jsxs("span",{className:"shrink-0 text-emerald-300",children:[ge.toFixed(1)," Å"]})]},`${I}-${J}-${le}`)}),p!==null&&Q.length===0&&o.jsxs("span",{className:"col-span-full text-[0.6875rem] text-slate-500",children:["No non-local Cα contacts within ",j.toFixed(1)," Å."]})]})]})]})]})]})]})}function vL({comparison:e,paeJson:r,busy:n,guided:s,selectedPaePair:i,onSelectPaePair:c,includePng:d,onToggleIncludePng:f,onExportHtml:p,onExportJson:b,onExportBundle:x,bridge:g}){const[_,y]=C.useState(null),[S,k]=C.useState(!1),[E,T]=C.useState(!1),j=C.useMemo(()=>e?Rq(e.matchedResidues.map($=>$.mobPlddt)):null,[e]),q=C.useMemo(()=>zq(r),[r]),z=C.useMemo(()=>e?[...e.matchedResidues].sort(($,H)=>H.distanceAngstrom-$.distanceAngstrom).slice(0,8):[],[e]);if(!e)return o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col p-3 @xl:p-4",children:[o.jsx(ir,{bridge:g,title:"Comparison Results & Provenance",subtitle:"Quantitative RMSD, coverage, PAE matrix, top deviation hotspots, and RUO exports.",icon:o.jsx(qi,{className:"h-4 w-4"}),guideOpen:E,onToggleGuide:()=>T($=>!$)}),o.jsx("div",{className:"flex-1",children:o.jsx(mE,{icon:o.jsx(qi,{className:"h-8 w-8"}),title:n?"Running comparison…":"No comparison yet",description:"Load a reference and a comparison structure (from a file, your library, or a public database) to see RMSD, coverage, confidence, and provenance here."})})]});const O=e.metrics,V=$=>{navigator.clipboard?.writeText($),y($),setTimeout(()=>y(null),1500)},P=[{label:"Cα RMSD",value:`${O.rmsdAngstrom.toFixed(3)} Å`,sub:"after rigid superposition",tone:"text-emerald-300"},{label:"Matched Cα",value:String(O.matchedCaCount),sub:"aligned residue pairs"},{label:"Reference coverage",value:`${(O.refCoverage.ratio*100).toFixed(1)}%`,sub:`${O.refCoverage.numerator} / ${O.refCoverage.denominator}`},{label:"Comparison coverage",value:`${(O.mobCoverage.ratio*100).toFixed(1)}%`,sub:`${O.mobCoverage.numerator} / ${O.mobCoverage.denominator}`}];return j!==null&&P.push({label:"Mean pLDDT",value:j.toFixed(1),sub:"prediction confidence (0–100)"}),q!==null&&P.push({label:"Mean PAE",value:`${q.toFixed(1)} Å`,sub:"predicted aligned error"}),o.jsx("div",{className:"@container h-full min-h-0 overflow-y-auto",children:o.jsxs("div",{className:"mx-auto max-w-5xl space-y-4 p-3 @xl:px-5 @xl:py-5",children:[o.jsx(ir,{bridge:g,title:`${e.reference.label} (${e.reference.chainId}) vs ${e.mobile.label} (${e.mobile.chainId})`,subtitle:"Deterministic Kabsch rigid superposition metrics, PAE domain confidence, top deviation hotspots & RUO exports.",icon:o.jsx(qi,{className:"h-4 w-4"}),guideOpen:E,onToggleGuide:()=>T($=>!$),actions:g&&o.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.jsx("button",{type:"button",onClick:()=>{g.setColorMode3D("deviation"),g.openTab("viewer",!1)},className:"rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-sky-400/40",children:"Color 3D by Δd"}),o.jsx("button",{type:"button",onClick:()=>{g.setColorMode3D("plddt"),g.openTab("viewer",!1)},className:"rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-emerald-400/40",children:"Color 3D by pLDDT"})]})}),o.jsx(Qi,{open:E,title:"How to Read Comparison Results",summary:"Results summarize deterministic Cα Kabsch superposition between your reference and comparison structures, paired with AlphaFold PAE uncertainty when available.",steps:["Check Cα RMSD and Coverage cards to see global fold similarity and whether termini/loops were excluded.","Inspect Highest Deviation Residues below and click any residue to jump directly to it in 3D.","Click any cell on the PAE heatmap to verify inter-residue domain confidence and focus residue i in 3D."],connectionTip:"Use 'Color 3D by Δd' or click any residue in the deviation table or PAE heatmap to synchronize the 3D Viewer, Sequence Track, and Ramachandran plot."}),o.jsx("div",{className:"grid grid-cols-2 gap-3 @2xl:grid-cols-3",children:P.map($=>o.jsxs("div",{className:"min-w-0 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5",children:[o.jsx("div",{className:"truncate text-xs text-slate-400",children:$.label}),o.jsx("div",{className:`mt-1 truncate text-xl font-semibold tabular-nums @2xl:text-2xl ${$.tone??"text-slate-100"}`,children:$.value}),$.sub&&o.jsx("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:$.sub})]},$.label))}),o.jsx(yt,{title:"Plain-English Summary",description:"Deterministic metric interpretations (RUO heuristics).",children:o.jsxs("div",{className:"grid gap-2 @2xl:grid-cols-2",children:[o.jsx(Ca,{insight:Aq(O.rmsdAngstrom)}),o.jsx(Ca,{insight:jq(O.refCoverage.ratio,O.refCoverage.numerator,O.refCoverage.denominator)}),j!==null&&o.jsx(Ca,{insight:wE(j)}),q!==null&&o.jsx(Ca,{insight:Tq(q)})]})}),z.length>0&&o.jsx(yt,{title:"Highest Structural Deviations (Top Δd Residues)",description:"Residues with the largest Cα-to-Cα offset after rigid superposition — click any chip to inspect in 3D.",actions:g&&o.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.jsxs("button",{type:"button",onClick:()=>g.highlightIn3D(z.map($=>$.refSeqId),"Top Δd Hotspots",{focusSeqId:z[0]?.refSeqId}),className:"inline-flex items-center gap-1 rounded-md border border-rose-400/40 bg-rose-500/15 px-2 py-1 text-xs font-medium text-rose-200 hover:bg-rose-500/25",children:[o.jsx(_s,{className:"h-3 w-3"})," Highlight Top ",z.length," in 3D"]}),o.jsxs("button",{type:"button",onClick:()=>g.openTab("sequence"),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-xs text-slate-200 hover:border-sky-400/40",children:[o.jsx(Vo,{className:"h-3 w-3"})," Sequence Track"]}),o.jsxs("button",{type:"button",onClick:()=>g.openTab("ramachandran"),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-xs text-slate-200 hover:border-cyan-400/40",children:[o.jsx(Qo,{className:"h-3 w-3"})," Ramachandran"]})]}),children:o.jsx("div",{className:"grid grid-cols-2 gap-2 @xl:grid-cols-4",children:z.map($=>o.jsxs("button",{type:"button",onClick:()=>{c($.mobSeqId,$.mobSeqId),g?.focusIn3D($.refSeqId,{centerCamera:!0})},className:"flex items-center justify-between gap-2 rounded-lg border border-white/[0.08] bg-black/25 px-2.5 py-2 text-left font-mono text-xs transition hover:border-amber-400/50",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"truncate font-semibold text-slate-100",children:[$.resName3," ",$.refSeqId]}),o.jsx("div",{className:"truncate text-[0.6875rem] text-slate-500",children:$.mobPlddt!=null?`pLDDT ${$.mobPlddt.toFixed(0)}`:"Exp/Model"})]}),o.jsxs("span",{className:"shrink-0 font-semibold text-amber-300",children:[$.distanceAngstrom.toFixed(2)," Å"]})]},`${$.refSeqId}-${$.mobSeqId}`))})}),o.jsx(wL,{paeJson:r,selected:i,onSelect:($,H)=>{c($,H),g?.focusIn3D($,{centerCamera:!0})},status:O.paeStatus,onFocusIn3D:g?$=>g.focusIn3D($,{centerCamera:!0,openViewer:"activate"}):void 0}),o.jsx(yt,{title:"Provenance",description:"Exact inputs used for this result.",children:o.jsxs("div",{className:"space-y-2",children:[[{tag:"Reference",rec:e.reference,tone:"text-sky-300"},{tag:"Comparison",rec:e.mobile,tone:"text-emerald-300"}].map(({tag:$,rec:H,tone:Z})=>o.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-white/[0.06] bg-black/20 p-3",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[o.jsx("span",{className:`font-medium ${Z}`,children:$}),o.jsx("span",{className:"text-slate-200",children:H.label}),o.jsx(It,{children:H.confidenceKind}),o.jsx(It,{children:H.license??"license unknown"})]}),o.jsxs("div",{className:"mt-1 truncate font-mono text-xs text-slate-500",children:["sha256 ",H.sha256]})]}),o.jsx("button",{type:"button",onClick:()=>V(H.sha256),title:"Copy SHA-256",className:"rounded-md p-1.5 text-slate-500 hover:bg-white/[0.06] hover:text-slate-200",children:_===H.sha256?o.jsx(Fi,{className:"h-4 w-4 text-emerald-400"}):o.jsx(Lr,{className:"h-4 w-4"})})]},$)),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 pt-1 text-xs text-slate-500",children:[o.jsxs("span",{children:["Engine ",e.engine.target," · ",e.engine.floatPrecision]}),o.jsxs("span",{children:["Result ",e.resultId.slice(0,16),"…"]}),o.jsx("span",{children:new Date(e.createdAtUtc).toLocaleString()})]}),o.jsxs("button",{type:"button",onClick:()=>k($=>!$),className:"flex items-center gap-1 pt-1 text-xs text-slate-400 hover:text-slate-200",children:[S?o.jsx(ph,{className:"h-3.5 w-3.5"}):o.jsx(Ty,{className:"h-3.5 w-3.5"}),"4×4 transform (",e.transform.direction,")"]}),S&&o.jsx("div",{className:"grid grid-cols-4 gap-1 rounded-lg bg-black/30 p-3 font-mono text-xs text-slate-300",children:e.transform.matrixRowMajor4x4.map(($,H)=>o.jsx("div",{className:"text-right tabular-nums",children:$.toFixed(4)},H))})]})}),o.jsxs(yt,{title:"Export",description:"Every export carries provenance and the research-use-only notice.",children:[o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(Oe,{variant:"primary",icon:o.jsx(sr,{className:"h-4 w-4"}),onClick:p,children:"HTML report"}),o.jsx(Oe,{icon:o.jsx(BA,{className:"h-4 w-4"}),onClick:b,children:"JSON manifest"}),o.jsx(Oe,{icon:o.jsx(UA,{className:"h-4 w-4"}),onClick:x,children:"Project bundle"})]}),o.jsxs("label",{className:"mt-4 flex items-center gap-3 text-sm text-slate-300",children:[o.jsx($r,{checked:d,onChange:f,label:"Embed 3D image"}),"Embed the current 3D view in the HTML report"]})]}),o.jsx("p",{className:"text-xs text-slate-500",children:Cn})]})})}function wL({paeJson:e,selected:r,onSelect:n,status:s,onFocusIn3D:i}){const c=C.useRef(null),d=C.useRef(null),[f,p]=C.useState(null),b=C.useMemo(()=>{if(!e)return null;try{const g=JSON.parse(e),y=(Array.isArray(g)?g[0]:g)?.predicted_aligned_error;return Array.isArray(y)&&Array.isArray(y[0])?y:null}catch{return null}},[e]);C.useEffect(()=>{if(!b){d.current=null;return}const g=b.length,_=document.createElement("canvas");_.width=g,_.height=g;const y=_.getContext("2d");if(!y)return;const S=y.createImageData(g,g);for(let k=0;k<g;k++)for(let E=0;E<g;E++){const[T,j,q]=cL(Number(b[k][E]??30)),z=(k*g+E)*4;S.data[z]=T,S.data[z+1]=j,S.data[z+2]=q,S.data[z+3]=255}y.putImageData(S,0,0),d.current=_},[b]),C.useEffect(()=>{const g=c.current,_=d.current;if(!g||!_||!b)return;const y=g.getContext("2d");if(!y)return;const S=g.width;y.imageSmoothingEnabled=!1,y.drawImage(_,0,0,S,S);const k=S/b.length,E=(T,j,q)=>{y.strokeStyle=q,y.lineWidth=1.5,y.beginPath(),y.moveTo((j-.5)*k,0),y.lineTo((j-.5)*k,S),y.moveTo(0,(T-.5)*k),y.lineTo(S,(T-.5)*k),y.stroke()};r&&E(r[0],r[1],"rgba(251,191,36,0.9)"),f&&E(f.i,f.j,"rgba(125,211,252,0.75)")},[b,f,r]);const x=(g,_)=>{if(!b)return;const y=g.currentTarget.getBoundingClientRect(),S=b.length,k=Math.max(0,Math.min(S-1,Math.floor((g.clientX-y.left)/y.width*S))),E=Math.max(0,Math.min(S-1,Math.floor((g.clientY-y.top)/y.height*S)));p({i:E+1,j:k+1,val:Number(b[E][k]??0)}),_&&n(E+1,k+1)};return o.jsx(yt,{title:"Predicted aligned error (PAE)",description:b?`${b.length} × ${b.length} residues · click a cell to focus residue i in 3D`:`No PAE matrix loaded (${s}). AlphaFold DB imports include it automatically.`,actions:o.jsxs("div",{className:"flex items-center gap-2",children:[f?o.jsxs("span",{className:"font-mono text-xs text-slate-300 tabular-nums",children:["(",f.i,", ",f.j,") = ",f.val.toFixed(1)," Å"]}):r?o.jsxs("span",{className:"font-mono text-xs text-amber-300",children:["selected (",r[0],", ",r[1],")"]}):null,r&&i&&o.jsxs("button",{type:"button",onClick:()=>i(r[0]),className:"inline-flex items-center gap-1 rounded-md border border-sky-400/40 bg-sky-500/15 px-2 py-0.5 text-xs text-sky-200 hover:bg-sky-500/25",children:[o.jsx(Ur,{className:"h-3 w-3"})," View in 3D"]})]}),children:b?o.jsxs("div",{className:"flex flex-col items-center gap-3 @lg:flex-row @lg:items-end",children:[o.jsx("canvas",{ref:c,width:520,height:520,onMouseMove:g=>x(g,!1),onClick:g=>x(g,!0),onMouseLeave:()=>p(null),className:"aspect-square w-full max-w-[22rem] cursor-crosshair rounded-lg border border-white/[0.08]"}),o.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400 @lg:flex-col @lg:items-start",children:[o.jsx("span",{children:"0 Å · confident"}),o.jsx("span",{className:"inline-block h-2 w-28 rounded-sm bg-gradient-to-r from-[#10d2a0] via-[#2d8c87] to-[#0f172a] @lg:h-28 @lg:w-2 @lg:bg-gradient-to-b"}),o.jsx("span",{children:"30 Å · uncertain"})]})]}):null})}function SL({comparison:e,refInspect:r,mobInspect:n,refChainId:s,mobChainId:i,focusedSeqId:c,onFocusResidue:d,bridge:f}){const p=C.useRef(null),[b,x]=C.useState("deviation"),[g,_]=C.useState("all"),[y,S]=C.useState(""),[k,E]=C.useState(!1),T=C.useMemo(()=>{const P=r?.chains.find(K=>K.chainId===s)??r?.chains[0],$=n?.chains.find(K=>K.chainId===i)??n?.chains[0],H=new Map;if(e)for(const K of e.matchedResidues)H.set(K.mobSeqId,K);const Z=P?.sequence1Letter??"",G=new Map;for(const K of P?.residues??[])G.set(K.seqId,{code:K.resCode1,hasCa:K.ca!=null,b:K.bOrPlddt});return $&&$.residues.length>0?$.residues.map((K,we)=>{const Se=H.get(K.seqId),Q=G.get(K.seqId),F=we<Z.length?Z[we]:null;return Se?{posIndex:we+1,refSeqId:Se.refSeqId,refCode:Se.resCode1,mobSeqId:Se.mobSeqId,mobCode:K.resCode1,distanceA:Se.distanceAngstrom,refBFactor:Se.refBFactor,mobPlddt:Se.mobPlddt,isMissingRefCoord:!1}:{posIndex:we+1,refSeqId:Q?K.seqId:null,refCode:Q?.hasCa?Q.code:"-",mobSeqId:K.seqId,mobCode:K.resCode1,distanceA:null,refBFactor:Q?.b??null,mobPlddt:K.bOrPlddt,isMissingRefCoord:!Q?.hasCa&&F!=null}}):e?e.matchedResidues.map((K,we)=>({posIndex:we+1,refSeqId:K.refSeqId,refCode:K.resCode1,mobSeqId:K.mobSeqId,mobCode:K.resCode1,distanceA:K.distanceAngstrom,refBFactor:K.refBFactor,mobPlddt:K.mobPlddt,isMissingRefCoord:!1})):[]},[e,r,n,s,i]),j=C.useMemo(()=>{let P=0,$=0,H=0,Z=null,G=0,K=[],we=0,Se=0,Q=0,F=0;for(const he of T){const W=he.refSeqId??he.mobSeqId??he.posIndex;he.distanceA!=null?(P++,$+=he.distanceA,he.distanceA>H&&(H=he.distanceA,Z=W),he.distanceA>=2&&(G++,K.push(W))):Se++,he.mobPlddt!=null&&(Q+=he.mobPlddt,F++,he.mobPlddt<70&&we++)}return{matched:P,meanD:P>0?$/P:0,maxD:H,maxDSeqId:Z,highDevCount:G,highDevSeqIds:K,lowPlddtCount:we,gapCount:Se,meanPlddt:F>0?Q/F:null}},[T]),q=C.useMemo(()=>g==="all"?T:T.filter(P=>g==="high_dev"?P.distanceA!=null&&P.distanceA>=2:g==="low_plddt"?P.mobPlddt!=null&&P.mobPlddt<70:g==="gaps"?P.distanceA==null:!0),[T,g]),z=C.useMemo(()=>T.find(P=>P.refSeqId===c||P.mobSeqId===c)??null,[T,c]),O=C.useMemo(()=>{let P=2;for(const $ of T)$.distanceA!=null&&$.distanceA>P&&(P=$.distanceA);return P},[T]),V=P=>{d(P),f?.focusIn3D(P,{centerCamera:!0})};return T.length===0?o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 p-3 @xl:p-4",children:[o.jsx(ir,{bridge:f,title:"Sequence Alignment & Per-Residue Deviation Track",subtitle:"Compare aligned amino-acid sequences, Cα deviations (Δd), pLDDT confidence, and B-factors residue-by-residue.",icon:o.jsx(Vo,{className:"h-4 w-4"}),guideOpen:k,onToggleGuide:()=>E(P=>!P)}),o.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 rounded-xl border border-white/[0.08] bg-[#0b1018] p-6 text-center text-xs text-slate-400",children:[o.jsx(Vo,{className:"h-8 w-8 text-slate-500"}),o.jsx("div",{className:"text-sm font-medium text-slate-200",children:"No structure pair loaded"}),o.jsx("p",{className:"max-w-md",children:"Load reference and comparison structures to inspect aligned sequence columns and per-residue Cα Δd deviations."}),f&&o.jsxs("button",{type:"button",onClick:f.loadExample,className:"inline-flex items-center gap-1.5 rounded-lg bg-sky-500 px-3.5 py-2 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:[o.jsx(Br,{className:"h-3.5 w-3.5"})," Load CA II Example"]})]})]}):o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3 text-xs @xl:p-4",children:[o.jsx(ir,{bridge:f,title:"Sequence Alignment & Per-Residue Δd Track",subtitle:"Inspect aligned residue columns, structural deviation spikes (Δd), experimental B-factors, and AlphaFold pLDDT.",icon:o.jsx(Vo,{className:"h-4 w-4"}),guideOpen:k,onToggleGuide:()=>E(P=>!P)}),o.jsx(Qi,{open:k,title:"How Sequence Deviation Tracking Works",summary:"Each column aligns a reference residue (top letter, sky blue) to the corresponding comparison/predicted residue (bottom letter, emerald). The bar height and color visualize local structural or confidence differences.",steps:["Switch the bar chart metric between Δd (Å), AlphaFold pLDDT, and Experimental B-factor.","Use the Filter pills to isolate only High-Deviation hotspots (Δd ≥ 2.0 Å), Low-Confidence loops (pLDDT < 70), or Missing Coordinate gaps (-).",'Click any residue column to focus it in the 3D Viewer, or click "Highlight High Δd in 3D" to inspect flexible loops on the 3D model.'],connectionTip:"Every column is directly bound to the 3D scene. Focusing a residue here highlights it in the 3D Viewer, updates the Peptide & CRISPR workbenches, and allows 1-click navigation to Ramachandran angles."}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 @lg:grid-cols-4",children:[o.jsx(bs,{label:"Aligned / Total",value:`${j.matched} / ${T.length}`,hint:`${j.gapCount} missing coords (-)`}),o.jsx(bs,{label:"Mean Δd",value:`${j.meanD.toFixed(3)} Å`,hint:"Average Cα offset"}),o.jsxs("button",{type:"button",onClick:()=>j.maxDSeqId!==null&&V(j.maxDSeqId),disabled:j.maxDSeqId===null,className:"min-w-0 rounded-lg border border-amber-400/25 bg-amber-500/[0.06] px-2.5 py-2 text-left transition hover:border-amber-400/50 disabled:opacity-50",title:"Click to jump to the highest-deviating residue",children:[o.jsx("div",{className:"truncate text-[0.6875rem] text-amber-300",children:"Max Δd (Jump ↗)"}),o.jsxs("div",{className:"mt-0.5 truncate font-mono text-sm font-semibold text-amber-200 tabular-nums",children:[j.maxD.toFixed(2)," Å ",j.maxDSeqId!==null?`(#${j.maxDSeqId})`:""]}),o.jsxs("div",{className:"mt-0.5 truncate text-[0.625rem] text-slate-400",children:[j.highDevCount," res ≥ 2.0 Å"]})]}),o.jsx(bs,{label:"Mean pLDDT",value:j.meanPlddt!==null?j.meanPlddt.toFixed(1):"n/a",hint:j.meanPlddt!==null?`${j.lowPlddtCount} res < 70`:"No pLDDT"})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-xl border border-white/[0.08] bg-[#0b1018] p-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx("span",{className:"text-[0.6875rem] text-slate-400",children:"Bar Metric:"}),[["deviation","Δd (Å)"],["plddt","pLDDT"],["bfactor","B-Factor"]].map(([P,$])=>o.jsx("button",{type:"button",onClick:()=>{x(P),f?.setColorMode3D(P)},className:`rounded-md border px-2 py-1 font-mono text-[0.6875rem] transition ${b===P?"border-sky-400/50 bg-sky-500/20 text-sky-200":"border-white/10 bg-slate-900 text-slate-400 hover:text-slate-200"}`,children:$},P))]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[[["all",`All (${T.length})`],["high_dev",`Δd ≥ 2Å (${j.highDevCount})`],["low_plddt",`pLDDT < 70 (${j.lowPlddtCount})`],["gaps",`Gaps (${j.gapCount})`]].map(([P,$])=>o.jsx("button",{type:"button",onClick:()=>_(P),className:`rounded-md border px-2 py-1 text-[0.6875rem] transition ${g===P?"border-emerald-400/50 bg-emerald-500/20 text-emerald-200":"border-white/10 bg-slate-900 text-slate-400 hover:text-slate-200"}`,children:$},P)),f&&j.highDevSeqIds.length>0&&o.jsxs("button",{type:"button",onClick:()=>f.highlightIn3D(j.highDevSeqIds,"High Δd ≥ 2.0 Å",{focusSeqId:j.maxDSeqId??j.highDevSeqIds[0]}),className:"inline-flex items-center gap-1 rounded-md border border-rose-400/40 bg-rose-500/15 px-2 py-1 text-[0.6875rem] font-medium text-rose-200 hover:bg-rose-500/25",children:[o.jsx(_s,{className:"h-3 w-3"})," Highlight High Δd in 3D"]})]}),o.jsxs("form",{onSubmit:P=>{P.preventDefault();const $=Number.parseInt(y.trim(),10);Number.isFinite($)&&$>0&&V($)},className:"flex items-center gap-1",children:[o.jsx("input",{value:y,onChange:P=>S(P.target.value),placeholder:"Jump res #",className:"h-7 w-20 rounded-md border border-white/10 bg-slate-950 px-2 font-mono text-[0.6875rem] text-slate-200 outline-none focus:border-sky-400"}),o.jsx("button",{type:"submit",className:"h-7 rounded-md border border-white/10 bg-white/[0.04] px-2 text-[0.6875rem] text-slate-300 hover:text-white",children:"Go"})]})]}),o.jsx("div",{ref:p,className:"min-h-36 flex-1 overflow-x-auto overflow-y-hidden rounded-xl border border-white/[0.08] bg-[#070a10] p-3",children:q.length===0?o.jsx("div",{className:"flex h-full items-center justify-center text-slate-500",children:"No residues match this filter."}):o.jsx("div",{className:"inline-flex min-w-max items-end gap-[3px]",children:q.map(P=>{const $=P.refSeqId??P.mobSeqId??P.posIndex,H=c!=null&&(P.refSeqId===c||P.mobSeqId===c);let Z=3,G=[71,85,105],K=!1;return b==="deviation"&&P.distanceA!=null?(K=!0,Z=Math.max(4,Math.round(P.distanceA/O*56)),G=Vd(P.distanceA)):b==="plddt"&&P.mobPlddt!=null?(K=!0,Z=Math.max(4,Math.round(P.mobPlddt/100*56)),G=ky(P.mobPlddt)):b==="bfactor"&&P.refBFactor!=null&&(K=!0,Z=Math.max(4,Math.min(56,Math.round(P.refBFactor/60*56))),G=Cy(P.refBFactor)),o.jsxs("button",{type:"button",onClick:()=>V($),title:`Pos ${P.posIndex} | Ref: ${P.refCode}${P.refSeqId??"-"} | Mob: ${P.mobCode}${P.mobSeqId??"-"} | Δd=${P.distanceA!=null?`${P.distanceA.toFixed(3)} Å`:"missing"} | B=${P.refBFactor??"n/a"} | pLDDT=${P.mobPlddt??"n/a"}`,className:`group flex w-4.5 shrink-0 flex-col items-center rounded py-1 font-mono transition ${H?"bg-amber-500/25 ring-1 ring-amber-400":"hover:bg-slate-800/80"}`,children:[o.jsx("span",{className:"h-3.5 text-[0.5625rem] text-slate-500",children:P.posIndex%10===0||P.posIndex===1?P.posIndex:""}),o.jsx("div",{className:"flex h-15 w-full items-end justify-center pb-1",children:o.jsx("div",{className:"w-2.5 rounded-t-[2px] transition-all",style:{height:`${Z}px`,backgroundColor:lL(G),opacity:K?.94:.3}})}),o.jsx("span",{className:`text-[0.75rem] font-semibold leading-tight ${P.refCode==="-"?"text-amber-400":"text-sky-300"}`,children:P.refCode}),o.jsx("span",{className:"text-[0.75rem] leading-tight text-emerald-300",children:P.mobCode})]},`${P.posIndex}-${P.mobSeqId??""}`)})})}),z?o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-amber-400/35 bg-amber-500/[0.06] px-3 py-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3 font-mono text-xs text-amber-100",children:[o.jsxs("span",{className:"font-semibold text-amber-200",children:["Focus: ",z.mobCode,z.refSeqId??z.mobSeqId]}),o.jsxs("span",{children:["Δd=",z.distanceA!=null?`${z.distanceA.toFixed(3)} Å`:"gap (-)"]}),o.jsxs("span",{children:["B=",z.refBFactor!=null?`${z.refBFactor.toFixed(2)} Ų`:"n/a"]}),o.jsxs("span",{children:["pLDDT=",z.mobPlddt!=null?z.mobPlddt.toFixed(1):"n/a"]}),z.mobPlddt!==null&&o.jsx("span",{className:"font-sans",children:o.jsx(Ca,{insight:wE(z.mobPlddt),compact:!0})})]}),f&&o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs("button",{type:"button",onClick:()=>f.focusIn3D(z.refSeqId??z.mobSeqId??z.posIndex,{centerCamera:!0,openViewer:"activate"}),className:"inline-flex items-center gap-1 rounded-md border border-sky-400/40 bg-sky-500/15 px-2 py-1 text-[0.6875rem] font-medium text-sky-200 hover:bg-sky-500/25",children:[o.jsx(Ur,{className:"h-3 w-3"})," Focus in 3D"]}),o.jsxs("button",{type:"button",onClick:()=>f.sendResidueToRamachandran(z.refSeqId??z.mobSeqId??z.posIndex),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-cyan-400/40",children:[o.jsx(Qo,{className:"h-3 w-3 text-cyan-300"})," Ramachandran"]}),o.jsxs("button",{type:"button",onClick:()=>{const P=z.refSeqId??z.mobSeqId??z.posIndex,$=z.mobCode!=="-"?z.mobCode:z.refCode;f.sendMutationToPeptide(`${$}${P}A`,P)},className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-emerald-400/40",children:[o.jsx(ar,{className:"h-3 w-3 text-emerald-300"})," Ala Scan"]}),o.jsxs("button",{type:"button",onClick:()=>f.sendResidueToCrispr(z.refSeqId??z.mobSeqId??z.posIndex),className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.04] px-2 py-1 text-[0.6875rem] text-slate-200 hover:border-violet-400/40",children:[o.jsx(Fs,{className:"h-3 w-3 text-violet-300"})," CRISPR Codon"]})]})]}):o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 font-mono text-[0.6875rem] text-slate-400",children:[o.jsx("span",{children:"Click any column to synchronize 3D Viewer, Peptide, CRISPR & Ramachandran."}),o.jsx("span",{className:"text-amber-300/90",children:"[-] = Missing coordinates in experimental structure"})]})]})}const SE=[[{id:"account",label:"Account",icon:o.jsx(ah,{className:"h-4 w-4"}),keywords:"sign in sign out profile email synlexa.com login"},{id:"usage",label:"Usage",icon:o.jsx(yR,{className:"h-4 w-4"}),keywords:"tokens requests cost history"}],[{id:"ai",label:"AI & API keys",icon:o.jsx(tp,{className:"h-4 w-4"}),keywords:"assistant claude anthropic gemini google model byok key synlexa cloud"}],[{id:"viewer",label:"3D viewer",icon:o.jsx(A6,{className:"h-4 w-4"}),keywords:"render style color cartoon surface layout png report"},{id:"workspace",label:"Workspace",icon:o.jsx(VA,{className:"h-4 w-4"}),keywords:"interface size scale zoom text tabs layout auto-save guided demo"}],[{id:"data",label:"Data & storage",icon:o.jsx(Vi,{className:"h-4 w-4"}),keywords:"library export import backup clear history storage"}]],pp={id:"about",label:"About",icon:o.jsx(zy,{className:"h-4 w-4"}),keywords:"version license engine keyboard shortcuts research use only"},Mx=[...SE.flat(),pp];function MA({item:e,active:r,onSelect:n}){return o.jsxs("button",{type:"button",onClick:n,"aria-current":r?"page":void 0,className:Ie("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-[0.4375rem] text-left text-sm transition-colors",r?"bg-white/[0.08] text-white":"text-slate-300 hover:bg-white/[0.04] hover:text-white"),children:[o.jsx("span",{className:r?"text-white":"text-slate-400",children:e.icon}),e.label]})}function kL(e){const{open:r,onClose:n,section:s,onSectionChange:i}=e,[c,d]=C.useState(""),f=C.useRef(null),p=C.useRef(null);C.useEffect(()=>{if(!r)return;d("");const k=E=>{E.key==="Escape"&&(E.stopPropagation(),n())};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[r,n]),C.useEffect(()=>{p.current?.scrollTo({top:0})},[s]);const b=c.trim().toLowerCase(),x=k=>!b||`${k.label} ${k.keywords}`.toLowerCase().includes(b),g=SE.map(k=>k.filter(x)).filter(k=>k.length>0),_=x(pp),y=g.length>0||_;if(!r)return null;const S=Mx.find(k=>k.id===s)??Mx[0];return o.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/55 p-3 backdrop-blur-[2px] sm:p-6",onMouseDown:k=>{k.target===k.currentTarget&&n()},children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Settings",className:"flex h-[min(46rem,100%)] w-[min(64rem,100%)] flex-col overflow-hidden rounded-2xl border border-white/10 bg-[#161a22] shadow-[0_24px_80px_-12px_rgba(0,0,0,0.7)]",children:[o.jsxs("div",{className:"flex h-12 shrink-0 items-center justify-between border-b border-white/[0.07] pr-2 pl-5",children:[o.jsx("h2",{className:"text-[0.9375rem] font-semibold text-slate-100",children:"Settings"}),o.jsx(sl,{label:"Close settings",onClick:n,children:o.jsx(Xi,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col md:flex-row",children:[o.jsxs("aside",{className:"hidden w-60 shrink-0 flex-col border-r border-white/[0.07] md:flex",children:[o.jsx("div",{className:"p-3 pb-2",children:o.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-white/[0.05] px-2.5 py-1.5 focus-within:ring-1 focus-within:ring-sky-400/50",children:[o.jsx(Gr,{className:"h-4 w-4 shrink-0 text-slate-500"}),o.jsx("input",{ref:f,value:c,onChange:k=>d(k.target.value),onKeyDown:k=>{if(k.key==="Enter"){const E=[...g.flat(),..._?[pp]:[]][0];E&&i(E.id)}},placeholder:"Search","aria-label":"Search settings",className:"min-w-0 flex-1 bg-transparent text-sm text-slate-100 placeholder:text-slate-500 focus:outline-none"})]})}),o.jsxs("nav",{className:"min-h-0 flex-1 overflow-y-auto px-3 pb-3",children:[g.map((k,E)=>o.jsx("div",{className:Ie("space-y-0.5 py-1.5",E>0&&"border-t border-white/[0.06]"),children:k.map(T=>o.jsx(MA,{item:T,active:s===T.id,onSelect:()=>i(T.id)},T.id))},k[0].id)),!y&&o.jsxs("p",{className:"px-2.5 py-2 text-sm text-slate-500",children:["No settings match “",c,"”."]})]}),_&&o.jsx("div",{className:"border-t border-white/[0.06] p-3",children:o.jsx(MA,{item:pp,active:s==="about",onSelect:()=>i("about")})})]}),o.jsx("div",{className:"flex shrink-0 gap-1 overflow-x-auto border-b border-white/[0.07] px-3 py-2 [scrollbar-width:none] md:hidden",children:Mx.map(k=>o.jsxs("button",{type:"button",onClick:()=>i(k.id),className:Ie("flex shrink-0 items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs whitespace-nowrap",s===k.id?"bg-white/[0.08] text-white":"text-slate-400 hover:bg-white/[0.04]"),children:[k.icon,k.label]},k.id))}),o.jsx("div",{ref:p,className:"@container min-w-0 flex-1 overflow-y-auto","aria-label":S.label,children:o.jsxs("div",{className:"mx-auto max-w-3xl space-y-5 px-5 py-6 @2xl:px-8",children:[s==="account"&&o.jsx(CL,{...e}),s==="ai"&&o.jsx(jL,{...e}),s==="usage"&&o.jsx(TL,{}),s==="viewer"&&o.jsx(EL,{}),s==="workspace"&&o.jsx(ML,{onResetLayout:e.onResetLayout}),s==="data"&&o.jsx(RL,{onClearedHistory:e.onClearedHistory}),s==="about"&&o.jsx(OL,{})]})})]})]})})}function ul({title:e,description:r}){return o.jsxs("div",{className:"pb-1",children:[o.jsx("h1",{className:"text-xl font-semibold text-slate-100",children:e}),r&&o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:r})]})}function CL({session:e,onSessionChange:r,onSignIn:n,onCancelSignIn:s,signInPending:i,aiConfig:c}){const{confirm:d,toast:f}=cl(),p=(e?.displayName??e?.email??"?").split(/[\s@.]+/).filter(Boolean).slice(0,2).map(b=>b[0]?.toUpperCase()).join("");return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"Account",description:"Your synlexa.com connection and how Studio uses it."}),o.jsx(yt,{children:e?o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-gradient-to-br from-sky-400 to-indigo-500 text-base font-semibold text-white",children:p||o.jsx(ah,{className:"h-5 w-5"})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"truncate text-base font-medium text-slate-100",children:e.displayName??e.email??"Signed in"}),o.jsx("div",{className:"truncate text-sm text-slate-400",children:e.email??"Email not shared"}),o.jsxs("div",{className:"mt-1.5 flex gap-1.5",children:[e.serverVerified?o.jsx(It,{tone:"good",children:"Verified by synlexa.com"}):o.jsx(It,{tone:"warn",children:"Not confirmed by synlexa.com"}),o.jsxs(It,{children:["Since ",new Date(e.establishedAtUtc).toLocaleDateString()]})]})]}),!e.serverVerified&&o.jsx(Oe,{variant:"primary",disabled:i,onClick:()=>n("signin"),children:i?"Waiting…":"Reconnect"}),o.jsx(Oe,{variant:"ghost",icon:o.jsx(k6,{className:"h-4 w-4"}),onClick:async()=>{await d({title:"Sign out?",message:"Your local library, settings, and API keys stay on this device.",confirmLabel:"Sign out"})&&(UI(),r(null),f("Signed out","success"))},children:"Sign out"})]}):i?o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-sky-400/10 text-sky-300",children:o.jsx(qs,{className:"h-5 w-5 animate-spin"})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-base font-medium text-slate-100",children:"Waiting for synlexa.com…"}),o.jsx("div",{className:"text-sm text-slate-400",children:"Finish signing in in the window that opened. Studio connects automatically."})]})]}),o.jsx(Oe,{variant:"ghost",onClick:s,children:"Cancel"})]}):o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-white/[0.06] text-slate-400",children:o.jsx(ah,{className:"h-5 w-5"})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-base font-medium text-slate-100",children:"Not signed in"}),o.jsx("div",{className:"text-sm text-slate-400",children:"Studio works fully offline. Sign in to use Synlexa Cloud and connect your organization."})]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Oe,{variant:"ghost",onClick:()=>n("signup"),children:"Create account"}),o.jsx(Oe,{variant:"primary",onClick:()=>n("signin"),children:"Sign in"})]})]})}),o.jsx(yt,{title:"Where your data lives",children:o.jsxs("ul",{className:"space-y-2 text-sm text-slate-300",children:[o.jsxs("li",{className:"flex gap-2",children:[o.jsx(Gs,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-400"}),"Structures, compounds, and your library are stored in this browser (IndexedDB) and never uploaded."]}),o.jsxs("li",{className:"flex gap-2",children:[o.jsx(Gs,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-400"}),"Calculations run locally in the WebAssembly engine."]}),o.jsxs("li",{className:"flex gap-2",children:[o.jsx(Gs,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-400"}),c[c.provider]?.apiKey?c.provider==="synlexa"?o.jsx(o.Fragment,{children:"AI requests go through synlexa.com to Google Gemini, with a summary of the loaded workspace. Synlexa does not store prompts or replies."}):o.jsxs(o.Fragment,{children:["AI requests go directly from this browser to"," ",c.provider==="anthropic"?"Anthropic":"Google"," using your own key, with a summary of the loaded workspace."]}):o.jsx(o.Fragment,{children:"Nothing is sent to an AI provider until you sign in for Synlexa Cloud or add your own key. The built-in assistant runs locally."})]})]})})]})}function NL({provider:e,value:r,onSave:n}){const[s,i]=C.useState(""),[c,d]=C.useState(!1),f=s.length>0;return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("div",{className:"relative min-w-0 flex-1",children:[o.jsx(Dn,{type:c?"text":"password",value:s,onChange:p=>i(p.target.value),placeholder:r?ZI(r):es[e].keyHint,autoComplete:"off",spellCheck:!1,className:"pr-9 font-mono text-[0.8125rem]",onKeyDown:p=>{p.key==="Enter"&&s.trim()&&(n(s.trim()),i(""))}}),o.jsx("button",{type:"button",onClick:()=>d(p=>!p),"aria-label":c?"Hide key":"Show key",className:"absolute top-1/2 right-2 -translate-y-1/2 text-slate-500 hover:text-slate-200",children:c?o.jsx(WR,{className:"h-4 w-4"}):o.jsx(LA,{className:"h-4 w-4"})})]}),f?o.jsx(Oe,{variant:"primary",onClick:()=>{n(s.trim()),i("")},children:"Save"}):r?o.jsx(Oe,{variant:"ghost",onClick:()=>n(""),children:"Remove"}):null]})}async function AL(e,r,n){if(e==="anthropic"){const c=new aa({apiKey:r,dangerouslyAllowBrowser:!0,maxRetries:0});try{const d=await c.models.retrieve(n);return`Connected · ${d.display_name??d.id}`}catch(d){throw d instanceof aa.AuthenticationError?new Error("Invalid API key"):d instanceof aa.NotFoundError?new Error(`Model "${n}" not available for this key`):d instanceof aa.APIConnectionError?new Error("Could not reach api.anthropic.com"):d instanceof Error?d:new Error(String(d))}}if(e==="openai"){const c=await fetch(`https://api.openai.com/v1/models/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`}}),d=await c.json().catch(()=>({}));if(!c.ok)throw new Error(d.error?.message??`HTTP ${c.status}`);return`Connected · ${d.id??n}`}const s=await fetch(`${y3}/${encodeURIComponent(n)}`,{headers:{"x-goog-api-key":r}}),i=await s.json().catch(()=>({}));if(!s.ok)throw new Error(i.error?.message??`HTTP ${s.status}`);return`Connected · ${i.displayName??n}`}function jL({aiConfig:e,onUpdateAiConfig:r,onPermissionsChange:n,session:s,onSignIn:i,signInPending:c}){const[d,f]=C.useState(null),[p,b]=C.useState({}),[x,g]=C.useState(()=>Zo()),[_,y]=C.useState(()=>t0());C.useEffect(()=>f3(()=>g(Zo())),[]);const S=Xc(e),k=e.routingPreference??"byok-first",E=(j,q)=>{const z=gI({..._,[j]:q});y(z),n?.(z)},T=async j=>{f(j);try{const q=e[j]??{apiKey:"",model:""},z=await AL(j,q.apiKey,q.model);b(O=>({...O,[j]:{ok:!0,msg:z}}))}catch(q){b(z=>({...z,[j]:{ok:!1,msg:q instanceof Error?q.message:String(q)}}))}finally{f(null)}};return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"AI & API keys",description:"Bring your own Anthropic, Gemini, or OpenAI/Codex key (BYOK), or choose Synlexa Cloud. When a BYOK key is entered in default mode, Studio routes directly to your provider instead of Synlexa Cloud."}),o.jsx(yt,{title:"Active AI routing & key priority",description:"Control whether your local BYOK keys always override Synlexa Cloud or whether you switch manually.",actions:o.jsx(It,{tone:S.isByok?"good":S.hasCloudToken?"accent":"neutral",children:S.isByok?`Using BYOK (${es[S.provider].label})`:S.provider==="synlexa"&&S.hasCloudToken?"Using Synlexa Cloud":"Local Deterministic Copilot"}),children:o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsx("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 text-xs",children:o.jsxs("div",{className:"flex items-center gap-2 text-slate-200",children:[o.jsx(Ki,{className:"h-4 w-4 shrink-0 text-emerald-400"}),S.isByok?o.jsxs("span",{children:["Requests go directly to ",o.jsx("strong",{children:es[S.provider].label})," using your encrypted BYOK key — Synlexa Cloud is bypassed."]}):S.provider==="synlexa"&&S.hasCloudToken?o.jsxs("span",{children:["Requests route through ",o.jsx("strong",{children:"Synlexa Cloud"})," (`synlexa.com` account).",S.hasByok?" (Manual override active; your BYOK keys are saved for instant switch.)":""]}):o.jsx("span",{children:"No BYOK key or Cloud token active — using offline deterministic Copilot."})]})}),o.jsx(Qt,{label:"Key routing priority",hint:"Prefer BYOK guarantees your personal API key is used instead of Synlexa Cloud whenever any key is saved.",children:o.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.jsx(Oe,{size:"sm",variant:k==="byok-first"?"primary":"secondary",onClick:()=>{const j=["anthropic","gemini","openai"].find(q=>!!e[q]?.apiKey?.trim());r({routingPreference:"byok-first",...j&&e.provider==="synlexa"?{provider:j}:{}})},children:"Prefer BYOK keys"}),o.jsx(Oe,{size:"sm",variant:k==="manual"?"primary":"secondary",onClick:()=>r({routingPreference:"manual"}),children:"Choose manually (BYOK / Cloud)"})]})})]})}),o.jsx(yt,{title:"Encrypted Local Key Vault (state.vscdb)",description:"BYOK keys are stored in the local ItemTable store and encrypted with a non-extractable key.",actions:o.jsx(It,{tone:"good",children:x.cipher}),children:o.jsxs("div",{className:"divide-y divide-white/[0.05] text-sm",children:[o.jsx(Qt,{label:"Storage backend",hint:"Never saved inside project files or plain-text localStorage.",children:o.jsx("span",{className:"font-mono text-xs text-sky-300",children:x.dbPath})}),o.jsx(Qt,{label:"Allow AI scientific web search",hint:"Lets the assistant query Europe PMC & ClinicalTrials.gov via MCP.",children:o.jsx($r,{checked:e.enableWebSearch!==!1,onChange:j=>r({enableWebSearch:j}),label:"Allow AI scientific web search"})})]})}),o.jsxs(yt,{title:"Default assistant",description:"Choose between your BYOK providers or Synlexa Cloud.",children:[o.jsx("div",{className:"grid gap-3 @lg:grid-cols-2",children:Uv.map(j=>{const q=S.provider===j,z=e[j]??{apiKey:"",model:es[j].models[0]?.id??""},O=!!z.apiKey,V=es[j].models.find(P=>P.id===z.model)?.label??z.model;return o.jsxs("button",{type:"button",onClick:()=>r({provider:j,...j==="synlexa"&&S.hasByok?{routingPreference:"manual"}:{}}),className:Ie("rounded-xl border p-4 text-left transition-colors",q?"border-sky-400/60 bg-sky-500/[0.07]":"border-white/10 hover:border-white/20 hover:bg-white/[0.02]"),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm font-semibold text-slate-100",children:es[j].label}),o.jsx("span",{className:Ie("h-4 w-4 rounded-full border-2",q?"border-sky-400 bg-sky-400 shadow-[inset_0_0_0_2px_#121722]":"border-slate-600")})]}),o.jsx("div",{className:"mt-1 text-xs text-slate-400",children:j==="synlexa"?O?`Signed in · ${V}`:"Sign in required":O?`BYOK key encrypted · ${V}`:"No key yet"})]},j)})}),!e[S.provider]?.apiKey&&o.jsx("p",{className:"mt-3 text-xs text-slate-400",children:"Until you add a BYOK key or sign in to Synlexa Cloud, the assistant answers with the built-in deterministic helper."})]}),o.jsxs(yt,{title:"Synlexa Cloud",description:"Gemini through your synlexa.com account. Used only when selected and no BYOK override is active.",children:[o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"Account",hint:e.synlexa.apiKey?"Connected":"Not connected",children:e.synlexa.apiKey?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-200",children:[o.jsx(Gs,{className:"h-4 w-4 text-emerald-400"}),s?.email??s?.displayName??"Signed in"]}):o.jsxs(Oe,{size:"sm",variant:"primary",disabled:c,onClick:()=>i("signin"),children:[c?o.jsx(qs,{className:"h-3.5 w-3.5 animate-spin"}):null,c?"Waiting for synlexa.com…":s?"Reconnect to synlexa.com":"Sign in to synlexa.com"]})}),o.jsx(Qt,{label:"Model",children:o.jsx("div",{className:"w-full @xl:w-80",children:o.jsx(Na,{value:e.synlexa.model,onChange:j=>r({synlexa:{model:j.target.value}}),children:es.synlexa.models.map(j=>o.jsxs("option",{value:j.id,children:[j.label," — ",j.note]},j.id))})})})]}),s&&!e.synlexa.apiKey&&o.jsx("p",{className:"mt-3 text-xs text-slate-400",children:"Your current sign-in was not confirmed by synlexa.com, so Studio has no account token. Sign in again to connect."})]}),["anthropic","gemini","openai"].map(j=>{const q=es[j],z=e[j]??{apiKey:"",model:q.models[0]?.id??""},O=q.models.some(P=>P.id===z.model),V=p[j];return o.jsxs(yt,{title:q.label,description:o.jsxs(o.Fragment,{children:["Get a key at"," ",o.jsx("a",{href:q.keyUrl,target:"_blank",rel:"noreferrer",className:"text-sky-300 hover:underline",children:new URL(q.keyUrl).host})]}),actions:o.jsxs(Oe,{size:"sm",disabled:!z.apiKey||d!==null,onClick:()=>void T(j),children:[d===j?o.jsx(qs,{className:"h-3.5 w-3.5 animate-spin"}):null,"Test connection"]}),children:[o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"API key",hint:z.apiKey?"Encrypted in state.vscdb · Active when saved":"Not set",children:o.jsx("div",{className:"w-full @xl:w-80",children:o.jsx(NL,{provider:j,value:z.apiKey,onSave:P=>{const $=P.trim();r({[j]:{apiKey:$},...$?{provider:j}:{}}),b(H=>({...H,[j]:void 0}))}})})}),o.jsx(Qt,{label:"Model",children:o.jsxs("div",{className:"w-full space-y-2 @xl:w-80",children:[o.jsxs(Na,{value:O?z.model:"__custom",onChange:P=>{P.target.value!=="__custom"?r({[j]:{model:P.target.value}}):r({[j]:{model:""}})},children:[q.models.map(P=>o.jsxs("option",{value:P.id,children:[P.label," — ",P.note]},P.id)),o.jsx("option",{value:"__custom",children:"Custom model ID…"})]}),!O&&o.jsx(Dn,{defaultValue:z.model,placeholder:"exact model ID",className:"font-mono text-[0.8125rem]",onBlur:P=>P.target.value.trim()&&r({[j]:{model:P.target.value.trim()}})})]})})]}),V&&o.jsx("div",{className:Ie("mt-3 rounded-lg px-3 py-2 text-sm",V.ok?"bg-emerald-500/10 text-emerald-200":"bg-rose-500/10 text-rose-200"),children:V.msg}),j==="anthropic"&&(z.model==="claude-opus-5-5"||z.model==="claude-sonnet-5-5")&&o.jsx("p",{className:"mt-3 text-xs text-slate-500",children:"If the selected model declines a request, the API automatically retries it on a fallback model (server-side fallback)."})]},j)}),o.jsx(yt,{title:"Agent Tool Permissions",description:"Control when the AI Assistant asks for interactive confirmation before acting across Studio tools.",children:o.jsx("div",{className:"divide-y divide-white/[0.05]",children:Object.keys(Z5).map(j=>{const q=Z5[j];return o.jsx(Qt,{label:q.label,hint:q.description,children:o.jsxs(Na,{value:_[j],onChange:z=>E(j,z.target.value),className:"w-44",children:[o.jsx("option",{value:"ask",children:"Ask before running"}),o.jsx("option",{value:"always-allow",children:"Always allow"}),o.jsx("option",{value:"deny",children:"Block (deny)"})]})},j)})})})]})}function TL(){const[e,r]=C.useState(iy),[n,s]=C.useState(30),{confirm:i}=cl();C.useEffect(()=>vI(()=>r(iy())),[]);const c=C.useMemo(()=>SI(e,n),[e,n]),d=Math.max(1,...c.days.map(p=>p.tokens)),f=new Intl.NumberFormat;return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"Usage",description:"AI requests and tokens made from this browser, as reported by each provider. Billing happens on your provider account."}),o.jsx("div",{className:"flex gap-1",children:[7,30].map(p=>o.jsxs("button",{type:"button",onClick:()=>s(p),className:Ie("rounded-lg px-3 py-1.5 text-sm",n===p?"bg-white/[0.1] text-white":"text-slate-400 hover:bg-white/[0.05]"),children:["Last ",p," days"]},p))}),o.jsx("div",{className:"grid grid-cols-2 gap-3 @2xl:grid-cols-4",children:[["Requests",c.totals.requests],["Input tokens",c.totals.inputTokens],["Output tokens",c.totals.outputTokens],["Tool calls",c.totals.toolCalls]].map(([p,b])=>o.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] p-4",children:[o.jsx("div",{className:"text-xs text-slate-400",children:p}),o.jsx("div",{className:"mt-1 text-2xl font-semibold text-slate-100 tabular-nums",children:f.format(b)})]},p))}),o.jsxs(yt,{title:"Tokens per day",children:[o.jsx("div",{className:"flex h-32 items-end gap-[3px]",children:c.days.map(p=>o.jsxs("div",{className:"group relative flex h-full flex-1 items-end",children:[o.jsx("div",{className:"w-full rounded-t-sm bg-sky-400/70 transition-colors group-hover:bg-sky-300",style:{height:`${p.tokens?Math.max(3,p.tokens/d*100):0}%`}}),o.jsxs("div",{className:"pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 hidden -translate-x-1/2 rounded-md bg-black/90 px-2 py-1 text-xs whitespace-nowrap text-slate-200 group-hover:block",children:[p.date,": ",f.format(p.tokens)," tokens · ",p.requests," req"]})]},p.date))}),o.jsxs("div",{className:"mt-2 flex justify-between text-xs text-slate-500",children:[o.jsx("span",{children:c.days[0]?.date}),o.jsx("span",{children:"Today"})]})]}),o.jsx(yt,{title:"By model",actions:o.jsx(Oe,{size:"sm",variant:"ghost",disabled:!e.length,onClick:async()=>{await i({title:"Clear usage history?",message:"This only resets the local counters.",confirmLabel:"Clear"})&&wI()},children:"Reset counters"}),children:c.byProvider.length===0?o.jsx("div",{className:"text-sm text-slate-400",children:"No AI requests in this period."}):o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"text-left text-xs text-slate-500",children:[o.jsx("th",{className:"pb-2 font-medium",children:"Model"}),o.jsx("th",{className:"pb-2 text-right font-medium",children:"Requests"}),o.jsx("th",{className:"pb-2 text-right font-medium",children:"Input"}),o.jsx("th",{className:"pb-2 text-right font-medium",children:"Output"}),o.jsx("th",{className:"pb-2 text-right font-medium",children:"Errors"})]})}),o.jsx("tbody",{className:"tabular-nums",children:c.byProvider.map(([p,b])=>{const[x,g]=p.split("::");return o.jsxs("tr",{className:"border-t border-white/[0.05]",children:[o.jsxs("td",{className:"py-2",children:[o.jsx("span",{className:"text-slate-200",children:g})," ",o.jsx("span",{className:"text-xs text-slate-500",children:x==="local"?"built-in":x})]}),o.jsx("td",{className:"py-2 text-right text-slate-300",children:f.format(b.requests)}),o.jsx("td",{className:"py-2 text-right text-slate-300",children:f.format(b.inputTokens)}),o.jsx("td",{className:"py-2 text-right text-slate-300",children:f.format(b.outputTokens)}),o.jsx("td",{className:Ie("py-2 text-right",b.errors?"text-rose-300":"text-slate-500"),children:b.errors})]},p)})})]})})]})}function EL(){const[e,r]=Zv(),n=e.viewer,s=i=>r(c=>({...c,viewer:{...c.viewer,...i}}));return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"3D viewer",description:"Defaults applied when Studio opens."}),o.jsx(yt,{children:o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"Representation",children:o.jsxs(Na,{className:"w-full @xl:w-56",value:n.defaultStyle,onChange:i=>s({defaultStyle:i.target.value}),children:[o.jsx("option",{value:"ribbon",children:"Ribbon"}),o.jsx("option",{value:"trace",children:"Cα trace"}),o.jsx("option",{value:"pocket",children:"Active pocket"})]})}),o.jsx(Qt,{label:"Color by",children:o.jsxs(Na,{className:"w-full @xl:w-56",value:n.defaultColorMode,onChange:i=>s({defaultColorMode:i.target.value}),children:[o.jsx("option",{value:"identity",children:"Structure identity"}),o.jsx("option",{value:"plddt",children:"pLDDT (predictions)"}),o.jsx("option",{value:"bfactor",children:"B-factor (experimental)"}),o.jsx("option",{value:"deviation",children:"Per-residue deviation Δd"})]})}),o.jsx(Qt,{label:"Layout",children:o.jsxs(Na,{className:"w-full @xl:w-56",value:n.defaultLayout,onChange:i=>s({defaultLayout:i.target.value}),children:[o.jsx("option",{value:"overlay",children:"Overlay"}),o.jsx("option",{value:"split",children:"Side by side"}),o.jsx("option",{value:"reference",children:"Reference only"}),o.jsx("option",{value:"mobile",children:"Comparison only"})]})}),o.jsx(Qt,{label:"Embed viewport image in HTML reports",children:o.jsx($r,{checked:n.embedPngInReports,onChange:i=>s({embedPngInReports:i})})})]})}),o.jsxs(yt,{title:"Controls",children:[o.jsxs("dl",{className:"grid grid-cols-[11rem_1fr] gap-y-2.5 text-sm",children:[o.jsx("dt",{className:"text-slate-400",children:"Rotate"}),o.jsx("dd",{className:"text-slate-200",children:"Drag · one-finger drag"}),o.jsx("dt",{className:"text-slate-400",children:"Zoom"}),o.jsx("dd",{className:"text-slate-200",children:"Scroll · trackpad pinch · two-finger pinch"}),o.jsx("dt",{className:"text-slate-400",children:"Pan"}),o.jsx("dd",{className:"text-slate-200",children:"Shift + drag · right-drag · two-finger drag"}),o.jsx("dt",{className:"text-slate-400",children:"Select residue"}),o.jsx("dd",{className:"text-slate-200",children:"Click"})]}),o.jsx("p",{className:"mt-3 text-xs text-slate-500",children:"Pinch and ctrl-scroll only zoom the 3D scene; the rest of the interface stays fixed."})]})]})}function ML({onResetLayout:e}){const[r,n]=Zv(),{toast:s}=cl();return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"Workspace",description:"Interface size, tabs, and behavior."}),o.jsx(yt,{children:o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"Interface size",hint:o.jsxs(o.Fragment,{children:["Also ",o.jsx(Rr,{children:"⌘"})," ",o.jsx(Rr,{children:"+"})," / ",o.jsx(Rr,{children:"⌘"})," ",o.jsx(Rr,{children:"−"})," / ",o.jsx(Rr,{children:"⌘"})," ",o.jsx(Rr,{children:"0"})]}),children:o.jsxs("div",{className:"flex w-full items-center gap-3 @xl:w-64",children:[o.jsx("input",{type:"range",min:nE,max:sE,step:aE,value:r.uiScale,onChange:i=>n({uiScale:Number(i.target.value)}),className:"flex-1 accent-sky-400","aria-label":"Interface size"}),o.jsxs("span",{className:"w-12 text-right text-sm text-slate-300 tabular-nums",children:[Math.round(r.uiScale*100),"%"]})]})}),o.jsx(Qt,{label:"Guided explanations",hint:"Plain-language notes next to metrics and in tools.",children:o.jsx($r,{checked:r.guidedMode,onChange:i=>n({guidedMode:i})})}),o.jsx(Qt,{label:"Reopen tabs on launch",children:o.jsx($r,{checked:r.restoreTabs,onChange:i=>n({restoreTabs:i})})}),o.jsx(Qt,{label:"Load example comparison on launch",hint:"Carbonic anhydrase II: crystal vs AlphaFold.",children:o.jsx($r,{checked:r.loadDemoOnStart,onChange:i=>n({loadDemoOnStart:i})})}),o.jsx(Qt,{label:"Save imports to library automatically",children:o.jsx($r,{checked:r.autoSaveImports,onChange:i=>n({autoSaveImports:i})})}),o.jsx(Qt,{label:"Confirm before deleting",children:o.jsx($r,{checked:r.confirmDeletes,onChange:i=>n({confirmDeletes:i})})}),o.jsx(Qt,{label:"Tab layout",children:o.jsx(Oe,{size:"sm",onClick:()=>{e(),s("Tab layout reset","success")},children:"Reset layout"})})]})}),o.jsx(yt,{title:"Keyboard shortcuts",actions:o.jsx(g6,{className:"h-4 w-4 text-slate-500"}),children:o.jsx("dl",{className:"grid grid-cols-[1fr_auto] gap-y-2.5 text-sm",children:[["Command palette",["⌘","K"]],["Open file",["⌘","O"]],["Search databases",["⌘","Shift","F"]],["Close tab",["Alt","W"]],["Toggle sidebar",["⌘","B"]],["Settings",["⌘",","]],["Interface size",["⌘","+ / −"]]].map(([i,c])=>o.jsxs("div",{className:"contents",children:[o.jsx("dt",{className:"text-slate-300",children:i}),o.jsx("dd",{className:"flex gap-1",children:c.map(d=>o.jsx(Rr,{children:d},d))})]},i))})})]})}function RL({onClearedHistory:e}){const{confirm:r,toast:n}=cl(),[s,i]=C.useState({count:0,bytes:0}),[c,d]=C.useState(null);return C.useEffect(()=>{const f=()=>nu().then(p=>i({count:p.length,bytes:p.reduce((b,x)=>b+x.sizeBytes,0)}));return f(),navigator.storage?.estimate?.().then(d).catch(()=>{}),r0(()=>void f())},[]),o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"Data & storage",description:"Everything here is stored on this device only."}),o.jsx(yt,{children:o.jsxs("div",{className:"divide-y divide-white/[0.05]",children:[o.jsx(Qt,{label:"Library",hint:`${s.count} items · ${Uc(s.bytes)}`,children:o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Oe,{size:"sm",disabled:!s.count,onClick:async()=>{const f=await lE(Cn),p=URL.createObjectURL(new Blob([JSON.stringify(f,null,2)],{type:"application/json"})),b=document.createElement("a");b.href=p,b.download=`synlexa-library-${new Date().toISOString().slice(0,10)}.json`,b.click(),setTimeout(()=>URL.revokeObjectURL(p),1e3)},children:"Export"}),o.jsx(Oe,{size:"sm",variant:"danger",disabled:!s.count,onClick:async()=>{await r({title:`Delete all ${s.count} library items?`,message:"This permanently removes every stored structure, compound, and sequence from this device. Export first if you want a backup.",confirmLabel:"Delete all",danger:!0})&&(await KD(),n("Library cleared","success"))},children:"Delete all"})]})}),o.jsx(Qt,{label:"Comparison run history",children:o.jsx(Oe,{size:"sm",variant:"danger",onClick:async()=>{await r({title:"Clear run history?",message:"Removes the list of past comparisons.",confirmLabel:"Clear",danger:!0})&&(await uE(),e(),n("Run history cleared","success"))},children:"Clear"})}),o.jsx(Qt,{label:"Settings",hint:"Restore every preference to its default.",children:o.jsx(Oe,{size:"sm",onClick:async()=>{await r({title:"Reset all settings?",message:"API keys and your library are not affected.",confirmLabel:"Reset"})&&(GD(),n("Settings reset","success"))},children:"Reset"})}),c?.usage!==void 0&&o.jsx(Qt,{label:"Browser storage used by Studio",children:o.jsxs("span",{className:"text-sm text-slate-300 tabular-nums",children:[Uc(c.usage??0),c.quota?` of ${Uc(c.quota)}`:""]})})]})})]})}const zL="0.4.5";function OL(){return o.jsxs(o.Fragment,{children:[o.jsx(ul,{title:"About Synlexa Studio"}),o.jsx(yt,{children:o.jsxs("dl",{className:"grid grid-cols-[10rem_1fr] gap-y-2.5 text-sm",children:[o.jsx("dt",{className:"text-slate-400",children:"Version"}),o.jsx("dd",{className:"text-slate-200",children:zL}),o.jsx("dt",{className:"text-slate-400",children:"Compute engine"}),o.jsx("dd",{className:"text-slate-200",children:"synlexa-bio-core (Rust → WebAssembly), runs locally"}),o.jsx("dt",{className:"text-slate-400",children:"Storage"}),o.jsx("dd",{className:"text-slate-200",children:"On this device (IndexedDB + localStorage)"})]})}),o.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.06] p-4 text-sm leading-relaxed text-amber-100/90",children:[Cn," Computational outputs are exploratory and have not been clinically validated."]})]})}const Cc=[{id:1,title:"Start Page & Multi-Project Workspaces",subtitle:"Create isolated projects from templates and keep structures, ligands, and edits organized",icon:Qc,targetTab:"home",actionLabel:"Open Start Page",tryActionKey:"home",summary:"Synlexa Studio starts on the Start Page so you can create a new research project, launch starter benchmarks, or resume saved workspaces before diving into 3D inspection.",bullets:['Click "+ New project" on the Start Page or Workspace Explorer to create a dedicated project (Structure Compare, Ligand Design & Binding, or Peptide & CRISPR Test).',"Switch between projects anytime — all imported structures, designed SMILES molecules, peptides, and CRISPR targets stay organized inside each project.","Alt-click any tool in the Tools sidebar to open tabs side-by-side."]},{id:2,title:"Import Multiple Structures & Split Chains / Ligands",subtitle:"Load PDB/mmCIF files or fetch RCSB, AlphaFold, UniProt, and PubChem records",icon:Px,targetTab:"viewer",actionLabel:"Open 3D Viewer",tryActionKey:"viewer",summary:"Import multiple local structures by drag-and-drop or fetch public IDs directly. Split multi-chain complexes or co-crystallized ligands into standalone project assets.",bullets:["Load structures into Reference and Comparison slots from your disk or Public Databases.",'Click "Split Ref" or "Split Comp" in the Workspace Explorer (or ask the AI Assistant) to split polymer chains and non-water HETATM ligands into independent assets.',"Inspect deterministic float64 Kabsch RMSD, TM-score, GDT-TS, and per-residue Cα distances in 3D."]},{id:3,title:"Design Molecules in the 2D Sketcher & RDKit Engine",subtitle:"Edit ligands visually or by SMILES, score drug-likeness & PAINS alerts, and save to project",icon:ia,targetTab:"chemistry",actionLabel:"Open Ligands & 2D Sketcher",tryActionKey:"chemistry",summary:"Draw ring systems and bonds on the interactive 2D SVG canvas or enter SMILES strings directly. Studio runs RDKit in WebAssembly to compute deterministic descriptors offline.",bullets:["Check exact molecular formula, MW, cLogP, TPSA, HBD/HBA, rotatable bonds, SA score, and Lipinski/Veber checks.","Flag PAINS structural alerts locally before saving promising analogs into your active project.",'Click "Bind" next to any saved project molecule to stage docking/binding tests.']},{id:4,title:"Peptide Engineering & CRISPR / Base-Editing Workbenches",subtitle:"Mutate residues, check 3D active-site contacts, and score SpCas9/SaCas9/Cas12a guides",icon:Fs,targetTab:"peptide",actionLabel:"Open Peptide Workbench",tryActionKey:"peptide",summary:"Test point mutations in loaded protein sequences and inspect base-editing CRISPR targets with automatic PAM matching and codon delta computation.",bullets:["In Peptide Engineering, apply mutations (e.g. H94A), track isoelectric point / charge shifts, and focus those positions in Mol* 3D.","In Gene & CRISPR, switch nucleases (SpCas9 NGG, SaCas9, Cas12a), inspect guide RNAs, and preview amino-acid consequences."]},{id:5,title:"External GPU Nodes (Colab / SSH) & Workflow Canvas",subtitle:"Connect AutoDock Vina, OpenMM MD, Boltz-2, RFdiffusion, and PySCF backends",icon:al,targetTab:"compute",actionLabel:"Open GPU & Compute Nodes",tryActionKey:"compute",summary:"Light visualization and cheminformatics run in-browser via Rust WASM & RDKit. Heavy GPU jobs dispatch cleanly to a local sidecar, Google Colab, or cluster worker.",bullets:["Connect your Google Colab / FastAPI compute worker URL & bearer token in GPU & Compute Nodes.","Design multi-step pipelines in Workflow Canvas and export reproducible Nextflow (`main.nf`) or Snakemake (`Snakefile`) definitions."]},{id:6,title:"Autonomous AI Agent: Live Thinking, Octopus Tools & Permissions",subtitle:"Full UI + project control with interactive permission prompts",icon:qr,targetTab:"assistant",actionLabel:"Open AI Assistant",tryActionKey:"assistant",summary:'The AI Assistant uses Studio’s in-app MCP server as "octopus arms" to create projects, design molecules, split structures, run workflows, and switch UI tabs.',bullets:["Watch the live Thinking & Tool Trace accordion while the agent plans rounds and runs tools.","Sensitive categories (external web/database fetches and remote GPU/workflow execution) pause for your interactive Allow Once / Session / Deny approval.","Adjust per-category policies anytime in Settings → Agent Tool Permissions."]},{id:7,title:"BYOK Key Vault (state.vscdb) vs Synlexa Cloud & Exports",subtitle:"Keep your own Anthropic/Gemini/OpenAI keys encrypted locally with full control",icon:Ki,actionLabel:"Open AI & Key Settings",tryActionKey:"settings",summary:"When you enter your own API key (Anthropic, Gemini, or OpenAI), Studio encrypts it in local state.vscdb and routes directly to your provider instead of Synlexa Cloud.",bullets:['Use "Prefer BYOK keys" (default) so personal API keys always take priority, or switch to manual mode to choose Synlexa Cloud anytime.',"Export RUO-labeled HTML reports, JSON manifests, and reproducible `.synlexa.bundle.json` project archives."]}];function PL({open:e,onClose:r,onExecuteStepAction:n}){const[s,i]=C.useState(0);if(C.useEffect(()=>{if(!e)return;const f=p=>{p.key==="Escape"&&r()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,r]),!e)return null;const c=Cc[s]??Cc[0],d=c.icon;return o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 backdrop-blur-xs",role:"dialog","aria-modal":"true","aria-label":"Synlexa Studio Interactive Tutorial",onClick:f=>{f.target===f.currentTarget&&r()},children:o.jsxs("div",{className:"flex max-h-[88vh] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-white/15 bg-[#0e131c] shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-white/[0.08] px-5 py-3.5",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-sky-500/15 text-sky-300",children:o.jsx(jy,{className:"h-4 w-4"})}),o.jsxs("div",{children:[o.jsx("h2",{className:"text-sm font-semibold text-slate-100",children:"Synlexa Studio Interactive Guide"}),o.jsxs("p",{className:"text-xs text-slate-400",children:["Step ",c.id," of ",Cc.length," · Research-Use-Only (RUO)"]})]})]}),o.jsx("button",{type:"button",onClick:r,"aria-label":"Close guide",className:"rounded-lg p-1.5 text-slate-400 hover:bg-white/[0.06] hover:text-white",children:o.jsx(Xi,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"flex flex-wrap gap-1.5 border-b border-white/[0.06] bg-white/[0.015] px-5 py-2.5",children:Cc.map((f,p)=>{const b=p===s;return o.jsxs("button",{type:"button",onClick:()=>i(p),className:Ie("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",b?"border-sky-400/50 bg-sky-500/15 text-sky-200":"border-white/10 bg-white/[0.02] text-slate-400 hover:text-slate-200"),children:[o.jsx("span",{className:"font-mono text-[0.6875rem]",children:f.id}),o.jsx("span",{className:"hidden sm:inline",children:f.title.split("&")[0]?.trim()})]},f.id)})}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-5",children:[o.jsxs("div",{className:"flex items-start gap-4",children:[o.jsx("span",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-sky-400/30 bg-sky-500/10 text-sky-300",children:o.jsx(d,{className:"h-5 w-5"})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("h3",{className:"text-lg font-semibold text-slate-100",children:c.title}),o.jsxs(It,{tone:"accent",children:["Step ",c.id]})]}),o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:c.subtitle})]})]}),o.jsx("p",{className:"mt-4 rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5 text-sm leading-relaxed text-slate-200",children:c.summary}),o.jsx("ul",{className:"mt-4 space-y-2.5",children:c.bullets.map((f,p)=>o.jsxs("li",{className:"flex items-start gap-2.5 text-sm text-slate-300",children:[o.jsx(Gs,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-400"}),o.jsx("span",{children:f})]},p))}),o.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-2 rounded-xl border border-sky-500/20 bg-sky-500/[0.06] px-4 py-3",children:[o.jsx("span",{className:"text-xs text-slate-300",children:"Try this feature directly inside the Studio workspace:"}),o.jsx(Oe,{size:"sm",variant:"primary",className:"ml-auto",onClick:()=>{n(c.tryActionKey),r()},children:c.actionLabel??"Try in Studio"})]})]}),o.jsxs("div",{className:"flex items-center justify-between border-t border-white/[0.08] px-5 py-3",children:[o.jsx(Oe,{size:"sm",variant:"ghost",disabled:s===0,icon:o.jsx(iR,{className:"h-3.5 w-3.5"}),onClick:()=>i(f=>Math.max(0,f-1)),children:"Previous"}),o.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500",children:[o.jsx(qi,{className:"h-3.5 w-3.5"}),o.jsx("span",{children:"Press Esc anytime · Reopen via Guide in the top bar"})]}),s<Cc.length-1?o.jsxs(Oe,{size:"sm",variant:"primary",onClick:()=>i(f=>Math.min(Cc.length-1,f+1)),children:["Next",o.jsx(DA,{className:"ml-1 h-3.5 w-3.5"})]}):o.jsx(Oe,{size:"sm",variant:"primary",onClick:r,children:"Done"})]})]})})}function $L({onExecuteNode:e,activeComputeLabel:r,onOpenComputeNodes:n,bridge:s}){const[i,c]=C.useState(()=>Zd[0]),[d,f]=C.useState(Zd[0].nodes[0]?.id??null),[p,b]=C.useState(null),[x,g]=C.useState({}),[_,y]=C.useState(!1),[S,k]=C.useState(null),[E,T]=C.useState(!1),j=C.useRef(null),q=C.useMemo(()=>new Map(i.nodes.map(W=>[W.id,W])),[i.nodes]),z=C.useMemo(()=>{let W=960,me=340;for(const I of i.nodes)I.x+230>W&&(W=I.x+230),I.y+130>me&&(me=I.y+130);return{width:W,height:me}},[i.nodes]),O=W=>{const me=Zn[W],I=`n${Date.now().toString(36).slice(-4)}`,J=i.nodes.length%4,ge=Math.floor(i.nodes.length/4);c(le=>({...le,nodes:[...le.nodes,{id:I,kind:W,x:40+J*235,y:45+ge*125,params:{...me.defaultParams}}]})),f(I)},V=W=>{c(me=>({...me,nodes:me.nodes.filter(I=>I.id!==W),edges:me.edges.filter(I=>I.from!==W&&I.to!==W)})),d===W&&f(null)},P=W=>{c(me=>({...me,edges:me.edges.filter(I=>I.id!==W)}))},$=W=>{if(!p||p===W){b(null);return}i.edges.some(I=>I.from===p&&I.to===W)||c(I=>({...I,edges:[...I.edges,{id:`e-${p}-${W}`,from:p,to:W}]})),b(null)},H=()=>{let W=i.nodes;try{W=fh(i)}catch{}const me=new Map;for(const J of W)me.set(J.id,0);for(const J of W){const ge=me.get(J.id)??0;for(const le of i.edges)le.from===J.id&&me.set(le.to,Math.max(me.get(le.to)??0,ge+1))}const I=new Map;for(const J of W){const ge=me.get(J.id)??0,le=I.get(ge)??[];le.push(J.id),I.set(ge,le)}c(J=>({...J,nodes:J.nodes.map(ge=>{const le=me.get(ge.id)??0,ae=(I.get(le)??[ge.id]).indexOf(ge.id);return{...ge,x:32+le*235,y:44+ae*124}})}))},Z=(W,me,I)=>{c(J=>({...J,nodes:J.nodes.map(ge=>ge.id===W?{...ge,params:{...ge.params,[me]:I}}:ge)}))},G=async()=>{k(null);let W;try{W=fh(i)}catch(I){k(I instanceof Error?I.message:String(I));return}y(!0);const me={};for(const I of W)me[I.id]={status:"idle"};g(me);try{for(const I of W){g(J=>({...J,[I.id]:{status:"running"}}));try{const J=await e(I.kind,I.params);g(ge=>({...ge,[I.id]:{status:"completed",summary:J.summary,metrics:J.metrics}}))}catch(J){const ge=J instanceof Error?J.message:String(J);g(le=>({...le,[I.id]:{status:"failed",error:ge}})),k(`Stopped at ${Zn[I.kind].label}: ${ge}`);break}}}finally{y(!1)}},K=(W,me)=>{const I=new Blob([me],{type:"text/plain;charset=utf-8"}),J=URL.createObjectURL(I),ge=document.createElement("a");ge.href=J,ge.download=W,ge.click(),setTimeout(()=>URL.revokeObjectURL(J),1e3)},we=(W,me,I,J)=>{W.target.closest("button")||(W.currentTarget.setPointerCapture(W.pointerId),j.current={id:me,startClientX:W.clientX,startClientY:W.clientY,origX:I,origY:J,moved:!1})},Se=W=>{const me=j.current;if(!me)return;const I=W.clientX-me.startClientX,J=W.clientY-me.startClientY;if((Math.abs(I)>4||Math.abs(J)>4)&&(me.moved=!0),!me.moved)return;const ge=Math.max(16,me.origX+I),le=Math.max(16,me.origY+J);c(D=>({...D,nodes:D.nodes.map(ae=>ae.id===me.id?{...ae,x:ge,y:le}:ae)}))},Q=W=>{const me=j.current;j.current=null,me&&!me.moved&&(p&&p!==W?$(W):f(W))},F=d?q.get(d)??null:null,he=F?i.edges.filter(W=>W.from===F.id||W.to===F.id):[];return o.jsxs("div",{className:"@container flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3 text-xs @xl:p-4",children:[o.jsx(ir,{bridge:s,title:"Visual Workflow Canvas (DAG)",subtitle:"Chain local Wasm/RDKit steps and external GPU jobs using your active 3D structure & ligand, or export Nextflow / Snakemake.",icon:o.jsx(Dp,{className:"h-4 w-4"}),guideOpen:E,onToggleGuide:()=>T(W=>!W),actions:o.jsxs("button",{type:"button",onClick:n,className:"rounded-lg border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-300 hover:border-sky-500/40",children:["GPU Node: ",o.jsx("strong",{className:r?"text-emerald-300":"text-amber-300",children:r??"Not paired"})]})}),o.jsx(Qi,{open:E,title:"How the Visual Workflow Canvas Works",summary:"Design reproducible Directed Acyclic Graph (DAG) pipelines combining Tier-0/Tier-1 browser Wasm steps (Kabsch, RDKit, Reports) and Tier-2 GPU Compute Node workloads (Vina, OpenMM, Boltz-2, RFdiffusion, PySCF).",steps:["Pick a starter template or click + buttons to add processing nodes onto the canvas.","Drag nodes to organize them, click Link → on one node then click a target node to connect edges, and edit node parameters in the Inspector below.","Click Run DAG to execute topologically using your active 3D structures & ligand SMILES, or export a reproducible Nextflow / Snakemake script."],connectionTip:"The Workspace Inputs node automatically pulls your currently loaded 3D Reference/Comparison structures, active SMILES ligand, and 3D Vina pocket box."}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx(Oe,{size:"sm",variant:"secondary",icon:o.jsx(VA,{className:"h-3.5 w-3.5"}),onClick:H,children:"Auto-Layout"}),o.jsx(Oe,{size:"sm",variant:"secondary",icon:o.jsx(sr,{className:"h-3.5 w-3.5"}),onClick:()=>K("main.nf",X3(i)),children:"Nextflow"}),o.jsx(Oe,{size:"sm",variant:"secondary",icon:o.jsx(sr,{className:"h-3.5 w-3.5"}),onClick:()=>K("Snakefile",Q3(i)),children:"Snakemake"}),o.jsx(Oe,{size:"sm",variant:"secondary",icon:o.jsx(sr,{className:"h-3.5 w-3.5"}),onClick:()=>K(`${i.id}.synlexa-flow.json`,JSON.stringify(i,null,2)),children:"JSON"})]}),o.jsx(Oe,{size:"sm",variant:"primary",disabled:_,icon:_?o.jsx(qs,{className:"h-3.5 w-3.5 animate-spin"}):o.jsx(qp,{className:"h-3.5 w-3.5"}),onClick:()=>void G(),children:_?"Running Pipeline…":"Run DAG"})]}),o.jsxs("div",{className:"space-y-2 rounded-xl border border-white/[0.08] bg-[#0b1018] p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsx("span",{className:"text-[0.6875rem] font-semibold text-slate-400 uppercase",children:"Templates:"}),Zd.map(W=>o.jsx("button",{type:"button",onClick:()=>{c(W),f(W.nodes[0]?.id??null),g({}),k(null)},className:Ie("rounded-lg border px-2.5 py-1 text-xs transition",i.id===W.id?"border-sky-400/50 bg-sky-500/20 text-sky-200":"border-white/10 bg-slate-900 text-slate-300 hover:border-white/25"),children:W.name},W.id))]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-t border-white/[0.06] pt-2",children:[o.jsx("span",{className:"text-[0.6875rem] text-slate-400",children:"Add Node:"}),Object.keys(Zn).map(W=>{const me=Zn[W];return o.jsxs("button",{type:"button",onClick:()=>O(W),title:`${me.toolName} (${me.tier})`,className:"flex items-center gap-1 rounded-md border border-white/10 bg-slate-950 px-2 py-1 text-[0.6875rem] text-slate-300 hover:border-sky-500/40",children:[o.jsx(gh,{className:"h-3 w-3 text-sky-300"}),me.label]},W)})]})]}),S&&o.jsx("div",{className:"rounded-xl border border-rose-500/40 bg-rose-500/10 px-3 py-2 text-rose-200",children:S}),o.jsx("div",{className:"relative min-h-[300px] flex-1 overflow-auto rounded-xl border border-white/[0.08] bg-[#070b12]",children:o.jsxs("div",{className:"relative",style:{width:z.width,height:z.height},children:[o.jsxs("svg",{className:"pointer-events-none absolute inset-0 h-full w-full",children:[o.jsx("defs",{children:o.jsx("pattern",{id:"synlexa-dag-grid",width:"28",height:"28",patternUnits:"userSpaceOnUse",children:o.jsx("path",{d:"M 28 0 L 0 0 0 28",fill:"none",stroke:"rgba(148,163,184,0.05)",strokeWidth:"1"})})}),o.jsx("rect",{width:"100%",height:"100%",fill:"url(#synlexa-dag-grid)"}),i.edges.map(W=>{const me=q.get(W.from),I=q.get(W.to);if(!me||!I)return null;const J=me.x+196,ge=me.y+46,le=I.x,D=I.y+46,ae=(J+le)/2,pe=d===W.from||d===W.to;return o.jsx("path",{d:`M ${J} ${ge} C ${ae} ${ge}, ${ae} ${D}, ${le} ${D}`,fill:"none",stroke:pe?"rgba(56,189,248,0.85)":"rgba(56,189,248,0.4)",strokeWidth:pe?2.5:2},W.id)})]}),i.nodes.map(W=>{const me=Zn[W.kind],I=x[W.id],J=d===W.id;return o.jsxs("div",{style:{left:W.x,top:W.y,width:196},onPointerDown:ge=>we(ge,W.id,W.x,W.y),onPointerMove:Se,onPointerUp:()=>Q(W.id),className:Ie("absolute cursor-grab rounded-xl border bg-[#0d121b]/95 p-2.5 shadow-lg transition select-none active:cursor-grabbing",J?"border-sky-400/80 ring-1 ring-sky-400/35":"border-white/10 hover:border-white/25"),children:[o.jsxs("div",{className:"flex items-start justify-between gap-1",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate font-semibold text-slate-100",children:me.label}),o.jsx("div",{className:"truncate font-mono text-[0.6875rem] text-slate-400",children:me.toolName})]}),I?.status==="running"&&o.jsx(qs,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-sky-400"}),I?.status==="completed"&&o.jsx(Gs,{className:"h-3.5 w-3.5 shrink-0 text-emerald-400"}),I?.status==="failed"&&o.jsx(Bc,{className:"h-3.5 w-3.5 shrink-0 text-rose-400"})]}),o.jsxs("div",{className:"mt-2 flex items-center justify-between gap-1",children:[o.jsx(It,{tone:me.tier==="tier2-gpu"?"warn":me.tier==="tier1-wasm"?"accent":"good",children:me.tier}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{type:"button",onClick:ge=>{ge.stopPropagation(),b(p===W.id?null:W.id)},className:Ie("rounded border px-1.5 py-0.5 text-[0.625rem]",p===W.id?"border-sky-400 bg-sky-500/20 text-sky-200":"border-white/10 text-slate-400 hover:text-slate-200"),children:p===W.id?"Click target…":"Link →"}),o.jsx("button",{type:"button",onClick:ge=>{ge.stopPropagation(),V(W.id)},className:"rounded p-0.5 text-slate-500 hover:text-rose-300",title:"Delete node",children:o.jsx(Wi,{className:"h-3 w-3"})})]})]}),I?.summary&&o.jsx("div",{className:"mt-1.5 truncate font-mono text-[0.6875rem] text-emerald-300",title:I.summary,children:I.summary}),I?.error&&o.jsx("div",{className:"mt-1.5 truncate font-mono text-[0.6875rem] text-rose-300",title:I.error,children:I.error})]},W.id)})]})}),F&&o.jsxs(yt,{className:"space-y-3 p-3.5",children:[o.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-semibold text-slate-100",children:Zn[F.kind].label}),o.jsxs("span",{className:"font-mono text-[0.6875rem] text-slate-500",children:["(",F.id,")"]}),o.jsx(It,{tone:Zn[F.kind].tier==="tier2-gpu"?"warn":"good",children:Zn[F.kind].tier})]}),o.jsxs("div",{className:"mt-0.5 text-[0.6875rem] text-slate-400",children:["Input: ",Zn[F.kind].inputPort," → Output: ",Zn[F.kind].outputPort]})]}),Zn[F.kind].tier==="tier2-gpu"&&!r&&o.jsx("button",{type:"button",onClick:n,className:"rounded-lg border border-amber-400/40 bg-amber-500/10 px-2.5 py-1 text-[0.6875rem] font-medium text-amber-200 hover:bg-amber-500/20",children:"Requires Online GPU Node — Pair Colab / Local →"})]}),Object.keys(F.params).length>0&&o.jsx("div",{className:"grid grid-cols-1 gap-2 @lg:grid-cols-2 @3xl:grid-cols-3",children:Object.entries(F.params).map(([W,me])=>o.jsxs("label",{className:"flex flex-col gap-1 rounded-lg border border-white/[0.07] bg-black/25 px-2.5 py-2",children:[o.jsx("span",{className:"font-mono text-[0.6875rem] text-slate-400",children:W}),typeof me=="boolean"?o.jsxs("span",{className:"flex items-center gap-2 text-xs text-slate-200",children:[o.jsx("input",{type:"checkbox",checked:me,onChange:I=>Z(F.id,W,I.target.checked),className:"accent-sky-400"}),me?"Enabled":"Disabled"]}):typeof me=="number"?o.jsx("input",{type:"number",value:me,onChange:I=>Z(F.id,W,Number(I.target.value)||0),className:"h-7 rounded border border-white/10 bg-slate-950 px-2 font-mono text-xs text-slate-100 outline-none focus:border-sky-400"}):o.jsx("input",{value:String(me),onChange:I=>Z(F.id,W,I.target.value),className:"h-7 rounded border border-white/10 bg-slate-950 px-2 font-mono text-xs text-slate-100 outline-none focus:border-sky-400"})]},W))}),he.length>0&&o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-t border-white/[0.06] pt-2",children:[o.jsx("span",{className:"text-[0.6875rem] text-slate-500",children:"Connections:"}),he.map(W=>{const me=Zn[q.get(W.from)?.kind??"load_structures"].label,I=Zn[q.get(W.to)?.kind??"load_structures"].label;return o.jsxs("button",{type:"button",onClick:()=>P(W.id),title:"Click to unlink edge",className:"inline-flex items-center gap-1 rounded-md border border-white/10 bg-black/30 px-2 py-0.5 text-[0.6875rem] text-slate-300 hover:border-rose-400/50 hover:text-rose-200",children:[o.jsxs("span",{children:[me," → ",I]}),o.jsx(sz,{className:"h-3 w-3"})]},W.id)})]})]})]})}const qd="application/x-synlexa-tab";function IL({layout:e,dispatch:r,meta:n,renderTab:s,keepAlive:i}){const c=C.useRef(null),[d,f]=C.useState(null),[p,b]=C.useState(null);C.useEffect(()=>{if(!p)return;const y=()=>b(null);return window.addEventListener("mousedown",y),window.addEventListener("blur",y),()=>{window.removeEventListener("mousedown",y),window.removeEventListener("blur",y)}},[p]);const x=y=>{y.preventDefault();const S=c.current;if(!S)return;const k=S.getBoundingClientRect(),E=j=>{r({type:"set_split",split:(j.clientX-k.left)/k.width})},T=()=>{window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",T),document.body.style.cursor=""};document.body.style.cursor="col-resize",window.addEventListener("pointermove",E),window.addEventListener("pointerup",T)},g=(y,S,k)=>{const E=y.dataTransfer.getData(qd);f(null),E&&(y.preventDefault(),r({type:"move",tab:E,toGroup:S,index:k}))},_=e.groups.length===2;return o.jsxs("div",{ref:c,className:"relative flex min-h-0 min-w-0 flex-1",children:[e.groups.map((y,S)=>o.jsxs("div",{style:_?{width:`${(S===0?e.split:1-e.split)*100}%`}:void 0,className:Ie("relative flex min-h-0 min-w-0 flex-col",!_&&"flex-1"),onMouseDownCapture:()=>e.focused!==S&&r({type:"focus_group",group:S}),children:[o.jsxs("div",{role:"tablist",className:Ie("flex h-10 shrink-0 items-stretch border-b border-white/[0.06] bg-[#0d1119]",e.focused===S&&_&&"shadow-[inset_0_-1px_0_0_rgba(56,189,248,0.25)]"),onDragOver:k=>{k.dataTransfer.types.includes(qd)&&k.preventDefault()},onDrop:k=>g(k,S),children:[o.jsx("div",{className:"flex min-w-0 flex-1 items-stretch overflow-x-auto [scrollbar-width:none]",children:y.tabs.map((k,E)=>{const T=n[k],j=y.active===k,q=!Op.has(k);return o.jsxs("div",{role:"tab","aria-selected":j,tabIndex:0,draggable:!0,onDragStart:z=>{z.dataTransfer.setData(qd,k),z.dataTransfer.effectAllowed="move",f(k)},onDragEnd:()=>f(null),onDragOver:z=>{z.dataTransfer.types.includes(qd)&&z.preventDefault()},onDrop:z=>{z.stopPropagation(),g(z,S,E)},onClick:()=>r({type:"activate",tab:k}),onAuxClick:z=>{z.button===1&&q&&r({type:"close",tab:k})},onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&r({type:"activate",tab:k})},onContextMenu:z=>{z.preventDefault(),b({tab:k,x:z.clientX,y:z.clientY})},className:Ie("group relative flex max-w-56 min-w-0 shrink-0 cursor-pointer items-center gap-2 border-r border-white/[0.05] pr-1.5 pl-3 text-[0.8125rem] transition-colors select-none",j?"bg-[#121722] text-slate-100":"text-slate-400 hover:bg-white/[0.03] hover:text-slate-200",d===k&&"opacity-40"),children:[j&&o.jsx("span",{className:Ie("absolute inset-x-0 top-0 h-0.5",e.focused===S?"bg-sky-400":"bg-slate-600")}),o.jsx("span",{className:Ie("shrink-0",j?"text-sky-300":"text-slate-500"),children:T.icon}),o.jsx("span",{className:"truncate",children:T.title}),T.badge,q?o.jsx("button",{type:"button","aria-label":`Close ${T.title}`,title:"Close (middle-click)",onClick:z=>{z.stopPropagation(),r({type:"close",tab:k})},className:Ie("flex h-5 w-5 items-center justify-center rounded text-slate-500 hover:bg-white/10 hover:text-slate-100",j?"opacity-100":"opacity-0 group-hover:opacity-100"),children:o.jsx(Xi,{className:"h-3.5 w-3.5"})}):o.jsx("span",{className:"w-1"})]},k)})}),o.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 px-1.5",children:[y.active&&o.jsx("button",{type:"button",title:_?"Move tab to the other side":"Split editor right","aria-label":"Split editor",onClick:()=>y.active&&r({type:"open",tab:y.active,toSide:!0}),disabled:!_&&y.tabs.length<2,className:"flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-white/[0.07] hover:text-slate-200 disabled:opacity-30",children:o.jsx(Ey,{className:"h-4 w-4"})}),_&&o.jsx("button",{type:"button",title:"Merge split panes into single full-width view","aria-label":"Merge split panes",onClick:()=>r({type:"merge_split"}),className:"flex h-7 w-7 items-center justify-center rounded-md text-slate-500 hover:bg-white/[0.07] hover:text-sky-300",children:o.jsx(Oy,{className:"h-3.5 w-3.5"})})]})]}),o.jsxs("div",{className:"relative min-h-0 flex-1 bg-[#0f131b]",onDragOver:k=>{k.dataTransfer.types.includes(qd)&&k.preventDefault()},onDrop:k=>g(k,S),children:[y.tabs.map(k=>{const E=y.active===k;return!E&&!i?.has(k)?null:o.jsx("div",{role:"tabpanel",className:Ie("absolute inset-0 overflow-hidden",!E&&"invisible"),"aria-hidden":!E,children:s(k)},k)}),d&&o.jsx("div",{className:"pointer-events-none absolute inset-2 rounded-xl border-2 border-dashed border-sky-400/30 bg-sky-400/[0.03]"})]})]},S)),_&&o.jsx("div",{onPointerDown:x,onDoubleClick:()=>r({type:"set_split",split:.6}),style:{left:`calc(${e.split*100}% - 3px)`},className:"absolute top-0 bottom-0 z-20 w-1.5 cursor-col-resize bg-transparent transition-colors hover:bg-sky-400/40",title:"Drag to resize · double-click to reset"}),_&&o.jsx("div",{style:{left:`${e.split*100}%`},className:"pointer-events-none absolute top-0 bottom-0 z-10 w-px bg-white/[0.08]"}),!_&&d&&o.jsx("div",{onDragOver:y=>y.preventDefault(),onDrop:y=>g(y,1),className:"absolute top-10 right-0 bottom-0 z-30 flex w-1/3 items-center justify-center rounded-l-xl border-2 border-dashed border-sky-400/50 bg-sky-400/10 text-sm font-medium text-sky-200",children:"Drop to open on the side"}),p&&o.jsx("div",{onMouseDown:y=>y.stopPropagation(),style:{left:p.x,top:p.y},className:"fixed z-[75] min-w-52 overflow-hidden rounded-xl border border-white/10 bg-[#161c28] py-1 text-sm shadow-2xl",children:[{label:_?"Move to other side":"Open to the side",run:()=>r({type:"open",tab:p.tab,toSide:!0}),disabled:!_&&e.groups[0].tabs.length<2},..._?[{label:"Merge split panes",run:()=>r({type:"merge_split"}),disabled:!1}]:[],{label:"Close",run:()=>r({type:"close",tab:p.tab}),disabled:Op.has(p.tab)},{label:"Close others",run:()=>r({type:"close_others",tab:p.tab})}].map(y=>o.jsx("button",{type:"button",disabled:y.disabled,onClick:()=>{y.run(),b(null)},className:"flex w-full px-3 py-2 text-left text-slate-200 hover:bg-white/[0.06] disabled:opacity-40",children:y.label},y.label))})]})}function DL({projectTitle:e,session:r,onOpenPalette:n,onOpenFile:s,onSearchDatabases:i,onOpenMcp:c,onOpenTutorial:d,onExportHtml:f,onExportJson:p,onExportBundle:b,canExport:x,onOpenAccount:g}){const _=(r?.displayName??r?.email??"").split(/[\s@.]+/).filter(Boolean).slice(0,2).map(y=>y[0]?.toUpperCase()).join("");return o.jsxs("header",{className:"relative flex h-12 shrink-0 items-center gap-3 border-b border-white/[0.06] bg-[#0a0d13] px-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[o.jsx("span",{className:"text-sm font-semibold tracking-tight text-slate-100",children:"Synlexa Studio"}),o.jsx("span",{className:"hidden text-slate-700 md:inline",children:"/"}),o.jsx("span",{className:"hidden max-w-[18rem] truncate text-sm text-slate-400 md:inline",title:e,children:e})]}),o.jsxs("button",{type:"button",onClick:n,className:"absolute left-1/2 hidden h-8 w-[min(25rem,30vw)] -translate-x-1/2 items-center gap-2 rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 text-sm text-slate-500 transition-colors hover:border-white/15 hover:text-slate-300 xl:flex",children:[o.jsx(Gr,{className:"h-4 w-4"}),o.jsx("span",{className:"flex-1 text-left",children:"Search commands, tools, MCP, settings…"}),o.jsx(Rr,{children:"⌘K"})]}),o.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[o.jsx(Oe,{size:"sm",variant:"ghost",icon:o.jsx(My,{className:"h-4 w-4"}),onClick:s,children:o.jsx("span",{className:"hidden sm:inline",children:"Open"})}),o.jsx(Oe,{size:"sm",variant:"ghost",icon:o.jsx(Vi,{className:"h-4 w-4"}),onClick:i,children:o.jsx("span",{className:"hidden sm:inline",children:"Databases"})}),d&&o.jsx(Oe,{size:"sm",variant:"ghost",icon:o.jsx(jy,{className:"h-4 w-4 text-emerald-400"}),onClick:d,children:o.jsx("span",{className:"hidden sm:inline",children:"Guide"})}),c&&o.jsx(Oe,{size:"sm",variant:"ghost",icon:o.jsx(rl,{className:"h-4 w-4 text-sky-400"}),onClick:c,children:o.jsx("span",{className:"hidden sm:inline",children:"MCP"})}),o.jsx(i1,{trigger:(y,S)=>o.jsxs(Oe,{size:"sm",variant:"secondary",onClick:S,icon:o.jsx(sr,{className:"h-4 w-4"}),children:[o.jsx("span",{className:"hidden sm:inline",children:"Export"}),o.jsx(ph,{className:Ie("h-3.5 w-3.5 transition-transform",y&&"rotate-180")})]}),items:[{label:"HTML report",icon:o.jsx(sr,{className:"h-4 w-4"}),onSelect:f,disabled:!x},{label:"JSON manifest",icon:o.jsx(BA,{className:"h-4 w-4"}),onSelect:p,disabled:!x},{label:"Project bundle",icon:o.jsx(UA,{className:"h-4 w-4"}),onSelect:b}]}),o.jsx("button",{type:"button",onClick:g,title:r?`Signed in as ${r.email??r.displayName??"user"}`:"Account & Settings",className:Ie("ml-1 flex h-8 w-8 items-center justify-center rounded-full text-xs font-semibold transition",r?"bg-gradient-to-br from-blue-500 to-blue-700 text-white":"border border-white/10 bg-white/[0.04] text-slate-400 hover:text-slate-200"),children:r?_||o.jsx(ah,{className:"h-4 w-4"}):o.jsx(ah,{className:"h-4 w-4"})})]})]})}function qL({view:e,sidebarOpen:r,onSelect:n,onOpenSettings:s,onOpenAssistant:i,onOpenMcp:c,libraryCount:d}){const f=[{id:"explorer",label:"Workspace",icon:o.jsx(qi,{className:"h-5 w-5"})},{id:"library",label:"Library",icon:o.jsx(sh,{className:"h-5 w-5"})},{id:"tools",label:"Tools",icon:o.jsx(Py,{className:"h-5 w-5"})},{id:"history",label:"History",icon:o.jsx(HA,{className:"h-5 w-5"})}];return o.jsxs("nav",{className:"flex w-14 shrink-0 flex-col items-center gap-1 border-r border-white/[0.06] bg-[#0a0d13] py-2",children:[f.map(p=>{const b=r&&e===p.id;return o.jsxs("button",{type:"button",title:p.label,"aria-label":p.label,onClick:()=>n(p.id),className:Ie("relative flex h-11 w-11 flex-col items-center justify-center rounded-xl transition-colors",b?"bg-white/[0.08] text-slate-100":"text-slate-500 hover:bg-white/[0.04] hover:text-slate-200"),children:[b&&o.jsx("span",{className:"absolute top-2 bottom-2 -left-1.5 w-0.5 rounded-full bg-sky-400"}),p.icon,p.id==="library"&&d>0&&o.jsx("span",{className:"absolute top-1 right-1 min-w-4 rounded-full bg-sky-500 px-1 text-[0.625rem] leading-4 font-semibold text-slate-950",children:d>99?"99+":d})]},p.id)}),o.jsx("div",{className:"flex-1"}),c&&o.jsx("button",{type:"button",title:"In-App MCP Server","aria-label":"In-App MCP Server",onClick:c,className:"flex h-11 w-11 items-center justify-center rounded-xl text-slate-500 hover:bg-white/[0.04] hover:text-sky-300",children:o.jsx(rl,{className:"h-5 w-5"})}),o.jsx("button",{type:"button",title:"AI Assistant","aria-label":"AI Assistant",onClick:i,className:"flex h-11 w-11 items-center justify-center rounded-xl text-slate-500 hover:bg-white/[0.04] hover:text-sky-300",children:o.jsx(qr,{className:"h-5 w-5"})}),o.jsx("button",{type:"button",title:"Settings (⌘,)","aria-label":"Settings",onClick:s,className:"flex h-11 w-11 items-center justify-center rounded-xl text-slate-500 hover:bg-white/[0.04] hover:text-slate-200",children:o.jsx(H6,{className:"h-5 w-5"})})]})}function LL({title:e,actions:r,children:n,width:s}){return o.jsxs("aside",{style:{width:s},className:"flex shrink-0 flex-col border-r border-white/[0.06] bg-[#0c1017]",children:[o.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between px-3",children:[o.jsx("span",{className:"text-xs font-semibold tracking-wide text-slate-400 uppercase",children:e}),o.jsx("div",{className:"flex items-center gap-0.5",children:r})]}),o.jsx("div",{className:"min-h-0 flex-1",children:n})]})}function RA({role:e,label:r,inspect:n,chain:s,onChangeChain:i,onReplace:c,onSaveToLibrary:d,hasContent:f}){const p=e==="reference",b=n&&n.chains.length>1&&!s;return o.jsxs("div",{className:Ie("rounded-xl border p-3",b?"border-amber-500/40 bg-amber-500/[0.04]":"border-white/[0.07] bg-white/[0.02]"),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:Ie("text-[0.6875rem] font-semibold tracking-wide uppercase",p?"text-sky-300":"text-emerald-300"),children:p?"Reference":"Comparison"}),o.jsxs("div",{className:"flex items-center",children:[f&&o.jsx(sl,{label:"Save to library",onClick:d,children:o.jsx(qA,{className:"h-4 w-4"})}),o.jsx(sl,{label:`Replace ${p?"reference":"comparison"} file`,onClick:c,children:o.jsx(Oc,{className:"h-4 w-4"})})]})]}),f?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mt-1 truncate text-sm font-medium text-slate-100",title:r,children:r}),o.jsx("div",{className:"mt-0.5 text-xs text-slate-500",children:n?`${n.format.toUpperCase()} · ${n.chains.length} chain${n.chains.length===1?"":"s"} · ${n.confidenceKind==="prediction_plddt"?"predicted":n.confidenceKind==="experimental_b_factor"?"experimental":"unknown confidence"}`:"Reading…"}),n&&n.chains.length>0&&o.jsx("div",{className:"mt-2.5 flex flex-wrap gap-1",children:n.chains.map(x=>o.jsx("button",{type:"button",onClick:()=>i(x.chainId),title:`${x.observedCaCount} observed Cα`,className:Ie("rounded-md border px-2 py-1 font-mono text-xs transition-colors",s===x.chainId?p?"border-sky-400/50 bg-sky-400/15 text-sky-200":"border-emerald-400/50 bg-emerald-400/15 text-emerald-200":"border-white/10 text-slate-400 hover:border-white/25 hover:text-slate-200"),children:x.chainId},x.chainId))}),b&&o.jsx("div",{className:"mt-2 text-xs text-amber-300",children:"Pick a chain to run the comparison."})]}):o.jsx("button",{type:"button",onClick:c,className:"mt-1.5 text-sm text-slate-400 hover:text-sky-300",children:"Load a structure…"})]})}function UL(e){const r=C.useRef(null),n=C.useRef("auto"),[s,i]=C.useState(!1),[c,d]=C.useState(!1),[f,p]=C.useState(""),[b,x]=C.useState("ligand-docking"),g=y=>{n.current=y,r.current?.click()},_=()=>{e.onCreateProject&&(e.onCreateProject({name:f.trim()||"Untitled Research Project",template:b}),p(""),d(!1))};return o.jsxs("div",{className:"relative flex h-full flex-col overflow-y-auto px-3 pb-4",onDragOver:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),i(!0))},onDragLeave:y=>y.currentTarget===y.target&&i(!1),onDrop:y=>{y.dataTransfer.files.length&&(y.preventDefault(),i(!1),e.onUploadFiles(y.dataTransfer.files,"auto"))},children:[o.jsx("input",{ref:r,type:"file",multiple:!0,accept:".cif,.mmcif,.pdb,.ent,.json,.fasta,.fa,.smi",className:"hidden",onChange:y=>{y.target.files?.length&&e.onUploadFiles(y.target.files,n.current),y.target.value=""}}),e.projects&&e.activeProject&&e.onSwitchProject&&o.jsxs("div",{className:"mb-3 rounded-xl border border-white/[0.08] bg-white/[0.02] p-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between gap-1.5",children:[o.jsx("span",{className:"text-[0.6875rem] font-semibold tracking-wide text-slate-400 uppercase",children:"Project"}),e.onCreateProject&&o.jsxs("button",{type:"button",onClick:()=>d(y=>!y),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[0.6875rem] text-sky-300 hover:bg-sky-500/10",children:[o.jsx(Qc,{className:"h-3 w-3"}),"New"]})]}),o.jsx(Na,{value:e.activeProject.id,onChange:y=>e.onSwitchProject?.(y.target.value),className:"mt-1.5 h-8 text-xs",children:e.projects.map(y=>o.jsx("option",{value:y.id,children:y.name},y.id))}),c&&o.jsxs("div",{className:"mt-2 space-y-1.5 border-t border-white/[0.06] pt-2",children:[o.jsx(Dn,{value:f,onChange:y=>p(y.target.value),placeholder:"Project name…",className:"h-7 text-xs"}),o.jsxs(Na,{value:b,onChange:y=>x(y.target.value),className:"h-7 text-xs",children:[o.jsx("option",{value:"structure-compare",children:"Structure Compare"}),o.jsx("option",{value:"ligand-docking",children:"Ligand Design & Binding"}),o.jsx("option",{value:"peptide-crispr",children:"Peptide & CRISPR Test"}),o.jsx("option",{value:"blank",children:"Blank Workspace"})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx(Oe,{size:"sm",variant:"primary",className:"flex-1",onClick:_,children:"Create"}),o.jsx(Oe,{size:"sm",variant:"ghost",onClick:()=>d(!1),children:"Cancel"})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(RA,{role:"reference",label:e.refLabel,inspect:e.refInspect,chain:e.refChain,onChangeChain:e.onChangeRefChain,onReplace:()=>g("reference"),onSaveToLibrary:()=>e.onSaveToLibrary("reference"),hasContent:e.hasRef}),o.jsx(RA,{role:"mobile",label:e.mobLabel,inspect:e.mobInspect,chain:e.mobChain,onChangeChain:e.onChangeMobChain,onReplace:()=>g("mobile"),onSaveToLibrary:()=>e.onSaveToLibrary("mobile"),hasContent:e.hasMob}),(e.hasRef||e.hasMob)&&e.onSplitStructure&&o.jsxs("div",{className:"flex gap-1.5",children:[e.hasRef&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"flex-1 text-[0.6875rem]",icon:o.jsx(Px,{className:"h-3 w-3"}),onClick:()=>e.onSplitStructure?.("reference"),title:"Split Reference chains & non-water HETATM ligands into project assets",children:"Split Ref"}),e.hasMob&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"flex-1 text-[0.6875rem]",icon:o.jsx(Px,{className:"h-3 w-3"}),onClick:()=>e.onSplitStructure?.("mobile"),title:"Split Comparison chains & non-water HETATM ligands into project assets",children:"Split Comp"})]}),o.jsxs("div",{className:"flex items-center gap-2 px-1 pt-1 text-xs text-slate-500",children:[o.jsx("span",{className:Ie("h-1.5 w-1.5 rounded-full",e.paePresent?"bg-emerald-400":"bg-slate-600")}),e.paePresent?"PAE matrix loaded":"No PAE matrix"]}),e.chainError&&o.jsxs("div",{className:"flex gap-2 rounded-lg border border-amber-500/30 bg-amber-500/[0.06] p-2.5 text-xs leading-relaxed text-amber-200",children:[o.jsx(Gc,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.chainError]})]}),o.jsxs("div",{className:"mt-3 space-y-1.5",children:[o.jsx(Oe,{className:"w-full",variant:"primary",size:"sm",icon:o.jsx(Oc,{className:"h-3.5 w-3.5"}),onClick:()=>g("auto"),children:"Import structures / files"}),o.jsx(Oe,{className:"w-full",size:"sm",icon:o.jsx(Vi,{className:"h-3.5 w-3.5"}),onClick:e.onSearchDatabases,children:"Search public databases"}),o.jsxs("div",{className:"grid grid-cols-3 gap-1 pt-0.5",children:[e.onOpenChemistry&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"text-[0.6875rem]",icon:o.jsx(gh,{className:"h-3 w-3"}),onClick:e.onOpenChemistry,children:"Mol"}),e.onOpenPeptide&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"text-[0.6875rem]",icon:o.jsx(ar,{className:"h-3 w-3"}),onClick:e.onOpenPeptide,children:"Pep"}),e.onOpenCrispr&&o.jsx(Oe,{size:"sm",variant:"secondary",className:"text-[0.6875rem]",icon:o.jsx(Fs,{className:"h-3 w-3"}),onClick:e.onOpenCrispr,children:"CRISPR"})]})]}),e.activeProject&&(e.activeProject.structures.length>0||e.activeProject.molecules.length>0||e.activeProject.peptides.length>0||e.activeProject.crisprs.length>0)&&o.jsxs("div",{className:"mt-4 space-y-2 border-t border-white/[0.06] pt-3",children:[o.jsxs("div",{className:"text-[0.6875rem] font-semibold tracking-wide text-slate-400 uppercase",children:["Project Assets (",e.activeProject.structures.length+e.activeProject.molecules.length+e.activeProject.peptides.length+e.activeProject.crisprs.length,")"]}),e.activeProject.structures.map(y=>o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-2 py-1.5 text-xs",children:[o.jsx(_s,{className:"h-3.5 w-3.5 shrink-0 text-sky-300"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-slate-200",title:y.label,children:y.label}),e.onLoadProjectStructure&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>e.onLoadProjectStructure?.(y,"reference"),className:"rounded px-1 py-0.5 text-[0.625rem] text-sky-300 hover:bg-sky-500/15",title:"Load as Reference",children:"Ref"}),o.jsx("button",{type:"button",onClick:()=>e.onLoadProjectStructure?.(y,"mobile"),className:"rounded px-1 py-0.5 text-[0.625rem] text-emerald-300 hover:bg-emerald-500/15",title:"Load as Comparison",children:"Comp"})]})]},y.id)),e.activeProject.molecules.map(y=>o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-2 py-1.5 text-xs",children:[o.jsx(ia,{className:"h-3.5 w-3.5 shrink-0 text-violet-300"}),o.jsx("button",{type:"button",onClick:()=>e.onOpenProjectMolecule?.(y),className:"min-w-0 flex-1 truncate text-left text-slate-200 hover:text-sky-300",title:y.smiles,children:y.name}),e.onDockMolecule&&o.jsxs("button",{type:"button",onClick:()=>e.onDockMolecule?.(y),className:"inline-flex items-center gap-0.5 rounded bg-emerald-500/10 px-1.5 py-0.5 text-[0.625rem] text-emerald-300 hover:bg-emerald-500/20",title:"Test binding / AutoDock Vina against active protein",children:[o.jsx(Br,{className:"h-2.5 w-2.5"}),"Bind"]}),e.onRemoveProjectAsset&&o.jsx("button",{type:"button",onClick:()=>e.onRemoveProjectAsset?.("molecule",y.id),className:"text-slate-500 hover:text-rose-400","aria-label":`Remove ${y.name}`,children:"×"})]},y.id)),e.activeProject.peptides.map(y=>o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-2 py-1.5 text-xs",children:[o.jsx(ar,{className:"h-3.5 w-3.5 shrink-0 text-amber-300"}),o.jsx("button",{type:"button",onClick:()=>e.onOpenPeptide?.(),className:"min-w-0 flex-1 truncate text-left text-slate-200 hover:text-sky-300",children:y.name})]},y.id)),e.activeProject.crisprs.map(y=>o.jsxs("div",{className:"flex items-center gap-1.5 rounded-lg border border-white/[0.06] bg-white/[0.02] px-2 py-1.5 text-xs",children:[o.jsx(Fs,{className:"h-3.5 w-3.5 shrink-0 text-emerald-300"}),o.jsx("button",{type:"button",onClick:()=>e.onOpenCrispr?.(),className:"min-w-0 flex-1 truncate text-left text-slate-200 hover:text-sky-300",children:y.name})]},y.id))]}),o.jsx("div",{className:Ie("mt-4 rounded-xl border border-dashed px-3 py-4 text-center text-xs leading-relaxed transition-colors",s?"border-sky-400/70 bg-sky-400/10 text-sky-200":"border-white/10 text-slate-500"),children:"Drop .cif / .pdb / PAE .json / .fasta / .smi / .synlexa.bundle.json here"}),o.jsx("button",{type:"button",onClick:e.onLoadExample,className:"mt-3 text-xs text-slate-500 hover:text-sky-300",children:"Load example comparison (CA II)"})]})}const BL=[{id:"viewer",group:"Structures & 3D",label:"3D Viewer",desc:"Superposed structures, residue picking, distances",icon:o.jsx(_s,{className:"h-4 w-4"})},{id:"results",group:"Structures & 3D",label:"Results",desc:"RMSD, coverage, confidence, PAE, exports",icon:o.jsx(qi,{className:"h-4 w-4"})},{id:"sequence",group:"Structures & 3D",label:"Sequence deviation",desc:"Per-residue Δd along the alignment",icon:o.jsx(Vo,{className:"h-4 w-4"})},{id:"ramachandran",group:"Structures & 3D",label:"Ramachandran",desc:"Backbone φ/ψ and Cα contacts",icon:o.jsx(Qo,{className:"h-4 w-4"})},{id:"chemistry",group:"Design & Editing",label:"Ligands & 2D Sketcher",desc:"RDKit WASM, PAINS alerts, 2D editor",icon:o.jsx(ia,{className:"h-4 w-4"})},{id:"peptide",group:"Design & Editing",label:"Peptide engineering",desc:"Point mutations, pI, charge, 3D contacts",icon:o.jsx(ar,{className:"h-4 w-4"})},{id:"crispr",group:"Design & Editing",label:"Gene & CRISPR",desc:"Codon edits and PAM sites",icon:o.jsx(Fs,{className:"h-4 w-4"})},{id:"workflow",group:"Pipelines & GPU",label:"Workflow Canvas",desc:"DAG pipelines + Nextflow/Snakemake",icon:o.jsx(Dp,{className:"h-4 w-4"})},{id:"compute",group:"Pipelines & GPU",label:"GPU & Compute Nodes",desc:"Colab, Vina, OpenMM, Boltz-2, PySCF",icon:o.jsx(al,{className:"h-4 w-4"})},{id:"plugins",group:"Pipelines & GPU",label:"Plugins & Add-ons",desc:"Open-source tools & license ledger",icon:o.jsx(Lp,{className:"h-4 w-4"})},{id:"assistant",group:"Agent & Workspace",label:"AI Assistant",desc:"Reasoning trace, octopus tools, search",icon:o.jsx(qr,{className:"h-4 w-4"})},{id:"mcp",group:"Agent & Workspace",label:"MCP Server",desc:"In-app MCP & Claude/Codex bridge",icon:o.jsx(rl,{className:"h-4 w-4"})},{id:"library",group:"Agent & Workspace",label:"Library manager",desc:"Organize saved molecules",icon:o.jsx(sh,{className:"h-4 w-4"})},{id:"home",group:"Agent & Workspace",label:"Start page",desc:"Projects, tutorial, quick actions",icon:o.jsx(FA,{className:"h-4 w-4"})}],GL=["Structures & 3D","Design & Editing","Pipelines & GPU","Agent & Workspace"];function HL({openTabs:e,onOpen:r}){return o.jsxs("div",{className:"h-full overflow-y-auto px-2 pb-4",children:[o.jsx("p",{className:"px-2 pb-2 text-xs text-slate-500",children:"Click to open a tab, or use the split icon to open beside 3D."}),o.jsx("div",{className:"space-y-3",children:GL.map(n=>o.jsxs("div",{children:[o.jsx("div",{className:"px-2.5 pb-1 text-[0.6875rem] font-semibold tracking-wider text-slate-500 uppercase",children:n}),o.jsx("ul",{className:"space-y-0.5",children:BL.filter(s=>s.group===n).map(s=>o.jsxs("li",{className:"group flex items-center gap-1 rounded-lg pr-1 hover:bg-white/[0.04]",children:[o.jsxs("button",{type:"button",onClick:i=>r(s.id,i.altKey),className:"flex min-w-0 flex-1 items-start gap-3 px-2.5 py-2 text-left",children:[o.jsx("span",{className:"mt-0.5 text-slate-500 group-hover:text-sky-300",children:s.icon}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsxs("span",{className:"flex items-center gap-2 text-[0.8125rem] text-slate-200",children:[s.label,e.has(s.id)&&o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-sky-400",title:"Open"})]}),o.jsx("span",{className:"block truncate text-xs text-slate-500",children:s.desc})]})]}),o.jsx("button",{type:"button",title:`Open ${s.label} side-by-side`,"aria-label":`Open ${s.label} side-by-side`,onClick:()=>r(s.id,!0),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-slate-500 opacity-0 transition group-hover:opacity-100 hover:bg-white/[0.08] hover:text-sky-300",children:o.jsx(Ey,{className:"h-3.5 w-3.5"})})]},s.id))})]},n))})]})}function FL({runs:e,onClear:r}){return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:e.length===0?o.jsx("p",{className:"px-2 py-6 text-center text-xs text-slate-500",children:"Comparisons you run appear here."}):o.jsx("ul",{className:"space-y-1",children:e.map(n=>o.jsxs("li",{className:"rounded-lg px-2.5 py-2 hover:bg-white/[0.03]",children:[o.jsxs("div",{className:"truncate text-[0.8125rem] text-slate-200",children:[n.refLabel," ",o.jsx("span",{className:"text-slate-600",children:"vs"})," ",n.mobLabel]}),o.jsxs("div",{className:"mt-0.5 flex justify-between text-xs text-slate-500 tabular-nums",children:[o.jsxs("span",{children:[n.rmsdAngstrom.toFixed(3)," Å · ",n.matchedCaCount," Cα · ",n.refChain,"/",n.mobChain]}),o.jsx("span",{children:new Date(n.createdAtUtc).toLocaleDateString()})]})]},n.id))})}),e.length>0&&o.jsx("div",{className:"border-t border-white/[0.06] p-2",children:o.jsx(Oe,{size:"sm",variant:"ghost",className:"w-full",icon:o.jsx(Wi,{className:"h-3.5 w-3.5"}),onClick:r,children:"Clear history"})})]})}function VL({busyLabel:e,wasmReady:r,rendererMode:n,rmsd:s,focusedSeqId:i,computeNodeLabel:c,computeOnline:d,onOpenComputeNodes:f,aiLabel:p,aiReady:b,onOpenAiSettings:x}){return o.jsxs("footer",{className:"flex h-7 shrink-0 items-center gap-4 border-t border-white/[0.06] bg-[#0a0d13] px-3 text-[0.6875rem] text-slate-500",children:[o.jsx("span",{className:"flex items-center gap-1.5",children:e?o.jsxs(o.Fragment,{children:[o.jsx(qs,{className:"h-3 w-3 animate-spin text-sky-400"}),o.jsx("span",{className:"text-slate-300",children:e})]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:Ie("h-1.5 w-1.5 rounded-full",r?"bg-emerald-400":"bg-amber-400")}),r?"Engine ready":"Starting engine…"]})}),o.jsxs("span",{className:"hidden items-center gap-1 sm:flex",children:[o.jsx(al,{className:"h-3 w-3"})," ",n==="webgl2"?"WebGL2":"Canvas fallback"]}),f&&o.jsxs("button",{type:"button",onClick:f,className:"hidden items-center gap-1.5 hover:text-slate-300 md:flex",children:[o.jsx("span",{className:Ie("h-1.5 w-1.5 rounded-full",d?"bg-emerald-400":"bg-slate-600")}),c?`GPU: ${c}`:"Connect Colab / GPU"]}),s!==null&&o.jsxs("span",{className:"tabular-nums",children:["RMSD ",s.toFixed(3)," Å"]}),i!==null&&o.jsxs("span",{className:"tabular-nums",children:["Residue ",i]}),o.jsx("div",{className:"flex-1"}),o.jsxs("button",{type:"button",onClick:x,className:"flex items-center gap-1.5 hover:text-slate-300",children:[o.jsx(qr,{className:Ie("h-3 w-3",b?"text-sky-400":"text-slate-600")}),p]}),o.jsx("span",{className:"font-medium text-amber-400/80",children:"Research use only"})]})}const KL=C.lazy(()=>Aa(()=>import("./MolStarViewport-DUHXlKIt.js"),__vite__mapDeps([0,1])).then(e=>({default:e.MolStarViewport}))),zA="MSHHWGYGKHNGPEHWHKDFPIAKGERQSPVDIDTHTAKYDPSLKPLSVSYDQATSLRILNNGHAFNVEFDDSQDKAVLKGGPLDGTYRLIQFHFHWGSLDGQGSEHTVDKKKYAAELHLVHWNTKYGDFGKAVQQPDGLAVLGIFLKVGSAKPGLQKVVDVLDSIKTKGKSADFTNFDPRGLLPESLDYWTYPGSLTTPPLLECVTWIVLKEPISVSSEQVLKFRKLNFNGEGEPEELMVDNWRPAQPLKNRQIKASFK",YL=new Set(["viewer"]);function Rx(e,r,n){const s=new Blob([r],{type:n}),i=URL.createObjectURL(s),c=document.createElement("a");c.href=i,c.download=e,c.click(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}function Zf(e){return e?{sourceTypeHint:e.confidenceKind==="experimental_b_factor"?"experimental":e.confidenceKind==="prediction_plddt"?"prediction":"auto",sourceUrl:e.sourceUrl,dataRevision:e.dataRevision,retrievedAtUtc:e.retrievedAtUtc,license:e.license}:{sourceTypeHint:"auto"}}function OA(e){if(!e)return null;try{const r=new URL(e).host;return r.includes("rcsb")?"RCSB PDB":r.includes("alphafold")?"AlphaFold DB":r.includes("uniprot")?"UniProtKB":r.includes("pubchem")||r.includes("ncbi")?"PubChem":r}catch{return null}}function ep(e){return e.replace(/\.(cif|mmcif|pdb|ent)$/i,"")}function WL(){const{toast:e}=cl(),[r,n]=Zv(),s=C.useRef(null);s.current||(s.current=new $y);const i=C.useRef(null),c=C.useRef(null),[d,f]=C.useState(!1),[p,b]=C.useState(null),[x,g]=C.useState(null),[_,y]=C.useState(null),[S,k]=C.useState("webgl2"),[E,T]=C.useReducer(_y,r.restoreTabs,cq),[j,q]=C.useState("explorer"),[z,O]=C.useState(!0),[V,P]=C.useState("account"),[$,H]=C.useState(!1),[Z,G]=C.useState(!1),[K,we]=C.useState(!1),[Se,Q]=C.useState(!1),F=C.useRef(null),[he,W]=C.useState(()=>rA()),[me,I]=C.useState(null),[J,ge]=C.useState([]),[le,D]=C.useState("webgl2"),[ae,pe]=C.useState(null),[Ae,Ne]=C.useState(null),[Re,$e]=C.useState(()=>Di()),[Ce,Ue]=C.useState(r.viewer.defaultLayout),[be,bt]=C.useState(r.viewer.defaultStyle),[Ot,St]=C.useState(r.viewer.defaultColorMode),[Ke,et]=C.useState(""),[ue,He]=C.useState(""),[Pe,ut]=C.useState({sourceTypeHint:"auto"}),[Je,re]=C.useState(null),[ve,Qe]=C.useState(""),[Fe,Fn]=C.useState(""),[We,Yr]=C.useState(""),[ss,su]=C.useState({sourceTypeHint:"auto"}),[qn,Wr]=C.useState(null),[_t,ja]=C.useState(""),[Nn,Ji]=C.useState(null),[tt,Mh]=C.useState(null),[Ln,dl]=C.useState(null),[Zi,Rh]=C.useState(null),[oa,hl]=C.useState(null),[zh,eo]=C.useState(null),[st,Lt]=C.useReducer(rq,{sequence:zA,mutationsInput:"H94A",mutations:["H94A"],sliceStart:1,sliceEnd:zA.length,focusSeqId:94}),[Ct,Oh]=C.useState(null),[i0,Ph]=C.useState(null),[Nt,An]=C.useReducer(iq,{transcriptId:"NM_000067.3",customDna:"",useCustomDna:!1,targetCodonIndex:94,baseEditOffset:0,newBase:"G",nuclease:"SpCas9"}),[as,Ta]=C.useState(null),[ml,Xr]=C.useState(null),[Mt,Un]=C.useReducer(oq,{selectedPresetId:Xo[0].id,name:Xo[0].name,smiles:Xo[0].smiles}),[Vs,to]=C.useState(null),[no,$h]=C.useState(null),[so,au]=C.useState("reference"),[Qr,fl]=C.useState(null),[ru,iu]=C.useState(null),[ou,rs]=C.useState([]),[Ut,on]=C.useState(()=>Ac()),[la,lu]=C.useState(!1),[cu,uu]=C.useState([]),[Ih,or]=C.useState([]),[pl,Jr]=C.useState(null),[Ea,Zr]=C.useState(()=>t0()),Ma=C.useRef(null),ei=C.useRef(new Set),[At,Dh]=C.useState(()=>dp()),[qh,lr]=C.useState(!1);C.useEffect(()=>(Jv(r.uiScale),dq(Cx)),[]),C.useEffect(()=>{r.restoreTabs&&uq(E)},[E,r.restoreTabs]),C.useEffect(()=>{const M=()=>nu().then(ge);return M(),r0(()=>void M())},[]),C.useEffect(()=>{x&&(e(x,"error"),g(null))},[x,e]);const je=C.useCallback((M,R=!1)=>{T({type:"open",tab:M,toSide:R})},[]),Jt=C.useCallback(M=>{M&&P(M),we(!0)},[]),Lh=C.useCallback(M=>new Promise(R=>{je("assistant"),Jr(M),Ma.current=R}),[je]),Uh=C.useCallback(M=>{const R=Ma.current;Ma.current=null,Jr(null),R?.(M)},[]),ti=C.useCallback(M=>{const R=SD(M);return M.template==="ligand-docking"?je("chemistry"):M.template==="peptide-crispr"?je("peptide"):M.template==="structure-compare"&&je("viewer"),e(`Created project "${R.name}"`,"success"),R},[je,e]),o0=C.useCallback(M=>{Un({type:"set_custom_smiles",smiles:M.smiles,name:M.name}),Ne({tool:"vina",nonce:Date.now()}),je("compute"),e(`Staged ${M.name} for receptor binding / Vina`,"info")},[je,e]),ct=C.useMemo(()=>{if(oa&&oa.seqIds.length>0)return new Set(oa.seqIds);const M=new Set;if(Ct?.local3dContacts)for(const R of Ct.local3dContacts)M.add(R.seqId);return M},[oa,Ct]),ao=C.useMemo(()=>oa&&oa.seqIds.length>0?oa.source:Ct?.local3dContacts&&Ct.local3dContacts.length>0?"Peptide <5 Å shell":null,[oa,Ct]),ca=C.useCallback(async(M,R={})=>{try{const{item:X,duplicate:oe}=await t1(M);return R.silent||e(oe?`${X.name} is already in your library`:`Saved ${X.name} to library`,oe?"info":"success"),X}catch(X){return e(`Could not save to library: ${X instanceof Error?X.message:String(X)}`,"error"),null}},[e]),ws=C.useCallback(M=>{r.autoSaveImports&&ca(M,{silent:!0})},[ca,r.autoSaveImports]),Pt=C.useCallback(async M=>{if(!M.rContent||!M.mContent)return null;if(!M.rChain||!M.mChain)return y("Select a chain for both the reference and the comparison structure."),null;b("Superposing structures…"),y(null);try{const R=await s.current.compareStructures({refLabel:M.rLabel,refContent:M.rContent,refChain:M.rChain,refMeta:M.rMeta,mobLabel:M.mLabel,mobContent:M.mContent,mobChain:M.mChain,mobMeta:M.mMeta,paeJson:M.pae??void 0});Mh(R),f(!0);const X=await nq({id:`${R.reference.sha256.slice(0,8)}-${R.mobile.sha256.slice(0,8)}-${R.reference.chainId}-${R.mobile.chainId}`,createdAtUtc:R.createdAtUtc,refLabel:R.reference.label,refChain:R.reference.chainId,refSha256:R.reference.sha256,mobLabel:R.mobile.label,mobChain:R.mobile.chainId,mobSha256:R.mobile.sha256,rmsdAngstrom:R.metrics.rmsdAngstrom,matchedCaCount:R.metrics.matchedCaCount,paeStatus:R.metrics.paeStatus});return rs(X),R}catch(R){return R instanceof Tr||(R instanceof XA&&R.code==="ERR_AMBIGUOUS_CHAIN"?y(R.message):g(R instanceof Error?R.message:String(R))),null}finally{b(null)}},[]),fn=()=>({rLabel:Ke,rContent:ue,rChain:ve,rMeta:Pe,mLabel:Fe,mContent:We,mChain:_t,mMeta:ss,pae:Nn}),ua=C.useCallback(async M=>{y(null),I(null),b(`Reading ${M.label}…`);try{const R=await s.current.inspectStructure(M.role==="reference"?"inspect-ref":"inspect-mob",{label:M.label,content:M.content,...M.meta});f(!0);const X=R.chains.length===1?R.chains[0].chainId:"";if(!X&&R.chains.length>1&&(q("explorer"),O(!0),y(`${M.label} has ${R.chains.length} chains (${R.chains.map(oe=>oe.chainId).join(", ")}). Pick one in the Workspace panel.`)),M.role==="reference")et(M.label),He(M.content),ut(M.meta),re(R),Qe(X),wx({label:M.label,role:"reference",content:M.content,paeJson:M.pae,sourceUrl:M.meta.sourceUrl??null,license:M.meta.license??null}),X&&We&&_t&&await Pt({rLabel:M.label,rContent:M.content,rChain:X,rMeta:M.meta,mLabel:Fe,mContent:We,mChain:_t,mMeta:ss,pae:Nn});else{const oe=M.pae!==void 0?M.pae:Nn;Fn(M.label),Yr(M.content),su(M.meta),Wr(R),ja(X),Ji(oe),wx({label:M.label,role:"mobile",content:M.content,paeJson:oe,sourceUrl:M.meta.sourceUrl??null,license:M.meta.license??null});const fe=(R.chains.find(ke=>ke.chainId===X)??R.chains[0])?.sequence1Letter;fe&&(Lt({type:"set_sequence",sequence:fe}),Lt({type:"set_mutations_input",raw:""})),X&&ue&&ve&&await Pt({rLabel:Ke,rContent:ue,rChain:ve,rMeta:Pe,mLabel:M.label,mContent:M.content,mChain:X,mMeta:M.meta,pae:oe})}return T({type:"activate",tab:"viewer"}),R}catch(R){return R instanceof Tr||g(R instanceof Error?R.message:String(R)),null}finally{b(null)}},[We,_t,Fe,ss,ue,ve,Ke,Pe,Nn,Pt]),gl=C.useCallback(M=>{const R=M==="reference"?ue:We,X=M==="reference"?Ke:Fe;if(!R)return e(`No ${M} structure loaded to split`,"error"),[];const oe=ND(R,X||M);for(const fe of oe)wx({label:fe.label,role:"extra",content:fe.pdbContent});return q("explorer"),O(!0),e(`Split ${X||M} into ${oe.length} chain/ligand part(s)`,"success"),oe},[ue,Ke,We,Fe,e]),du=C.useCallback((M,R)=>{ua({role:R,label:M.label,content:M.content,meta:{sourceTypeHint:"auto",sourceUrl:M.sourceUrl??void 0,license:M.license??void 0},pae:M.paeJson??void 0})},[ua]),bl=C.useRef(null),cr=C.useCallback(async()=>{b("Loading example…"),y(null),I("ca2-azm");try{const M=await uz(),R=Zf(M.manifest.fixtures.find(Be=>Be.fileName==="3HS4.cif")),X=Zf(M.manifest.fixtures.find(Be=>Be.fileName==="AF-P00918-F1-model_v6.cif"));et("3HS4.cif"),He(M.refCif),ut(R),Fn("AF-P00918-F1-model_v6.cif"),Yr(M.mobCif),su(X),Ji(M.paeJson);const[oe,fe]=await Promise.all([s.current.inspectStructure("inspect-ref",{label:"3HS4.cif",content:M.refCif,...R}),s.current.inspectStructure("inspect-mob",{label:"AF-P00918-F1-model_v6.cif",content:M.mobCif,...X})]);f(!0),re(oe),Wr(fe);const ke=oe.chains.length===1?oe.chains[0].chainId:"",Le=fe.chains.length===1?fe.chains[0].chainId:"";Qe(ke),ja(Le),dl(94),fe.chains[0]?.sequence1Letter&&(Lt({type:"set_sequence",sequence:fe.chains[0].sequence1Letter}),Lt({type:"add_mutation",notation:"H94A"})),ke&&Le&&await Pt({rLabel:"3HS4.cif",rContent:M.refCif,rChain:ke,rMeta:R,mLabel:"AF-P00918-F1-model_v6.cif",mContent:M.mobCif,mChain:Le,mMeta:X,pae:M.paeJson})}catch(M){if(M instanceof Tr)return;g(M instanceof Error?M.message:String(M))}finally{b(null)}},[Pt]);C.useEffect(()=>{fI().then(()=>on(Ac())),iD(),bD(),wD();const M=vD(()=>Dh(dp())),R=L3(()=>$e(Di()));return cE().then(rs).catch(()=>{}),r.loadDemoOnStart&&cr(),()=>{M(),R(),s.current?.dispose()}},[]),C.useEffect(()=>{const M=()=>{cy();try{F.current?.close()}catch{}F.current=null},R=(Le,Be)=>{Be||M(),qI(Le).then(ft=>{W(ft),on(Ac()),Be&&window.history.replaceState({},"",`${window.location.pathname}${window.location.hash}`||"/");const vt=ft.displayName??ft.email;e(ft.serverVerified?`Signed in${vt?` as ${vt}`:""}`:"Signed in, but synlexa.com could not confirm the session. Synlexa Cloud stays off until you reconnect.",ft.serverVerified?"success":"warn")}).catch(ft=>e(ft instanceof Error?ft.message:String(ft),"error")).finally(()=>{Q(!1),M()})},X=j3(window.location.href);X&&R(X,!0);const oe=WI(Le=>R(Le,!1)),fe=HI(Le=>R(Le,!1)),ke=Le=>{Le.key===n0&&(W(rA()),on(Ac()),Q(!1))};return window.addEventListener("storage",ke),()=>{oe(),fe(),window.removeEventListener("storage",ke)}},[e]),C.useEffect(()=>{if(!Se||!F.current)return;const M=window.setInterval(()=>{const R=F.current;R&&R.closed&&(window.clearInterval(M),window.setTimeout(()=>{F.current===R&&(F.current=null,Q(!1))},1500))},500);return()=>window.clearInterval(M)},[Se]);const Bn=C.useCallback(M=>{const R=VI(),X=R?null:KI("about:blank");PI(M,{platform:R?"desktop":"web"}).then(async({url:oe})=>{if(R){if(!await FI(oe))throw new Error("Could not open your browser.");Q(!0);return}X&&!X.closed?(X.location.href=oe,X.focus(),F.current=X,Q(!0)):window.location.assign(oe)}).catch(oe=>{X?.close(),e(oe instanceof Error?oe.message:String(oe),"error")})},[e]),hu=C.useCallback(()=>{cy();try{F.current?.close()}catch{}F.current=null,up(),Q(!1)},[]);C.useEffect(()=>{if(!st.sequence)return;let M=!0;return Ph(null),s.current?.analyzePeptide({sequence:st.sequence,mutations:st.mutations,sliceStart:st.sliceStart,sliceEnd:st.sliceEnd,structureContent:ue||void 0,chainId:ve||void 0,focusSeqId:st.focusSeqId??void 0}).then(R=>{M&&(f(!0),Oh(R))}).catch(R=>{R instanceof Tr||!M||Ph(R instanceof Error?R.message:String(R))}),()=>{M=!1}},[st.sequence,st.mutations,st.sliceStart,st.sliceEnd,st.focusSeqId,ue,ve]),C.useEffect(()=>{let M=!0;return Xr(null),s.current?.analyzeGeneCrispr({transcriptId:Nt.useCustomDna?void 0:Nt.transcriptId,codingDna:Nt.useCustomDna?Nt.customDna:void 0,targetCodonIndex:Nt.targetCodonIndex,baseEditIndex:(Nt.targetCodonIndex-1)*3+Nt.baseEditOffset+1,newBase:Nt.newBase,nuclease:Nt.nuclease}).then(R=>{M&&(f(!0),Ta(R))}).catch(R=>{R instanceof Tr||!M||Xr(R instanceof Error?R.message:String(R))}),()=>{M=!1}},[Nt]),C.useEffect(()=>{if(!Mt.smiles)return;let M=!0;return $h(null),s.current?.analyzeMoleculeSmiles({name:Mt.name,smiles:Mt.smiles}).then(R=>{M&&(f(!0),to(R))}).catch(R=>{R instanceof Tr||!M||$h(R instanceof Error?R.message:String(R))}),()=>{M=!1}},[Mt]),C.useEffect(()=>{const M=so==="reference"?ue:We,R=so==="reference"?ve:_t;if(!M)return;let X=!0;return iu(null),s.current?.analyzeRamachandran({content:M,chainId:R||void 0}).then(oe=>{X&&(f(!0),fl(oe))}).catch(oe=>{oe instanceof Tr||!X||iu(oe instanceof Error?oe.message:String(oe))}),()=>{X=!1}},[so,ue,ve,We,_t]);const Yt=C.useCallback(M=>{dl(M),Lt({type:"focus_residue",seqId:M}),An({type:"set_target_codon",codonIndex:M})},[]),mu=C.useCallback(async M=>{if(I(M.id),y(null),M.kind==="chemistry-panel"){M.smilesPresetId&&Un({type:"select_preset",presetId:M.smilesPresetId}),je("chemistry");return}if(!(!M.reference||!M.mobile)){b(`Loading ${M.title}…`);try{const[R,X,oe,fe]=await Promise.all([cz(),Rb(M.reference.fileName),Rb(M.mobile.fileName),M.paeFileName?Rb(M.paeFileName).catch(()=>null):Promise.resolve(null)]),ke=Zf(R.fixtures.find(Zt=>Zt.fileName===M.reference.fileName)),Le=Zf(R.fixtures.find(Zt=>Zt.fileName===M.mobile.fileName));et(M.reference.label),He(X),ut(ke),Fn(M.mobile.label),Yr(oe),su(Le),Ji(fe);const[Be,ft]=await Promise.all([s.current.inspectStructure("inspect-ref",{label:M.reference.label,content:X,...ke}),s.current.inspectStructure("inspect-mob",{label:M.mobile.label,content:oe,...Le})]);f(!0),re(Be),Wr(ft),Qe(M.reference.chainId),ja(M.mobile.chainId);const vt=ft.chains.find(Zt=>Zt.chainId===M.mobile.chainId)??ft.chains[0];vt?.sequence1Letter&&(Lt({type:"set_sequence",sequence:vt.sequence1Letter}),Lt({type:"set_mutations_input",raw:(M.peptideMutations??[]).join(", ")})),M.crispr&&(An({type:"select_transcript",transcriptId:M.crispr.transcriptId}),An({type:"set_target_codon",codonIndex:M.crispr.targetCodonIndex}),An({type:"set_base_edit",offset:M.crispr.baseEditOffset,newBase:M.crispr.newBase}),An({type:"set_nuclease",nuclease:M.crispr.nuclease})),M.smilesPresetId&&Un({type:"select_preset",presetId:M.smilesPresetId}),M.focusSeqId&&(dl(M.focusSeqId),Lt({type:"focus_residue",seqId:M.focusSeqId})),await Pt({rLabel:M.reference.label,rContent:X,rChain:M.reference.chainId,rMeta:ke,mLabel:M.mobile.label,mContent:oe,mChain:M.mobile.chainId,mMeta:Le,pae:fe}),T({type:"activate",tab:"viewer"}),M.openTab&&M.openTab!=="sequence"&&je(M.openTab)}catch(R){R instanceof Tr||g(R instanceof Error?R.message:String(R))}finally{b(null)}}},[Pt,je]),Ra=C.useCallback(async(M,R)=>{const X={sourceTypeHint:M.sourceTypeHint,sourceUrl:M.sourceUrl,dataRevision:M.dataRevision??void 0,retrievedAtUtc:M.retrievedAtUtc,license:M.license};await ua({role:R,label:M.label,content:M.content,meta:X,pae:R==="mobile"?M.paeJson??null:void 0}),ws({kind:"structure",format:/\.pdb$/i.test(M.label)?"pdb":"cif",name:ep(M.label),content:M.content,paeJson:M.paeJson,source:{database:OA(M.sourceUrl),accession:M.uniprotAccession??ep(M.label),sourceUrl:M.sourceUrl,license:M.license,retrievedAtUtc:M.retrievedAtUtc,origin:M.origin,sourceTypeHint:M.sourceTypeHint,dataRevision:M.dataRevision}})},[ua,ws]),xl=C.useCallback(M=>{Un({type:"set_custom_smiles",smiles:M.smiles,name:M.name}),je("chemistry"),ws({kind:"compound",format:"smiles",name:M.name,content:M.smiles,source:{database:"PubChem",accession:M.cid!==null?`CID ${M.cid}`:null,sourceUrl:M.sourceUrl,license:M.license,retrievedAtUtc:M.retrievedAtUtc,origin:M.origin}})},[je,ws]),fu=C.useCallback(async(M,R="auto")=>{I(null);const X=()=>({database:null,accession:null,sourceUrl:null,license:null,retrievedAtUtc:null,origin:"local-file"});let oe=!!ue,fe=!!We;for(const ke of Array.from(M)){const Le=ke.name.toLowerCase(),Be=await ke.text();if(Le.endsWith(".synlexa.bundle.json")){try{const vt=await ZD(Be),Zt=vt.files.find($a=>$a.role==="reference"),ks=vt.files.find($a=>$a.role==="mobile"),ri=vt.files.find($a=>$a.role==="pae");if(Zt&&ks){et(Zt.label),He(Zt.content),Fn(ks.label),Yr(ks.content),Ji(ri?.content??null);const[$a,u0]=await Promise.all([s.current.inspectStructure("inspect-ref",{label:Zt.label,content:Zt.content}),s.current.inspectStructure("inspect-mob",{label:ks.label,content:ks.content})]);re($a),Wr(u0),Qe(vt.state.refChain),ja(vt.state.mobChain),vt.comparisonResult&&Mh(vt.comparisonResult),e(`Opened project ${ke.name}`,"success")}}catch(vt){g(vt instanceof Error?vt.message:String(vt))}continue}if(/\.(fasta|fa|faa)$/.test(Le)){const vt=Be.split(/\r?\n/).filter(Zt=>!Zt.startsWith(">")).join("").trim().toUpperCase();/^[ACGTU\s]+$/i.test(vt)&&vt.length>=9?(An({type:"set_custom_dna",dna:vt.replace(/U/g,"T")}),je("crispr")):(Lt({type:"set_sequence",sequence:vt}),je("peptide")),ws({kind:"sequence",format:"fasta",name:ke.name.replace(/\.[^.]+$/,""),content:vt,source:X()});continue}if(Le.endsWith(".smi")){const vt=Be.split(/\r?\n/).find(ri=>ri.trim().length>0)??"",[Zt,...ks]=vt.trim().split(/\s+/);if(Zt){const ri=ks.join(" ")||ke.name.replace(/\.[^.]+$/,"");Un({type:"set_custom_smiles",smiles:Zt,name:ri}),je("chemistry"),ws({kind:"compound",format:"smiles",name:ri,content:Zt,source:X()})}continue}if(Le.endsWith(".json")){Ji(Be),e("PAE matrix loaded","success"),ue&&We&&ve&&_t&&await Pt({...fn(),pae:Be});continue}if(!/\.(cif|mmcif|pdb|ent)$/.test(Le)){e(`${ke.name}: unsupported file type`,"warn");continue}const ft=R!=="auto"?R:oe&&(Le.includes("af-")||Le.includes("model")||!fe)?"mobile":"reference";ft==="reference"?oe=!0:fe=!0,await ua({role:ft,label:ke.name,content:Be,meta:{sourceTypeHint:"auto"}}),ws({kind:"structure",format:/\.(pdb|ent)$/.test(Le)?"pdb":"cif",name:ep(ke.name),content:Be,source:X()})}},[Ke,ue,ve,Pe,Fe,We,_t,ss,Nn,Pt,ua,je,ws,e]),za=C.useCallback(async(M,R)=>{if(n1(M.id,{lastOpenedAtUtc:new Date().toISOString()}),M.kind==="compound"){Un({type:"set_custom_smiles",smiles:M.content,name:M.name}),je("chemistry");return}if(M.kind==="sequence"){/^[ACGT]+$/.test(M.content)&&M.content.length>=9?(An({type:"set_custom_dna",dna:M.content}),je("crispr")):(Lt({type:"set_sequence",sequence:M.content}),je("peptide"));return}const X=R!=="auto"?R:ue&&(M.source.sourceTypeHint==="prediction"||!We)?"mobile":"reference";await ua({role:X,label:`${M.name}.${M.format==="pdb"?"pdb":"cif"}`,content:M.content,meta:{sourceTypeHint:M.source.sourceTypeHint??"auto",sourceUrl:M.source.sourceUrl??void 0,license:M.source.license??void 0,retrievedAtUtc:M.source.retrievedAtUtc??void 0,dataRevision:M.source.dataRevision??void 0},pae:X==="mobile"?M.paeJson??null:void 0}),e(`${M.name} loaded as ${X==="reference"?"reference":"comparison"}`,"success")},[ue,We,ua,je,e]),l0=C.useCallback(M=>{const R=M==="reference"?Ke:Fe,X=M==="reference"?ue:We,oe=M==="reference"?Pe:ss;X&&ca({kind:"structure",format:/\.(pdb|ent)$/i.test(R)?"pdb":"cif",name:ep(R),content:X,paeJson:M==="mobile"?Nn:null,source:{database:OA(oe.sourceUrl),accession:null,sourceUrl:oe.sourceUrl??null,license:oe.license??null,retrievedAtUtc:oe.retrievedAtUtc??null,origin:oe.sourceUrl?"pinned-local-cache":"local-file",sourceTypeHint:oe.sourceTypeHint,dataRevision:oe.dataRevision??null}})},[Ke,Fe,ue,We,Pe,ss,Nn,ca]),ni=r.viewer.embedPngInReports,da=C.useCallback(()=>{if(!tt){e("Run a comparison first","warn");return}const M=lI({comparison:tt,peptide:Ct,crispr:as,smiles:Vs,viewportPngDataUrl:ni?i.current?.capturePngDataUrl()??null:null});Rx(`synlexa-ruo-report-${tt.resultId.slice(0,12)}.html`,M,"text/html;charset=utf-8")},[tt,Ct,as,Vs,ni,e]),is=C.useCallback(()=>{if(!tt){e("Run a comparison first","warn");return}const M=oI({comparison:tt,peptide:Ct,crispr:as,smiles:Vs,viewportPngDataUrl:ni?i.current?.capturePngDataUrl()??null:null});Rx(`synlexa-ruo-manifest-${tt.resultId.slice(0,12)}.json`,M,"application/json;charset=utf-8")},[tt,Ct,as,Vs,ni,e]),si=C.useCallback(async()=>{if(!ue||!We){e("Load a reference and a comparison structure first","warn");return}const M=await JD({refLabel:Ke,refContent:ue,mobLabel:Fe,mobContent:We,paeJson:Nn,comparisonResult:tt,state:{refChain:ve,mobChain:_t,focusedSeqId:Ln,peptide:{sequence:st.sequence,mutations:st.mutations,sliceStart:st.sliceStart,sliceEnd:st.sliceEnd},crispr:{transcriptId:Nt.transcriptId,customDna:Nt.customDna,targetCodonIndex:Nt.targetCodonIndex,baseEditIndex:Nt.baseEditOffset,newBase:Nt.newBase,nuclease:Nt.nuclease},smiles:{name:Mt.name,smiles:Mt.smiles}}});Rx(`synlexa-project-${Date.now()}.synlexa.bundle.json`,JSON.stringify(M,null,2),"application/json;charset=utf-8")},[Ke,ue,Fe,We,Nn,tt,ve,_t,Ln,st,Nt,Mt,e]),Bh=C.useCallback(M=>{M.type==="focus_residues"&&M.seqIds.length>0?Yt(M.seqIds[0]):M.type==="compare_structures"?Pt(fn()):M.type==="request_report"?M.format==="json"?is():da():M.type==="switch_tab"?je(M.tab):M.type==="apply_peptide_mutation"?Lt({type:"add_mutation",notation:M.notation}):M.type==="analyze_smiles"?Un({type:"set_custom_smiles",smiles:M.smiles,name:M.name}):M.type==="focus_crispr_codon"&&Yt(M.codonIndex)},[Yt,Pt,Ke,ue,ve,Pe,Fe,We,_t,ss,Nn,is,da,je]),ro=C.useCallback(async(M,R)=>{switch(M){case"fetch_from_database":{const X=String(R.source||"rcsb"),oe=String(R.query||""),fe=await Iy(X,oe);if(fe.records.length===0)return{ok:!1,summary:`No matches in ${X} for "${oe}"`,data:{origin:fe.origin,records:[]}};const ke=fe.records[0];if(R.autoImport!==!1){if(ke.source==="pubchem"){const ft=dj(ke);return xl(ft),{ok:!0,summary:`Imported ${ft.name} (${ft.origin})`,data:ft}}const Le=R.role==="reference"?"reference":R.role==="mobile"?"mobile":ke.source==="rcsb"?"reference":"mobile",Be=await uj(ke);return await Ra(Be,Le),{ok:!0,summary:`Imported ${Be.label} as ${Le}`,data:{label:Be.label,role:Le,sha256:Be.sha256,origin:Be.origin,sourceUrl:Be.sourceUrl,license:Be.license}}}return{ok:!0,summary:`Found ${fe.records.length} record(s) in ${X}`,data:{origin:fe.origin,records:fe.records.slice(0,5)}}}case"run_structure_superposition":{const X=typeof R.refChain=="string"&&R.refChain?R.refChain:ve,oe=typeof R.mobChain=="string"&&R.mobChain?R.mobChain:_t;X!==ve&&Qe(X),oe!==_t&&ja(oe);const fe=await Pt({...fn(),rChain:X,mChain:oe});return fe?(je("results"),{ok:!0,summary:`RMSD ${fe.metrics.rmsdAngstrom.toFixed(4)} Å (${fe.metrics.matchedCaCount} Cα)`,data:{resultId:fe.resultId,metrics:fe.metrics,refSha256:fe.reference.sha256,mobSha256:fe.mobile.sha256}}):{ok:!1,summary:"Superposition did not complete (check chains)",data:null}}case"focus_3d_residues":{const X=(Array.isArray(R.seqIds)?R.seqIds:[]).map(Number).filter(fe=>Number.isFinite(fe)&&fe>0);if(X.length===0)return{ok:!1,summary:"No positive residue IDs supplied",data:null};Yt(X[0]);const oe=X.map(fe=>tt?.matchedResidues.find(ke=>ke.refSeqId===fe)??{refSeqId:fe,note:"not in matched Cα set"});return{ok:!0,summary:`Focused residue(s) ${X.join(", ")}`,data:{seqIds:X,matched:oe}}}case"engineer_peptide_mutation":{const X=Array.isArray(R.mutations)?R.mutations.map(ke=>String(ke).trim().toUpperCase()).filter(Boolean):[],oe=typeof R.focusSeqId=="number"&&Number.isFinite(R.focusSeqId)?R.focusSeqId:st.focusSeqId??void 0;je("peptide");for(const ke of X)Lt({type:"add_mutation",notation:ke});oe&&Yt(oe);const fe=await s.current.analyzePeptide({sequence:st.sequence,mutations:Array.from(new Set([...st.mutations,...X])),sliceStart:st.sliceStart,sliceEnd:st.sliceEnd,structureContent:ue||void 0,chainId:ve||void 0,focusSeqId:oe});return Oh(fe),lA({name:X.join(", ")||`Peptide (${fe.engineered.length} aa)`,sequence:st.sequence,mutations:Array.from(new Set([...st.mutations,...X]))}),{ok:!0,summary:`Applied ${X.join(", ")||"peptide analysis"} (ΔMW ${fe.deltas.mwAverageDa.toFixed(1)} Da, pI ${fe.engineered.pi.toFixed(2)})`,data:fe}}case"design_crispr_edit":{const X=typeof R.transcriptId=="string"&&R.transcriptId?R.transcriptId:Nt.transcriptId,oe=Math.max(1,Number(R.targetCodonIndex)||Nt.targetCodonIndex),fe=[0,1,2].includes(Number(R.baseEditOffset))?Number(R.baseEditOffset):Nt.baseEditOffset,ke=["A","C","G","T"].includes(String(R.newBase).toUpperCase())?String(R.newBase).toUpperCase():Nt.newBase,Le=["SpCas9","SaCas9","Cas12a"].includes(String(R.nuclease))?String(R.nuclease):Nt.nuclease;je("crispr"),An({type:"select_transcript",transcriptId:X}),An({type:"set_target_codon",codonIndex:oe}),An({type:"set_base_edit",offset:fe,newBase:ke}),An({type:"set_nuclease",nuclease:Le});const Be=await s.current.analyzeGeneCrispr({transcriptId:X,targetCodonIndex:oe,baseEditIndex:(oe-1)*3+fe+1,newBase:ke,nuclease:Le});return Ta(Be),cA({name:`${Be.geneSymbol} codon ${oe} (${Be.targetCodon.wtCodon}→${Be.targetCodon.editedCodon})`,transcriptId:X,targetCodonIndex:oe,baseEditOffset:fe,newBase:ke,nuclease:Le}),{ok:!0,summary:`${Be.geneSymbol} codon ${oe}: ${Be.targetCodon.wtCodon}→${Be.targetCodon.editedCodon} (${Be.targetCodon.consequence}), ${Be.pamSites.length} PAMs`,data:{...Be,pamSites:Be.pamSites.slice(0,8)}}}case"inspect_chemical_smiles":{const X=String(R.smiles||"").trim(),oe=typeof R.name=="string"&&R.name.trim()?R.name.trim():"Assistant SMILES";je("chemistry"),Un({type:"set_custom_smiles",smiles:X,name:oe});const fe=await s.current.analyzeMoleculeSmiles({name:oe,smiles:X});return to(fe),{ok:!0,summary:`${fe.formula}, MW ${fe.molecularWeight.toFixed(2)} Da, TPSA ${fe.tpsa.toFixed(1)} Ų`,data:fe}}case"analyze_ramachandran":{const X=R.target==="mobile"?"mobile":"reference",oe=X==="reference"?ue:We,fe=typeof R.chainId=="string"&&R.chainId?R.chainId:X==="reference"?ve:_t;au(X),je("ramachandran");const ke=await s.current.analyzeRamachandran({content:oe,chainId:fe||void 0});return fl(ke),{ok:!0,summary:`${X} (${ke.chainId}): ${ke.regionCounts.favored}/${ke.residueCount} favored, ${ke.contactPairs.length} contacts`,data:{chainId:ke.chainId,residueCount:ke.residueCount,secondaryCounts:ke.secondaryCounts,regionCounts:ke.regionCounts,contactCount:ke.contactPairs.length,outliers:ke.residues.filter(Le=>Le.region==="outlier").slice(0,10)}}}case"export_ruo_report":{const X=String(R.format||"html");return X==="json"?is():X==="bundle"?await si():da(),{ok:!0,summary:`Started ${X.toUpperCase()} download`,data:{exported:X}}}case"get_workspace_state":{const X=typeof R.section=="string"?R.section:"all",oe=typeof R.topN=="number"&&Number.isFinite(R.topN)?R.topN:10,ke=Ii({refLabel:Ke,mobLabel:Fe,refChain:ve,mobChain:_t,refInspect:Je,mobInspect:qn,comparison:tt,peptide:Ct,crispr:as,smiles:Vs,ramachandran:Qr},J,X,oe);return{ok:!0,summary:`Inspected workspace (${X}, ${tt?`RMSD ${tt.metrics.rmsdAngstrom.toFixed(3)} Å`:"no comparison"})`,data:ke}}case"search_scientific_web":{const X=String(R.query||"").trim(),oe=["all","literature","trials"].includes(String(R.scope))?String(R.scope):"all",fe=typeof R.limit=="number"&&Number.isFinite(R.limit)?R.limit:5,ke=await UD(X,{scope:oe,limit:fe});return{ok:!0,summary:`Web search "${X}": ${ke.hits.length} record(s) (${ke.origin})`,data:ke}}case"query_local_library":{const X=typeof R.kind=="string"?R.kind:"all",oe=typeof R.query=="string"?R.query.trim().toLowerCase():"",fe=J.filter(ke=>X==="all"?!0:ke.kind===X).filter(ke=>oe?`${ke.name} ${ke.source.accession??""} ${ke.tags.join(" ")}`.toLowerCase().includes(oe):!0).slice(0,20).map(ke=>({id:ke.id,kind:ke.kind,name:ke.name,format:ke.format,sha256:ke.sha256,source:ke.source}));return{ok:!0,summary:`Found ${fe.length} local library item(s)`,data:{count:fe.length,items:fe}}}case"list_compute_nodes":{const X=Di();return{ok:!0,summary:`${X.nodes.length} paired node(s); active=${X.activeNode?.label??"none"}`,data:{activeNodeId:X.activeNodeId,nodes:X.nodes.map(oe=>({id:oe.id,label:oe.label,kind:oe.kind,online:oe.online,gpus:oe.capabilities?.gpus??[],installedTools:oe.capabilities?.tools.filter(fe=>fe.installed).map(fe=>fe.id)??[]}))}}}case"run_compute_job":{const oe=Di().activeNode;if(!oe||!oe.online)return{ok:!1,summary:"No online Compute Node connected. Open Compute Nodes tab to pair Colab or a local GPU daemon.",data:null};const fe=String(R.toolId||"vina_docking"),ke=typeof R.smiles=="string"&&R.smiles.trim()?R.smiles.trim():Mt.smiles,Le=oA(tt,Ln),Be=fe==="vina_docking"?{ligandSmiles:ke,receptorPdb:ue,center:Le?.center??[0,0,0],size:Le?.size??[22,22,22]}:fe==="openmm_md"?{pdbContent:ue,steps:Number(R.steps??1e3)}:fe==="pyscf_qm"?{smiles:ke}:fe==="boltz_predict"?{sequences:[{id:"A",sequence:st.sequence}]}:{...R};je("compute");const ft=await dy(oe.id,fe,Be);return hy(oe.id,ft.job_id),{ok:!0,summary:`Dispatched ${fe} (${ft.job_id}) to ${oe.label}`,data:ft}}case"control_app_ui":{const X=["home","viewer","results","sequence","ramachandran","peptide","crispr","chemistry","workflow","compute","plugins","assistant","mcp","library"],oe=typeof R.tab=="string"&&X.includes(R.tab)?R.tab:null;oe&&je(oe,!!R.toSide),typeof R.sidebarView=="string"&&["explorer","library","tools","history"].includes(R.sidebarView)&&q(R.sidebarView),typeof R.sidebarOpen=="boolean"&&O(R.sidebarOpen),(R.viewportEngine==="webgl2"||R.viewportEngine==="molstar")&&D(R.viewportEngine),(R.viewportLayout==="overlay"||R.viewportLayout==="split"||R.viewportLayout==="reference"||R.viewportLayout==="mobile")&&Ue(R.viewportLayout),(R.renderStyle==="ribbon"||R.renderStyle==="trace"||R.renderStyle==="pocket")&&bt(R.renderStyle),(R.colorMode==="plddt"||R.colorMode==="bfactor"||R.colorMode==="deviation"||R.colorMode==="identity")&&St(R.colorMode);const fe=R.cameraPreset??R.applyPreset;return(fe==="overview"||fe==="active-site"||fe==="n-terminus"||fe==="reset")&&i.current?.applyPreset(fe),R.openTutorial===!0||R.openModal==="tutorial"?lr(!0):R.openModal==="databases"?G(!0):R.openModal==="settings"?Jt("ai"):R.openModal==="palette"?H(!0):R.openModal==="close"&&(lr(!1),G(!1),we(!1),H(!1)),R.resetLayout===!0&&T({type:"reset"}),{ok:!0,summary:`Updated UI (${[oe?`tab=${oe}`:null,R.sidebarView?`sidebar=${String(R.sidebarView)}`:null,R.openModal?`modal=${String(R.openModal)}`:null].filter(Boolean).join(", ")||"applied state"})`,data:{tab:oe,sidebarView:R.sidebarView??null,viewportEngine:R.viewportEngine??null}}}case"manage_project":{const X=String(R.action||"list");if(X==="list"){const oe=dp();return{ok:!0,summary:`${oe.projects.length} project(s); active="${oe.activeProject?.name??"none"}"`,data:{activeProjectId:oe.activeProject?.id??null,projects:oe.projects.map(fe=>({id:fe.id,name:fe.name,template:fe.template,structures:fe.structures.map(ke=>ke.label),molecules:fe.molecules.map(ke=>({name:ke.name,smiles:ke.smiles})),peptides:fe.peptides.length,crisprs:fe.crisprs.length}))}}}if(X==="create"){const oe=["blank","structure-compare","ligand-docking","peptide-crispr"].includes(String(R.template))?String(R.template):"ligand-docking",fe=ti({name:String(R.name||"AI Research Project"),description:typeof R.description=="string"?R.description:void 0,template:oe});return{ok:!0,summary:`Created project "${fe.name}" (${fe.id})`,data:fe}}if(X==="switch"){const oe=vx(String(R.projectId||""));return oe?{ok:!0,summary:`Switched active project to "${oe.name}"`,data:oe}:{ok:!1,summary:`Project "${String(R.projectId)}" not found`,data:null}}if(X==="add_molecule"){const oe=String(R.smiles||Mt.smiles).trim(),fe=String(R.name||"Designed Ligand").trim(),ke=Sx({name:fe,smiles:oe,note:typeof R.note=="string"?R.note:void 0});return Un({type:"set_custom_smiles",smiles:oe,name:fe}),je("chemistry"),{ok:!0,summary:`Saved "${fe}" (${oe}) into active project`,data:ke}}if(X==="split_chains"){const oe=(R.target??R.role)==="mobile"?"mobile":"reference",fe=gl(oe);return fe.length===0?{ok:!1,summary:`No ${oe} structure loaded or no chains found`,data:[]}:{ok:!0,summary:`Split ${oe} into ${fe.length} chain/ligand assets`,data:fe.map(ke=>({label:ke.label,kind:ke.kind,chainId:ke.chainId,atomCount:ke.atomCount}))}}if(X==="stage_binding"){const oe=typeof R.smiles=="string"&&R.smiles.trim()?R.smiles.trim():Mt.smiles,fe=typeof R.name=="string"&&R.name.trim()?R.name.trim():Mt.name;return Un({type:"set_custom_smiles",smiles:oe,name:fe}),Ne({tool:"vina",nonce:Date.now()}),je("compute"),{ok:!0,summary:`Staged "${fe}" + "${Ke||"active receptor"}" for binding`,data:{smiles:oe,name:fe,receptor:Ke}}}return{ok:!1,summary:`Unknown project action: ${X}`,data:null}}case"design_molecule_rdkit":{let X=String(R.smiles||Mt.smiles).trim();const oe=String(R.name||"Designed Analog").trim(),fe=typeof R.modifyAction=="string"?R.modifyAction:"";fe==="add_fluoro"&&!X.includes("F")?X=`${X}F`:fe==="add_methyl"?X=`${X}C`:fe==="add_hydroxyl"&&(X=`${X}O`),je("chemistry"),Un({type:"set_custom_smiles",smiles:X,name:oe});const ke=await s.current.analyzeMoleculeSmiles({name:oe,smiles:X});to(ke);let Le=[],Be=X,ft=null;if(typeof Worker<"u")try{const Zt=await Fo().analyzeMolecule(X);Be=Zt.canonicalSmiles||X,Le=Zt.alerts.map(ks=>`${ks.family}: ${ks.label}`),typeof R.smartsQuery=="string"&&R.smartsQuery.trim()&&(ft=!!(await Fo().searchLibrary(R.smartsQuery.trim(),[{id:oe,name:oe,smiles:Be}]))[0]?.substructureMatch)}catch{}const vt=R.saveToProject===!1?null:Sx({name:oe,smiles:Be,note:Le.length?`Alerts: ${Le.join("; ")}`:"Clean PAINS/Brenk"});return{ok:!0,summary:`Designed "${oe}" (${ke.formula}, MW ${ke.molecularWeight.toFixed(1)}, cLogP ${ke.crippenLogP.toFixed(2)}, TPSA ${ke.tpsa.toFixed(1)})`,data:{name:oe,canonicalSmiles:Be,descriptors:ke,alerts:Le,smartsMatched:ft,savedProjectAssetId:vt?.id??null}}}case"run_workflow_pipeline":{const X=Zd.find(Be=>Be.id===R.templateId)??Zd[0],oe=String(R.action||"run");if(je("workflow"),oe==="export_nextflow"){const Be=X3(X);return{ok:!0,summary:`Exported Nextflow DSL2 for "${X.name}"`,data:{templateId:X.id,nextflow:Be}}}if(oe==="export_snakemake"){const Be=Q3(X);return{ok:!0,summary:`Exported Snakemake Snakefile for "${X.name}"`,data:{templateId:X.id,snakefile:Be}}}const fe=fh(X);je("workflow");const ke=[];for(const Be of fe){if(!bl.current)break;try{const ft=await bl.current(Be.kind,Be.params);ke.push({id:Be.id,kind:Be.kind,ok:!0,summary:ft.summary})}catch(ft){const vt=ft instanceof Error?ft.message:String(ft);ke.push({id:Be.id,kind:Be.kind,ok:!1,summary:vt});break}}return{ok:ke.length===fe.length&&ke.every(Be=>Be.ok),summary:`${X.name}: completed ${ke.filter(Be=>Be.ok).length}/${fe.length} workflow step(s)`,data:{templateId:X.id,templateName:X.name,steps:ke}}}case"manage_plugins":{const X=String(R.action||"list");if(X==="list"){const ke=Jd();return{ok:!0,summary:`${ke.filter(Le=>Le.enabled).length}/${ke.length} plugin(s) enabled`,data:ke.map(Le=>({id:Le.id,name:Le.name,category:Le.category,tier:Le.tier,license:Le.license,commercialSafe:Le.commercialSafe,enabled:Le.enabled}))}}const oe=String(R.pluginId||"").trim();if(!oe)return{ok:!1,summary:"pluginId required",data:null};const fe=X==="enable";return H3(oe,fe),je("plugins"),{ok:!0,summary:`${fe?"Enabled":"Disabled"} plugin ${oe}`,data:{pluginId:oe,enabled:fe}}}}},[Ke,ue,ve,Pe,Je,Fe,We,_t,ss,qn,Nn,tt,st,Ct,Nt,as,Mt.smiles,Mt.name,Vs,Qr,J,Ln,Pt,Yt,Ra,xl,da,is,si,je,Jt,ti,gl]),jn=C.useMemo(()=>oA(tt,Ln),[tt,Ln]),yl=C.useMemo(()=>(tt?.refDisplayAtoms?.ligands??Je?.ligands??[]).filter(R=>R.resName.toUpperCase()!=="HOH"&&R.atoms.length>0).map(R=>{let X=0,oe=0,fe=0;for(const Le of R.atoms)X+=Le.xyz[0],oe+=Le.xyz[1],fe+=Le.xyz[2];const ke=Math.max(1,R.atoms.length);return{resName:R.resName,chainId:R.chainId,seqId:R.seqId,atomCount:R.atoms.length,centroid:[X/ke,oe/ke,fe/ke]}}),[tt,Je]),Ks=C.useMemo(()=>({activeProjectName:At.activeProject?.name??null,refLabel:Ke,refChain:ve,mobLabel:Fe,mobChain:_t,hasRef:!!ue,hasMob:!!We,hasComparison:!!tt,focusedSeqId:Ln,activeHighlight:ct.size>0?{source:ao??"Selection",seqIds:Array.from(ct)}:null,projectMolecules:At.activeProject?.molecules??[],projectStructures:At.activeProject?.structures??[],coCrystalLigands:yl,dockingBox:jn,focusIn3D:(M,R)=>{Yt(M),R?.style&&bt(R.style),R?.centerCamera!==!1&&Rh({seqId:M,nonce:Date.now()}),R?.openViewer==="activate"?je("viewer",!1):R?.openViewer==="side"&&je("viewer",!0)},highlightIn3D:(M,R,X)=>{const oe=Array.from(new Set(M.filter(fe=>Number.isFinite(fe)&&fe>0)));hl(oe.length>0?{source:R,seqIds:oe}:null),X?.focusSeqId!==void 0&&(Yt(X.focusSeqId),Rh({seqId:X.focusSeqId,nonce:Date.now()})),X?.style&&bt(X.style),X?.openViewer==="activate"?je("viewer",!1):X?.openViewer==="side"&&je("viewer",!0),oe.length>0&&e(`Highlighted ${oe.length} residue(s) in 3D (${R})`,"info")},clearHighlights3D:()=>hl(null),setStyle3D:M=>bt(M),setColorMode3D:M=>St(M),openTab:je,openDatabases:()=>G(!0),loadExample:()=>void cr(),saveMoleculeToProject:M=>{Sx(M),e(`Saved ${M.name} to active project`,"success")},saveMoleculeToLibrary:M=>{ca({kind:"compound",format:"smiles",name:M.name,content:M.smiles,source:{database:null,accession:null,sourceUrl:null,license:null,retrievedAtUtc:new Date().toISOString(),origin:"manual"}})},savePeptideToProject:M=>{lA(M),e(`Saved peptide "${M.name}" to active project`,"success")},saveCrisprToProject:M=>{cA(M),e(`Saved CRISPR edit "${M.name}" to active project`,"success")},syncPeptideFromChain:M=>{const R=M==="reference"?Je:qn,X=M==="reference"?ve:_t,oe=R?.chains.find(fe=>fe.chainId===X)??R?.chains[0];if(!oe?.sequence1Letter){e(`No amino-acid sequence found on ${M} chain`,"warn");return}Lt({type:"set_sequence",sequence:oe.sequence1Letter}),e(`Synced ${oe.sequence1Letter.length} aa from ${M} chain ${oe.chainId}`,"success")},sendMutationToPeptide:(M,R)=>{Lt({type:"add_mutation",notation:M}),R&&Yt(R),je("peptide"),e(`Applied ${M} in Peptide Workbench`,"info")},sendResidueToCrispr:M=>{Yt(M),je("crispr")},sendResidueToRamachandran:M=>{Yt(M),je("ramachandran")}}),[At.activeProject,Ke,ve,Fe,_t,ue,We,tt,Ln,ct,ao,yl,jn,Je,qn,Yt,je,cr,ca,e]),ur=C.useCallback(async(M,R)=>{switch(M){case"load_structures":if(!ue&&!Mt.smiles)throw new Error("Load a structure or SMILES first.");return{summary:`${Ke||"No structure"} · ${Mt.name}`};case"kabsch_compare":{const X=await Pt({rLabel:Ke,rContent:ue,rChain:ve,rMeta:Pe,mLabel:Fe,mContent:We,mChain:_t,mMeta:ss,pae:Nn});if(!X)throw new Error("Superposition failed; verify reference & mobile chains.");return{summary:`RMSD ${X.metrics.rmsdAngstrom.toFixed(3)} Å (${X.metrics.matchedCaCount} Cα)`,metrics:X.metrics}}case"rdkit_prep":{if(typeof Worker>"u")return{summary:`Wasm SMILES (${Mt.smiles})`};const X=await Fo().analyzeMolecule(Mt.smiles);return{summary:`${X.canonicalSmiles} · ${X.alerts.length} alerts`,metrics:X.descriptors}}case"export_report":return is(),{summary:"Exported RUO JSON provenance manifest"};default:{const oe=Di().activeNode;if(!oe||!oe.online)throw new Error(`Node "${M}" requires an online Tier-2 GPU/Compute Node (pair Colab or local worker).`);const fe={...R,smiles:Mt.smiles,ligandSmiles:Mt.smiles,pdbContent:ue,receptorPdb:ue,targetPdb:ue,center:jn?.center??[0,0,0],size:jn?.size??[22,22,22],sequences:[{id:"A",sequence:st.sequence}]},ke=await dy(oe.id,M,fe),Le=await hy(oe.id,ke.job_id);if(Le.status!=="completed")throw new Error(Le.error_message||`Remote job ${Le.status}`);return{summary:`${M} complete on ${oe.label}`,metrics:Le.metrics}}}},[Ke,ue,ve,Pe,Fe,We,_t,ss,Nn,Mt.name,Mt.smiles,st.sequence,jn,Pt,is]);bl.current=ur;const ha=C.useMemo(()=>({refLabel:Ke,mobLabel:Fe,refChain:ve,mobChain:_t,refInspect:Je,mobInspect:qn,comparison:tt,peptide:Ct,crispr:as,smiles:Vs,ramachandran:Qr}),[Ke,Fe,ve,_t,Je,qn,tt,Ct,as,Vs,Qr]),_l=C.useMemo(()=>({workspace:ha,libraryItems:J,executeTool:ro}),[ha,J,ro]),pu=C.useCallback(async M=>{const R=M.trim();if(!R||la)return;const X={id:`u-${Date.now()}`,role:"user",text:R,timestampUtc:new Date().toISOString()},oe=cu;uu(fe=>[...fe,X]),or([]),lu(!0);try{const fe=await rD({prompt:R,history:oe,workspace:ha,executeTool:(ke,Le)=>eE(_l,ke,Le,"internal-ai-agent"),onFallbackAction:Bh,onProgress:or,requestToolPermission:Lh,sessionApprovedCategories:ei.current,permissionPolicies:Ea,config:Ut});uu(ke=>[...ke,fe])}finally{or([]),Ma.current=null,Jr(null),lu(!1)}},[la,cu,ha,_l,Bh,Lh,Ea,Ut]),vl=C.useCallback(M=>on(JI(M)),[]),io=C.useCallback(M=>{W(M),on(Ac())},[]),Ss=E.groups[E.focused]?.active??null;C.useEffect(()=>{const M=R=>{const X=R.metaKey||R.ctrlKey,oe=R.key.toLowerCase();X&&oe==="k"?(R.preventDefault(),H(fe=>!fe)):X&&oe==="o"?(R.preventDefault(),c.current?.click()):X&&R.shiftKey&&oe==="f"?(R.preventDefault(),G(!0)):X&&oe==="b"?(R.preventDefault(),O(fe=>!fe)):X&&R.key===","?(R.preventDefault(),Jt()):R.altKey&&R.code==="KeyW"&&Ss&&(R.preventDefault(),T({type:"close",tab:Ss}))};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[Ss,Jt]);const gu=C.useMemo(()=>[{id:"tutorial",category:"Help",label:"Open Interactive Studio Tutorial & Guide",run:()=>lr(!0)},{id:"new-project",category:"Project",label:"Create New Research Project",run:()=>{ti({name:`Project ${(At.projects.length||0)+1}`,template:"ligand-docking"})}},{id:"split-ref",category:"Project",label:"Split Reference Chains & HETATM Ligands",run:()=>{gl("reference")}},{id:"open-file",category:"File",label:"Open file…",shortcut:"⌘O",run:()=>c.current?.click()},{id:"db",category:"File",label:"Search public databases",shortcut:"⌘⇧F",run:()=>G(!0)},{id:"example",category:"File",label:"Load example comparison (carbonic anhydrase II)",run:()=>void cr()},{id:"tab-viewer",category:"Open tab",label:"3D Viewer",run:()=>je("viewer")},{id:"tab-results",category:"Open tab",label:"Results",run:()=>je("results")},{id:"tab-seq",category:"Open tab",label:"Sequence deviation",run:()=>je("sequence")},{id:"tab-rama",category:"Open tab",label:"Ramachandran plot",run:()=>je("ramachandran")},{id:"tab-pep",category:"Open tab",label:"Peptide engineering",run:()=>je("peptide")},{id:"tab-crispr",category:"Open tab",label:"Gene & CRISPR",run:()=>je("crispr")},{id:"tab-chem",category:"Open tab",label:"Ligands & 2D Sketcher",run:()=>je("chemistry")},{id:"tab-workflow",category:"Open tab",label:"Workflow Canvas",run:()=>je("workflow")},{id:"tab-compute",category:"Open tab",label:"GPU & Compute Nodes",run:()=>je("compute")},{id:"tab-plugins",category:"Open tab",label:"Plugins & Add-ons",run:()=>je("plugins")},{id:"toggle-molstar",category:"3D view",label:`Switch 3D Engine (${le==="molstar"?"Fast WebGL2":"Mol* Pro"})`,run:()=>D(M=>M==="molstar"?"webgl2":"molstar")},{id:"tab-ai",category:"Open tab",label:"AI Assistant",run:()=>je("assistant")},{id:"tab-mcp",category:"Open tab",label:"MCP Server",run:()=>je("mcp")},{id:"tab-lib",category:"Open tab",label:"Library",run:()=>je("library")},{id:"tab-home",category:"Open tab",label:"Start page",run:()=>je("home")},{id:"cam-site",category:"3D view",label:"Focus active site",run:()=>i.current?.applyPreset("active-site")},{id:"cam-reset",category:"3D view",label:"Reset camera",run:()=>i.current?.applyPreset("overview")},{id:"color-plddt",category:"3D view",label:"Color by pLDDT",run:()=>St("plddt")},{id:"color-b",category:"3D view",label:"Color by B-factor",run:()=>St("bfactor")},{id:"color-dev",category:"3D view",label:"Color by deviation Δd",run:()=>St("deviation")},{id:"color-id",category:"3D view",label:"Color by structure",run:()=>St("identity")},{id:"export-html",category:"Export",label:"HTML report",run:da},{id:"export-json",category:"Export",label:"JSON manifest",run:is},{id:"export-bundle",category:"Export",label:"Project bundle",run:()=>void si()},{id:"settings",category:"Settings",label:"Open settings",shortcut:"⌘,",run:()=>Jt()},{id:"settings-ai",category:"Settings",label:"AI & API keys",run:()=>Jt("ai")},{id:"settings-usage",category:"Settings",label:"Usage",run:()=>Jt("usage")},{id:"settings-account",category:"Settings",label:he?"Account":"Sign in",run:()=>he?Jt("account"):Bn("signin")},{id:"ui-bigger",category:"View",label:"Increase interface size",shortcut:"⌘+",run:()=>Cx(1)},{id:"ui-smaller",category:"View",label:"Decrease interface size",shortcut:"⌘−",run:()=>Cx(-1)},{id:"sidebar",category:"View",label:"Toggle sidebar",shortcut:"⌘B",run:()=>O(M=>!M)},{id:"layout-reset",category:"View",label:"Reset tab layout",run:()=>T({type:"reset"})}],[cr,je,da,is,si,Jt,he,Bn]),oo=C.useMemo(()=>new Set(E.groups.flatMap(M=>M.tabs)),[E]),ma=C.useMemo(()=>{const M=new Set;return Je&&M.add(Je.sha256),qn&&M.add(qn.sha256),M},[Je,qn]),bn="h-4 w-4",wl={home:{title:"Start",icon:o.jsx(FA,{className:bn})},viewer:{title:"3D Viewer",icon:o.jsx(_s,{className:bn})},results:{title:"Results",icon:o.jsx(qi,{className:bn})},sequence:{title:"Sequence",icon:o.jsx(Vo,{className:bn})},ramachandran:{title:"Ramachandran",icon:o.jsx(Qo,{className:bn})},peptide:{title:"Peptide",icon:o.jsx(ar,{className:bn})},crispr:{title:"CRISPR",icon:o.jsx(Fs,{className:bn})},chemistry:{title:"Ligands",icon:o.jsx(ia,{className:bn})},workflow:{title:"Workflows",icon:o.jsx(Dp,{className:bn})},compute:{title:"GPU Nodes",icon:o.jsx(al,{className:bn}),badge:Re.activeNode?.online?o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400"}):void 0},plugins:{title:"Plugins",icon:o.jsx(Lp,{className:bn})},assistant:{title:"Assistant",icon:o.jsx(qr,{className:bn}),badge:la?o.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-sky-400"}):void 0},mcp:{title:"MCP Server",icon:o.jsx(rl,{className:bn})},library:{title:"Library",icon:o.jsx(sh,{className:bn})}},ai=r.guidedMode,Oa=M=>o.jsx("div",{className:"h-full min-h-0",children:M}),Sl=M=>{switch(M){case"home":return o.jsx(Jq,{activeStarterId:me,runHistory:ou,projects:At.projects,activeProject:At.activeProject,onCreateProject:ti,onSwitchProject:R=>{vx(R),e("Switched active project","info")},onDeleteProject:R=>{kD(R),e("Deleted project","info")},onOpenTutorial:()=>lr(!0),onImportFile:()=>c.current?.click(),onSearchDatabases:()=>G(!0),onOpenLibrary:()=>je("library"),onOpenAssistant:()=>je("assistant"),onOpenChemistry:()=>je("chemistry"),onOpenPeptide:()=>je("peptide"),onOpenCrispr:()=>je("crispr"),onOpenWorkflows:()=>je("workflow"),onOpenComputeNodes:()=>je("compute"),onOpenPlugins:()=>je("plugins"),onLaunchStarter:R=>void mu(R),onOpenLibraryItem:R=>void za(R,"auto")});case"viewer":return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"flex h-8 shrink-0 items-center justify-between border-b border-white/[0.06] bg-[#0a0d13] px-2.5 text-[0.75rem]",children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"mr-1 text-slate-500",children:"3D Engine:"}),o.jsx("button",{type:"button",onClick:()=>D("webgl2"),className:`rounded-md px-2 py-0.5 font-medium transition ${le==="webgl2"?"bg-sky-500/20 text-sky-200":"text-slate-400 hover:text-slate-200"}`,children:"Fast WebGL2"}),o.jsx("button",{type:"button",onClick:()=>D("molstar"),className:`rounded-md px-2 py-0.5 font-medium transition ${le==="molstar"?"bg-sky-500/20 text-sky-200":"text-slate-400 hover:text-slate-200"}`,children:"Mol* Pro"})]}),ae&&o.jsxs("div",{className:"flex items-center gap-2 font-mono text-[0.6875rem] text-emerald-300",children:[o.jsxs("span",{children:["Overlay: ",ae.label]}),o.jsx("button",{type:"button",onClick:()=>pe(null),className:"text-slate-400 hover:text-slate-200",children:"Clear"})]})]}),o.jsxs("div",{className:"relative min-h-0 flex-1",children:[le==="molstar"?o.jsx(C.Suspense,{fallback:o.jsx("div",{className:"flex h-full items-center justify-center bg-[#070b12] text-xs text-slate-400",children:"Loading Mol* Pro 3D engine…"}),children:o.jsx(KL,{ref:i,refLabel:Ke,refContent:ue,mobLabel:Fe,mobContent:We,comparison:tt,layout:Ce,style:be,colorMode:Ot,focusedSeqId:Ln,focusCameraRequest:Zi,highlightSourceLabel:ao,highlightCount:ct.size,onClearHighlights:()=>hl(null),extraOverlay:ae,onPickResidue:Yt,onSendPocketToDocking:()=>{Ne({tool:"vina",nonce:Date.now()}),je("compute")}})}):o.jsx(hL,{ref:i,comparison:tt,refInspect:Je,mobInspect:qn,refChainId:ve,mobChainId:_t,layout:Ce,onChangeLayout:Ue,style:be,onChangeStyle:bt,colorMode:Ot,onChangeColorMode:St,focusedSeqId:Ln,focusCameraRequest:Zi,highlightedSeqIds:ct,highlightSourceLabel:ao,onClearHighlights:()=>hl(null),paePair:zh,onPickResidue:Yt,onRendererModeDetected:k,simpleMode:!1}),!ue&&!We&&!p&&o.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center p-6",children:o.jsxs("div",{className:"pointer-events-auto max-w-sm rounded-2xl border border-white/10 bg-[#121722]/95 p-6 text-center shadow-2xl backdrop-blur",children:[o.jsx(_s,{className:"mx-auto h-8 w-8 text-slate-500"}),o.jsx("div",{className:"mt-3 text-base font-medium text-slate-100",children:"No structure loaded"}),o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"Open a file, pick one from your library, or search a public database."}),o.jsxs("div",{className:"mt-4 flex flex-wrap justify-center gap-2",children:[o.jsx("button",{type:"button",onClick:()=>c.current?.click(),className:"rounded-lg bg-sky-500 px-3.5 py-2 text-sm font-semibold text-slate-950 hover:bg-sky-400",children:"Open file"}),o.jsx("button",{type:"button",onClick:()=>G(!0),className:"rounded-lg border border-white/10 px-3.5 py-2 text-sm text-slate-200 hover:bg-white/[0.06]",children:"Search databases"})]}),o.jsx("button",{type:"button",onClick:()=>void cr(),className:"mt-3 text-xs text-slate-500 hover:text-sky-300",children:"or load the example comparison"})]})})]})]});case"results":return o.jsx(vL,{comparison:tt,paeJson:Nn,busy:!!p,guided:ai,selectedPaePair:zh,onSelectPaePair:(R,X)=>{eo([R,X]),Yt(R)},includePng:ni,onToggleIncludePng:R=>n(X=>({...X,viewer:{...X.viewer,embedPngInReports:R}})),onExportHtml:da,onExportJson:is,onExportBundle:()=>void si(),bridge:Ks});case"sequence":return Oa(o.jsx(SL,{comparison:tt,refInspect:Je,mobInspect:qn,refChainId:ve,mobChainId:_t,focusedSeqId:Ln,onFocusResidue:Yt,bridge:Ks}));case"ramachandran":return Oa(o.jsx(_L,{refLabel:Ke,refChain:ve,mobLabel:Fe,mobChain:_t,activeSource:so,onChangeSource:au,result:Qr,error:ru,focusedSeqId:Ln,onFocusResidue:Yt,simpleMode:ai,bridge:Ks}));case"peptide":return Oa(o.jsx(mL,{state:st,dispatch:Lt,result:Ct,error:i0,onFocusResidue:Yt,simpleMode:ai,bridge:Ks}));case"crispr":return Oa(o.jsx(Yq,{state:Nt,dispatch:An,result:as,error:ml,onFocusResidue:Yt,simpleMode:ai,bridge:Ks}));case"chemistry":return Oa(o.jsx(Bq,{state:Mt,dispatch:Un,result:Vs,comparison:tt,error:no,onFocusResidue:Yt,onStageForCompute:(R,X)=>{Un({type:"set_custom_smiles",smiles:X.smiles,name:X.name}),Ne({tool:R,nonce:Date.now()}),je("compute")},libraryCompounds:J.filter(R=>R.kind==="compound").map(R=>({id:R.id,name:R.name,smiles:R.content})),simpleMode:ai,bridge:Ks}));case"workflow":return o.jsx($L,{onExecuteNode:ur,activeComputeLabel:Re.activeNode?.online?Re.activeNode.label:null,onOpenComputeNodes:()=>je("compute"),bridge:Ks});case"compute":return o.jsx(Fq,{activeSmiles:Mt.smiles,activeSmilesName:Mt.name,activeRefPdbOrCif:ue,activeRefLabel:Ke,pocketBox:jn,stagedComputeTarget:Ae,onImportArtifactToViewer:R=>{pe({id:`art-${Date.now()}`,...R}),D("molstar"),je("viewer")},bridge:Ks});case"plugins":return o.jsx(xL,{onOpenComputeNodes:()=>je("compute"),onOpenMcpServer:()=>je("mcp"),onOpenToolTab:R=>je(R)});case"assistant":return o.jsx(Nq,{messages:cu,busy:la,config:Ut,liveSteps:Ih,pendingPermission:pl,onResolvePermission:Uh,onSelectProvider:(R,X)=>vl({provider:R,...R==="synlexa"&&Xc(Ut).hasByok?{routingPreference:"manual"}:{},...X?{[R]:{model:X}}:{}}),onToggleWebSearch:R=>vl({enableWebSearch:R}),onSend:R=>void pu(R),onClear:()=>uu([]),onOpenKeySettings:()=>Jt("ai"),onOpenMcpServer:()=>je("mcp")});case"mcp":return o.jsx(tL,{runtime:_l,onOpenAiAssistant:()=>je("assistant"),onOpenVaultSettings:()=>Jt("ai")});case"library":return o.jsx(CA,{onOpenItem:(R,X)=>void za(R,X),loadedShas:ma})}},lo=Xc(Ut),ln=Ut[lo.provider]??{apiKey:"",model:""},Pa=es[lo.provider].models.find(M=>M.id===ln.model)?.label??ln.model,kl=ln.apiKey?`${lo.isByok?"BYOK":"Cloud"}: ${Pa}`:lo.provider==="synlexa"?"AI: sign in or add BYOK":"AI: no key",co=At.activeProject?.name??(me?sq(me)?.title:null)??(Ke||Fe?[Ke,Fe].filter(Boolean).join(" vs "):"Untitled workspace"),c0=M=>{M==="settings"?Jt("ai"):je(M)},bu={explorer:"Workspace",library:"Library",tools:"Tools",history:"History"};return o.jsxs("div",{className:"flex h-dvh w-screen flex-col overflow-hidden bg-[#0b0e14] text-slate-100",children:[o.jsx("input",{ref:c,type:"file",multiple:!0,accept:".cif,.mmcif,.pdb,.ent,.json,.fasta,.fa,.faa,.smi",className:"hidden",onChange:M=>{M.target.files?.length&&fu(M.target.files,"auto"),M.target.value=""}}),o.jsx(DL,{projectTitle:co,session:he,onOpenPalette:()=>H(!0),onOpenFile:()=>c.current?.click(),onSearchDatabases:()=>G(!0),onOpenMcp:()=>je("mcp"),onOpenTutorial:()=>lr(!0),onExportHtml:da,onExportJson:is,onExportBundle:()=>void si(),canExport:!!tt,onOpenAccount:()=>Jt("account")}),o.jsxs("div",{className:"flex min-h-0 flex-1",children:[o.jsx(qL,{view:j,sidebarOpen:z,onSelect:M=>{z&&M===j?O(!1):(q(M),O(!0))},onOpenSettings:()=>Jt(),onOpenAssistant:()=>je("assistant"),onOpenMcp:()=>je("mcp"),libraryCount:J.length}),z&&o.jsxs(LL,{title:bu[j],width:j==="library"?304:276,actions:j==="library"?o.jsx(sl,{label:"Open full library manager",onClick:()=>je("library"),children:o.jsx(Oy,{className:"h-3.5 w-3.5"})}):void 0,children:[j==="explorer"&&o.jsx(UL,{refLabel:Ke,mobLabel:Fe,refInspect:Je,mobInspect:qn,refChain:ve,mobChain:_t,hasRef:!!ue,hasMob:!!We,paePresent:!!Nn,chainError:_,onChangeRefChain:M=>{Qe(M),Pt({...fn(),rChain:M})},onChangeMobChain:M=>{ja(M);const R=qn?.chains.find(X=>X.chainId===M)?.sequence1Letter;R&&Lt({type:"set_sequence",sequence:R}),Pt({...fn(),mChain:M})},onUploadFiles:(M,R)=>void fu(M,R),onSaveToLibrary:l0,onSearchDatabases:()=>G(!0),onLoadExample:()=>void cr(),projects:At.projects,activeProject:At.activeProject,onCreateProject:ti,onSwitchProject:M=>vx(M),onSplitStructure:M=>gl(M),onLoadProjectStructure:du,onOpenProjectMolecule:M=>{Un({type:"set_custom_smiles",smiles:M.smiles,name:M.name}),je("chemistry")},onDockMolecule:o0,onRemoveProjectAsset:(M,R)=>CD(M,R),onOpenChemistry:()=>je("chemistry"),onOpenPeptide:()=>je("peptide"),onOpenCrispr:()=>je("crispr")}),j==="library"&&o.jsx(CA,{compact:!0,onOpenItem:(M,R)=>void za(M,R),loadedShas:ma}),j==="tools"&&o.jsx(HL,{openTabs:oo,onOpen:(M,R)=>je(M,R)}),j==="history"&&o.jsx(FL,{runs:ou,onClear:()=>void uE().then(()=>rs([]))})]}),o.jsx("main",{className:"flex min-w-0 flex-1 flex-col",children:o.jsx(IL,{layout:E,dispatch:T,meta:wl,renderTab:Sl,keepAlive:YL})})]}),o.jsx(VL,{busyLabel:p,wasmReady:d,rendererMode:S,rmsd:tt?.metrics.rmsdAngstrom??null,focusedSeqId:Ln,computeNodeLabel:Re.activeNode?.label??null,computeOnline:!!Re.activeNode?.online,onOpenComputeNodes:()=>je("compute"),aiLabel:kl,aiReady:!!ln.apiKey,onOpenAiSettings:()=>Jt("ai")}),o.jsx(Hq,{open:$,onClose:()=>H(!1),commands:gu}),o.jsx(Xq,{open:Z,onClose:()=>G(!1),onImportStructure:Ra,onImportCompound:xl}),o.jsx(kL,{open:K,onClose:()=>we(!1),section:V,onSectionChange:P,aiConfig:Ut,onUpdateAiConfig:vl,onPermissionsChange:Zr,session:he,onSessionChange:io,onSignIn:Bn,onCancelSignIn:hu,signInPending:Se,onResetLayout:()=>T({type:"reset"}),onClearedHistory:()=>rs([])}),o.jsx(PL,{open:qh,onClose:()=>lr(!1),onExecuteStepAction:c0})]})}Jv(Xv().uiScale);const PA=JM.createRoot(document.getElementById("root"));if(YI(window.location.href)){window.history.replaceState({},"",window.location.pathname||"/");try{window.close()}catch{}PA.render(o.jsx("div",{className:"flex h-full items-center justify-center bg-[#0d1117] p-6 text-center",children:o.jsxs("div",{children:[o.jsx("div",{className:"text-base font-medium text-slate-100",children:"You're signed in"}),o.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"Closing sign-in window and returning to Synlexa Studio…"}),o.jsx("button",{type:"button",onClick:()=>window.close(),className:"mt-4 rounded-md border border-slate-700 bg-slate-800 px-3 py-1.5 text-xs font-medium text-slate-200 hover:bg-slate-700",children:"Close window"})]})})),window.setTimeout(()=>{try{window.close()}catch{}},80),window.setTimeout(()=>{try{window.close()}catch{}},350)}else PA.render(o.jsx(C.StrictMode,{children:o.jsx(pq,{children:o.jsx(WL,{})})}));export{De as A,_s as B,OR as C,eU as D,sC as M,XL as R,Ur as a,bR as b,oA as c,JM as d,GM as g,o as j,C as r};