@fungi.computer/spore 0.19.1 → 0.19.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/THIRD_PARTY_NOTICES
CHANGED
|
@@ -589,7 +589,7 @@ SOFTWARE.
|
|
|
589
589
|
|
|
590
590
|
---
|
|
591
591
|
|
|
592
|
-
@fungi.computer/agar 0.23.
|
|
592
|
+
@fungi.computer/agar 0.23.1, @fungi.computer/almanac 0.2.1, @fungi.computer/approvals 0.2.4, @fungi.computer/bird-dog 0.3.7, @fungi.computer/cairn 0.1.0, @fungi.computer/carrier 0.2.5, @fungi.computer/cli-version 0.0.2, @fungi.computer/cordyceps 0.4.3, @fungi.computer/corral 0.1.50, @fungi.computer/gills 0.4.0, @fungi.computer/graft 0.2.44, @fungi.computer/knapsack 0.4.21, @fungi.computer/lantern 0.4.2, @fungi.computer/maosaico 0.1.2, @fungi.computer/mule 0.3.0, @fungi.computer/mycelium 0.4.7, @fungi.computer/nacre 0.8.4, @fungi.computer/parakeet 0.16.0, @fungi.computer/puffball 0.12.0, @fungi.computer/seam 0.2.6, @fungi.computer/shiitake 0.21.9, @fungi.computer/shiitake-extensions 0.11.20, @fungi.computer/spore 0.19.2, @fungi.computer/sprite 0.2.2, @fungi.computer/stipe 0.1.1, @fungi.computer/truffle 0.18.2, @fungi.computer/veil 0.11.1, @fungi.computer/watchdog 0.1.4, @fungi.computer/whistle 0.3.0, @fungi.computer/zookeeper 0.0.51
|
|
593
593
|
|
|
594
594
|
MIT License
|
|
595
595
|
|
|
@@ -703,7 +703,7 @@ License: https://github.com/APIDevTools/json-schema-ref-parser/blob/v16.0.3/LICE
|
|
|
703
703
|
|
|
704
704
|
---
|
|
705
705
|
|
|
706
|
-
@fungi.computer/knapsack 0.4.
|
|
706
|
+
@fungi.computer/knapsack 0.4.21, @openai/codex 0.162.1
|
|
707
707
|
|
|
708
708
|
Apache License
|
|
709
709
|
Version 2.0, January 2004
|
package/dist/cli.js
CHANGED
|
@@ -1281,7 +1281,7 @@ Use @@ alone or followed by an existing context line; unified-diff @@ line numbe
|
|
|
1281
1281
|
Request Headers: {${_}}`}if(r&&m){let _=[...m.entries()].map(([y,x])=>`${y}: ${x}`).join(", ");g+=`
|
|
1282
1282
|
Response Headers: {${_}}`}if(h||l>=400)console.error(g);else console.log(g)});return(a)=>async(c,u)=>{let l=performance.now(),d=u?.method||"GET",p=typeof c==="string"?c:c.toString(),f=n?new Headers(u?.headers):void 0;try{let m=await a(c,u),h=performance.now()-l;if(m.status>=i)s({method:d,url:p,status:m.status,statusText:m.statusText,duration:h,requestHeaders:f,responseHeaders:r?m.headers:void 0});return m}catch(m){throw s({method:d,url:p,status:0,statusText:"Network Error",duration:performance.now()-l,requestHeaders:f,error:m}),m}}},gci=(...e)=>(t)=>{let n=t;for(let r of e)n=r(n);return n},_ci=(e)=>(t)=>(n,r)=>e(t,n,r),hEn,yci=class{_eventSource;_endpoint;_abortController;_url;_resourceMetadataUrl;_scope;_eventSourceInit;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_protocolVersion;onclose;onerror;onmessage;constructor(e,t){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,GSn(t?.authProvider))this._oauthProvider=t.authProvider,this._authProvider=VSn(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation});else this._authProvider=t?.authProvider;this._fetch=t?.fetch,this._fetchWithInit=b4e(t?.fetch,t?.requestInit)}_last401Response;async _commonHeaders(){let e={},t;try{t=await this._authProvider?.token()}catch(r){throw sy(r)}if(t)e.Authorization=`Bearer ${t}`;if(this._protocolVersion)e["mcp-protocol-version"]=this._protocolVersion;let n=ide(this._requestInit?.headers);return new Headers({...e,...n})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,n)=>{this._eventSource=new OJ(this._url.href,{...this._eventSourceInit,fetch:async(r,i)=>{let o=await this._commonHeaders();o.set("Accept","text/event-stream");let s=await e(r,{...i,headers:o});if(s.status===401){if(this._last401Response=s,s.headers.has("www-authenticate")){let{resourceMetadataUrl:a,scope:c}=$3(s);this._resourceMetadataUrl=a,this._scope=c}}return s}}),this._abortController=new AbortController,this._eventSource.onerror=(r)=>{if(r.code===401&&this._authProvider){if(this._authProvider.onUnauthorized&&this._last401Response){let s=this._last401Response;this._last401Response=void 0,this._eventSource?.close(),this._authProvider.onUnauthorized({response:s,serverUrl:this._url,fetchFn:this._fetchWithInit}).then(()=>this._startOrAuth().then(t,n),(a)=>{sy(a),this.onerror?.(a),n(a)});return}let o=sy(new Xd);n(o),this.onerror?.(o);return}let i=new hEn(r.code,r.message,r);n(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(r)=>{let i=r;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(o){n(o),this.onerror?.(o),this.close();return}t()}),this._eventSource.onmessage=(r)=>{let i=r,o;try{o=qT.parse(JSON.parse(i.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(o)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e,t){if(!this._oauthProvider)throw new Xd("finishAuth requires an OAuthClientProvider");let{authorizationCode:n,iss:r}=await JSn(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await z3(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:r,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new Xd("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){return this._send(e,!1)}async _send(e,t){if(!this._endpoint)throw new uo(Vi.NotConnected,"Not connected");try{let n=await this._commonHeaders();n.set("content-type","application/json");let r={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._endpoint,r);if(!i.ok){if(i.status===401&&this._authProvider){if(i.headers.has("www-authenticate")){let{resourceMetadataUrl:s,scope:a}=$3(i);this._resourceMetadataUrl=s,this._scope=a}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:i,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(s){throw sy(s)}return await i.text?.().catch(()=>{}),this._send(e,!0)}if(await i.text?.().catch(()=>{}),t)throw sy(new LE(Vi.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:i.statusText}));throw sy(new Xd)}let o=await i.text?.().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${i.status}): ${o}`)}await i.text?.().catch(()=>{})}catch(n){throw this.onerror?.(n),n}}setProtocolVersion(e){this._protocolVersion=e}},xci=1,vci,bci,Tde=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,GSn(t?.authProvider))this._oauthProvider=t.authProvider,this._authProvider=VSn(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation});else this._authProvider=t?.authProvider;this._fetch=t?.fetch,this._fetchWithInit=b4e(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??vci,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??xci)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(n){throw sy(n)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Tpt({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Tpt({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new LE(Vi.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});if(e.resourceMetadataUrl)this._resourceMetadataUrl=e.resourceMetadataUrl;let n=await this._oauthProvider.tokens(),r=K4e(this._scope,n?.scope,e.scope);this._scope=r;let i=KSn(r,n?.scope);return z3(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:r,forceReauthorization:i,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}async _commonHeaders(){let e={},t;try{t=await this._authProvider?.token()}catch(r){throw sy(r)}if(t)e.Authorization=`Bearer ${t}`;if(this._sessionId)e["mcp-session-id"]=this._sessionId;if(this._protocolVersion)e["mcp-protocol-version"]=this._protocolVersion;let n=ide(this._requestInit?.headers);return new Headers({...e,...n})}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!_N(t))return;let n=t.params?._meta?.[DR];if(typeof n!=="string")return;e.set("mcp-protocol-version",n),e.set("mcp-method",t.method);let r=t.params,i=t.method==="resources/read"?typeof r?.uri==="string"?r.uri:void 0:typeof r?.name==="string"?r.name:void 0;if(i!==void 0)e.set("mcp-name",hdt(i))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!_N(e))return!1;let t=e.params?._meta?.[DR];return typeof t==="string"&&N3(t)}async _startOrAuthSse(e,t=!1,n=0){let{resumptionToken:r,requestSignal:i}=e,o=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;try{let s=await this._commonHeaders(),a=[...s.get("accept")?.split(",").map((d)=>d.trim().toLowerCase())??[],"text/event-stream"];if(s.set("accept",[...new Set(a)].join(", ")),r)s.set("last-event-id",r);let c=this._abortController?.signal,u=i!==void 0&&c!==void 0?qSn(c,i):i??c,l=await(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:s,signal:u});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=$3(l);this._resourceMetadataUrl=d,this._scope=K4e(this._scope,p)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(d){throw sy(d)}return await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,n)}if(await l.text?.().catch(()=>{}),t)throw sy(new LE(Vi.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:l.statusText}));throw sy(new Xd)}if(l.status===403){let{resourceMetadataUrl:d,scope:p,error:f,errorDescription:m}=$3(l);if(f==="insufficient_scope"){let h=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:p,resourceMetadataUrl:d,errorDescription:m,statusText:l.statusText,text:h},n)!=="AUTHORIZED")throw sy(new Xd);return this._startOrAuthSse(e,t,n+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}throw new LE(Vi.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${l.statusText}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(s){if(!o())this.onerror?.(s);throw s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(n,e),r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`)),e.onRequestStreamEnd?.();return}let r=this._getNextReconnectionDelay(t),i=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this._startOrAuthSse(e).catch((o)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`));try{this._scheduleReconnection(e,t+1)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}})};if(this._reconnectionScheduler){let o=this._reconnectionScheduler(i,r,t);this._cancelReconnection=typeof o==="function"?o:void 0}else{let o=setTimeout(i,r);this._cancelReconnection=()=>clearTimeout(o)}}_handleSseStream(e,t,n){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:r,replayMessageId:i,requestSignal:o,onRequestStreamEnd:s}=t,a=()=>this._abortController?.signal.aborted===!0||o?.aborted===!0,c,u=!1,l=!1;(async()=>{try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new Hdt({onRetry:(f)=>{this._serverRetryMs=f}})).getReader();while(!0){let{value:f,done:m}=await p.read();if(m)break;if(f.id)c=f.id,u=!0,r?.(f.id);if(!f.data)continue;if(!f.event||f.event==="message")try{let h=qT.parse(JSON.parse(f.data));if(wU(h)||EU(h)){if(l=!0,i!==void 0)h.id=i}this.onmessage?.(h)}catch(h){this.onerror?.(h)}}if((n||u)&&!l&&this._abortController&&!a())this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:o,onRequestStreamEnd:s},0);else if(!a())s?.()}catch(p){if(a())return;if(this.onerror?.(Error(`SSE stream disconnected: ${p}`)),(n||u)&&!l&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:o,onRequestStreamEnd:s},0)}catch(f){this.onerror?.(Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`)),s?.()}else s?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new Xd("finishAuth requires an OAuthClientProvider");let{authorizationCode:n,iss:r}=await JSn(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await z3(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:r,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new Xd("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,n,r=0){try{let{resumptionToken:i,onresumptiontoken:o}=t||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:_N(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((g)=>this.onerror?.(g));return}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let a=Array.isArray(e)?e.some((g)=>x4e(g)):x4e(e);if(a)s.delete("mcp-session-id");if(t?.headers!==void 0)for(let[g,_]of Object.entries(t.headers)){if(bci.has(g.toLowerCase()))continue;s.set(g,_)}s.set("content-type","application/json");let c=[...s.get("accept")?.split(",").map((g)=>g.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(c)].join(", "));let u=this._abortController?.signal,l=t?.requestSignal!==void 0&&u!==void 0?qSn(u,t.requestSignal):t?.requestSignal??u,d={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:l},p=await(this._fetch??fetch)(this._url,d);if(a&&p.ok)this._sessionId=p.headers.get("mcp-session-id")||void 0;if(!p.ok){if(p.status===401&&this._authProvider){if(p.headers.has("www-authenticate")){let{resourceMetadataUrl:_,scope:y}=$3(p);this._resourceMetadataUrl=_,this._scope=K4e(this._scope,y)}if(this._authProvider.onUnauthorized&&!n){try{await this._authProvider.onUnauthorized({response:p,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(_){throw sy(_)}return await p.text?.().catch(()=>{}),this._send(e,t,!0,r)}if(await p.text?.().catch(()=>{}),n)throw sy(new LE(Vi.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:p.statusText}));throw sy(new Xd)}let g=await p.text?.().catch(()=>null);if(p.status===403){let{resourceMetadataUrl:_,scope:y,error:x,errorDescription:w}=$3(p);if(x==="insufficient_scope"){if(await this._stepUpAuthorize({scope:y,resourceMetadataUrl:_,errorDescription:w,statusText:p.statusText,text:g},r)!=="AUTHORIZED")throw sy(new Xd);return this._send(e,t,n,r+1)}}if(p.status===400&&typeof g==="string"&&this._isModernEnvelopedRequest(e))try{let _=qT.parse(JSON.parse(g)),y=(Array.isArray(e)?e:[e]).filter((x)=>_N(x));if(EU(_)&&y.some((x)=>x.id===_.id)){this.onmessage?.(_);return}}catch{}throw new LE(Vi.ClientHttpNotImplemented,`Error POSTing to endpoint: ${g}`,{status:p.status,statusText:p.statusText,text:g})}if(p.status===202){if(await p.text?.().catch(()=>{}),fdt(e))this._startOrAuthSse({resumptionToken:void 0}).catch((g)=>this.onerror?.(g));return}let f=(Array.isArray(e)?e:[e]).some((g)=>("method"in g)&&("id"in g)&&g.id!==void 0),m=p.headers.get("content-type"),h=bdt(m);if(f)if(h==="text/event-stream")this._handleSseStream(p.body,{onresumptiontoken:o,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(h==="application/json"){let g=await p.json(),_=Array.isArray(g)?g.map((y)=>qT.parse(y)):[qT.parse(g)];for(let y of _)this.onmessage?.(y)}else throw await p.text?.().catch(()=>{}),new uo(Vi.ClientHttpUnexpectedContent,`Unexpected content type: ${m}`,{contentType:m});else await p.text?.().catch(()=>{})}catch(i){if(t?.requestSignal?.aborted!==!0)this.onerror?.(i);throw i}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.text?.().catch(()=>{}),!n.ok&&n.status!==405)throw new LE(Vi.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${n.statusText}`,{status:n.status,statusText:n.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},wci;var Ade=C(()=>{hwn();zwn();Uwn();Wwn();Hwn();$J=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Kb(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Kb(this,e)}constructor(e){super(e);this.name=new.target.name,SU(this,new.target)}},Q4e=class extends $J{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,n){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(n)}`);this.kind=e,this.expected=t,this.received=n}},WSn=class extends $J{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`);this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Ipt=class extends $J{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=e}},V4e=class extends $J{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`);this.recordedIssuer=e,this.currentIssuer=t}},Tpt=class extends $J{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`);this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};Xd=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Kb(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Kb(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",SU(this,new.target)}};G4e=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]);lEn=Symbol.for("mcp.authSeamEscape");Vai=new Set([-32001,-32020,-32021]);Cpt=new WeakMap;BSn={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},kde=class extends xdt{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new uo(Vi.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t);if(this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new A4e,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=twn(t?.inputRequired),this._cache=new qai(t?.responseCacheStore??new cEn,t?.responseCacheStore!==void 0,(n)=>this._reportStoreError(n),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??dci,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&N3(this._negotiatedProtocolVersion)&&_N(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new uo(Vi.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}));return swn({getRequestHandler:(n)=>this._getRequestHandler(n),buildContext:(n)=>this.buildContext(n,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t)}_setupListChangedHandlers(e){if(e.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools);if(e.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts);if(e.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=vdt(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){if(e==="elicitation/create")return async(n,r)=>{let i=P3(this._negotiatedProtocolVersion),o=i.validateRequest("elicitation/create",n);if(!o.ok&&o.reason==="not-in-era")o=i.validateInputRequest("elicitation/create",n);if(!o.ok)throw new Ju(o.reason==="not-in-era"?rs.InternalError:rs.InvalidParams,o.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${o.message}`);let{params:s}=o.value;s.mode=s.mode??"form";let{supportsFormMode:a,supportsUrlMode:c}=fEn(this._capabilities.elicitation);if(s.mode==="form"&&!a)throw new Ju(rs.InvalidParams,"Client does not support form-mode elicitation requests");if(s.mode==="url"&&!c)throw new Ju(rs.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(n,r),l=i.validateResult("elicitation/create",u);if(!l.ok&&l.reason==="not-in-era")l=i.validateInputResponse("elicitation/create",u);if(!l.ok)throw new Ju(l.reason==="not-in-era"?rs.InternalError:rs.InvalidParams,l.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${l.message}`);let d=l.value,p=s.mode==="form"?s.requestedSchema:void 0;if(s.mode==="form"&&d.action==="accept"&&d.content&&p&&this._capabilities.elicitation?.form?.applyDefaults)try{J4e(p,d.content)}catch{}return d};if(e==="sampling/createMessage")return async(n,r)=>{let i=P3(this._negotiatedProtocolVersion),o=i.validateRequest("sampling/createMessage",n);if(!o.ok&&o.reason==="not-in-era")o=i.validateInputRequest("sampling/createMessage",n);if(!o.ok)throw new Ju(o.reason==="not-in-era"?rs.InternalError:rs.InvalidParams,o.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${o.message}`);let{params:s}=o.value,a=await t(n,r),c=Boolean(s.tools||s.toolChoice),u=i.samplingResultVariant(c,a);if(!u.ok&&u.reason==="not-in-era")u=i.validateInputResponse("sampling/createMessage",a);if(!u.ok)throw new Ju(u.reason==="not-in-era"?rs.InternalError:rs.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value};return t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new uo(Vi.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,lci(t.prior),t);let n=rci(this._versionNegotiation,this._supportedProtocolVersionsOption);if(n.kind!=="legacy")return this._connectNegotiated(e,n,t);return this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let n=this._negotiatedProtocolVersion;if(n!==void 0)e.setProtocolVersion?.(n);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let n=ndt(this._supportedProtocolVersions);try{let r=n[0];if(r===void 0)throw new uo(Vi.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let i=await this.request({method:"initialize",params:{protocolVersion:r,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(i===void 0)throw Error(`Server sent invalid initialize result: ${i}`);if(!n.includes(i.protocolVersion))throw Error(`Server's protocol version is not supported: ${i.protocolVersion}`);if(this._serverCapabilities=i.capabilities,this._serverVersion=i.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion)e.setProtocolVersion(i.protocolVersion);if(this._instructions=i.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=i.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(r){throw this.close(),r}}async _connectNegotiated(e,t,n){if(e.sessionId!==void 0){await super.connect(e);let i=this._negotiatedProtocolVersion;if(i!==void 0&&e.setProtocolVersion)e.setProtocolVersion(i);return}this._resetConnectionState();let r;try{let i=$Sn(e),o={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:FSn(),defaultTimeoutMs:n?.timeout??ade},s=i==="stdio"?aci(e):void 0;r=s===void 0?await pEn(t,{...o,transport:e,transportKind:i}):await cci(t,e,s,o)}catch(i){throw await e.close().catch(()=>{}),zSn(e),i}if(zSn(e),await super.connect(e),r.era==="legacy"){await this._legacyHandshake(e,n);return}if(this._serverCapabilities=r.discover.capabilities,this._serverVersion=jSn(r.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.discover.instructions,this._discoverResult=r.discover,this._negotiatedProtocolVersion=r.version,e.setProtocolVersion)e.setProtocolVersion(r.version);if(this._listChangedConfig){let i=this._listChangedConfig,o=this._serverCapabilities,s={...i.tools&&o?.tools?.listChanged&&{tools:i.tools},...i.prompts&&o?.prompts?.listChanged&&{prompts:i.prompts},...i.resources&&o?.resources?.listChanged&&{resources:i.resources}},a=!0;try{this._setupListChangedHandlers(s)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let c=a?{...s.tools&&{toolsListChanged:!0},...s.prompts&&{promptsListChanged:!0},...s.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(c).length>0){let u=new AbortController,l=()=>u.abort(n?.signal?.reason);if(n?.signal?.aborted)l();n?.signal?.addEventListener("abort",l);try{this._autoOpenedSubscription=await this.listen(c,{timeout:n?.timeout,signal:u.signal})}catch(d){if(n?.signal?.aborted)throw await this.close().catch(()=>{}),d;this.onerror?.(d instanceof Error?d:Error(String(d)))}finally{n?.signal?.removeEventListener("abort",l)}}}}async _connectFromPrior(e,t,n){if(t.kind==="legacy")return this._connectPlainLegacy(e,n);let r=t.discover;this._resetConnectionState();let i=this._supportedProtocolVersionsOption,o=(i&&ode(i).length>0?ode(i):tdt).find((s)=>r.supportedVersions.includes(s));if(o===void 0)throw new uo(Vi.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=r,this._serverCapabilities=r.capabilities,this._serverVersion=jSn(r),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.instructions,this._negotiatedProtocolVersion=o,e.setProtocolVersion?.(o),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;if(t!==void 0)return`${t.name}@${t.version}`;return e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return N3(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new uo(Vi.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new uo(Vi.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new uo(Vi.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new uo(Vi.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new uo(Vi.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new uo(Vi.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new uo(Vi.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new uo(Vi.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new uo(Vi.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new uo(Vi.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},xU,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let n=await this._serveFromCache("prompts/list",void 0,t);if(n!==void 0)return n;return this._listAllPages("prompts/list",e,t,(r,i)=>r.prompts.push(...i.prompts))}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let n=await this._serveFromCache("resources/list",void 0,t);if(n!==void 0)return n;return this._listAllPages("resources/list",e,t,(r,i)=>r.resources.push(...i.resources))}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let n=await this._serveFromCache("resources/templates/list",void 0,t);if(n!==void 0)return n;return this._listAllPages("resources/templates/list",e,t,(r,i)=>r.resourceTemplates.push(...i.resourceTemplates))}async _listAllPages(e,t,n,r,i){let o=n?.cacheMode==="bypass",s=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},n),c=a.nextCursor,u=new Set,l=1;while(c!==void 0&&!u.has(c)){if(this._listMaxPages!==0&&l>=this._listMaxPages)throw new uo(Vi.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});u.add(c);let d=await this.request({method:e,params:{...t,cursor:c}},n);r(a,d),c=d.nextCursor,l++}if(delete a.nextCursor,i?.(a),o)return a;return await this._cache.write(e,a,s,this._freshness(a)),a}_freshness(e,t){let n=e,r=typeof n.ttlMs==="number"?n.ttlMs:this._defaultCacheTtlMs,i=n.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,r),uEn),scope:i,params:t}}async _serveFromCache(e,t,n){if(n?.cacheMode==="bypass"||n?.cacheMode==="refresh")return;let r=await this._cache.read(e,t).catch((i)=>void this._reportStoreError(i));if(r!==void 0){if(n?.signal?.aborted){let i=n.signal.reason;throw i instanceof uo?i:new uo(Vi.RequestTimeout,String(i))}return r.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(!e.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let n=t??await this._cache.toolDefinition(e);return n===void 0?void 0:mdt(n.inputSchema)}async readResource(e,t){let n=await this._serveFromCache("resources/read",e.uri,t);if(n!==void 0)return n;let r=this._cache.captureGeneration("resources/read",e.uri),i=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let o=this._freshness(i,e.uri);if(o.expiresAt>this._cache.now())await this._cache.write("resources/read",i,r,o);else if(t?.cacheMode==="refresh")await this._cache.evictKey("resources/read",e.uri)}return i}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new uo(Vi.NotConnected,"Not connected");let n=this._negotiatedProtocolVersion;if(n===void 0||!N3(n))throw new uo(Vi.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${n??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:n});if(t?.signal?.aborted){let y=t.signal.reason;throw y instanceof uo?y:new uo(Vi.RequestTimeout,String(y))}let r=new AbortController,i=`listen:${this._nextListenId++}`,o="opening",s,a,c,u,l=new Promise((y,x)=>{c=y,u=x}),d,p=new Promise((y)=>{d=y}),f=(y)=>{if(o==="closed")return;let x=o==="opening";if(s!==void 0)clearTimeout(s),s=void 0;if("ack"in y){o="open",c(y.ack);return}if(o="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(i),r.abort(),d(y.cause),x)u(y.error??new uo(Vi.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},m=async()=>{r.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:i}}).catch(()=>{})},h=async()=>{if(o==="closed")return;f({cause:"local"}),await m()};this._listenState.set(i,{settle:f});let g=t?.timeout??ade;if(s=setTimeout(()=>{f({cause:"remote",error:new uo(Vi.RequestTimeout,"subscriptions/listen ack timed out",{timeout:g})}),m().catch(()=>{})},g),t?.signal){let y=t.signal;a=()=>{if(o==="closed")return;let x=y.reason;f({cause:"local",error:x instanceof Error?x:Error(String(x??"Aborted"))}),m().catch(()=>{})},y.addEventListener("abort",a,{once:!0})}let _={jsonrpc:"2.0",id:i,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}};try{await this.transport.send(_,{requestSignal:r.signal,onRequestStreamEnd:()=>f({cause:"remote",error:Error("subscriptions/listen: stream ended")})})}catch(y){f({cause:"remote",error:y instanceof Error?y:Error(String(y))})}return{honoredFilter:await l,close:h,closed:p}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let n=Object.hasOwn(BSn,e.method)?BSn[e.method]:void 0;if(e.method==="notifications/resources/updated"){let r=e.params?.uri;if(typeof r==="string")this._cache.evictKey("resources/read",r)}else if(n!==void 0)for(let r of n)this._cache.evict(r);if(e.method==="notifications/subscriptions/acknowledged"){let r=e.params?._meta?.[lJ],i=typeof r==="string"?this._listenState.get(r):void 0;if(i!==void 0){let o=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);i.settle({ack:o.ok?o.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let r=e.params?.requestId,i=typeof r==="string"?this._listenState.get(r):void 0;if(i!==void 0){i.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,n=typeof t==="string"?this._listenState.get(t):void 0;if(n!==void 0){if(EU(e))n.settle({cause:"remote",error:Ju.fromError(e.error.code,e.error.message,e.error.data)});else n.settle({cause:"graceful",error:new uo(Vi.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new uo(Vi.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let n=this.getProtocolEra()==="modern"&&FSn()!=="browser",r=async()=>{if(!n)return t;let c;try{c=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(l){this._reportStoreError(l)}if(!c?.valid||c.declarations.length===0)return t;let u=Ybn(c.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},i=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,(c)=>this._compileOutputValidator(c)).catch((c)=>void this._reportStoreError(c)):this._compileOutputValidator(t.toolDefinition),o=()=>{if(i===void 0||i.ok)return;let c=i.compileError,u=(c instanceof Error?c.message:String(c)).slice(0,200);throw new Ju(rs.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};o();let s;try{s=await this.request({method:"tools/call",params:e},await r())}catch(c){let u=c instanceof Ju&&c.code===EJ;if(!n||!u||t?.toolDefinition!==void 0)throw c;let l={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,l).catch((d)=>this._reportStoreError(d)),i=await this._cache.outputValidator(e.name,(d)=>this._compileOutputValidator(d)).catch((d)=>void this._reportStoreError(d)),o(),s=await this.request({method:"tools/call",params:e},await r())}let a=i!==void 0&&i.ok?i.validator:void 0;if(a){if(s.structuredContent===void 0&&!s.isError)throw new Ju(rs.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent!==void 0&&!s.isError)try{let c=a(s.structuredContent);if(!c.valid)throw new Ju(rs.InvalidParams,`Structured content does not match the tool's output schema: ${c.errorMessage}`)}catch(c){if(c instanceof Ju)throw c;throw new Ju(rs.InvalidParams,`Failed to validate structured content: ${c instanceof Error?c.message:String(c)}`)}}return s}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let r=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(r),r}let n=await this._serveFromCache("tools/list",void 0,t);if(n!==void 0)return n;return this._listAllPages("tools/list",e,t,(r,i)=>r.tools.push(...i.tools),(r)=>this._excludeInvalidXMcpHeaderTools(r))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||$Sn(this.transport)==="stdio")return;let t=e.tools.filter((n)=>{let r=mdt(n.inputSchema);if(!r.valid)return console.warn(`[mcp-sdk] excluding tool '${n.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${r.reason}`),!1;return!0});if(t.length!==e.tools.length)e.tools=t}_setupListChangedHandler(e,t,n,r){let i=v4e(Ule,n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=="function")throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:o,debounceMs:s}=i.data,{onChanged:a}=n,c=async()=>{if(!o){a(null,null);return}try{a(null,await r())}catch(l){a(l instanceof Error?l:Error(String(l)),null)}},u=()=>{if(s){let l=this._listChangedDebounceTimers.get(e);if(l)clearTimeout(l);let d=setTimeout(c,s);this._listChangedDebounceTimers.set(e,d)}else c()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};hEn=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Kb(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Kb(this,e)}constructor(e,t,n){super(`SSE error: ${t}`);this.code=e,this.event=n,SU(this,new.target)}},vci={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},bci=new Set(["authorization","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"])});async function bEn(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",Aci.encode(e)));return Array.from(t,(n)=>n.toString(16).padStart(2,"0")).join("")}function Ici(e){let t=e.replace(/[^A-Za-z0-9_]/gu,"_");return Cci.test(t)?t:`t_${t}`}function Dci(e){let t=sbn().safeParse(e.inputSchema);if(!t.success)return{schema:Mpt,loose:!0};try{return{schema:ute(t.data).pipe(Mpt),loose:!1}}catch{return{schema:Mpt,loose:!0}}}function Oci(e,t){let n=[e.title,e.description].filter((o)=>o!==void 0&&o.length>0).join(": "),r=n.length>0?n:e.name;return(t?`${r}
|
|
1283
1283
|
|
|
1284
|
-
${Rci}`:r).slice(0,Tci)}function Pci(e,t,n,r){let i={};for(let o of r){let s=Ici(o.name);if(s in i)continue;let a=Dci(o);i[s]=Wi.operation({replay:o.annotations?.readOnlyHint===!0?"safe":"unsafe",description:Oci(o,a.loose),input:a.schema,output:tDe,execute:async(c,u)=>{let l=await n.callTool({name:o.name,arguments:c},{signal:u.signal});if(l.isError!==!0&&l.structuredContent!==void 0)return tDe.parse(l.structuredContent);return tDe.parse({isError:l.isError===!0,content:l.content})}})}return Wi.module({id:e.id,name:e.name,namespace:t,description:`MCP server "${e.name}" at ${e.url.origin}: tools it advertises.`,operations:i})}async function Mci(e,t){let n=[],r;for(let i=0;i<xEn;i+=1){let o=await e.listTools(r===void 0?void 0:{cursor:r},{signal:t});if(n.push(...o.tools),n.length>yEn)throw Error(`MCP server advertises more than ${String(yEn)} tools`);if(r=o.nextCursor,r===void 0)return n}throw Error(`MCP server tool list exceeds ${String(xEn)} pages`)}function Nci(){return Promise.resolve().then(() => (Ade(),gEn))}function vEn(e,t){if(e.UnauthorizedError.isInstance(t))return"unauthorized";if(e.SdkHttpError.isInstance(t)&&(t.status===401||t.status===403))return"unauthorized";return"rejected"}async function Lci(e,t,n,r){let i=await Nci(),o=new i.Client({name:"fungi-knapsack",version:"1"}),s=new i.StreamableHTTPClientTransport(new URL(e.url),{requestInit:{headers:{...e.headers},redirect:"error"},fetch:n});try{await o.connect(s,{signal:r})}catch(a){throw await o.close(),new TU(e.id,vEn(i,a),a)}try{let a=await Mci(o,r).catch((l)=>{throw new TU(e.id,vEn(i,l)==="unauthorized"?"unauthorized":"invalid-advertisement",l)}),c;try{c=Pci(e,t,o,a)}catch(l){throw new TU(e.id,"invalid-advertisement",l)}let u=await bEn(JSON.stringify([e.id,e.name,e.url.href,a.map((l)=>[l.name,l.description??null,l.inputSchema,l.annotations?.readOnlyHint??null])]));return{module:c,version:u,close:()=>o.close()}}catch(a){throw await o.close(),a}}function Fci(e,t,n,r){return ii({try:(i)=>Lci(e,t,n,i),catch:(i)=>i instanceof TU?i:new TU(e.id,"rejected",i)}).pipe(mS({duration:r,orElse:()=>it(new TU(e.id,"timeout"))}))}function wEn(e){let t=e.connectTimeoutMillis??kci,n=e.namespace??["mcp"];return{id:e.id,acquire:async(r)=>{r.signal.throwIfAborted();let i=e.subscribe(r.invalidate),o=[],s=async()=>{await Promise.allSettled(o.map((a)=>a.close()))};try{let a=await e.read();if(a.servers.length>_En)throw Error(`At most ${String(_En)} MCP servers per source`);let c=await Fa(ws(a.servers,(l)=>ah(Fci(l,n,e.fetch,t).pipe(nu((d)=>Gt(()=>o.push(d))))),{concurrency:Eci}),{signal:r.signal}),u=[a.version];for(let l of c){if(Xi(l)){e.onUnavailable(l.failure),u.push(`unavailable:${l.failure.serverId}:${l.failure.reason}`);continue}u.push(l.success.version)}return r.signal.throwIfAborted(),{snapshot:{version:`mcp-${await bEn(JSON.stringify(u))}`,modules:o.map((l)=>l.module)},release:async()=>{i(),await s()}}}catch(a){throw i(),await s(),a}}}}var _En=16,yEn=256,xEn=16,Eci=4,kci=1e4,Tci=2048,Aci,tDe,Mpt,Cci,TU,Rci="Arguments are a JSON object; this server's schema is outside the supported subset, so the server validates them.";var SEn=C(()=>{Eh();abn();vr();ac();qn();Aci=new TextEncoder,tDe=ss(),Mpt=qe(D(),tDe),Cci=/^[A-Za-z][A-Za-z0-9_]*$/u;TU=class TU extends Error{name="McpServerUnavailableError";serverId;reason;constructor(e,t,n){super(`MCP server ${e} is unavailable: ${t}`,{cause:n});this.serverId=e,this.reason=t}}});var U3,Npt,Lpt,rDe,nDe,EEn,$ci,zci,kEn,Uci,jci,Bci,Fpt,TEn,AEn,CEn,IEn,qci,Wci,Ida,REn,Rda,$pt,Hci,DEn,Dda;var zpt=C(()=>{td();qn();U3=Ha({family:"knapsack-ui",version:1,kinds:{request:{prefix:"ui_request"},connection:{prefix:"ui_connection"},claim:{prefix:"ui_claim"},attempt:{prefix:"ui_attempt"}}}),Npt=D().min(1).max(256),Lpt=D().refine((e)=>U3.request.parse(e).ok),rDe=ss(),nDe=qe(D(),rDe),EEn=qe(D(),Ve()),$ci=es("status",[se({status:Ee("available")}),se({status:Ee("unavailable"),reason:D()})]),zci=Ke({namespace:Npt,id:Npt}),kEn={command:zci,sourceId:Npt,title:D(),category:D(),description:D().nullable(),order:et(),keybind:D().nullable(),availability:$ci},Uci=Nt([se({inputSchema:nDe,outputSchema:nDe}).strict(),se({inputSchema:nDe}).strict(),se({outputSchema:nDe}).strict()]),jci=se({...kEn,action:Uci}).strict(),Bci=se(kEn).strict(),Fpt=Nt([jci,Bci]),TEn=se({command:Ke({namespace:D().max(256),id:D().max(256)})}),AEn=TEn.extend({arguments:rDe}).strict(),CEn=TEn.strict(),IEn=Nt([AEn,CEn]),qci=Nt([se({type:Ee("discover")}).strict(),AEn.extend({type:Ee("execute")}),CEn.extend({type:Ee("execute")})]),Wci=se({requestId:Lpt,request:qci}),Ida=Wci.extend({connectionId:D().refine((e)=>U3.connection.parse(e).ok)}),REn=se({requestId:Lpt,connectionId:D().refine((e)=>U3.connection.parse(e).ok),attemptId:D().refine((e)=>U3.attempt.parse(e).ok)}),Rda=es("status",[se({status:Ee("claimed"),claimId:D()}),se({status:Ee("waiting"),retryAfterMs:et().int().min(10).max(1000)}),se({status:Ee("skipped")})]),$pt=Nt([se({status:Ee("handled"),result:rDe}).strict(),se({status:Ee("handled")}).strict(),se({status:Ee("closed")}).strict(),se({status:Ee("missing")}).strict(),se({status:Ee("invalid")}).strict(),se({status:Ee("unavailable"),reason:D()}).strict(),se({status:Ee("failed"),error:se({code:D(),message:D(),details:rDe})}).strict(),se({status:Ee("failed"),error:se({code:D(),message:D()}).strict()}).strict()]),Hci=es("type",[se({type:Ee("discover"),commands:Ge(Fpt)}),se({type:Ee("execute"),outcome:$pt})]),DEn=se({requestId:Lpt,claimId:D().refine((e)=>U3.claim.parse(e).ok),result:Hci}),Dda=es("status",[se({status:Ee("accepted")}),se({status:Ee("ignored")})])});function Kci(e){return e.expected==="execute"&&e.phase==="claimed"?new Jb("browser_execution_indeterminate","The browser disconnected after execution dispatch"):new Jb("browser_disconnected","The connected browser disconnected before returning a result")}function Jci(e,t,n,r){if(e===void 0||e.expiresAt<=n||!r.has(e.connectionId))return;if(e.connectionId===t.connectionId&&e.attemptId===t.attemptId)return{status:"claimed",claimId:e.claimId};return{status:"waiting",retryAfterMs:Math.max(10,Math.min(1000,e.expiresAt-n))}}function OEn(e,t){return e!==void 0&&e.expiresAt<=t}function Qci(e,t,n){return e.phase==="claimed"&&e.claim?.claimId===t&&!OEn(e.claim,n)}function PEn(e={}){return Ct(function*(){let t=yield*eM(1),n=new Map,r=e.claimLeaseMs??30000,i=Number.isFinite(r)?Math.max(100,Math.min(60000,r)):30000,o,s=(m)=>{n.delete(m.id);let h,g;if(o?.phase==="claimed"&&o.claim?.connectionId===m.id)if(n.size>0)o={...o,phase:"queued",claim:void 0},g={requestId:o.requestId,request:o.request};else h=o,o=void 0;else if(o!==void 0&&n.size===0)h=o,o=void 0;return{connection:m,failed:h,reoffer:g,recipients:[...n.values()]}},a=(m)=>{let h=m.reoffer;return(m.failed===void 0?Ln:une(m.failed.result,Kci(m.failed)).pipe(wm)).pipe(Wn(h===void 0?Ln:ws(m.recipients,(g)=>wS(g.requests,h),{discard:!0})),Wn(ZP(m.connection.requests)))},c=(m)=>c3(t,()=>s(m),a),u=()=>Da(Ct(function*(){let m=yield*NLt(1),h={id:U3.connection.generate(),requests:m};return yield*t.withPermits(1)(Gt(()=>{if(n.set(h.id,h),o!==void 0&&!o.cancelled)dh(h.requests,{requestId:o.requestId,request:o.request})})),h}),c).pipe(Mn((m)=>{let h=()=>SS(m.requests).pipe(mt((g)=>t.withPermits(1)(Gt(()=>o?.requestId===g.requestId&&n.has(m.id))).pipe(mt((_)=>_?rt(g):wr(h)))));return Object.freeze({id:m.id,take:wr(h)})})),l=(m)=>c3(t,()=>{if(o?.requestId===m)o={...o,cancelled:!0}},()=>Ln);return Object.freeze({connect:u,request:(m)=>ng((h)=>Ct(function*(){let g=yield*nF(),_,y=c3(t,()=>{if(n.size===0)return{status:"offline"};if(o!==void 0)return{status:"busy"};let x=U3.request.generate(),w={requestId:x,request:m};o={requestId:x,request:m,cancelled:!1,expected:m.type,phase:"queued",claim:void 0,result:g};for(let b of n.values())dh(b.requests,w);return _=x,{status:"admitted"}},(x)=>{if(x.status==="offline")return it(new Jb("browser_not_connected","No browser is connected"));if(x.status==="busy")return it(new Jb("browser_busy","The connected browser already has pending work"));return Ln}).pipe(Wn(kx(g)));return yield*h(y).pipe(Jy(()=>_===void 0?Ln:l(_)))})),claim:(m)=>Vci(m).pipe(Lo(()=>new Jb("invalid_browser_wire","Browser claim is invalid")),mt((h)=>c3(t,()=>{let g=o;if(g?.requestId!==h.requestId)return{status:"skipped"};if(g.cancelled)return o=void 0,{status:"skipped"};let _=Date.now(),y=Jci(g.claim,h,_,new Set(n.keys()));if(y!==void 0)return y;if(!n.has(h.connectionId))return{status:"skipped"};let x={attemptId:h.attemptId,claimId:U3.claim.generate(),connectionId:h.connectionId,expiresAt:_+i};return o={...g,phase:"claimed",claim:x},{status:"claimed",claimId:x.claimId}},rt))),acceptResult:(m)=>Gci(m).pipe(Lo(()=>new Jb("invalid_browser_wire","Browser result is invalid")),mt((h)=>c3(t,()=>{let g=o;if(g?.requestId!==h.requestId)return{status:"ignored"};let _=Date.now();if(!Qci(g,h.claimId,_)){if(OEn(g.claim,_))o={...g,phase:"queued",claim:void 0};return{status:"ignored"}}if(o=void 0,g.expected!==h.result.type){let y=new Jb("invalid_browser_wire","Browser result does not match its request");return{status:"mismatch",owned:g,failure:y}}return{status:"accepted",owned:g}},(g)=>{if(g.status==="ignored")return rt({status:"ignored"});if(g.status==="mismatch")return une(g.owned.result,g.failure).pipe(Wn(it(g.failure)));return fW(g.owned.result,h.result).pipe(po({status:"accepted"}))})))})})}var Gci=(e)=>Un(()=>DEn.parse(e)),Vci=(e)=>Un(()=>REn.parse(e)),Jb;var MEn=C(()=>{nM();rF();vr();_I();Nst();zpt();Jb=class Jb extends Error{code;constructor(e,t){super(t);this.code=e,this.name="UiHostError"}}});async function Upt(e,t){t?.throwIfAborted();let n=await lf(e,t===void 0?void 0:{signal:t});if(ns(n))return n.value;let r=sh(n.cause);if(Po(r))throw r.value;if(af(n.cause))throw t?.throwIfAborted(),new DOMException("The operation was aborted","AbortError");let i=_u(n.cause);if(i instanceof Error)throw i;throw Error("Live App command host failed without an Error cause")}function eui(e){return{status:"unavailable",reason:e}}function FEn(e){switch(e.code){case"browser_busy":case"browser_not_connected":case"browser_disconnected":return rt(eui(e.code));default:return it(e)}}function tui(e,t){return e.request(t).pipe(Cs(FEn))}function nui(e,t){return e.request(t).pipe(Cs((n)=>{if(n.code==="browser_execution_indeterminate")return rt({status:"indeterminate",reason:"browser_disconnected_after_dispatch"});return FEn(n)}))}function rui(e){if("status"in e)return e;if(e.type!=="discover")throw new Jb("invalid_browser_wire","Browser returned an execution result for discovery");return{status:"available",commands:[...e.commands]}}function iui(e){if("status"in e)return e;if(e.type!=="execute")throw new Jb("invalid_browser_wire","Browser returned a discovery result for execution");return e.outcome}function oui(e){let t=m_(e.connect().pipe(Mn((n)=>rM(`: connected
|
|
1284
|
+
${Rci}`:r).slice(0,Tci)}function Pci(e,t,n,r){let i={};for(let o of r){let s=Ici(o.name);if(s in i)continue;let a=Dci(o);i[s]=Wi.operation({replay:o.annotations?.readOnlyHint===!0?"safe":"unsafe",description:Oci(o,a.loose),input:a.schema,output:tDe,execute:async(c,u)=>{let l=await n.callTool({name:o.name,arguments:c},{signal:u.signal});if(l.isError!==!0&&l.structuredContent!==void 0)return tDe.parse(l.structuredContent);return tDe.parse({isError:l.isError===!0,content:l.content})}})}return Wi.module({id:e.id,name:e.name,namespace:t,description:`MCP server "${e.name}" at ${e.url.origin}: tools it advertises.`,operations:i})}async function Mci(e,t){let n=[],r;for(let i=0;i<xEn;i+=1){let o=await e.listTools(r===void 0?void 0:{cursor:r},{signal:t});if(n.push(...o.tools),n.length>yEn)throw Error(`MCP server advertises more than ${String(yEn)} tools`);if(r=o.nextCursor,r===void 0)return n}throw Error(`MCP server tool list exceeds ${String(xEn)} pages`)}function Nci(){return Promise.resolve().then(() => (Ade(),gEn))}function vEn(e,t){if(e.UnauthorizedError.isInstance(t))return"unauthorized";if(e.SdkHttpError.isInstance(t)&&(t.status===401||t.status===403))return"unauthorized";return"rejected"}async function Lci(e,t,n,r){let i=await Nci(),o=new i.Client({name:"fungi-knapsack",version:"1"}),s=new i.StreamableHTTPClientTransport(new URL(e.url),{requestInit:{headers:{...e.headers},redirect:"manual"},fetch:n});try{await o.connect(s,{signal:r})}catch(a){throw await o.close(),new TU(e.id,vEn(i,a),a)}try{let a=await Mci(o,r).catch((l)=>{throw new TU(e.id,vEn(i,l)==="unauthorized"?"unauthorized":"invalid-advertisement",l)}),c;try{c=Pci(e,t,o,a)}catch(l){throw new TU(e.id,"invalid-advertisement",l)}let u=await bEn(JSON.stringify([e.id,e.name,e.url.href,a.map((l)=>[l.name,l.description??null,l.inputSchema,l.annotations?.readOnlyHint??null])]));return{module:c,version:u,close:()=>o.close()}}catch(a){throw await o.close(),a}}function Fci(e,t,n,r){return ii({try:(i)=>Lci(e,t,n,i),catch:(i)=>i instanceof TU?i:new TU(e.id,"rejected",i)}).pipe(mS({duration:r,orElse:()=>it(new TU(e.id,"timeout"))}))}function wEn(e){let t=e.connectTimeoutMillis??kci,n=e.namespace??["mcp"];return{id:e.id,acquire:async(r)=>{r.signal.throwIfAborted();let i=e.subscribe(r.invalidate),o=[],s=async()=>{await Promise.allSettled(o.map((a)=>a.close()))};try{let a=await e.read();if(a.servers.length>_En)throw Error(`At most ${String(_En)} MCP servers per source`);let c=await Fa(ws(a.servers,(l)=>ah(Fci(l,n,e.fetch,t).pipe(nu((d)=>Gt(()=>o.push(d))))),{concurrency:Eci}),{signal:r.signal}),u=[a.version];for(let l of c){if(Xi(l)){e.onUnavailable(l.failure),u.push(`unavailable:${l.failure.serverId}:${l.failure.reason}`);continue}u.push(l.success.version)}return r.signal.throwIfAborted(),{snapshot:{version:`mcp-${await bEn(JSON.stringify(u))}`,modules:o.map((l)=>l.module)},release:async()=>{i(),await s()}}}catch(a){throw i(),await s(),a}}}}var _En=16,yEn=256,xEn=16,Eci=4,kci=1e4,Tci=2048,Aci,tDe,Mpt,Cci,TU,Rci="Arguments are a JSON object; this server's schema is outside the supported subset, so the server validates them.";var SEn=C(()=>{Eh();abn();vr();ac();qn();Aci=new TextEncoder,tDe=ss(),Mpt=qe(D(),tDe),Cci=/^[A-Za-z][A-Za-z0-9_]*$/u;TU=class TU extends Error{name="McpServerUnavailableError";serverId;reason;constructor(e,t,n){super(`MCP server ${e} is unavailable: ${t}`,{cause:n});this.serverId=e,this.reason=t}}});var U3,Npt,Lpt,rDe,nDe,EEn,$ci,zci,kEn,Uci,jci,Bci,Fpt,TEn,AEn,CEn,IEn,qci,Wci,Ida,REn,Rda,$pt,Hci,DEn,Dda;var zpt=C(()=>{td();qn();U3=Ha({family:"knapsack-ui",version:1,kinds:{request:{prefix:"ui_request"},connection:{prefix:"ui_connection"},claim:{prefix:"ui_claim"},attempt:{prefix:"ui_attempt"}}}),Npt=D().min(1).max(256),Lpt=D().refine((e)=>U3.request.parse(e).ok),rDe=ss(),nDe=qe(D(),rDe),EEn=qe(D(),Ve()),$ci=es("status",[se({status:Ee("available")}),se({status:Ee("unavailable"),reason:D()})]),zci=Ke({namespace:Npt,id:Npt}),kEn={command:zci,sourceId:Npt,title:D(),category:D(),description:D().nullable(),order:et(),keybind:D().nullable(),availability:$ci},Uci=Nt([se({inputSchema:nDe,outputSchema:nDe}).strict(),se({inputSchema:nDe}).strict(),se({outputSchema:nDe}).strict()]),jci=se({...kEn,action:Uci}).strict(),Bci=se(kEn).strict(),Fpt=Nt([jci,Bci]),TEn=se({command:Ke({namespace:D().max(256),id:D().max(256)})}),AEn=TEn.extend({arguments:rDe}).strict(),CEn=TEn.strict(),IEn=Nt([AEn,CEn]),qci=Nt([se({type:Ee("discover")}).strict(),AEn.extend({type:Ee("execute")}),CEn.extend({type:Ee("execute")})]),Wci=se({requestId:Lpt,request:qci}),Ida=Wci.extend({connectionId:D().refine((e)=>U3.connection.parse(e).ok)}),REn=se({requestId:Lpt,connectionId:D().refine((e)=>U3.connection.parse(e).ok),attemptId:D().refine((e)=>U3.attempt.parse(e).ok)}),Rda=es("status",[se({status:Ee("claimed"),claimId:D()}),se({status:Ee("waiting"),retryAfterMs:et().int().min(10).max(1000)}),se({status:Ee("skipped")})]),$pt=Nt([se({status:Ee("handled"),result:rDe}).strict(),se({status:Ee("handled")}).strict(),se({status:Ee("closed")}).strict(),se({status:Ee("missing")}).strict(),se({status:Ee("invalid")}).strict(),se({status:Ee("unavailable"),reason:D()}).strict(),se({status:Ee("failed"),error:se({code:D(),message:D(),details:rDe})}).strict(),se({status:Ee("failed"),error:se({code:D(),message:D()}).strict()}).strict()]),Hci=es("type",[se({type:Ee("discover"),commands:Ge(Fpt)}),se({type:Ee("execute"),outcome:$pt})]),DEn=se({requestId:Lpt,claimId:D().refine((e)=>U3.claim.parse(e).ok),result:Hci}),Dda=es("status",[se({status:Ee("accepted")}),se({status:Ee("ignored")})])});function Kci(e){return e.expected==="execute"&&e.phase==="claimed"?new Jb("browser_execution_indeterminate","The browser disconnected after execution dispatch"):new Jb("browser_disconnected","The connected browser disconnected before returning a result")}function Jci(e,t,n,r){if(e===void 0||e.expiresAt<=n||!r.has(e.connectionId))return;if(e.connectionId===t.connectionId&&e.attemptId===t.attemptId)return{status:"claimed",claimId:e.claimId};return{status:"waiting",retryAfterMs:Math.max(10,Math.min(1000,e.expiresAt-n))}}function OEn(e,t){return e!==void 0&&e.expiresAt<=t}function Qci(e,t,n){return e.phase==="claimed"&&e.claim?.claimId===t&&!OEn(e.claim,n)}function PEn(e={}){return Ct(function*(){let t=yield*eM(1),n=new Map,r=e.claimLeaseMs??30000,i=Number.isFinite(r)?Math.max(100,Math.min(60000,r)):30000,o,s=(m)=>{n.delete(m.id);let h,g;if(o?.phase==="claimed"&&o.claim?.connectionId===m.id)if(n.size>0)o={...o,phase:"queued",claim:void 0},g={requestId:o.requestId,request:o.request};else h=o,o=void 0;else if(o!==void 0&&n.size===0)h=o,o=void 0;return{connection:m,failed:h,reoffer:g,recipients:[...n.values()]}},a=(m)=>{let h=m.reoffer;return(m.failed===void 0?Ln:une(m.failed.result,Kci(m.failed)).pipe(wm)).pipe(Wn(h===void 0?Ln:ws(m.recipients,(g)=>wS(g.requests,h),{discard:!0})),Wn(ZP(m.connection.requests)))},c=(m)=>c3(t,()=>s(m),a),u=()=>Da(Ct(function*(){let m=yield*NLt(1),h={id:U3.connection.generate(),requests:m};return yield*t.withPermits(1)(Gt(()=>{if(n.set(h.id,h),o!==void 0&&!o.cancelled)dh(h.requests,{requestId:o.requestId,request:o.request})})),h}),c).pipe(Mn((m)=>{let h=()=>SS(m.requests).pipe(mt((g)=>t.withPermits(1)(Gt(()=>o?.requestId===g.requestId&&n.has(m.id))).pipe(mt((_)=>_?rt(g):wr(h)))));return Object.freeze({id:m.id,take:wr(h)})})),l=(m)=>c3(t,()=>{if(o?.requestId===m)o={...o,cancelled:!0}},()=>Ln);return Object.freeze({connect:u,request:(m)=>ng((h)=>Ct(function*(){let g=yield*nF(),_,y=c3(t,()=>{if(n.size===0)return{status:"offline"};if(o!==void 0)return{status:"busy"};let x=U3.request.generate(),w={requestId:x,request:m};o={requestId:x,request:m,cancelled:!1,expected:m.type,phase:"queued",claim:void 0,result:g};for(let b of n.values())dh(b.requests,w);return _=x,{status:"admitted"}},(x)=>{if(x.status==="offline")return it(new Jb("browser_not_connected","No browser is connected"));if(x.status==="busy")return it(new Jb("browser_busy","The connected browser already has pending work"));return Ln}).pipe(Wn(kx(g)));return yield*h(y).pipe(Jy(()=>_===void 0?Ln:l(_)))})),claim:(m)=>Vci(m).pipe(Lo(()=>new Jb("invalid_browser_wire","Browser claim is invalid")),mt((h)=>c3(t,()=>{let g=o;if(g?.requestId!==h.requestId)return{status:"skipped"};if(g.cancelled)return o=void 0,{status:"skipped"};let _=Date.now(),y=Jci(g.claim,h,_,new Set(n.keys()));if(y!==void 0)return y;if(!n.has(h.connectionId))return{status:"skipped"};let x={attemptId:h.attemptId,claimId:U3.claim.generate(),connectionId:h.connectionId,expiresAt:_+i};return o={...g,phase:"claimed",claim:x},{status:"claimed",claimId:x.claimId}},rt))),acceptResult:(m)=>Gci(m).pipe(Lo(()=>new Jb("invalid_browser_wire","Browser result is invalid")),mt((h)=>c3(t,()=>{let g=o;if(g?.requestId!==h.requestId)return{status:"ignored"};let _=Date.now();if(!Qci(g,h.claimId,_)){if(OEn(g.claim,_))o={...g,phase:"queued",claim:void 0};return{status:"ignored"}}if(o=void 0,g.expected!==h.result.type){let y=new Jb("invalid_browser_wire","Browser result does not match its request");return{status:"mismatch",owned:g,failure:y}}return{status:"accepted",owned:g}},(g)=>{if(g.status==="ignored")return rt({status:"ignored"});if(g.status==="mismatch")return une(g.owned.result,g.failure).pipe(Wn(it(g.failure)));return fW(g.owned.result,h.result).pipe(po({status:"accepted"}))})))})})}var Gci=(e)=>Un(()=>DEn.parse(e)),Vci=(e)=>Un(()=>REn.parse(e)),Jb;var MEn=C(()=>{nM();rF();vr();_I();Nst();zpt();Jb=class Jb extends Error{code;constructor(e,t){super(t);this.code=e,this.name="UiHostError"}}});async function Upt(e,t){t?.throwIfAborted();let n=await lf(e,t===void 0?void 0:{signal:t});if(ns(n))return n.value;let r=sh(n.cause);if(Po(r))throw r.value;if(af(n.cause))throw t?.throwIfAborted(),new DOMException("The operation was aborted","AbortError");let i=_u(n.cause);if(i instanceof Error)throw i;throw Error("Live App command host failed without an Error cause")}function eui(e){return{status:"unavailable",reason:e}}function FEn(e){switch(e.code){case"browser_busy":case"browser_not_connected":case"browser_disconnected":return rt(eui(e.code));default:return it(e)}}function tui(e,t){return e.request(t).pipe(Cs(FEn))}function nui(e,t){return e.request(t).pipe(Cs((n)=>{if(n.code==="browser_execution_indeterminate")return rt({status:"indeterminate",reason:"browser_disconnected_after_dispatch"});return FEn(n)}))}function rui(e){if("status"in e)return e;if(e.type!=="discover")throw new Jb("invalid_browser_wire","Browser returned an execution result for discovery");return{status:"available",commands:[...e.commands]}}function iui(e){if("status"in e)return e;if(e.type!=="execute")throw new Jb("invalid_browser_wire","Browser returned a discovery result for execution");return e.outcome}function oui(e){let t=m_(e.connect().pipe(Mn((n)=>rM(`: connected
|
|
1285
1285
|
|
|
1286
1286
|
`).pipe(OF(Ave(n.take).pipe(hre((r)=>`event: browser-request
|
|
1287
1287
|
data: ${JSON.stringify({...r,connectionId:n.id})}
|
|
@@ -2261,7 +2261,7 @@ ${l.stderr.trim()}`);await TAt(r),e(`fungi updated ${n.version} \u2192 ${a}.`)}a
|
|
|
2261
2261
|
`)),...e.language===void 0?{}:{filetype:e.language},fg:i.foreground,syntaxStyle:o,selectionBg:i.selection,selectionFg:i.selectionForeground,wrapMode:"word"}),je(lZ,{hidden:a,presentation:r})]})}}}function Car(e,t,n=!1){let{colors:r}=t,i=Hpt(e,n);return i==="neutral"?r.foreground:r[i]}function VCt({caption:e,tone:t,open:n,presentation:r}){let i=Zge-4;return Gn("text",{selectable:!1,fg:r.colors.foreground,wrapMode:"none",width:e===void 0?3:Zge,flexShrink:0,children:[e===void 0?null:Gn("span",{attributes:2,children:[_c(e,i).padStart(i)," "]}),je("span",{fg:t,children:"\u25CF "}),je("span",{attributes:2,children:n===void 0?" ":n?"\u25BE":"\u25B8"})]})}function Iar(e){return e===void 0?"":` \xB7 ${Kpt(e)}`}function Sar({call:e,disclosureId:t,disclosure:n,nested:r,terminalWidth:i,inset:o,toggle:s,presentation:a}){let{colors:c}=a,u=JY()?.[e.kind],l=uDe(e),d=bN(n,t,l),p=e.status==="running",f=i-2*o-(r?6:4)-(Tp-2);return Gn("box",{flexShrink:0,children:[Gn("box",{flexDirection:"row",height:1,onMouseDown:(m)=>{m.preventDefault(),s(t,l)},children:[Gn("text",{selectable:!1,fg:c.foreground,wrapMode:"none",flexGrow:1,flexShrink:1,marginLeft:-1,children:[je(QY,{glyph:u}),je("span",{attributes:1,children:br(p?e.activeVerb:e.verb)})," ",HCt(br(e.label),Math.max(0,i-2*o-Zge-Tp-3-Dv(p?e.activeVerb:e.verb)-(e.exitCode===void 0?0:Dv(` \xB7 exit ${String(e.exitCode)}`)))),e.exitCode===void 0?null:je("span",{fg:e.recovered===!0?c.foreground:c.error,children:` \xB7 exit ${String(e.exitCode)}`})]}),je(VCt,{caption:Iar(e.durationMs).replace(/^ \u00B7 /u,""),tone:Car(e.status,a,e.recovered===!0),open:d,presentation:a})]}),d?Gn("box",{marginLeft:Tp,marginTop:1,children:[e.error===void 0?null:je("text",{fg:e.recovered===!0?c.foreground:c.error,marginBottom:1,children:br(e.error)}),e.sections.map((m,h)=>je(Gyo,{section:m,full:n.mode==="expanded",presentation:a,width:f},`${m.kind}:${String(h)}`))]}):null,e.live===void 0?null:je("box",{marginLeft:Tp,flexShrink:0,children:Vpt(e,d).map((m,h)=>je("text",{fg:c.foreground,attributes:2,height:1,wrapMode:"none",children:br(m)},String(h)))})]})}function Vyo({group:e,disclosure:t,inset:n,terminalWidth:r,toggle:i,presentation:o}){let{colors:s}=o,a=JY(),c=cDe(e),u=bN(t,e.id,c),l=e.status==="running"?e.active:void 0,d=a?.search,p=e.status==="completed",f=e.calls.length===1?e.calls[0]:void 0;if(f!==void 0)return je("box",{id:tO(e.id),flexShrink:0,marginBottom:1,paddingX:n,children:je(Sar,{call:f,disclosure:t,disclosureId:f.id,inset:n,nested:!1,presentation:o,terminalWidth:r,toggle:i})});let m=je("box",{children:Xpt(e,u).map((h)=>je(Sar,{call:h,disclosure:t,disclosureId:h.id,inset:n,nested:!0,presentation:o,terminalWidth:r,toggle:i},h.id))});return Gn("box",{id:tO(e.id),flexShrink:0,marginBottom:1,paddingX:n,children:[Gn("box",{flexDirection:"row",height:1,onMouseDown:(h)=>{h.preventDefault(),i(e.id,c)},children:[Gn("text",{selectable:!1,fg:s.foreground,wrapMode:"none",flexGrow:1,flexShrink:1,marginLeft:-1,children:[je(QY,{glyph:d}),l===void 0?null:Gn("span",{attributes:1,children:[br(l.activeVerb)," "]}),HCt(br((l===void 0?e.summary:l.label)+` \xB7 ${String(e.calls.length)} ${e.calls.length===1?"call":"calls"}`+(e.failedCount>0?` \xB7 ${String(e.failedCount)} failed`:"")+(e.recoveredCount>0?` \xB7 ${String(e.recoveredCount)} recovered`:"")),Math.max(0,r-2*n-Zge-2-Tp-(l===void 0?0:Dv(l.activeVerb)+1)))]}),je(VCt,{caption:Iar(e.durationMs).replace(/^ \u00B7 /u,""),tone:Car(e.status,o),open:u,presentation:o})]}),m,p&&e.calls.length>3?je("text",{marginLeft:Tp,height:1,selectable:!1,fg:s.foreground,onMouseDown:(h)=>{h.preventDefault(),i(e.id,c)},children:u?"Show less":`Show all ${String(e.calls.length)} calls`}):null]})}function Kyo(e,t){return t===null?"compacted \xB7 the agent's memory starts below":`compacted ${l9(e)} \u2192 ${l9(t)}`}function Jyo(e,t){let n=` ${t} `,r=Math.max(0,e-n.length),i=Math.floor(r/2),o=r-i;return`${"\u2500".repeat(i)}${n}${"\u2500".repeat(o)}`}function Qyo({id:e,inset:t,terminalWidth:n,presentation:r,tokensBefore:i,tokensAfter:o}){return je("box",{id:tO(e),flexShrink:0,marginTop:1,marginBottom:1,paddingX:t,children:je("text",{fg:r.colors.foreground,attributes:2,wrapMode:"none",children:Jyo(Math.max(0,n-2*t),Kyo(i,o))})})}function Xyo({id:e,inset:t,presentation:n,result:r,diagnostic:i}){let{colors:o,dimForeground:s}=n,a=i===null?Ear[r]:`${Ear[r]}: ${zy(i)}`;return je("box",{id:tO(e),flexShrink:0,paddingX:t,height:1,marginBottom:1,children:je("text",{fg:r==="failed"?o.error:s,attributes:2,wrapMode:"none",children:br(`\xB7 ${a}`)})})}function KCt(e){return e.author?.kind==="agent"}function kar(e){return e.kind==="user_message"&&!KCt(e)}function Yyo(e,t,n){return t!==void 0&&!n&&kar(e)&&kar(t)}function Tar(e,t){let n=e.status==="pending"||e.status==="queued",r=n&&e.delivery==="followUp";return{cue:r,foreground:n?r?t.dimForeground:t.colors.accent:t.colors.foreground}}function Zyo({item:e,disclosure:t,inset:n,terminalWidth:r,toggle:i,presentation:o,stacksOnNext:s}){let{colors:a,surface:c}=o,u=JY()?.error,l=JY()?.agent;if(e.kind==="compaction_divider")return je(Qyo,{id:e.id,inset:n,terminalWidth:r,presentation:o,tokensBefore:e.tokensBefore,tokensAfter:e.tokensAfter});if(e.kind==="compaction_notice")return je(Xyo,{id:e.id,inset:n,presentation:o,result:e.result,diagnostic:e.diagnostic});if(e.kind==="tool_group")return je(Vyo,{presentation:o,group:e,disclosure:t,inset:n,terminalWidth:r,toggle:i});if(e.kind==="user_message"&&KCt(e)){let{foreground:p}=Tar(e,o),f=bN(t,e.id,!1),m=e.author?.name??"",h=Math.max(0,r-2*n-Tp);return Gn("box",{id:tO(e.id),flexShrink:0,marginBottom:1,paddingX:n,children:[je("box",{flexDirection:"row",height:1,onMouseDown:(g)=>{g.preventDefault(),i(e.id,!1)},children:Gn("text",{selectable:!1,fg:a.foreground,wrapMode:"none",flexGrow:1,flexShrink:1,marginLeft:-1,children:[je(QY,{glyph:l}),je("span",{fg:o.dimForeground,attributes:2,children:_c(br(f?m:`${m} \xB7 ${e.text}`),h)})]})}),f?je("text",{marginLeft:Tp,fg:p,attributes:e.status==="confirmed"?0:2,selectionBg:a.selection,selectionFg:a.selectionForeground,children:br(e.text)}):null]})}if(e.kind==="user_message"){let{cue:p,foreground:f}=Tar(e,o);return je("box",{id:tO(e.id),flexDirection:"row",flexShrink:0,marginBottom:s?0:1,backgroundColor:c,paddingX:n,paddingY:1,children:je("text",{marginLeft:Tp,flexGrow:1,flexShrink:1,fg:f,attributes:e.status==="confirmed"?1:2,...p?{wrapMode:"none"}:{},selectionBg:a.selection,selectionFg:a.selectionForeground,children:p?_c(br(e.text),Math.max(0,r-2*n-Tp)):br(e.text)})})}if(!iN(e))return null;let d=e.repeatCount===void 0?e.text:`${e.text} x${String(e.repeatCount)}`;return Gn("box",{id:tO(e.id),flexShrink:0,marginBottom:1,paddingX:n,children:[e.thinking?je("box",{marginLeft:Tp,marginBottom:e.text?1:0,children:je("text",{fg:a.foreground,attributes:2,children:bN(t,e.id,!1)?br(e.thinking):"Thinking"})}):null,e.text?Gn("box",{flexDirection:"row",children:[e.isError?je("text",{width:GLe,marginLeft:-1,flexShrink:0,selectable:!1,wrapMode:"none",children:je(QY,{glyph:u})}):je("text",{width:Tp,flexShrink:0,fg:a.info,wrapMode:"none",children:d7(e.pending?"\u25CF":"")}),je("box",{flexGrow:1,flexShrink:1,children:e.isError&&e.providerError!==void 0?je("text",{fg:a.error,wrapMode:"word",children:br(d)}):je(KTt,{content:d,presentation:o,foreground:e.isError?a.error:a.foreground,streaming:e.pending})}),e.isError&&e.providerError===void 0?je(VCt,{tone:a.error,presentation:o}):null]}):null,e.isError&&e.errorDetail?je("box",{marginLeft:Tp,children:je("text",{fg:a.foreground,attributes:2,children:br(e.errorDetail)})}):null,e.isError&&e.providerError!==void 0&&bN(t,e.id,!1)?Gn("box",{marginLeft:Tp,flexDirection:"column",children:[je("text",{fg:a.error,children:"Provider details (latest response)"}),je("text",{fg:a.error,children:br(e.providerError)})]}):null]})}function t1o(e,t){let n=e.viewport.y,r=n+e.viewport.height;return e.getChildren().filter((o)=>o.id.startsWith(e_e)&&t.has(o.id.slice(e_e.length))&&o.y+o.height>n&&o.y<r).at(-1)?.id.slice(e_e.length)}function n1o(e,t,n){if(n==="older"){let o=Math.max(0,e.start-_ar),s=Math.min(e.end,o+yar);return{start:o,end:s}}let r=Math.min(t,e.end+_ar);return{start:Math.max(e.start,r-yar),end:r}}function r1o({emptyState:e,detailsRequest:t,groupRequest:n,inputEnabled:r,presentation:i,sessionAddress:o,terminalWidth:s}){let a=AU(),c=CU(),u=KT(),l=JT(),d=ys(()=>IU(l,a.commandAnchors,a.positionAnchors),[l,a.commandAnchors,a.positionAnchors]),{rendering:p}=Tf(),f=1,m=Or(null),[h,g]=ti(()=>OB(a.settled.length)),_=Or(!0),y=_.current?OB(a.settled.length):xar(h,a.settled.length),x=Or(y);x.current=y;let w=Or(a.settled.length);w.current=a.settled.length;let[b,E]=ti(!1),A=Or(!1),R=Or(void 0),L=Or(void 0),z=Or(void 0),j=Or(!1),[G,ee]=ti(Qpt),ie=Or(t);ie.current=t;let le=Or(t),be=Or(n);be.current=n;let xe=Or(n),B=Uc((J)=>{if(A.current===J)return;A.current=J,E(J)},[]),K=Uc(()=>{let J=m.current;if(J!==null)R.current=GCt(J)},[]),X=Uc(()=>{if(j.current||z.current!==void 0)return;let J=m.current;if(J===null)return;let te=J.scrollTop>=Math.max(0,J.scrollHeight-J.viewport.height-1),ye=x.current.end===w.current;if(te&&ye){_.current=!0,R.current=void 0,B(!1);let ce=OB(w.current);if(!bar(x.current,ce))g(ce);return}if(_.current)return;_.current=!1,B(!0),K()},[K,B]),Y=Uc((J,te)=>{let ye=m.current;if(ye===null||L.current!==void 0)return!1;let ce=x.current,de={anchor:GCt(ye),movement:te,previousHeight:ye.scrollHeight,previousTop:ye.scrollTop};if(J==="older"&&ce.start===0){if(!a.hasMoreHistory||a.loadingOlderHistory)return!1;return z.current={direction:J,change:de},a.loadOlderHistory(),!0}if(J==="newer"&&ce.end===w.current){if(!a.hasNewerHistory||a.loadingOlderHistory)return!1;return z.current={direction:J,change:de},a.loadNewerHistory(),!0}let Se=n1o(ce,w.current,J);if(bar(ce,Se))return!1;return L.current=de,_.current=!1,B(!0),g(Se),!0},[a,B]);Vn(()=>{let J=OB(w.current);_.current=!0,R.current=void 0,L.current=void 0,z.current=void 0,B(!1),g(J),le.current=ie.current,xe.current=be.current},[o,B]),Vn(()=>{if(_.current){g(OB(a.settled.length));return}let J=z.current;if(J!==void 0){if(a.loadingOlderHistory)return;z.current=void 0,L.current=J.change,g(J.direction==="older"?{start:0,end:Math.min(Aar,a.settled.length)}:OB(a.settled.length));return}g((te)=>xar(te,a.settled.length))},[a.loadingOlderHistory,a.settled]),Vn(()=>{if(le.current===t)return;le.current=t,K(),ee(Zpt)},[K,t]),Ah(()=>{let J=2,te,ye=()=>{if(J-=1,J>0){te=p.afterFrame(ye),p.requestFrame();return}let ce=m.current;if(ce===null)return;j.current=!0;let de=L.current;if(de!==void 0){if(L.current=void 0,!(de.anchor!==void 0&&war(ce,de.anchor)))ce.scrollTo(de.previousTop+ce.scrollHeight-de.previousHeight);if(de.movement!==0)ce.scrollBy(de.movement,"viewport");R.current=GCt(ce)}else if(_.current)ce.scrollTo(ce.scrollHeight);else if(R.current!==void 0)war(ce,R.current);j.current=!1,X()};return te=p.afterFrame(ye),p.requestFrame(),()=>{te?.()}},[G,X,i,p,o,a.settled,a.tail,a.loadingOlderHistory,y.end,y.start,s]);let fe=Uc((J,te)=>{K(),ee((ye)=>Ypt(ye,J,te))},[K]);Vn(()=>{if(xe.current===n)return;xe.current=n;let J=m.current,te=new Set(a.settled.filter((de)=>de.kind==="tool_group"||de.kind==="user_message"&&KCt(de)).map((de)=>de.id)),ye=J===null?void 0:t1o(J,te),ce=a.settled.find((de)=>de.id===ye);if(ce?.kind==="user_message")fe(ce.id,!1);if(ce?.kind==="tool_group"){let de=ce.calls.length===1?ce.calls[0]:void 0;fe(de?.id??ce.id,de===void 0?cDe(ce):uDe(de))}},[n,a.settled,fe]),E6((J)=>{if(!r||J.name!=="pageup"&&J.name!=="pagedown")return!1;let te=m.current;if(te===null)return!1;let ye=J.name==="pageup";if(ye)a.pinVisibleHistory(),_.current=!1,B(!0);if(!((ye?te.scrollTop<=te.viewport.height:te.scrollTop>=te.scrollHeight-2*te.viewport.height)&&Y(ye?"older":"newer",ye?-1:1)))te.scrollBy(ye?-1:1,"viewport");return X(),J.preventDefault(),!0});let V=Uc((J)=>{let te=m.current,ye=J.scroll?.direction;if(te===null||ye!=="up"&&ye!=="down")return;if(ye==="up")a.pinVisibleHistory(),_.current=!1,B(!0);if(ye==="up"?te.scrollTop<=te.viewport.height:te.scrollTop>=te.scrollHeight-2*te.viewport.height)Y(ye==="up"?"older":"newer",0);X()},[X,Y,a,B]),Z=Uc((J)=>{let te=m.current;if(te===null||J.x<te.x+te.width-2)return;a.pinVisibleHistory(),_.current=!1,B(!0)},[a,B]),ue=Uc(()=>{let J=m.current;a.jumpToLatest(),z.current=void 0,_.current=!0,R.current=void 0,B(!1),g(OB(w.current)),J?.scrollTo(J.scrollHeight)},[a,B]),Le=ys(()=>a.settled.slice(y.start,y.end),[a.settled,y.end,y.start]),ve=ys(()=>y.end===a.settled.length?[...Le,...a.tail]:Le,[a.settled.length,a.tail,y.end,Le]),Pe=ys(()=>ve.map((J,te)=>Gn(jIe,{children:[je(e1o,{stacksOnNext:Yyo(J,ve[te+1],(d.after.get(J.id)?.length??0)>0),presentation:i,item:J,disclosure:G,inset:1,terminalWidth:s,toggle:fe},J.id),d.after.get(J.id)?.map(({entryId:ye,cell:ce})=>je(cZ,{id:tO(JSON.stringify([ye,ce.id])),rows:ce.rows,presentation:i},JSON.stringify([ye,ce.id])))]},J.id)),[G,i,s,fe,ve,d]);return Gn("box",{flexGrow:1,flexShrink:1,minHeight:0,paddingTop:1,children:[Gn("scrollbox",{ref:m,flexGrow:1,flexShrink:1,minHeight:0,stickyScroll:!0,stickyStart:"bottom",scrollX:!1,onMouseDown:Z,onMouseScroll:V,contentOptions:{minHeight:0},scrollbarOptions:{showArrows:!1,onChange:X,trackOptions:{foregroundColor:i.colors.surface,backgroundColor:i.colors.background}},children:[u.observation.status==="unavailable"?Gn("text",{fg:i.colors.error,marginX:1,children:[d7("\u25CF"),br(u.observation.reason)," \xB7 /reconnect to retry"]}):null,y.start===0?d.before.map(({entryId:J,cell:te})=>je(cZ,{id:tO(JSON.stringify([J,te.id])),rows:te.rows,presentation:i},JSON.stringify([J,te.id]))):null,ve.length===0&&d.before.length===0&&!a.hasMoreHistory?Gn("box",{flexDirection:"column",marginX:1,children:[je("text",{fg:i.colors.foreground,attributes:2,children:"Start a conversation."}),je("text",{fg:i.colors.foreground,attributes:2,children:br(`Model: ${e.model??"No model selected"}`)}),e.folder===void 0?null:je("text",{fg:i.colors.foreground,attributes:2,children:br(`Folder: ${e.folder}`)}),e.signInRequired?je("text",{fg:i.colors.info,children:"Sign in to start: type /login"}):null]}):je(yk,{children:Pe})]}),u.viewState.kind==="error"?Gn("box",{flexDirection:"column",flexShrink:0,paddingX:1,children:[je("text",{fg:i.colors.error,flexShrink:0,width:"100%",wrapMode:"word",children:br(`Stopped: ${zy(u.viewState.cause)}`)}),je("text",{fg:i.colors.info,flexShrink:0,width:"100%",wrapMode:"word",children:e.signInRequired&&u.viewState.cause.startsWith("model:rejected:")?"/login \xB7 sign in, then send your message again":c.failure==="admission"?"/retry \xB7 or edit and submit the draft":"/retry \xB7 /continue \xB7 or type a new instruction"})]}):null,b?je("text",{flexShrink:0,height:1,wrapMode:"none",bg:i.colors.background,fg:i.colors.info,marginX:1,onMouseDown:(J)=>{J.preventDefault(),ue()},children:"Jump to latest \u2193"}):null]})}var Aar=60,_ar=60,yar=240,e_e="tui-timeline-row:",Ear,e1o,Rar;var Dar=C(async()=>{qc();Gi();bf();iq();await Mc([Xa(),har(),Xa(),qCt(),Xa(),Xa(),Xa(),Xa()]);Ear={nothing_to_compact:"nothing to compact",failed:"compaction failed",stale:"compaction skipped: the context moved on",insufficient:"compaction skipped: the summary would not fit"};e1o=QK(Zyo);Rar=QK(r1o)});function Oar(e){let{observation:t,reconnect:n,onObservationUnavailable:r,rebindService:i,timing:o=o1o,clock:s=i1o,lastReplyAt:a}=e,[c,u]=ti(),[l,d]=ti(!1);return Vn(()=>{if(t==="unavailable")d(!0);else if(t==="live")d(!1)},[t]),Vn(()=>{if(!l)return;let p=new AbortController,f=()=>!p.signal.aborted,m,h,g,_=a===void 0||a===0?s.now():a,y=Math.max(0,s.now()-_),x=y>=o.appearAfterMs,w=y>=o.stuckAfterMs,b=()=>{u(g!==void 0?{phase:"incompatible",message:g}:!x?void 0:w?{phase:"stuck",alive:h,seconds:Math.max(0,Math.floor((s.now()-_)/1000)),lastError:m}:{phase:"restarting"})},E=0,A,R=async()=>{try{let ie=await r?.();if(!f()||ie)return;let le=await i?.(p.signal);if(!f())return;if(le?.kind==="unavailable")m=void 0,h=le.alive;else{if(le?.kind==="rebound")h=!0;let be=await n();if(be.kind==="reconnected"||!f())return;m=be.kind==="failed"?be.cause:void 0}}catch(ie){if(xi("session-observation-recovery",ie),!f())return;if(ie instanceof Error&&(ie.name==="LocalServiceUpdated"||ie.name==="LocalServiceIncompatible")){g=ie.message,z(),j(),b();return}m=ie instanceof Error?ie.message:String(ie)}b(),L()};function L(){let ie=Math.min(o.firstAttemptAfterMs*2**E,o.maxRetryDelayMs),le=Math.min(o.maxRetryDelayMs,ie*(0.8+0.4*s.random()));E+=1,A=s.schedule(()=>{R()},le)}L();let z=s.schedule(()=>{x=!0,b()},Math.max(0,o.appearAfterMs-y)),j=s.schedule(()=>{x=!0,w=!0,b()},Math.max(0,o.stuckAfterMs-y)),G=()=>{if(!f())return;if(w)b();ee=s.schedule(G,1000)},ee=s.schedule(G,1000);return()=>{p.abort(),z(),j(),A?.(),ee(),u(void 0)}},[l,n,r,i,o,s,a]),c}function Par({view:e,colors:t,viewport:n,onClose:r}){let i=e.phase==="incompatible"?{title:"Can't use the service",summary:e.message}:e.phase==="restarting"?{title:"Reconnecting to the service",summary:"Your conversation will resume."}:{title:e.alive===!1?"The service stopped":`The service is busy (no reply for ${String(e.seconds)}s)`,summary:e.alive===!1?"Run `fungi resume` in another terminal. This conversation keeps trying and keeps your draft.":"Your conversation will resume; your draft is kept.",facts:e.lastError===void 0?[]:[{label:"Error",value:e.lastError}]};return je(VY,{colors:t,onClose:r,children:je(Z_,{content:i,colors:t,width:J1(n.width),compact:n.height<14,full:!0})})}var i1o,o1o;var Mar=C(async()=>{qc();Gi();await Xa();i1o={now:Date.now,random:Math.random,schedule(e,t){let n=setTimeout(e,t);return()=>{clearTimeout(n)}}},o1o={firstAttemptAfterMs:250,appearAfterMs:1000,stuckAfterMs:30000,maxRetryDelayMs:30000}});import{ScrollBoxRenderable as hnc}from"@opentui/core";function s1o(e){xi("mcp-approval-answer",e)}function Lar({session:e,draftIdentity:t,...n}){let r=RA(),i=Uc(({action:o,...s})=>{r.show(o===void 0?s:{...s,action:{label:o.label,run:o.onSelect}})},[r]);return je(hft,{session:e,draftStorage:BSt,draftIdentity:t,clients:n.clients,interactionStore:n.interactionStore,authorOf:yR,onToast:i,children:je(l1o,{...n,session:e})})}function t_e({color:e,inset:t,children:n,oneLine:r=!1}){return Gn("box",{flexDirection:"row",marginX:t,children:[je("text",{width:Tp,flexShrink:0,fg:e,children:d7("\u25CF")}),je("text",{flexGrow:1,flexShrink:1,fg:e,wrapMode:r?"none":"word",children:n})]})}function l1o({commands:e,interactionStore:t,mcpApprovals:n,applicationCommands:r,onExit:i,onStopAll:o,session:s,onOpen:a,initialTheme:c="terminal",onThemeConfirm:u=gge,themeError:l,modelSource:d,sandboxSource:p,folder:f,onTitled:m,reloadSources:h,onResume:g,onNew:_,onForked:y,inputHandoff:x,onObservationUnavailable:w,onRebindService:b,initialCommandError:E,initialCommandNotice:A}){let R=Rut(),L=Tf();mft(ys(()=>({label:"Add it with /login",onSelect:()=>{e.execute({namespace:"account",id:"login"},{origin:"slash"}).catch((bn)=>{xi("open-login-from-secret-refusal",bn)})}}),[e]));let z=o===void 0?void 0:async()=>{try{L.toast(nar(await o()))}catch(bn){xi("session-stop-all",bn),L.toast(rar(bn))}},j=Q5(),G=Ta(L.dialogs.open.subscribe,L.dialogs.open.read),ee={show:L.dialogs.show,dismiss:L.dialogs.dismiss,isOpen:G},ie=CU();Vn(()=>L.sessions.registerDraftCheckpoint?.(s,ie.checkpointDraft),[L.sessions,s,ie.checkpointDraft]);let le=KT(),be=gft(),xe=JT(),B=AU(),K=ys(()=>IU(xe,B.commandAnchors,B.positionAnchors),[xe,B.commandAnchors,B.positionAnchors]),X=Zsr(e,a),Y=xe.flatMap(({entryId:bn,value:vi})=>vi.panel.filter((Xs)=>Xs.tone==="attention"&&(Xs.actions?.length??0)>0).map((Xs)=>({entryId:bn,row:Xs,key:JSON.stringify([bn,Xs.id])}))),fe=(bn)=>bn.actions?.some((vi)=>vi.awaiting!==void 0)===!0,V=Y.filter(({row:bn})=>!fe(bn)),Z=Or(!1),[ue,Le]=ti(null),[ve,Pe]=ti(!1),J=Math.max(0,V.findIndex((bn)=>bn.key===ue)),te=V[J],ye=ve&&te!==void 0;Vn(()=>{if(V.length===0)Pe(!1)},[V.length]),E6((bn)=>{if(ee.isOpen||!j||Z.current)return!1;if(bn.name==="up"&&bn.meta&&te!==void 0)return Pe(!0),!0;if(!ye)return!1;if(bn.name==="escape"||bn.name==="down"&&bn.meta)return Pe(!1),!0;if(bn.name==="up"||bn.name==="down"){let vi=V[(J+(bn.name==="up"?-1:1)+V.length)%V.length];if(vi!==void 0)Le(vi.key);return!0}if(bn.name==="return"){let vi=te.row.actions?.[0];if(vi!==void 0)Pe(!1),X.execute(te.entryId,vi);return!0}return!1});let ce=Oar({observation:le.observation.status,reconnect:le.reconnect,onObservationUnavailable:w,rebindService:b,lastReplyAt:be}),[de,Se]=ti(!1);Vn(()=>{if(ce===void 0)Se(!1)},[ce===void 0]);let Oe=ce===void 0?xe:[],he=ITt(ee,{commands:e,initialTheme:c,initialError:l,confirm:u}),{presentation:Re}=he;ZTt(Re);let{colors:Ze,surface:nt}=Re,tt=DTt({source:d,commands:e}),{status:kt,refresh:Pt}=qTt({source:p,commands:e,dialog:ee,colors:Ze});Vn(()=>{if(p!==void 0)Pt()},[p,le.status,le.commandId,Pt]),far({commands:e,refreshModels:tt.refresh,refreshColors:Re.refresh,hostSources:h});let ct=Cft({commands:e,origin:"slash",keys:{scroll:"PgUp/PgDn",queue:"Tab"},busy:Nar.has(le.status),interactionStore:t,showCommands:async()=>{let bn=await e.execute({namespace:"shell",id:"command-line"},{origin:"slash"});if(bn.status!=="handled")throw Error(bn.status==="failed"?bn.error.message:"Commands are unavailable.")}}),{store:Ft}=ct,kn=ct.interactions.inspection,Ut=kn===void 0?void 0:xe.find((bn)=>bn.entryId===kn.entryId)?.value.panel.find((bn)=>bn.id===kn.rowId&&bn.inspection!==void 0);Z.current=Ut!==void 0;let Ir=Or(null),lt=Ut?.inspection?.rows,{width:Zt,height:Kn}=JTt(),[yr,dt]=ti();Ah(()=>{if(lt===void 0)return;let bn=L.rendering.afterFrame(()=>{let vi=Ir.current;if(vi!==null)dt({rows:lt,width:Zt,height:vi.scrollHeight})});return L.rendering.requestFrame(),bn},[L.rendering,lt,Zt]);let Qt=Math.max(1,Math.min(12,Math.floor(Kn/2)-1,yr!==void 0&&yr.rows===lt&&yr.width===Zt?yr.height:lt?.length??1)),gn=[Ut?.inspection?.title,Ut?.detail].filter(Boolean).join(" \xB7 "),In="\u2191/\u2193 scroll \xB7 Esc back to draft";E6((bn)=>{if(!j||ee.isOpen||ct.interactions.open!==void 0||Ut===void 0)return!1;if(bn.name==="escape")return Ft.inspect(void 0),!0;let vi=bn.name==="up"||bn.name==="pageup"?-1:bn.name==="down"||bn.name==="pagedown"?1:0;if(vi===0)return!1;return Ir.current?.scrollBy(vi,bn.name.startsWith("page")?"viewport":"step"),!0}),Vn(()=>{if(E!==void 0)Ft.report({tone:"error",message:E});else if(A!==void 0)Ft.report({tone:"info",message:A})},[E,A,Ft]);let xn=kft(ct.awaiting,ie.draft),nr=Or(void 0),rr=()=>{let bn=nr.current;if(bn===void 0)return!1;return bn(),!0};E6((bn)=>{if(ee.isOpen||!j||Z.current)return!1;if(bn.name==="up"&&bn.meta&&ct.awaiting.total>0)return ct.store.awaiting.focus(),!0;return!1});let zr=Zt-2,Qr={store:ct.store,enabled:j,home:Jnr(),width:zr,noteLimit:u3e,onFailure:s1o};kDe({...Qr,source:n}),kDe({...Qr,source:HTt({session:s,enabled:j})}),jTt({dialog:ee,colors:Ze,slash:ct,inputHandoff:x,enabled:j});let Li=1,Su=Or(ie.draft);Su.current=ie.draft;let Wt=Or(ct);Wt.current=ct;let[_n,Pn]=ti(0),[Vr,qr]=ti(0);dar({session:s,commands:e,resume:g,create:_,onForked:y,onTitled:m});let ri=le.status==="idle"?xe.find(({value:bn})=>bn.waiting!==null):void 0,Wr=B.queued.prompts.length>0||le.viewState.kind==="queued",lo=ct.interactions.notice,pt=car({notice:lo!==void 0,dismissNotice:()=>{Ft.report(void 0)},commandId:le.commandId,status:le.status,queued:Wr,waitingLabel:ri?.value.waiting?.cancel.label,interaction:X.selecting?"actions":ee.isOpen||xn!==void 0||ct.interactions.open!==void 0||Ut!==void 0||ct.open?"prompt":null,cancel:ie.cancel,stopAll:z,onCancelFailure:(bn)=>{Ft.report({tone:"error",message:`Cancellation could not reach the session: ${bn instanceof Error?bn.message:String(bn)}. Press Ctrl+C again to exit; you can resume later.`})},cancelWaiting:async()=>{if(!Wr&&ri?.value.waiting!==null&&ri?.value.waiting!==void 0){await X.execute(ri.entryId,ri.value.waiting.cancel,!0);return}await ie.cancel()},exit:i,dismissInteraction:()=>ee.dismiss()||rr()||(ct.open||ct.interactions.open!==void 0||Ut!==void 0)&&Wt.current.dismiss()}),Tt=ie.failure==="failed"||ie.failure==="interrupted"||ie.failure==="admission",vt=le.viewState.kind==="error"&&ie.failure!=="admission";uar({serviceStatusOpen:ce!==void 0,showServiceStatus:()=>{Se(!1)},collapseServiceStatus:()=>{if(ce===void 0||de)return!1;return Se(!0),!0},canCancel:le.status!=="queued"&&Nar.has(le.status),canRetry:Tt,canContinue:vt,commands:e,application:r,cancellation:pt,stopAll:z,reconnect:le.reconnect,retry:()=>{if(!Tt)return!1;return ie.retry(),!0},continue:async()=>{if(!vt)return!1;return await s.command({type:"prompt",delivery:"followUp",requestId:a1o.request.generate(),text:"Continue the previous task. First address the error that stopped it."}),!0},details:()=>{Pn((bn)=>bn+1)},toolGroup:()=>{qr((bn)=>bn+1)}});let ur=Math.max(1,Math.min(6,Math.floor(Kn/3))),jn=pt.pending?{kind:"cancelling"}:le.viewState,Tr=xe.flatMap(({value:bn},vi)=>bn.chips.map((Xs)=>({chip:Xs,entryOrder:vi}))).sort((bn,vi)=>bn.chip.order-vi.chip.order||bn.entryOrder-vi.entryOrder),to=(Y.length>0||ct.awaiting.total>0)&&(jn.kind==="idle"||jn.kind==="waiting_for_you"),gt=tt.selectedModel??B.model,Nr=gt===void 0?void 0:FZ(gt,tt.selectedReasoning),pe=Ykt({width:Zt-2*Li,status:`\u25CF ${I7e(jn,to)}`,compactStatus:`\u25CF ${I7e(jn,to)}`,model:Nr,context:le.context===void 0?void 0:g9e(le.context)}),Jr=Nr,mi=tt.signInRequired,Vt=ys(()=>({model:Jr,folder:f,signInRequired:mi}),[Jr,f,mi]),Eo=c1o[jn.kind],Pu=ys(()=>[{slot:"state",order:0,text:pe.statusText,tone:Eo},{slot:"model",order:1,text:pe.modelText,tone:"muted"},...kt===void 0?[]:[{slot:"chips",order:0,text:kt.mode==="full-access"?"full access":kt.mode==="workspace"?"workspace \xB7 sandboxed":"read-only \xB7 sandboxed",tone:kt.available?"muted":"warning"}]],[pe.statusText,pe.modelText,Eo,kt]);return Ege(Pu),Gn("box",{position:"relative",backgroundColor:Ze.background,flexDirection:"column",height:"100%",width:"100%",children:[je(Rar,{emptyState:Vt,detailsRequest:_n,groupRequest:Vr,inputEnabled:j&&!ee.isOpen&&Ut===void 0,presentation:Re,sessionAddress:s.address,terminalWidth:Zt}),Gn("box",{flexShrink:0,children:[ct.open&&!ee.isOpen&&xn===void 0?je(GTt,{slash:ct,colors:Ze,maxRows:ur,width:Zt-2}):null,xn===void 0?null:je(eAt,{item:xn,position:ct.awaiting.position,total:ct.awaiting.total,onLater:()=>{ct.store.awaiting.later(xn.key)},colors:Ze,surface:nt,width:Zt-2*Li,rows:Kn,active:j&&!ee.isOpen,escapeRef:nr},xn.key),Gn("box",{flexDirection:"row",backgroundColor:nt,paddingX:1,paddingY:1,visible:xn===void 0,children:[Gn("text",{fg:Ze.primary,width:2,flexShrink:0,children:["\u203A"," "]}),je(ear,{focused:j&&!ee.isOpen&&!ye&&xn===void 0,readOnly:ie.recallState.kind==="recalling",inputHandoff:x,maxHeight:ur,colors:Ze,onKeyDown:(bn)=>{let vi=Wt.current;if(j&&!ee.isOpen&&!ye&&!vi.open&&bn.name==="up"&&bn.eventType==="press"&&!bn.repeated&&!bn.ctrl&&!bn.meta&&!bn.shift&&!bn.option&&!bn.super&&!bn.hyper&&Su.current===""&&(ie.images?.length??0)===0){bn.preventDefault(),ie.recall();return}if(bn.name==="tab"&&!bn.shift&&!bn.ctrl&&!bn.meta){if(bn.preventDefault(),vi.open)vi.complete();else if(!Su.current.startsWith("/"))vi.submit("followUp");return}if(vi.open&&(bn.name==="up"||bn.name==="down"))bn.preventDefault(),vi.move(bn.name==="up"?-1:1)},onChange:(bn)=>{Su.current=bn,ie.setDraft(bn)},onSubmit:()=>{Wt.current.submit("steer")},value:ie.draft})]}),ie.admissionError!==void 0?je(t_e,{color:Ze.warning,inset:Li,children:ie.admissionError==="offline_queue_full"?"One prompt is already queued; it sends when the service is back.":"Too many prompts are still awaiting admission. Try again shortly."}):null,ie.recallState.kind==="recalling"?je("text",{fg:Ze.foreground,attributes:2,children:"Recalling queued message\u2026"}):null,(ie.images?.length??0)>0?Gn("text",{fg:Ze.foreground,attributes:2,children:[String(ie.images?.length)," attached image(s)"]}):null,je(kge,{inset:Li}),Oe.map(({entryId:bn,value:vi})=>{let Xs=vi.panel.length>0?vi.panel:Tr.filter((on)=>xe[on.entryOrder]?.entryId===bn).map(({chip:on})=>on.row),Ya=Xs.filter((on)=>!(kn?.entryId===bn&&kn.rowId===on.id)&&!Y.some((sr)=>sr.entryId===bn&&sr.row===on)),yc=Xs.flatMap((on)=>{let sr=JSON.stringify([bn,on.id]);if(!fe({...on})||sr===xn?.key)return[];let qi=ct.awaiting.items.findIndex((Yt)=>Yt.key===sr),xr=[qi>=0&&ct.awaiting.total>1?`${String(qi+1)} of ${String(ct.awaiting.total)}`:void 0,"Alt+\u2191 answer"].filter(Boolean).join(" \xB7 ");return[{...on,title:_c(br(on.title),Math.max(1,Zt-2*Li-Tp-Dv(xr)-3)),detail:xr}]}),Hc=K.omitted.find((on)=>on.entryId===bn),Mu=Xs.length===0?[]:[...Hc===void 0?[]:[{id:`omitted:${bn}`,title:`${String(Hc.count)} earlier change${Hc.count===1?"":"s"} omitted`,tone:"muted"}],...K.unanchored.filter((on)=>on.entryId===bn).flatMap(({cell:on})=>on.rows.map((sr)=>({...sr,id:`unanchored:${on.id}:${sr.id}`})))],hl=te?.entryId===bn?te.row:void 0,Yu=hl===void 0?[]:[{...hl,title:`${V.length>1?`${String(J+1)}/${String(V.length)} \xB7 `:""}${hl.title}`,detail:[hl.detail,ye?`Enter ${hl.actions?.[0]?.label.toLowerCase()??"select"}${V.length>1?" \xB7 \u2191/\u2193 cycle":""} \xB7 Esc back to draft`:`Alt+\u2191 ${hl.actions?.[0]?.label.toLowerCase()??"select"}`].filter(Boolean).join(" \xB7 ")}];return Ya.length===0&&Yu.length===0&&yc.length===0&&Mu.length===0?null:je(cZ,{id:`client-panel:${JSON.stringify([R,bn])}`,rows:[...Ya,...Mu,...Yu,...yc],presentation:Re,compactWidth:Zt-2*Li,expandedRowId:hl?.id,focusedRowId:ye?hl?.id:void 0,onOpen:a===void 0?void 0:(on)=>{Promise.resolve(a(on)).catch((sr)=>{xi("client-row-open",sr)})}},bn)}),Ut?.inspection===void 0?null:Gn("box",{flexDirection:"column",flexShrink:1,height:Qt+1,children:[Gn("box",{flexDirection:"row",justifyContent:"space-between",marginX:Li,height:1,children:[je("text",{fg:Ze.foreground,wrapMode:"none",children:_c(br(gn),Math.max(0,Zt-4-Dv(In)))}),je("text",{fg:Ze.foreground,attributes:2,wrapMode:"none",children:In})]}),je("scrollbox",{ref:Ir,height:Qt,flexShrink:0,contentOptions:{minHeight:0,flexGrow:0},scrollX:!1,horizontalScrollbarOptions:{visible:!1},scrollbarOptions:{showArrows:!1},children:je(cZ,{rows:Ut.inspection.rows,presentation:Re})})]}),he.error?je(t_e,{color:Ze.error,inset:Li,children:br(he.error)}):null,lo!==void 0&&!ee.isOpen?je(t_e,{color:Ze[u1o[lo.tone]],inset:Li,children:br(lo.message)}):null,tt.loginNotice!==void 0&&!ee.isOpen?je(t_e,{color:Ze.info,inset:Li,children:tt.loginNotice}):null,ce!==void 0&&de?je(t_e,{color:Ze.warning,inset:Li,oneLine:!0,children:ce.phase==="incompatible"?`${ce.message} \xB7 Ctrl+B shows details`:ce.phase==="stuck"&&ce.alive===!1?"The service stopped. Run `fungi resume`. \xB7 Ctrl+B shows details":ce.phase==="stuck"&&ce.alive===!0?`Service busy (no reply for ${String(ce.seconds)}s) \xB7 Ctrl+B shows details`:"Reconnecting to the service... \xB7 Ctrl+B shows details"}):null]}),ce===void 0||de?null:je(Par,{view:ce,viewport:{width:Zt,height:Kn},colors:Ze,onClose:()=>{Se(!0)}})]})}var a1o,c1o,Nar,u1o;var Far=C(async()=>{qc();bf();bf();Gi();par();mar();$Ct();await Mc([Xa(),Xa(),qCt(),Xa(),Xa(),tar(),lar(),Xa(),Xa(),Xa(),Xa(),Xa(),Xa(),Xa(),Dar(),Xa(),Mar()]);a1o=Ha({family:"tui-error-recovery",version:1,kinds:{request:{prefix:"request"}}}),c1o={idle:"success",waiting_for_you:"success",responding:"success",sending:"success",streaming:"success",thinking:"warning",queued:"warning",retrying:"warning",cancelling:"warning",running_tool:"warning",compacting:"warning",connecting:"warning",disconnected:"error",error:"error"};Nar=new Set(["cancelling","queued","retrying","sending","streaming","thinking"]),u1o={info:"info",success:"success",error:"error"}});var D7e,$ar,d1o,p1o,zar;var Uar=C(async()=>{Gi();await Mc([Xa(),Far(),Xa()]);D7e=D().min(1).max(256),$ar=D().max(4096).optional(),d1o=Nt([se({kind:Ee("conversation"),agentId:D7e,sessionId:D7e,title:$ar}),se({kind:Ee("conversation"),agentId:D7e,sessionId:oh(),createRequestId:D7e,title:$ar})]),p1o=Ha({family:"tui-session-create-request",version:1,kinds:{request:{prefix:"request"}}}),zar={kind:"conversation",instantiate:(e)=>{let t=d1o.safeParse(e);if(!t.success)return;let n=t.data,r=n.title?.trim(),i=r===void 0||r.length===0?void 0:r;return{key:n.sessionId===null?JSON.stringify([n.agentId,null,n.createRequestId]):JSON.stringify([n.agentId,n.sessionId]),title:i??"New conversation",render:async(o)=>{let s,a=await o.sessions.acquire(n,o.signal);if(o.signal.aborted)return null;let c=n.sessionId??(await a.read()).sessionId;o.signal.throwIfAborted();let u=o.sessions.describe?.(a),l=u?.resume,d=u?.forked,p=u?.observationUnavailable,f=u?.agentName?.trim(),h=`${f===void 0||f.length===0?"Agent":f} \xB7 New conversation`;o.setTitle(i??h);let g=async()=>{let w=(await u?.sessionTitle?.(o.signal))?.trim();if(!o.signal.aborted)o.setTitle(w===void 0||w.length===0?h:w)},_=YTt(o),y=Age(_,{exit:void 0,ctrlC:()=>(o.exit(),Promise.resolve())});return o.onDispose(y.dispose),ul(l7,{kit:o},ul(Lar,{session:a,draftIdentity:{agentId:n.agentId,sessionId:c},commands:_,applicationCommands:{lease:y,exit:o.exit},onExit:o.exit,initialTheme:u?.themeName,onThemeConfirm:u?.saveTheme,themeError:u?.themeError,clients:u?.clients,interactionStore:u?.interactions,mcpApprovals:u?.mcpApprovals,modelSource:u?.models,sandboxSource:u?.sandbox,onStopAll:u?.stopAll,folder:u?.folder,onTitled:async(x)=>{if(x===null)await g();else o.setTitle(x)},reloadSources:u?.reload,initialCommandError:u?.initialError,initialCommandNotice:u?.initialNotice,onObservationUnavailable:p===void 0?void 0:()=>p(o.paneId),onRebindService:u?.rebindService,inputHandoff:u?.inputHandoff,onResume:l===void 0?void 0:()=>l(o.paneId),onNew:async()=>{s??=p1o.request.generate();let x=await o.replace({kind:"conversation",agentId:n.agentId,sessionId:null,createRequestId:s});if(x.kind==="refused")throw Error(x.reason);s=void 0},onForked:d===void 0?(x)=>o.replace({kind:"conversation",agentId:n.agentId,sessionId:x}).then((w)=>{if(w.kind==="refused")throw Error(w.reason)}):(x)=>d(x,o.paneId),onOpen:(x)=>o.open({kind:"conversation",...Rge(x)}).then((w)=>{if(w.kind==="refused")o.toast({variant:"error",duration:"until-dismissed",message:w.reason})})}))}}}}});var jar;var Bar=C(async()=>{await Mc([Xsr(),Uar(),_At()]);jar=[zar,Qsr,irr]});function qar(e,t){let n=[...new Set(t)].flatMap((o)=>e.filter((s)=>s.commandId===o)).slice(0,3),r=new Set(n.map((o)=>o.commandId)),i=(o,s=o.category)=>({commandId:o.commandId,command:o.command,name:o.title,description:o.description,group:s});return[...n.map((o)=>i(o,"Recent")),...e.filter((o)=>!r.has(o.commandId)).map((o)=>i(o))]}function Har(e){let t=Or(e);t.current=e;let n=Or([]),r=(s)=>{Promise.resolve().then(s).catch((a)=>(t.current.toast({variant:"error",duration:"until-dismissed",message:"Pane command failed. Try again."}),xi("pane-shell-command",a)))},i=(s)=>{let{commandId:a}=s;r(async()=>{let c=await t.current.host.execute(s.command,{origin:"keyboard"});if(c.status==="handled")n.current=[a,...n.current.filter((u)=>u!==a)].slice(0,3);else t.current.toast({variant:"error",duration:"until-dismissed",message:c.status==="failed"?Qb(c.error.message):"Pane command is unavailable."})})},o=()=>{let s=t.current,a=qar(s.host.active().palette,n.current);s.dialog.show((c)=>je(Wp,{title:"Commands",colors:s.colors,searchable:!0,descriptionWrap:!1,collapsedGroups:["Panes","Advanced"],collapsedLabel:"More commands",visibleLimit:6,rowLimit:9,choices:a,onCancel:c.dismiss,onSelect:(u)=>{let l=a[u];if(l!==void 0)c.dismiss(),i(l)}}))};Vn(()=>{let s=()=>t.current.registry.read().find((m)=>m.focused)?.paneId,a=(m)=>{let h=t.current.registry.read(),g=h.findIndex((_)=>_.focused);return h[(g+m+h.length)%h.length]?.paneId},c=(m)=>{let h=a(m);if(h!==void 0)t.current.registry.focus(h)},u=(m)=>{let h=s(),g=a(m);if(h!==void 0&&g!==void 0)t.current.registry.swap(h,g)},l=(m,h,g,_,y,x)=>({description:x,id:m,title:h,category:"Panes",projections:{bindings:{values:g,order:_},palette:{order:10+_},help:{order:_}},handler:y}),d=[{id:"open-app",title:"Open pane",category:"Panes",description:"Choose a terminal, program, conversation or App.",projections:{bindings:{values:["<leader>o"],order:0},palette:{order:0}},handler:()=>{r(t.current.openPane)}},{id:"show-command-palette",title:"Show commands",category:"Panes",handler:o},{id:"command-line",title:"All commands",category:"Panes",projections:{bindings:{values:["<leader><leader>","<leader>:"],order:7}},handler:o},l("zoom","Zoom pane",["alt+enter","<leader>z"],2,()=>{let m=s();if(m!==void 0)t.current.registry.toggleZoom(m)},"Alt+Enter inserts a newline in the composer; Ctrl K z zooms from there."),l("focus-previous","Focus left",["alt+left","<leader>h"],3,()=>{c(-1)}),l("focus-next","Focus right",["alt+right","<leader>l"],4,()=>{c(1)}),l("swap-previous","Move pane left",["alt+shift+left","<leader>{"],5,()=>{u(-1)}),l("swap-next","Move pane right",["alt+shift+right","<leader>}"],6,()=>{u(1)}),{id:"pane-close",title:"Close pane",category:"Panes",projections:{palette:{order:1},bindings:{values:["<leader>x"],order:1}},handler:()=>{let m=s();return m===void 0?Promise.resolve():t.current.registry.close(m)}},...[["beside",["<leader>v","<leader>%"]],["below",["<leader>s",'<leader>"']]].map(([m,h])=>({id:`pane-open-${m}`,title:`Open pane ${m}`,category:"Panes",projections:{palette:{order:1},bindings:{values:[...h],order:12}},handler:()=>{r(()=>t.current.openPane(m))}})),...[["main-left","Main on left"],["main-top","Main on top"],["columns","Equal columns"],["rows","Equal rows"],["grid","Grid"]].map(([m,h])=>({id:`layout-${m}`,title:`Layout: ${h}`,category:"Panes",projections:{palette:{order:2}},handler:()=>{t.current.registry.setLayout(m)}})),{id:"layout-next",title:"Next layout",category:"Panes",projections:{palette:{order:2},bindings:{values:["<leader> "],order:8}},handler:()=>{t.current.registry.cycleLayout()}},...[-4,4].map((m)=>({id:m<0?"pane-shrink":"pane-grow",title:m<0?"Shrink main pane":"Grow main pane",category:"Panes",projections:{palette:{order:3},bindings:{values:[m<0?"<leader><":"<leader>>"],order:m<0?9:10}},handler:()=>{t.current.registry.resizeBy(m)}})),{id:"pane-equalize",title:"Equalize panes",category:"Panes",projections:{palette:{order:3},bindings:{values:["<leader>="],order:11}},handler:()=>{t.current.registry.equalize()}}],p=new Set(d.flatMap((m)=>(m.projections?.bindings?.values??[]).map(War))),f=t.current.registry.launchers.flatMap((m)=>{if(m.binding===void 0)return[];let h=War(m.binding),g=!p.has(h);if(g)p.add(h);else xi("pane-launcher-binding-taken",Error(`${m.target.kind} asked for ${m.binding}, which is taken`));return[{id:`open-${m.target.kind.replaceAll(":","-")}`,title:`Open ${m.name.toLowerCase()}`,category:"Panes",description:m.description,projections:g?{bindings:{values:[m.binding],order:13},palette:{order:1}}:{palette:{order:1}},handler:()=>{r(async()=>{let _=await t.current.registry.open(m.target,!0,{direction:"beside",afterPaneId:s()??null});if(_.kind==="refused")t.current.toast({variant:"error",message:_.reason})})}}]});return e.host.registerShellCommands([...d,...f])},[e.host,e.registry])}function War(e){return e.trim()}var Gar=C(async()=>{qc();QJ();Gi();await Xa()});function nO(e){let t=e,n=new Set;return{value:{read:()=>t,subscribe:(i)=>(n.add(i),()=>{n.delete(i)})},set:(i)=>{if(Object.is(t,i))return;t=i;for(let o of n)o()},clear:()=>{n.clear()}}}function f1o(e,t,n,r){console.error(`App window ${n} failed`,{windowId:e,generation:t,phase:n},uh(r))}function m1o(e,t){return JSON.stringify(e)===JSON.stringify(t)}function h1o(e,t){if(e===null||t===null)return e===t;return e.canGoBack===t.canGoBack&&e.canGoForward===t.canGoForward&&e.title===t.title&&JSON.stringify([e.crumbs,e.primary,e.menu,e.status])===JSON.stringify([t.crumbs,t.primary,t.menu,t.status])}function Var(e){let t=(J,te,ye,ce)=>{if(e.onFailure!==void 0)e.onFailure({windowId:J,generation:te,phase:ye,cause:ce});else f1o(J,te,ye,ce)},n=new Map,r=new Set,i=new Set,o=new Map,s=!1,a,c=(J,te)=>{let ye=n.get(J)?.generation??null,de=(o.get(J)??Promise.resolve()).then(te),Se=de.then(()=>{if(o.get(J)===Se)o.delete(J)},(Oe)=>{if(t(J,ye,"mutation",Oe),o.get(J)===Se)o.delete(J)});return o.set(J,Se),de},u=()=>({windows:Array.from(n.values(),(J)=>{let te={windowId:J.launch.windowId,launch:J.launch,container:J.container,status:J.status,generation:J.generation,navigation:J.status==="ready"?J.navigation:null,statusItems:J.statusItems},ye=J.error===void 0?te:{...te,error:J.error};return J.cleanupError===void 0?ye:{...ye,cleanupError:J.cleanupError}})}),l=u(),d=()=>{l=u();for(let J of Array.from(i))J()},p=()=>l,f=(J)=>n.get(J.launch.windowId)===J,m=(J)=>f(J)&&!J.controller.signal.aborted&&!J.retiring&&!J.disposed,h=(J)=>J.closeRequested,g=(J,te)=>f(J)&&!J.disposed&&J.visibilityVersion===te,_=(J,te)=>te.signal.aborted||h(J)||!m(J),y=(J)=>{if(r.delete(J),!J.retiring)J.retiring=!0,J.controller.abort();for(let te of J.attachmentWaiters)te(!1);J.attachmentWaiters.clear()},x=async(J)=>{if(J.disposed)return;if(J.disposal){await J.disposal;return}for(let ye of J.attachmentWaiters)ye(!1);J.attachmentWaiters.clear();let te=(async()=>{if(!J.host&&J.mountPromise)await J.mountPromise;let ye=J.host;if(!ye){J.disposed=!0;return}let ce=J.hostOperation;if(ce)try{await ce}catch(de){if(J.error===void 0)J.status="error",J.error=de,d()}if(await ye.dispose(),J.host===ye)J.host=void 0;J.disposed=!0})();J.disposal=te;try{await te}catch(ye){throw J.disposal=void 0,J.cleanupError=ye,d(),ye}},w=async(J,te)=>{try{await te.dispose()}catch(ye){if(J.cleanupError=ye,f(J)&&J.error===void 0)J.status="error",J.error=ye,d();throw ye}},b=async(J,te,ye)=>{let ce=Promise.resolve().then(()=>te.setVisibility(ye));J.hostOperation=ce;try{await ce}finally{if(J.hostOperation===ce)J.hostOperation=void 0}},E=async(J,te)=>{if(!g(J,te)||J.retiring)return;let ye=J.host;if(!ye)return;let ce=J.visibility;try{await b(J,ye,ce)}catch(de){if(!g(J,te))return;J.status="error",J.error=de,d();try{await x(J)}catch(Se){throw J.cleanupError=Se,d(),Se}}},A=async(J)=>{if(performance.mark("fungi.app-open.window-mount-start"),e.waitForAttachment&&!e.isAttached?.(J.container)){if(performance.mark("fungi.app-open.window-wait-for-attachment"),!await new Promise((ce)=>{J.attachmentWaiters.add(ce)}))return;performance.mark("fungi.app-open.window-attached")}let te;try{performance.mark("fungi.app-open.window-host-mount-start"),te=await e.mount(J.container,J.launch,J.controller.signal,{onDeliveryPending:()=>{if(!m(J)||J.deliveryPending)return;J.deliveryPending=!0,J.status=J.visibility==="hidden"?"minimized":"getting-ready",d()},onComputerChoice:()=>Promise.resolve().then(()=>{if(!m(J)||J.status!=="ready"||J.computerChoice===void 0)throw new vg("Computer choice is unavailable for this window",{code:"CAPABILITY_DENIED",retryable:!1});J.computerChoice()}),onNavigationState:(ye)=>{if(!m(J)||h1o(J.navigation,ye))return;J.navigation=ye,d()},onStatusItems:(ye)=>{if(!m(J)||m1o(J.statusItems,ye))return;J.statusItems=ye,d()}}),performance.mark("fungi.app-open.window-host-mount-ready")}catch(ye){if(!m(J)){if(ye!==J.controller.signal.reason)t(J.launch.windowId,J.generation,"mount",ye);return}J.status=J.visibility==="hidden"?"minimized":"error",J.error=ye,d();return}if(!m(J)){await w(J,te);return}if(J.host=te,J.visibility==="hidden")await E(J,J.visibilityVersion);if(!m(J)){await x(J);return}if(J.status!=="error")J.status=J.visibility==="hidden"?"minimized":"ready",J.error=void 0,J.cleanupError=void 0,d()},R=(J)=>{let te=A(J);return J.mountPromise=te,te.catch((ye)=>{t(J.launch.windowId,J.generation,"mount",ye);return}),te},L=(J,te)=>({launch:J,container:e.createContainer(J),generation:te,status:"loading",deliveryPending:!1,controller:new AbortController,host:void 0,disposed:!1,retiring:!1,disposal:void 0,mountPromise:void 0,hostOperation:void 0,reconfigureController:void 0,closeRequested:!1,error:void 0,cleanupError:void 0,visibility:"visible",attachmentWaiters:new Set,visibilityVersion:0,navigation:null,statusItems:[],computerChoice:void 0}),z=(J)=>{let te=n.get(J.windowId),ye=!s&&!te?L(J,1):void 0,ce;if(ye)n.set(J.windowId,ye),d(),ce=R(ye);return c(J.windowId,async()=>{if(s){if(ye&&n.get(J.windowId)===ye)y(ye),await x(ye),n.delete(J.windowId),d();return}let Se=n.get(J.windowId);if(ye){if(Se!==ye)return;return}if(Se){if(ce=Se.mountPromise,Se.visibility==="hidden"&&!Se.retiring){let he=++Se.visibilityVersion;if(Se.visibility="visible",Se.status=Se.error!==void 0?"error":Se.host?"ready":Se.deliveryPending?"getting-ready":"loading",d(),Se.error===void 0)await E(Se,he)}else d();return}let Oe=L(J,1);n.set(J.windowId,Oe),d(),ce=R(Oe)}).then(async()=>{if(ce)await ce})},j=(J)=>{if(s)return;let te=n.get(J);if(!te||te.disposed||te.retiring)return;for(let ye of te.attachmentWaiters)ye(!0);te.attachmentWaiters.clear()},G=(J,te)=>{let ye=n.get(J);if(s)return Promise.resolve();if(ye&&!ye.retiring&&ye.error!==void 0)return ye.visibility=te,ye.status=te==="hidden"?"minimized":"error",d(),Promise.resolve();if(!ye||ye.disposed||ye.retiring||ye.status==="error")return c(J,async()=>{let de=n.get(J);if(!de||de.disposed||de.retiring||de.status==="error")return;let Se=++de.visibilityVersion;de.visibility=te,de.status=te==="hidden"?"minimized":de.host?"ready":de.deliveryPending?"getting-ready":"loading",d(),await E(de,Se)});let ce=++ye.visibilityVersion;return ye.visibility=te,ye.status=te==="hidden"?"minimized":ye.host?"ready":ye.deliveryPending?"getting-ready":"loading",d(),c(J,()=>E(ye,ce))},ee=(J)=>G(J,"hidden"),ie=(J)=>G(J,"visible"),le=async()=>{if(s)return;let J=[...n.values()].filter((te)=>!te.retiring&&te.visibility==="visible");for(let te of J)r.add(te);await Promise.all(J.map((te)=>ee(te.launch.windowId)))},be=async()=>{let J=[...r];r.clear(),await Promise.all(J.filter((te)=>n.get(te.launch.windowId)===te).map((te)=>ie(te.launch.windowId)))},xe=async(J)=>{if(s)return!0;let te=J.host?.requestClose;if(!te)return!0;try{return await te()}catch(ye){if(f(J))J.status="error",J.error=ye,d();throw ye}},B=(J)=>{let te=n.get(J),ye=te!==void 0;if(te?.reconfigureController?.abort(),te)te.closeRequested=!0;return c(J,async()=>{if(!ye)return;let ce=n.get(J);if(!ce)return;let de;try{de=await xe(ce)}catch(Se){throw ce.closeRequested=!1,Se}if(!de){ce.closeRequested=!1;return}y(ce);try{await x(ce)}catch(Se){if(f(ce)){if(ce.status="error",ce.error===void 0)ce.error=Se;ce.cleanupError=Se,d()}throw Se}if(!f(ce))return;n.delete(J),d()})},K=(J,te)=>c(J,async()=>{if(s)return;let ce=n.get(J);if(!ce||ce.disposed||ce.retiring)return;if(h(ce))return;let de={...te(ce.launch),windowId:J};if(e.validateReconfiguration?.(ce.launch,de),e.isChromeOnlyChange?.(ce.launch,de)===!0){ce.launch=de,d();return}let Se=new AbortController;ce.reconfigureController=Se;try{let Oe=ce.mountPromise;if(!ce.host&&Oe)await Fa(ii({try:()=>Oe,catch:(Ze)=>Ze}),{signal:Se.signal});if(_(ce,Se))return;let he=ce.host;if(!he)throw Error("The App host is not ready for reconfiguration.");let Re=Promise.resolve().then(()=>he.reconfigure(de,Se.signal));ce.hostOperation=Re;try{await Re}finally{if(ce.hostOperation===Re)ce.hostOperation=void 0}if(_(ce,Se))return;ce.launch=de,ce.status=ce.visibility==="hidden"?"minimized":"ready",ce.error=void 0,ce.cleanupError=void 0,d()}catch(Oe){if(_(ce,Se))return;throw Oe}finally{if(ce.reconfigureController===Se)ce.reconfigureController=void 0}}),X=(J,te)=>K(J,()=>te),Y=(J,te)=>{let ye;return c(J,async()=>{if(s)return;let de=n.get(J),Se=!1;if(de){if(!await xe(de))return;Se=r.has(de),y(de);try{await x(de)}catch(Re){if(f(de)){if(de.status="error",de.error===void 0)de.error=Re;de.cleanupError=Re,d()}throw Re}}let Oe={...te,windowId:J},he=L(Oe,de?de.generation+1:1);if(de?.visibility==="hidden")he.visibility="hidden",he.status="minimized";if(Se)r.add(he);n.set(J,he),d(),ye=R(he)}).then(async()=>{if(ye)await ye})},fe=async(J)=>{let te=n.get(J);if(!te||!m(te)||te.status!=="ready"||te.navigation?.canGoBack!==!0)return!1;let ye=te.host?.requestBack;return ye?await ye():!1},V=async(J)=>{let te=n.get(J);if(!te||!m(te)||te.status!=="ready"||te.navigation?.canGoForward!==!0)return!1;let ye=te.host?.requestForward;return ye?await ye():!1},Z=async(J,te)=>{let ye=n.get(J);if(!ye||!m(ye)||ye.status!=="ready")return!1;if(ye.navigation===null||!cat(ye.navigation,te))return!1;let ce=ye.host?.activateNavigation;return ce?await ce(te):!1},ue=async(J,te)=>{let ye=n.get(J);if(!ye||!m(ye)||ye.status!=="ready")return!1;if(!Zst(ye.statusItems,te))return!1;let ce=ye.host?.activateStatus;return ce?await ce(te):!1},Le=(J,te)=>{let ye=n.get(J);if(!ye||!m(ye))throw new vg("App window is unavailable",{code:"DISCONNECTED",retryable:!1});return ye.computerChoice=te,()=>{if(ye.computerChoice===te)ye.computerChoice=void 0}},ve=async()=>{s=!0;for(let J of n.values())J.closeRequested=!0,J.reconfigureController?.abort();try{await Promise.allSettled(o.values());let J=[],te=await Promise.allSettled([...n.keys()].map((ye)=>B(ye)));for(let ye of te)if(ye.status==="rejected")J.push(ye.reason);if(J.length>0)throw AggregateError(J,"Failed to dispose App windows")}finally{i.clear()}};return{open:z,attach:j,minimize:ee,restore:ie,hideAll:le,restoreHidden:be,close:B,reconfigure:X,update:K,activateNavigation:Z,activateStatus:ue,registerComputerChoice:Le,replace:Y,back:fe,forward:V,dispose:()=>{if(a)return a;let J=ve();return a=J,J.then(()=>{if(a===J)a=void 0},()=>{if(a===J)a=void 0}),J},read:p,subscribe:(J)=>(i.add(J),()=>i.delete(J))}}var src;var Kar=C(()=>{$k();vr();tr();X_t();src=Hu(re({...pat.fields,retryable:Be(!0)}))});function Qar(e){return"init"in e}function JCt(e){return typeof e.write==="function"}function g1o(e){return!!e.onMount}function Jar(e){return"v"in e||"e"in e}function O7e(e){if("e"in e)throw e.e;if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&!("v"in e))throw Error("[Bug] atom state is not initialized");return e.v}function P7e(e){return typeof(e==null?void 0:e.then)==="function"}function _1o(e){if(!(e instanceof Error))return!1;let t=e.name,n=e.message.toLowerCase();return(t==="RangeError"||t==="InternalError")&&(n.includes("call stack")||n.includes("too much recursion")||n.includes("stack overflow"))}function Xar(e,t,n){if(!n.p.has(e)){n.p.add(e);let r=()=>n.p.delete(e);t.then(r,r)}}function Yar(e,t,n){let r=n.get(e),i=r==null?void 0:r.t,o=t.p;if(!(i==null?void 0:i.size))return o;if(!o.size)return i;let s=new Set(i);for(let a of o)s.add(a);return s}function y1o(e){return!!e.INTERNAL_onInit}function Zar(...e){let t={get(s){return r(n,t,s)},set(s,...a){return i(n,t,s,...a)},sub(s,a){return o(n,t,s,a)}},n=[new WeakMap,new WeakMap,new WeakMap,new Set,new Set,new Set,{},x1o,v1o,b1o,w1o,S1o,E1o,k1o,T1o,A1o,C1o,I1o,R1o,D1o,O1o,P1o,M1o,N1o,void 0,new WeakMap,L1o,F1o,[0]].map((s,a)=>e[a]||s);$1o.set(t,Object.freeze(n));let r=n[21],i=n[22],o=n[23];return t}var x1o=(e,t,n,...r)=>n.read(...r),v1o=(e,t,n,...r)=>n.write(...r),b1o=(e,t,n)=>n.INTERNAL_onInit(t),w1o=(e,t,n,r)=>{var i;return(i=n.onMount)==null?void 0:i.call(n,r)},S1o=(e,t,n)=>{var r;let i=e[0],o=i.get(n);if(!o){let s=e[6],a=e[9];if(o={d:new Map,p:new Set,n:0},i.set(n,o),(r=s.i)==null||r.call(s,n),y1o(n))a(e,t,n)}return o},E1o=(e,t)=>{var n;let r=e[1],i=e[3],o=e[4],s=e[5],a=e[6],c=e[13];if(!a.f&&!i.size&&!o.size&&!s.size)return;let u=[],l=(d)=>{try{d()}catch(p){u.push(p)}};do{if(a.f)l(a.f);let d=new Set;for(let p of i){let f=(n=r.get(p))==null?void 0:n.l;if(f)for(let m of f)d.add(m)}i.clear();for(let p of s)d.add(p);s.clear();for(let p of o)d.add(p);o.clear();for(let p of d)l(p);if(i.size)c(e,t)}while(i.size||s.size||o.size);if(u.length)throw AggregateError(u)},k1o=(e,t)=>{let n=e[1],r=e[2],i=e[3],o=e[11],s=e[14],a=e[17];if(!i.size)return;let c=[],u=[],l=new WeakSet,d=new WeakSet,p=[],f=[];for(let m of i)p.push(m),f.push(o(e,t,m));while(p.length){let m=p.length-1,h=p[m],g=f[m];if(d.has(h)){p.pop(),f.pop();continue}if(l.has(h)){if(r.get(h)===g.n)c.push(h),u.push(g);else if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&r.has(h))throw Error("[Bug] invalidated atom exists");d.add(h),p.pop(),f.pop();continue}l.add(h);for(let _ of Yar(h,g,n))if(!l.has(_))p.push(_),f.push(o(e,t,_))}for(let m=c.length-1;m>=0;--m){let h=c[m],g=u[m],_=!1;for(let y of g.d.keys())if(y!==h&&i.has(y)){_=!0;break}if(_)r.set(h,g.n),s(e,t,h),a(e,t,h);r.delete(h)}},QCt,T1o=(e,t,n)=>{var r,i;let o=e[1],s=e[2],a=e[3],c=e[6],u=e[7],l=e[11],d=e[12],p=e[13],f=e[14],m=e[16],h=e[17],g=e[20],_=e[26],y=e[28],x=l(e,t,n),w=y[0];if(Jar(x)){if(o.has(n)&&s.get(n)!==x.n||x.m===w)return x.m=w,x;let le=!1;for(let[be,xe]of x.d)if(f(e,t,be).n!==xe){le=!0;break}if(!le)return x.m=w,x}let b=!0,E=new Set(x.d.keys()),A=()=>{for(let le of E)x.d.delete(le)},R=()=>{if(o.has(n)){let le=!a.size;if(h(e,t,n),le)p(e,t),d(e,t)}},L=(le)=>{var be;if(le===n){let B=l(e,t,le);if(!Jar(B))if(Qar(le))g(e,t,le,le.init);else throw Error("no atom init");return O7e(B)}let xe=f(e,t,le);try{return O7e(xe)}finally{if(E.delete(le),x.d.set(le,xe.n),P7e(x.v))Xar(n,x.v,xe);if(o.has(n))(be=o.get(le))==null||be.t.add(n);if(!b)R()}},z,j,G={get signal(){if(!z)z=new AbortController;return z.signal},get setSelf(){if((import.meta.env?import.meta.env.MODE:void 0)!=="production")console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3.");if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&!JCt(n))console.warn("setSelf function cannot be used with read-only atom");if(!j&&JCt(n))j=(...le)=>{if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&b)console.warn("setSelf function cannot be called in sync");if(!b)try{return m(e,t,n,le)}finally{p(e,t),d(e,t)}};return j}},ee=x.n,ie=s.get(n)===ee;try{if((import.meta.env?import.meta.env.MODE:void 0)!=="production")QCt.delete(t);let le=u(e,t,n,L,G);if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&QCt.has(t))console.warn("Detected store mutation during atom read. This is not supported.");if(g(e,t,n,le),P7e(le)){_(e,t,le,()=>z==null?void 0:z.abort());let be=()=>{A(),R()};le.then(be,be)}else A();return(r=c.r)==null||r.call(c,n),x.m=w,x}catch(le){if(_1o(le))throw le;return delete x.v,x.e=le,++x.n,x.m=w,x}finally{if(b=!1,x.n!==ee&&ie)s.set(n,x.n),a.add(n),(i=c.c)==null||i.call(c,n)}},A1o=(e,t,n)=>{let r=e[1],i=e[2],o=e[11],s=[n];while(s.length){let a=s.pop(),c=o(e,t,a);for(let u of Yar(a,c,r)){let l=o(e,t,u);if(i.get(u)!==l.n)i.set(u,l.n),s.push(u)}}},C1o=(e,t,n,r)=>{let i=e[3],o=e[6],s=e[8],a=e[11],c=e[12],u=e[13],l=e[14],d=e[15],p=e[16],f=e[17],m=e[20],h=e[28],g=!0,_=(x)=>O7e(l(e,t,x)),y=(x,...w)=>{var b;let E=a(e,t,x);try{if(x===n){if(!Qar(x))throw Error("atom not writable");if((import.meta.env?import.meta.env.MODE:void 0)!=="production")QCt.add(t);let A=E.n,R=w[0];if(m(e,t,x,R),f(e,t,x),A!==E.n)++h[0],i.add(x),d(e,t,x),(b=o.c)==null||b.call(o,x);return}else return p(e,t,x,w)}finally{if(!g)u(e,t),c(e,t)}};try{return s(e,t,n,_,y,...r)}finally{g=!1}},I1o=(e,t,n)=>{var r;let i=e[1],o=e[3],s=e[6],a=e[11],c=e[15],u=e[18],l=e[19],d=a(e,t,n),p=i.get(n);if(p&&d.d.size>0){for(let[f,m]of d.d)if(!p.d.has(f)){let h=a(e,t,f);if(u(e,t,f).t.add(n),p.d.add(f),m!==h.n)o.add(f),c(e,t,f),(r=s.c)==null||r.call(s,f)}for(let f of p.d)if(!d.d.has(f)){p.d.delete(f);let m=l(e,t,f);m==null||m.t.delete(n)}}},R1o=(e,t,n)=>{var r;let i=e[1],o=e[4],s=e[6],a=e[10],c=e[11],u=e[12],l=e[13],d=e[14],p=e[16],f=e[18],m=c(e,t,n),h=i.get(n);if(!h){d(e,t,n);for(let g of m.d.keys())f(e,t,g).t.add(n);if(h={l:new Set,d:new Set(m.d.keys()),t:new Set},i.set(n,h),JCt(n)&&g1o(n)){let g=()=>{let _=!0,y=(...x)=>{try{return p(e,t,n,x)}finally{if(!_)l(e,t),u(e,t)}};try{let x=a(e,t,n,y);if(x)h.u=()=>{_=!0;try{x()}finally{_=!1}}}finally{_=!1}};o.add(g)}(r=s.m)==null||r.call(s,n)}return h},D1o=(e,t,n)=>{var r,i;let o=e[1],s=e[5],a=e[6],c=e[11],u=e[19],l=c(e,t,n),d=o.get(n);if(!d||d.l.size)return d;let p=!1;for(let f of d.t)if((r=o.get(f))==null?void 0:r.d.has(n)){p=!0;break}if(!p){if(d.u)s.add(d.u);d=void 0,o.delete(n);for(let f of l.d.keys()){let m=u(e,t,f);m==null||m.t.delete(n)}(i=a.u)==null||i.call(a,n);return}return d},O1o=(e,t,n,r)=>{let i=e[11],o=e[27],s=i(e,t,n),a="v"in s,c=s.v;if(P7e(r))for(let u of s.d.keys())Xar(n,r,i(e,t,u));if(s.v=r,delete s.e,!a||!Object.is(c,s.v)){if(++s.n,P7e(c))o(e,t,c)}},P1o=(e,t,n)=>{let r=e[14];return O7e(r(e,t,n))},M1o=(e,t,n,...r)=>{let i=e[3],o=e[12],s=e[13],a=e[16],c=i.size;try{return a(e,t,n,r)}finally{if(i.size!==c)s(e,t),o(e,t)}},N1o=(e,t,n,r)=>{let i=e[12],o=e[13],s=e[18],a=e[19],u=s(e,t,n).l;return u.add(r),o(e,t),i(e,t),()=>{u.delete(r),a(e,t,n),o(e,t),i(e,t)}},L1o=(e,t,n,r)=>{let i=e[25],o=i.get(n);if(!o){o=new Set,i.set(n,o);let s=()=>i.delete(n);n.then(s,s)}o.add(r)},F1o=(e,t,n)=>{let i=e[25].get(n);i==null||i.forEach((o)=>o())},$1o;var ecr=C(()=>{QCt=new WeakSet,$1o=new WeakMap});function ncr(e,t){let n=`atom${++z1o}`,r={toString(){return(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};if(typeof e==="function")r.read=e;else r.init=e,r.read=U1o,r.write=j1o;if(t)r.write=t;return r}function U1o(e){return e(this)}function j1o(e,t,n){return t(this,typeof n==="function"?n(e(this)):n)}function rcr(){if(tcr)return tcr();return Zar()}var z1o=0,tcr;var icr=C(()=>{ecr()});var XCt,M7e=(e,t,n)=>Math.min(Math.max(e,t),n),ZCt=(e,t,n)=>{let r=M7e(e.width,n.width,Math.max(n.width,t.width)),i=M7e(e.height,n.height,Math.max(n.height,t.height));return{width:r,height:i,x:M7e(e.x,0,Math.max(0,t.width-r)),y:M7e(e.y,0,Math.max(0,t.height-i))}},YCt=(e,t,n)=>{let r=t.width/2,i=t.height/2,o=e==="left"?{x:0,y:0,width:r,height:t.height}:e==="right"?{x:r,y:0,width:r,height:t.height}:e==="top-left"?{x:0,y:0,width:r,height:i}:e==="top-right"?{x:r,y:0,width:r,height:i}:e==="bottom-left"?{x:0,y:i,width:r,height:i}:{x:r,y:i,width:r,height:i};return ZCt(o,t,n)},eIt=()=>{let e=rcr(),t=()=>e.get(XCt),n=0,r=(a)=>{n+=1,e.set(XCt,a(t()))},i=(a,c,u)=>{r((l)=>{let d=new Map(l.frames);return d.set(a,c),{...l,frames:d,participating:new Set(l.participating).add(a),tiles:l.tiles.includes(a)?l.tiles:[...l.tiles,a],minima:new Map(l.minima).set(a,u),order:l.order.includes(a)?l.order:[...l.order.filter((p)=>p!==l.zoomed),a,...l.zoomed?[l.zoomed]:[]]}})},o=(a)=>t().frames.has(a),s=(a,c)=>{let u=t().gesture;return u?.kind==="frame"&&u.id===a&&u.pointerId===c};return{get version(){return n},get frames(){return t().frames},get order(){return t().order},get tiles(){return t().tiles},get minima(){return t().minima},get participating(){return t().participating},get mainSize(){return t().mainSize},get zoomed(){return t().zoomed},get gesture(){return t().gesture},get restore(){return t().restore},subscribe:(a)=>e.sub(XCt,a),register:i,setParticipation:(a,c)=>{if(!t().frames.has(a))return;r((u)=>{if(u.participating.has(a)===c)return u;let d=new Set(u.participating);if(c)d.add(a);else d.delete(a);let p=c?u.tiles.includes(a)?u.tiles:[...u.tiles,a]:u.tiles.filter((m)=>m!==a),f=c?u.order.includes(a)?u.order:[...u.order,a]:u.order.filter((m)=>m!==a);return{...u,participating:d,tiles:p,order:f,zoomed:c||u.zoomed!==a?u.zoomed:null,gesture:!c&&u.gesture?.kind==="frame"&&u.gesture.id===a?null:u.gesture}})},setMinima:(a,c)=>{let u=t().minima.get(a);if(!u||u.width===c.width&&u.height===c.height)return;r((l)=>({...l,minima:new Map(l.minima).set(a,c)}))},unregister:(a)=>{r((c)=>{if(!c.frames.has(a))return c;let u=new Map(c.frames);u.delete(a);let l=new Map(c.restore);l.delete(a);let d=c.order.filter((g)=>g!==a),p=c.tiles.filter((g)=>g!==a),f=new Map(c.minima);f.delete(a);let m=new Set(c.participating);m.delete(a);let h=c.gesture?.kind==="frame"&&c.gesture.id===a?null:c.gesture;return{...c,frames:u,restore:l,order:d,tiles:p,minima:f,participating:m,gesture:h,zoomed:c.zoomed===a?null:c.zoomed}})},begin:(a,c)=>{if(!o(a)||!t().participating.has(a))return;r((u)=>({...u,gesture:{kind:"frame",id:a,pointerId:c,start:u.frames.get(a)??{x:0,y:0,width:0,height:0}},order:[...u.order.filter((l)=>l!==a),a]}))},move:(a,c,u,l,d,p=null)=>{if(o(a)&&t().participating.has(a)&&s(a,c))r((f)=>({...f,frames:new Map(f.frames).set(a,ZCt(u,l,d)),gesture:f.gesture?.kind==="frame"?{...f.gesture,snap:p?{side:p,frame:YCt(p,l,d)}:null}:f.gesture}))},end:(a,c)=>{if(s(a,c))r((u)=>{let l=u.gesture;if(l?.kind!=="frame"||!l.snap)return{...u,gesture:null};return{...u,frames:new Map(u.frames).set(a,l.snap.frame),restore:new Map(u.restore).set(a,u.restore.get(a)??l.start),gesture:null}})},cancel:(a,c)=>{let u=t().gesture;if(u?.kind==="frame"&&u.id===a&&u.pointerId===c)r((l)=>{let d=new Map(l.frames);return d.set(a,u.start),{...l,frames:d,gesture:null}})},snap:(a,c,u,l)=>{if(!o(a)||!t().participating.has(a))return;r((d)=>{let p=new Map(d.restore);p.set(a,d.frames.get(a)??YCt(c,u,l));let f=new Map(d.frames);return f.set(a,YCt(c,u,l)),{...d,frames:f,restore:p,order:[...d.order.filter((m)=>m!==a),a]}})},restoreFrame:(a,c,u)=>{if(!o(a)||!t().participating.has(a))return;r((l)=>{let d=l.restore.get(a);if(!d)return l;let p=new Map(l.frames);p.set(a,ZCt(d,c,u));let f=new Map(l.restore);return f.delete(a),{...l,frames:p,restore:f}})},focus:(a)=>{if(!o(a))return;r((c)=>({...c,order:[...c.order.filter((u)=>u!==a),a],zoomed:c.zoomed===null?null:a}))},swap:(a,c)=>{if(!o(a)||!o(c)||!t().participating.has(a)||!t().participating.has(c))return;r((u)=>({...u,tiles:u.tiles.map((l)=>l===a?c:l===c?a:l)}))},zoom:(a)=>{if(a!==null&&(!o(a)||!t().participating.has(a)))return;r((c)=>({...c,zoomed:a,order:a===null?c.order:[...c.order.filter((u)=>u!==a),a]}))},resizeMain:(a)=>{r((c)=>({...c,mainSize:a}))},beginDivider:(a)=>{if(t().gesture)return!1;return r((c)=>({...c,gesture:{kind:"divider",pointerId:a,start:c.mainSize}})),!0},finishDivider:(a,c)=>{let u=t().gesture;if(u?.kind!=="divider"||u.pointerId!==a)return;r((l)=>({...l,gesture:null,mainSize:c?u.start:l.mainSize}))},destroy:()=>{r((a)=>({...a,gesture:null,restore:new Map}))}}};var ocr=C(()=>{icr();XCt=ncr({frames:new Map,order:[],tiles:[],minima:new Map,participating:new Set,mainSize:void 0,zoomed:null,gesture:null,restore:new Map})});function N7e(e,t,n,r,i){let o=i.layout??"main-left";if(o==="columns"||o==="rows"||o==="grid")return B1o(e,t,n,r,i,o);if(o==="main-top"){let s=scr(e,new Map([...t].map(([a,c])=>[a,{width:c.height,height:c.width}])),n,{width:r.height,height:r.width},i);return{frames:new Map([...s.frames].map(([a,c])=>[a,{x:c.y,y:c.x,width:c.height,height:c.width}])),tabGroups:s.tabGroups,divider:s.divider&&{...s.divider,axis:"y"}}}return scr(e,t,n,r,i)}function B1o(e,t,n,r,i,o){let s=new Map,a=[];if(!e.length)return{frames:s,tabGroups:a,divider:null};let c=Math.max(0,i.gap??8),u=e.reduce((y,x)=>({width:Math.max(y.width,t.get(x)?.width??0),height:Math.max(y.height,t.get(x)?.height??0)}),{width:0,height:0}),l=(y,x)=>x+c===0?e.length:Math.min(e.length,Math.max(1,Math.floor((y+c)/(x+c)))),d=l(r.width,u.width),p=l(r.height,u.height),f=u.width>r.width||u.height>r.height?1:o==="columns"?d:o==="rows"?p:Math.min(e.length,d*p),m=o==="columns"?f:o==="rows"?1:Math.min(d,Math.max(Math.ceil(Math.sqrt(f)),Math.ceil(f/p))),h=Math.ceil(f/m),g=(r.width-c*(m-1))/m,_=(r.height-c*(h-1))/h;for(let y=0;y<f;y++){let x=e.slice(y,y===f-1?void 0:y+1),w=x.length===1?x[0]:[...n].reverse().find((b)=>x.includes(b))??x[0];if(w)s.set(w,{x:y%m*(g+c),y:Math.floor(y/m)*(_+c),width:g,height:_});if(x.length>1)a.push(x)}return{frames:s,tabGroups:a,divider:null}}function scr(e,t,n,r,i){let o=new Map,s=[],a={x:0,y:0,...r},[c,...u]=e,l=(w,b)=>{let E=[...n].reverse().find((A)=>w.includes(A))??w[0];if(E)o.set(E,b);if(w.length>1)s.push(w)};if(!c)return{frames:o,tabGroups:s,divider:null};if(!u.length)return o.set(c,a),{frames:o,tabGroups:s,divider:null};let d=Math.max(0,i.gap??8),p=t.get(c)?.width??0,f=Math.max(...u.map((w)=>t.get(w)?.width??0)),m=r.width-d-f;if(p>m)return l([...e],a),{frames:o,tabGroups:s,divider:null};let h=Math.min(m,Math.max(p,i.mainSize??r.width/2)),g={axis:"x",position:h,min:p,max:m};o.set(c,{...a,width:h});let _={...a,x:h+d,width:r.width-h-d},x=u.map((w)=>t.get(w)?.height??0).reduce((w,b)=>w+b,0)+d*(u.length-1);if(x>r.height)l(u,_);else{let w=(r.height-x)/u.length,b=0;for(let E of u){let A=(t.get(E)?.height??0)+w;o.set(E,{..._,y:b,height:A}),b+=A+d}}return{frames:o,tabGroups:s,divider:g}}var acr=C(()=>{ocr()});function ccr(e){let t=new Map(e.kinds.map((E)=>[E.kind,E]));if(t.size!==e.kinds.length)throw Error("Pane kinds must have distinct identities");let n=eIt(),r=new Map,i=new Map,o=new Set,s=nO([]),a=e.viewport,c=!1,u=()=>c,l,d="main-left",p=0,f=new AbortController,m=()=>{let E={layout:d,gap:0};if(n.mainSize!==void 0)E.mainSize=n.mainSize;let A=N7e(n.tiles,n.minima,n.order,a,E);if(n.zoomed!==null&&n.participating.has(n.zoomed))A.frames=new Map([[n.zoomed,{x:0,y:0,...a}]]);let R=n.order.at(-1)??null;e.commands.focus(r.get(R??"")?.commandScope??null);let L=[];for(let z of g.read().windows){let j=r.get(z.windowId);if(j===void 0)continue;let G=A.frames.get(z.windowId),ee=G??{x:0,y:0,...j.viewport.value.read()};j.focused.set(R===z.windowId);let ie={width:Math.floor(ee.width)-(g.read().windows.length>1&&n.zoomed===null&&ee.x+ee.width<a.width?1:0),height:Math.max(1,Math.floor(ee.height))};if(ie.width!==j.viewport.value.read().width||ie.height!==j.viewport.value.read().height)j.viewport.set(ie);L.push({paneId:z.windowId,title:j.title,frame:{x:Math.floor(ee.x),y:Math.floor(ee.y),width:Math.floor(ee.width),height:Math.floor(ee.height)},visible:G!==void 0,focused:R===z.windowId,zoomed:n.zoomed===z.windowId,node:j.node,state:z.status==="error"?"error":z.status==="loading"?"loading":"ready",error:z.error,status:[...j.status.values()],presentation:j.theme.value.read()})}s.set(L)};async function h(E,A){let R=new AbortController,L=AbortSignal.any([A,f.signal,R.signal]),z=E.windowId,j=`${z}:${String(++p)}`,G=e.commands.mountPane(j),ee=nO(a),ie=nO(!1),le=new Set,be=new Set,xe=nO(e.theme.read()),B=new Map,K=()=>{xe.set([...B.values()].at(-1)??e.theme.read()),m()},X=new Map,Y=nO([]),fe=(Oe)=>{let he={...Oe,text:Qb(Oe.text)};if(he.compact!==void 0)he.compact=Qb(he.compact);return he},V=()=>{Y.set([...X.values()]),m()},Z=new Set,ue=new Set;ue.add(e.theme.subscribe(()=>{if(B.size===0)K()}));let Le=new Set,ve=!0;function Pe(Oe){return{read:Oe.read,subscribe:(he)=>{if(!ve)return()=>{return};let Re=Oe.subscribe(he);return ue.add(Re),()=>{ue.delete(Re),Re()}}}}let J=e.apps,te={paneId:z,setTitle:(Oe)=>{if(!ve)return;if(ce.title=Qb(Oe),ce.node!==null&&r.get(z)?.kit===te)m()},exit:e.exit,rendering:{afterFrame:(Oe)=>{if(!ve)return()=>{return};let he=e.rendering.afterFrame(()=>{if(ue.delete(he),ve)Oe()});return ue.add(he),()=>{ue.delete(he),he()}},requestFrame:()=>{if(ve)e.rendering.requestFrame()},isFocused:(Oe)=>ve&&ie.value.read()&&e.rendering.isFocused(Oe)},viewport:Pe(ee.value),input:{focused:Pe(ie.value),onKey:(Oe)=>{if(ve)le.add(Oe);return()=>{le.delete(Oe)}},onPaste:(Oe)=>{if(ve)be.add(Oe);return()=>{be.delete(Oe)}},requestFocus:()=>{if(ve)n.focus(z)}},commands:G,dialogs:{dismiss:()=>ve&&e.dialogs.dismiss(),open:Pe(e.dialogs.open),show:(Oe,he)=>{if(!ve)throw Error("Pane has closed");let Re=e.dialogs.show(Oe,he);return Le.add(Re),Re}},status:{items:Pe(Y.value),contribute:(Oe)=>{if(!ve)throw Error("Pane has closed");let he=Symbol();return X.set(he,fe(Oe)),V(),{update:(Re)=>{if(ve&&X.has(he))X.set(he,fe(Re)),V()},dispose:()=>{if(X.delete(he))V()}}}},replace:(Oe)=>ve?w(z,Oe):Promise.resolve({kind:"refused",reason:"Pane has closed"}),open:(Oe)=>ve?x(Oe):Promise.resolve({kind:"refused",reason:"Pane has closed"}),toast:(Oe)=>{if(ve)e.toast({...Oe,key:Oe.duration==="until-dismissed"?JSON.stringify([z,Oe.key??Oe.message]):void 0})},apps:J===void 0?void 0:{signedIn:(Oe)=>J.signedIn(AbortSignal.any([L,Oe])),read:(Oe)=>J.read(AbortSignal.any([L,Oe])),requestGill:(Oe,he,Re)=>J.requestGill(Oe,he,AbortSignal.any([L,Re])),openUi:(Oe,he)=>J.openUi(Oe,AbortSignal.any([L,he]))},sessions:{...e.sessions,acquire:(Oe,he)=>e.sessions.acquire(Oe,AbortSignal.any([L,he]))},theme:Pe(xe.value),presentTheme:(Oe)=>{if(!ve)throw Error("Pane has closed");let he=Symbol();return B.set(he,Oe),K(),{update:(Re)=>{if(ve&&B.has(he))B.set(he,Re),K()},dispose:()=>{if(B.delete(he)&&ve)K()}}},signal:L,onDispose:(Oe)=>{if(ve)ue.add(Oe);else Oe()},guardClose:(Oe)=>{if(ve)Z.add(Oe);return()=>{Z.delete(Oe)}},guardQuit:(Oe)=>{if(ve)o.add(Oe);let he=()=>{o.delete(Oe)};return ue.add(he),he}},ye=()=>{if(!ve)return;ve=!1,R.abort();let Oe=[],he=(Re)=>{try{Re()}catch(Ze){Oe.push(Ze)}};for(let Re of Le)he(Re.dismiss);for(let Re of ue)he(Re);if(he(G.dispose),ce.node=null,le.clear(),be.clear(),X.clear(),Y.clear(),B.clear(),xe.clear(),Z.clear(),ue.clear(),ee.clear(),ie.clear(),r.get(z)?.kit===te){if(r.delete(z),i.get(E.identity)===z)i.delete(E.identity);n.unregister(z)}if(Oe.length>0)throw AggregateError(Oe,"Pane cleanup failed")},ce={kit:te,title:Qb(E.instance.title),node:null,commandScope:j,viewport:ee,focused:ie,keys:le,pastes:be,status:X,theme:xe},de=r.get(z);try{if(de===void 0){if(r.set(z,ce),n.register(z,{x:0,y:0,...a},e.minima),E.focus)n.focus(z)}if(ce.node=await E.instance.render(te),!L.aborted){if(r.set(z,ce),de!==void 0)n.focus(z);m()}}catch(Oe){try{ye()}catch(he){throw AggregateError([Oe,he],"Pane mount and cleanup failed",{cause:he})}throw Oe}let Se;return{reconfigure:async(Oe,he)=>{if(Se!==void 0){if(await Se.requestClose?.()===!1)throw Error("Pane close was declined")}else for(let nt of Z)if(!await nt())throw Error("Pane close was declined");let Re=await h(Oe,he===void 0?A:AbortSignal.any([A,he])),Ze=Se;if(Se=Re,Ze!==void 0)await Ze.dispose();else ye()},setVisibility:(Oe)=>{if(Se!==void 0)return Se.setVisibility(Oe);n.setParticipation(z,Oe==="visible")},requestClose:async()=>{if(Se!==void 0)return await Se.requestClose?.()??!0;for(let Oe of Z)if(!await Oe())return!1;return!0},dispose:()=>{if(Se===void 0)ye();else return Se.dispose()}}}let g=Var({createContainer:({windowId:E})=>({paneId:E}),mount:(E,A,R)=>h(A,R),onFailure:({cause:E})=>{xi("pane-lifetime",E)}}),_=g.subscribe(m),y=n.subscribe(m);async function x(E,A=!0,R){if(c)return{kind:"refused",reason:"Workspace has closed"};let L=t.get(E.kind)?.instantiate(E);if(L===void 0)return{kind:"refused",reason:"Pane target is not supported"};let z=JSON.stringify([E.kind,L.key]),j=i.get(z);if(j!==void 0){if(A)n.focus(j);return{kind:"focused",paneId:j}}let G=q1o.pane.generate();i.set(z,G),await g.open({windowId:G,instance:L,identity:z,focus:A});let ee=g.read().windows.find((ie)=>ie.windowId===G);if(u()||ee===void 0)return{kind:"refused",reason:"Workspace closed while opening pane"};if(ee.status==="error")throw i.delete(z),await g.close(G),Error("Pane mount failed",{cause:ee.error});if(R!==void 0){let ie=R.afterPaneId===null?-1:n.tiles.indexOf(R.afterPaneId);for(let le=n.tiles.indexOf(G);ie>=0&&le>ie+1;le-=1){let be=n.tiles[le-1];if(be!==void 0)n.swap(G,be)}d=R.direction==="beside"?"columns":"rows",m()}return{kind:"opened",paneId:G}}async function w(E,A){let R=g.read().windows.find((ee)=>ee.windowId===E);if(c||R===void 0)return{kind:"refused",reason:"Pane has closed"};let L=t.get(A.kind)?.instantiate(A);if(L===void 0)return{kind:"refused",reason:"Pane target is not supported"};let z=JSON.stringify([A.kind,L.key]),j=i.get(z);if(j!==void 0&&j!==E)return{kind:"refused",reason:"That conversation is already open in another pane"};if(z===R.launch.identity)return{kind:"focused",paneId:E};try{await g.reconfigure(E,{windowId:E,instance:L,identity:z,focus:!0})}catch(ee){throw Error("Pane mount failed",{cause:ee})}if(g.read().windows.find((ee)=>ee.windowId===E)?.launch.identity!==z)return{kind:"refused",reason:"Pane closed while preparing replacement"};return i.delete(R.launch.identity),i.set(z,E),m(),{kind:"opened",paneId:E}}let b=()=>r.get(n.order.at(-1)??"");return{toast:e.toast,launchers:e.kinds.flatMap((E)=>E.launcher===void 0?[]:[E.launcher]),open:x,canQuit:async()=>{for(let E of o)if(!await E())return!1;return!0},close:g.close,replace:w,focus:n.focus,swap:n.swap,zoom:n.zoom,toggleZoom:(E)=>{n.zoom(n.zoomed===E?null:E)},resizeBy:(E)=>{let A={layout:d,gap:0};if(n.mainSize!==void 0)A.mainSize=n.mainSize;let L=N7e(n.tiles,n.minima,n.order,a,A).divider;if(L!==null)n.resizeMain(Math.max(L.min,Math.min(L.max,L.position+E)))},resize:(E)=>{n.resizeMain(Math.max(0,E))},equalize:()=>{n.resizeMain(void 0)},setLayout:(E)=>{d=E,m()},cycleLayout:()=>{d=W1o[d],m()},viewport:(E)=>{a=E,m()},read:s.value.read,subscribe:s.value.subscribe,key:(E)=>{if(e.dialogs.open.read()||E.defaultPrevented)return!1;for(let A of b()?.keys??[])if(A(E))return E.preventDefault(),!0;return!1},paste:(E)=>{if(e.dialogs.open.read()||E.defaultPrevented)return;for(let A of b()?.pastes??[])A(E)},dispose:()=>{if(l!==void 0)return l;return c=!0,f.abort(),l=g.dispose().finally(()=>{_(),y(),n.destroy(),s.clear()}),l}}}var q1o,W1o;var ucr=C(async()=>{KC();Kar();acr();QJ();await Xa();q1o=Ha({family:"tui-pane",version:1,kinds:{pane:{prefix:"tui_pane"}}}),W1o={"main-left":"main-top","main-top":"columns",columns:"rows",rows:"grid",grid:"main-left"}});import{CliRenderEvents as lcr}from"@opentui/core";function dcr(e){return je("box",{width:"100%",height:"100%",position:"relative",children:je(vge,{children:je(H1o,{...e})})})}function H1o(e){let t=md(k7e),n=ww(),r=kp(),i=e.dialog,o=IA(e.theme,{refreshOnReturnToTerminal:!1}),s=ys(()=>({colors:o.colors,surface:o.surface,syntax:o.syntax,dimForeground:o.dimForeground,nativeDefaults:o.nativeDefaults}),[o.colors,o.surface,o.syntax,o.dimForeground,o.nativeDefaults]),a=RA(),[c]=ti(()=>({theme:nO(s),open:nO(i.isOpen),dialog:{current:i}}));c.dialog.current=i;let[u]=ti(()=>ccr({kinds:e.kinds??[...jar,...e.additionalKinds??[]],commands:e.commandHost,viewport:r,minima:{width:40,height:12},sessions:e.sessions,apps:e.apps,theme:c.theme.value,exit:e.exit,toast:a.show,dialogs:{open:c.open.value,show:(...m)=>c.dialog.current.show(...m),dismiss:()=>c.dialog.current.dismiss()},rendering:{afterFrame:(m)=>(n.once(lcr.FRAME,m),()=>{n.off(lcr.FRAME,m)}),requestFrame:()=>{n.requestRender()},isFocused:(m)=>n.currentFocusedRenderable===m}}));Vn(()=>{c.theme.set(s)},[c,s]),Ah(()=>{c.open.set(i.isOpen)},[c,i.isOpen]),Vn(()=>{u.viewport(r)},[u,r.width,r.height]),Vn(()=>(e.onRegistry(u),()=>{u.dispose().catch((m)=>xi("pane-workspace-close",m))}),[u,e.onRegistry]);let l={registry:u,host:e.commandHost,dialog:i,colors:o.colors,openPane:e.openPane,toast:a.show};Har(l),jY((m)=>{u.key(m)}),ktr((m)=>{u.paste(m)});let d=Ta(u.subscribe,u.read),p=d.length>1,f=d.find((m)=>m.focused)?.presentation??o;return je(c7.Provider,{value:f.colors,children:Gn("box",{width:"100%",height:"100%",position:"relative",children:[d.length===0?je(Yge,{state:"empty",message:"No panes open. Ctrl K: pane commands \xB7 Ctrl C: exit.",colors:f.colors}):null,d.map((m)=>je("box",{position:"absolute",visible:m.visible,border:p&&!m.zoomed&&m.frame.x+m.frame.width<r.width?["right"]:[],borderColor:f.colors.surface,left:m.frame.x,top:m.frame.y,width:m.frame.width,height:m.frame.height,onMouseDown:()=>{u.focus(m.paneId)},children:m.state==="loading"?je(Yge,{state:"loading",message:`Opening ${m.focused?"\u25B8 ":" "}${m.title}${m.zoomed?" \xB7 zoomed":""}\u2026`,colors:f.colors}):m.node},m.paneId)),t,je(wge,{dialog:i,colors:f.colors})]})})}var pcr=C(async()=>{qc();BCt();Gi();await Mc([u7(),$h(),Bar(),Xa(),Gar(),ucr(),MCt()])});function nIt(e){return{commands:e.commands,toolSigils:e.toolSigils,apps:e.apps,paneKinds:e.paneKinds,commandHost:e.commandHost,setQuitGuard:e.setQuitGuard,acquireSession:e.acquireSession,onExit:e.onExit,chooseConversation:e.chooseConversation,openConversation:e.openConversation,initialTheme:e.initialTheme}}function tIt(e){return e.target??{kind:"conversation",agentId:e.session.address,sessionId:e.session.address}}function fcr(e){return JSON.stringify([e.agentId,e.sessionId])}function G1o(e){return e.sessionId===null?{agentId:e.agentId,sessionId:null,createRequestId:e.createRequestId}:{agentId:e.agentId,sessionId:e.sessionId}}function V1o(e){return{clients:e.clients,interactions:e.interactionStore,mcpApprovals:e.mcpApprovals,models:e.modelSource,sandbox:e.sandboxSource,stopAll:e.onStopAll,sessionTitle:e.sessionTitle,folder:e.folder,reload:e.reloadSources,observationUnavailable:e.onObservationUnavailable,rebindService:e.onRebindService,themeName:e.initialTheme,saveTheme:e.onThemeConfirm,themeError:e.themeError,initialError:e.initialCommandError,initialNotice:e.initialCommandNotice,resume:e.onResume,create:e.onNew,forked:e.onForked,inputHandoff:e.inputHandoff}}function mcr({entries:e,requested:t,dialog:n,configuration:r,registerDraftCheckpoint:i}){let o=e[0],s=r??(o===void 0?void 0:nIt(o.props));if(s===void 0)throw Error("Workspace requires its host configuration");return je(K1o,{registerDraftCheckpoint:i,initial:s,entries:e,requested:t,dialog:n})}function K1o({initial:e,entries:t,requested:n,dialog:r,registerDraftCheckpoint:i}){let o=Or(void 0);Vn(()=>()=>o.current?.abort(),[]);let[s,a]=ti(e.initialTheme??"terminal"),c=IA(s,{refreshOnReturnToTerminal:!1}),u=Or(s);u.current=s;let l=Or(t);l.current=t;let[d]=ti(()=>e.commandHost??E7e(e.commands)),[p,f]=ti(),m=Uc((x)=>{f(x)},[]);Vn(()=>(e.setQuitGuard?.(p?.canQuit),()=>e.setQuitGuard?.(void 0)),[e.setQuitGuard,p]);let[h]=ti(()=>({retired:new WeakSet,contexts:new WeakMap})),g=(x)=>({...x,themeName:u.current,saveTheme:async(w)=>{await x.saveTheme?.(w),u.current=w,a(w)}}),[_]=ti(()=>({registerDraftCheckpoint:i,acquire:async(x,w)=>{if(w.aborted)throw w.reason;let b=l.current.find(({props:z})=>fcr(tIt(z))===fcr(x)&&!h.retired.has(z.session)),E,A;if(b===void 0){let z=e.acquireSession;if(z===void 0)throw Error("That Session is not available through Local");let j=await z(G1o(x),w);E=j.session,A=j.close,h.contexts.set(E,j.context)}else E=b.props.session,A=b.props.onClose;let R=()=>{h.retired.add(E),h.contexts.delete(E);let z=A?.();if(z!==void 0)Promise.resolve(z).catch((j)=>xi("pane-session-close",j))};if((()=>w.aborted)())R();else w.addEventListener("abort",R,{once:!0});return E},describe:(x)=>{let w=h.contexts.get(x);if(w!==void 0)return g(w);let b=l.current.find((E)=>E.props.session===x)?.props;if(b===void 0)throw Error("Session observation was retired");return g(V1o(b))}}));Vn(()=>{let x=l.current.find((b)=>b.request===n);if(p===void 0||x===void 0)return;(x.props.replacePaneId===void 0?p.open(tIt(x.props),!0,x.props.openPlacement):p.replace(x.props.replacePaneId,tIt(x.props))).then((b)=>{if(b.kind==="refused")p.toast({variant:"error",duration:"until-dismissed",message:b.reason})}).catch((b)=>(xi("conversation-pane-open",b),p.toast({variant:"error",duration:"until-dismissed",message:b instanceof Error?b.message:"Conversation pane could not open"}),{kind:"refused",reason:"Conversation pane could not open"}))},[p,n]),Vn(()=>()=>{if(e.commandHost===void 0)d.dispose()},[d,e.commandHost]);let y=async(x)=>{let w=x===void 0?void 0:{direction:x,afterPaneId:p?.read().find((j)=>j.focused)?.paneId??null};o.current?.abort();let b=new AbortController;o.current=b;let E=[...e.openConversation===void 0?[]:[{name:"New conversation",description:"Start a conversation in a new pane",open:async(j)=>{j.dismiss(),await e.openConversation?.(w)}}],...e.chooseConversation===void 0?[]:[{name:"Resume conversation",description:"Open a saved conversation",open:async(j)=>{j.dismiss(),await e.chooseConversation?.(w)}}]],A=(p?.launchers??[]).map((j)=>({name:j.name,description:j.description,open:async(G)=>{G.dismiss();let ee=await p?.open(j.target,!0,w);if(ee?.kind==="refused")throw Error(ee.reason)}})),R=e.apps;if(R===void 0||!await R.signedIn(b.signal)){if(b.signal.aborted)return;z("Open pane",[...E,...A]);return}if(b.signal.aborted)return;let L=[...E,...A,{name:"Apps",description:"Open an App pane or hand off to its App",open:async(j)=>{let G=await R.read(b.signal);if(b.signal.aborted||!j.isCurrent())return;let ee=G.apps.flatMap((ie)=>ie.gills.length===0?[{name:ie.displayName??ie.appId,description:"Open in your browser",open:async(le)=>{le.dismiss(),await R.openUi(ie.surfaceId,b.signal)}}]:ie.gills.map((le)=>({name:`${ie.displayName??ie.appId} \xB7 ${le.title}`,description:ie.availability==="available"?"Open App pane":"Unavailable",open:async(be)=>{be.dismiss();let xe=await p?.open({kind:"gill",surfaceId:ie.surfaceId,viewId:le.id,title:le.title},!0,w);if(xe?.kind==="refused")throw Error(xe.reason)}})));if(ee.length===0)throw Error("This Team has no Apps yet");z("Apps",ee)}}];function z(j,G){r.show((ee)=>je(Wp,{title:j,choices:G,searchable:!0,colors:c.colors,onCancel:()=>{b.abort(),ee.dismiss()},onSelect:(ie)=>{let le=G[ie];if(le===void 0)return;le.open(ee).catch((be)=>{if(b.signal.aborted)return{kind:"retired",cause:be};return ee.dismiss(),xi("pane-picker-open",be),p?.toast({variant:"error",duration:"until-dismissed",message:be instanceof Error?be.message:"The pane could not open"}),{kind:"failed",cause:be}})}}))}z("Open pane",L)};return je(WLe.Provider,{value:e.toolSigils,children:je(bge,{children:je(dcr,{commandHost:d,sessions:_,apps:e.apps,additionalKinds:e.paneKinds,theme:s,exit:()=>e.onExit?.(),onRegistry:m,dialog:r,openPane:y})})})}var hcr=C(async()=>{qc();PCt();Gi();await Mc([Xa(),Xa(),pcr()])});function gcr({sessions:e,onCancel:t,onSelect:n,themeError:r}){let i=S6(),o=kp(),s=o.height<14,a=J1(o.width),c=Date.now(),u=e.map((l)=>zZ(l.updatedAt,c));return Gn("box",{flexDirection:"column",rowGap:s?0:1,children:[je(Z_,{content:{title:"Resume a conversation",summary:r??"Pick one to continue where you left off."},width:a,compact:s,colors:i}),je(Wp,{searchable:!0,descriptionWrap:!1,descriptionWidth:Math.max(...u.map((l)=>Bun.stringWidth(l)),1),colors:i,choices:e.map((l,d)=>({name:l.title.trim()||"Untitled",description:u[d]})),onCancel:t,onSelect:n})]})}var _cr=C(async()=>{qc();bf();await Mc([$h(),EB(),J5(),u7(),_ge()])});import{homedir as J1o}from"os";function rIt(e){let t=J1o();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function X1o(e){let t=`${String(e.sessionCount)} conversation${e.sessionCount===1?"":"s"}`;return e.updatedAt===void 0?t:`${t} \xB7 ${new Date(e.updatedAt).toLocaleDateString()}`}function ycr({sessions:e,agents:t=[],notice:n,folder:r,loadSummary:i,choose:o}){let s=S6(),{height:a,width:c}=kp(),u=t.map(({agentId:_})=>_).join(","),l=Or({agentsKey:u,index:0}),[d,p]=ti("loading");Vn(()=>{let _=new AbortController;return i(_.signal).then((y)=>{if(!_.signal.aborted)p(y)},()=>{if(!_.signal.aborted)p({account:void 0,model:void 0})}),()=>{_.abort()}},[i]);let f=a>=34&&c>=72,m=Math.max(1,Math.min(84,c-4)),h=d!=="loading"&&(d.account!==void 0||d.model!==void 0),g=(_,y,x=!1)=>Gn("box",{flexDirection:"row",height:1,flexShrink:0,children:[je("text",{fg:s.foreground,attributes:2,width:9,flexShrink:0,children:_}),je("text",{fg:s.foreground,attributes:x?2:0,wrapMode:"none",children:_c(br(y),Math.max(0,m-9))})]});return je("box",{flexDirection:"column",height:a,alignItems:"center",paddingX:2,paddingTop:1,backgroundColor:s.background,children:Gn("box",{flexDirection:"column",width:"100%",maxWidth:84,flexShrink:1,flexGrow:1,minHeight:0,children:[Gn("box",{flexDirection:"column",flexShrink:0,children:[f?je("text",{fg:s.primary,alignSelf:"center",children:Q1o}):null,je("text",{fg:s.foreground,attributes:2,marginBottom:1,alignSelf:"center",children:f?"Your ideas, growing.":"fungi \xB7 Your ideas, growing."}),d==="loading"?Gn(yk,{children:[g("Account","Checking\u2026",!0),g("Model","Checking\u2026",!0)]}):Gn(yk,{children:[g("Account",d.account??"Not signed in",!h),g("Model",d.model??"None yet",d.model===void 0)]}),g("Folder",rIt(r)),n===void 0?null:je("text",{fg:s.info,marginTop:1,wrapMode:"word",children:br(n)}),d!=="loading"&&!h?je("text",{fg:s.info,marginTop:1,children:"Sign in to start: run fungi login, or type /login in a session."}):null]}),je("box",{flexDirection:"column",flexGrow:1,minHeight:0,marginTop:1,children:t.length>1?je(Wp,{title:"Agents in this folder",colors:s,descriptionWrap:!1,choices:t.map((_)=>({name:WDe(_,t),description:X1o(_)})),hints:[{keys:"Enter",label:"open",priority:0},{keys:"a",label:"archive",priority:1},{keys:"\u2191\u2193",label:"choose",priority:1},{keys:"Esc",label:"quit",priority:2}],onHighlight:(_)=>{l.current={agentsKey:u,index:_}},onKey:(_)=>{if(_.name!=="a"||_.ctrl||_.meta)return!1;return o({kind:"archive",index:l.current.agentsKey===u?l.current.index:0}),!0},onSelect:(_)=>{o({kind:"agent",index:_})},onCancel:()=>{o(void 0)}},`agents-${u}`):je(Wp,{title:e.length===0?"No conversations in this folder yet":"Recent conversations",colors:s,descriptionWrap:!1,choices:[{name:"+ New session",description:"n"},...e.map((_)=>({name:_.title.trim()||"Untitled",description:new Date(_.updatedAt).toLocaleDateString()}))],hints:[{keys:"Enter",label:"open",priority:0},{keys:"n",label:"new session",priority:0},{keys:"\u2191\u2193",label:"choose",priority:1},{keys:"Esc",label:"quit",priority:2}],onKey:(_)=>{if(_.name!=="n"||_.ctrl||_.meta)return!1;return o({kind:"new"}),!0},onSelect:(_)=>{o(_===0?{kind:"new"}:{kind:"resume",index:_-1})},onCancel:()=>{o(void 0)}},"conversations")})]})})}var Q1o;var iIt=C(async()=>{qc();Hbt();Gi();r7();ay();await Mc([$h(),J5(),u7()]);Q1o=jme.replace(/^\n+|\n+$/gu,"")});import{readFile as Y1o,realpath as Z1o}from"fs/promises";import{basename as exo,dirname as xcr,join as txo}from"path";import{createRequire as nxo}from"module";function rxo(e){let t=new AbortController,n=()=>t.signal.aborted,r=!1,{running:i,running:o}=e,s=async()=>{if(await e.policy()==="off"||n())return;let d=AB.parse(await e.installed());if(n())return;if(Bun.semver.order(d,o)>0)e.notify({kind:"restart",version:d}),o=d;let p=AB.parse(await e.registry(t.signal));if(n())return;if(Bun.semver.order(p,d)>0&&Bun.semver.order(p,i)>0)e.notify({kind:"available",version:p}),i=p},a=async()=>{if(r||n())return;r=!0;try{await s()}catch(d){e.reportFailure(d)}finally{r=!1}},c=()=>{a()},l=(e.schedule??((d,p)=>{let f=setInterval(d,p);return f.unref(),()=>{clearInterval(f)}}))(c,600000);return c(),()=>{t.abort(),l()}}function bcr(e){let t=process.env.FUNGI_LAUNCHER;if(t===void 0||exo(t)!=="fungi.cjs")return()=>{return};let n;return rxo({running:ixo,policy:async()=>{let r=await bB();if(r.error!==void 0)throw Error(r.error);return r.update??"notify"},installed:async()=>{if(n===void 0){await Promise.resolve().then(() => Pge());n=(await QLe()).launcher}let r=await Z1o(n);return vcr.parse(JSON.parse(await Y1o(txo(xcr(xcr(r)),"package.json"),"utf8"))).version},registry:KLe,notify:e,reportFailure:(r)=>{xi("update-check",r)}})}var vcr,ixo;var wcr=C(()=>{qn();wAt();HY();_y();vcr=se({version:AB}),ixo=vcr.parse(nxo(import.meta.url)("../package.json")).version});function oxo(e,t){if(e.kind==="available")return{variant:"info",message:`Fungi ${e.version} is available: run fungi update`};return{variant:"info",message:"Update installed: restart to update",duration:"until-dismissed",action:{label:"Restart to update",run:t}}}function Scr({restart:e,watch:t=bcr}){let n=RA();return Vn(()=>t((r)=>{n.show(oxo(r,e))}),[n,t,e]),null}var Ecr=C(async()=>{Gi();wcr();await Xa()});function sxo({store:e}){return Gn(bge,{children:[je(axo,{store:e}),je(Scr,{restart:e.restartUpdate})]})}function axo({store:e}){let t=Ta(e.subscribe,e.read),n=t.entries,r=IA(t.picker?.initialTheme??t.landing?.initialTheme??t.configuration?.initialTheme??"terminal"),i=jLe();Vn(()=>{let c=t.picker;if(c===void 0)return;let u=i.show((l)=>je(gcr,{...c,onSelect:(d)=>{c.onSelect(d),l.dismiss()},onCancel:l.dismiss}),{onDismiss:()=>{if(e.read().picker===c){let l={...e.read()};delete l.picker,e.update(l)}c.onCancel()}});return()=>{u.dismiss()}},[t.picker,i.show,e]);let o=n!==void 0&&t.queryClient!==void 0,s=o?t.recovery:void 0,a=o?t.serviceUpdated:void 0;if(Vn(()=>{if(s===void 0)return;let c=i.show(()=>je(Acr,{...s}),{beforeDismiss:()=>!1});return()=>{c.dismiss()}},[s,i.show]),Vn(()=>{if(a===void 0)return;let c=i.show(()=>je(Tcr,{...a}),{onDismiss:()=>{if(e.read().serviceUpdated===a)a.exit()}});return()=>{c.dismiss()}},[a,i.show,e]),n===void 0&&t.recovery!==void 0)return je(c7.Provider,{value:r.colors,children:je(Acr,{...t.recovery})});if(n===void 0&&t.serviceUpdated!==void 0)return je(c7.Provider,{value:r.colors,children:je(Tcr,{...t.serviceUpdated})});if(n===void 0&&t.landing!==void 0)return je(c7.Provider,{value:r.colors,children:je(ycr,{...t.landing})});if(n===void 0||t.queryClient===void 0)return Gn("box",{flexDirection:"column",flexGrow:1,children:[je(Yge,{state:"loading",message:"Connecting to Local Shiitake\u2026 Ctrl+C to exit.",colors:r.colors}),i.isOpen?je(uxo,{dialog:i,colors:r.colors}):null]});return je(Out,{client:t.queryClient,children:je(mcr,{registerDraftCheckpoint:e.registerCheckpoint,entries:n,configuration:t.configuration,requested:t.requested??0,dialog:i})})}function Tcr({message:e,exit:t}){let n=S6(),r=kp(),i=r.height<14;return Gn("box",{flexDirection:"column",flexGrow:1,rowGap:i?0:1,children:[je(Z_,{content:{title:"Fungi was updated",summary:e},width:J1(r.width),compact:i,colors:n}),je(Wp,{colors:n,choices:[{name:"Exit this window"}],onSelect:t,onCancel:t})]})}function Ccr(e,t,n){let r=_7(e);r.update({...r.read(),serviceUpdated:{message:t,exit:n}})}function cxo({message:e,retry:t,exit:n}){let r=S6(),i=kp(),[o,s]=ti(!1),a=i.height<14,c=J1(i.width),u={title:"Connection unavailable",summary:"Your saved conversations are unchanged.",details:[{label:"Error",value:e}]};if(o)return Gn("box",{flexDirection:"column",flexGrow:1,rowGap:a?0:1,focusable:!0,focused:!0,onKeyDown:(l)=>{if(l.name==="d"||l.name==="escape")l.preventDefault(),s(!1)},children:[je(SB,{content:u,width:c,maxRows:i.height-8,colors:r}),je(AA,{hints:[{keys:"d",label:"back",priority:0},{keys:"Esc",label:"back",priority:1}],width:c,colors:r})]});return Gn("box",{flexDirection:"column",flexGrow:1,rowGap:a?0:1,children:[je(Z_,{content:u,width:c,compact:a,colors:r}),je(Wp,{colors:r,choices:[{name:"Retry connection"},{name:"Exit"}],hints:[{keys:"\u2191\u2193",label:"choose",priority:1},{keys:"Enter",label:"select",priority:0},{keys:"d",label:"details",priority:2},{keys:"Ctrl+C",label:"exit",priority:2}],onKey:(l)=>{if(l.name!=="d"||l.ctrl||l.meta||l.option)return!1;return s(!0),!0},onSelect:(l)=>{if(l===0)t();else if(l===1)n()},onCancel:()=>{return}})]})}function Acr({error:e,retry:t,exit:n}){let r=S6(),i=kp();if(!(e instanceof om))return je(cxo,{message:e.message,retry:t,exit:n});let o=i.height<14;return Gn("box",{flexDirection:"column",flexGrow:1,rowGap:o?0:1,children:[je(Z_,{content:{title:e.reason==="newer"?"This Agent was saved by a newer Fungi":"Fungi cannot read this Agent",summary:e.message},width:J1(i.width),compact:o,full:!0,colors:r}),je(Wp,{colors:r,choices:e.reason==="newer"?[{name:"Exit"}]:[{name:"Start a new Agent"},{name:"Exit"}],onSelect:(s)=>{if(e.reason==="newer")n();else if(s===0)t();else if(s===1)n()},onCancel:n})]})}function Icr(e,t,n,r){let i=_7(e);i.update({...i.read(),recovery:{error:t,retry:n,exit:r}})}function uxo({dialog:e,colors:t}){return je(wge,{dialog:e,colors:t})}function _7(e){let t=kcr.get(e);if(t!==void 0)return t;let n={},r=!1,i,o=Jsr(),s=new Set,a={registerCheckpoint:(c,u)=>o.register(c.address,u),checkpointDrafts:o.checkpoint,restartUpdate:async()=>{if(i===void 0)throw Error("Restart is unavailable in this window. Your current draft has not been changed.");await i()},bindUpdateRestart:(c)=>{if(i!==void 0)throw Error("This terminal already owns an update restart action");return i=c,()=>{if(i===c)i=void 0}},read:()=>n,subscribe:(c)=>(s.add(c),()=>{s.delete(c)}),update:(c)=>{if(n=c,!r)r=!0,e.render(je(sxo,{store:a}));for(let u of s)u()}};return kcr.set(e,a),a}function Rcr(e){_7(e).update({})}function Dcr(e,t){return _7(e).bindUpdateRestart(t)}function oIt(e,t){_7(e).checkpointDrafts(t)}function Ocr(e,t,n){let r=_7(e),i=r.read(),o=(i.requested??0)+1,s=i.entries?.filter((a)=>a.props.session.address!==n.session.address)??[];r.update({entries:[...s,{props:{...n,onClose:()=>{let a=r.read();return r.update({...a,entries:a.entries?.filter((c)=>c.props.session.address!==n.session.address)??[]}),n.onClose?.()}},request:o}],configuration:i.configuration??nIt(n),queryClient:t,requested:o})}function Pcr(e,t){let n=_7(e);n.update({...n.read(),landing:{...t,choose:(r)=>{let i={...n.read()};delete i.landing,n.update(i),t.choose(r)}}})}function Mcr(e,t){let n=_7(e);n.update({...n.read(),picker:t})}var kcr;var sIt=C(async()=>{qc();I3();Gi();cge();BCt();await Mc([u7(),cw(),$h(),WTt(),hcr(),_cr(),EB(),J5(),_ge(),ULe(),iIt(),Ecr(),jCt()]);kcr=new WeakMap});import aIt from"process";import{StringDecoder as lxo}from"string_decoder";function dxo(e){return Buffer.byteLength(e,"utf8")}async function pxo(e=aIt.stdin,t){if(e.isTTY===!0)throw Error("fungi run requires a prompt or piped stdin");let n="",r=0,i=new lxo("utf8"),o=e[Symbol.asyncIterator](),s,a=t===void 0?void 0:new Promise((c,u)=>{s=()=>{let l=t.reason;u(l instanceof Error?l:Error("fungi run cancelled",{cause:l}))},t.addEventListener("abort",s,{once:!0})});try{t?.throwIfAborted();for(;;){let c=o.next(),u=a===void 0?await c:await Promise.race([c,a]);if(u.done===!0)break;let l=Buffer.isBuffer(u.value)?u.value:Buffer.from(u.value);if(r+=l.byteLength,r>Lcr)throw Error("fungi run prompt is too large");n+=i.write(l)}}finally{if(s!==void 0&&t!==void 0)t.removeEventListener("abort",s);try{await o.return?.()}catch(c){xi("one-shot-prompt-iterator-close",c)}}if(n+=i.end(),n.length===0)throw Error("fungi run prompt is empty");return n}function Ncr(e){if(e.role!=="assistant")return"";return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function fxo(e){if(e.kind==="heartbeat"||e.kind==="activity"||e.kind==="progress"||e.kind==="tool_output")return[];return e.kind==="reset"?e.baseline.messages:e.messages}function mxo(e){if(e.kind==="heartbeat"||e.kind==="activity"||e.kind==="progress"||e.kind==="tool_output")return[];return e.kind==="reset"?e.baseline.terminals:e.terminals}function $A(e,t){return e instanceof Error?e:Error(t,{cause:e})}function hxo(e){if(e.length===0)return;let t=e[0];if(e.length===1&&t!==void 0)throw t;throw AggregateError(e,"fungi run failed")}function gxo(e,t){return new Promise((n,r)=>{try{e.write(t,(i)=>{if(i===void 0||i===null)n();else r(i)})}catch(i){r($A(i,"fungi run output failed"))}})}async function _xo(e,t,n){try{await e.watch.close()}catch(r){n($A(r,"fungi run Session watch close failed"))}try{await e.changes.return?.()}catch(r){t.push($A(r,"fungi run Session watch stop failed"))}}function yxo(e,t,n){let{correlatedSequence:r,finalAssistant:i}=e;for(let s of fxo(t)){if(s.commandId===n&&s.value.role==="user"&&(r===void 0||s.sequence<r))r=s.sequence,i=void 0;if(r!==void 0&&s.value.role==="assistant"&&s.commandId===n&&s.sequence>r&&(i===void 0||s.sequence>i.sequence))i=s}let o=e.terminal;for(let s of mxo(t))if(s.commandId===n)o=s;return{correlatedSequence:r,finalAssistant:i,terminal:o}}function Fcr(e){if(e.requested)throw Error("fungi run cancelled")}async function xxo(e,t,n){let r={correlatedSequence:void 0,finalAssistant:void 0,terminal:void 0};for await(let i of{[Symbol.asyncIterator]:()=>e}){if(Fcr(n),i.kind==="heartbeat"||i.kind==="progress"||i.kind==="tool_output")continue;r=yxo(r,i,t);let o=r.terminal;if(o===void 0)continue;if(o.outcome!=="completed")throw Error(o.outcome==="failed"?zy(o.diagnostic):`fungi run ${o.outcome}`);if(r.finalAssistant===void 0)throw Error("fungi run settled without a durable assistant result");return r.finalAssistant}throw Error(n.requested?"fungi run cancelled":"fungi run Session watch ended before settlement")}async function L7e(e,t={}){let n=t.stdout??aIt.stdout,r=t.signals??aIt,i=t.requestId??YUe(),o=new AbortController,s={requested:!1,accepted:!1,abortStarted:!1},a=t.abortOnSignal??!0,c=[],u,l=()=>{if(s.requested)return;s.requested=!0,d(),o.abort()},d=()=>{if(!s.requested||!a||!s.accepted||s.abortStarted)return;s.abortStarted=!0;try{s.abortPromise=Promise.resolve(e.abort()).then(()=>{return},(f)=>{s.abortFailure=$A(f,"fungi run cancellation abort failed")})}catch(f){s.abortFailure=$A(f,"fungi run cancellation abort failed")}},p=Zh(Ct(function*(){yield*Da(Gt(()=>{r.on("SIGINT",l),r.on("SIGTERM",l)}),()=>Gt(()=>{r.off("SIGINT",l),r.off("SIGTERM",l)}));let f=t.prompt??(yield*ii({try:()=>pxo(t.stdin,o.signal),catch:(y)=>$A(y,"fungi run prompt failed")}));if(f.length===0)throw Error("fungi run prompt is empty");if(dxo(f)>Lcr)throw Error("fungi run prompt is too large");let m=yield*Da(ii({try:async()=>{let y=await e.watch();return{watch:y,changes:y.changes[Symbol.asyncIterator]()}},catch:(y)=>$A(y,"fungi run watch failed")}),(y)=>cf(()=>_xo(y,c,(x)=>{u=x}))),{changes:h}=m,g=yield*tg(Ct(function*(){let y=yield*ii({try:()=>e.command({type:"prompt",delivery:"followUp",requestId:i,text:f}),catch:(x)=>$A(x,"fungi run prompt failed")});if(y.commandId.length===0)throw Error("fungi run acceptance correlation failed");if(s.accepted=!0,s.requested)d();return y}));Fcr(s);let _=yield*ii({try:()=>xxo(h,g.commandId,s),catch:(y)=>$A(y,"fungi run failed")});yield*ii({try:()=>gxo(n,`${n.isTTY===!0?br(Ncr(_.value)):Ncr(_.value)}
|
|
2262
2262
|
`),catch:(y)=>$A(y,"fungi run output failed")})}));try{await e0(p,{signal:o.signal})}catch(f){c.unshift(s.requested?Error("fungi run cancelled"):$A(f,"fungi run failed"))}if(s.abortPromise!==void 0)await s.abortPromise;if(s.abortFailure!==void 0)c.push(s.abortFailure);if(u!==void 0)c.push(u);hxo(c)}var Lcr=262144;var cIt=C(()=>{ay();td();vr();iq();T7e();_y()});async function $cr(e,t,n,r={}){let[i,o]=await Promise.all([N1(r),t.length>1?null:Dyt({models:e,databasePath:t[0]?.databasePath,signal:n})]);return{account:i===void 0?o===null?void 0:`Signed in with ${o.providerId}`:`Fungi \xB7 ${i.team?.name??"no Team chosen"}`,model:o===null?void 0:FZ({provider:o.providerId,model:o.modelId},o.reasoning)}}var zcr=C(async()=>{bf();await vA()});import{pathToFileURL as vxo}from"url";function Ucr(e,t,n=!1){return ii({try:async()=>{let r=await Bun.resolve(e,t).catch((o)=>{if(n&&o instanceof Error&&"code"in o&&o.code==="ERR_MODULE_NOT_FOUND")return;throw o});if(r===void 0)return;let i=bxo(await import(vxo(r).href));return lU(i.default)},catch:(r)=>Error(`Client extension unavailable: ${e}`,{cause:r})})}var bxo;var jcr=C(()=>{vr();tr();AR();bxo=en(re({default:Ea}))});function wxo(e,t,n,r,i){return oH(iH((o)=>Da(Gt(()=>{let s=()=>{Cx(o)};if(r.addEventListener("abort",s,{once:!0}),r.aborted)s();let a={state:"unknown"},c,u,l=()=>{let m=n?.snapshot().open?.host.snapshot(),h=m?.status==="prompting"||m?.status==="working"&&m.handoff!==void 0?{state:"blocked"}:a.state==="blocked"?a:m?.status==="working"?{state:"working"}:a;if(h.state===c?.state&&h.header===c.header)return;c=h,dh(o,h)},d=()=>{u?.(),u=n?.snapshot().open?.host.subscribe(l),l()},p=n?.subscribe(d),f=tft(t,e,(m)=>{a=m,l()},i);return d(),()=>{r.removeEventListener("abort",s),f(),p?.(),u?.()}}),(s)=>Gt(s)),{bufferSize:1,strategy:"sliding"}).pipe(Q7t(()=>!r.aborted)))}function Bcr(e){return Ct(function*(){let t=(e.clients??[]).map((o)=>lU(o)),n=new Set(t.map((o)=>o.id));if(n.size!==t.length)return yield*it(Error("Duplicate builtin client extension"));let r=e.entries.map((o)=>({entry:o,root:e.invocationRoot})),i=yield*ws(r,({entry:o,root:s})=>Ucr(o,s).pipe(mt((a)=>{if(a===void 0)return rt(void 0);if(n.has(a.id))return it(Error(`Duplicate client extension: ${a.id}`));return n.add(a.id),rt(a)}),Cs((a)=>Gt(()=>{e.onError(a);return})))).pipe(Mn((o)=>[...t,...o.filter((s)=>s!==void 0)]),Xy);return{entries:U0(i),attach:(o,s)=>yI(i).pipe(hxe,mt((a)=>ws(a,(c)=>c.attach===void 0?Ln:Zh(Ct(function*(){let u=new AbortController;yield*ch(()=>Gt(()=>{u.abort()}));let l=c.attach?.({activity:wxo(o,e.queryClient,s,u.signal,e.questionExtensionId),signal:u.signal,onError:e.onError});if(l!==void 0)yield*l}).pipe(Wn(tD))).pipe(zl((u)=>Gt(()=>{if(af(u))return;let l=_u(u);e.onError(l instanceof Error?l:Error("Client extension attachment failed",{cause:u}))})),Xy),{discard:!0})),Wn(tD),Xy,wm)}})}var qcr=C(()=>{bf();AR();Fc();vr();ES();Gf();_I();jcr()});var Wcr;var Hcr=C(()=>{qn();Wcr=Ke({error:Ee("App execution unavailable"),reason:an(["exec_isolation_required","execution_not_admitted","artifact_unavailable","disabled"])})});function Gcr(e,t){let n=Wcr.safeParse(e);if(!n.success||n.data.reason!=="exec_isolation_required"&&n.data.reason!=="disabled")return;return $1n({viewId:t.id,title:t.title,state:"error",rows:[],reason:n.data.reason,error:n.data.reason==="disabled"?`${t.title} is disabled.`:`${t.title} isn't available on this preview.`})}var Vcr=C(()=>{uU();Hcr();uU()});var Sxo;var Kcr=C(()=>{tr();vr();_S();eZ();Sxo=qW()([],()=>(e,t,n)=>Un({try:()=>kir(e,n.onExcessProperty==="error"),catch:()=>new _b(t,e,n)}))});var Xcr,Jcr,Qcr,uIt,kxo,Txo;var lIt=C(()=>{Kcr();XAt();tr();i7e();Uge();IB();Z5();Uge();IB();Uge();Xcr={artifactRef:rZ,digest:Ew,version:Ce.pipe(ot(Jn(1))),byteLength:Zn.pipe(ot(id()),ot(_s(0)),ot(mr(Number.isSafeInteger)))},Jcr=re({...Xcr,mediaType:Bt(["text/html; charset=utf-8","application/vnd.fungi.app-assets+json"])}),Qcr=re({...Xcr,mediaType:Be("application/vnd.fungi.app-backend+json")}),uIt={declaration:yt(l7e)},kxo=vn([re({format:Be("fungi-app-v1"),ui:Jcr,backend:Qcr,...uIt}),re({format:Be("fungi-app-v1"),ui:Jcr,...uIt}),re({format:Be("fungi-app-v1"),backend:Qcr,...uIt})]).pipe(ot(mr((e)=>e.declaration?.api===void 0||("backend"in e),{message:"An App API requires a backend"}))),Txo=Ti(kxo)});var Axo,Cxo,Ixo;var Ycr=C(()=>{tr();eZ();Axo=Bt(["durable-facet","region"]),Cxo=re({runtime:re({kind:Axo,stateSchema:Zn.pipe(ot(id()),ot(_s(0)))}),compatibilityDate:Ce.pipe(ot(Ja(/^\d{4}-\d{2}-\d{2}$/))),exportName:Ce.pipe(ot(Jn(1))),code:Ce.pipe(ot(Jn(1)))}),Ixo=Ti(Cxo)});var Zcr;var F7e=C(()=>{Z5();gor();Zcr=Object.freeze({maxBytes:65536})});var tur=C(()=>{lIt();IB();Ycr();F7e()});var dIt=()=>{};var Rxo,Dxo,Oxo;var $7e=C(()=>{tr();Z5();Rxo=vn([re({kind:Be("absent")}),re({kind:Be("ambiguous")}),re({kind:Be("unselected"),app:h7,surface:C6}),re({kind:Be("selected"),app:h7,surface:C6,releaseId:A6,currentReleaseId:A6,sequence:Zn.pipe(ot(id()),ot(_s(0))),release:iCt})]),Dxo=vn([re({kind:Be("success"),value:dn(Rxo)}),re({kind:Be("failure"),failure:re({kind:Be("unavailable")})})]),Oxo=yn(Dxo,{onExcessProperty:"error"})});var nur=C(()=>{dIt();Z5();$7e();F7e()});function z7e(e){return(e.startsWith("/")?e.slice(1):e).replaceAll("-","").replaceAll("_","").replaceAll("1","i").replaceAll("l","i").replaceAll("0","o").replaceAll("5","s").replaceAll("3","e")}var Lxo;var rur=C(()=>{tr();Z5();Lxo=re({platformRoutes:dn(re({appId:RB,stableRoute:iZ})),structuralRoutes:dn(iZ)}).pipe(ot(mr((e)=>{let t=e.platformRoutes.map(({stableRoute:n})=>z7e(n));return new Set(t).size===t.length},{message:"Platform route assignments conflict"})),ot(mr((e)=>{let t=new Set(e.structuralRoutes.map(z7e));return!e.platformRoutes.some(({stableRoute:n})=>t.has(z7e(n)))},{message:"Platform route assignments conflict with structural routes"})))});var iur=C(()=>{rur();$7e()});var our=C(()=>{$7e();Z5()});var sur=()=>{};var aur=C(()=>{tur();dIt();Z5();F7e();nur();iur();our();sur();Z5()});var cur,Fxo,uur,lur,U7e,dur,$xo,pur,fur,zxo,Uxo,jxo,Bxo,qxo,mur,Wxo,pIt,Hxo,Gxo,Vxo,iac;var hur=C(()=>{tr();lIt();eZ();aur();uU();qn();cur=or(()=>Nt([Ke({kind:Ee("default"),appId:D().min(1)}),Ke({kind:Ee("installation"),installationId:D().min(1)})])),Fxo=or(()=>Ke({requestId:D().min(1),address:cur,authorityVersion:et().int().positive(),state:an({unaffected:"unaffected",pending:"pending",applied:"applied",expired:"expired"}),outstanding:et().int().nonnegative()})),uur=Ke({address:cur,installationId:D().min(1).nullable(),surfaceId:D().min(1),appId:D().min(1),displayName:D().trim().min(1).optional(),icon:D().min(1).nullable().optional(),releaseId:D().min(1).nullable(),authorityVersion:et().int().nonnegative(),enforcement:Fxo.nullable(),handlers:Ge(Ee("file.open")),roles:Ge(D().min(1)),declaredCapabilities:Ge(D().min(1)),calls:Ve().transform((e)=>en(u7e)(e)).optional(),commands:Ge(Ve()).transform((e)=>e.map((t)=>en(c7e)(t))),gills:Ge(Ve()).transform((e)=>e.map((t)=>en(LIe,{onExcessProperty:"error"})(t))),availability:an({available:"available",unavailable:"unavailable"}),surface:Ke({stableRoute:D().min(1)}).nullable(),surfacePath:D().startsWith("/")}),lur=Ke({surfaceId:D().min(1).nullable(),chosen:Tn()}),U7e=zf(Hu(Ew)),dur=zf(Hu(a7e)),$xo=et().int().positive(),pur=Ge(D().min(1)).refine((e)=>new Set(e).size===e.length,"Operations must be unique").readonly(),fur=qe(D().min(1),D().min(1)).readonly(),zxo=Ke({kind:D().min(1),id:D().min(1)}).readonly(),Uxo=Ke({capability:dur,capabilityApproved:Ee(!0),operations:pur,fingerprints:fur,resources:Nt([Ee("tenant-scope"),Ge(zxo).readonly()])}).readonly(),jxo=Ke({authorityVersion:et().int().positive(),declaredOperationsDigest:U7e,approvedGrants:Ge(Uxo).refine((e)=>new Set(e.map((t)=>t.capability)).size===e.length,"Capabilities must be unique").refine((e)=>e.every((t)=>{let n=Object.keys(t.fingerprints);return n.length===t.operations.length&&t.operations.every((r)=>n.includes(r))}),"Every approved operation needs exactly one fingerprint").readonly(),approval:Ke({by:r7e,at:et().int().nonnegative(),authorityVersion:$xo}).readonly().nullable()}),Bxo=Ke({artifactDigest:U7e,digest:U7e,capabilities:Ge(Ke({capability:dur,operations:pur,fingerprints:fur}).readonly()).readonly()}),qxo=Ke({authority:jxo.nullable(),declaredOperations:Bxo,artifactDigest:U7e,canEdit:Tn()}),mur=or(()=>Ke({actorIsTeamOwner:Tn(),needsUpdate:Ge(Ke({installationId:D().min(1).nullable(),appId:D().min(1).nullable(),displayName:D().min(1)})).optional(),apps:Ge(uur.extend({override:Ke({appId:D().min(1).optional(),releaseId:D().min(1),surfaceRoute:D().min(1).nullable()}).nullable(),permission:qxo.nullable()})),roles:qe(D().min(1),lur)})),Wxo=or(()=>Ge(Ke({key:D().max(64),label:D().max(256),kind:an(["computer","repository","branch"]),required:Tn(),options:D().max(256).optional()})).max(4).refine(Hu(hut),"Invalid Gill placement parameters")),pIt=Ke({view:Ee("rows"),id:D().trim().min(1).max(256),title:D().trim().min(1).max(256),params:Wxo.optional(),desktop:Ke({sizes:Ge(an({S:"S",M:"M",L:"L"})).min(1).max(3).refine((e)=>new Set(e).size===e.length,"Repeated Gill size")}).optional()}),Hxo=es("view",[pIt,pIt.omit({params:!0}).extend({view:Ee("surface"),desktop:pIt.shape.desktop.unwrap()})]),Gxo=uur.pick({surfaceId:!0,appId:!0,displayName:!0}).extend({gills:Ge(Hxo).max(16)}),Vxo=or(()=>Ke({apps:Ge(Gxo).max(50),roles:Ke({inbox:lur.optional()})})),iac=or(()=>Nt([Vxo,Ke({error:D()})]))});async function gur(e={}){let t={...e,credentialPath:e.credentialPath??is().credentialPath},n=await N1(t);if(n?.team===void 0)throw Error("Sign in to Fungi and choose a Team to view its Apps");let{team:r,issuer:i}=n,o=new URL(n.issuer).origin,s=`/api/teams/${encodeURIComponent(r.teamId)}`,a=iX(o,t);async function c(){let l=await N1(t);if(l?.issuer!==i||l.team?.teamId!==r.teamId)throw Error("The selected Fungi Team changed; reopen the App pane")}async function u(l){await c();let d=await a(`${o}${s}/local/apps`,{signal:l??null});if(!d.ok)throw await d.body?.cancel(),Error(`App directory refused with HTTP ${String(d.status)}`);let p=await d.json();return await c(),l?.throwIfAborted(),mur.parse(p)}return{team:r,read:u,async surfaceUrl(l,d){let f=(await u(d)).apps.find((h)=>h.surfaceId===l);if(f?.availability!=="available"||f.surface===null||f.releaseId===null)throw Error("That App is not available in the selected Team");let m=new URL(f.surfacePath,o);if(m.origin!==o)throw Error("The App surface is not on the selected Hub");return m.searchParams.set("authorityVersion",String(f.authorityVersion)),m.searchParams.set("releaseId",f.releaseId),m.searchParams.set("surfaceRoute",f.surface.stableRoute),await c(),m},async openSession(l,d){await c(),d.throwIfAborted();let p=Object.assign(async(h,g)=>(await c(),d.throwIfAborted(),a(h,{...g,signal:AbortSignal.any([d,...g?.signal?[g.signal]:[]])})),{preconnect:globalThis.fetch.preconnect});class f extends $X{constructor(h){super(h,{fetch:p})}}let m=aU({baseUrl:`${o}${s}/local/agents/${encodeURIComponent(l.agentId)}`,fetch:p,eventSource:f});try{let h=m.session(l.sessionId);return await h.read(),await c(),d.throwIfAborted(),{session:h,close:m.close}}catch(h){throw await m.close(),Error("The selected Team Session could not be opened",{cause:h})}},async requestGill(l,d,p){let m=(await u(p)).apps.find((x)=>x.surfaceId===l),h=m?.gills.find((x)=>x.id===d.viewId);if(m===void 0||h===void 0||m.availability!=="available"||m.releaseId===null)throw Error("That Gill is not available in the selected Team");let g=m.address.kind==="default"?`default/${encodeURIComponent(m.address.appId)}`:encodeURIComponent(m.address.installationId),_=new URL(`${s}/apps/${g}/gills`,o);if(_.searchParams.set("authorityVersion",String(m.authorityVersion)),_.searchParams.set("releaseId",m.releaseId),m.surface!==null)_.searchParams.set("surfaceRoute",m.surface.stableRoute);await c();let y=await j1n({decodeRefusal:Gcr,endpoint:_.href,fetch:a,declaration:h}).request(d,p);return await c(),p?.throwIfAborted(),y}}}var _ur=C(async()=>{Vcr();Tbt();ny();q_();hur();uU();await t2()});import{spawn as Kxo}from"child_process";function Jxo(e){return new Promise((t,n)=>{let r=Kxo(process.platform==="darwin"?"open":"xdg-open",[e.href],{stdio:"ignore"});r.once("error",(i)=>{n(Error("The App could not open in your browser",{cause:i}))}),r.once("exit",(i)=>{if(i===0)t();else n(Error("The browser launcher did not open the App"))})})}function yur(e,t=()=>gur({credentialPath:e})){let n,r=()=>n??=t().catch((o)=>{throw n=void 0,o});return{apps:{signedIn:async()=>(await N1({credentialPath:e}))?.team!==void 0,read:async(o)=>(await r()).read(o),requestGill:async(o,s,a)=>(await r()).requestGill(o,s,a),openUi:async(o,s)=>Jxo(await(await r()).surfaceUrl(o,s))},openSession:async(o,s)=>(await r()).openSession(o,s)}}var xur=C(async()=>{await Mc([vA(),_ur()])});function vur(e,t,n){return[{id:"archive",title:"Archive an Agent",category:"Conversation",description:"Hide an Agent from this folder's lists; keep its conversations and files.",projections:{palette:{},help:{},slash:{aliases:["archive"],consumesDraft:!0}},handler:async({interaction:r})=>{if(r===void 0)throw Error("Archiving an Agent needs a person.");let{agents:i}=await t.discover(e,{signal:r.signal});if(i.length===0){r.notify({type:"info",message:"No Agents to archive."});return}if(i.length>256)throw Error("Use fungi agents list, then fungi agents archive <agent-id>.");let o=await r.prompt({type:"choice",message:"Archive which Agent?",summary:"Its conversations and files stay.",options:i.map((c)=>({value:c.agentId,label:fIt(c),description:Qxo(c.sessionCount)}))}),s=i.find((c)=>c.agentId===o);if(s===void 0)throw Error("Choose a listed Agent.");if(!await r.prompt({type:"confirmation",message:`Archive ${oq(fIt(s),40)}?`,summary:"Its conversations and files stay. You can restore it later.",facts:[{label:"Chats",value:String(s.sessionCount)}],details:[{label:"Agent ID",value:o}],confirmLabel:"Archive",cancelLabel:"Keep Agent",destructive:!0}))return{cancelled:!0};await r.run(()=>t.archive({invocationRoot:e,agentId:o,archived:!0},{signal:r.signal})),r.notify({type:"success",message:`Archived ${fIt(s)}. Restore with fungi agents unarchive ${o}.`});return}},{id:"extensions",title:"Manage extensions",category:"Settings",description:"List, add, remove, enable or disable installed extensions and skills.",projections:{palette:{},help:{},slash:{aliases:["extensions"],consumesDraft:!0}},handler:async({interaction:r})=>{if(r===void 0)throw Error("Managing extensions needs a person.");await Xxo(e,r,n)}}]}async function Xxo(e,t,n){let r=["list","add","remove","enable","disable"],i=await t.prompt({type:"choice",message:"Manage extensions",summary:"Extensions add tools, programs and skills to your Agents.",options:[{value:"list",label:"List installed extensions"},{value:"add",label:"Add an extension",description:"Install trusted code from Git, npm or a local path"},{value:"remove",label:"Remove an extension"},{value:"enable",label:"Enable an extension or its skills"},{value:"disable",label:"Disable an extension or its skills"}]}),o=r.find((l)=>l===i);if(o===void 0)throw Error("Choose a listed action.");let s=n(),a={...s,add:(...l)=>t.run(()=>s.add(...l)),list:(...l)=>t.run(()=>s.list(...l)),remove:(...l)=>t.run(()=>s.remove(...l)),enableProject:(...l)=>t.run(()=>s.enableProject(...l)),disableProject:(...l)=>t.run(()=>s.disableProject(...l)),enableAgent:(...l)=>t.run(()=>s.enableAgent(...l)),disableAgent:(...l)=>t.run(()=>s.disableAgent(...l)),enableAgentSkills:(...l)=>t.run(()=>s.enableAgentSkills(...l)),disableAgentSkills:(...l)=>t.run(()=>s.disableAgentSkills(...l))},c=[];if(o==="add")c.push(await t.prompt({type:"text",message:"Add an extension",summary:"Extensions run inside Fungi with access to every Agent.",placeholder:"Git URL, npm package or folder path"}));else if(o!=="list"){let l=await a.list();if(l.length===0){t.notify({type:"info",message:"No extensions installed."});return}if(l.length>256)throw Error("Use fungi extension list to manage this many extensions.");if(o==="enable"||o==="disable")c.push(await t.prompt({type:"choice",message:o==="enable"?"Turn it on where?":"Turn it off where?",options:[{value:"project",label:"This folder's client and programs"},{value:"agent",label:"This folder's Agent tools"},{value:"skills",label:"This folder's Agent skills"}]}));let d=await t.prompt({type:"choice",message:o==="remove"?"Remove which extension?":"Which extension?",options:l.map((p)=>({value:p.id,label:p.id,description:p.version}))});if(o==="remove"&&!await t.prompt({type:"confirmation",message:`Remove ${oq(d,40)}?`,summary:"It stops working in every folder where it was turned on.",details:[{label:"Extension",value:d}],confirmLabel:"Remove",cancelLabel:"Keep extension",destructive:!0}))return;c.push(d)}let u="";await Q8e({action:o,arguments:c,cwd:e,stdout:{write:(l)=>{u+=l}},confirm:(l)=>t.prompt({type:"confirmation",message:l,confirmLabel:"Add skills",cancelLabel:"Skip"})},a),t.notify({type:o==="list"?"info":"success",message:u.trim()})}var fIt=(e)=>e.name??"Unnamed Agent",Qxo=(e)=>`${String(e)} conversation${e===1?"":"s"}`;var bur=C(()=>{bf();X8e()});function mIt(e){let t=new Map;for(let r of e)t.set(r.kind,(t.get(r.kind)??0)+1);let n=[...t.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>`${String(i)} ${r}`).join(", ");return`Skipped ${String(e.length)} saved conversation${e.length===1?"":"s"} (${n}).`}function j7e(e){if(e.connect!==void 0)throw Error("--connect is unavailable; fungi uses the persistent Local service");if(e.listen!==void 0)throw Error("--listen is unavailable until the shared Local service exposes client sharing");if(e.providerId!==void 0||e.modelId!==void 0||e.reasoning!==void 0)throw Error("Session model selection requires the shared Local preference contract")}async function wur(e){let{options:t,serviceManager:n,renderPicker:r,root:i,theme:o,signal:s,destroyed:a,onNotice:c}=e;if(t.sessionChoice!==void 0)return t.sessionChoice.resume({signal:s,fungiMcp:t.fungiMcp,mode:t.mode});if((t.entry==="landing"||t.entry==="new")&&!t.resume){let d=()=>(e.discoverSessions??n.discover)(t.invocationRoot,{signal:s}),p=await d();if(p.problems.length>0)c(mIt(p.problems));let f=()=>p.agents.filter((y)=>y.unreadable===void 0),m=f().length>1?void 0:f()[0],h=()=>{let y=m?.databasePath;if(y===void 0){if(f().length>1)throw new Rj(f().map((x)=>x.agentId));return n.connect({invocationRoot:t.invocationRoot,mode:t.mode,fungiMcp:t.fungiMcp},{signal:s})}return n.createSession({invocationRoot:t.invocationRoot,databasePath:y,requestId:hIt.request.generate(),mode:t.mode,fungiMcp:t.fungiMcp},{signal:s})};if(t.entry==="new")return h();if(a())return;let g=(y,x,w)=>new Promise((b)=>{let E=()=>{A(void 0)},A=(R)=>{s.removeEventListener("abort",E),b(R)};if(s.addEventListener("abort",E,{once:!0}),s.aborted){E();return}e.renderLanding(i,y,t.invocationRoot,A,o,x,w)}),_;for(;;){let y=m===void 0?[]:p.sessions,x=await g(y,p.agents,_);if(_=void 0,x?.kind==="archive"){let b=p.agents[x.index];if(b===void 0||s.aborted||a())return;try{await n.archive({invocationRoot:t.invocationRoot,agentId:b.agentId,archived:!0},{signal:s})}catch(E){if(E instanceof Error&&E.name==="AbortError")throw E;_=E instanceof Error?E.message:"The Agent could not be archived"}p=await d(),m=f().length>1?void 0:f()[0];continue}if(x?.kind==="agent"){let b=p.agents[x.index];if(b===void 0)return;if(b.unreadable!==void 0){_=b.unreadable;continue}if(m=b,y=p.sessions.filter((E)=>E.databasePath===b.databasePath),x=a()?void 0:await g(y,[b]),x===void 0&&!a()&&!s.aborted){m=void 0;continue}}if(x===void 0||a())return;if(x.kind==="new")return h();if(x.kind==="agent")return;let w=y[x.index];if(w===void 0)return;return w.resume({signal:s,fungiMcp:t.fungiMcp,mode:t.mode})}}let u=t.databasePath===void 0&&t.connect===void 0&&(t.resume||t.sessionId===void 0)?await(e.discoverSessions??n.discover)(t.invocationRoot,{signal:s}):void 0;if(u!==void 0&&(t.resume||u.agents.length>1)){if(u.problems.length>0)c(mIt(u.problems));let d=u.sessions[0];if(d===void 0)throw Error(u.problems.length>0?mIt(u.problems):"No saved conversations in this folder");if(j7e(t),t.last)return d.resume({signal:s,fungiMcp:t.fungiMcp,mode:t.mode});if(a())return;let p=await new Promise((f)=>{let m=()=>{h(void 0)},h=(g)=>{s.removeEventListener("abort",m),f(g)};if(s.addEventListener("abort",m,{once:!0}),s.aborted){m();return}r(i,u.sessions,(g)=>{h(u.sessions[g])},()=>{h(void 0)},o)});if(p===void 0||a())return;return p.resume({signal:s,fungiMcp:t.fungiMcp,mode:t.mode})}if(t.connect!==void 0)throw Error("--connect is unavailable; fungi uses the persistent Local service");if(t.listen!==void 0)throw Error("--listen is unavailable until the shared Local service exposes client sharing");j7e(t);let l=t.databasePath===void 0?{invocationRoot:t.invocationRoot,fungiMcp:t.fungiMcp,sessionId:t.sessionId,mode:t.mode}:{invocationRoot:t.invocationRoot,fungiMcp:t.fungiMcp,databasePath:t.databasePath,sessionId:t.sessionId,mode:t.mode};return n.connect(l,{signal:s})}var hIt;var gIt=C(async()=>{KC();await cw();hIt=Ha({family:"tui-session-create-request",version:1,kinds:{request:{prefix:"request"}}})});import{homedir as Yxo}from"os";async function Eur(e,t,n,r=Yxo()){let i=V3(r),{terminal:o,root:s,commands:a,queryClient:c,serviceManager:u,theme:l}=n,d=await e0(Yh()),p=yur(i),f,m=[],h,g=new Set,_=!1,y=await e0(t.prepareClientExtensions({invocationRoot:e.invocationRoot,entries:e.extensions??[],clients:e.clients,questionExtensionId:e.questionExtensionId,queryClient:c,onError:(Pe)=>{if(n.onDiagnostic(Pe),o.destroyed())return;let J=`Client extension: ${Pe.message}`;if(g.size===0)m.push(J);else for(let te of g)te.interactionStore.report({tone:"error",message:J})}}).pipe(vm(d))),x=await e0(y.entries),w,b,E,A=Promise.withResolvers(),R,L,z=()=>w!==void 0,j=(Pe=!1)=>{if(!Pe&&t.automaticInstalledRestart===!1||o.destroyed()||h===void 0||z()||t.checkInstalledUpdate===void 0)return Promise.resolve(!1);return R??=(async()=>{let J=h,te=[J,...[...g].filter((ce)=>ce!==J)],ye=await t.checkInstalledUpdate?.(te.map(({host:ce})=>({invocationRoot:e.invocationRoot,sessionId:ce.sessionId})));if(o.destroyed()||h!==J||z()||g.size!==te.length||ye===void 0)return!1;if(ye.kind==="restart"&&n.restartInstalledUpdate!==void 0)return t.checkpointDrafts(s,te.map(({host:ce})=>ce.session.address)),n.restartInstalledUpdate(ye),o.setQuitGuard(void 0),o.exit(),!0;return!1})().finally(()=>{R=void 0}),R},G=Dcr(s,async()=>{if(!await j(!0)||!o.destroyed())throw Error("The installed update is not ready to restart. Keep this window open and try again.")}),ee=()=>{if(t.automaticInstalledRestart===!1||t.checkInstalledUpdate===void 0||o.destroyed())return;L=setTimeout(()=>{j().catch((Pe)=>{n.onDiagnostic(Rd(Pe,"Installed update restart check failed"))}).finally(ee)},1000)};o.setExitHandler(()=>{A.resolve(void 0)});let ie=!1,le=(Pe)=>{ie=!0,o.inputHandoff?.pause(),t.renderServiceUpdated(s,Pe.message,o.exit)},be=(Pe)=>e0(bs(Pe,Sa)),xe=(Pe)=>wur({options:Pe,serviceManager:u,discoverSessions:t.discoverSessions,renderPicker:(...J)=>{o.inputHandoff?.pause(),t.renderPicker(...J)},renderLanding:(...J)=>{o.inputHandoff?.pause(),t.renderLanding(...J)},root:s,theme:l(),signal:o.signal,destroyed:o.destroyed,onNotice:(J)=>{f=J}}),B=async(Pe,J,te)=>{let ye=await e0(Da(ii({try:Pe,catch:(de)=>Rd(de,"Session selection failed")}),(de)=>ii({try:()=>de?.close()??Promise.resolve(),catch:(Se)=>Rd(Se,"Selected client close failed")}).pipe(Np)).pipe(vm(J)));if(ye===void 0||o.destroyed()||te.aborted)return;if(g.size===0)o.inputHandoff?.capture();let ce=await e0(Da(Gt(KK),(de)=>Gt(de.close)).pipe(vm(J)));return{host:ye,scope:J,interactionStore:ce}},K=(Pe,J,te)=>{if(w!==void 0||o.destroyed())return Promise.reject(Error("Another Local transition is already pending"));return w=(async()=>{let ye=await e0(pne(d,"sequential")),ce=!1,de;try{let Se=await B(Pe,ye,o.signal);if(Se===void 0)return;let{host:Oe,interactionStore:he}=Se,Re=[...g].find((nt)=>nt.host.agentId===Oe.agentId&&nt.host.sessionId===Oe.sessionId);if(Re!==void 0){h=Re,ue(Re,J,te);return}let Ze=h;h=Se,g.add(Se),_=!0;try{ue(Se,J,te)}catch(nt){throw h=Ze,g.delete(Se),nt}if(ce=!0,!o.destroyed())await e0(y.attach(Oe.session,he).pipe(vm(ye)))}catch(Se){if(Se instanceof r6){if(!o.destroyed())le(Se);return}throw de=Rd(Se,"Session selection failed"),de}finally{if(!ce)await be(ye).catch((Se)=>{throw R6(de,[Rd(Se,"Candidate client cleanup failed")])})}})().finally(()=>{w=void 0}),w.catch((ye)=>{xi("session-selection-callback",ye)}),w},X=async(Pe,J,te)=>{let ye=b??=hIt.request.generate();await K(()=>u.createSession({invocationRoot:e.invocationRoot,databasePath:Pe,requestId:ye,fungiMcp:e.fungiMcp},{signal:o.signal}),J,te),b=void 0},Y=async(Pe)=>{if(o.destroyed())return;let J=h??[...g].at(-1);if(J===void 0)throw Error("No conversation is open to start from");await X(J.host.databasePath,void 0,Pe)},fe=(Pe)=>{let{host:J}=Pe,te=()=>!o.destroyed()&&g.has(Pe),ye=!1,ce=async(de)=>{if(!te())return;await X(J.databasePath,de)};return{folder:rIt(e.invocationRoot),onStopAll:async()=>{if(!te())throw Error("The selected Agent changed.");return J.stopAll()},acquireSession:Z,apps:p.apps,paneKinds:e.paneKinds,commandHost:o.commandHost,setQuitGuard:o.setQuitGuard,target:{kind:"conversation",agentId:J.agentId,sessionId:J.sessionId},onClose:async()=>{if(!g.delete(Pe))return;if(h===Pe)h=void 0;await be(Pe.scope)},openConversation:Y,chooseConversation:(de)=>K(()=>xe({...e,mode:void 0,sessionId:void 0,databasePath:void 0,resume:!0,last:!1}),void 0,de),interactionStore:Pe.interactionStore,clients:x,inputHandoff:o.inputHandoff,initialCommandError:[e.initialCommandError,...m].filter((de)=>de!==void 0).join(`
|
|
2263
2263
|
`)||void 0,initialCommandNotice:f,sessionTitle:async(de)=>(await(t.discoverSessions??u.discover)(e.invocationRoot,{signal:de})).sessions.find((Se)=>Se.sessionId===J.sessionId)?.title,modelSource:{account:n.account,identity:J.session.address,models:(de)=>u.models({signal:de}),effectiveModel:(de)=>J.effectiveModel({signal:de}),modelPreference:J.session.modelPreference},sandboxSource:{identity:JSON.stringify([J.agentId,J.sessionId]),read:(de)=>J.sandboxStatus({signal:de}),setMode:async(de,Se)=>{if(!te())throw Error("The selected Agent changed.");Se.throwIfAborted(),await(await u.connect({invocationRoot:e.invocationRoot,databasePath:J.databasePath,sessionId:J.sessionId,mode:de,fungiMcp:e.fungiMcp},{signal:Se})).close()},rules:{list:(de)=>Promise.resolve().then(()=>(de.throwIfAborted(),yme(e.invocationRoot,"list"))),remove:(de,Se)=>Promise.resolve().then(()=>{if(!te())throw Error("The selected Agent changed.");return Se.throwIfAborted(),yme(e.invocationRoot,"remove",de)})}},reloadSources:Zxo,onResume:async(de)=>{if(!te())return;await K(()=>xe({...e,mode:void 0,databasePath:void 0,sessionId:void 0,resume:!0,last:!1}),de)},onNew:(de)=>ce(de),onForked:async(de,Se)=>{if(!te())return;await K(()=>xe({...e,mode:void 0,databasePath:J.databasePath,sessionId:de}),Se)},onRebindService:(de)=>J.rebind({signal:de}),onObservationUnavailable:async()=>{if(!te()||ye)return!te();ye=!0;try{if(await j())return!0;return await u.status(),!te()}catch(de){if(de instanceof r6){if(te())le(de);return!0}return n.onDiagnostic(Rd(de,"Service protocol check failed")),!1}finally{ye=!1}}}},V=(Pe)=>{let J=fe(Pe),te=l();return{agentName:"Shiitake",folder:J.folder,clients:J.clients,interactions:J.interactionStore,models:J.modelSource,sandbox:J.sandboxSource,stopAll:J.onStopAll,sessionTitle:J.sessionTitle,reload:J.reloadSources,observationUnavailable:J.onObservationUnavailable,rebindService:J.onRebindService,themeName:te.initialTheme,saveTheme:te.onThemeConfirm,themeError:te.themeError,initialError:J.initialCommandError,initialNotice:J.initialCommandNotice,resume:J.onResume,create:J.onNew,forked:J.onForked,inputHandoff:J.inputHandoff}},Z=async(Pe,J)=>{if(Pe.sessionId!==null&&![...g].some((Se)=>Se.host.agentId===Pe.agentId)){if(!(await(t.discoverSessions??u.discover)(e.invocationRoot,{signal:J})).sessions.some((Oe)=>Oe.sessionId===Pe.sessionId)){let Oe=await p.openSession({agentId:Pe.agentId,sessionId:Pe.sessionId},J);return{session:Oe.session,close:Oe.close,context:{themeName:l().initialTheme,themeError:l().themeError,saveTheme:l().onThemeConfirm,reload:[Sur],clients:x,interactions:KK()}}}}let te=await e0(pne(d,"sequential")),ye=!1,ce,de;try{let Se=[...g].find((nt)=>nt.host.agentId===Pe.agentId),he=await B(async()=>{if(Se!==void 0){if(Pe.sessionId===null)return u.createSession({invocationRoot:e.invocationRoot,databasePath:Se.host.databasePath,requestId:Pe.createRequestId,fungiMcp:e.fungiMcp},{signal:J});return u.connect({invocationRoot:e.invocationRoot,databasePath:Se.host.databasePath,sessionId:Pe.sessionId,fungiMcp:e.fungiMcp},{signal:J})}let tt=(await(t.discoverSessions??u.discover)(e.invocationRoot,{signal:J})).sessions.find((kt)=>kt.sessionId===Pe.sessionId);if(tt===void 0)throw Error("That Session is not available through Local");return tt.resume({signal:J,fungiMcp:e.fungiMcp})},te,J);if(he===void 0)throw Error("Pane Session acquisition was cancelled");if(he.host.agentId!==Pe.agentId)throw Error("Local returned a different Agent for this Session");if(Pe.sessionId!==null&&he.host.sessionId!==Pe.sessionId)throw Error("Local returned a different Session");ce=he,g.add(he),await e0(y.attach(he.host.session,he.interactionStore).pipe(vm(te)));let Re=V(he),Ze=fe(he).onClose;return ye=!0,{session:he.host.session,context:Re,close:Ze}}catch(Se){throw de=Rd(Se,"Pane Session acquisition failed"),de}finally{if(!ye){if(ce!==void 0)g.delete(ce);await be(te).catch((Se)=>{throw R6(de,[Rd(Se,"Pane Session cleanup failed")])})}}},ue=(Pe,J,te)=>{t.render(s,c,Pe.host.session,a,o.exit,l(),{...fe(Pe),replacePaneId:J,openPlacement:te}),m.length=0},Le=a.contribute({sourceId:"local-management",namespace:"local",commands:vur(e.invocationRoot,u,()=>zR({home:r}))});try{let Pe=e;while(!o.destroyed())try{t.renderConnecting(s),await K(()=>xe(Pe));break}catch(ye){if(xi("session-connect-recovery",ye),o.destroyed())break;if(o.inputHandoff?.pause(),!await new Promise((de,Se)=>{let Oe=(Re)=>{o.signal.removeEventListener("abort",he),de(Re)},he=()=>{Oe(!1)};o.signal.addEventListener("abort",he,{once:!0});try{t.renderRecovery(s,Rd(ye,"Connection unavailable"),()=>{if(ye instanceof om)Pe={...e,databasePath:void 0,sessionId:void 0,sessionChoice:void 0,connect:void 0,resume:!1,last:!1,entry:"new"};Oe(!0)},o.exit)}catch(Re){o.signal.removeEventListener("abort",he),Se(Rd(Re,"Connection recovery display failed"))}}))break;o.inputHandoff?.capture()}let J=()=>_,te=()=>ie;if(!J()&&!te())o.exit();if(ee(),!o.destroyed())await A.promise}catch(Pe){if(!o.destroyed())E=Rd(Pe,"Local TUI failed")}finally{if(G(),Le.dispose(),L!==void 0)clearTimeout(L);o.exit(),o.setExitHandler(void 0)}let ve=[];try{await w}catch(Pe){if(!o.signal.aborted)ve.push(Rd(Pe,"Session transition failed"))}try{await be(d)}catch(Pe){ve.push(Rd(Pe,"Selected client cleanup failed"))}if(E!==void 0||ve.length>0)throw R6(E,ve)}var Sur,Zxo;var kur=C(async()=>{bur();xme();PQ();bf();vr();uc();s_();_y();T7e();await Mc([xur(),vA(),cw(),sIt(),gIt(),iIt()]);Sur={name:"client extensions",effect:"unsupported",reason:"loaded once at startup; replacing one needs an unload lifecycle"},Zxo=[{name:"AGENTS.md instructions",effect:"next_turn"},{name:"skills",effect:"next_turn"},{name:"Session extensions",effect:"unsupported",reason:"fixed when the Local service starts; replacing one needs an unload lifecycle"},Sur]});import dZ from"process";import{homedir as evo}from"os";import{basename as tvo}from"path";import{createCliRenderer as nvo}from"@opentui/core";async function ivo(e,t,n){try{await t()}catch(r){e.push(Rd(r,n))}}async function ovo(e,t,n,r){if(t===void 0)return;await ivo(e,()=>n(t),r)}async function B7e(e,t={},n=evo()){let r=V3(n),i={...rvo,createServiceManager:()=>aw({home:n,reportCleanupFailure:(u)=>{xi("local-service-cleanup",u)}}),loginProviders:async()=>(await tw(r,{report:(u)=>{xi("extension-login",u)}})).getProviders(),renderLanding:(u,l,d,p,f,m,h)=>{Pcr(u,{initialTheme:f.initialTheme,sessions:l,agents:m,notice:h,folder:d,loadSummary:async(g)=>$cr(await tw(r,{report:(_)=>{xi("extension-login",_)}}),m,g,{credentialPath:r}),choose:p})},...t},o,s,a;try{if(j7e(e),s=await A7e({signals:i.signals,createQueryClient:i.createQueryClient,createRenderer:i.createRenderer,createRoot:i.createRoot,createWhistle:i.createWhistle,enableKeymap:i.enableKeymap,probeSigils:dZ.stdin.isTTY}),s!==void 0){i.renderConnecting(s.root);let u=await lf(ii({try:()=>i.loadThemePreference(),catch:(x)=>Rd(x,"Theme preference unavailable")}).pipe(Cs((x)=>rt({theme:"terminal",error:x.message}))),{signal:s.signal});if(tu(u)){if(af(u.cause)){await s.close();return}throw _u(u.cause)}let l=u.value,d=await s.loadToolSigils(l.sigils??"auto"),{theme:p,error:f}=l,m=()=>({initialTheme:p,toolSigils:d,themeError:f,onThemeConfirm:async(x)=>{await i.saveThemePreference(x),p=x,f=void 0}}),h=i.createServiceManager(),g={owner:z8n(h,i.loginProviders),host:"local",scope:"user",policy:{loginAllowed:FN}},_={restartInstalledUpdate:(x)=>{a=x},account:g,commands:s.commands,queryClient:s.queryClient,root:s.root,serviceManager:h,terminal:s,theme:m,onDiagnostic:(x)=>{xi("client-extension",x)}},y=yft(s.commands,g.owner,{sourceId:"local-account",namespace:"account",host:g.host,scope:g.scope,policy:g.policy});try{await Eur(e,i,_,n)}finally{y.dispose()}}}catch(u){o=Rd(u,"Local TUI failed")}let c=[];if(await ovo(c,s,(u)=>u.close(),"Local terminal application cleanup failed"),o!==void 0||c.length>0)throw R6(o,c);if(a!==void 0)await i.resumeInstalledUpdate(a)}var rvo;var _It=C(async()=>{vr();uc();Fc();_y();sCt();CR();pL();bf();hQ();HY();cIt();qcr();await Mc([jCt(),cw(),$h(),vA(),sIt(),zcr(),LCt(),kur(),gIt()]);rvo={checkpointDrafts:oIt,automaticInstalledRestart:dZ.env.FUNGI_LAUNCHER!==void 0&&tvo(dZ.env.FUNGI_LAUNCHER)!=="fungi.cjs",resumeInstalledUpdate:Ksr,signals:dZ,loadThemePreference:bB,saveThemePreference:gge,createWhistle:pU,prepareClientExtensions:Bcr,createQueryClient:d7e,createRenderer:nvo,createRoot:UY,render:(e,t,n,r,i,o,s)=>{Ocr(e,t,{...o,commands:r,onExit:i,session:n,...s})},renderConnecting:Rcr,renderRecovery:Icr,renderServiceUpdated:Ccr,renderPicker:(e,t,n,r,i)=>{Mcr(e,{...i,onCancel:r,onSelect:n,sessions:t})},enableKeymap:!0,runOneShot:L7e,checkInstalledUpdate:dZ.env.FUNGI_LAUNCHER===void 0?void 0:async(e)=>{let t=Bun.which("fungi"),n=dZ.env.FUNGI_LAUNCHER;if(t===null||n===void 0)return;return Vsr(t,n,e)}}});import svo from"process";async function Tur(e,t,n=svo,r){let i=new AbortController,o=()=>{i.abort()};n.on("SIGINT",o),n.on("SIGTERM",o);try{let s=r==="oauth"?"subscription":r,a=fj(t.getProviders()).filter((l)=>s===void 0||l.methods.some((d)=>d.kind===s)&&!(s==="api_key"&&l.id==="fungi")),c=[];for(let l of a){i.signal.throwIfAborted();let d=await t.checkAuth(l.id,{signal:i.signal});if(d!==void 0)c.push({providerId:l.id,providerName:l.name,type:d.type})}i.signal.throwIfAborted();let u=await e.search({message:r==="api_key"?"Which provider's API key?":"Choose a provider",choices:d9(a,c,myt,"login"),collapsedGroup:"More providers",signal:i.signal});if(vv(u))throw Error("Login cancelled. Run fungi login to try again.");return u}finally{n.off("SIGINT",o),n.off("SIGTERM",o)}}var Aur=C(()=>{AL();bf();pL()});function Iur(e){if(e===void 0)return;let t=Cur.safeParse(e);if(!t.success)throw Error("Invalid --reasoning value: "+e+". Expected one of "+Cur.options.join(", "));return t.data}var Cur;var Rur=C(()=>{qn();Cur=an(["minimal","low","medium","high","xhigh","max"])});async function avo(e,t,n,r){let{agents:i}=await e.discover(t,{signal:r}),o=i.find((s)=>s.agentId===n);if(o===void 0)throw Error(i.length===0?`No Agent ${n} in this folder; it has no saved Agents`:`No Agent ${n} in this folder; choose one of ${i.map((s)=>s.agentId).join(", ")}`);return o.databasePath}async function Dur(e,t={}){let n={createServiceManager:()=>aw(),runOneShot:L7e,...t},r,i,o=new AbortController,s=()=>{o.abort()};try{if(e.connect===void 0){if(e.providerId!==void 0||e.modelId!==void 0||e.reasoning!==void 0)throw Error("Session model selection requires the shared Local preference contract");let u=n.createServiceManager(),l=e.signals??process;l.on("SIGINT",s),l.on("SIGTERM",s);try{let d=e.agentId===void 0?e.databasePath:await avo(u,e.invocationRoot,e.agentId,o.signal),p=d===void 0?{invocationRoot:e.invocationRoot,mode:e.mode,fungiMcp:e.fungiMcp}:{invocationRoot:e.invocationRoot,databasePath:d,mode:e.mode,fungiMcp:e.fungiMcp};r=await u.connect(p,{signal:o.signal})}finally{l.off("SIGINT",s),l.off("SIGTERM",s)}if(o.signal.aborted)throw Error("fungi run cancelled")}else throw Error("--connect is unavailable; fungi uses the persistent Local service");let c=r;await n.runOneShot(c.session,{prompt:e.prompt,stdin:e.stdin,stdout:e.stdout,signals:e.signals,requestId:e.requestId,abortOnSignal:!0})}catch(c){i=Rd(c,"Local one-shot run failed")}let a=[];try{await r?.close()}catch(c){a.push(Rd(c,"Local TUI host close failed"))}if(i!==void 0||a.length>0)throw R6(i,a)}var Our=C(async()=>{cIt();await cw()});import{Worker as cvo}from"worker_threads";import{Buffer as Nur}from"buffer";import{constants as n_e}from"fs";import{open as Lur,readdir as uvo}from"fs/promises";import{totalmem as lvo}from"os";import{join as yIt}from"path";async function $ur(e,t){let n=await e.stat();if(!n.isFile()||(n.mode&511)!==384||n.size>t)throw Error("Watchdog evidence is not a bounded private regular file")}async function Mur(e,t){let n=await Lur(e,n_e.O_WRONLY|n_e.O_CREAT|n_e.O_NOFOLLOW,384);try{await $ur(n,wOe),await n.truncate(0),await n.writeFile(t,"utf8"),await n.sync()}finally{await n.close()}}async function gvo(){for(let e of["/proc/self/fd","/dev/fd"])try{return(await uvo(e)).length}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")continue;Go("service-watchdog.fd-count",t);return}return}async function _vo(e){let t=[];for(let r=3;r>=0;r--){let i=yIt(e,`service-stream.jsonl${r===0?"":`.${String(r)}`}`),o;try{o=await Lur(i,n_e.O_RDWR|n_e.O_NOFOLLOW)}catch(s){if(s instanceof Error&&"code"in s&&s.code==="ENOENT")continue;throw s}try{await $ur(o,wOe/4),t.push(await o.readFile()),await o.sync()}finally{await o.close()}}let n=Nur.concat(t);if(n.byteLength>wOe)throw Error("Service capture exceeds its byte bound");return n.toString("utf8")}async function zur(e,t={}){let n=mvo.parse({stallMs:t.stallMs,startupMs:t.startupMs,rssLimitBytes:t.rssLimitBytes,rssSustainMs:t.rssSustainMs}),r=t.heartbeat??new SharedArrayBuffer(24);if(r.byteLength!==24)throw Error("Invalid service watchdog state size");let i=new BigInt64Array(r),o=t.worker??new cvo(new URL("./private-local-service-worker.mjs",import.meta.url),{workerData:{directory:e,heartbeat:r,heartbeatIntervalMs:Math.min(1000,Math.floor(n.stallMs/4))}}),s=process.hrtime.bigint(),a=0n,c=s,u,l=[],d,p,f=dA(),m=(x)=>{u??=process.hrtime.bigint(),o.postMessage(x)},h=()=>{m("SIGINT")},g=()=>{m("SIGTERM")},_=(x,w,b)=>{clearInterval(y);let E=x==="rss-bound"?fvo:1;setTimeout(()=>process.exit(E),Pur),(async()=>{let R={source:"local-service",event:"watchdog-exit",reason:x,timestamp:new Date().toISOString(),pid:process.pid,version:f,workerDigest:dvo,lagMs:w,boundMs:b,captureBudgetMs:Pur,rssLimitBytes:n.rssLimitBytes,rssSamples:l,openFds:await gvo(),uptimeMs:Math.round(process.uptime()*1000)},L=yIt(e,"watchdog-exit.json"),z=async(j)=>{await Mur(L,JSON.stringify({...R,capture:j})+`
|
|
2264
|
-
`)};try{await z({state:"pending"});try{let j=await _vo(e);await Mur(yIt(e,"watchdog-stream.jsonl"),j),await z(Atomics.load(i,1)!==0n?{state:"failed",code:"capture-sink-failed"}:{state:j.length===0?"empty":"captured",file:"watchdog-stream.jsonl",bytes:Nur.byteLength(j)})}catch(j){Go("service-watchdog.capture",j),await z({state:"failed",code:"capture-write-failed"})}}catch(j){Go("service-watchdog.evidence",j)}})().then(()=>{process.exit(E)},(R)=>{Go("service-watchdog.evidence",R),process.exit(E)})},y;process.on("SIGINT",h),process.on("SIGTERM",g);try{await new Promise((x,w)=>{o.once("error",w),o.once("exit",(b)=>{if(b===0)x();else w(Error(`Local service worker exited (${String(b)})`))}),y=setInterval(()=>{let b=process.hrtime.bigint();if(u!==void 0){let j=Number(b-u)/1e6;if(j>4500)_("shutdown-timeout",j,4500);return}let E=process.memoryUsage.rss();if(d===void 0||b-d>=1000000000n){if(d=b,l.push({atMs:Math.round(Number(b-s)/1e6),rss:E}),l.length>hvo)l.shift()}if(E>n.rssLimitBytes){p??=b;let j=Number(b-p)/1e6;if(j>=n.rssSustainMs)_("rss-bound",j,n.rssSustainMs)}else p=void 0;let A=Atomics.load(i,0);if(A!==a)a=A,c=b;let R=Atomics.load(i,2)!==0n,L=Number(b-(R?c:s))/1e6,z=R?n.stallMs:n.startupMs;if(L>z)_(R?"event-loop-stall":"startup-timeout",L,z)},Math.min(250,Math.floor(n.stallMs/4)))})}finally{clearInterval(y),process.off("SIGINT",h),process.off("SIGTERM",g),await o.terminate()}}var dvo,Fur=1048576,pvo,fvo=75,mvo,hvo=32,Pur=200;var Uur=C(async()=>{qn();im();S0t();await dj();dvo=D().regex(/^(?:source|[a-f0-9]{64})$/u).parse("
|
|
2264
|
+
`)};try{await z({state:"pending"});try{let j=await _vo(e);await Mur(yIt(e,"watchdog-stream.jsonl"),j),await z(Atomics.load(i,1)!==0n?{state:"failed",code:"capture-sink-failed"}:{state:j.length===0?"empty":"captured",file:"watchdog-stream.jsonl",bytes:Nur.byteLength(j)})}catch(j){Go("service-watchdog.capture",j),await z({state:"failed",code:"capture-write-failed"})}}catch(j){Go("service-watchdog.evidence",j)}})().then(()=>{process.exit(E)},(R)=>{Go("service-watchdog.evidence",R),process.exit(E)})},y;process.on("SIGINT",h),process.on("SIGTERM",g);try{await new Promise((x,w)=>{o.once("error",w),o.once("exit",(b)=>{if(b===0)x();else w(Error(`Local service worker exited (${String(b)})`))}),y=setInterval(()=>{let b=process.hrtime.bigint();if(u!==void 0){let j=Number(b-u)/1e6;if(j>4500)_("shutdown-timeout",j,4500);return}let E=process.memoryUsage.rss();if(d===void 0||b-d>=1000000000n){if(d=b,l.push({atMs:Math.round(Number(b-s)/1e6),rss:E}),l.length>hvo)l.shift()}if(E>n.rssLimitBytes){p??=b;let j=Number(b-p)/1e6;if(j>=n.rssSustainMs)_("rss-bound",j,n.rssSustainMs)}else p=void 0;let A=Atomics.load(i,0);if(A!==a)a=A,c=b;let R=Atomics.load(i,2)!==0n,L=Number(b-(R?c:s))/1e6,z=R?n.stallMs:n.startupMs;if(L>z)_(R?"event-loop-stall":"startup-timeout",L,z)},Math.min(250,Math.floor(n.stallMs/4)))})}finally{clearInterval(y),process.off("SIGINT",h),process.off("SIGTERM",g),await o.terminate()}}var dvo,Fur=1048576,pvo,fvo=75,mvo,hvo=32,Pur=200;var Uur=C(async()=>{qn();im();S0t();await dj();dvo=D().regex(/^(?:source|[a-f0-9]{64})$/u).parse("4717b26bc924c8a45324e9993c4607eb31116e52883ed6e96e152dcaf3b91784"),pvo=Math.min(4096*Fur,lvo()/2),mvo=Ke({stallMs:et().int().min(50).max(30000).default(30000),startupMs:et().int().min(50).max(60000).default(60000),rssLimitBytes:et().int().min(64*Fur).default(Math.floor(pvo)),rssSustainMs:et().int().min(50).max(600000).default(60000)})});iq();QJ();AR();TN();var PDe=PE(pv,{contribute:(e)=>({chips:[],panel:e.status!=="running"||e.value===null?[]:e.value.asks.map((t)=>{let n=t.questions[0],r=`${n?.question??"Question"}${t.questions.length>1?` (+${String(t.questions.length-1)} more)`:""}`,i=n?.options.map((o)=>o.label).join(" \xB7 ")??"";if(t.escalated!==void 0){let{by:o,reason:s,note:a}=t.escalated;if(r=`${s==="escalated"?`escalated by ${o.name}`:s==="sender_archived"?`${o.name} archived`:`${o.name} is gone`} \xB7 ${r}`,a!==void 0)i=`${i}
|
|
2265
2265
|
${a}`}if(t.waitingOn!==void 0)return{id:t.askId,title:`waiting on ${t.waitingOn.name} \xB7 ${r}`,detail:i,tone:"muted",actions:[{id:"answerFlow",label:"Answer",input:{askId:t.askId}}]};return{id:t.askId,title:r,detail:i,tone:"attention",actions:[{id:"answerFlow",label:"Answer",input:{askId:t.askId},awaiting:"question"}]}}),timeline:{cells:[],omitted:0},waiting:null})});AR();eQ();var $de=(e)=>{let t=e.replace(/\s+/gu," ").trim();return t.length<=80?t:`${t.slice(0,79)}\u2026`},Ndi=(e)=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`};function Ldi(e){let t=e.state==="active",n=t?`Pursuing goal since ${Ndi(e.startedAt)}`:e.pauseCause?.kind==="delegator"?`Goal paused by ${$de(e.pauseCause.detail??"delegator")} (/goal resume)`:"Goal paused (/goal resume)",r=!t&&e.pauseCause?.kind!=="delegator"&&e.pauseCause?.detail!=null?[$de(e.pauseCause.detail)]:[],i={id:"goal",title:[n,$de(e.objective),...r].join(" \xB7 "),tone:t?"running":"muted",actions:[{id:"goal",label:t?"Pause goal":"Resume goal",input:{action:t?"pause":"resume"}}]};return $de(e.objective)===e.objective?i:{...i,detail:e.objective.slice(0,1024)}}function Fdi(e){let t={id:"goal-ended",title:`${e.outcome==="achieved"?"Goal achieved":"Goal cleared"} \xB7 ${$de(e.objective)}`,tone:e.outcome==="achieved"?"settled":"muted"},n=e.reason===null?t:{...t,detail:e.reason};return{id:String(e.sequence),sequence:e.sequence,at:e.endedAt,commandId:null,afterSequence:e.afterSequence,rows:[n]}}var $kn=PE(uy,{promptPresentation:"footer",contribute:(e)=>{if(e.status!=="running"||e.value===null)return{chips:[],panel:[],timeline:{cells:[],omitted:0},waiting:null};let{goal:t,ended:n,omitted:r}=e.value;return{chips:[],panel:t===null?[]:[Ldi(t)],timeline:{cells:n.map(Fdi),omitted:r},waiting:null}}});AR();zde();var zdi=(e)=>{let t=e.replace(/\s+/gu," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`},jkn=(e)=>e.state==="failed"?"error":e.state==="active"?"running":e.state==="paused"?"muted":"settled",Bkn=(e)=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),qkn=PE(W3,{promptPresentation:"footer",contribute:(e)=>{if(e.status!=="running"||e.value===null)return{chips:[],panel:[],timeline:{cells:[],omitted:0},waiting:null};let{loop:t}=e.value,n=t.state==="active"&&t.nextDueAt!==null;return{chips:t.state!=="active"&&t.state!=="paused"?[]:[{id:"loop",order:2,row:{id:"loop",title:`Loop ${t.mode==="self_paced"?"self-paced":"fixed"}${n?" (waiting)":""}`,tone:jkn(t)}}],panel:[{id:"loop",title:`Loop \xB7 ${t.state} \xB7 ${t.mode==="self_paced"?"self-paced":`${t.cron?.expression??"fixed"} ${t.cron?.timeZone??""}`}${t.nextDueAt===null?"":` \xB7 Next ${Bkn(t.nextDueAt)}`} \xB7 ${zdi(t.prompt)}`,detail:[t.reason,t.prompt].filter((r)=>r!==null).join(`
|
|
2266
2266
|
`).slice(0,1024),tone:jkn(t)},...t.lastError===null?[]:[{id:"error",title:t.lastError.slice(0,4096),tone:"error"}]],timeline:{cells:[],omitted:0},waiting:n?{summary:`Waiting until ${Bkn(t.nextDueAt)}`,cancel:{id:"loop",label:"stop loop",input:{action:"stop-ask"}}}:null}}});AR();UDe();var qdi=(e)=>{let t=e.steps.findIndex((i)=>i.status==="in_progress"),n=e.steps.filter((i)=>i.status==="completed").length;return{title:(t<0?e.steps.find((i)=>i.status==="pending"):e.steps[t])?.step??"Plan complete",detail:`${String(t<0?n:t+1)}/${String(e.steps.length)}`}},Wdi=(e)=>e.steps.map((t,n)=>({id:String(n),title:t.step,tone:t.status==="completed"?"settled":t.status==="in_progress"?"running":"muted"})),Gkn=PE(CN,{contribute:(e)=>({chips:[],panel:e.status!=="running"||e.value===null||!zDe(e.value.plan)?[]:[{id:"plan",...qdi(e.value.plan),actions:[{id:"plan",label:"Clear plan",input:{action:"clear"}}],inspection:{commandId:"plan",title:"Plan",rows:Wdi(e.value.plan)}}],timeline:{cells:[],omitted:0},waiting:null})});AR();emt();var BDe={working:{label:"working",tone:"running",status:"info"},waiting_on_agent:{label:"waiting",tone:"muted",status:"neutral"},needs_you:{label:"needs you",tone:"attention",status:"warning"},idle:{label:"idle",tone:"settled",status:"success"},failed:{label:"failed",tone:"error",status:"error"},unavailable:{label:"unavailable",tone:"muted",status:"neutral"}};function Jkn(e){let t=e.state==="waiting_on_agent"?`waiting on ${e.waitingOn??"its parent"}`:BDe[e.state].label,n=Ude(e.escalated);return n===void 0?t:`${t} \xB7 ${n}`}function Xdi(e){let t=BDe[e.state],n={id:e.agentId,title:`${e.name} \xB7 ${Jkn(e)}`,tone:t.tone,status:{label:Jkn(e),tone:t.status}},i=e.ask?.questions[0]?.question??e.attention,o=i===void 0?n:{...n,detail:i.slice(0,200)};if(e.sessionId===null)return{...o,detail:e.attention??"not messaged yet"};let s={...o,open:{params:[{key:"agent",value:e.agentId},{key:"session",value:e.sessionId}]}};if(e.ask===void 0)return s;let a={id:"answerChild",label:"Answer",input:{agentId:e.agentId,sessionId:e.sessionId,askId:e.ask.askId}};return{...s,actions:[e.state==="needs_you"?{...a,awaiting:"question"}:a]}}function Ydi(e){let t=(c)=>e.counts[c],n=e.waitingOn.map(({name:c,count:u})=>`${String(u)} waiting on ${c}`),r=e.escalatedBy.map(({name:c,reason:u,count:l})=>{let d=Ude({by:c,reason:u});return e.escalated===t("needs_you")&&e.escalatedBy.length===1?d:`${String(l)} ${d}`}),i=r.length===0?"needs you":`needs you (${r.join("; ")})`,o=[...["working"].map((c)=>[c,t(c)]).filter(([,c])=>c>0).map(([c,u])=>`${String(u)} ${BDe[c].label}`),...n,...["needs_you","failed","unavailable"].map((c)=>[c,t(c)]).filter(([,c])=>c>0).map(([c,u])=>`${String(u)} ${c==="needs_you"?i:BDe[c].label}`)],s=t("working")+t("needs_you"),a=t("needs_you")>0?"attention":t("failed")>0?"error":t("working")>0?"running":"muted";return{id:"summary",title:[`${String(s)} sub-agent${s===1?"":"s"}`,...o,...e.uncounted>0?[`${String(e.uncounted)} not read`]:[],"/agents shows them"].join(" \xB7 "),tone:a}}var Qkn=PE(MU,{contribute:(e)=>({chips:[],panel:e.status!=="running"||e.value===null?[]:e.value.agents.length>0&&!e.value.expanded?[Ydi(e.value)]:[...e.value.agents.map(Xdi),...e.value.more===0&&e.value.uncounted===0?[]:[{id:"more",title:[...e.value.more===0?[]:[`${String(e.value.more)} more sub-agent${e.value.more===1?"":"s"}`],...e.value.uncounted===0?[]:[`${String(e.value.uncounted)} not read`]].join(" \xB7 "),tone:"muted"}]],timeline:{cells:[],omitted:0},waiting:null})});AR();hd();Gf();vr();tr();import qDe from"process";import{once as Zdi}from"events";import{createConnection as epi}from"net";import{createInterface as tpi}from"readline";var Xkn="fungi:agent:v1",tmt=Date.now()*1000,npi=en(Ti(vn([re({id:Ce,result:Ea}),re({id:Ce,error:re({code:Ce,message:Ce})})])));function rpi(){return tmt=Math.max(tmt+1,Date.now()*1000),tmt}function ipi(e,t,n){let r=n?.state,i=rpi(),o=`${Xkn}:${String(i)}`,s={pane_id:t,source:Xkn,agent:"fungi",seq:i};if(r!==void 0)s.state=r;if(r==="blocked")s.message=n?.header===void 0?"Waiting for your response":`Waiting for your response: ${n.header}`;let a={id:o,method:r===void 0?"pane.release_agent":"pane.report_agent",params:s};return ii({try:async(c)=>{let u=epi({path:e,signal:c}),l=tpi({input:u,crlfDelay:1/0});try{let d=l[Symbol.asyncIterator](),[,p]=await Promise.all([Zdi(u,"connect",{signal:c}).then(()=>{u.write(`${JSON.stringify(a)}
|
|
2267
2267
|
`)}),d.next()]);if(p.done)throw Error("Herdr closed without a response");let f=npi(p.value);if(f.id!==o)throw Error("Herdr response ID mismatch");if("error"in f)throw Error(`Herdr report refused: ${f.error.code}`)}finally{l.close(),u.destroy()}},catch:(c)=>Error("Herdr report failed",{cause:c})}).pipe(gxe("2 seconds"))}function opi(e,t){let{HERDR_ENV:n,HERDR_SOCKET_PATH:r,HERDR_PANE_ID:i}=t.environment;if(n!=="1"||!r||!i)return Ln;let o=qDe.platform==="win32"?`\\\\.\\pipe\\${r}`:r,s=(a)=>ipi(o,i,a).pipe(Cs((c)=>Gt(()=>{t.onError(c)})));return Ct(function*(){yield*Da(Ln,()=>s(void 0)),yield*e.pipe(X7t((a,c)=>a.state===c.state&&a.header===c.header),PF(s),Cs((a)=>Gt(()=>{t.onError(a)})),Xy)})}var spi=PE({id:wu.make("corral"),commands:{},projection:null},{attach:({activity:e,onError:t})=>opi(Cve(e,(n)=>Error("Corral activity delivery failed",{cause:n})),{environment:{HERDR_ENV:qDe.env.HERDR_ENV,HERDR_SOCKET_PATH:qDe.env.HERDR_SOCKET_PATH,HERDR_PANE_ID:qDe.env.HERDR_PANE_ID},onError:t})}),Ykn=spi;import{createRequire as yvo}from"module";import{homedir as xvo}from"os";import{dirname as jur,join as xIt,resolve as zh}from"path";import{fileURLToPath as vvo}from"url";import{lstatSync as Bur,realpathSync as bvo}from"fs";QJ();var rQ=`Usage: fungi agents list [--archived] [-C dir]
|
|
@@ -2400,7 +2400,7 @@ that npm create fungi-app runs, at the version released with this fungi.
|
|
|
2400
2400
|
|
|
2401
2401
|
Add --help to create or install for its options.
|
|
2402
2402
|
See also: fungi oyster --help
|
|
2403
|
-
`,CBa=dr({version:D().min(1)});function xWi(){return{oyster:"0.47.
|
|
2403
|
+
`,CBa=dr({version:D().min(1)});function xWi(){return{oyster:"0.47.1",createFungiApp:"0.0.113"}}var vWi=(e)=>new Promise((t,n)=>{let r=gWi(e.command,[...e.args],{cwd:e.cwd,env:{...process.env,...e.env},stdio:"inherit"});r.once("error",n),r.once("close",(i,o)=>{t(i??(o===null?1:128))})}),bWi=new Set(["try","install-apps","install"]),wWi=new Set(["create","dev","build","install"]);function mGn(e,t,n){return{command:"npm",args:["exec","--yes",`--package=${e}`,"--",t,...n]}}function SWi(e){return e.length===0||e[0]==="help"||e[0]==="-h"||e[0]==="--help"}async function hGn(e){let{group:t,args:n,cwd:r,stdout:i}=e,o=t==="oyster"?bWi:wWi,[s,...a]=n;if(SWi(n)){i.write(t==="oyster"?MSt:NSt);return}if(s===void 0||!o.has(s))throw new Zme(`Unknown ${t} command: ${s??""}`,`Run fungi ${t} --help`);let c=xWi(),u={FUNGI_HOST:`spore@${e.sporeVersion}`},l;if(t==="oyster"||s==="install")l=mGn(`@fungi.computer/oyster@${c.oyster}`,"oyster",n);else if(s==="create")l=mGn(`create-fungi-app@${c.createFungiApp}`,"create-fungi-app",a);else{let p=yWi(r,"node_modules",".bin","fungi-app");if(!_Wi(p))throw new Zme("This folder is not a Fungi App","Run fungi app create <dir>, or npm install here");l={command:p,args:n}}let d=await(e.runner??vWi)({...l,cwd:r,env:u});if(d!==0)process.exitCode=d}X8e();var TWi=`Usage: fungi [command] [options]
|
|
2404
2404
|
|
|
2405
2405
|
Start here:
|
|
2406
2406
|
fungi Open your conversations in this folder
|
|
@@ -1883,7 +1883,7 @@ eof_line: "*** End of File" LF
|
|
|
1883
1883
|
Use @@ alone or followed by an existing context line; unified-diff @@ line numbers are not supported. Add/Delete File and optional Move to are also supported. Paths stay inside the root; symlinks and parent traversal are rejected. A failure returns recovery guidance and may follow earlier file writes; inspect the result before retrying. Prefer this to shell or Python replacement.`,parameters:smn(Jre),constrainedSampling:{type:"grammar",variants:{openai_lark:Q8i}}},executionMode:"sequential",prepare:n=>kt({try:()=>Jre.parse(n.arguments),catch:i=>({message:i instanceof Error?i.message:"Invalid patch input"})}).pipe(mt(i=>({execute:()=>gO(k9i(e,i,n.id).pipe(mt(r=>({type:"result",result:{content:[{type:"text",text:JSON.stringify(r)}],isError:"status"in r&&r.status!=="completed"}}))))})))}}var VFe="Search skips .git and gitignored paths.",KC={list:`List one directory level. ${VFe}`,glob:`Find paths by glob. ${VFe}`,grep:`Search file content. ${VFe}`};function JC(e){return{...e,results:e.results.map(t=>t.text===void 0||t.text.length<=Qhn?t:{...t,text:`${t.text.slice(0,Qhn)}\u2026`})}}function A9i(e){const t=e.results.map(n=>n.line===void 0?`${n.path}${n.type==="directory"?"/":""}`:`${n.path}:${String(n.line)}: ${n.text??""}`);return t.length===0&&e.truncated===null&&t.push("(nothing found)"),e.truncated==="limit"&&t.push("[truncated: result limit reached; raise limit or narrow path]"),e.truncated==="scan"&&t.push("[truncated: scan limit reached before the search finished; narrow path]"),t.join(`
|
|
1884
1884
|
`)}function KFe(e){return{content:[{type:"text",text:A9i(e)}],isError:!1}}function T9i(e,t){if(!("image"in e))return e;if(t.images===void 0)throw new Error("Images can only be read inside execute or through the read tool.");const{mimeType:n,data:i,bytes:r}=e.image,o=t.images.push({data:i,mimeType:n,path:e.path,bytes:r});return{path:e.path,image:{ref:o,mimeType:n,bytes:r}}}function I9i(e){return t=>"image"in t?e()?{content:[{type:"text",text:JSON.stringify({path:t.path,mimeType:t.image.mimeType,bytes:t.image.bytes})},{type:"image",data:t.image.data,mimeType:t.image.mimeType}],isError:!1}:{content:[{type:"text",text:`Image limit reached for this run (max ${String(kZ)} images). Work with the images already shown.`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(t)}],isError:!1}}function Qre(e,t,n,i,r,o=s=>({content:[{type:"text",text:JSON.stringify(s)}],isError:!1})){return{[imn]:!0,module:GFe,access:"read",replay:"safe",descriptor:{name:e,description:t,parameters:smn(n)},executionMode:"sequential",prepare:a=>kt({try:()=>n.parse(a.arguments),catch:c=>({message:c instanceof Error?c.message:"Invalid Files input"})}).pipe(mt(c=>({execute:()=>gO(omn(async u=>i.parse(await r(c,u))).pipe(mt(u=>({type:"result",result:{...o(u)}}))))})))}}function amn(e){const t=a=>e.pathInstructions===void 0?a:`${a} ${e.pathInstructions}`,n=e.port.patch,i=n===void 0?void 0:async(a,c)=>Vhn.parse(await n(Jre.parse(a),c));let r=0;const o={read:In.operation({replay:"safe",access:"read",input:Bhn,output:V8i,description:t(Yhn),execute:async(a,c)=>T9i(await e.port.read(a,c),c)}),list:In.operation({replay:"safe",access:"read",input:emn,output:VC,description:t(KC.list),execute:async(a,c)=>JC(await e.port.list(a,c))}),glob:In.operation({replay:"safe",access:"read",input:tmn,output:VC,description:t(KC.glob),execute:async(a,c)=>JC(await e.port.glob(a,c))}),grep:In.operation({replay:"safe",access:"read",input:nmn,output:VC,description:t(KC.grep),execute:async(a,c)=>JC(await e.port.grep(a,c))}),edit:In.operation({replay:"unsafe",access:"write",input:u9i,output:p9i,description:t("Replace one exact or retained-fuzzy text match."),execute:async(a,c)=>S9i(e.port,a,c)})},s=i===void 0?void 0:In.operation({replay:"unsafe",access:"write",input:Jre,output:Vhn,description:t("Apply a bounded Codex-format patch through the same Files owner as apply_patch."),execute:i});return Object.freeze({tools:Object.freeze([...i===void 0?[]:[E9i(i)],Qre("read",t(Yhn),Bhn,Hhn,e.port.read,I9i(()=>(r+=1)<=kZ)),Qre("list",t(KC.list),emn,VC,async(a,c)=>JC(await e.port.list(a,c)),KFe),Qre("glob",t(KC.glob),tmn,VC,async(a,c)=>JC(await e.port.glob(a,c)),KFe),Qre("grep",t(KC.grep),nmn,VC,async(a,c)=>JC(await e.port.grep(a,c)),KFe)]),module:In.module({id:GFe,name:"files",description:"Bounded file operations over one authorized target.",operations:s===void 0?o:{...o,patch:s}})})}Yc(),_t(),_t();var C9i=32,cmn=5e4,umn=new Set(["__proto__","constructor","prototype"]),lmn=e=>umn.has(e),dmn=ei(()=>j().min(1).max(128).refine(e=>!umn.has(e))),pmn=e=>j().max(e).brand(),R9i=ei(()=>It([Le(Wt()),Ot(j(),Wt())]));function O9i(e={nodes:0}){return Wt().transform(t=>{const n=[{value:t,depth:0,field:""}];for(;n.length;){const i=n.pop();if(!i)break;if(++e.nodes>cmn)return"nodes_limit";if(i.depth>C9i)return"depth_limit";const r=R9i.safeParse(i.value);if(!r.success){if(["name","required"].includes(i.field)&&lmn(j().safeParse(i.value).data??""))return"unsafe_name";continue}if(Object.getOwnPropertyNames(i.value).some(lmn))return"unsafe_name";for(const[o,s]of Object.entries(r.data)){if(n.length+e.nodes>=cmn)return"nodes_limit";n.push({value:s,depth:i.depth+1,field:Array.isArray(r.data)?i.field:o})}}return null})}var P9i=ei(()=>It([Ot(j(),o0()),Rt()]));function M9i(e=!1){const t=ei(()=>{const n=Eo({$schema:j().optional(),title:pmn(200).optional(),description:pmn(2048).optional(),type:It([En(["null","boolean","object","array","number","integer","string"]),Le(En(["null","boolean","object","array","number","integer","string"]))]).optional(),enum:Le(o0()).min(1).optional(),const:o0().optional(),properties:Ot(dmn,t).optional(),required:Le(dmn).optional(),additionalProperties:t.optional(),propertyNames:t.optional(),items:t.optional(),prefixItems:Le(t).optional(),minItems:et().int().nonnegative().optional(),maxItems:et().int().nonnegative().optional(),uniqueItems:Ie(!1).optional(),minLength:et().int().nonnegative().optional(),maxLength:et().int().nonnegative().optional(),minimum:et().optional(),maximum:et().optional(),exclusiveMinimum:It([et(),Rt()]).optional(),exclusiveMaximum:It([et(),Rt()]).optional(),multipleOf:et().positive().optional(),allOf:Le(t).optional(),anyOf:Le(t).optional(),oneOf:Le(t).optional(),readOnly:Rt().optional(),writeOnly:Rt().optional(),default:o0().optional(),example:o0().optional(),examples:Le(o0()).optional(),deprecated:Rt().optional()}),i=e?n.extend({nullable:Rt().optional()}):n;return It([Rt(),i]).pipe(P9i)});return Wt().superRefine((n,i)=>{const r=O9i().parse(n);r&&i.addIssue({code:"custom",message:r})}).pipe(t)}yt(),ki(),_t();var hmn=16,mmn=256,fmn=16,D9i=4,L9i=1e4,N9i=2048,$9i=new TextEncoder,Xre=E.json(),JFe=E.record(E.string(),Xre),U9i=/^[A-Za-z][A-Za-z0-9_]*$/u,QC=class extends Error{name="McpServerUnavailableError";serverId;reason;constructor(e,t,n){super(`MCP server ${e} is unavailable: ${t}`,{cause:n}),this.serverId=e,this.reason=t}};async function gmn(e){const t=new Uint8Array(await crypto.subtle.digest("SHA-256",$9i.encode(e)));return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function F9i(e){const t=e.replace(/[^A-Za-z0-9_]/gu,"_");return U9i.test(t)?t:`t_${t}`}var B9i="Arguments are a JSON object; this server's schema is outside the supported subset, so the server validates them.";function j9i(e){const t=M9i().safeParse(e.inputSchema);if(!t.success)return{schema:JFe,loose:!0};try{return{schema:E.fromJSONSchema(t.data).pipe(JFe),loose:!1}}catch{return{schema:JFe,loose:!0}}}function W9i(e,t){const n=[e.title,e.description].filter(o=>o!==void 0&&o.length>0).join(": "),i=n.length>0?n:e.name;return(t?`${i}
|
|
1885
1885
|
|
|
1886
|
-
${B9i}`:i).slice(0,N9i)}function z9i(e,t,n,i){const r={};for(const o of i){const s=F9i(o.name);if(s in r)continue;const a=j9i(o);r[s]=In.operation({replay:o.annotations?.readOnlyHint===!0?"safe":"unsafe",description:W9i(o,a.loose),input:a.schema,output:Xre,execute:async(c,u)=>{const l=await n.callTool({name:o.name,arguments:c},{signal:u.signal});return l.isError!==!0&&l.structuredContent!==void 0?Xre.parse(l.structuredContent):Xre.parse({isError:l.isError===!0,content:l.content})}})}return In.module({id:e.id,name:e.name,namespace:t,description:`MCP server "${e.name}" at ${e.url.origin}: tools it advertises.`,operations:r})}async function q9i(e,t){const n=[];let i;for(let r=0;r<fmn;r+=1){const o=await e.listTools(i===void 0?void 0:{cursor:i},{signal:t});if(n.push(...o.tools),n.length>mmn)throw new Error(`MCP server advertises more than ${String(mmn)} tools`);if(i=o.nextCursor,i===void 0)return n}throw new Error(`MCP server tool list exceeds ${String(fmn)} pages`)}function H9i(){return Promise.resolve().then(()=>(Lne(),nrn))}function ymn(e,t){return e.UnauthorizedError.isInstance(t)||e.SdkHttpError.isInstance(t)&&(t.status===401||t.status===403)?"unauthorized":"rejected"}async function G9i(e,t,n,i){const r=await H9i(),o=new r.Client({name:"fungi-knapsack",version:"1"}),s=new r.StreamableHTTPClientTransport(new URL(e.url),{requestInit:{headers:{...e.headers},redirect:"error"},fetch:n});try{await o.connect(s,{signal:i})}catch(a){throw await o.close(),new QC(e.id,ymn(r,a),a)}try{const a=await q9i(o,i).catch(l=>{throw new QC(e.id,ymn(r,l)==="unauthorized"?"unauthorized":"invalid-advertisement",l)});let c;try{c=z9i(e,t,o,a)}catch(l){throw new QC(e.id,"invalid-advertisement",l)}const u=await gmn(JSON.stringify([e.id,e.name,e.url.href,a.map(l=>[l.name,l.description??null,l.inputSchema,l.annotations?.readOnlyHint??null])]));return{module:c,version:u,close:()=>o.close()}}catch(a){throw await o.close(),a}}function V9i(e,t,n,i){return Ir({try:r=>G9i(e,t,n,r),catch:r=>r instanceof QC?r:new QC(e.id,"rejected",r)}).pipe(hA({duration:i,orElse:()=>xe(new QC(e.id,"timeout"))}))}function K9i(e){const t=e.connectTimeoutMillis??L9i,n=e.namespace??["mcp"];return{id:e.id,acquire:async i=>{i.signal.throwIfAborted();const r=e.subscribe(i.invalidate),o=[],s=async()=>{await Promise.allSettled(o.map(a=>a.close()))};try{const a=await e.read();if(a.servers.length>hmn)throw new Error(`At most ${String(hmn)} MCP servers per source`);const c=await Bc(po(a.servers,l=>fd(V9i(l,n,e.fetch,t).pipe(hs(d=>nt(()=>o.push(d))))),{concurrency:D9i}),{signal:i.signal}),u=[a.version];for(const l of c){if(Sn(l)){e.onUnavailable(l.failure),u.push(`unavailable:${l.failure.serverId}:${l.failure.reason}`);continue}u.push(l.success.version)}return i.signal.throwIfAborted(),{snapshot:{version:`mcp-${await gmn(JSON.stringify(u))}`,modules:o.map(l=>l.module)},release:async()=>{r(),await s()}}}catch(a){throw r(),await s(),a}}}}Yc(),io(),yt(),Qr(),ri(),qu(),_t(),D4(),rA(),yt(),S4(),dHt(),ba(),_t();var jx=D0({family:"knapsack-ui",version:1,kinds:{request:{prefix:"ui_request"},connection:{prefix:"ui_connection"},claim:{prefix:"ui_claim"},attempt:{prefix:"ui_attempt"}}}),QFe=j().min(1).max(256),XFe=j().refine(e=>jx.request.parse(e).ok),Yre=o0(),Zre=Ot(j(),Yre),J9i=Ot(j(),Wt()),Q9i=ml("status",[de({status:Ie("available")}),de({status:Ie("unavailable"),reason:j()})]),X9i=Eo({namespace:QFe,id:QFe}),vmn={command:X9i,sourceId:QFe,title:j(),category:j(),description:j().nullable(),order:et(),keybind:j().nullable(),availability:Q9i},Y9i=It([de({inputSchema:Zre,outputSchema:Zre}).strict(),de({inputSchema:Zre}).strict(),de({outputSchema:Zre}).strict()]),Z9i=de({...vmn,action:Y9i}).strict(),eOi=de(vmn).strict(),_mn=It([Z9i,eOi]),wmn=de({command:Eo({namespace:j().max(256),id:j().max(256)})}),bmn=wmn.extend({arguments:Yre}).strict(),xmn=wmn.strict(),tOi=It([bmn,xmn]),nOi=It([de({type:Ie("discover")}).strict(),bmn.extend({type:Ie("execute")}),xmn.extend({type:Ie("execute")})]),iOi=de({requestId:XFe,request:nOi}),yWi=iOi.extend({connectionId:j().refine(e=>jx.connection.parse(e).ok)}),rOi=de({requestId:XFe,connectionId:j().refine(e=>jx.connection.parse(e).ok),attemptId:j().refine(e=>jx.attempt.parse(e).ok)}),vWi=ml("status",[de({status:Ie("claimed"),claimId:j()}),de({status:Ie("waiting"),retryAfterMs:et().int().min(10).max(1e3)}),de({status:Ie("skipped")})]),Smn=It([de({status:Ie("handled"),result:Yre}).strict(),de({status:Ie("handled")}).strict(),de({status:Ie("closed")}).strict(),de({status:Ie("missing")}).strict(),de({status:Ie("invalid")}).strict(),de({status:Ie("unavailable"),reason:j()}).strict(),de({status:Ie("failed"),error:de({code:j(),message:j(),details:Yre})}).strict(),de({status:Ie("failed"),error:de({code:j(),message:j()}).strict()}).strict()]),oOi=ml("type",[de({type:Ie("discover"),commands:Le(_mn)}),de({type:Ie("execute"),outcome:Smn})]),sOi=de({requestId:XFe,claimId:j().refine(e=>jx.claim.parse(e).ok),result:oOi}),_Wi=ml("status",[de({status:Ie("accepted")}),de({status:Ie("ignored")})]),aOi=e=>kt(()=>sOi.parse(e)),cOi=e=>kt(()=>rOi.parse(e)),Gg=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name="UiHostError"}};function uOi(e){return e.expected==="execute"&&e.phase==="claimed"?new Gg("browser_execution_indeterminate","The browser disconnected after execution dispatch"):new Gg("browser_disconnected","The connected browser disconnected before returning a result")}function lOi(e,t,n,i){if(!(e===void 0||e.expiresAt<=n||!i.has(e.connectionId)))return e.connectionId===t.connectionId&&e.attemptId===t.attemptId?{status:"claimed",claimId:e.claimId}:{status:"waiting",retryAfterMs:Math.max(10,Math.min(1e3,e.expiresAt-n))}}function kmn(e,t){return e!==void 0&&e.expiresAt<=t}function dOi(e,t,n){return e.phase==="claimed"&&e.claim?.claimId===t&&!kmn(e.claim,n)}function pOi(e={}){return je(function*(){const t=yield*Z9(1),n=new Map,i=e.claimLeaseMs??3e4,r=Number.isFinite(i)?Math.max(100,Math.min(6e4,i)):3e4;let o;const s=m=>{n.delete(m.id);let f,g;return o?.phase==="claimed"&&o.claim?.connectionId===m.id?n.size>0?(o={...o,phase:"queued",claim:void 0},g={requestId:o.requestId,request:o.request}):(f=o,o=void 0):o!==void 0&&n.size===0&&(f=o,o=void 0),{connection:m,failed:f,reoffer:g,recipients:[...n.values()]}},a=m=>{const f=m.reoffer;return(m.failed===void 0?pt:rW(m.failed.result,uOi(m.failed)).pipe(Ef)).pipe(gt(f===void 0?pt:po(m.recipients,g=>C0(g.requests,f),{discard:!0})),gt(b4(m.connection.requests)))},c=m=>xk(t,()=>s(m),a),u=()=>vl(je(function*(){const m=yield*Omt(1),f={id:jx.connection.generate(),requests:m};return yield*t.withPermits(1)(nt(()=>{n.set(f.id,f),o!==void 0&&!o.cancelled&&Bf(f.requests,{requestId:o.requestId,request:o.request})})),f}),c).pipe(mt(m=>{const f=()=>jv(m.requests).pipe(Me(g=>t.withPermits(1)(nt(()=>o?.requestId===g.requestId&&n.has(m.id))).pipe(Me(y=>y?we(g):Ut(f)))));return Object.freeze({id:m.id,take:Ut(f)})})),l=m=>xk(t,()=>{o?.requestId===m&&(o={...o,cancelled:!0})},()=>pt);return Object.freeze({connect:u,request:m=>Rp(f=>je(function*(){const g=yield*L7();let y;const v=xk(t,()=>{if(n.size===0)return{status:"offline"};if(o!==void 0)return{status:"busy"};const _=jx.request.generate(),b={requestId:_,request:m};o={requestId:_,request:m,cancelled:!1,expected:m.type,phase:"queued",claim:void 0,result:g};for(const w of n.values())Bf(w.requests,b);return y=_,{status:"admitted"}},_=>_.status==="offline"?xe(new Gg("browser_not_connected","No browser is connected")):_.status==="busy"?xe(new Gg("browser_busy","The connected browser already has pending work")):pt).pipe(gt(y0(g)));return yield*f(v).pipe(Ov(()=>y===void 0?pt:l(y)))})),claim:m=>cOi(m).pipe(or(()=>new Gg("invalid_browser_wire","Browser claim is invalid")),Me(f=>xk(t,()=>{const g=o;if(g?.requestId!==f.requestId)return{status:"skipped"};if(g.cancelled)return o=void 0,{status:"skipped"};const y=Date.now(),v=lOi(g.claim,f,y,new Set(n.keys()));if(v!==void 0)return v;if(!n.has(f.connectionId))return{status:"skipped"};const _={attemptId:f.attemptId,claimId:jx.claim.generate(),connectionId:f.connectionId,expiresAt:y+r};return o={...g,phase:"claimed",claim:_},{status:"claimed",claimId:_.claimId}},we))),acceptResult:m=>aOi(m).pipe(or(()=>new Gg("invalid_browser_wire","Browser result is invalid")),Me(f=>xk(t,()=>{const g=o;if(g?.requestId!==f.requestId)return{status:"ignored"};const y=Date.now();if(!dOi(g,f.claimId,y))return kmn(g.claim,y)&&(o={...g,phase:"queued",claim:void 0}),{status:"ignored"};if(o=void 0,g.expected!==f.result.type){const v=new Gg("invalid_browser_wire","Browser result does not match its request");return{status:"mismatch",owned:g,failure:v}}return{status:"accepted",owned:g}},g=>g.status==="ignored"?we({status:"ignored"}):g.status==="mismatch"?rW(g.owned.result,g.failure).pipe(gt(xe(g.failure))):oW(g.owned.result,f.result).pipe(mi({status:"accepted"})))))})})}var Emn=E.object({status:E.literal("unavailable"),reason:E.enum(["browser_busy","browser_not_connected","browser_disconnected"])}),hOi=E.object({status:E.literal("indeterminate"),reason:E.literal("browser_disconnected_after_dispatch")}),mOi=E.discriminatedUnion("status",[E.object({status:E.literal("available"),commands:E.array(_mn)}),Emn]),fOi=E.union([Smn,Emn,hOi]);async function YFe(e,t){t?.throwIfAborted();const n=await Tf(e,t===void 0?void 0:{signal:t});if(yr(n))return n.value;const i=Bh(n.cause);if(si(i))throw i.value;if(hw(n.cause))throw t?.throwIfAborted(),new DOMException("The operation was aborted","AbortError");const r=Du(n.cause);throw r instanceof Error?r:new Error("Live App command host failed without an Error cause")}function gOi(e){return{status:"unavailable",reason:e}}function Amn(e){switch(e.code){case"browser_busy":case"browser_not_connected":case"browser_disconnected":return we(gOi(e.code));default:return xe(e)}}function yOi(e,t){return e.request(t).pipe(fc(Amn))}function vOi(e,t){return e.request(t).pipe(fc(n=>n.code==="browser_execution_indeterminate"?we({status:"indeterminate",reason:"browser_disconnected_after_dispatch"}):Amn(n)))}function _Oi(e){if("status"in e)return e;if(e.type!=="discover")throw new Gg("invalid_browser_wire","Browser returned an execution result for discovery");return{status:"available",commands:[...e.commands]}}function wOi(e){if("status"in e)return e;if(e.type!=="execute")throw new Gg("invalid_browser_wire","Browser returned a discovery result for execution");return e.outcome}function bOi(e){const t=Yv(e.connect().pipe(mt(n=>j6(`: connected
|
|
1886
|
+
${B9i}`:i).slice(0,N9i)}function z9i(e,t,n,i){const r={};for(const o of i){const s=F9i(o.name);if(s in r)continue;const a=j9i(o);r[s]=In.operation({replay:o.annotations?.readOnlyHint===!0?"safe":"unsafe",description:W9i(o,a.loose),input:a.schema,output:Xre,execute:async(c,u)=>{const l=await n.callTool({name:o.name,arguments:c},{signal:u.signal});return l.isError!==!0&&l.structuredContent!==void 0?Xre.parse(l.structuredContent):Xre.parse({isError:l.isError===!0,content:l.content})}})}return In.module({id:e.id,name:e.name,namespace:t,description:`MCP server "${e.name}" at ${e.url.origin}: tools it advertises.`,operations:r})}async function q9i(e,t){const n=[];let i;for(let r=0;r<fmn;r+=1){const o=await e.listTools(i===void 0?void 0:{cursor:i},{signal:t});if(n.push(...o.tools),n.length>mmn)throw new Error(`MCP server advertises more than ${String(mmn)} tools`);if(i=o.nextCursor,i===void 0)return n}throw new Error(`MCP server tool list exceeds ${String(fmn)} pages`)}function H9i(){return Promise.resolve().then(()=>(Lne(),nrn))}function ymn(e,t){return e.UnauthorizedError.isInstance(t)||e.SdkHttpError.isInstance(t)&&(t.status===401||t.status===403)?"unauthorized":"rejected"}async function G9i(e,t,n,i){const r=await H9i(),o=new r.Client({name:"fungi-knapsack",version:"1"}),s=new r.StreamableHTTPClientTransport(new URL(e.url),{requestInit:{headers:{...e.headers},redirect:"manual"},fetch:n});try{await o.connect(s,{signal:i})}catch(a){throw await o.close(),new QC(e.id,ymn(r,a),a)}try{const a=await q9i(o,i).catch(l=>{throw new QC(e.id,ymn(r,l)==="unauthorized"?"unauthorized":"invalid-advertisement",l)});let c;try{c=z9i(e,t,o,a)}catch(l){throw new QC(e.id,"invalid-advertisement",l)}const u=await gmn(JSON.stringify([e.id,e.name,e.url.href,a.map(l=>[l.name,l.description??null,l.inputSchema,l.annotations?.readOnlyHint??null])]));return{module:c,version:u,close:()=>o.close()}}catch(a){throw await o.close(),a}}function V9i(e,t,n,i){return Ir({try:r=>G9i(e,t,n,r),catch:r=>r instanceof QC?r:new QC(e.id,"rejected",r)}).pipe(hA({duration:i,orElse:()=>xe(new QC(e.id,"timeout"))}))}function K9i(e){const t=e.connectTimeoutMillis??L9i,n=e.namespace??["mcp"];return{id:e.id,acquire:async i=>{i.signal.throwIfAborted();const r=e.subscribe(i.invalidate),o=[],s=async()=>{await Promise.allSettled(o.map(a=>a.close()))};try{const a=await e.read();if(a.servers.length>hmn)throw new Error(`At most ${String(hmn)} MCP servers per source`);const c=await Bc(po(a.servers,l=>fd(V9i(l,n,e.fetch,t).pipe(hs(d=>nt(()=>o.push(d))))),{concurrency:D9i}),{signal:i.signal}),u=[a.version];for(const l of c){if(Sn(l)){e.onUnavailable(l.failure),u.push(`unavailable:${l.failure.serverId}:${l.failure.reason}`);continue}u.push(l.success.version)}return i.signal.throwIfAborted(),{snapshot:{version:`mcp-${await gmn(JSON.stringify(u))}`,modules:o.map(l=>l.module)},release:async()=>{r(),await s()}}}catch(a){throw r(),await s(),a}}}}Yc(),io(),yt(),Qr(),ri(),qu(),_t(),D4(),rA(),yt(),S4(),dHt(),ba(),_t();var jx=D0({family:"knapsack-ui",version:1,kinds:{request:{prefix:"ui_request"},connection:{prefix:"ui_connection"},claim:{prefix:"ui_claim"},attempt:{prefix:"ui_attempt"}}}),QFe=j().min(1).max(256),XFe=j().refine(e=>jx.request.parse(e).ok),Yre=o0(),Zre=Ot(j(),Yre),J9i=Ot(j(),Wt()),Q9i=ml("status",[de({status:Ie("available")}),de({status:Ie("unavailable"),reason:j()})]),X9i=Eo({namespace:QFe,id:QFe}),vmn={command:X9i,sourceId:QFe,title:j(),category:j(),description:j().nullable(),order:et(),keybind:j().nullable(),availability:Q9i},Y9i=It([de({inputSchema:Zre,outputSchema:Zre}).strict(),de({inputSchema:Zre}).strict(),de({outputSchema:Zre}).strict()]),Z9i=de({...vmn,action:Y9i}).strict(),eOi=de(vmn).strict(),_mn=It([Z9i,eOi]),wmn=de({command:Eo({namespace:j().max(256),id:j().max(256)})}),bmn=wmn.extend({arguments:Yre}).strict(),xmn=wmn.strict(),tOi=It([bmn,xmn]),nOi=It([de({type:Ie("discover")}).strict(),bmn.extend({type:Ie("execute")}),xmn.extend({type:Ie("execute")})]),iOi=de({requestId:XFe,request:nOi}),yWi=iOi.extend({connectionId:j().refine(e=>jx.connection.parse(e).ok)}),rOi=de({requestId:XFe,connectionId:j().refine(e=>jx.connection.parse(e).ok),attemptId:j().refine(e=>jx.attempt.parse(e).ok)}),vWi=ml("status",[de({status:Ie("claimed"),claimId:j()}),de({status:Ie("waiting"),retryAfterMs:et().int().min(10).max(1e3)}),de({status:Ie("skipped")})]),Smn=It([de({status:Ie("handled"),result:Yre}).strict(),de({status:Ie("handled")}).strict(),de({status:Ie("closed")}).strict(),de({status:Ie("missing")}).strict(),de({status:Ie("invalid")}).strict(),de({status:Ie("unavailable"),reason:j()}).strict(),de({status:Ie("failed"),error:de({code:j(),message:j(),details:Yre})}).strict(),de({status:Ie("failed"),error:de({code:j(),message:j()}).strict()}).strict()]),oOi=ml("type",[de({type:Ie("discover"),commands:Le(_mn)}),de({type:Ie("execute"),outcome:Smn})]),sOi=de({requestId:XFe,claimId:j().refine(e=>jx.claim.parse(e).ok),result:oOi}),_Wi=ml("status",[de({status:Ie("accepted")}),de({status:Ie("ignored")})]),aOi=e=>kt(()=>sOi.parse(e)),cOi=e=>kt(()=>rOi.parse(e)),Gg=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name="UiHostError"}};function uOi(e){return e.expected==="execute"&&e.phase==="claimed"?new Gg("browser_execution_indeterminate","The browser disconnected after execution dispatch"):new Gg("browser_disconnected","The connected browser disconnected before returning a result")}function lOi(e,t,n,i){if(!(e===void 0||e.expiresAt<=n||!i.has(e.connectionId)))return e.connectionId===t.connectionId&&e.attemptId===t.attemptId?{status:"claimed",claimId:e.claimId}:{status:"waiting",retryAfterMs:Math.max(10,Math.min(1e3,e.expiresAt-n))}}function kmn(e,t){return e!==void 0&&e.expiresAt<=t}function dOi(e,t,n){return e.phase==="claimed"&&e.claim?.claimId===t&&!kmn(e.claim,n)}function pOi(e={}){return je(function*(){const t=yield*Z9(1),n=new Map,i=e.claimLeaseMs??3e4,r=Number.isFinite(i)?Math.max(100,Math.min(6e4,i)):3e4;let o;const s=m=>{n.delete(m.id);let f,g;return o?.phase==="claimed"&&o.claim?.connectionId===m.id?n.size>0?(o={...o,phase:"queued",claim:void 0},g={requestId:o.requestId,request:o.request}):(f=o,o=void 0):o!==void 0&&n.size===0&&(f=o,o=void 0),{connection:m,failed:f,reoffer:g,recipients:[...n.values()]}},a=m=>{const f=m.reoffer;return(m.failed===void 0?pt:rW(m.failed.result,uOi(m.failed)).pipe(Ef)).pipe(gt(f===void 0?pt:po(m.recipients,g=>C0(g.requests,f),{discard:!0})),gt(b4(m.connection.requests)))},c=m=>xk(t,()=>s(m),a),u=()=>vl(je(function*(){const m=yield*Omt(1),f={id:jx.connection.generate(),requests:m};return yield*t.withPermits(1)(nt(()=>{n.set(f.id,f),o!==void 0&&!o.cancelled&&Bf(f.requests,{requestId:o.requestId,request:o.request})})),f}),c).pipe(mt(m=>{const f=()=>jv(m.requests).pipe(Me(g=>t.withPermits(1)(nt(()=>o?.requestId===g.requestId&&n.has(m.id))).pipe(Me(y=>y?we(g):Ut(f)))));return Object.freeze({id:m.id,take:Ut(f)})})),l=m=>xk(t,()=>{o?.requestId===m&&(o={...o,cancelled:!0})},()=>pt);return Object.freeze({connect:u,request:m=>Rp(f=>je(function*(){const g=yield*L7();let y;const v=xk(t,()=>{if(n.size===0)return{status:"offline"};if(o!==void 0)return{status:"busy"};const _=jx.request.generate(),b={requestId:_,request:m};o={requestId:_,request:m,cancelled:!1,expected:m.type,phase:"queued",claim:void 0,result:g};for(const w of n.values())Bf(w.requests,b);return y=_,{status:"admitted"}},_=>_.status==="offline"?xe(new Gg("browser_not_connected","No browser is connected")):_.status==="busy"?xe(new Gg("browser_busy","The connected browser already has pending work")):pt).pipe(gt(y0(g)));return yield*f(v).pipe(Ov(()=>y===void 0?pt:l(y)))})),claim:m=>cOi(m).pipe(or(()=>new Gg("invalid_browser_wire","Browser claim is invalid")),Me(f=>xk(t,()=>{const g=o;if(g?.requestId!==f.requestId)return{status:"skipped"};if(g.cancelled)return o=void 0,{status:"skipped"};const y=Date.now(),v=lOi(g.claim,f,y,new Set(n.keys()));if(v!==void 0)return v;if(!n.has(f.connectionId))return{status:"skipped"};const _={attemptId:f.attemptId,claimId:jx.claim.generate(),connectionId:f.connectionId,expiresAt:y+r};return o={...g,phase:"claimed",claim:_},{status:"claimed",claimId:_.claimId}},we))),acceptResult:m=>aOi(m).pipe(or(()=>new Gg("invalid_browser_wire","Browser result is invalid")),Me(f=>xk(t,()=>{const g=o;if(g?.requestId!==f.requestId)return{status:"ignored"};const y=Date.now();if(!dOi(g,f.claimId,y))return kmn(g.claim,y)&&(o={...g,phase:"queued",claim:void 0}),{status:"ignored"};if(o=void 0,g.expected!==f.result.type){const v=new Gg("invalid_browser_wire","Browser result does not match its request");return{status:"mismatch",owned:g,failure:v}}return{status:"accepted",owned:g}},g=>g.status==="ignored"?we({status:"ignored"}):g.status==="mismatch"?rW(g.owned.result,g.failure).pipe(gt(xe(g.failure))):oW(g.owned.result,f.result).pipe(mi({status:"accepted"})))))})})}var Emn=E.object({status:E.literal("unavailable"),reason:E.enum(["browser_busy","browser_not_connected","browser_disconnected"])}),hOi=E.object({status:E.literal("indeterminate"),reason:E.literal("browser_disconnected_after_dispatch")}),mOi=E.discriminatedUnion("status",[E.object({status:E.literal("available"),commands:E.array(_mn)}),Emn]),fOi=E.union([Smn,Emn,hOi]);async function YFe(e,t){t?.throwIfAborted();const n=await Tf(e,t===void 0?void 0:{signal:t});if(yr(n))return n.value;const i=Bh(n.cause);if(si(i))throw i.value;if(hw(n.cause))throw t?.throwIfAborted(),new DOMException("The operation was aborted","AbortError");const r=Du(n.cause);throw r instanceof Error?r:new Error("Live App command host failed without an Error cause")}function gOi(e){return{status:"unavailable",reason:e}}function Amn(e){switch(e.code){case"browser_busy":case"browser_not_connected":case"browser_disconnected":return we(gOi(e.code));default:return xe(e)}}function yOi(e,t){return e.request(t).pipe(fc(Amn))}function vOi(e,t){return e.request(t).pipe(fc(n=>n.code==="browser_execution_indeterminate"?we({status:"indeterminate",reason:"browser_disconnected_after_dispatch"}):Amn(n)))}function _Oi(e){if("status"in e)return e;if(e.type!=="discover")throw new Gg("invalid_browser_wire","Browser returned an execution result for discovery");return{status:"available",commands:[...e.commands]}}function wOi(e){if("status"in e)return e;if(e.type!=="execute")throw new Gg("invalid_browser_wire","Browser returned a discovery result for execution");return e.outcome}function bOi(e){const t=Yv(e.connect().pipe(mt(n=>j6(`: connected
|
|
1887
1887
|
|
|
1888
1888
|
`).pipe(ZH(Nwe(n.take).pipe(vO(i=>`event: browser-request
|
|
1889
1889
|
data: ${JSON.stringify({...i,connectionId:n.id})}
|
package/dist/whats-new.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"release":"0.
|
|
1
|
+
{"release":"0.66.0","lines":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fungi.computer/spore",
|
|
3
|
-
"version": "0.19.
|
|
3
|
+
"version": "0.19.2",
|
|
4
4
|
"description": "Spore by Fungi: open-source AI agents for your terminal and ACP editor, powered by Shiitake by Fungi.",
|
|
5
5
|
"homepage": "https://docs.fungi.computer/shiitake",
|
|
6
6
|
"keywords": [
|
|
@@ -45,10 +45,10 @@
|
|
|
45
45
|
"@opencode-ai/pty": "0.3.0"
|
|
46
46
|
},
|
|
47
47
|
"optionalDependencies": {
|
|
48
|
-
"@fungi.computer/spore-native-linux-x64": "0.19.
|
|
49
|
-
"@fungi.computer/spore-native-linux-arm64": "0.19.
|
|
50
|
-
"@fungi.computer/spore-native-darwin-arm64": "0.19.
|
|
51
|
-
"@fungi.computer/spore-native-darwin-x64": "0.19.
|
|
48
|
+
"@fungi.computer/spore-native-linux-x64": "0.19.2",
|
|
49
|
+
"@fungi.computer/spore-native-linux-arm64": "0.19.2",
|
|
50
|
+
"@fungi.computer/spore-native-darwin-arm64": "0.19.2",
|
|
51
|
+
"@fungi.computer/spore-native-darwin-x64": "0.19.2",
|
|
52
52
|
"@oven/bun-darwin-x64": "1.4.4",
|
|
53
53
|
"@oven/bun-darwin-aarch64": "1.4.4",
|
|
54
54
|
"@oven/bun-linux-x64": "1.4.4",
|